blob: a760e2c1473033e8e8ae6bd25efa2c8130cf9542 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drh9cbe6352005-11-29 03:13:21 +0000141/*
drh7ed97b92010-01-20 13:07:21 +0000142** Allowed values of unixFile.fsFlags
143*/
144#define SQLITE_FSFLAGS_IS_MSDOS 0x1
145
146/*
drhf1a221e2006-01-15 17:27:17 +0000147** If we are to be thread-safe, include the pthreads header and define
148** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000149*/
drhd677b3d2007-08-20 22:48:41 +0000150#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000151# include <pthread.h>
152# define SQLITE_UNIX_THREADS 1
153#endif
154
155/*
156** Default permissions when creating a new file
157*/
158#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
159# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
160#endif
161
danielk1977b4b47412007-08-17 15:53:36 +0000162/*
aswiftaebf4132008-11-21 00:10:35 +0000163 ** Default permissions when creating auto proxy dir
164 */
165#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
166# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
167#endif
168
169/*
danielk1977b4b47412007-08-17 15:53:36 +0000170** Maximum supported path-length.
171*/
172#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000173
drh734c9862008-11-28 15:37:20 +0000174/*
drh734c9862008-11-28 15:37:20 +0000175** Only set the lastErrno if the error code is a real error and not
176** a normal expected return code of SQLITE_BUSY or SQLITE_OK
177*/
178#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
179
drhd91c68f2010-05-14 14:52:25 +0000180/* Forward references */
181typedef struct unixShm unixShm; /* Connection shared memory */
182typedef struct unixShmNode unixShmNode; /* Shared memory instance */
183typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
184typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000185
186/*
dane946c392009-08-22 11:39:46 +0000187** Sometimes, after a file handle is closed by SQLite, the file descriptor
188** cannot be closed immediately. In these cases, instances of the following
189** structure are used to store the file descriptor while waiting for an
190** opportunity to either close or reuse it.
191*/
dane946c392009-08-22 11:39:46 +0000192struct UnixUnusedFd {
193 int fd; /* File descriptor to close */
194 int flags; /* Flags this file descriptor was opened with */
195 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
196};
197
198/*
drh9b35ea62008-11-29 02:20:26 +0000199** The unixFile structure is subclass of sqlite3_file specific to the unix
200** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000201*/
drh054889e2005-11-30 03:20:31 +0000202typedef struct unixFile unixFile;
203struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000204 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000205 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000206 int h; /* The file descriptor */
207 int dirfd; /* File descriptor for the directory */
208 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000209 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000210 int lastErrno; /* The unix errno from last I/O error */
211 void *lockingContext; /* Locking style specific state */
212 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000213 const char *zPath; /* Name of the file */
214 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000215 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000216#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000217 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000218#endif
drh7ed97b92010-01-20 13:07:21 +0000219#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000220 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000221#endif
222#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000223 int isDelete; /* Delete on close if true */
224 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000225#endif
drh8f941bc2009-01-14 23:03:40 +0000226#ifndef NDEBUG
227 /* The next group of variables are used to track whether or not the
228 ** transaction counter in bytes 24-27 of database files are updated
229 ** whenever any part of the database changes. An assertion fault will
230 ** occur if a file is updated without also updating the transaction
231 ** counter. This test is made to avoid new problems similar to the
232 ** one described by ticket #3584.
233 */
234 unsigned char transCntrChng; /* True if the transaction counter changed */
235 unsigned char dbUpdate; /* True if any part of database file changed */
236 unsigned char inNormalWrite; /* True if in a normal write operation */
237#endif
danielk1977967a4a12007-08-20 14:23:44 +0000238#ifdef SQLITE_TEST
239 /* In test mode, increase the size of this structure a bit so that
240 ** it is larger than the struct CrashFile defined in test6.c.
241 */
242 char aPadding[32];
243#endif
drh9cbe6352005-11-29 03:13:21 +0000244};
245
drh0ccebe72005-06-07 22:22:50 +0000246/*
drha7e61d82011-03-12 17:02:57 +0000247** Allowed values for the unixFile.ctrlFlags bitmask:
248*/
249#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
drh77197112011-03-15 19:08:48 +0000250#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
drha7e61d82011-03-12 17:02:57 +0000251
252/*
drh198bf392006-01-06 21:52:49 +0000253** Include code that is common to all os_*.c files
254*/
255#include "os_common.h"
256
257/*
drh0ccebe72005-06-07 22:22:50 +0000258** Define various macros that are missing from some systems.
259*/
drhbbd42a62004-05-22 17:41:58 +0000260#ifndef O_LARGEFILE
261# define O_LARGEFILE 0
262#endif
263#ifdef SQLITE_DISABLE_LFS
264# undef O_LARGEFILE
265# define O_LARGEFILE 0
266#endif
267#ifndef O_NOFOLLOW
268# define O_NOFOLLOW 0
269#endif
270#ifndef O_BINARY
271# define O_BINARY 0
272#endif
273
274/*
drh2b4b5962005-06-15 17:47:55 +0000275** The threadid macro resolves to the thread-id or to 0. Used for
276** testing and debugging only.
277*/
drhd677b3d2007-08-20 22:48:41 +0000278#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000279#define threadid pthread_self()
280#else
281#define threadid 0
282#endif
283
drh99ab3b12011-03-02 15:09:07 +0000284/*
drh9a3baf12011-04-25 18:01:27 +0000285** Different Unix systems declare open() in different ways. Same use
286** open(const char*,int,mode_t). Others use open(const char*,int,...).
287** The difference is important when using a pointer to the function.
288**
289** The safest way to deal with the problem is to always use this wrapper
290** which always has the same well-defined interface.
291*/
292static int posixOpen(const char *zFile, int flags, int mode){
293 return open(zFile, flags, mode);
294}
295
296/*
drh99ab3b12011-03-02 15:09:07 +0000297** Many system calls are accessed through pointer-to-functions so that
298** they may be overridden at runtime to facilitate fault injection during
299** testing and sandboxing. The following array holds the names and pointers
300** to all overrideable system calls.
301*/
302static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000303 const char *zName; /* Name of the sytem call */
304 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
305 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000306} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000307 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
308#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000309
drh58ad5802011-03-23 22:02:23 +0000310 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000311#define osClose ((int(*)(int))aSyscall[1].pCurrent)
312
drh58ad5802011-03-23 22:02:23 +0000313 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000314#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
315
drh58ad5802011-03-23 22:02:23 +0000316 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000317#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
318
drh58ad5802011-03-23 22:02:23 +0000319 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000320#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
321
322/*
323** The DJGPP compiler environment looks mostly like Unix, but it
324** lacks the fcntl() system call. So redefine fcntl() to be something
325** that always succeeds. This means that locking does not occur under
326** DJGPP. But it is DOS - what did you expect?
327*/
328#ifdef __DJGPP__
329 { "fstat", 0, 0 },
330#define osFstat(a,b,c) 0
331#else
drh58ad5802011-03-23 22:02:23 +0000332 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000333#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
334#endif
335
drh58ad5802011-03-23 22:02:23 +0000336 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000337#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
338
drh58ad5802011-03-23 22:02:23 +0000339 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000340#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000341
drh58ad5802011-03-23 22:02:23 +0000342 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000343#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
344
drhd4a80312011-04-15 14:33:20 +0000345#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000346 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000347#else
drh58ad5802011-03-23 22:02:23 +0000348 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000349#endif
350#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
351
352#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000353 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000354#else
drh58ad5802011-03-23 22:02:23 +0000355 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000356#endif
357#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
358
drh58ad5802011-03-23 22:02:23 +0000359 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000360#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
361
drhd4a80312011-04-15 14:33:20 +0000362#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000363 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000364#else
drh58ad5802011-03-23 22:02:23 +0000365 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000366#endif
367#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
368 aSyscall[12].pCurrent)
369
370#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000371 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000372#else
drh58ad5802011-03-23 22:02:23 +0000373 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000374#endif
375#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
376 aSyscall[13].pCurrent)
377
drha6c47492011-04-11 18:35:09 +0000378#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000379 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000380#else
381 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000382#endif
drh2aa5a002011-04-13 13:42:25 +0000383#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000384
385#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000386 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000387#else
drh58ad5802011-03-23 22:02:23 +0000388 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000389#endif
dan0fd7d862011-03-29 10:04:23 +0000390#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000391
392}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000393
394/*
395** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000396** "unix" VFSes. Return SQLITE_OK opon successfully updating the
397** system call pointer, or SQLITE_NOTFOUND if there is no configurable
398** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000399*/
400static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000401 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
402 const char *zName, /* Name of system call to override */
403 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000404){
drh58ad5802011-03-23 22:02:23 +0000405 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000406 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000407
408 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000409 if( zName==0 ){
410 /* If no zName is given, restore all system calls to their default
411 ** settings and return NULL
412 */
dan51438a72011-04-02 17:00:47 +0000413 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000414 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
415 if( aSyscall[i].pDefault ){
416 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000417 }
418 }
419 }else{
420 /* If zName is specified, operate on only the one system call
421 ** specified.
422 */
423 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
424 if( strcmp(zName, aSyscall[i].zName)==0 ){
425 if( aSyscall[i].pDefault==0 ){
426 aSyscall[i].pDefault = aSyscall[i].pCurrent;
427 }
drh1df30962011-03-02 19:06:42 +0000428 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000429 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
430 aSyscall[i].pCurrent = pNewFunc;
431 break;
432 }
433 }
434 }
435 return rc;
436}
437
drh1df30962011-03-02 19:06:42 +0000438/*
439** Return the value of a system call. Return NULL if zName is not a
440** recognized system call name. NULL is also returned if the system call
441** is currently undefined.
442*/
drh58ad5802011-03-23 22:02:23 +0000443static sqlite3_syscall_ptr unixGetSystemCall(
444 sqlite3_vfs *pNotUsed,
445 const char *zName
446){
447 unsigned int i;
448
449 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000450 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
451 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
452 }
453 return 0;
454}
455
456/*
457** Return the name of the first system call after zName. If zName==NULL
458** then return the name of the first system call. Return NULL if zName
459** is the last system call or if zName is not the name of a valid
460** system call.
461*/
462static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000463 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000464
465 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000466 if( zName ){
467 for(i=0; i<ArraySize(aSyscall)-1; i++){
468 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000469 }
470 }
dan0fd7d862011-03-29 10:04:23 +0000471 for(i++; i<ArraySize(aSyscall); i++){
472 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000473 }
474 return 0;
475}
476
drhad4f1e52011-03-04 15:43:57 +0000477/*
478** Retry open() calls that fail due to EINTR
479*/
480static int robust_open(const char *z, int f, int m){
481 int rc;
482 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
483 return rc;
484}
danielk197713adf8a2004-06-03 16:08:41 +0000485
drh107886a2008-11-21 22:21:50 +0000486/*
dan9359c7b2009-08-21 08:29:10 +0000487** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000488** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000489** vxworksFileId objects used by this file, all of which may be
490** shared by multiple threads.
491**
492** Function unixMutexHeld() is used to assert() that the global mutex
493** is held when required. This function is only used as part of assert()
494** statements. e.g.
495**
496** unixEnterMutex()
497** assert( unixMutexHeld() );
498** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000499*/
500static void unixEnterMutex(void){
501 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
502}
503static void unixLeaveMutex(void){
504 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
505}
dan9359c7b2009-08-21 08:29:10 +0000506#ifdef SQLITE_DEBUG
507static int unixMutexHeld(void) {
508 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
509}
510#endif
drh107886a2008-11-21 22:21:50 +0000511
drh734c9862008-11-28 15:37:20 +0000512
513#ifdef SQLITE_DEBUG
514/*
515** Helper function for printing out trace information from debugging
516** binaries. This returns the string represetation of the supplied
517** integer lock-type.
518*/
drh308c2a52010-05-14 11:30:18 +0000519static const char *azFileLock(int eFileLock){
520 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000521 case NO_LOCK: return "NONE";
522 case SHARED_LOCK: return "SHARED";
523 case RESERVED_LOCK: return "RESERVED";
524 case PENDING_LOCK: return "PENDING";
525 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000526 }
527 return "ERROR";
528}
529#endif
530
531#ifdef SQLITE_LOCK_TRACE
532/*
533** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000534**
drh734c9862008-11-28 15:37:20 +0000535** This routine is used for troubleshooting locks on multithreaded
536** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
537** command-line option on the compiler. This code is normally
538** turned off.
539*/
540static int lockTrace(int fd, int op, struct flock *p){
541 char *zOpName, *zType;
542 int s;
543 int savedErrno;
544 if( op==F_GETLK ){
545 zOpName = "GETLK";
546 }else if( op==F_SETLK ){
547 zOpName = "SETLK";
548 }else{
drh99ab3b12011-03-02 15:09:07 +0000549 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000550 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
551 return s;
552 }
553 if( p->l_type==F_RDLCK ){
554 zType = "RDLCK";
555 }else if( p->l_type==F_WRLCK ){
556 zType = "WRLCK";
557 }else if( p->l_type==F_UNLCK ){
558 zType = "UNLCK";
559 }else{
560 assert( 0 );
561 }
562 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000563 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000564 savedErrno = errno;
565 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
566 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
567 (int)p->l_pid, s);
568 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
569 struct flock l2;
570 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000571 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000572 if( l2.l_type==F_RDLCK ){
573 zType = "RDLCK";
574 }else if( l2.l_type==F_WRLCK ){
575 zType = "WRLCK";
576 }else if( l2.l_type==F_UNLCK ){
577 zType = "UNLCK";
578 }else{
579 assert( 0 );
580 }
581 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
582 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
583 }
584 errno = savedErrno;
585 return s;
586}
drh99ab3b12011-03-02 15:09:07 +0000587#undef osFcntl
588#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000589#endif /* SQLITE_LOCK_TRACE */
590
drhff812312011-02-23 13:33:46 +0000591/*
592** Retry ftruncate() calls that fail due to EINTR
593*/
drhff812312011-02-23 13:33:46 +0000594static int robust_ftruncate(int h, sqlite3_int64 sz){
595 int rc;
drh99ab3b12011-03-02 15:09:07 +0000596 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000597 return rc;
598}
drh734c9862008-11-28 15:37:20 +0000599
600/*
601** This routine translates a standard POSIX errno code into something
602** useful to the clients of the sqlite3 functions. Specifically, it is
603** intended to translate a variety of "try again" errors into SQLITE_BUSY
604** and a variety of "please close the file descriptor NOW" errors into
605** SQLITE_IOERR
606**
607** Errors during initialization of locks, or file system support for locks,
608** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
609*/
610static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
611 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000612#if 0
613 /* At one point this code was not commented out. In theory, this branch
614 ** should never be hit, as this function should only be called after
615 ** a locking-related function (i.e. fcntl()) has returned non-zero with
616 ** the value of errno as the first argument. Since a system call has failed,
617 ** errno should be non-zero.
618 **
619 ** Despite this, if errno really is zero, we still don't want to return
620 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
621 ** propagated back to the caller. Commenting this branch out means errno==0
622 ** will be handled by the "default:" case below.
623 */
drh734c9862008-11-28 15:37:20 +0000624 case 0:
625 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000626#endif
627
drh734c9862008-11-28 15:37:20 +0000628 case EAGAIN:
629 case ETIMEDOUT:
630 case EBUSY:
631 case EINTR:
632 case ENOLCK:
633 /* random NFS retry error, unless during file system support
634 * introspection, in which it actually means what it says */
635 return SQLITE_BUSY;
636
637 case EACCES:
638 /* EACCES is like EAGAIN during locking operations, but not any other time*/
639 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
640 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
641 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
642 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
643 return SQLITE_BUSY;
644 }
645 /* else fall through */
646 case EPERM:
647 return SQLITE_PERM;
648
danea83bc62011-04-01 11:56:32 +0000649 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
650 ** this module never makes such a call. And the code in SQLite itself
651 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
652 ** this case is also commented out. If the system does set errno to EDEADLK,
653 ** the default SQLITE_IOERR_XXX code will be returned. */
654#if 0
drh734c9862008-11-28 15:37:20 +0000655 case EDEADLK:
656 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000657#endif
drh734c9862008-11-28 15:37:20 +0000658
659#if EOPNOTSUPP!=ENOTSUP
660 case EOPNOTSUPP:
661 /* something went terribly awry, unless during file system support
662 * introspection, in which it actually means what it says */
663#endif
664#ifdef ENOTSUP
665 case ENOTSUP:
666 /* invalid fd, unless during file system support introspection, in which
667 * it actually means what it says */
668#endif
669 case EIO:
670 case EBADF:
671 case EINVAL:
672 case ENOTCONN:
673 case ENODEV:
674 case ENXIO:
675 case ENOENT:
676 case ESTALE:
677 case ENOSYS:
678 /* these should force the client to close the file and reconnect */
679
680 default:
681 return sqliteIOErr;
682 }
683}
684
685
686
687/******************************************************************************
688****************** Begin Unique File ID Utility Used By VxWorks ***************
689**
690** On most versions of unix, we can get a unique ID for a file by concatenating
691** the device number and the inode number. But this does not work on VxWorks.
692** On VxWorks, a unique file id must be based on the canonical filename.
693**
694** A pointer to an instance of the following structure can be used as a
695** unique file ID in VxWorks. Each instance of this structure contains
696** a copy of the canonical filename. There is also a reference count.
697** The structure is reclaimed when the number of pointers to it drops to
698** zero.
699**
700** There are never very many files open at one time and lookups are not
701** a performance-critical path, so it is sufficient to put these
702** structures on a linked list.
703*/
704struct vxworksFileId {
705 struct vxworksFileId *pNext; /* Next in a list of them all */
706 int nRef; /* Number of references to this one */
707 int nName; /* Length of the zCanonicalName[] string */
708 char *zCanonicalName; /* Canonical filename */
709};
710
711#if OS_VXWORKS
712/*
drh9b35ea62008-11-29 02:20:26 +0000713** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000714** variable:
715*/
716static struct vxworksFileId *vxworksFileList = 0;
717
718/*
719** Simplify a filename into its canonical form
720** by making the following changes:
721**
722** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000723** * convert /./ into just /
724** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000725**
726** Changes are made in-place. Return the new name length.
727**
728** The original filename is in z[0..n-1]. Return the number of
729** characters in the simplified name.
730*/
731static int vxworksSimplifyName(char *z, int n){
732 int i, j;
733 while( n>1 && z[n-1]=='/' ){ n--; }
734 for(i=j=0; i<n; i++){
735 if( z[i]=='/' ){
736 if( z[i+1]=='/' ) continue;
737 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
738 i += 1;
739 continue;
740 }
741 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
742 while( j>0 && z[j-1]!='/' ){ j--; }
743 if( j>0 ){ j--; }
744 i += 2;
745 continue;
746 }
747 }
748 z[j++] = z[i];
749 }
750 z[j] = 0;
751 return j;
752}
753
754/*
755** Find a unique file ID for the given absolute pathname. Return
756** a pointer to the vxworksFileId object. This pointer is the unique
757** file ID.
758**
759** The nRef field of the vxworksFileId object is incremented before
760** the object is returned. A new vxworksFileId object is created
761** and added to the global list if necessary.
762**
763** If a memory allocation error occurs, return NULL.
764*/
765static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
766 struct vxworksFileId *pNew; /* search key and new file ID */
767 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
768 int n; /* Length of zAbsoluteName string */
769
770 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000771 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000772 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
773 if( pNew==0 ) return 0;
774 pNew->zCanonicalName = (char*)&pNew[1];
775 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
776 n = vxworksSimplifyName(pNew->zCanonicalName, n);
777
778 /* Search for an existing entry that matching the canonical name.
779 ** If found, increment the reference count and return a pointer to
780 ** the existing file ID.
781 */
782 unixEnterMutex();
783 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
784 if( pCandidate->nName==n
785 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
786 ){
787 sqlite3_free(pNew);
788 pCandidate->nRef++;
789 unixLeaveMutex();
790 return pCandidate;
791 }
792 }
793
794 /* No match was found. We will make a new file ID */
795 pNew->nRef = 1;
796 pNew->nName = n;
797 pNew->pNext = vxworksFileList;
798 vxworksFileList = pNew;
799 unixLeaveMutex();
800 return pNew;
801}
802
803/*
804** Decrement the reference count on a vxworksFileId object. Free
805** the object when the reference count reaches zero.
806*/
807static void vxworksReleaseFileId(struct vxworksFileId *pId){
808 unixEnterMutex();
809 assert( pId->nRef>0 );
810 pId->nRef--;
811 if( pId->nRef==0 ){
812 struct vxworksFileId **pp;
813 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
814 assert( *pp==pId );
815 *pp = pId->pNext;
816 sqlite3_free(pId);
817 }
818 unixLeaveMutex();
819}
820#endif /* OS_VXWORKS */
821/*************** End of Unique File ID Utility Used By VxWorks ****************
822******************************************************************************/
823
824
825/******************************************************************************
826*************************** Posix Advisory Locking ****************************
827**
drh9b35ea62008-11-29 02:20:26 +0000828** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000829** section 6.5.2.2 lines 483 through 490 specify that when a process
830** sets or clears a lock, that operation overrides any prior locks set
831** by the same process. It does not explicitly say so, but this implies
832** that it overrides locks set by the same process using a different
833** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000834**
835** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000836** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
837**
838** Suppose ./file1 and ./file2 are really the same file (because
839** one is a hard or symbolic link to the other) then if you set
840** an exclusive lock on fd1, then try to get an exclusive lock
841** on fd2, it works. I would have expected the second lock to
842** fail since there was already a lock on the file due to fd1.
843** But not so. Since both locks came from the same process, the
844** second overrides the first, even though they were on different
845** file descriptors opened on different file names.
846**
drh734c9862008-11-28 15:37:20 +0000847** This means that we cannot use POSIX locks to synchronize file access
848** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000849** to synchronize access for threads in separate processes, but not
850** threads within the same process.
851**
852** To work around the problem, SQLite has to manage file locks internally
853** on its own. Whenever a new database is opened, we have to find the
854** specific inode of the database file (the inode is determined by the
855** st_dev and st_ino fields of the stat structure that fstat() fills in)
856** and check for locks already existing on that inode. When locks are
857** created or removed, we have to look at our own internal record of the
858** locks to see if another thread has previously set a lock on that same
859** inode.
860**
drh9b35ea62008-11-29 02:20:26 +0000861** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
862** For VxWorks, we have to use the alternative unique ID system based on
863** canonical filename and implemented in the previous division.)
864**
danielk1977ad94b582007-08-20 06:44:22 +0000865** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000866** descriptor. It is now a structure that holds the integer file
867** descriptor and a pointer to a structure that describes the internal
868** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000869** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000870** point to the same locking structure. The locking structure keeps
871** a reference count (so we will know when to delete it) and a "cnt"
872** field that tells us its internal lock status. cnt==0 means the
873** file is unlocked. cnt==-1 means the file has an exclusive lock.
874** cnt>0 means there are cnt shared locks on the file.
875**
876** Any attempt to lock or unlock a file first checks the locking
877** structure. The fcntl() system call is only invoked to set a
878** POSIX lock if the internal lock structure transitions between
879** a locked and an unlocked state.
880**
drh734c9862008-11-28 15:37:20 +0000881** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000882**
883** If you close a file descriptor that points to a file that has locks,
884** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000885** released. To work around this problem, each unixInodeInfo object
886** maintains a count of the number of pending locks on tha inode.
887** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000888** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000889** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000890** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000891** be closed and that list is walked (and cleared) when the last lock
892** clears.
893**
drh9b35ea62008-11-29 02:20:26 +0000894** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000895**
drh9b35ea62008-11-29 02:20:26 +0000896** Many older versions of linux use the LinuxThreads library which is
897** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000898** A cannot be modified or overridden by a different thread B.
899** Only thread A can modify the lock. Locking behavior is correct
900** if the appliation uses the newer Native Posix Thread Library (NPTL)
901** on linux - with NPTL a lock created by thread A can override locks
902** in thread B. But there is no way to know at compile-time which
903** threading library is being used. So there is no way to know at
904** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000905** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000906** current process.
drh5fdae772004-06-29 03:29:00 +0000907**
drh8af6c222010-05-14 12:43:01 +0000908** SQLite used to support LinuxThreads. But support for LinuxThreads
909** was dropped beginning with version 3.7.0. SQLite will still work with
910** LinuxThreads provided that (1) there is no more than one connection
911** per database file in the same process and (2) database connections
912** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000913*/
914
915/*
916** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000917** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000918*/
919struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000920 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000921#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000922 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000923#else
drh107886a2008-11-21 22:21:50 +0000924 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000925#endif
926};
927
928/*
drhbbd42a62004-05-22 17:41:58 +0000929** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000930** inode. Or, on LinuxThreads, there is one of these structures for
931** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000932**
danielk1977ad94b582007-08-20 06:44:22 +0000933** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000934** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000935** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000936*/
drh8af6c222010-05-14 12:43:01 +0000937struct unixInodeInfo {
938 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000939 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000940 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
941 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000942 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000943 unixShmNode *pShmNode; /* Shared memory associated with this inode */
944 int nLock; /* Number of outstanding file locks */
945 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
946 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
947 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000948#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000949 unsigned long long sharedByte; /* for AFP simulated shared lock */
950#endif
drh6c7d5c52008-11-21 20:32:33 +0000951#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000952 sem_t *pSem; /* Named POSIX semaphore */
953 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000954#endif
drhbbd42a62004-05-22 17:41:58 +0000955};
956
drhda0e7682008-07-30 15:27:54 +0000957/*
drh8af6c222010-05-14 12:43:01 +0000958** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000959*/
drhd91c68f2010-05-14 14:52:25 +0000960static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000961
drh5fdae772004-06-29 03:29:00 +0000962/*
dane18d4952011-02-21 11:46:24 +0000963**
964** This function - unixLogError_x(), is only ever called via the macro
965** unixLogError().
966**
967** It is invoked after an error occurs in an OS function and errno has been
968** set. It logs a message using sqlite3_log() containing the current value of
969** errno and, if possible, the human-readable equivalent from strerror() or
970** strerror_r().
971**
972** The first argument passed to the macro should be the error code that
973** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
974** The two subsequent arguments should be the name of the OS function that
975** failed (e.g. "unlink", "open") and the the associated file-system path,
976** if any.
977*/
drh0e9365c2011-03-02 02:08:13 +0000978#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
979static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000980 int errcode, /* SQLite error code */
981 const char *zFunc, /* Name of OS function that failed */
982 const char *zPath, /* File path associated with error */
983 int iLine /* Source line number where error occurred */
984){
985 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000986 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000987
988 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
989 ** the strerror() function to obtain the human-readable error message
990 ** equivalent to errno. Otherwise, use strerror_r().
991 */
992#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
993 char aErr[80];
994 memset(aErr, 0, sizeof(aErr));
995 zErr = aErr;
996
997 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
998 ** assume that the system provides the the GNU version of strerror_r() that
999 ** returns a pointer to a buffer containing the error message. That pointer
1000 ** may point to aErr[], or it may point to some static storage somewhere.
1001 ** Otherwise, assume that the system provides the POSIX version of
1002 ** strerror_r(), which always writes an error message into aErr[].
1003 **
1004 ** If the code incorrectly assumes that it is the POSIX version that is
1005 ** available, the error message will often be an empty string. Not a
1006 ** huge problem. Incorrectly concluding that the GNU version is available
1007 ** could lead to a segfault though.
1008 */
1009#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1010 zErr =
1011# endif
drh0e9365c2011-03-02 02:08:13 +00001012 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001013
1014#elif SQLITE_THREADSAFE
1015 /* This is a threadsafe build, but strerror_r() is not available. */
1016 zErr = "";
1017#else
1018 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001019 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001020#endif
1021
1022 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001023 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001024 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001025 "os_unix.c:%d: (%d) %s(%s) - %s",
1026 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001027 );
1028
1029 return errcode;
1030}
1031
drh0e9365c2011-03-02 02:08:13 +00001032/*
1033** Close a file descriptor.
1034**
1035** We assume that close() almost always works, since it is only in a
1036** very sick application or on a very sick platform that it might fail.
1037** If it does fail, simply leak the file descriptor, but do log the
1038** error.
1039**
1040** Note that it is not safe to retry close() after EINTR since the
1041** file descriptor might have already been reused by another thread.
1042** So we don't even try to recover from an EINTR. Just log the error
1043** and move on.
1044*/
1045static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001046 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001047 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1048 pFile ? pFile->zPath : 0, lineno);
1049 }
1050}
dane18d4952011-02-21 11:46:24 +00001051
1052/*
danb0ac3e32010-06-16 10:55:42 +00001053** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001054*/
drh0e9365c2011-03-02 02:08:13 +00001055static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001056 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001057 UnixUnusedFd *p;
1058 UnixUnusedFd *pNext;
1059 for(p=pInode->pUnused; p; p=pNext){
1060 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001061 robust_close(pFile, p->fd, __LINE__);
1062 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001063 }
drh0e9365c2011-03-02 02:08:13 +00001064 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001065}
1066
1067/*
drh8af6c222010-05-14 12:43:01 +00001068** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001069**
1070** The mutex entered using the unixEnterMutex() function must be held
1071** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001072*/
danb0ac3e32010-06-16 10:55:42 +00001073static void releaseInodeInfo(unixFile *pFile){
1074 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001075 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001076 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001077 pInode->nRef--;
1078 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001079 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001080 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001081 if( pInode->pPrev ){
1082 assert( pInode->pPrev->pNext==pInode );
1083 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001084 }else{
drh8af6c222010-05-14 12:43:01 +00001085 assert( inodeList==pInode );
1086 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001087 }
drh8af6c222010-05-14 12:43:01 +00001088 if( pInode->pNext ){
1089 assert( pInode->pNext->pPrev==pInode );
1090 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001091 }
drh8af6c222010-05-14 12:43:01 +00001092 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001093 }
drhbbd42a62004-05-22 17:41:58 +00001094 }
1095}
1096
1097/*
drh8af6c222010-05-14 12:43:01 +00001098** Given a file descriptor, locate the unixInodeInfo object that
1099** describes that file descriptor. Create a new one if necessary. The
1100** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001101**
dan9359c7b2009-08-21 08:29:10 +00001102** The mutex entered using the unixEnterMutex() function must be held
1103** when this function is called.
1104**
drh6c7d5c52008-11-21 20:32:33 +00001105** Return an appropriate error code.
1106*/
drh8af6c222010-05-14 12:43:01 +00001107static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001108 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001109 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001110){
1111 int rc; /* System call return code */
1112 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001113 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1114 struct stat statbuf; /* Low-level file information */
1115 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001116
dan9359c7b2009-08-21 08:29:10 +00001117 assert( unixMutexHeld() );
1118
drh6c7d5c52008-11-21 20:32:33 +00001119 /* Get low-level information about the file that we can used to
1120 ** create a unique name for the file.
1121 */
1122 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001123 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001124 if( rc!=0 ){
1125 pFile->lastErrno = errno;
1126#ifdef EOVERFLOW
1127 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1128#endif
1129 return SQLITE_IOERR;
1130 }
1131
drheb0d74f2009-02-03 15:27:02 +00001132#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001133 /* On OS X on an msdos filesystem, the inode number is reported
1134 ** incorrectly for zero-size files. See ticket #3260. To work
1135 ** around this problem (we consider it a bug in OS X, not SQLite)
1136 ** we always increase the file size to 1 by writing a single byte
1137 ** prior to accessing the inode number. The one byte written is
1138 ** an ASCII 'S' character which also happens to be the first byte
1139 ** in the header of every SQLite database. In this way, if there
1140 ** is a race condition such that another thread has already populated
1141 ** the first page of the database, no damage is done.
1142 */
drh7ed97b92010-01-20 13:07:21 +00001143 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001144 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001145 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001146 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001147 return SQLITE_IOERR;
1148 }
drh99ab3b12011-03-02 15:09:07 +00001149 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001150 if( rc!=0 ){
1151 pFile->lastErrno = errno;
1152 return SQLITE_IOERR;
1153 }
1154 }
drheb0d74f2009-02-03 15:27:02 +00001155#endif
drh6c7d5c52008-11-21 20:32:33 +00001156
drh8af6c222010-05-14 12:43:01 +00001157 memset(&fileId, 0, sizeof(fileId));
1158 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001159#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001160 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001161#else
drh8af6c222010-05-14 12:43:01 +00001162 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001163#endif
drh8af6c222010-05-14 12:43:01 +00001164 pInode = inodeList;
1165 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1166 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001167 }
drh8af6c222010-05-14 12:43:01 +00001168 if( pInode==0 ){
1169 pInode = sqlite3_malloc( sizeof(*pInode) );
1170 if( pInode==0 ){
1171 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001172 }
drh8af6c222010-05-14 12:43:01 +00001173 memset(pInode, 0, sizeof(*pInode));
1174 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1175 pInode->nRef = 1;
1176 pInode->pNext = inodeList;
1177 pInode->pPrev = 0;
1178 if( inodeList ) inodeList->pPrev = pInode;
1179 inodeList = pInode;
1180 }else{
1181 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001182 }
drh8af6c222010-05-14 12:43:01 +00001183 *ppInode = pInode;
1184 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001185}
drh6c7d5c52008-11-21 20:32:33 +00001186
aswift5b1a2562008-08-22 00:22:35 +00001187
1188/*
danielk197713adf8a2004-06-03 16:08:41 +00001189** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001190** file by this or any other process. If such a lock is held, set *pResOut
1191** to a non-zero value otherwise *pResOut is set to zero. The return value
1192** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001193*/
danielk1977861f7452008-06-05 11:39:11 +00001194static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001195 int rc = SQLITE_OK;
1196 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001197 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001198
danielk1977861f7452008-06-05 11:39:11 +00001199 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1200
drh054889e2005-11-30 03:20:31 +00001201 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001202 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001203
1204 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001205 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001206 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001207 }
1208
drh2ac3ee92004-06-07 16:27:46 +00001209 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001210 */
danielk197709480a92009-02-09 05:32:32 +00001211#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001212 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001213 struct flock lock;
1214 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001215 lock.l_start = RESERVED_BYTE;
1216 lock.l_len = 1;
1217 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001218 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1219 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1220 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001221 } else if( lock.l_type!=F_UNLCK ){
1222 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001223 }
1224 }
danielk197709480a92009-02-09 05:32:32 +00001225#endif
danielk197713adf8a2004-06-03 16:08:41 +00001226
drh6c7d5c52008-11-21 20:32:33 +00001227 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001228 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001229
aswift5b1a2562008-08-22 00:22:35 +00001230 *pResOut = reserved;
1231 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001232}
1233
1234/*
drha7e61d82011-03-12 17:02:57 +00001235** Attempt to set a system-lock on the file pFile. The lock is
1236** described by pLock.
1237**
drh77197112011-03-15 19:08:48 +00001238** If the pFile was opened read/write from unix-excl, then the only lock
1239** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001240** the first time any lock is attempted. All subsequent system locking
1241** operations become no-ops. Locking operations still happen internally,
1242** in order to coordinate access between separate database connections
1243** within this process, but all of that is handled in memory and the
1244** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001245**
1246** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1247** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1248** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001249**
1250** Zero is returned if the call completes successfully, or -1 if a call
1251** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001252*/
1253static int unixFileLock(unixFile *pFile, struct flock *pLock){
1254 int rc;
drh3cb93392011-03-12 18:10:44 +00001255 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001256 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001257 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001258 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1259 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1260 ){
drh3cb93392011-03-12 18:10:44 +00001261 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001262 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001263 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001264 lock.l_whence = SEEK_SET;
1265 lock.l_start = SHARED_FIRST;
1266 lock.l_len = SHARED_SIZE;
1267 lock.l_type = F_WRLCK;
1268 rc = osFcntl(pFile->h, F_SETLK, &lock);
1269 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001270 pInode->bProcessLock = 1;
1271 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001272 }else{
1273 rc = 0;
1274 }
1275 }else{
1276 rc = osFcntl(pFile->h, F_SETLK, pLock);
1277 }
1278 return rc;
1279}
1280
1281/*
drh308c2a52010-05-14 11:30:18 +00001282** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001283** of the following:
1284**
drh2ac3ee92004-06-07 16:27:46 +00001285** (1) SHARED_LOCK
1286** (2) RESERVED_LOCK
1287** (3) PENDING_LOCK
1288** (4) EXCLUSIVE_LOCK
1289**
drhb3e04342004-06-08 00:47:47 +00001290** Sometimes when requesting one lock state, additional lock states
1291** are inserted in between. The locking might fail on one of the later
1292** transitions leaving the lock state different from what it started but
1293** still short of its goal. The following chart shows the allowed
1294** transitions and the inserted intermediate states:
1295**
1296** UNLOCKED -> SHARED
1297** SHARED -> RESERVED
1298** SHARED -> (PENDING) -> EXCLUSIVE
1299** RESERVED -> (PENDING) -> EXCLUSIVE
1300** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001301**
drha6abd042004-06-09 17:37:22 +00001302** This routine will only increase a lock. Use the sqlite3OsUnlock()
1303** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001304*/
drh308c2a52010-05-14 11:30:18 +00001305static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001306 /* The following describes the implementation of the various locks and
1307 ** lock transitions in terms of the POSIX advisory shared and exclusive
1308 ** lock primitives (called read-locks and write-locks below, to avoid
1309 ** confusion with SQLite lock names). The algorithms are complicated
1310 ** slightly in order to be compatible with windows systems simultaneously
1311 ** accessing the same database file, in case that is ever required.
1312 **
1313 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1314 ** byte', each single bytes at well known offsets, and the 'shared byte
1315 ** range', a range of 510 bytes at a well known offset.
1316 **
1317 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1318 ** byte'. If this is successful, a random byte from the 'shared byte
1319 ** range' is read-locked and the lock on the 'pending byte' released.
1320 **
danielk197790ba3bd2004-06-25 08:32:25 +00001321 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1322 ** A RESERVED lock is implemented by grabbing a write-lock on the
1323 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001324 **
1325 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001326 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1327 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1328 ** obtained, but existing SHARED locks are allowed to persist. A process
1329 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1330 ** This property is used by the algorithm for rolling back a journal file
1331 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001332 **
danielk197790ba3bd2004-06-25 08:32:25 +00001333 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1334 ** implemented by obtaining a write-lock on the entire 'shared byte
1335 ** range'. Since all other locks require a read-lock on one of the bytes
1336 ** within this range, this ensures that no other locks are held on the
1337 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001338 **
1339 ** The reason a single byte cannot be used instead of the 'shared byte
1340 ** range' is that some versions of windows do not support read-locks. By
1341 ** locking a random byte from a range, concurrent SHARED locks may exist
1342 ** even if the locking primitive used is always a write-lock.
1343 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001344 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001345 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001346 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001347 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001348 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001349
drh054889e2005-11-30 03:20:31 +00001350 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001351 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1352 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001353 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001354
1355 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001356 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001357 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001358 */
drh308c2a52010-05-14 11:30:18 +00001359 if( pFile->eFileLock>=eFileLock ){
1360 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1361 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001362 return SQLITE_OK;
1363 }
1364
drh0c2694b2009-09-03 16:23:44 +00001365 /* Make sure the locking sequence is correct.
1366 ** (1) We never move from unlocked to anything higher than shared lock.
1367 ** (2) SQLite never explicitly requests a pendig lock.
1368 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001369 */
drh308c2a52010-05-14 11:30:18 +00001370 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1371 assert( eFileLock!=PENDING_LOCK );
1372 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001373
drh8af6c222010-05-14 12:43:01 +00001374 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001375 */
drh6c7d5c52008-11-21 20:32:33 +00001376 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001377 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001378
danielk1977ad94b582007-08-20 06:44:22 +00001379 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001380 ** handle that precludes the requested lock, return BUSY.
1381 */
drh8af6c222010-05-14 12:43:01 +00001382 if( (pFile->eFileLock!=pInode->eFileLock &&
1383 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001384 ){
1385 rc = SQLITE_BUSY;
1386 goto end_lock;
1387 }
1388
1389 /* If a SHARED lock is requested, and some thread using this PID already
1390 ** has a SHARED or RESERVED lock, then increment reference counts and
1391 ** return SQLITE_OK.
1392 */
drh308c2a52010-05-14 11:30:18 +00001393 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001394 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001395 assert( eFileLock==SHARED_LOCK );
1396 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001397 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001398 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001399 pInode->nShared++;
1400 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001401 goto end_lock;
1402 }
1403
danielk19779a1d0ab2004-06-01 14:09:28 +00001404
drh3cde3bb2004-06-12 02:17:14 +00001405 /* A PENDING lock is needed before acquiring a SHARED lock and before
1406 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1407 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001408 */
drh0c2694b2009-09-03 16:23:44 +00001409 lock.l_len = 1L;
1410 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001411 if( eFileLock==SHARED_LOCK
1412 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001413 ){
drh308c2a52010-05-14 11:30:18 +00001414 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001415 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001416 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001417 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001418 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001419 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001420 pFile->lastErrno = tErrno;
1421 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001422 goto end_lock;
1423 }
drh3cde3bb2004-06-12 02:17:14 +00001424 }
1425
1426
1427 /* If control gets to this point, then actually go ahead and make
1428 ** operating system calls for the specified lock.
1429 */
drh308c2a52010-05-14 11:30:18 +00001430 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001431 assert( pInode->nShared==0 );
1432 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001433 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001434
drh2ac3ee92004-06-07 16:27:46 +00001435 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001436 lock.l_start = SHARED_FIRST;
1437 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001438 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001439 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001440 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001441 }
dan661d71a2011-03-30 19:08:03 +00001442
drh2ac3ee92004-06-07 16:27:46 +00001443 /* Drop the temporary PENDING lock */
1444 lock.l_start = PENDING_BYTE;
1445 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001446 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001447 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1448 /* This could happen with a network mount */
1449 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001450 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001451 }
dan661d71a2011-03-30 19:08:03 +00001452
1453 if( rc ){
1454 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001455 pFile->lastErrno = tErrno;
1456 }
dan661d71a2011-03-30 19:08:03 +00001457 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001458 }else{
drh308c2a52010-05-14 11:30:18 +00001459 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001460 pInode->nLock++;
1461 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001462 }
drh8af6c222010-05-14 12:43:01 +00001463 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001464 /* We are trying for an exclusive lock but another thread in this
1465 ** same process is still holding a shared lock. */
1466 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001467 }else{
drh3cde3bb2004-06-12 02:17:14 +00001468 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001469 ** assumed that there is a SHARED or greater lock on the file
1470 ** already.
1471 */
drh308c2a52010-05-14 11:30:18 +00001472 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001473 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001474
1475 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1476 if( eFileLock==RESERVED_LOCK ){
1477 lock.l_start = RESERVED_BYTE;
1478 lock.l_len = 1L;
1479 }else{
1480 lock.l_start = SHARED_FIRST;
1481 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001482 }
dan661d71a2011-03-30 19:08:03 +00001483
1484 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001485 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001486 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001487 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001488 pFile->lastErrno = tErrno;
1489 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001490 }
drhbbd42a62004-05-22 17:41:58 +00001491 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001492
drh8f941bc2009-01-14 23:03:40 +00001493
1494#ifndef NDEBUG
1495 /* Set up the transaction-counter change checking flags when
1496 ** transitioning from a SHARED to a RESERVED lock. The change
1497 ** from SHARED to RESERVED marks the beginning of a normal
1498 ** write operation (not a hot journal rollback).
1499 */
1500 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001501 && pFile->eFileLock<=SHARED_LOCK
1502 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001503 ){
1504 pFile->transCntrChng = 0;
1505 pFile->dbUpdate = 0;
1506 pFile->inNormalWrite = 1;
1507 }
1508#endif
1509
1510
danielk1977ecb2a962004-06-02 06:30:16 +00001511 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001512 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001513 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001514 }else if( eFileLock==EXCLUSIVE_LOCK ){
1515 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001516 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001517 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001518
1519end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001520 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001521 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1522 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001523 return rc;
1524}
1525
1526/*
dan08da86a2009-08-21 17:18:03 +00001527** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001528** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001529*/
1530static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001531 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001532 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001533 p->pNext = pInode->pUnused;
1534 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001535 pFile->h = -1;
1536 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001537}
1538
1539/*
drh308c2a52010-05-14 11:30:18 +00001540** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001541** must be either NO_LOCK or SHARED_LOCK.
1542**
1543** If the locking level of the file descriptor is already at or below
1544** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001545**
1546** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1547** the byte range is divided into 2 parts and the first part is unlocked then
1548** set to a read lock, then the other part is simply unlocked. This works
1549** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1550** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001551*/
drha7e61d82011-03-12 17:02:57 +00001552static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001553 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001554 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001555 struct flock lock;
1556 int rc = SQLITE_OK;
1557 int h;
drha6abd042004-06-09 17:37:22 +00001558
drh054889e2005-11-30 03:20:31 +00001559 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001560 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001561 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001562 getpid()));
drha6abd042004-06-09 17:37:22 +00001563
drh308c2a52010-05-14 11:30:18 +00001564 assert( eFileLock<=SHARED_LOCK );
1565 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001566 return SQLITE_OK;
1567 }
drh6c7d5c52008-11-21 20:32:33 +00001568 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001569 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001570 pInode = pFile->pInode;
1571 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001572 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001573 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001574 SimulateIOErrorBenign(1);
1575 SimulateIOError( h=(-1) )
1576 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001577
1578#ifndef NDEBUG
1579 /* When reducing a lock such that other processes can start
1580 ** reading the database file again, make sure that the
1581 ** transaction counter was updated if any part of the database
1582 ** file changed. If the transaction counter is not updated,
1583 ** other connections to the same file might not realize that
1584 ** the file has changed and hence might not know to flush their
1585 ** cache. The use of a stale cache can lead to database corruption.
1586 */
dan7c246102010-04-12 19:00:29 +00001587#if 0
drh8f941bc2009-01-14 23:03:40 +00001588 assert( pFile->inNormalWrite==0
1589 || pFile->dbUpdate==0
1590 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001591#endif
drh8f941bc2009-01-14 23:03:40 +00001592 pFile->inNormalWrite = 0;
1593#endif
1594
drh7ed97b92010-01-20 13:07:21 +00001595 /* downgrading to a shared lock on NFS involves clearing the write lock
1596 ** before establishing the readlock - to avoid a race condition we downgrade
1597 ** the lock in 2 blocks, so that part of the range will be covered by a
1598 ** write lock until the rest is covered by a read lock:
1599 ** 1: [WWWWW]
1600 ** 2: [....W]
1601 ** 3: [RRRRW]
1602 ** 4: [RRRR.]
1603 */
drh308c2a52010-05-14 11:30:18 +00001604 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001605
1606#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001607 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001608 assert( handleNFSUnlock==0 );
1609#endif
1610#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001611 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001612 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001613 off_t divSize = SHARED_SIZE - 1;
1614
1615 lock.l_type = F_UNLCK;
1616 lock.l_whence = SEEK_SET;
1617 lock.l_start = SHARED_FIRST;
1618 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001619 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001620 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001621 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001622 if( IS_LOCK_ERROR(rc) ){
1623 pFile->lastErrno = tErrno;
1624 }
1625 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001626 }
drh7ed97b92010-01-20 13:07:21 +00001627 lock.l_type = F_RDLCK;
1628 lock.l_whence = SEEK_SET;
1629 lock.l_start = SHARED_FIRST;
1630 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001631 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001632 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001633 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1634 if( IS_LOCK_ERROR(rc) ){
1635 pFile->lastErrno = tErrno;
1636 }
1637 goto end_unlock;
1638 }
1639 lock.l_type = F_UNLCK;
1640 lock.l_whence = SEEK_SET;
1641 lock.l_start = SHARED_FIRST+divSize;
1642 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001643 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001644 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001645 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001646 if( IS_LOCK_ERROR(rc) ){
1647 pFile->lastErrno = tErrno;
1648 }
1649 goto end_unlock;
1650 }
drh30f776f2011-02-25 03:25:07 +00001651 }else
1652#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1653 {
drh7ed97b92010-01-20 13:07:21 +00001654 lock.l_type = F_RDLCK;
1655 lock.l_whence = SEEK_SET;
1656 lock.l_start = SHARED_FIRST;
1657 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001658 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001659 /* In theory, the call to unixFileLock() cannot fail because another
1660 ** process is holding an incompatible lock. If it does, this
1661 ** indicates that the other process is not following the locking
1662 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1663 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1664 ** an assert to fail). */
1665 rc = SQLITE_IOERR_RDLOCK;
1666 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001667 goto end_unlock;
1668 }
drh9c105bb2004-10-02 20:38:28 +00001669 }
1670 }
drhbbd42a62004-05-22 17:41:58 +00001671 lock.l_type = F_UNLCK;
1672 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001673 lock.l_start = PENDING_BYTE;
1674 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001675 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001676 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001677 }else{
danea83bc62011-04-01 11:56:32 +00001678 rc = SQLITE_IOERR_UNLOCK;
1679 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001680 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001681 }
drhbbd42a62004-05-22 17:41:58 +00001682 }
drh308c2a52010-05-14 11:30:18 +00001683 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001684 /* Decrement the shared lock counter. Release the lock using an
1685 ** OS call only when all threads in this same process have released
1686 ** the lock.
1687 */
drh8af6c222010-05-14 12:43:01 +00001688 pInode->nShared--;
1689 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001690 lock.l_type = F_UNLCK;
1691 lock.l_whence = SEEK_SET;
1692 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001693 SimulateIOErrorBenign(1);
1694 SimulateIOError( h=(-1) )
1695 SimulateIOErrorBenign(0);
dan661d71a2011-03-30 19:08:03 +00001696 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001697 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001698 }else{
danea83bc62011-04-01 11:56:32 +00001699 rc = SQLITE_IOERR_UNLOCK;
1700 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001701 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001702 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001703 }
drha6abd042004-06-09 17:37:22 +00001704 }
1705
drhbbd42a62004-05-22 17:41:58 +00001706 /* Decrement the count of locks against this same file. When the
1707 ** count reaches zero, close any other file descriptors whose close
1708 ** was deferred because of outstanding locks.
1709 */
drh8af6c222010-05-14 12:43:01 +00001710 pInode->nLock--;
1711 assert( pInode->nLock>=0 );
1712 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001713 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001714 }
1715 }
aswift5b1a2562008-08-22 00:22:35 +00001716
1717end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001718 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001719 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001720 return rc;
drhbbd42a62004-05-22 17:41:58 +00001721}
1722
1723/*
drh308c2a52010-05-14 11:30:18 +00001724** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001725** must be either NO_LOCK or SHARED_LOCK.
1726**
1727** If the locking level of the file descriptor is already at or below
1728** the requested locking level, this routine is a no-op.
1729*/
drh308c2a52010-05-14 11:30:18 +00001730static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001731 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001732}
1733
1734/*
danielk1977e339d652008-06-28 11:23:00 +00001735** This function performs the parts of the "close file" operation
1736** common to all locking schemes. It closes the directory and file
1737** handles, if they are valid, and sets all fields of the unixFile
1738** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001739**
1740** It is *not* necessary to hold the mutex when this routine is called,
1741** even on VxWorks. A mutex will be acquired on VxWorks by the
1742** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001743*/
1744static int closeUnixFile(sqlite3_file *id){
1745 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001746 if( pFile->dirfd>=0 ){
1747 robust_close(pFile, pFile->dirfd, __LINE__);
1748 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001749 }
dan661d71a2011-03-30 19:08:03 +00001750 if( pFile->h>=0 ){
1751 robust_close(pFile, pFile->h, __LINE__);
1752 pFile->h = -1;
1753 }
1754#if OS_VXWORKS
1755 if( pFile->pId ){
1756 if( pFile->isDelete ){
1757 unlink(pFile->pId->zCanonicalName);
1758 }
1759 vxworksReleaseFileId(pFile->pId);
1760 pFile->pId = 0;
1761 }
1762#endif
1763 OSTRACE(("CLOSE %-3d\n", pFile->h));
1764 OpenCounter(-1);
1765 sqlite3_free(pFile->pUnused);
1766 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001767 return SQLITE_OK;
1768}
1769
1770/*
danielk1977e3026632004-06-22 11:29:02 +00001771** Close a file.
1772*/
danielk197762079062007-08-15 17:08:46 +00001773static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001774 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001775 unixFile *pFile = (unixFile *)id;
1776 unixUnlock(id, NO_LOCK);
1777 unixEnterMutex();
1778
1779 /* unixFile.pInode is always valid here. Otherwise, a different close
1780 ** routine (e.g. nolockClose()) would be called instead.
1781 */
1782 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1783 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1784 /* If there are outstanding locks, do not actually close the file just
1785 ** yet because that would clear those locks. Instead, add the file
1786 ** descriptor to pInode->pUnused list. It will be automatically closed
1787 ** when the last lock is cleared.
1788 */
1789 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001790 }
dan661d71a2011-03-30 19:08:03 +00001791 releaseInodeInfo(pFile);
1792 rc = closeUnixFile(id);
1793 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001794 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001795}
1796
drh734c9862008-11-28 15:37:20 +00001797/************** End of the posix advisory lock implementation *****************
1798******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001799
drh734c9862008-11-28 15:37:20 +00001800/******************************************************************************
1801****************************** No-op Locking **********************************
1802**
1803** Of the various locking implementations available, this is by far the
1804** simplest: locking is ignored. No attempt is made to lock the database
1805** file for reading or writing.
1806**
1807** This locking mode is appropriate for use on read-only databases
1808** (ex: databases that are burned into CD-ROM, for example.) It can
1809** also be used if the application employs some external mechanism to
1810** prevent simultaneous access of the same database by two or more
1811** database connections. But there is a serious risk of database
1812** corruption if this locking mode is used in situations where multiple
1813** database connections are accessing the same database file at the same
1814** time and one or more of those connections are writing.
1815*/
drhbfe66312006-10-03 17:40:40 +00001816
drh734c9862008-11-28 15:37:20 +00001817static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1818 UNUSED_PARAMETER(NotUsed);
1819 *pResOut = 0;
1820 return SQLITE_OK;
1821}
drh734c9862008-11-28 15:37:20 +00001822static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1823 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1824 return SQLITE_OK;
1825}
drh734c9862008-11-28 15:37:20 +00001826static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1827 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1828 return SQLITE_OK;
1829}
1830
1831/*
drh9b35ea62008-11-29 02:20:26 +00001832** Close the file.
drh734c9862008-11-28 15:37:20 +00001833*/
1834static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001835 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001836}
1837
1838/******************* End of the no-op lock implementation *********************
1839******************************************************************************/
1840
1841/******************************************************************************
1842************************* Begin dot-file Locking ******************************
1843**
drh0c2694b2009-09-03 16:23:44 +00001844** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001845** files in order to control access to the database. This works on just
1846** about every filesystem imaginable. But there are serious downsides:
1847**
1848** (1) There is zero concurrency. A single reader blocks all other
1849** connections from reading or writing the database.
1850**
1851** (2) An application crash or power loss can leave stale lock files
1852** sitting around that need to be cleared manually.
1853**
1854** Nevertheless, a dotlock is an appropriate locking mode for use if no
1855** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001856**
1857** Dotfile locking works by creating a file in the same directory as the
1858** database and with the same name but with a ".lock" extension added.
1859** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1860** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001861*/
1862
1863/*
1864** The file suffix added to the data base filename in order to create the
1865** lock file.
1866*/
1867#define DOTLOCK_SUFFIX ".lock"
1868
drh7708e972008-11-29 00:56:52 +00001869/*
1870** This routine checks if there is a RESERVED lock held on the specified
1871** file by this or any other process. If such a lock is held, set *pResOut
1872** to a non-zero value otherwise *pResOut is set to zero. The return value
1873** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1874**
1875** In dotfile locking, either a lock exists or it does not. So in this
1876** variation of CheckReservedLock(), *pResOut is set to true if any lock
1877** is held on the file and false if the file is unlocked.
1878*/
drh734c9862008-11-28 15:37:20 +00001879static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1880 int rc = SQLITE_OK;
1881 int reserved = 0;
1882 unixFile *pFile = (unixFile*)id;
1883
1884 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1885
1886 assert( pFile );
1887
1888 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001889 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001890 /* Either this connection or some other connection in the same process
1891 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001892 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001893 }else{
1894 /* The lock is held if and only if the lockfile exists */
1895 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001896 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001897 }
drh308c2a52010-05-14 11:30:18 +00001898 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001899 *pResOut = reserved;
1900 return rc;
1901}
1902
drh7708e972008-11-29 00:56:52 +00001903/*
drh308c2a52010-05-14 11:30:18 +00001904** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001905** of the following:
1906**
1907** (1) SHARED_LOCK
1908** (2) RESERVED_LOCK
1909** (3) PENDING_LOCK
1910** (4) EXCLUSIVE_LOCK
1911**
1912** Sometimes when requesting one lock state, additional lock states
1913** are inserted in between. The locking might fail on one of the later
1914** transitions leaving the lock state different from what it started but
1915** still short of its goal. The following chart shows the allowed
1916** transitions and the inserted intermediate states:
1917**
1918** UNLOCKED -> SHARED
1919** SHARED -> RESERVED
1920** SHARED -> (PENDING) -> EXCLUSIVE
1921** RESERVED -> (PENDING) -> EXCLUSIVE
1922** PENDING -> EXCLUSIVE
1923**
1924** This routine will only increase a lock. Use the sqlite3OsUnlock()
1925** routine to lower a locking level.
1926**
1927** With dotfile locking, we really only support state (4): EXCLUSIVE.
1928** But we track the other locking levels internally.
1929*/
drh308c2a52010-05-14 11:30:18 +00001930static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001931 unixFile *pFile = (unixFile*)id;
1932 int fd;
1933 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001934 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001935
drh7708e972008-11-29 00:56:52 +00001936
1937 /* If we have any lock, then the lock file already exists. All we have
1938 ** to do is adjust our internal record of the lock level.
1939 */
drh308c2a52010-05-14 11:30:18 +00001940 if( pFile->eFileLock > NO_LOCK ){
1941 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001942#if !OS_VXWORKS
1943 /* Always update the timestamp on the old file */
1944 utimes(zLockFile, NULL);
1945#endif
drh7708e972008-11-29 00:56:52 +00001946 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001947 }
1948
1949 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001950 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001951 if( fd<0 ){
1952 /* failed to open/create the file, someone else may have stolen the lock */
1953 int tErrno = errno;
1954 if( EEXIST == tErrno ){
1955 rc = SQLITE_BUSY;
1956 } else {
1957 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1958 if( IS_LOCK_ERROR(rc) ){
1959 pFile->lastErrno = tErrno;
1960 }
1961 }
drh7708e972008-11-29 00:56:52 +00001962 return rc;
drh734c9862008-11-28 15:37:20 +00001963 }
drh0e9365c2011-03-02 02:08:13 +00001964 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001965
1966 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001967 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001968 return rc;
1969}
1970
drh7708e972008-11-29 00:56:52 +00001971/*
drh308c2a52010-05-14 11:30:18 +00001972** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001973** must be either NO_LOCK or SHARED_LOCK.
1974**
1975** If the locking level of the file descriptor is already at or below
1976** the requested locking level, this routine is a no-op.
1977**
1978** When the locking level reaches NO_LOCK, delete the lock file.
1979*/
drh308c2a52010-05-14 11:30:18 +00001980static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001981 unixFile *pFile = (unixFile*)id;
1982 char *zLockFile = (char *)pFile->lockingContext;
1983
1984 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001985 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1986 pFile->eFileLock, getpid()));
1987 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001988
1989 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001990 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001991 return SQLITE_OK;
1992 }
drh7708e972008-11-29 00:56:52 +00001993
1994 /* To downgrade to shared, simply update our internal notion of the
1995 ** lock state. No need to mess with the file on disk.
1996 */
drh308c2a52010-05-14 11:30:18 +00001997 if( eFileLock==SHARED_LOCK ){
1998 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001999 return SQLITE_OK;
2000 }
2001
drh7708e972008-11-29 00:56:52 +00002002 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002003 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00002004 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00002005 int rc = 0;
2006 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002007 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002008 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002009 }
2010 if( IS_LOCK_ERROR(rc) ){
2011 pFile->lastErrno = tErrno;
2012 }
2013 return rc;
2014 }
drh308c2a52010-05-14 11:30:18 +00002015 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002016 return SQLITE_OK;
2017}
2018
2019/*
drh9b35ea62008-11-29 02:20:26 +00002020** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002021*/
2022static int dotlockClose(sqlite3_file *id) {
2023 int rc;
2024 if( id ){
2025 unixFile *pFile = (unixFile*)id;
2026 dotlockUnlock(id, NO_LOCK);
2027 sqlite3_free(pFile->lockingContext);
2028 }
drh734c9862008-11-28 15:37:20 +00002029 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002030 return rc;
2031}
2032/****************** End of the dot-file lock implementation *******************
2033******************************************************************************/
2034
2035/******************************************************************************
2036************************** Begin flock Locking ********************************
2037**
2038** Use the flock() system call to do file locking.
2039**
drh6b9d6dd2008-12-03 19:34:47 +00002040** flock() locking is like dot-file locking in that the various
2041** fine-grain locking levels supported by SQLite are collapsed into
2042** a single exclusive lock. In other words, SHARED, RESERVED, and
2043** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2044** still works when you do this, but concurrency is reduced since
2045** only a single process can be reading the database at a time.
2046**
drh734c9862008-11-28 15:37:20 +00002047** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2048** compiling for VXWORKS.
2049*/
2050#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002051
drh6b9d6dd2008-12-03 19:34:47 +00002052/*
drhff812312011-02-23 13:33:46 +00002053** Retry flock() calls that fail with EINTR
2054*/
2055#ifdef EINTR
2056static int robust_flock(int fd, int op){
2057 int rc;
2058 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2059 return rc;
2060}
2061#else
drh5c819272011-02-23 14:00:12 +00002062# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002063#endif
2064
2065
2066/*
drh6b9d6dd2008-12-03 19:34:47 +00002067** This routine checks if there is a RESERVED lock held on the specified
2068** file by this or any other process. If such a lock is held, set *pResOut
2069** to a non-zero value otherwise *pResOut is set to zero. The return value
2070** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2071*/
drh734c9862008-11-28 15:37:20 +00002072static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2073 int rc = SQLITE_OK;
2074 int reserved = 0;
2075 unixFile *pFile = (unixFile*)id;
2076
2077 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2078
2079 assert( pFile );
2080
2081 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002082 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002083 reserved = 1;
2084 }
2085
2086 /* Otherwise see if some other process holds it. */
2087 if( !reserved ){
2088 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002089 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002090 if( !lrc ){
2091 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002092 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002093 if ( lrc ) {
2094 int tErrno = errno;
2095 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002096 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002097 if( IS_LOCK_ERROR(lrc) ){
2098 pFile->lastErrno = tErrno;
2099 rc = lrc;
2100 }
2101 }
2102 } else {
2103 int tErrno = errno;
2104 reserved = 1;
2105 /* someone else might have it reserved */
2106 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2107 if( IS_LOCK_ERROR(lrc) ){
2108 pFile->lastErrno = tErrno;
2109 rc = lrc;
2110 }
2111 }
2112 }
drh308c2a52010-05-14 11:30:18 +00002113 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002114
2115#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2116 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2117 rc = SQLITE_OK;
2118 reserved=1;
2119 }
2120#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2121 *pResOut = reserved;
2122 return rc;
2123}
2124
drh6b9d6dd2008-12-03 19:34:47 +00002125/*
drh308c2a52010-05-14 11:30:18 +00002126** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002127** of the following:
2128**
2129** (1) SHARED_LOCK
2130** (2) RESERVED_LOCK
2131** (3) PENDING_LOCK
2132** (4) EXCLUSIVE_LOCK
2133**
2134** Sometimes when requesting one lock state, additional lock states
2135** are inserted in between. The locking might fail on one of the later
2136** transitions leaving the lock state different from what it started but
2137** still short of its goal. The following chart shows the allowed
2138** transitions and the inserted intermediate states:
2139**
2140** UNLOCKED -> SHARED
2141** SHARED -> RESERVED
2142** SHARED -> (PENDING) -> EXCLUSIVE
2143** RESERVED -> (PENDING) -> EXCLUSIVE
2144** PENDING -> EXCLUSIVE
2145**
2146** flock() only really support EXCLUSIVE locks. We track intermediate
2147** lock states in the sqlite3_file structure, but all locks SHARED or
2148** above are really EXCLUSIVE locks and exclude all other processes from
2149** access the file.
2150**
2151** This routine will only increase a lock. Use the sqlite3OsUnlock()
2152** routine to lower a locking level.
2153*/
drh308c2a52010-05-14 11:30:18 +00002154static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002155 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002156 unixFile *pFile = (unixFile*)id;
2157
2158 assert( pFile );
2159
2160 /* if we already have a lock, it is exclusive.
2161 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002162 if (pFile->eFileLock > NO_LOCK) {
2163 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002164 return SQLITE_OK;
2165 }
2166
2167 /* grab an exclusive lock */
2168
drhff812312011-02-23 13:33:46 +00002169 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002170 int tErrno = errno;
2171 /* didn't get, must be busy */
2172 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2173 if( IS_LOCK_ERROR(rc) ){
2174 pFile->lastErrno = tErrno;
2175 }
2176 } else {
2177 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002178 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002179 }
drh308c2a52010-05-14 11:30:18 +00002180 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2181 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002182#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2183 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2184 rc = SQLITE_BUSY;
2185 }
2186#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2187 return rc;
2188}
2189
drh6b9d6dd2008-12-03 19:34:47 +00002190
2191/*
drh308c2a52010-05-14 11:30:18 +00002192** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002193** must be either NO_LOCK or SHARED_LOCK.
2194**
2195** If the locking level of the file descriptor is already at or below
2196** the requested locking level, this routine is a no-op.
2197*/
drh308c2a52010-05-14 11:30:18 +00002198static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002199 unixFile *pFile = (unixFile*)id;
2200
2201 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002202 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2203 pFile->eFileLock, getpid()));
2204 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002205
2206 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002207 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002208 return SQLITE_OK;
2209 }
2210
2211 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002212 if (eFileLock==SHARED_LOCK) {
2213 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002214 return SQLITE_OK;
2215 }
2216
2217 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002218 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002219#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002220 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002221#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002222 return SQLITE_IOERR_UNLOCK;
2223 }else{
drh308c2a52010-05-14 11:30:18 +00002224 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002225 return SQLITE_OK;
2226 }
2227}
2228
2229/*
2230** Close a file.
2231*/
2232static int flockClose(sqlite3_file *id) {
2233 if( id ){
2234 flockUnlock(id, NO_LOCK);
2235 }
2236 return closeUnixFile(id);
2237}
2238
2239#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2240
2241/******************* End of the flock lock implementation *********************
2242******************************************************************************/
2243
2244/******************************************************************************
2245************************ Begin Named Semaphore Locking ************************
2246**
2247** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002248**
2249** Semaphore locking is like dot-lock and flock in that it really only
2250** supports EXCLUSIVE locking. Only a single process can read or write
2251** the database file at a time. This reduces potential concurrency, but
2252** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002253*/
2254#if OS_VXWORKS
2255
drh6b9d6dd2008-12-03 19:34:47 +00002256/*
2257** This routine checks if there is a RESERVED lock held on the specified
2258** file by this or any other process. If such a lock is held, set *pResOut
2259** to a non-zero value otherwise *pResOut is set to zero. The return value
2260** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2261*/
drh734c9862008-11-28 15:37:20 +00002262static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2263 int rc = SQLITE_OK;
2264 int reserved = 0;
2265 unixFile *pFile = (unixFile*)id;
2266
2267 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2268
2269 assert( pFile );
2270
2271 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002272 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002273 reserved = 1;
2274 }
2275
2276 /* Otherwise see if some other process holds it. */
2277 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002278 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002279 struct stat statBuf;
2280
2281 if( sem_trywait(pSem)==-1 ){
2282 int tErrno = errno;
2283 if( EAGAIN != tErrno ){
2284 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2285 pFile->lastErrno = tErrno;
2286 } else {
2287 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002288 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002289 }
2290 }else{
2291 /* we could have it if we want it */
2292 sem_post(pSem);
2293 }
2294 }
drh308c2a52010-05-14 11:30:18 +00002295 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002296
2297 *pResOut = reserved;
2298 return rc;
2299}
2300
drh6b9d6dd2008-12-03 19:34:47 +00002301/*
drh308c2a52010-05-14 11:30:18 +00002302** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002303** of the following:
2304**
2305** (1) SHARED_LOCK
2306** (2) RESERVED_LOCK
2307** (3) PENDING_LOCK
2308** (4) EXCLUSIVE_LOCK
2309**
2310** Sometimes when requesting one lock state, additional lock states
2311** are inserted in between. The locking might fail on one of the later
2312** transitions leaving the lock state different from what it started but
2313** still short of its goal. The following chart shows the allowed
2314** transitions and the inserted intermediate states:
2315**
2316** UNLOCKED -> SHARED
2317** SHARED -> RESERVED
2318** SHARED -> (PENDING) -> EXCLUSIVE
2319** RESERVED -> (PENDING) -> EXCLUSIVE
2320** PENDING -> EXCLUSIVE
2321**
2322** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2323** lock states in the sqlite3_file structure, but all locks SHARED or
2324** above are really EXCLUSIVE locks and exclude all other processes from
2325** access the file.
2326**
2327** This routine will only increase a lock. Use the sqlite3OsUnlock()
2328** routine to lower a locking level.
2329*/
drh308c2a52010-05-14 11:30:18 +00002330static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002331 unixFile *pFile = (unixFile*)id;
2332 int fd;
drh8af6c222010-05-14 12:43:01 +00002333 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002334 int rc = SQLITE_OK;
2335
2336 /* if we already have a lock, it is exclusive.
2337 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002338 if (pFile->eFileLock > NO_LOCK) {
2339 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002340 rc = SQLITE_OK;
2341 goto sem_end_lock;
2342 }
2343
2344 /* lock semaphore now but bail out when already locked. */
2345 if( sem_trywait(pSem)==-1 ){
2346 rc = SQLITE_BUSY;
2347 goto sem_end_lock;
2348 }
2349
2350 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002351 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002352
2353 sem_end_lock:
2354 return rc;
2355}
2356
drh6b9d6dd2008-12-03 19:34:47 +00002357/*
drh308c2a52010-05-14 11:30:18 +00002358** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002359** must be either NO_LOCK or SHARED_LOCK.
2360**
2361** If the locking level of the file descriptor is already at or below
2362** the requested locking level, this routine is a no-op.
2363*/
drh308c2a52010-05-14 11:30:18 +00002364static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002365 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002366 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002367
2368 assert( pFile );
2369 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002370 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2371 pFile->eFileLock, getpid()));
2372 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002373
2374 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002375 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002376 return SQLITE_OK;
2377 }
2378
2379 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002380 if (eFileLock==SHARED_LOCK) {
2381 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002382 return SQLITE_OK;
2383 }
2384
2385 /* no, really unlock. */
2386 if ( sem_post(pSem)==-1 ) {
2387 int rc, tErrno = errno;
2388 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2389 if( IS_LOCK_ERROR(rc) ){
2390 pFile->lastErrno = tErrno;
2391 }
2392 return rc;
2393 }
drh308c2a52010-05-14 11:30:18 +00002394 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002395 return SQLITE_OK;
2396}
2397
2398/*
2399 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002400 */
drh734c9862008-11-28 15:37:20 +00002401static int semClose(sqlite3_file *id) {
2402 if( id ){
2403 unixFile *pFile = (unixFile*)id;
2404 semUnlock(id, NO_LOCK);
2405 assert( pFile );
2406 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002407 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002408 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002409 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002410 }
2411 return SQLITE_OK;
2412}
2413
2414#endif /* OS_VXWORKS */
2415/*
2416** Named semaphore locking is only available on VxWorks.
2417**
2418*************** End of the named semaphore lock implementation ****************
2419******************************************************************************/
2420
2421
2422/******************************************************************************
2423*************************** Begin AFP Locking *********************************
2424**
2425** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2426** on Apple Macintosh computers - both OS9 and OSX.
2427**
2428** Third-party implementations of AFP are available. But this code here
2429** only works on OSX.
2430*/
2431
drhd2cb50b2009-01-09 21:41:17 +00002432#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002433/*
2434** The afpLockingContext structure contains all afp lock specific state
2435*/
drhbfe66312006-10-03 17:40:40 +00002436typedef struct afpLockingContext afpLockingContext;
2437struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002438 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002439 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002440};
2441
2442struct ByteRangeLockPB2
2443{
2444 unsigned long long offset; /* offset to first byte to lock */
2445 unsigned long long length; /* nbr of bytes to lock */
2446 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2447 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2448 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2449 int fd; /* file desc to assoc this lock with */
2450};
2451
drhfd131da2007-08-07 17:13:03 +00002452#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002453
drh6b9d6dd2008-12-03 19:34:47 +00002454/*
2455** This is a utility for setting or clearing a bit-range lock on an
2456** AFP filesystem.
2457**
2458** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2459*/
2460static int afpSetLock(
2461 const char *path, /* Name of the file to be locked or unlocked */
2462 unixFile *pFile, /* Open file descriptor on path */
2463 unsigned long long offset, /* First byte to be locked */
2464 unsigned long long length, /* Number of bytes to lock */
2465 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002466){
drh6b9d6dd2008-12-03 19:34:47 +00002467 struct ByteRangeLockPB2 pb;
2468 int err;
drhbfe66312006-10-03 17:40:40 +00002469
2470 pb.unLockFlag = setLockFlag ? 0 : 1;
2471 pb.startEndFlag = 0;
2472 pb.offset = offset;
2473 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002474 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002475
drh308c2a52010-05-14 11:30:18 +00002476 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002477 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002478 offset, length));
drhbfe66312006-10-03 17:40:40 +00002479 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2480 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002481 int rc;
2482 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002483 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2484 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002485#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2486 rc = SQLITE_BUSY;
2487#else
drh734c9862008-11-28 15:37:20 +00002488 rc = sqliteErrorFromPosixError(tErrno,
2489 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002490#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002491 if( IS_LOCK_ERROR(rc) ){
2492 pFile->lastErrno = tErrno;
2493 }
2494 return rc;
drhbfe66312006-10-03 17:40:40 +00002495 } else {
aswift5b1a2562008-08-22 00:22:35 +00002496 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002497 }
2498}
2499
drh6b9d6dd2008-12-03 19:34:47 +00002500/*
2501** This routine checks if there is a RESERVED lock held on the specified
2502** file by this or any other process. If such a lock is held, set *pResOut
2503** to a non-zero value otherwise *pResOut is set to zero. The return value
2504** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2505*/
danielk1977e339d652008-06-28 11:23:00 +00002506static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002507 int rc = SQLITE_OK;
2508 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002509 unixFile *pFile = (unixFile*)id;
2510
aswift5b1a2562008-08-22 00:22:35 +00002511 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2512
2513 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002514 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002515 if( context->reserved ){
2516 *pResOut = 1;
2517 return SQLITE_OK;
2518 }
drh8af6c222010-05-14 12:43:01 +00002519 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002520
2521 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002522 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002523 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002524 }
2525
2526 /* Otherwise see if some other process holds it.
2527 */
aswift5b1a2562008-08-22 00:22:35 +00002528 if( !reserved ){
2529 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002530 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002531 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002532 /* if we succeeded in taking the reserved lock, unlock it to restore
2533 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002534 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002535 } else {
2536 /* if we failed to get the lock then someone else must have it */
2537 reserved = 1;
2538 }
2539 if( IS_LOCK_ERROR(lrc) ){
2540 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002541 }
2542 }
drhbfe66312006-10-03 17:40:40 +00002543
drh7ed97b92010-01-20 13:07:21 +00002544 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002545 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002546
2547 *pResOut = reserved;
2548 return rc;
drhbfe66312006-10-03 17:40:40 +00002549}
2550
drh6b9d6dd2008-12-03 19:34:47 +00002551/*
drh308c2a52010-05-14 11:30:18 +00002552** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002553** of the following:
2554**
2555** (1) SHARED_LOCK
2556** (2) RESERVED_LOCK
2557** (3) PENDING_LOCK
2558** (4) EXCLUSIVE_LOCK
2559**
2560** Sometimes when requesting one lock state, additional lock states
2561** are inserted in between. The locking might fail on one of the later
2562** transitions leaving the lock state different from what it started but
2563** still short of its goal. The following chart shows the allowed
2564** transitions and the inserted intermediate states:
2565**
2566** UNLOCKED -> SHARED
2567** SHARED -> RESERVED
2568** SHARED -> (PENDING) -> EXCLUSIVE
2569** RESERVED -> (PENDING) -> EXCLUSIVE
2570** PENDING -> EXCLUSIVE
2571**
2572** This routine will only increase a lock. Use the sqlite3OsUnlock()
2573** routine to lower a locking level.
2574*/
drh308c2a52010-05-14 11:30:18 +00002575static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002576 int rc = SQLITE_OK;
2577 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002578 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002579 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002580
2581 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002582 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2583 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002584 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002585
drhbfe66312006-10-03 17:40:40 +00002586 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002587 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002588 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002589 */
drh308c2a52010-05-14 11:30:18 +00002590 if( pFile->eFileLock>=eFileLock ){
2591 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2592 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002593 return SQLITE_OK;
2594 }
2595
2596 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002597 ** (1) We never move from unlocked to anything higher than shared lock.
2598 ** (2) SQLite never explicitly requests a pendig lock.
2599 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002600 */
drh308c2a52010-05-14 11:30:18 +00002601 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2602 assert( eFileLock!=PENDING_LOCK );
2603 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002604
drh8af6c222010-05-14 12:43:01 +00002605 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002606 */
drh6c7d5c52008-11-21 20:32:33 +00002607 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002608 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002609
2610 /* If some thread using this PID has a lock via a different unixFile*
2611 ** handle that precludes the requested lock, return BUSY.
2612 */
drh8af6c222010-05-14 12:43:01 +00002613 if( (pFile->eFileLock!=pInode->eFileLock &&
2614 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002615 ){
2616 rc = SQLITE_BUSY;
2617 goto afp_end_lock;
2618 }
2619
2620 /* If a SHARED lock is requested, and some thread using this PID already
2621 ** has a SHARED or RESERVED lock, then increment reference counts and
2622 ** return SQLITE_OK.
2623 */
drh308c2a52010-05-14 11:30:18 +00002624 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002625 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002626 assert( eFileLock==SHARED_LOCK );
2627 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002628 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002629 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002630 pInode->nShared++;
2631 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002632 goto afp_end_lock;
2633 }
drhbfe66312006-10-03 17:40:40 +00002634
2635 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002636 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2637 ** be released.
2638 */
drh308c2a52010-05-14 11:30:18 +00002639 if( eFileLock==SHARED_LOCK
2640 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002641 ){
2642 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002643 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002644 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002645 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002646 goto afp_end_lock;
2647 }
2648 }
2649
2650 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002651 ** operating system calls for the specified lock.
2652 */
drh308c2a52010-05-14 11:30:18 +00002653 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002654 int lrc1, lrc2, lrc1Errno;
2655 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002656
drh8af6c222010-05-14 12:43:01 +00002657 assert( pInode->nShared==0 );
2658 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002659
2660 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002661 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002662 /* note that the quality of the randomness doesn't matter that much */
2663 lk = random();
drh8af6c222010-05-14 12:43:01 +00002664 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002665 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002666 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002667 if( IS_LOCK_ERROR(lrc1) ){
2668 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002669 }
aswift5b1a2562008-08-22 00:22:35 +00002670 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002671 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002672
aswift5b1a2562008-08-22 00:22:35 +00002673 if( IS_LOCK_ERROR(lrc1) ) {
2674 pFile->lastErrno = lrc1Errno;
2675 rc = lrc1;
2676 goto afp_end_lock;
2677 } else if( IS_LOCK_ERROR(lrc2) ){
2678 rc = lrc2;
2679 goto afp_end_lock;
2680 } else if( lrc1 != SQLITE_OK ) {
2681 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002682 } else {
drh308c2a52010-05-14 11:30:18 +00002683 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002684 pInode->nLock++;
2685 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002686 }
drh8af6c222010-05-14 12:43:01 +00002687 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002688 /* We are trying for an exclusive lock but another thread in this
2689 ** same process is still holding a shared lock. */
2690 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002691 }else{
2692 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2693 ** assumed that there is a SHARED or greater lock on the file
2694 ** already.
2695 */
2696 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002697 assert( 0!=pFile->eFileLock );
2698 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002699 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002700 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002701 if( !failed ){
2702 context->reserved = 1;
2703 }
drhbfe66312006-10-03 17:40:40 +00002704 }
drh308c2a52010-05-14 11:30:18 +00002705 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002706 /* Acquire an EXCLUSIVE lock */
2707
2708 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002709 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002710 */
drh6b9d6dd2008-12-03 19:34:47 +00002711 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002712 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002713 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002714 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002715 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002716 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002717 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002718 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002719 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2720 ** a critical I/O error
2721 */
2722 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2723 SQLITE_IOERR_LOCK;
2724 goto afp_end_lock;
2725 }
2726 }else{
aswift5b1a2562008-08-22 00:22:35 +00002727 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002728 }
2729 }
aswift5b1a2562008-08-22 00:22:35 +00002730 if( failed ){
2731 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002732 }
2733 }
2734
2735 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002736 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002737 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002738 }else if( eFileLock==EXCLUSIVE_LOCK ){
2739 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002740 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002741 }
2742
2743afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002744 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002745 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2746 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002747 return rc;
2748}
2749
2750/*
drh308c2a52010-05-14 11:30:18 +00002751** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002752** must be either NO_LOCK or SHARED_LOCK.
2753**
2754** If the locking level of the file descriptor is already at or below
2755** the requested locking level, this routine is a no-op.
2756*/
drh308c2a52010-05-14 11:30:18 +00002757static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002758 int rc = SQLITE_OK;
2759 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002760 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002761 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2762 int skipShared = 0;
2763#ifdef SQLITE_TEST
2764 int h = pFile->h;
2765#endif
drhbfe66312006-10-03 17:40:40 +00002766
2767 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002768 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002769 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002770 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002771
drh308c2a52010-05-14 11:30:18 +00002772 assert( eFileLock<=SHARED_LOCK );
2773 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002774 return SQLITE_OK;
2775 }
drh6c7d5c52008-11-21 20:32:33 +00002776 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002777 pInode = pFile->pInode;
2778 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002779 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002780 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002781 SimulateIOErrorBenign(1);
2782 SimulateIOError( h=(-1) )
2783 SimulateIOErrorBenign(0);
2784
2785#ifndef NDEBUG
2786 /* When reducing a lock such that other processes can start
2787 ** reading the database file again, make sure that the
2788 ** transaction counter was updated if any part of the database
2789 ** file changed. If the transaction counter is not updated,
2790 ** other connections to the same file might not realize that
2791 ** the file has changed and hence might not know to flush their
2792 ** cache. The use of a stale cache can lead to database corruption.
2793 */
2794 assert( pFile->inNormalWrite==0
2795 || pFile->dbUpdate==0
2796 || pFile->transCntrChng==1 );
2797 pFile->inNormalWrite = 0;
2798#endif
aswiftaebf4132008-11-21 00:10:35 +00002799
drh308c2a52010-05-14 11:30:18 +00002800 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002801 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002802 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002803 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002804 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002805 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2806 } else {
2807 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002808 }
2809 }
drh308c2a52010-05-14 11:30:18 +00002810 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002811 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002812 }
drh308c2a52010-05-14 11:30:18 +00002813 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002814 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2815 if( !rc ){
2816 context->reserved = 0;
2817 }
aswiftaebf4132008-11-21 00:10:35 +00002818 }
drh8af6c222010-05-14 12:43:01 +00002819 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2820 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002821 }
aswiftaebf4132008-11-21 00:10:35 +00002822 }
drh308c2a52010-05-14 11:30:18 +00002823 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002824
drh7ed97b92010-01-20 13:07:21 +00002825 /* Decrement the shared lock counter. Release the lock using an
2826 ** OS call only when all threads in this same process have released
2827 ** the lock.
2828 */
drh8af6c222010-05-14 12:43:01 +00002829 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2830 pInode->nShared--;
2831 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002832 SimulateIOErrorBenign(1);
2833 SimulateIOError( h=(-1) )
2834 SimulateIOErrorBenign(0);
2835 if( !skipShared ){
2836 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2837 }
2838 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002839 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002840 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002841 }
2842 }
2843 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002844 pInode->nLock--;
2845 assert( pInode->nLock>=0 );
2846 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002847 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002848 }
2849 }
drhbfe66312006-10-03 17:40:40 +00002850 }
drh7ed97b92010-01-20 13:07:21 +00002851
drh6c7d5c52008-11-21 20:32:33 +00002852 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002853 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002854 return rc;
2855}
2856
2857/*
drh339eb0b2008-03-07 15:34:11 +00002858** Close a file & cleanup AFP specific locking context
2859*/
danielk1977e339d652008-06-28 11:23:00 +00002860static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002861 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002862 if( id ){
2863 unixFile *pFile = (unixFile*)id;
2864 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002865 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002866 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002867 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002868 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002869 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002870 ** the last lock is cleared.
2871 */
dan08da86a2009-08-21 17:18:03 +00002872 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002873 }
danb0ac3e32010-06-16 10:55:42 +00002874 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002875 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002876 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002877 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002878 }
drh7ed97b92010-01-20 13:07:21 +00002879 return rc;
drhbfe66312006-10-03 17:40:40 +00002880}
2881
drhd2cb50b2009-01-09 21:41:17 +00002882#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002883/*
2884** The code above is the AFP lock implementation. The code is specific
2885** to MacOSX and does not work on other unix platforms. No alternative
2886** is available. If you don't compile for a mac, then the "unix-afp"
2887** VFS is not available.
2888**
2889********************* End of the AFP lock implementation **********************
2890******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002891
drh7ed97b92010-01-20 13:07:21 +00002892/******************************************************************************
2893*************************** Begin NFS Locking ********************************/
2894
2895#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2896/*
drh308c2a52010-05-14 11:30:18 +00002897 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002898 ** must be either NO_LOCK or SHARED_LOCK.
2899 **
2900 ** If the locking level of the file descriptor is already at or below
2901 ** the requested locking level, this routine is a no-op.
2902 */
drh308c2a52010-05-14 11:30:18 +00002903static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002904 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002905}
2906
2907#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2908/*
2909** The code above is the NFS lock implementation. The code is specific
2910** to MacOSX and does not work on other unix platforms. No alternative
2911** is available.
2912**
2913********************* End of the NFS lock implementation **********************
2914******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002915
2916/******************************************************************************
2917**************** Non-locking sqlite3_file methods *****************************
2918**
2919** The next division contains implementations for all methods of the
2920** sqlite3_file object other than the locking methods. The locking
2921** methods were defined in divisions above (one locking method per
2922** division). Those methods that are common to all locking modes
2923** are gather together into this division.
2924*/
drhbfe66312006-10-03 17:40:40 +00002925
2926/*
drh734c9862008-11-28 15:37:20 +00002927** Seek to the offset passed as the second argument, then read cnt
2928** bytes into pBuf. Return the number of bytes actually read.
2929**
2930** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2931** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2932** one system to another. Since SQLite does not define USE_PREAD
2933** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2934** See tickets #2741 and #2681.
2935**
2936** To avoid stomping the errno value on a failed read the lastErrno value
2937** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002938*/
drh734c9862008-11-28 15:37:20 +00002939static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2940 int got;
drh7ed97b92010-01-20 13:07:21 +00002941#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002942 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002943#endif
drh734c9862008-11-28 15:37:20 +00002944 TIMER_START;
2945#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002946 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002947 SimulateIOError( got = -1 );
2948#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002949 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002950 SimulateIOError( got = -1 );
2951#else
2952 newOffset = lseek(id->h, offset, SEEK_SET);
2953 SimulateIOError( newOffset-- );
2954 if( newOffset!=offset ){
2955 if( newOffset == -1 ){
2956 ((unixFile*)id)->lastErrno = errno;
2957 }else{
2958 ((unixFile*)id)->lastErrno = 0;
2959 }
2960 return -1;
2961 }
drhe562be52011-03-02 18:01:10 +00002962 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002963#endif
2964 TIMER_END;
2965 if( got<0 ){
2966 ((unixFile*)id)->lastErrno = errno;
2967 }
drh308c2a52010-05-14 11:30:18 +00002968 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002969 return got;
drhbfe66312006-10-03 17:40:40 +00002970}
2971
2972/*
drh734c9862008-11-28 15:37:20 +00002973** Read data from a file into a buffer. Return SQLITE_OK if all
2974** bytes were read successfully and SQLITE_IOERR if anything goes
2975** wrong.
drh339eb0b2008-03-07 15:34:11 +00002976*/
drh734c9862008-11-28 15:37:20 +00002977static int unixRead(
2978 sqlite3_file *id,
2979 void *pBuf,
2980 int amt,
2981 sqlite3_int64 offset
2982){
dan08da86a2009-08-21 17:18:03 +00002983 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002984 int got;
2985 assert( id );
drh08c6d442009-02-09 17:34:07 +00002986
dan08da86a2009-08-21 17:18:03 +00002987 /* If this is a database file (not a journal, master-journal or temp
2988 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002989#if 0
dane946c392009-08-22 11:39:46 +00002990 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002991 || offset>=PENDING_BYTE+512
2992 || offset+amt<=PENDING_BYTE
2993 );
dan7c246102010-04-12 19:00:29 +00002994#endif
drh08c6d442009-02-09 17:34:07 +00002995
dan08da86a2009-08-21 17:18:03 +00002996 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002997 if( got==amt ){
2998 return SQLITE_OK;
2999 }else if( got<0 ){
3000 /* lastErrno set by seekAndRead */
3001 return SQLITE_IOERR_READ;
3002 }else{
dan08da86a2009-08-21 17:18:03 +00003003 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003004 /* Unread parts of the buffer must be zero-filled */
3005 memset(&((char*)pBuf)[got], 0, amt-got);
3006 return SQLITE_IOERR_SHORT_READ;
3007 }
3008}
3009
3010/*
3011** Seek to the offset in id->offset then read cnt bytes into pBuf.
3012** Return the number of bytes actually read. Update the offset.
3013**
3014** To avoid stomping the errno value on a failed write the lastErrno value
3015** is set before returning.
3016*/
3017static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3018 int got;
drh7ed97b92010-01-20 13:07:21 +00003019#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003020 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003021#endif
drh734c9862008-11-28 15:37:20 +00003022 TIMER_START;
3023#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003024 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003025#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003026 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003027#else
3028 newOffset = lseek(id->h, offset, SEEK_SET);
dan661d71a2011-03-30 19:08:03 +00003029 SimulateIOError( newOffset-- );
drh734c9862008-11-28 15:37:20 +00003030 if( newOffset!=offset ){
3031 if( newOffset == -1 ){
3032 ((unixFile*)id)->lastErrno = errno;
3033 }else{
3034 ((unixFile*)id)->lastErrno = 0;
3035 }
3036 return -1;
3037 }
drhe562be52011-03-02 18:01:10 +00003038 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003039#endif
3040 TIMER_END;
3041 if( got<0 ){
3042 ((unixFile*)id)->lastErrno = errno;
3043 }
3044
drh308c2a52010-05-14 11:30:18 +00003045 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003046 return got;
3047}
3048
3049
3050/*
3051** Write data from a buffer into a file. Return SQLITE_OK on success
3052** or some other error code on failure.
3053*/
3054static int unixWrite(
3055 sqlite3_file *id,
3056 const void *pBuf,
3057 int amt,
3058 sqlite3_int64 offset
3059){
dan08da86a2009-08-21 17:18:03 +00003060 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003061 int wrote = 0;
3062 assert( id );
3063 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003064
dan08da86a2009-08-21 17:18:03 +00003065 /* If this is a database file (not a journal, master-journal or temp
3066 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003067#if 0
dane946c392009-08-22 11:39:46 +00003068 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003069 || offset>=PENDING_BYTE+512
3070 || offset+amt<=PENDING_BYTE
3071 );
dan7c246102010-04-12 19:00:29 +00003072#endif
drh08c6d442009-02-09 17:34:07 +00003073
drh8f941bc2009-01-14 23:03:40 +00003074#ifndef NDEBUG
3075 /* If we are doing a normal write to a database file (as opposed to
3076 ** doing a hot-journal rollback or a write to some file other than a
3077 ** normal database file) then record the fact that the database
3078 ** has changed. If the transaction counter is modified, record that
3079 ** fact too.
3080 */
dan08da86a2009-08-21 17:18:03 +00003081 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003082 pFile->dbUpdate = 1; /* The database has been modified */
3083 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003084 int rc;
drh8f941bc2009-01-14 23:03:40 +00003085 char oldCntr[4];
3086 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003087 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003088 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003089 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003090 pFile->transCntrChng = 1; /* The transaction counter has changed */
3091 }
3092 }
3093 }
3094#endif
3095
dan08da86a2009-08-21 17:18:03 +00003096 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003097 amt -= wrote;
3098 offset += wrote;
3099 pBuf = &((char*)pBuf)[wrote];
3100 }
3101 SimulateIOError(( wrote=(-1), amt=1 ));
3102 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003103
drh734c9862008-11-28 15:37:20 +00003104 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003105 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003106 /* lastErrno set by seekAndWrite */
3107 return SQLITE_IOERR_WRITE;
3108 }else{
dan08da86a2009-08-21 17:18:03 +00003109 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003110 return SQLITE_FULL;
3111 }
3112 }
dan6e09d692010-07-27 18:34:15 +00003113
drh734c9862008-11-28 15:37:20 +00003114 return SQLITE_OK;
3115}
3116
3117#ifdef SQLITE_TEST
3118/*
3119** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003120** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003121*/
3122int sqlite3_sync_count = 0;
3123int sqlite3_fullsync_count = 0;
3124#endif
3125
3126/*
drh89240432009-03-25 01:06:01 +00003127** We do not trust systems to provide a working fdatasync(). Some do.
3128** Others do no. To be safe, we will stick with the (slower) fsync().
3129** If you know that your system does support fdatasync() correctly,
3130** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003131*/
drh89240432009-03-25 01:06:01 +00003132#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003133# define fdatasync fsync
3134#endif
3135
3136/*
3137** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3138** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3139** only available on Mac OS X. But that could change.
3140*/
3141#ifdef F_FULLFSYNC
3142# define HAVE_FULLFSYNC 1
3143#else
3144# define HAVE_FULLFSYNC 0
3145#endif
3146
3147
3148/*
3149** The fsync() system call does not work as advertised on many
3150** unix systems. The following procedure is an attempt to make
3151** it work better.
3152**
3153** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3154** for testing when we want to run through the test suite quickly.
3155** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3156** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3157** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003158**
3159** SQLite sets the dataOnly flag if the size of the file is unchanged.
3160** The idea behind dataOnly is that it should only write the file content
3161** to disk, not the inode. We only set dataOnly if the file size is
3162** unchanged since the file size is part of the inode. However,
3163** Ted Ts'o tells us that fdatasync() will also write the inode if the
3164** file size has changed. The only real difference between fdatasync()
3165** and fsync(), Ted tells us, is that fdatasync() will not flush the
3166** inode if the mtime or owner or other inode attributes have changed.
3167** We only care about the file size, not the other file attributes, so
3168** as far as SQLite is concerned, an fdatasync() is always adequate.
3169** So, we always use fdatasync() if it is available, regardless of
3170** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003171*/
3172static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003173 int rc;
drh734c9862008-11-28 15:37:20 +00003174
3175 /* The following "ifdef/elif/else/" block has the same structure as
3176 ** the one below. It is replicated here solely to avoid cluttering
3177 ** up the real code with the UNUSED_PARAMETER() macros.
3178 */
3179#ifdef SQLITE_NO_SYNC
3180 UNUSED_PARAMETER(fd);
3181 UNUSED_PARAMETER(fullSync);
3182 UNUSED_PARAMETER(dataOnly);
3183#elif HAVE_FULLFSYNC
3184 UNUSED_PARAMETER(dataOnly);
3185#else
3186 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003187 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003188#endif
3189
3190 /* Record the number of times that we do a normal fsync() and
3191 ** FULLSYNC. This is used during testing to verify that this procedure
3192 ** gets called with the correct arguments.
3193 */
3194#ifdef SQLITE_TEST
3195 if( fullSync ) sqlite3_fullsync_count++;
3196 sqlite3_sync_count++;
3197#endif
3198
3199 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3200 ** no-op
3201 */
3202#ifdef SQLITE_NO_SYNC
3203 rc = SQLITE_OK;
3204#elif HAVE_FULLFSYNC
3205 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003206 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003207 }else{
3208 rc = 1;
3209 }
3210 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003211 ** It shouldn't be possible for fullfsync to fail on the local
3212 ** file system (on OSX), so failure indicates that FULLFSYNC
3213 ** isn't supported for this file system. So, attempt an fsync
3214 ** and (for now) ignore the overhead of a superfluous fcntl call.
3215 ** It'd be better to detect fullfsync support once and avoid
3216 ** the fcntl call every time sync is called.
3217 */
drh734c9862008-11-28 15:37:20 +00003218 if( rc ) rc = fsync(fd);
3219
drh7ed97b92010-01-20 13:07:21 +00003220#elif defined(__APPLE__)
3221 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3222 ** so currently we default to the macro that redefines fdatasync to fsync
3223 */
3224 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003225#else
drh0b647ff2009-03-21 14:41:04 +00003226 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003227#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003228 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003229 rc = fsync(fd);
3230 }
drh0b647ff2009-03-21 14:41:04 +00003231#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003232#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3233
3234 if( OS_VXWORKS && rc!= -1 ){
3235 rc = 0;
3236 }
chw97185482008-11-17 08:05:31 +00003237 return rc;
drhbfe66312006-10-03 17:40:40 +00003238}
3239
drh734c9862008-11-28 15:37:20 +00003240/*
3241** Make sure all writes to a particular file are committed to disk.
3242**
3243** If dataOnly==0 then both the file itself and its metadata (file
3244** size, access time, etc) are synced. If dataOnly!=0 then only the
3245** file data is synced.
3246**
3247** Under Unix, also make sure that the directory entry for the file
3248** has been created by fsync-ing the directory that contains the file.
3249** If we do not do this and we encounter a power failure, the directory
3250** entry for the journal might not exist after we reboot. The next
3251** SQLite to access the file will not know that the journal exists (because
3252** the directory entry for the journal was never created) and the transaction
3253** will not roll back - possibly leading to database corruption.
3254*/
3255static int unixSync(sqlite3_file *id, int flags){
3256 int rc;
3257 unixFile *pFile = (unixFile*)id;
3258
3259 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3260 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3261
3262 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3263 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3264 || (flags&0x0F)==SQLITE_SYNC_FULL
3265 );
3266
3267 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3268 ** line is to test that doing so does not cause any problems.
3269 */
3270 SimulateDiskfullError( return SQLITE_FULL );
3271
3272 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003273 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003274 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3275 SimulateIOError( rc=1 );
3276 if( rc ){
3277 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003278 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003279 }
3280 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003281 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3282 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003283#ifndef SQLITE_DISABLE_DIRSYNC
3284 /* The directory sync is only attempted if full_fsync is
3285 ** turned off or unavailable. If a full_fsync occurred above,
3286 ** then the directory sync is superfluous.
3287 */
3288 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3289 /*
3290 ** We have received multiple reports of fsync() returning
3291 ** errors when applied to directories on certain file systems.
3292 ** A failed directory sync is not a big deal. So it seems
3293 ** better to ignore the error. Ticket #1657
3294 */
3295 /* pFile->lastErrno = errno; */
3296 /* return SQLITE_IOERR; */
3297 }
3298#endif
drh0e9365c2011-03-02 02:08:13 +00003299 /* Only need to sync once, so close the directory when we are done */
3300 robust_close(pFile, pFile->dirfd, __LINE__);
3301 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003302 }
3303 return rc;
3304}
3305
3306/*
3307** Truncate an open file to a specified size
3308*/
3309static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003310 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003311 int rc;
dan6e09d692010-07-27 18:34:15 +00003312 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003313 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003314
3315 /* If the user has configured a chunk-size for this file, truncate the
3316 ** file so that it consists of an integer number of chunks (i.e. the
3317 ** actual file size after the operation may be larger than the requested
3318 ** size).
3319 */
3320 if( pFile->szChunk ){
3321 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3322 }
3323
drhff812312011-02-23 13:33:46 +00003324 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003325 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003326 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003327 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003328 }else{
drh3313b142009-11-06 04:13:18 +00003329#ifndef NDEBUG
3330 /* If we are doing a normal write to a database file (as opposed to
3331 ** doing a hot-journal rollback or a write to some file other than a
3332 ** normal database file) and we truncate the file to zero length,
3333 ** that effectively updates the change counter. This might happen
3334 ** when restoring a database using the backup API from a zero-length
3335 ** source.
3336 */
dan6e09d692010-07-27 18:34:15 +00003337 if( pFile->inNormalWrite && nByte==0 ){
3338 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003339 }
3340#endif
3341
drh734c9862008-11-28 15:37:20 +00003342 return SQLITE_OK;
3343 }
3344}
3345
3346/*
3347** Determine the current size of a file in bytes
3348*/
3349static int unixFileSize(sqlite3_file *id, i64 *pSize){
3350 int rc;
3351 struct stat buf;
3352 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003353 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003354 SimulateIOError( rc=1 );
3355 if( rc!=0 ){
3356 ((unixFile*)id)->lastErrno = errno;
3357 return SQLITE_IOERR_FSTAT;
3358 }
3359 *pSize = buf.st_size;
3360
drh8af6c222010-05-14 12:43:01 +00003361 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003362 ** writes a single byte into that file in order to work around a bug
3363 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3364 ** layers, we need to report this file size as zero even though it is
3365 ** really 1. Ticket #3260.
3366 */
3367 if( *pSize==1 ) *pSize = 0;
3368
3369
3370 return SQLITE_OK;
3371}
3372
drhd2cb50b2009-01-09 21:41:17 +00003373#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003374/*
3375** Handler for proxy-locking file-control verbs. Defined below in the
3376** proxying locking division.
3377*/
3378static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003379#endif
drh715ff302008-12-03 22:32:44 +00003380
dan502019c2010-07-28 14:26:17 +00003381/*
3382** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3383** file-control operation.
3384**
3385** If the user has configured a chunk-size for this file, it could be
3386** that the file needs to be extended at this point. Otherwise, the
3387** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3388*/
3389static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3390 if( pFile->szChunk ){
3391 i64 nSize; /* Required file size */
3392 struct stat buf; /* Used to hold return values of fstat() */
3393
drh99ab3b12011-03-02 15:09:07 +00003394 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003395
3396 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3397 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003398
dan502019c2010-07-28 14:26:17 +00003399#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003400 /* The code below is handling the return value of osFallocate()
3401 ** correctly. posix_fallocate() is defined to "returns zero on success,
3402 ** or an error number on failure". See the manpage for details. */
3403 int err;
drhff812312011-02-23 13:33:46 +00003404 do{
dan661d71a2011-03-30 19:08:03 +00003405 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3406 }while( err==EINTR );
3407 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003408#else
3409 /* If the OS does not have posix_fallocate(), fake it. First use
3410 ** ftruncate() to set the file size, then write a single byte to
3411 ** the last byte in each block within the extended region. This
3412 ** is the same technique used by glibc to implement posix_fallocate()
3413 ** on systems that do not have a real fallocate() system call.
3414 */
3415 int nBlk = buf.st_blksize; /* File-system block size */
3416 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003417
drhff812312011-02-23 13:33:46 +00003418 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003419 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003420 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003421 }
3422 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003423 while( iWrite<nSize ){
3424 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3425 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003426 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003427 }
dan502019c2010-07-28 14:26:17 +00003428#endif
3429 }
3430 }
3431
3432 return SQLITE_OK;
3433}
danielk1977ad94b582007-08-20 06:44:22 +00003434
danielk1977e3026632004-06-22 11:29:02 +00003435/*
drh9e33c2c2007-08-31 18:34:59 +00003436** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003437*/
drhcc6bb3e2007-08-31 16:11:35 +00003438static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003439 switch( op ){
3440 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003441 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003442 return SQLITE_OK;
3443 }
drh7708e972008-11-29 00:56:52 +00003444 case SQLITE_LAST_ERRNO: {
3445 *(int*)pArg = ((unixFile*)id)->lastErrno;
3446 return SQLITE_OK;
3447 }
dan6e09d692010-07-27 18:34:15 +00003448 case SQLITE_FCNTL_CHUNK_SIZE: {
3449 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003450 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003451 }
drh9ff27ec2010-05-19 19:26:05 +00003452 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003453 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003454 }
drh8f941bc2009-01-14 23:03:40 +00003455#ifndef NDEBUG
3456 /* The pager calls this method to signal that it has done
3457 ** a rollback and that the database is therefore unchanged and
3458 ** it hence it is OK for the transaction change counter to be
3459 ** unchanged.
3460 */
3461 case SQLITE_FCNTL_DB_UNCHANGED: {
3462 ((unixFile*)id)->dbUpdate = 0;
3463 return SQLITE_OK;
3464 }
3465#endif
drhd2cb50b2009-01-09 21:41:17 +00003466#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003467 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003468 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003469 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003470 }
drhd2cb50b2009-01-09 21:41:17 +00003471#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003472 case SQLITE_FCNTL_SYNC_OMITTED: {
3473 return SQLITE_OK; /* A no-op */
3474 }
drh9e33c2c2007-08-31 18:34:59 +00003475 }
drh0b52b7d2011-01-26 19:46:22 +00003476 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003477}
3478
3479/*
danielk1977a3d4c882007-03-23 10:08:38 +00003480** Return the sector size in bytes of the underlying block device for
3481** the specified file. This is almost always 512 bytes, but may be
3482** larger for some devices.
3483**
3484** SQLite code assumes this function cannot fail. It also assumes that
3485** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003486** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003487** same for both.
3488*/
danielk1977397d65f2008-11-19 11:35:39 +00003489static int unixSectorSize(sqlite3_file *NotUsed){
3490 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003491 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003492}
3493
danielk197790949c22007-08-17 16:50:38 +00003494/*
danielk1977397d65f2008-11-19 11:35:39 +00003495** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003496*/
danielk1977397d65f2008-11-19 11:35:39 +00003497static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3498 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003499 return 0;
3500}
3501
drhd9e5c4f2010-05-12 18:01:39 +00003502#ifndef SQLITE_OMIT_WAL
3503
3504
3505/*
drhd91c68f2010-05-14 14:52:25 +00003506** Object used to represent an shared memory buffer.
3507**
3508** When multiple threads all reference the same wal-index, each thread
3509** has its own unixShm object, but they all point to a single instance
3510** of this unixShmNode object. In other words, each wal-index is opened
3511** only once per process.
3512**
3513** Each unixShmNode object is connected to a single unixInodeInfo object.
3514** We could coalesce this object into unixInodeInfo, but that would mean
3515** every open file that does not use shared memory (in other words, most
3516** open files) would have to carry around this extra information. So
3517** the unixInodeInfo object contains a pointer to this unixShmNode object
3518** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003519**
3520** unixMutexHeld() must be true when creating or destroying
3521** this object or while reading or writing the following fields:
3522**
3523** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003524**
3525** The following fields are read-only after the object is created:
3526**
3527** fid
3528** zFilename
3529**
drhd91c68f2010-05-14 14:52:25 +00003530** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003531** unixMutexHeld() is true when reading or writing any other field
3532** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003533*/
drhd91c68f2010-05-14 14:52:25 +00003534struct unixShmNode {
3535 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003536 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003537 char *zFilename; /* Name of the mmapped file */
3538 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003539 int szRegion; /* Size of shared-memory regions */
3540 int nRegion; /* Size of array apRegion */
3541 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003542 int nRef; /* Number of unixShm objects pointing to this */
3543 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003544#ifdef SQLITE_DEBUG
3545 u8 exclMask; /* Mask of exclusive locks held */
3546 u8 sharedMask; /* Mask of shared locks held */
3547 u8 nextShmId; /* Next available unixShm.id value */
3548#endif
3549};
3550
3551/*
drhd9e5c4f2010-05-12 18:01:39 +00003552** Structure used internally by this VFS to record the state of an
3553** open shared memory connection.
3554**
drhd91c68f2010-05-14 14:52:25 +00003555** The following fields are initialized when this object is created and
3556** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003557**
drhd91c68f2010-05-14 14:52:25 +00003558** unixShm.pFile
3559** unixShm.id
3560**
3561** All other fields are read/write. The unixShm.pFile->mutex must be held
3562** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003563*/
3564struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003565 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3566 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003567 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003568 u16 sharedMask; /* Mask of shared locks held */
3569 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003570#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003571 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003572#endif
3573};
3574
3575/*
drhd9e5c4f2010-05-12 18:01:39 +00003576** Constants used for locking
3577*/
drhbd9676c2010-06-23 17:58:38 +00003578#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003579#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003580
drhd9e5c4f2010-05-12 18:01:39 +00003581/*
drh73b64e42010-05-30 19:55:15 +00003582** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003583**
3584** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3585** otherwise.
3586*/
3587static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003588 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3589 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003590 int ofst, /* First byte of the locking range */
3591 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003592){
3593 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003594 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003595
drhd91c68f2010-05-14 14:52:25 +00003596 /* Access to the unixShmNode object is serialized by the caller */
3597 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003598
drh73b64e42010-05-30 19:55:15 +00003599 /* Shared locks never span more than one byte */
3600 assert( n==1 || lockType!=F_RDLCK );
3601
3602 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003603 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003604
drh3cb93392011-03-12 18:10:44 +00003605 if( pShmNode->h>=0 ){
3606 /* Initialize the locking parameters */
3607 memset(&f, 0, sizeof(f));
3608 f.l_type = lockType;
3609 f.l_whence = SEEK_SET;
3610 f.l_start = ofst;
3611 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003612
drh3cb93392011-03-12 18:10:44 +00003613 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3614 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3615 }
drhd9e5c4f2010-05-12 18:01:39 +00003616
3617 /* Update the global lock state and do debug tracing */
3618#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003619 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003620 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003621 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003622 if( rc==SQLITE_OK ){
3623 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003624 OSTRACE(("unlock %d ok", ofst));
3625 pShmNode->exclMask &= ~mask;
3626 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003627 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003628 OSTRACE(("read-lock %d ok", ofst));
3629 pShmNode->exclMask &= ~mask;
3630 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003631 }else{
3632 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003633 OSTRACE(("write-lock %d ok", ofst));
3634 pShmNode->exclMask |= mask;
3635 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003636 }
3637 }else{
3638 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003639 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003640 }else if( lockType==F_RDLCK ){
3641 OSTRACE(("read-lock failed"));
3642 }else{
3643 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003644 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003645 }
3646 }
drh20e1f082010-05-31 16:10:12 +00003647 OSTRACE((" - afterwards %03x,%03x\n",
3648 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003649 }
drhd9e5c4f2010-05-12 18:01:39 +00003650#endif
3651
3652 return rc;
3653}
3654
drhd9e5c4f2010-05-12 18:01:39 +00003655
3656/*
drhd91c68f2010-05-14 14:52:25 +00003657** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003658**
3659** This is not a VFS shared-memory method; it is a utility function called
3660** by VFS shared-memory methods.
3661*/
drhd91c68f2010-05-14 14:52:25 +00003662static void unixShmPurge(unixFile *pFd){
3663 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003664 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003665 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003666 int i;
drhd91c68f2010-05-14 14:52:25 +00003667 assert( p->pInode==pFd->pInode );
3668 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003669 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003670 if( p->h>=0 ){
3671 munmap(p->apRegion[i], p->szRegion);
3672 }else{
3673 sqlite3_free(p->apRegion[i]);
3674 }
dan13a3cb82010-06-11 19:04:21 +00003675 }
dan18801912010-06-14 14:07:50 +00003676 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003677 if( p->h>=0 ){
3678 robust_close(pFd, p->h, __LINE__);
3679 p->h = -1;
3680 }
drhd91c68f2010-05-14 14:52:25 +00003681 p->pInode->pShmNode = 0;
3682 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003683 }
3684}
3685
3686/*
danda9fe0c2010-07-13 18:44:03 +00003687** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003688** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003689**
drh7234c6d2010-06-19 15:10:09 +00003690** The file used to implement shared-memory is in the same directory
3691** as the open database file and has the same name as the open database
3692** file with the "-shm" suffix added. For example, if the database file
3693** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003694** for shared memory will be called "/home/user1/config.db-shm".
3695**
3696** Another approach to is to use files in /dev/shm or /dev/tmp or an
3697** some other tmpfs mount. But if a file in a different directory
3698** from the database file is used, then differing access permissions
3699** or a chroot() might cause two different processes on the same
3700** database to end up using different files for shared memory -
3701** meaning that their memory would not really be shared - resulting
3702** in database corruption. Nevertheless, this tmpfs file usage
3703** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3704** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3705** option results in an incompatible build of SQLite; builds of SQLite
3706** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3707** same database file at the same time, database corruption will likely
3708** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3709** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003710**
3711** When opening a new shared-memory file, if no other instances of that
3712** file are currently open, in this process or in other processes, then
3713** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003714**
3715** If the original database file (pDbFd) is using the "unix-excl" VFS
3716** that means that an exclusive lock is held on the database file and
3717** that no other processes are able to read or write the database. In
3718** that case, we do not really need shared memory. No shared memory
3719** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003720*/
danda9fe0c2010-07-13 18:44:03 +00003721static int unixOpenSharedMemory(unixFile *pDbFd){
3722 struct unixShm *p = 0; /* The connection to be opened */
3723 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3724 int rc; /* Result code */
3725 unixInodeInfo *pInode; /* The inode of fd */
3726 char *zShmFilename; /* Name of the file used for SHM */
3727 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003728
danda9fe0c2010-07-13 18:44:03 +00003729 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003730 p = sqlite3_malloc( sizeof(*p) );
3731 if( p==0 ) return SQLITE_NOMEM;
3732 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003733 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003734
danda9fe0c2010-07-13 18:44:03 +00003735 /* Check to see if a unixShmNode object already exists. Reuse an existing
3736 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003737 */
3738 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003739 pInode = pDbFd->pInode;
3740 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003741 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003742 struct stat sStat; /* fstat() info for database file */
3743
3744 /* Call fstat() to figure out the permissions on the database file. If
3745 ** a new *-shm file is created, an attempt will be made to create it
3746 ** with the same permissions. The actual permissions the file is created
3747 ** with are subject to the current umask setting.
3748 */
drh3cb93392011-03-12 18:10:44 +00003749 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003750 rc = SQLITE_IOERR_FSTAT;
3751 goto shm_open_err;
3752 }
3753
drha4ced192010-07-15 18:32:40 +00003754#ifdef SQLITE_SHM_DIRECTORY
3755 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3756#else
drh7234c6d2010-06-19 15:10:09 +00003757 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003758#endif
drh7234c6d2010-06-19 15:10:09 +00003759 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003760 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003761 rc = SQLITE_NOMEM;
3762 goto shm_open_err;
3763 }
drhd91c68f2010-05-14 14:52:25 +00003764 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003765 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003766#ifdef SQLITE_SHM_DIRECTORY
3767 sqlite3_snprintf(nShmFilename, zShmFilename,
3768 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3769 (u32)sStat.st_ino, (u32)sStat.st_dev);
3770#else
drh7234c6d2010-06-19 15:10:09 +00003771 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003772#endif
drhd91c68f2010-05-14 14:52:25 +00003773 pShmNode->h = -1;
3774 pDbFd->pInode->pShmNode = pShmNode;
3775 pShmNode->pInode = pDbFd->pInode;
3776 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3777 if( pShmNode->mutex==0 ){
3778 rc = SQLITE_NOMEM;
3779 goto shm_open_err;
3780 }
drhd9e5c4f2010-05-12 18:01:39 +00003781
drh3cb93392011-03-12 18:10:44 +00003782 if( pInode->bProcessLock==0 ){
3783 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3784 (sStat.st_mode & 0777));
3785 if( pShmNode->h<0 ){
3786 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3787 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003788 }
drh3cb93392011-03-12 18:10:44 +00003789
3790 /* Check to see if another process is holding the dead-man switch.
3791 ** If not, truncate the file to zero length.
3792 */
3793 rc = SQLITE_OK;
3794 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3795 if( robust_ftruncate(pShmNode->h, 0) ){
3796 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
3797 }
3798 }
3799 if( rc==SQLITE_OK ){
3800 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3801 }
3802 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003803 }
drhd9e5c4f2010-05-12 18:01:39 +00003804 }
3805
drhd91c68f2010-05-14 14:52:25 +00003806 /* Make the new connection a child of the unixShmNode */
3807 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003808#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003809 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003810#endif
drhd91c68f2010-05-14 14:52:25 +00003811 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003812 pDbFd->pShm = p;
3813 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003814
3815 /* The reference count on pShmNode has already been incremented under
3816 ** the cover of the unixEnterMutex() mutex and the pointer from the
3817 ** new (struct unixShm) object to the pShmNode has been set. All that is
3818 ** left to do is to link the new object into the linked list starting
3819 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3820 ** mutex.
3821 */
3822 sqlite3_mutex_enter(pShmNode->mutex);
3823 p->pNext = pShmNode->pFirst;
3824 pShmNode->pFirst = p;
3825 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003826 return SQLITE_OK;
3827
3828 /* Jump here on any error */
3829shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003830 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003831 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003832 unixLeaveMutex();
3833 return rc;
3834}
3835
3836/*
danda9fe0c2010-07-13 18:44:03 +00003837** This function is called to obtain a pointer to region iRegion of the
3838** shared-memory associated with the database file fd. Shared-memory regions
3839** are numbered starting from zero. Each shared-memory region is szRegion
3840** bytes in size.
3841**
3842** If an error occurs, an error code is returned and *pp is set to NULL.
3843**
3844** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3845** region has not been allocated (by any client, including one running in a
3846** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3847** bExtend is non-zero and the requested shared-memory region has not yet
3848** been allocated, it is allocated by this function.
3849**
3850** If the shared-memory region has already been allocated or is allocated by
3851** this call as described above, then it is mapped into this processes
3852** address space (if it is not already), *pp is set to point to the mapped
3853** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003854*/
danda9fe0c2010-07-13 18:44:03 +00003855static int unixShmMap(
3856 sqlite3_file *fd, /* Handle open on database file */
3857 int iRegion, /* Region to retrieve */
3858 int szRegion, /* Size of regions */
3859 int bExtend, /* True to extend file if necessary */
3860 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003861){
danda9fe0c2010-07-13 18:44:03 +00003862 unixFile *pDbFd = (unixFile*)fd;
3863 unixShm *p;
3864 unixShmNode *pShmNode;
3865 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003866
danda9fe0c2010-07-13 18:44:03 +00003867 /* If the shared-memory file has not yet been opened, open it now. */
3868 if( pDbFd->pShm==0 ){
3869 rc = unixOpenSharedMemory(pDbFd);
3870 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003871 }
drhd9e5c4f2010-05-12 18:01:39 +00003872
danda9fe0c2010-07-13 18:44:03 +00003873 p = pDbFd->pShm;
3874 pShmNode = p->pShmNode;
3875 sqlite3_mutex_enter(pShmNode->mutex);
3876 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003877 assert( pShmNode->pInode==pDbFd->pInode );
3878 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3879 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003880
3881 if( pShmNode->nRegion<=iRegion ){
3882 char **apNew; /* New apRegion[] array */
3883 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3884 struct stat sStat; /* Used by fstat() */
3885
3886 pShmNode->szRegion = szRegion;
3887
drh3cb93392011-03-12 18:10:44 +00003888 if( pShmNode->h>=0 ){
3889 /* The requested region is not mapped into this processes address space.
3890 ** Check to see if it has been allocated (i.e. if the wal-index file is
3891 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003892 */
drh3cb93392011-03-12 18:10:44 +00003893 if( osFstat(pShmNode->h, &sStat) ){
3894 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003895 goto shmpage_out;
3896 }
drh3cb93392011-03-12 18:10:44 +00003897
3898 if( sStat.st_size<nByte ){
3899 /* The requested memory region does not exist. If bExtend is set to
3900 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3901 **
3902 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3903 ** the requested memory region.
3904 */
3905 if( !bExtend ) goto shmpage_out;
3906 if( robust_ftruncate(pShmNode->h, nByte) ){
3907 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3908 pShmNode->zFilename);
3909 goto shmpage_out;
3910 }
3911 }
danda9fe0c2010-07-13 18:44:03 +00003912 }
3913
3914 /* Map the requested memory region into this processes address space. */
3915 apNew = (char **)sqlite3_realloc(
3916 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3917 );
3918 if( !apNew ){
3919 rc = SQLITE_IOERR_NOMEM;
3920 goto shmpage_out;
3921 }
3922 pShmNode->apRegion = apNew;
3923 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003924 void *pMem;
3925 if( pShmNode->h>=0 ){
3926 pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
3927 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3928 );
3929 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00003930 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00003931 goto shmpage_out;
3932 }
3933 }else{
3934 pMem = sqlite3_malloc(szRegion);
3935 if( pMem==0 ){
3936 rc = SQLITE_NOMEM;
3937 goto shmpage_out;
3938 }
3939 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00003940 }
3941 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3942 pShmNode->nRegion++;
3943 }
3944 }
3945
3946shmpage_out:
3947 if( pShmNode->nRegion>iRegion ){
3948 *pp = pShmNode->apRegion[iRegion];
3949 }else{
3950 *pp = 0;
3951 }
3952 sqlite3_mutex_leave(pShmNode->mutex);
3953 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003954}
3955
3956/*
drhd9e5c4f2010-05-12 18:01:39 +00003957** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003958**
3959** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3960** different here than in posix. In xShmLock(), one can go from unlocked
3961** to shared and back or from unlocked to exclusive and back. But one may
3962** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003963*/
3964static int unixShmLock(
3965 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003966 int ofst, /* First lock to acquire or release */
3967 int n, /* Number of locks to acquire or release */
3968 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003969){
drh73b64e42010-05-30 19:55:15 +00003970 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3971 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3972 unixShm *pX; /* For looping over all siblings */
3973 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3974 int rc = SQLITE_OK; /* Result code */
3975 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003976
drhd91c68f2010-05-14 14:52:25 +00003977 assert( pShmNode==pDbFd->pInode->pShmNode );
3978 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003979 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003980 assert( n>=1 );
3981 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3982 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3983 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3984 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3985 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00003986 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3987 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00003988
drhc99597c2010-05-31 01:41:15 +00003989 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00003990 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00003991 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00003992 if( flags & SQLITE_SHM_UNLOCK ){
3993 u16 allMask = 0; /* Mask of locks held by siblings */
3994
3995 /* See if any siblings hold this same lock */
3996 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3997 if( pX==p ) continue;
3998 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3999 allMask |= pX->sharedMask;
4000 }
4001
4002 /* Unlock the system-level locks */
4003 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004004 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004005 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004006 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004007 }
drh73b64e42010-05-30 19:55:15 +00004008
4009 /* Undo the local locks */
4010 if( rc==SQLITE_OK ){
4011 p->exclMask &= ~mask;
4012 p->sharedMask &= ~mask;
4013 }
4014 }else if( flags & SQLITE_SHM_SHARED ){
4015 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4016
4017 /* Find out which shared locks are already held by sibling connections.
4018 ** If any sibling already holds an exclusive lock, go ahead and return
4019 ** SQLITE_BUSY.
4020 */
4021 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004022 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004023 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004024 break;
4025 }
4026 allShared |= pX->sharedMask;
4027 }
4028
4029 /* Get shared locks at the system level, if necessary */
4030 if( rc==SQLITE_OK ){
4031 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004032 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004033 }else{
drh73b64e42010-05-30 19:55:15 +00004034 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004035 }
drhd9e5c4f2010-05-12 18:01:39 +00004036 }
drh73b64e42010-05-30 19:55:15 +00004037
4038 /* Get the local shared locks */
4039 if( rc==SQLITE_OK ){
4040 p->sharedMask |= mask;
4041 }
4042 }else{
4043 /* Make sure no sibling connections hold locks that will block this
4044 ** lock. If any do, return SQLITE_BUSY right away.
4045 */
4046 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004047 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4048 rc = SQLITE_BUSY;
4049 break;
4050 }
4051 }
4052
4053 /* Get the exclusive locks at the system level. Then if successful
4054 ** also mark the local connection as being locked.
4055 */
4056 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004057 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004058 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004059 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004060 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004061 }
drhd9e5c4f2010-05-12 18:01:39 +00004062 }
4063 }
drhd91c68f2010-05-14 14:52:25 +00004064 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004065 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4066 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004067 return rc;
4068}
4069
drh286a2882010-05-20 23:51:06 +00004070/*
4071** Implement a memory barrier or memory fence on shared memory.
4072**
4073** All loads and stores begun before the barrier must complete before
4074** any load or store begun after the barrier.
4075*/
4076static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004077 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004078){
drhff828942010-06-26 21:34:06 +00004079 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004080 unixEnterMutex();
4081 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004082}
4083
dan18801912010-06-14 14:07:50 +00004084/*
danda9fe0c2010-07-13 18:44:03 +00004085** Close a connection to shared-memory. Delete the underlying
4086** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004087**
4088** If there is no shared memory associated with the connection then this
4089** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004090*/
danda9fe0c2010-07-13 18:44:03 +00004091static int unixShmUnmap(
4092 sqlite3_file *fd, /* The underlying database file */
4093 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004094){
danda9fe0c2010-07-13 18:44:03 +00004095 unixShm *p; /* The connection to be closed */
4096 unixShmNode *pShmNode; /* The underlying shared-memory file */
4097 unixShm **pp; /* For looping over sibling connections */
4098 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004099
danda9fe0c2010-07-13 18:44:03 +00004100 pDbFd = (unixFile*)fd;
4101 p = pDbFd->pShm;
4102 if( p==0 ) return SQLITE_OK;
4103 pShmNode = p->pShmNode;
4104
4105 assert( pShmNode==pDbFd->pInode->pShmNode );
4106 assert( pShmNode->pInode==pDbFd->pInode );
4107
4108 /* Remove connection p from the set of connections associated
4109 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004110 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004111 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4112 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004113
danda9fe0c2010-07-13 18:44:03 +00004114 /* Free the connection p */
4115 sqlite3_free(p);
4116 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004117 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004118
4119 /* If pShmNode->nRef has reached 0, then close the underlying
4120 ** shared-memory file, too */
4121 unixEnterMutex();
4122 assert( pShmNode->nRef>0 );
4123 pShmNode->nRef--;
4124 if( pShmNode->nRef==0 ){
drh3cb93392011-03-12 18:10:44 +00004125 if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004126 unixShmPurge(pDbFd);
4127 }
4128 unixLeaveMutex();
4129
4130 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004131}
drh286a2882010-05-20 23:51:06 +00004132
danda9fe0c2010-07-13 18:44:03 +00004133
drhd9e5c4f2010-05-12 18:01:39 +00004134#else
drh6b017cc2010-06-14 18:01:46 +00004135# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004136# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004137# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004138# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004139#endif /* #ifndef SQLITE_OMIT_WAL */
4140
drh734c9862008-11-28 15:37:20 +00004141/*
4142** Here ends the implementation of all sqlite3_file methods.
4143**
4144********************** End sqlite3_file Methods *******************************
4145******************************************************************************/
4146
4147/*
drh6b9d6dd2008-12-03 19:34:47 +00004148** This division contains definitions of sqlite3_io_methods objects that
4149** implement various file locking strategies. It also contains definitions
4150** of "finder" functions. A finder-function is used to locate the appropriate
4151** sqlite3_io_methods object for a particular database file. The pAppData
4152** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4153** the correct finder-function for that VFS.
4154**
4155** Most finder functions return a pointer to a fixed sqlite3_io_methods
4156** object. The only interesting finder-function is autolockIoFinder, which
4157** looks at the filesystem type and tries to guess the best locking
4158** strategy from that.
4159**
drh1875f7a2008-12-08 18:19:17 +00004160** For finder-funtion F, two objects are created:
4161**
4162** (1) The real finder-function named "FImpt()".
4163**
dane946c392009-08-22 11:39:46 +00004164** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004165**
4166**
4167** A pointer to the F pointer is used as the pAppData value for VFS
4168** objects. We have to do this instead of letting pAppData point
4169** directly at the finder-function since C90 rules prevent a void*
4170** from be cast into a function pointer.
4171**
drh6b9d6dd2008-12-03 19:34:47 +00004172**
drh7708e972008-11-29 00:56:52 +00004173** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004174**
drh7708e972008-11-29 00:56:52 +00004175** * A constant sqlite3_io_methods object call METHOD that has locking
4176** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4177**
4178** * An I/O method finder function called FINDER that returns a pointer
4179** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004180*/
drhd9e5c4f2010-05-12 18:01:39 +00004181#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004182static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004183 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004184 CLOSE, /* xClose */ \
4185 unixRead, /* xRead */ \
4186 unixWrite, /* xWrite */ \
4187 unixTruncate, /* xTruncate */ \
4188 unixSync, /* xSync */ \
4189 unixFileSize, /* xFileSize */ \
4190 LOCK, /* xLock */ \
4191 UNLOCK, /* xUnlock */ \
4192 CKLOCK, /* xCheckReservedLock */ \
4193 unixFileControl, /* xFileControl */ \
4194 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004195 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004196 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004197 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004198 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004199 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004200}; \
drh0c2694b2009-09-03 16:23:44 +00004201static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4202 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004203 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004204} \
drh0c2694b2009-09-03 16:23:44 +00004205static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004206 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004207
4208/*
4209** Here are all of the sqlite3_io_methods objects for each of the
4210** locking strategies. Functions that return pointers to these methods
4211** are also created.
4212*/
4213IOMETHODS(
4214 posixIoFinder, /* Finder function name */
4215 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004216 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004217 unixClose, /* xClose method */
4218 unixLock, /* xLock method */
4219 unixUnlock, /* xUnlock method */
4220 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004221)
drh7708e972008-11-29 00:56:52 +00004222IOMETHODS(
4223 nolockIoFinder, /* Finder function name */
4224 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004225 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004226 nolockClose, /* xClose method */
4227 nolockLock, /* xLock method */
4228 nolockUnlock, /* xUnlock method */
4229 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004230)
drh7708e972008-11-29 00:56:52 +00004231IOMETHODS(
4232 dotlockIoFinder, /* Finder function name */
4233 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004234 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004235 dotlockClose, /* xClose method */
4236 dotlockLock, /* xLock method */
4237 dotlockUnlock, /* xUnlock method */
4238 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004239)
drh7708e972008-11-29 00:56:52 +00004240
chw78a13182009-04-07 05:35:03 +00004241#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004242IOMETHODS(
4243 flockIoFinder, /* Finder function name */
4244 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004245 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004246 flockClose, /* xClose method */
4247 flockLock, /* xLock method */
4248 flockUnlock, /* xUnlock method */
4249 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004250)
drh7708e972008-11-29 00:56:52 +00004251#endif
4252
drh6c7d5c52008-11-21 20:32:33 +00004253#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004254IOMETHODS(
4255 semIoFinder, /* Finder function name */
4256 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004257 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004258 semClose, /* xClose method */
4259 semLock, /* xLock method */
4260 semUnlock, /* xUnlock method */
4261 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004262)
aswiftaebf4132008-11-21 00:10:35 +00004263#endif
drh7708e972008-11-29 00:56:52 +00004264
drhd2cb50b2009-01-09 21:41:17 +00004265#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004266IOMETHODS(
4267 afpIoFinder, /* Finder function name */
4268 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004269 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004270 afpClose, /* xClose method */
4271 afpLock, /* xLock method */
4272 afpUnlock, /* xUnlock method */
4273 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004274)
drh715ff302008-12-03 22:32:44 +00004275#endif
4276
4277/*
4278** The proxy locking method is a "super-method" in the sense that it
4279** opens secondary file descriptors for the conch and lock files and
4280** it uses proxy, dot-file, AFP, and flock() locking methods on those
4281** secondary files. For this reason, the division that implements
4282** proxy locking is located much further down in the file. But we need
4283** to go ahead and define the sqlite3_io_methods and finder function
4284** for proxy locking here. So we forward declare the I/O methods.
4285*/
drhd2cb50b2009-01-09 21:41:17 +00004286#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004287static int proxyClose(sqlite3_file*);
4288static int proxyLock(sqlite3_file*, int);
4289static int proxyUnlock(sqlite3_file*, int);
4290static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004291IOMETHODS(
4292 proxyIoFinder, /* Finder function name */
4293 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004294 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004295 proxyClose, /* xClose method */
4296 proxyLock, /* xLock method */
4297 proxyUnlock, /* xUnlock method */
4298 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004299)
aswiftaebf4132008-11-21 00:10:35 +00004300#endif
drh7708e972008-11-29 00:56:52 +00004301
drh7ed97b92010-01-20 13:07:21 +00004302/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4303#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4304IOMETHODS(
4305 nfsIoFinder, /* Finder function name */
4306 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004307 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004308 unixClose, /* xClose method */
4309 unixLock, /* xLock method */
4310 nfsUnlock, /* xUnlock method */
4311 unixCheckReservedLock /* xCheckReservedLock method */
4312)
4313#endif
drh7708e972008-11-29 00:56:52 +00004314
drhd2cb50b2009-01-09 21:41:17 +00004315#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004316/*
drh6b9d6dd2008-12-03 19:34:47 +00004317** This "finder" function attempts to determine the best locking strategy
4318** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004319** object that implements that strategy.
4320**
4321** This is for MacOSX only.
4322*/
drh1875f7a2008-12-08 18:19:17 +00004323static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004324 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004325 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004326){
4327 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004328 const char *zFilesystem; /* Filesystem type name */
4329 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004330 } aMap[] = {
4331 { "hfs", &posixIoMethods },
4332 { "ufs", &posixIoMethods },
4333 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004334 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004335 { "webdav", &nolockIoMethods },
4336 { 0, 0 }
4337 };
4338 int i;
4339 struct statfs fsInfo;
4340 struct flock lockInfo;
4341
4342 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004343 /* If filePath==NULL that means we are dealing with a transient file
4344 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004345 return &nolockIoMethods;
4346 }
4347 if( statfs(filePath, &fsInfo) != -1 ){
4348 if( fsInfo.f_flags & MNT_RDONLY ){
4349 return &nolockIoMethods;
4350 }
4351 for(i=0; aMap[i].zFilesystem; i++){
4352 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4353 return aMap[i].pMethods;
4354 }
4355 }
4356 }
4357
4358 /* Default case. Handles, amongst others, "nfs".
4359 ** Test byte-range lock using fcntl(). If the call succeeds,
4360 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004361 */
drh7708e972008-11-29 00:56:52 +00004362 lockInfo.l_len = 1;
4363 lockInfo.l_start = 0;
4364 lockInfo.l_whence = SEEK_SET;
4365 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004366 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004367 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4368 return &nfsIoMethods;
4369 } else {
4370 return &posixIoMethods;
4371 }
drh7708e972008-11-29 00:56:52 +00004372 }else{
4373 return &dotlockIoMethods;
4374 }
4375}
drh0c2694b2009-09-03 16:23:44 +00004376static const sqlite3_io_methods
4377 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004378
drhd2cb50b2009-01-09 21:41:17 +00004379#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004380
chw78a13182009-04-07 05:35:03 +00004381#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4382/*
4383** This "finder" function attempts to determine the best locking strategy
4384** for the database file "filePath". It then returns the sqlite3_io_methods
4385** object that implements that strategy.
4386**
4387** This is for VXWorks only.
4388*/
4389static const sqlite3_io_methods *autolockIoFinderImpl(
4390 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004391 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004392){
4393 struct flock lockInfo;
4394
4395 if( !filePath ){
4396 /* If filePath==NULL that means we are dealing with a transient file
4397 ** that does not need to be locked. */
4398 return &nolockIoMethods;
4399 }
4400
4401 /* Test if fcntl() is supported and use POSIX style locks.
4402 ** Otherwise fall back to the named semaphore method.
4403 */
4404 lockInfo.l_len = 1;
4405 lockInfo.l_start = 0;
4406 lockInfo.l_whence = SEEK_SET;
4407 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004408 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004409 return &posixIoMethods;
4410 }else{
4411 return &semIoMethods;
4412 }
4413}
drh0c2694b2009-09-03 16:23:44 +00004414static const sqlite3_io_methods
4415 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004416
4417#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4418
drh7708e972008-11-29 00:56:52 +00004419/*
4420** An abstract type for a pointer to a IO method finder function:
4421*/
drh0c2694b2009-09-03 16:23:44 +00004422typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004423
aswiftaebf4132008-11-21 00:10:35 +00004424
drh734c9862008-11-28 15:37:20 +00004425/****************************************************************************
4426**************************** sqlite3_vfs methods ****************************
4427**
4428** This division contains the implementation of methods on the
4429** sqlite3_vfs object.
4430*/
4431
danielk1977a3d4c882007-03-23 10:08:38 +00004432/*
danielk1977e339d652008-06-28 11:23:00 +00004433** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004434*/
4435static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004436 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004437 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004438 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004439 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004440 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004441 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004442 int isDelete, /* Delete on close if true */
4443 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004444){
drh7708e972008-11-29 00:56:52 +00004445 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004446 unixFile *pNew = (unixFile *)pId;
4447 int rc = SQLITE_OK;
4448
drh8af6c222010-05-14 12:43:01 +00004449 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004450
dane946c392009-08-22 11:39:46 +00004451 /* Parameter isDelete is only used on vxworks. Express this explicitly
4452 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004453 */
drh7708e972008-11-29 00:56:52 +00004454 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004455
dan00157392010-10-05 11:33:15 +00004456 /* Usually the path zFilename should not be a relative pathname. The
4457 ** exception is when opening the proxy "conch" file in builds that
4458 ** include the special Apple locking styles.
4459 */
dan00157392010-10-05 11:33:15 +00004460#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004461 assert( zFilename==0 || zFilename[0]=='/'
4462 || pVfs->pAppData==(void*)&autolockIoFinder );
4463#else
4464 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004465#endif
dan00157392010-10-05 11:33:15 +00004466
drh308c2a52010-05-14 11:30:18 +00004467 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004468 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004469 pNew->dirfd = dirfd;
drhd9e5c4f2010-05-12 18:01:39 +00004470 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004471 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4472 pNew->ctrlFlags = UNIXFILE_EXCL;
4473 }else{
4474 pNew->ctrlFlags = 0;
4475 }
drh77197112011-03-15 19:08:48 +00004476 if( isReadOnly ){
4477 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4478 }
drh339eb0b2008-03-07 15:34:11 +00004479
drh6c7d5c52008-11-21 20:32:33 +00004480#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004481 pNew->pId = vxworksFindFileId(zFilename);
4482 if( pNew->pId==0 ){
4483 noLock = 1;
4484 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004485 }
4486#endif
4487
drhda0e7682008-07-30 15:27:54 +00004488 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004489 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004490 }else{
drh0c2694b2009-09-03 16:23:44 +00004491 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004492#if SQLITE_ENABLE_LOCKING_STYLE
4493 /* Cache zFilename in the locking context (AFP and dotlock override) for
4494 ** proxyLock activation is possible (remote proxy is based on db name)
4495 ** zFilename remains valid until file is closed, to support */
4496 pNew->lockingContext = (void*)zFilename;
4497#endif
drhda0e7682008-07-30 15:27:54 +00004498 }
danielk1977e339d652008-06-28 11:23:00 +00004499
drh7ed97b92010-01-20 13:07:21 +00004500 if( pLockingStyle == &posixIoMethods
4501#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4502 || pLockingStyle == &nfsIoMethods
4503#endif
4504 ){
drh7708e972008-11-29 00:56:52 +00004505 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004506 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004507 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004508 /* If an error occured in findInodeInfo(), close the file descriptor
4509 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004510 ** in two scenarios:
4511 **
4512 ** (a) A call to fstat() failed.
4513 ** (b) A malloc failed.
4514 **
4515 ** Scenario (b) may only occur if the process is holding no other
4516 ** file descriptors open on the same file. If there were other file
4517 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004518 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004519 ** handle h - as it is guaranteed that no posix locks will be released
4520 ** by doing so.
4521 **
4522 ** If scenario (a) caused the error then things are not so safe. The
4523 ** implicit assumption here is that if fstat() fails, things are in
4524 ** such bad shape that dropping a lock or two doesn't matter much.
4525 */
drh0e9365c2011-03-02 02:08:13 +00004526 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004527 h = -1;
4528 }
drh7708e972008-11-29 00:56:52 +00004529 unixLeaveMutex();
4530 }
danielk1977e339d652008-06-28 11:23:00 +00004531
drhd2cb50b2009-01-09 21:41:17 +00004532#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004533 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004534 /* AFP locking uses the file path so it needs to be included in
4535 ** the afpLockingContext.
4536 */
4537 afpLockingContext *pCtx;
4538 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4539 if( pCtx==0 ){
4540 rc = SQLITE_NOMEM;
4541 }else{
4542 /* NB: zFilename exists and remains valid until the file is closed
4543 ** according to requirement F11141. So we do not need to make a
4544 ** copy of the filename. */
4545 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004546 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004547 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004548 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004549 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004550 if( rc!=SQLITE_OK ){
4551 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004552 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004553 h = -1;
4554 }
drh7708e972008-11-29 00:56:52 +00004555 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004556 }
drh7708e972008-11-29 00:56:52 +00004557 }
4558#endif
danielk1977e339d652008-06-28 11:23:00 +00004559
drh7708e972008-11-29 00:56:52 +00004560 else if( pLockingStyle == &dotlockIoMethods ){
4561 /* Dotfile locking uses the file path so it needs to be included in
4562 ** the dotlockLockingContext
4563 */
4564 char *zLockFile;
4565 int nFilename;
drhea678832008-12-10 19:26:22 +00004566 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004567 zLockFile = (char *)sqlite3_malloc(nFilename);
4568 if( zLockFile==0 ){
4569 rc = SQLITE_NOMEM;
4570 }else{
4571 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004572 }
drh7708e972008-11-29 00:56:52 +00004573 pNew->lockingContext = zLockFile;
4574 }
danielk1977e339d652008-06-28 11:23:00 +00004575
drh6c7d5c52008-11-21 20:32:33 +00004576#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004577 else if( pLockingStyle == &semIoMethods ){
4578 /* Named semaphore locking uses the file path so it needs to be
4579 ** included in the semLockingContext
4580 */
4581 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004582 rc = findInodeInfo(pNew, &pNew->pInode);
4583 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4584 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004585 int n;
drh2238dcc2009-08-27 17:56:20 +00004586 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004587 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004588 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004589 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004590 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4591 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004592 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004593 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004594 }
chw97185482008-11-17 08:05:31 +00004595 }
drh7708e972008-11-29 00:56:52 +00004596 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004597 }
drh7708e972008-11-29 00:56:52 +00004598#endif
aswift5b1a2562008-08-22 00:22:35 +00004599
4600 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004601#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004602 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004603 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004604 h = -1;
chw97185482008-11-17 08:05:31 +00004605 unlink(zFilename);
4606 isDelete = 0;
4607 }
4608 pNew->isDelete = isDelete;
4609#endif
danielk1977e339d652008-06-28 11:23:00 +00004610 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004611 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4612 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004613 }else{
drh7708e972008-11-29 00:56:52 +00004614 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004615 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004616 }
danielk1977e339d652008-06-28 11:23:00 +00004617 return rc;
drh054889e2005-11-30 03:20:31 +00004618}
drh9c06c952005-11-26 00:25:00 +00004619
danielk1977ad94b582007-08-20 06:44:22 +00004620/*
4621** Open a file descriptor to the directory containing file zFilename.
4622** If successful, *pFd is set to the opened file descriptor and
4623** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4624** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4625** value.
4626**
4627** If SQLITE_OK is returned, the caller is responsible for closing
4628** the file descriptor *pFd using close().
4629*/
danielk1977fee2d252007-08-18 10:59:19 +00004630static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004631 int ii;
drh777b17a2007-09-20 10:02:54 +00004632 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004633 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004634
drh153c62c2007-08-24 03:51:33 +00004635 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004636 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004637 if( ii>0 ){
4638 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004639 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004640 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004641#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004642 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004643#endif
drh308c2a52010-05-14 11:30:18 +00004644 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004645 }
4646 }
danielk1977fee2d252007-08-18 10:59:19 +00004647 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004648 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004649}
4650
danielk1977b4b47412007-08-17 15:53:36 +00004651/*
drh8b3cf822010-06-01 21:02:51 +00004652** Return the name of a directory in which to put temporary files.
4653** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004654*/
drh7234c6d2010-06-19 15:10:09 +00004655static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004656 static const char *azDirs[] = {
4657 0,
aswiftaebf4132008-11-21 00:10:35 +00004658 0,
danielk197717b90b52008-06-06 11:11:25 +00004659 "/var/tmp",
4660 "/usr/tmp",
4661 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004662 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004663 };
drh8b3cf822010-06-01 21:02:51 +00004664 unsigned int i;
4665 struct stat buf;
4666 const char *zDir = 0;
4667
4668 azDirs[0] = sqlite3_temp_directory;
4669 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004670 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004671 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004672 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004673 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004674 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004675 break;
4676 }
4677 return zDir;
4678}
4679
4680/*
4681** Create a temporary file name in zBuf. zBuf must be allocated
4682** by the calling process and must be big enough to hold at least
4683** pVfs->mxPathname bytes.
4684*/
4685static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004686 static const unsigned char zChars[] =
4687 "abcdefghijklmnopqrstuvwxyz"
4688 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4689 "0123456789";
drh41022642008-11-21 00:24:42 +00004690 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004691 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004692
4693 /* It's odd to simulate an io-error here, but really this is just
4694 ** using the io-error infrastructure to test that SQLite handles this
4695 ** function failing.
4696 */
4697 SimulateIOError( return SQLITE_IOERR );
4698
drh7234c6d2010-06-19 15:10:09 +00004699 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004700 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004701
4702 /* Check that the output buffer is large enough for the temporary file
4703 ** name. If it is not, return SQLITE_ERROR.
4704 */
danielk197700e13612008-11-17 19:18:54 +00004705 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004706 return SQLITE_ERROR;
4707 }
4708
4709 do{
4710 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004711 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004712 sqlite3_randomness(15, &zBuf[j]);
4713 for(i=0; i<15; i++, j++){
4714 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4715 }
4716 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004717 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004718 return SQLITE_OK;
4719}
4720
drhd2cb50b2009-01-09 21:41:17 +00004721#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004722/*
4723** Routine to transform a unixFile into a proxy-locking unixFile.
4724** Implementation in the proxy-lock division, but used by unixOpen()
4725** if SQLITE_PREFER_PROXY_LOCKING is defined.
4726*/
4727static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004728#endif
drhc66d5b62008-12-03 22:48:32 +00004729
dan08da86a2009-08-21 17:18:03 +00004730/*
4731** Search for an unused file descriptor that was opened on the database
4732** file (not a journal or master-journal file) identified by pathname
4733** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4734** argument to this function.
4735**
4736** Such a file descriptor may exist if a database connection was closed
4737** but the associated file descriptor could not be closed because some
4738** other file descriptor open on the same file is holding a file-lock.
4739** Refer to comments in the unixClose() function and the lengthy comment
4740** describing "Posix Advisory Locking" at the start of this file for
4741** further details. Also, ticket #4018.
4742**
4743** If a suitable file descriptor is found, then it is returned. If no
4744** such file descriptor is located, -1 is returned.
4745*/
dane946c392009-08-22 11:39:46 +00004746static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4747 UnixUnusedFd *pUnused = 0;
4748
4749 /* Do not search for an unused file descriptor on vxworks. Not because
4750 ** vxworks would not benefit from the change (it might, we're not sure),
4751 ** but because no way to test it is currently available. It is better
4752 ** not to risk breaking vxworks support for the sake of such an obscure
4753 ** feature. */
4754#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004755 struct stat sStat; /* Results of stat() call */
4756
4757 /* A stat() call may fail for various reasons. If this happens, it is
4758 ** almost certain that an open() call on the same path will also fail.
4759 ** For this reason, if an error occurs in the stat() call here, it is
4760 ** ignored and -1 is returned. The caller will try to open a new file
4761 ** descriptor on the same path, fail, and return an error to SQLite.
4762 **
4763 ** Even if a subsequent open() call does succeed, the consequences of
4764 ** not searching for a resusable file descriptor are not dire. */
4765 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004766 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004767
4768 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004769 pInode = inodeList;
4770 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4771 || pInode->fileId.ino!=sStat.st_ino) ){
4772 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004773 }
drh8af6c222010-05-14 12:43:01 +00004774 if( pInode ){
dane946c392009-08-22 11:39:46 +00004775 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004776 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004777 pUnused = *pp;
4778 if( pUnused ){
4779 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004780 }
4781 }
4782 unixLeaveMutex();
4783 }
dane946c392009-08-22 11:39:46 +00004784#endif /* if !OS_VXWORKS */
4785 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004786}
danielk197717b90b52008-06-06 11:11:25 +00004787
4788/*
danddb0ac42010-07-14 14:48:58 +00004789** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004790** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004791** and a value suitable for passing as the third argument to open(2) is
4792** written to *pMode. If an IO error occurs, an SQLite error code is
4793** returned and the value of *pMode is not modified.
4794**
4795** If the file being opened is a temporary file, it is always created with
4796** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004797** is a database or master journal file, it is created with the permissions
4798** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004799**
drh8ab58662010-07-15 18:38:39 +00004800** Finally, if the file being opened is a WAL or regular journal file, then
4801** this function queries the file-system for the permissions on the
4802** corresponding database file and sets *pMode to this value. Whenever
4803** possible, WAL and journal files are created using the same permissions
4804** as the associated database file.
danddb0ac42010-07-14 14:48:58 +00004805*/
4806static int findCreateFileMode(
4807 const char *zPath, /* Path of file (possibly) being created */
4808 int flags, /* Flags passed as 4th argument to xOpen() */
4809 mode_t *pMode /* OUT: Permissions to open file with */
4810){
4811 int rc = SQLITE_OK; /* Return Code */
drh8ab58662010-07-15 18:38:39 +00004812 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004813 char zDb[MAX_PATHNAME+1]; /* Database file path */
4814 int nDb; /* Number of valid bytes in zDb */
4815 struct stat sStat; /* Output of stat() on database file */
4816
dana0c989d2010-11-05 18:07:37 +00004817 /* zPath is a path to a WAL or journal file. The following block derives
4818 ** the path to the associated database file from zPath. This block handles
4819 ** the following naming conventions:
4820 **
4821 ** "<path to db>-journal"
4822 ** "<path to db>-wal"
4823 ** "<path to db>-journal-NNNN"
4824 ** "<path to db>-wal-NNNN"
4825 **
4826 ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
4827 ** used by the test_multiplex.c module.
4828 */
4829 nDb = sqlite3Strlen30(zPath) - 1;
4830 while( nDb>0 && zPath[nDb]!='l' ) nDb--;
4831 nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
danddb0ac42010-07-14 14:48:58 +00004832 memcpy(zDb, zPath, nDb);
4833 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004834
danddb0ac42010-07-14 14:48:58 +00004835 if( 0==stat(zDb, &sStat) ){
4836 *pMode = sStat.st_mode & 0777;
4837 }else{
4838 rc = SQLITE_IOERR_FSTAT;
4839 }
4840 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4841 *pMode = 0600;
4842 }else{
4843 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4844 }
4845 return rc;
4846}
4847
4848/*
danielk1977ad94b582007-08-20 06:44:22 +00004849** Open the file zPath.
4850**
danielk1977b4b47412007-08-17 15:53:36 +00004851** Previously, the SQLite OS layer used three functions in place of this
4852** one:
4853**
4854** sqlite3OsOpenReadWrite();
4855** sqlite3OsOpenReadOnly();
4856** sqlite3OsOpenExclusive();
4857**
4858** These calls correspond to the following combinations of flags:
4859**
4860** ReadWrite() -> (READWRITE | CREATE)
4861** ReadOnly() -> (READONLY)
4862** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4863**
4864** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4865** true, the file was configured to be automatically deleted when the
4866** file handle closed. To achieve the same effect using this new
4867** interface, add the DELETEONCLOSE flag to those specified above for
4868** OpenExclusive().
4869*/
4870static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004871 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4872 const char *zPath, /* Pathname of file to be opened */
4873 sqlite3_file *pFile, /* The file descriptor to be filled in */
4874 int flags, /* Input flags to control the opening */
4875 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004876){
dan08da86a2009-08-21 17:18:03 +00004877 unixFile *p = (unixFile *)pFile;
4878 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004879 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004880 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004881 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004882 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004883 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004884
4885 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4886 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4887 int isCreate = (flags & SQLITE_OPEN_CREATE);
4888 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4889 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004890#if SQLITE_ENABLE_LOCKING_STYLE
4891 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4892#endif
danielk1977b4b47412007-08-17 15:53:36 +00004893
danielk1977fee2d252007-08-18 10:59:19 +00004894 /* If creating a master or main-file journal, this function will open
4895 ** a file-descriptor on the directory too. The first time unixSync()
4896 ** is called the directory file descriptor will be fsync()ed and close()d.
4897 */
danddb0ac42010-07-14 14:48:58 +00004898 int isOpenDirectory = (isCreate && (
4899 eType==SQLITE_OPEN_MASTER_JOURNAL
4900 || eType==SQLITE_OPEN_MAIN_JOURNAL
4901 || eType==SQLITE_OPEN_WAL
4902 ));
danielk1977fee2d252007-08-18 10:59:19 +00004903
danielk197717b90b52008-06-06 11:11:25 +00004904 /* If argument zPath is a NULL pointer, this function is required to open
4905 ** a temporary file. Use this buffer to store the file name in.
4906 */
4907 char zTmpname[MAX_PATHNAME+1];
4908 const char *zName = zPath;
4909
danielk1977fee2d252007-08-18 10:59:19 +00004910 /* Check the following statements are true:
4911 **
4912 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4913 ** (b) if CREATE is set, then READWRITE must also be set, and
4914 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004915 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004916 */
danielk1977b4b47412007-08-17 15:53:36 +00004917 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004918 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004919 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004920 assert(isDelete==0 || isCreate);
4921
danddb0ac42010-07-14 14:48:58 +00004922 /* The main DB, main journal, WAL file and master journal are never
4923 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004924 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4925 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4926 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004927 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004928
danielk1977fee2d252007-08-18 10:59:19 +00004929 /* Assert that the upper layer has set one of the "file-type" flags. */
4930 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4931 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4932 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004933 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004934 );
4935
dan08da86a2009-08-21 17:18:03 +00004936 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004937
dan08da86a2009-08-21 17:18:03 +00004938 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004939 UnixUnusedFd *pUnused;
4940 pUnused = findReusableFd(zName, flags);
4941 if( pUnused ){
4942 fd = pUnused->fd;
4943 }else{
dan6aa657f2009-08-24 18:57:58 +00004944 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004945 if( !pUnused ){
4946 return SQLITE_NOMEM;
4947 }
4948 }
4949 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004950 }else if( !zName ){
4951 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004952 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004953 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004954 if( rc!=SQLITE_OK ){
4955 return rc;
4956 }
4957 zName = zTmpname;
4958 }
4959
dan08da86a2009-08-21 17:18:03 +00004960 /* Determine the value of the flags parameter passed to POSIX function
4961 ** open(). These must be calculated even if open() is not called, as
4962 ** they may be stored as part of the file handle and used by the
4963 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004964 if( isReadonly ) openFlags |= O_RDONLY;
4965 if( isReadWrite ) openFlags |= O_RDWR;
4966 if( isCreate ) openFlags |= O_CREAT;
4967 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4968 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004969
danielk1977b4b47412007-08-17 15:53:36 +00004970 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004971 mode_t openMode; /* Permissions to create file with */
4972 rc = findCreateFileMode(zName, flags, &openMode);
4973 if( rc!=SQLITE_OK ){
4974 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004975 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004976 return rc;
4977 }
drhad4f1e52011-03-04 15:43:57 +00004978 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004979 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004980 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4981 /* Failed to open the file for read/write access. Try read-only. */
4982 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004983 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004984 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004985 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00004986 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00004987 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004988 }
4989 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00004990 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00004991 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004992 }
danielk1977b4b47412007-08-17 15:53:36 +00004993 }
dan08da86a2009-08-21 17:18:03 +00004994 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004995 if( pOutFlags ){
4996 *pOutFlags = flags;
4997 }
4998
dane946c392009-08-22 11:39:46 +00004999 if( p->pUnused ){
5000 p->pUnused->fd = fd;
5001 p->pUnused->flags = flags;
5002 }
5003
danielk1977b4b47412007-08-17 15:53:36 +00005004 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005005#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005006 zPath = zName;
5007#else
danielk197717b90b52008-06-06 11:11:25 +00005008 unlink(zName);
chw97185482008-11-17 08:05:31 +00005009#endif
danielk1977b4b47412007-08-17 15:53:36 +00005010 }
drh41022642008-11-21 00:24:42 +00005011#if SQLITE_ENABLE_LOCKING_STYLE
5012 else{
dan08da86a2009-08-21 17:18:03 +00005013 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005014 }
5015#endif
5016
danielk1977fee2d252007-08-18 10:59:19 +00005017 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00005018 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00005019 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00005020 /* It is safe to close fd at this point, because it is guaranteed not
5021 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00005022 ** it would not be safe to close as this would release any locks held
5023 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005024 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00005025 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005026 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005027 }
5028 }
danielk1977e339d652008-06-28 11:23:00 +00005029
5030#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005031 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005032#endif
5033
drhda0e7682008-07-30 15:27:54 +00005034 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005035
drh7ed97b92010-01-20 13:07:21 +00005036
5037#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5038 struct statfs fsInfo;
5039 if( fstatfs(fd, &fsInfo) == -1 ){
5040 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005041 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
5042 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005043 return SQLITE_IOERR_ACCESS;
5044 }
5045 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5046 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5047 }
5048#endif
5049
5050#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005051#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005052 isAutoProxy = 1;
5053#endif
5054 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005055 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5056 int useProxy = 0;
5057
dan08da86a2009-08-21 17:18:03 +00005058 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5059 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005060 if( envforce!=NULL ){
5061 useProxy = atoi(envforce)>0;
5062 }else{
5063 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005064 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005065 /* In theory, the close(fd) call is sub-optimal. If the file opened
5066 ** with fd is a database file, and there are other connections open
5067 ** on that file that are currently holding advisory locks on it,
5068 ** then the call to close() will cancel those locks. In practice,
5069 ** we're assuming that statfs() doesn't fail very often. At least
5070 ** not while other file descriptors opened by the same process on
5071 ** the same file are working. */
5072 p->lastErrno = errno;
5073 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005074 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00005075 }
drh0e9365c2011-03-02 02:08:13 +00005076 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005077 rc = SQLITE_IOERR_ACCESS;
5078 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005079 }
5080 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5081 }
5082 if( useProxy ){
drh77197112011-03-15 19:08:48 +00005083 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5084 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005085 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005086 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005087 if( rc!=SQLITE_OK ){
5088 /* Use unixClose to clean up the resources added in fillInUnixFile
5089 ** and clear all the structure's references. Specifically,
5090 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5091 */
5092 unixClose(pFile);
5093 return rc;
5094 }
aswiftaebf4132008-11-21 00:10:35 +00005095 }
dane946c392009-08-22 11:39:46 +00005096 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005097 }
5098 }
5099#endif
5100
drh77197112011-03-15 19:08:48 +00005101 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5102 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005103open_finished:
5104 if( rc!=SQLITE_OK ){
5105 sqlite3_free(p->pUnused);
5106 }
5107 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005108}
5109
dane946c392009-08-22 11:39:46 +00005110
danielk1977b4b47412007-08-17 15:53:36 +00005111/*
danielk1977fee2d252007-08-18 10:59:19 +00005112** Delete the file at zPath. If the dirSync argument is true, fsync()
5113** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005114*/
drh6b9d6dd2008-12-03 19:34:47 +00005115static int unixDelete(
5116 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5117 const char *zPath, /* Name of file to be deleted */
5118 int dirSync /* If true, fsync() directory after deleting file */
5119){
danielk1977fee2d252007-08-18 10:59:19 +00005120 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005121 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005122 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00005123 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005124 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005125 }
danielk1977d39fa702008-10-16 13:27:40 +00005126#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005127 if( dirSync ){
5128 int fd;
5129 rc = openDirectory(zPath, &fd);
5130 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005131#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005132 if( fsync(fd)==-1 )
5133#else
5134 if( fsync(fd) )
5135#endif
5136 {
dane18d4952011-02-21 11:46:24 +00005137 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005138 }
drh0e9365c2011-03-02 02:08:13 +00005139 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005140 }
5141 }
danielk1977d138dd82008-10-15 16:02:48 +00005142#endif
danielk1977fee2d252007-08-18 10:59:19 +00005143 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005144}
5145
danielk197790949c22007-08-17 16:50:38 +00005146/*
5147** Test the existance of or access permissions of file zPath. The
5148** test performed depends on the value of flags:
5149**
5150** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5151** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5152** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5153**
5154** Otherwise return 0.
5155*/
danielk1977861f7452008-06-05 11:39:11 +00005156static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005157 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5158 const char *zPath, /* Path of the file to examine */
5159 int flags, /* What do we want to learn about the zPath file? */
5160 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005161){
rse25c0d1a2007-09-20 08:38:14 +00005162 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005163 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005164 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005165 switch( flags ){
5166 case SQLITE_ACCESS_EXISTS:
5167 amode = F_OK;
5168 break;
5169 case SQLITE_ACCESS_READWRITE:
5170 amode = W_OK|R_OK;
5171 break;
drh50d3f902007-08-27 21:10:36 +00005172 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005173 amode = R_OK;
5174 break;
5175
5176 default:
5177 assert(!"Invalid flags argument");
5178 }
drh99ab3b12011-03-02 15:09:07 +00005179 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005180 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5181 struct stat buf;
5182 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5183 *pResOut = 0;
5184 }
5185 }
danielk1977861f7452008-06-05 11:39:11 +00005186 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005187}
5188
danielk1977b4b47412007-08-17 15:53:36 +00005189
5190/*
5191** Turn a relative pathname into a full pathname. The relative path
5192** is stored as a nul-terminated string in the buffer pointed to by
5193** zPath.
5194**
5195** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5196** (in this case, MAX_PATHNAME bytes). The full-path is written to
5197** this buffer before returning.
5198*/
danielk1977adfb9b02007-09-17 07:02:56 +00005199static int unixFullPathname(
5200 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5201 const char *zPath, /* Possibly relative input path */
5202 int nOut, /* Size of output buffer in bytes */
5203 char *zOut /* Output buffer */
5204){
danielk1977843e65f2007-09-01 16:16:15 +00005205
5206 /* It's odd to simulate an io-error here, but really this is just
5207 ** using the io-error infrastructure to test that SQLite handles this
5208 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005209 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005210 */
5211 SimulateIOError( return SQLITE_ERROR );
5212
drh153c62c2007-08-24 03:51:33 +00005213 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005214 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005215
drh3c7f2dc2007-12-06 13:26:20 +00005216 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005217 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005218 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005219 }else{
5220 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005221 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005222 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005223 }
drhea678832008-12-10 19:26:22 +00005224 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005225 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005226 }
5227 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005228}
5229
drh0ccebe72005-06-07 22:22:50 +00005230
drh761df872006-12-21 01:29:22 +00005231#ifndef SQLITE_OMIT_LOAD_EXTENSION
5232/*
5233** Interfaces for opening a shared library, finding entry points
5234** within the shared library, and closing the shared library.
5235*/
5236#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005237static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5238 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005239 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5240}
danielk197795c8a542007-09-01 06:51:27 +00005241
5242/*
5243** SQLite calls this function immediately after a call to unixDlSym() or
5244** unixDlOpen() fails (returns a null pointer). If a more detailed error
5245** message is available, it is written to zBufOut. If no error message
5246** is available, zBufOut is left unmodified and SQLite uses a default
5247** error message.
5248*/
danielk1977397d65f2008-11-19 11:35:39 +00005249static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005250 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005251 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005252 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005253 zErr = dlerror();
5254 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005255 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005256 }
drh6c7d5c52008-11-21 20:32:33 +00005257 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005258}
drh1875f7a2008-12-08 18:19:17 +00005259static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5260 /*
5261 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5262 ** cast into a pointer to a function. And yet the library dlsym() routine
5263 ** returns a void* which is really a pointer to a function. So how do we
5264 ** use dlsym() with -pedantic-errors?
5265 **
5266 ** Variable x below is defined to be a pointer to a function taking
5267 ** parameters void* and const char* and returning a pointer to a function.
5268 ** We initialize x by assigning it a pointer to the dlsym() function.
5269 ** (That assignment requires a cast.) Then we call the function that
5270 ** x points to.
5271 **
5272 ** This work-around is unlikely to work correctly on any system where
5273 ** you really cannot cast a function pointer into void*. But then, on the
5274 ** other hand, dlsym() will not work on such a system either, so we have
5275 ** not really lost anything.
5276 */
5277 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005278 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005279 x = (void(*(*)(void*,const char*))(void))dlsym;
5280 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005281}
danielk1977397d65f2008-11-19 11:35:39 +00005282static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5283 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005284 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005285}
danielk1977b4b47412007-08-17 15:53:36 +00005286#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5287 #define unixDlOpen 0
5288 #define unixDlError 0
5289 #define unixDlSym 0
5290 #define unixDlClose 0
5291#endif
5292
5293/*
danielk197790949c22007-08-17 16:50:38 +00005294** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005295*/
danielk1977397d65f2008-11-19 11:35:39 +00005296static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5297 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005298 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005299
drhbbd42a62004-05-22 17:41:58 +00005300 /* We have to initialize zBuf to prevent valgrind from reporting
5301 ** errors. The reports issued by valgrind are incorrect - we would
5302 ** prefer that the randomness be increased by making use of the
5303 ** uninitialized space in zBuf - but valgrind errors tend to worry
5304 ** some users. Rather than argue, it seems easier just to initialize
5305 ** the whole array and silence valgrind, even if that means less randomness
5306 ** in the random seed.
5307 **
5308 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005309 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005310 ** tests repeatable.
5311 */
danielk1977b4b47412007-08-17 15:53:36 +00005312 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005313#if !defined(SQLITE_TEST)
5314 {
drh842b8642005-01-21 17:53:17 +00005315 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005316 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005317 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005318 time_t t;
5319 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005320 memcpy(zBuf, &t, sizeof(t));
5321 pid = getpid();
5322 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005323 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005324 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005325 }else{
drhe562be52011-03-02 18:01:10 +00005326 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005327 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005328 }
drhbbd42a62004-05-22 17:41:58 +00005329 }
5330#endif
drh72cbd072008-10-14 17:58:38 +00005331 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005332}
5333
danielk1977b4b47412007-08-17 15:53:36 +00005334
drhbbd42a62004-05-22 17:41:58 +00005335/*
5336** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005337** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005338** The return value is the number of microseconds of sleep actually
5339** requested from the underlying operating system, a number which
5340** might be greater than or equal to the argument, but not less
5341** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005342*/
danielk1977397d65f2008-11-19 11:35:39 +00005343static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005344#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005345 struct timespec sp;
5346
5347 sp.tv_sec = microseconds / 1000000;
5348 sp.tv_nsec = (microseconds % 1000000) * 1000;
5349 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005350 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005351 return microseconds;
5352#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005353 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005354 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005355 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005356#else
danielk1977b4b47412007-08-17 15:53:36 +00005357 int seconds = (microseconds+999999)/1000000;
5358 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005359 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005360 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005361#endif
drh88f474a2006-01-02 20:00:12 +00005362}
5363
5364/*
drh6b9d6dd2008-12-03 19:34:47 +00005365** The following variable, if set to a non-zero value, is interpreted as
5366** the number of seconds since 1970 and is used to set the result of
5367** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005368*/
5369#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005370int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005371#endif
5372
5373/*
drhb7e8ea22010-05-03 14:32:30 +00005374** Find the current time (in Universal Coordinated Time). Write into *piNow
5375** the current time and date as a Julian Day number times 86_400_000. In
5376** other words, write into *piNow the number of milliseconds since the Julian
5377** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5378** proleptic Gregorian calendar.
5379**
5380** On success, return 0. Return 1 if the time and date cannot be found.
5381*/
5382static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5383 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5384#if defined(NO_GETTOD)
5385 time_t t;
5386 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005387 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005388#elif OS_VXWORKS
5389 struct timespec sNow;
5390 clock_gettime(CLOCK_REALTIME, &sNow);
5391 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5392#else
5393 struct timeval sNow;
5394 gettimeofday(&sNow, 0);
5395 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5396#endif
5397
5398#ifdef SQLITE_TEST
5399 if( sqlite3_current_time ){
5400 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5401 }
5402#endif
5403 UNUSED_PARAMETER(NotUsed);
5404 return 0;
5405}
5406
5407/*
drhbbd42a62004-05-22 17:41:58 +00005408** Find the current time (in Universal Coordinated Time). Write the
5409** current time and date as a Julian Day number into *prNow and
5410** return 0. Return 1 if the time and date cannot be found.
5411*/
danielk1977397d65f2008-11-19 11:35:39 +00005412static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005413 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005414 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005415 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005416 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005417 return 0;
5418}
danielk1977b4b47412007-08-17 15:53:36 +00005419
drh6b9d6dd2008-12-03 19:34:47 +00005420/*
5421** We added the xGetLastError() method with the intention of providing
5422** better low-level error messages when operating-system problems come up
5423** during SQLite operation. But so far, none of that has been implemented
5424** in the core. So this routine is never called. For now, it is merely
5425** a place-holder.
5426*/
danielk1977397d65f2008-11-19 11:35:39 +00005427static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5428 UNUSED_PARAMETER(NotUsed);
5429 UNUSED_PARAMETER(NotUsed2);
5430 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005431 return 0;
5432}
5433
drhf2424c52010-04-26 00:04:55 +00005434
5435/*
drh734c9862008-11-28 15:37:20 +00005436************************ End of sqlite3_vfs methods ***************************
5437******************************************************************************/
5438
drh715ff302008-12-03 22:32:44 +00005439/******************************************************************************
5440************************** Begin Proxy Locking ********************************
5441**
5442** Proxy locking is a "uber-locking-method" in this sense: It uses the
5443** other locking methods on secondary lock files. Proxy locking is a
5444** meta-layer over top of the primitive locking implemented above. For
5445** this reason, the division that implements of proxy locking is deferred
5446** until late in the file (here) after all of the other I/O methods have
5447** been defined - so that the primitive locking methods are available
5448** as services to help with the implementation of proxy locking.
5449**
5450****
5451**
5452** The default locking schemes in SQLite use byte-range locks on the
5453** database file to coordinate safe, concurrent access by multiple readers
5454** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5455** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5456** as POSIX read & write locks over fixed set of locations (via fsctl),
5457** on AFP and SMB only exclusive byte-range locks are available via fsctl
5458** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5459** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5460** address in the shared range is taken for a SHARED lock, the entire
5461** shared range is taken for an EXCLUSIVE lock):
5462**
5463** PENDING_BYTE 0x40000000
5464** RESERVED_BYTE 0x40000001
5465** SHARED_RANGE 0x40000002 -> 0x40000200
5466**
5467** This works well on the local file system, but shows a nearly 100x
5468** slowdown in read performance on AFP because the AFP client disables
5469** the read cache when byte-range locks are present. Enabling the read
5470** cache exposes a cache coherency problem that is present on all OS X
5471** supported network file systems. NFS and AFP both observe the
5472** close-to-open semantics for ensuring cache coherency
5473** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5474** address the requirements for concurrent database access by multiple
5475** readers and writers
5476** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5477**
5478** To address the performance and cache coherency issues, proxy file locking
5479** changes the way database access is controlled by limiting access to a
5480** single host at a time and moving file locks off of the database file
5481** and onto a proxy file on the local file system.
5482**
5483**
5484** Using proxy locks
5485** -----------------
5486**
5487** C APIs
5488**
5489** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5490** <proxy_path> | ":auto:");
5491** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5492**
5493**
5494** SQL pragmas
5495**
5496** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5497** PRAGMA [database.]lock_proxy_file
5498**
5499** Specifying ":auto:" means that if there is a conch file with a matching
5500** host ID in it, the proxy path in the conch file will be used, otherwise
5501** a proxy path based on the user's temp dir
5502** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5503** actual proxy file name is generated from the name and path of the
5504** database file. For example:
5505**
5506** For database path "/Users/me/foo.db"
5507** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5508**
5509** Once a lock proxy is configured for a database connection, it can not
5510** be removed, however it may be switched to a different proxy path via
5511** the above APIs (assuming the conch file is not being held by another
5512** connection or process).
5513**
5514**
5515** How proxy locking works
5516** -----------------------
5517**
5518** Proxy file locking relies primarily on two new supporting files:
5519**
5520** * conch file to limit access to the database file to a single host
5521** at a time
5522**
5523** * proxy file to act as a proxy for the advisory locks normally
5524** taken on the database
5525**
5526** The conch file - to use a proxy file, sqlite must first "hold the conch"
5527** by taking an sqlite-style shared lock on the conch file, reading the
5528** contents and comparing the host's unique host ID (see below) and lock
5529** proxy path against the values stored in the conch. The conch file is
5530** stored in the same directory as the database file and the file name
5531** is patterned after the database file name as ".<databasename>-conch".
5532** If the conch file does not exist, or it's contents do not match the
5533** host ID and/or proxy path, then the lock is escalated to an exclusive
5534** lock and the conch file contents is updated with the host ID and proxy
5535** path and the lock is downgraded to a shared lock again. If the conch
5536** is held by another process (with a shared lock), the exclusive lock
5537** will fail and SQLITE_BUSY is returned.
5538**
5539** The proxy file - a single-byte file used for all advisory file locks
5540** normally taken on the database file. This allows for safe sharing
5541** of the database file for multiple readers and writers on the same
5542** host (the conch ensures that they all use the same local lock file).
5543**
drh715ff302008-12-03 22:32:44 +00005544** Requesting the lock proxy does not immediately take the conch, it is
5545** only taken when the first request to lock database file is made.
5546** This matches the semantics of the traditional locking behavior, where
5547** opening a connection to a database file does not take a lock on it.
5548** The shared lock and an open file descriptor are maintained until
5549** the connection to the database is closed.
5550**
5551** The proxy file and the lock file are never deleted so they only need
5552** to be created the first time they are used.
5553**
5554** Configuration options
5555** ---------------------
5556**
5557** SQLITE_PREFER_PROXY_LOCKING
5558**
5559** Database files accessed on non-local file systems are
5560** automatically configured for proxy locking, lock files are
5561** named automatically using the same logic as
5562** PRAGMA lock_proxy_file=":auto:"
5563**
5564** SQLITE_PROXY_DEBUG
5565**
5566** Enables the logging of error messages during host id file
5567** retrieval and creation
5568**
drh715ff302008-12-03 22:32:44 +00005569** LOCKPROXYDIR
5570**
5571** Overrides the default directory used for lock proxy files that
5572** are named automatically via the ":auto:" setting
5573**
5574** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5575**
5576** Permissions to use when creating a directory for storing the
5577** lock proxy files, only used when LOCKPROXYDIR is not set.
5578**
5579**
5580** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5581** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5582** force proxy locking to be used for every database file opened, and 0
5583** will force automatic proxy locking to be disabled for all database
5584** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5585** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5586*/
5587
5588/*
5589** Proxy locking is only available on MacOSX
5590*/
drhd2cb50b2009-01-09 21:41:17 +00005591#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005592
drh715ff302008-12-03 22:32:44 +00005593/*
5594** The proxyLockingContext has the path and file structures for the remote
5595** and local proxy files in it
5596*/
5597typedef struct proxyLockingContext proxyLockingContext;
5598struct proxyLockingContext {
5599 unixFile *conchFile; /* Open conch file */
5600 char *conchFilePath; /* Name of the conch file */
5601 unixFile *lockProxy; /* Open proxy lock file */
5602 char *lockProxyPath; /* Name of the proxy lock file */
5603 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005604 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005605 void *oldLockingContext; /* Original lockingcontext to restore on close */
5606 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5607};
5608
drh7ed97b92010-01-20 13:07:21 +00005609/*
5610** The proxy lock file path for the database at dbPath is written into lPath,
5611** which must point to valid, writable memory large enough for a maxLen length
5612** file path.
drh715ff302008-12-03 22:32:44 +00005613*/
drh715ff302008-12-03 22:32:44 +00005614static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5615 int len;
5616 int dbLen;
5617 int i;
5618
5619#ifdef LOCKPROXYDIR
5620 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5621#else
5622# ifdef _CS_DARWIN_USER_TEMP_DIR
5623 {
drh7ed97b92010-01-20 13:07:21 +00005624 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005625 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5626 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005627 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005628 }
drh7ed97b92010-01-20 13:07:21 +00005629 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005630 }
5631# else
5632 len = strlcpy(lPath, "/tmp/", maxLen);
5633# endif
5634#endif
5635
5636 if( lPath[len-1]!='/' ){
5637 len = strlcat(lPath, "/", maxLen);
5638 }
5639
5640 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005641 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005642 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005643 char c = dbPath[i];
5644 lPath[i+len] = (c=='/')?'_':c;
5645 }
5646 lPath[i+len]='\0';
5647 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005648 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005649 return SQLITE_OK;
5650}
5651
drh7ed97b92010-01-20 13:07:21 +00005652/*
5653 ** Creates the lock file and any missing directories in lockPath
5654 */
5655static int proxyCreateLockPath(const char *lockPath){
5656 int i, len;
5657 char buf[MAXPATHLEN];
5658 int start = 0;
5659
5660 assert(lockPath!=NULL);
5661 /* try to create all the intermediate directories */
5662 len = (int)strlen(lockPath);
5663 buf[0] = lockPath[0];
5664 for( i=1; i<len; i++ ){
5665 if( lockPath[i] == '/' && (i - start > 0) ){
5666 /* only mkdir if leaf dir != "." or "/" or ".." */
5667 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5668 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5669 buf[i]='\0';
5670 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5671 int err=errno;
5672 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005673 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005674 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005675 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005676 return err;
5677 }
5678 }
5679 }
5680 start=i+1;
5681 }
5682 buf[i] = lockPath[i];
5683 }
drh308c2a52010-05-14 11:30:18 +00005684 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005685 return 0;
5686}
5687
drh715ff302008-12-03 22:32:44 +00005688/*
5689** Create a new VFS file descriptor (stored in memory obtained from
5690** sqlite3_malloc) and open the file named "path" in the file descriptor.
5691**
5692** The caller is responsible not only for closing the file descriptor
5693** but also for freeing the memory associated with the file descriptor.
5694*/
drh7ed97b92010-01-20 13:07:21 +00005695static int proxyCreateUnixFile(
5696 const char *path, /* path for the new unixFile */
5697 unixFile **ppFile, /* unixFile created and returned by ref */
5698 int islockfile /* if non zero missing dirs will be created */
5699) {
5700 int fd = -1;
5701 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005702 unixFile *pNew;
5703 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005704 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005705 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005706 int terrno = 0;
5707 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005708
drh7ed97b92010-01-20 13:07:21 +00005709 /* 1. first try to open/create the file
5710 ** 2. if that fails, and this is a lock file (not-conch), try creating
5711 ** the parent directories and then try again.
5712 ** 3. if that fails, try to open the file read-only
5713 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5714 */
5715 pUnused = findReusableFd(path, openFlags);
5716 if( pUnused ){
5717 fd = pUnused->fd;
5718 }else{
5719 pUnused = sqlite3_malloc(sizeof(*pUnused));
5720 if( !pUnused ){
5721 return SQLITE_NOMEM;
5722 }
5723 }
5724 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005725 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005726 terrno = errno;
5727 if( fd<0 && errno==ENOENT && islockfile ){
5728 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005729 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005730 }
5731 }
5732 }
5733 if( fd<0 ){
5734 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005735 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005736 terrno = errno;
5737 }
5738 if( fd<0 ){
5739 if( islockfile ){
5740 return SQLITE_BUSY;
5741 }
5742 switch (terrno) {
5743 case EACCES:
5744 return SQLITE_PERM;
5745 case EIO:
5746 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5747 default:
drh9978c972010-02-23 17:36:32 +00005748 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005749 }
5750 }
5751
5752 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5753 if( pNew==NULL ){
5754 rc = SQLITE_NOMEM;
5755 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005756 }
5757 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005758 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005759 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005760 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005761 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005762 pUnused->fd = fd;
5763 pUnused->flags = openFlags;
5764 pNew->pUnused = pUnused;
5765
drh77197112011-03-15 19:08:48 +00005766 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005767 if( rc==SQLITE_OK ){
5768 *ppFile = pNew;
5769 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005770 }
drh7ed97b92010-01-20 13:07:21 +00005771end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005772 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005773 sqlite3_free(pNew);
5774 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005775 return rc;
5776}
5777
drh7ed97b92010-01-20 13:07:21 +00005778#ifdef SQLITE_TEST
5779/* simulate multiple hosts by creating unique hostid file paths */
5780int sqlite3_hostid_num = 0;
5781#endif
5782
5783#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5784
drh0ab216a2010-07-02 17:10:40 +00005785/* Not always defined in the headers as it ought to be */
5786extern int gethostuuid(uuid_t id, const struct timespec *wait);
5787
drh7ed97b92010-01-20 13:07:21 +00005788/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5789** bytes of writable memory.
5790*/
5791static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005792 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5793 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005794#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5795 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005796 {
5797 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5798 if( gethostuuid(pHostID, &timeout) ){
5799 int err = errno;
5800 if( pError ){
5801 *pError = err;
5802 }
5803 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005804 }
drh7ed97b92010-01-20 13:07:21 +00005805 }
drhe8b0c9b2010-09-25 14:13:17 +00005806#endif
drh7ed97b92010-01-20 13:07:21 +00005807#ifdef SQLITE_TEST
5808 /* simulate multiple hosts by creating unique hostid file paths */
5809 if( sqlite3_hostid_num != 0){
5810 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5811 }
5812#endif
5813
5814 return SQLITE_OK;
5815}
5816
5817/* The conch file contains the header, host id and lock file path
5818 */
5819#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5820#define PROXY_HEADERLEN 1 /* conch file header length */
5821#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5822#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5823
5824/*
5825** Takes an open conch file, copies the contents to a new path and then moves
5826** it back. The newly created file's file descriptor is assigned to the
5827** conch file structure and finally the original conch file descriptor is
5828** closed. Returns zero if successful.
5829*/
5830static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5831 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5832 unixFile *conchFile = pCtx->conchFile;
5833 char tPath[MAXPATHLEN];
5834 char buf[PROXY_MAXCONCHLEN];
5835 char *cPath = pCtx->conchFilePath;
5836 size_t readLen = 0;
5837 size_t pathLen = 0;
5838 char errmsg[64] = "";
5839 int fd = -1;
5840 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005841 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005842
5843 /* create a new path by replace the trailing '-conch' with '-break' */
5844 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5845 if( pathLen>MAXPATHLEN || pathLen<6 ||
5846 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005847 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005848 goto end_breaklock;
5849 }
5850 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005851 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005852 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005853 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005854 goto end_breaklock;
5855 }
5856 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005857 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5858 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005859 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005860 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005861 goto end_breaklock;
5862 }
drhe562be52011-03-02 18:01:10 +00005863 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005864 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005865 goto end_breaklock;
5866 }
5867 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005868 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005869 goto end_breaklock;
5870 }
5871 rc = 0;
5872 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005873 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005874 conchFile->h = fd;
5875 conchFile->openFlags = O_RDWR | O_CREAT;
5876
5877end_breaklock:
5878 if( rc ){
5879 if( fd>=0 ){
5880 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005881 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005882 }
5883 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5884 }
5885 return rc;
5886}
5887
5888/* Take the requested lock on the conch file and break a stale lock if the
5889** host id matches.
5890*/
5891static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5892 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5893 unixFile *conchFile = pCtx->conchFile;
5894 int rc = SQLITE_OK;
5895 int nTries = 0;
5896 struct timespec conchModTime;
5897
5898 do {
5899 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5900 nTries ++;
5901 if( rc==SQLITE_BUSY ){
5902 /* If the lock failed (busy):
5903 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5904 * 2nd try: fail if the mod time changed or host id is different, wait
5905 * 10 sec and try again
5906 * 3rd try: break the lock unless the mod time has changed.
5907 */
5908 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005909 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005910 pFile->lastErrno = errno;
5911 return SQLITE_IOERR_LOCK;
5912 }
5913
5914 if( nTries==1 ){
5915 conchModTime = buf.st_mtimespec;
5916 usleep(500000); /* wait 0.5 sec and try the lock again*/
5917 continue;
5918 }
5919
5920 assert( nTries>1 );
5921 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5922 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5923 return SQLITE_BUSY;
5924 }
5925
5926 if( nTries==2 ){
5927 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005928 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005929 if( len<0 ){
5930 pFile->lastErrno = errno;
5931 return SQLITE_IOERR_LOCK;
5932 }
5933 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5934 /* don't break the lock if the host id doesn't match */
5935 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5936 return SQLITE_BUSY;
5937 }
5938 }else{
5939 /* don't break the lock on short read or a version mismatch */
5940 return SQLITE_BUSY;
5941 }
5942 usleep(10000000); /* wait 10 sec and try the lock again */
5943 continue;
5944 }
5945
5946 assert( nTries==3 );
5947 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5948 rc = SQLITE_OK;
5949 if( lockType==EXCLUSIVE_LOCK ){
5950 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5951 }
5952 if( !rc ){
5953 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5954 }
5955 }
5956 }
5957 } while( rc==SQLITE_BUSY && nTries<3 );
5958
5959 return rc;
5960}
5961
5962/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005963** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5964** lockPath means that the lockPath in the conch file will be used if the
5965** host IDs match, or a new lock path will be generated automatically
5966** and written to the conch file.
5967*/
5968static int proxyTakeConch(unixFile *pFile){
5969 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5970
drh7ed97b92010-01-20 13:07:21 +00005971 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005972 return SQLITE_OK;
5973 }else{
5974 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005975 uuid_t myHostID;
5976 int pError = 0;
5977 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005978 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005979 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005980 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005981 int createConch = 0;
5982 int hostIdMatch = 0;
5983 int readLen = 0;
5984 int tryOldLockPath = 0;
5985 int forceNewLockPath = 0;
5986
drh308c2a52010-05-14 11:30:18 +00005987 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5988 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005989
drh7ed97b92010-01-20 13:07:21 +00005990 rc = proxyGetHostID(myHostID, &pError);
5991 if( (rc&0xff)==SQLITE_IOERR ){
5992 pFile->lastErrno = pError;
5993 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005994 }
drh7ed97b92010-01-20 13:07:21 +00005995 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005996 if( rc!=SQLITE_OK ){
5997 goto end_takeconch;
5998 }
drh7ed97b92010-01-20 13:07:21 +00005999 /* read the existing conch file */
6000 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6001 if( readLen<0 ){
6002 /* I/O error: lastErrno set by seekAndRead */
6003 pFile->lastErrno = conchFile->lastErrno;
6004 rc = SQLITE_IOERR_READ;
6005 goto end_takeconch;
6006 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6007 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6008 /* a short read or version format mismatch means we need to create a new
6009 ** conch file.
6010 */
6011 createConch = 1;
6012 }
6013 /* if the host id matches and the lock path already exists in the conch
6014 ** we'll try to use the path there, if we can't open that path, we'll
6015 ** retry with a new auto-generated path
6016 */
6017 do { /* in case we need to try again for an :auto: named lock file */
6018
6019 if( !createConch && !forceNewLockPath ){
6020 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6021 PROXY_HOSTIDLEN);
6022 /* if the conch has data compare the contents */
6023 if( !pCtx->lockProxyPath ){
6024 /* for auto-named local lock file, just check the host ID and we'll
6025 ** use the local lock file path that's already in there
6026 */
6027 if( hostIdMatch ){
6028 size_t pathLen = (readLen - PROXY_PATHINDEX);
6029
6030 if( pathLen>=MAXPATHLEN ){
6031 pathLen=MAXPATHLEN-1;
6032 }
6033 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6034 lockPath[pathLen] = 0;
6035 tempLockPath = lockPath;
6036 tryOldLockPath = 1;
6037 /* create a copy of the lock path if the conch is taken */
6038 goto end_takeconch;
6039 }
6040 }else if( hostIdMatch
6041 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6042 readLen-PROXY_PATHINDEX)
6043 ){
6044 /* conch host and lock path match */
6045 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006046 }
drh7ed97b92010-01-20 13:07:21 +00006047 }
6048
6049 /* if the conch isn't writable and doesn't match, we can't take it */
6050 if( (conchFile->openFlags&O_RDWR) == 0 ){
6051 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006052 goto end_takeconch;
6053 }
drh7ed97b92010-01-20 13:07:21 +00006054
6055 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006056 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006057 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6058 tempLockPath = lockPath;
6059 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006060 }
drh7ed97b92010-01-20 13:07:21 +00006061
6062 /* update conch with host and path (this will fail if other process
6063 ** has a shared lock already), if the host id matches, use the big
6064 ** stick.
drh715ff302008-12-03 22:32:44 +00006065 */
drh7ed97b92010-01-20 13:07:21 +00006066 futimes(conchFile->h, NULL);
6067 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006068 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006069 /* We are trying for an exclusive lock but another thread in this
6070 ** same process is still holding a shared lock. */
6071 rc = SQLITE_BUSY;
6072 } else {
6073 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006074 }
drh715ff302008-12-03 22:32:44 +00006075 }else{
drh7ed97b92010-01-20 13:07:21 +00006076 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006077 }
drh7ed97b92010-01-20 13:07:21 +00006078 if( rc==SQLITE_OK ){
6079 char writeBuffer[PROXY_MAXCONCHLEN];
6080 int writeSize = 0;
6081
6082 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6083 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6084 if( pCtx->lockProxyPath!=NULL ){
6085 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6086 }else{
6087 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6088 }
6089 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006090 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006091 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6092 fsync(conchFile->h);
6093 /* If we created a new conch file (not just updated the contents of a
6094 ** valid conch file), try to match the permissions of the database
6095 */
6096 if( rc==SQLITE_OK && createConch ){
6097 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006098 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006099 if( err==0 ){
6100 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6101 S_IROTH|S_IWOTH);
6102 /* try to match the database file R/W permissions, ignore failure */
6103#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006104 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006105#else
drhff812312011-02-23 13:33:46 +00006106 do{
drhe562be52011-03-02 18:01:10 +00006107 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006108 }while( rc==(-1) && errno==EINTR );
6109 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006110 int code = errno;
6111 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6112 cmode, code, strerror(code));
6113 } else {
6114 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6115 }
6116 }else{
6117 int code = errno;
6118 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6119 err, code, strerror(code));
6120#endif
6121 }
drh715ff302008-12-03 22:32:44 +00006122 }
6123 }
drh7ed97b92010-01-20 13:07:21 +00006124 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6125
6126 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006127 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006128 if( rc==SQLITE_OK && pFile->openFlags ){
6129 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006130 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006131 }
6132 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006133 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006134 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006135 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006136 if( fd>=0 ){
6137 pFile->h = fd;
6138 }else{
drh9978c972010-02-23 17:36:32 +00006139 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006140 during locking */
6141 }
6142 }
6143 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6144 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6145 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6146 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6147 /* we couldn't create the proxy lock file with the old lock file path
6148 ** so try again via auto-naming
6149 */
6150 forceNewLockPath = 1;
6151 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006152 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006153 }
6154 }
6155 if( rc==SQLITE_OK ){
6156 /* Need to make a copy of path if we extracted the value
6157 ** from the conch file or the path was allocated on the stack
6158 */
6159 if( tempLockPath ){
6160 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6161 if( !pCtx->lockProxyPath ){
6162 rc = SQLITE_NOMEM;
6163 }
6164 }
6165 }
6166 if( rc==SQLITE_OK ){
6167 pCtx->conchHeld = 1;
6168
6169 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6170 afpLockingContext *afpCtx;
6171 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6172 afpCtx->dbPath = pCtx->lockProxyPath;
6173 }
6174 } else {
6175 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6176 }
drh308c2a52010-05-14 11:30:18 +00006177 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6178 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006179 return rc;
drh308c2a52010-05-14 11:30:18 +00006180 } while (1); /* in case we need to retry the :auto: lock file -
6181 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006182 }
6183}
6184
6185/*
6186** If pFile holds a lock on a conch file, then release that lock.
6187*/
6188static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006189 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006190 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6191 unixFile *conchFile; /* Name of the conch file */
6192
6193 pCtx = (proxyLockingContext *)pFile->lockingContext;
6194 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006195 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006196 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006197 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006198 if( pCtx->conchHeld>0 ){
6199 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6200 }
drh715ff302008-12-03 22:32:44 +00006201 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006202 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6203 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006204 return rc;
6205}
6206
6207/*
6208** Given the name of a database file, compute the name of its conch file.
6209** Store the conch filename in memory obtained from sqlite3_malloc().
6210** Make *pConchPath point to the new name. Return SQLITE_OK on success
6211** or SQLITE_NOMEM if unable to obtain memory.
6212**
6213** The caller is responsible for ensuring that the allocated memory
6214** space is eventually freed.
6215**
6216** *pConchPath is set to NULL if a memory allocation error occurs.
6217*/
6218static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6219 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006220 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006221 char *conchPath; /* buffer in which to construct conch name */
6222
6223 /* Allocate space for the conch filename and initialize the name to
6224 ** the name of the original database file. */
6225 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6226 if( conchPath==0 ){
6227 return SQLITE_NOMEM;
6228 }
6229 memcpy(conchPath, dbPath, len+1);
6230
6231 /* now insert a "." before the last / character */
6232 for( i=(len-1); i>=0; i-- ){
6233 if( conchPath[i]=='/' ){
6234 i++;
6235 break;
6236 }
6237 }
6238 conchPath[i]='.';
6239 while ( i<len ){
6240 conchPath[i+1]=dbPath[i];
6241 i++;
6242 }
6243
6244 /* append the "-conch" suffix to the file */
6245 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006246 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006247
6248 return SQLITE_OK;
6249}
6250
6251
6252/* Takes a fully configured proxy locking-style unix file and switches
6253** the local lock file path
6254*/
6255static int switchLockProxyPath(unixFile *pFile, const char *path) {
6256 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6257 char *oldPath = pCtx->lockProxyPath;
6258 int rc = SQLITE_OK;
6259
drh308c2a52010-05-14 11:30:18 +00006260 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006261 return SQLITE_BUSY;
6262 }
6263
6264 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6265 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6266 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6267 return SQLITE_OK;
6268 }else{
6269 unixFile *lockProxy = pCtx->lockProxy;
6270 pCtx->lockProxy=NULL;
6271 pCtx->conchHeld = 0;
6272 if( lockProxy!=NULL ){
6273 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6274 if( rc ) return rc;
6275 sqlite3_free(lockProxy);
6276 }
6277 sqlite3_free(oldPath);
6278 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6279 }
6280
6281 return rc;
6282}
6283
6284/*
6285** pFile is a file that has been opened by a prior xOpen call. dbPath
6286** is a string buffer at least MAXPATHLEN+1 characters in size.
6287**
6288** This routine find the filename associated with pFile and writes it
6289** int dbPath.
6290*/
6291static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006292#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006293 if( pFile->pMethod == &afpIoMethods ){
6294 /* afp style keeps a reference to the db path in the filePath field
6295 ** of the struct */
drhea678832008-12-10 19:26:22 +00006296 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006297 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6298 } else
drh715ff302008-12-03 22:32:44 +00006299#endif
6300 if( pFile->pMethod == &dotlockIoMethods ){
6301 /* dot lock style uses the locking context to store the dot lock
6302 ** file path */
6303 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6304 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6305 }else{
6306 /* all other styles use the locking context to store the db file path */
6307 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006308 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006309 }
6310 return SQLITE_OK;
6311}
6312
6313/*
6314** Takes an already filled in unix file and alters it so all file locking
6315** will be performed on the local proxy lock file. The following fields
6316** are preserved in the locking context so that they can be restored and
6317** the unix structure properly cleaned up at close time:
6318** ->lockingContext
6319** ->pMethod
6320*/
6321static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6322 proxyLockingContext *pCtx;
6323 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6324 char *lockPath=NULL;
6325 int rc = SQLITE_OK;
6326
drh308c2a52010-05-14 11:30:18 +00006327 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006328 return SQLITE_BUSY;
6329 }
6330 proxyGetDbPathForUnixFile(pFile, dbPath);
6331 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6332 lockPath=NULL;
6333 }else{
6334 lockPath=(char *)path;
6335 }
6336
drh308c2a52010-05-14 11:30:18 +00006337 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6338 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006339
6340 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6341 if( pCtx==0 ){
6342 return SQLITE_NOMEM;
6343 }
6344 memset(pCtx, 0, sizeof(*pCtx));
6345
6346 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6347 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006348 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6349 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6350 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6351 ** (c) the file system is read-only, then enable no-locking access.
6352 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6353 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6354 */
6355 struct statfs fsInfo;
6356 struct stat conchInfo;
6357 int goLockless = 0;
6358
drh99ab3b12011-03-02 15:09:07 +00006359 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006360 int err = errno;
6361 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6362 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6363 }
6364 }
6365 if( goLockless ){
6366 pCtx->conchHeld = -1; /* read only FS/ lockless */
6367 rc = SQLITE_OK;
6368 }
6369 }
drh715ff302008-12-03 22:32:44 +00006370 }
6371 if( rc==SQLITE_OK && lockPath ){
6372 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6373 }
6374
6375 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006376 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6377 if( pCtx->dbPath==NULL ){
6378 rc = SQLITE_NOMEM;
6379 }
6380 }
6381 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006382 /* all memory is allocated, proxys are created and assigned,
6383 ** switch the locking context and pMethod then return.
6384 */
drh715ff302008-12-03 22:32:44 +00006385 pCtx->oldLockingContext = pFile->lockingContext;
6386 pFile->lockingContext = pCtx;
6387 pCtx->pOldMethod = pFile->pMethod;
6388 pFile->pMethod = &proxyIoMethods;
6389 }else{
6390 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006391 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006392 sqlite3_free(pCtx->conchFile);
6393 }
drhd56b1212010-08-11 06:14:15 +00006394 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006395 sqlite3_free(pCtx->conchFilePath);
6396 sqlite3_free(pCtx);
6397 }
drh308c2a52010-05-14 11:30:18 +00006398 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6399 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006400 return rc;
6401}
6402
6403
6404/*
6405** This routine handles sqlite3_file_control() calls that are specific
6406** to proxy locking.
6407*/
6408static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6409 switch( op ){
6410 case SQLITE_GET_LOCKPROXYFILE: {
6411 unixFile *pFile = (unixFile*)id;
6412 if( pFile->pMethod == &proxyIoMethods ){
6413 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6414 proxyTakeConch(pFile);
6415 if( pCtx->lockProxyPath ){
6416 *(const char **)pArg = pCtx->lockProxyPath;
6417 }else{
6418 *(const char **)pArg = ":auto: (not held)";
6419 }
6420 } else {
6421 *(const char **)pArg = NULL;
6422 }
6423 return SQLITE_OK;
6424 }
6425 case SQLITE_SET_LOCKPROXYFILE: {
6426 unixFile *pFile = (unixFile*)id;
6427 int rc = SQLITE_OK;
6428 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6429 if( pArg==NULL || (const char *)pArg==0 ){
6430 if( isProxyStyle ){
6431 /* turn off proxy locking - not supported */
6432 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6433 }else{
6434 /* turn off proxy locking - already off - NOOP */
6435 rc = SQLITE_OK;
6436 }
6437 }else{
6438 const char *proxyPath = (const char *)pArg;
6439 if( isProxyStyle ){
6440 proxyLockingContext *pCtx =
6441 (proxyLockingContext*)pFile->lockingContext;
6442 if( !strcmp(pArg, ":auto:")
6443 || (pCtx->lockProxyPath &&
6444 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6445 ){
6446 rc = SQLITE_OK;
6447 }else{
6448 rc = switchLockProxyPath(pFile, proxyPath);
6449 }
6450 }else{
6451 /* turn on proxy file locking */
6452 rc = proxyTransformUnixFile(pFile, proxyPath);
6453 }
6454 }
6455 return rc;
6456 }
6457 default: {
6458 assert( 0 ); /* The call assures that only valid opcodes are sent */
6459 }
6460 }
6461 /*NOTREACHED*/
6462 return SQLITE_ERROR;
6463}
6464
6465/*
6466** Within this division (the proxying locking implementation) the procedures
6467** above this point are all utilities. The lock-related methods of the
6468** proxy-locking sqlite3_io_method object follow.
6469*/
6470
6471
6472/*
6473** This routine checks if there is a RESERVED lock held on the specified
6474** file by this or any other process. If such a lock is held, set *pResOut
6475** to a non-zero value otherwise *pResOut is set to zero. The return value
6476** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6477*/
6478static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6479 unixFile *pFile = (unixFile*)id;
6480 int rc = proxyTakeConch(pFile);
6481 if( rc==SQLITE_OK ){
6482 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006483 if( pCtx->conchHeld>0 ){
6484 unixFile *proxy = pCtx->lockProxy;
6485 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6486 }else{ /* conchHeld < 0 is lockless */
6487 pResOut=0;
6488 }
drh715ff302008-12-03 22:32:44 +00006489 }
6490 return rc;
6491}
6492
6493/*
drh308c2a52010-05-14 11:30:18 +00006494** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006495** of the following:
6496**
6497** (1) SHARED_LOCK
6498** (2) RESERVED_LOCK
6499** (3) PENDING_LOCK
6500** (4) EXCLUSIVE_LOCK
6501**
6502** Sometimes when requesting one lock state, additional lock states
6503** are inserted in between. The locking might fail on one of the later
6504** transitions leaving the lock state different from what it started but
6505** still short of its goal. The following chart shows the allowed
6506** transitions and the inserted intermediate states:
6507**
6508** UNLOCKED -> SHARED
6509** SHARED -> RESERVED
6510** SHARED -> (PENDING) -> EXCLUSIVE
6511** RESERVED -> (PENDING) -> EXCLUSIVE
6512** PENDING -> EXCLUSIVE
6513**
6514** This routine will only increase a lock. Use the sqlite3OsUnlock()
6515** routine to lower a locking level.
6516*/
drh308c2a52010-05-14 11:30:18 +00006517static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006518 unixFile *pFile = (unixFile*)id;
6519 int rc = proxyTakeConch(pFile);
6520 if( rc==SQLITE_OK ){
6521 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006522 if( pCtx->conchHeld>0 ){
6523 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006524 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6525 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006526 }else{
6527 /* conchHeld < 0 is lockless */
6528 }
drh715ff302008-12-03 22:32:44 +00006529 }
6530 return rc;
6531}
6532
6533
6534/*
drh308c2a52010-05-14 11:30:18 +00006535** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006536** must be either NO_LOCK or SHARED_LOCK.
6537**
6538** If the locking level of the file descriptor is already at or below
6539** the requested locking level, this routine is a no-op.
6540*/
drh308c2a52010-05-14 11:30:18 +00006541static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006542 unixFile *pFile = (unixFile*)id;
6543 int rc = proxyTakeConch(pFile);
6544 if( rc==SQLITE_OK ){
6545 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006546 if( pCtx->conchHeld>0 ){
6547 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006548 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6549 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006550 }else{
6551 /* conchHeld < 0 is lockless */
6552 }
drh715ff302008-12-03 22:32:44 +00006553 }
6554 return rc;
6555}
6556
6557/*
6558** Close a file that uses proxy locks.
6559*/
6560static int proxyClose(sqlite3_file *id) {
6561 if( id ){
6562 unixFile *pFile = (unixFile*)id;
6563 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6564 unixFile *lockProxy = pCtx->lockProxy;
6565 unixFile *conchFile = pCtx->conchFile;
6566 int rc = SQLITE_OK;
6567
6568 if( lockProxy ){
6569 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6570 if( rc ) return rc;
6571 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6572 if( rc ) return rc;
6573 sqlite3_free(lockProxy);
6574 pCtx->lockProxy = 0;
6575 }
6576 if( conchFile ){
6577 if( pCtx->conchHeld ){
6578 rc = proxyReleaseConch(pFile);
6579 if( rc ) return rc;
6580 }
6581 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6582 if( rc ) return rc;
6583 sqlite3_free(conchFile);
6584 }
drhd56b1212010-08-11 06:14:15 +00006585 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006586 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006587 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006588 /* restore the original locking context and pMethod then close it */
6589 pFile->lockingContext = pCtx->oldLockingContext;
6590 pFile->pMethod = pCtx->pOldMethod;
6591 sqlite3_free(pCtx);
6592 return pFile->pMethod->xClose(id);
6593 }
6594 return SQLITE_OK;
6595}
6596
6597
6598
drhd2cb50b2009-01-09 21:41:17 +00006599#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006600/*
6601** The proxy locking style is intended for use with AFP filesystems.
6602** And since AFP is only supported on MacOSX, the proxy locking is also
6603** restricted to MacOSX.
6604**
6605**
6606******************* End of the proxy lock implementation **********************
6607******************************************************************************/
6608
drh734c9862008-11-28 15:37:20 +00006609/*
danielk1977e339d652008-06-28 11:23:00 +00006610** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006611**
6612** This routine registers all VFS implementations for unix-like operating
6613** systems. This routine, and the sqlite3_os_end() routine that follows,
6614** should be the only routines in this file that are visible from other
6615** files.
drh6b9d6dd2008-12-03 19:34:47 +00006616**
6617** This routine is called once during SQLite initialization and by a
6618** single thread. The memory allocation and mutex subsystems have not
6619** necessarily been initialized when this routine is called, and so they
6620** should not be used.
drh153c62c2007-08-24 03:51:33 +00006621*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006622int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006623 /*
6624 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006625 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6626 ** to the "finder" function. (pAppData is a pointer to a pointer because
6627 ** silly C90 rules prohibit a void* from being cast to a function pointer
6628 ** and so we have to go through the intermediate pointer to avoid problems
6629 ** when compiling with -pedantic-errors on GCC.)
6630 **
6631 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006632 ** finder-function. The finder-function returns a pointer to the
6633 ** sqlite_io_methods object that implements the desired locking
6634 ** behaviors. See the division above that contains the IOMETHODS
6635 ** macro for addition information on finder-functions.
6636 **
6637 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6638 ** object. But the "autolockIoFinder" available on MacOSX does a little
6639 ** more than that; it looks at the filesystem type that hosts the
6640 ** database file and tries to choose an locking method appropriate for
6641 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006642 */
drh7708e972008-11-29 00:56:52 +00006643 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006644 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006645 sizeof(unixFile), /* szOsFile */ \
6646 MAX_PATHNAME, /* mxPathname */ \
6647 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006648 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006649 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006650 unixOpen, /* xOpen */ \
6651 unixDelete, /* xDelete */ \
6652 unixAccess, /* xAccess */ \
6653 unixFullPathname, /* xFullPathname */ \
6654 unixDlOpen, /* xDlOpen */ \
6655 unixDlError, /* xDlError */ \
6656 unixDlSym, /* xDlSym */ \
6657 unixDlClose, /* xDlClose */ \
6658 unixRandomness, /* xRandomness */ \
6659 unixSleep, /* xSleep */ \
6660 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006661 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006662 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006663 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006664 unixGetSystemCall, /* xGetSystemCall */ \
6665 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006666 }
6667
drh6b9d6dd2008-12-03 19:34:47 +00006668 /*
6669 ** All default VFSes for unix are contained in the following array.
6670 **
6671 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6672 ** by the SQLite core when the VFS is registered. So the following
6673 ** array cannot be const.
6674 */
danielk1977e339d652008-06-28 11:23:00 +00006675 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006676#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006677 UNIXVFS("unix", autolockIoFinder ),
6678#else
6679 UNIXVFS("unix", posixIoFinder ),
6680#endif
6681 UNIXVFS("unix-none", nolockIoFinder ),
6682 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006683 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006684#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006685 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006686#endif
6687#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006688 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006689#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006690 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006691#endif
chw78a13182009-04-07 05:35:03 +00006692#endif
drhd2cb50b2009-01-09 21:41:17 +00006693#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006694 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006695 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006696 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006697#endif
drh153c62c2007-08-24 03:51:33 +00006698 };
drh6b9d6dd2008-12-03 19:34:47 +00006699 unsigned int i; /* Loop counter */
6700
drh2aa5a002011-04-13 13:42:25 +00006701 /* Double-check that the aSyscall[] array has been constructed
6702 ** correctly. See ticket [bb3a86e890c8e96ab] */
6703 assert( ArraySize(aSyscall)==16 );
6704
drh6b9d6dd2008-12-03 19:34:47 +00006705 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006706 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006707 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006708 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006709 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006710}
danielk1977e339d652008-06-28 11:23:00 +00006711
6712/*
drh6b9d6dd2008-12-03 19:34:47 +00006713** Shutdown the operating system interface.
6714**
6715** Some operating systems might need to do some cleanup in this routine,
6716** to release dynamically allocated objects. But not on unix.
6717** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006718*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006719int sqlite3_os_end(void){
6720 return SQLITE_OK;
6721}
drhdce8bdb2007-08-16 13:01:44 +00006722
danielk197729bafea2008-06-26 10:41:19 +00006723#endif /* SQLITE_OS_UNIX */