blob: cd8cec0046b69ad298bc791ff77e4f77c708f376 [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>
dan32c12fe2013-05-02 17:37:31 +0000122#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
drh1da88f02011-12-17 16:09:16 +0000125
danielk1977e339d652008-06-28 11:23:00 +0000126
drh40bbb0a2008-09-23 10:23:26 +0000127#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000128# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000129# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <semaphore.h>
131# include <limits.h>
132# else
drh9b35ea62008-11-29 02:20:26 +0000133# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000135# endif
drhbfe66312006-10-03 17:40:40 +0000136#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000137
drhf8b4d8c2010-03-05 13:53:22 +0000138#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000139# include <sys/mount.h>
140#endif
141
drhdbe4b882011-06-20 18:00:17 +0000142#ifdef HAVE_UTIME
143# include <utime.h>
144#endif
145
drh9cbe6352005-11-29 03:13:21 +0000146/*
drh7ed97b92010-01-20 13:07:21 +0000147** Allowed values of unixFile.fsFlags
148*/
149#define SQLITE_FSFLAGS_IS_MSDOS 0x1
150
151/*
drhf1a221e2006-01-15 17:27:17 +0000152** If we are to be thread-safe, include the pthreads header and define
153** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000154*/
drhd677b3d2007-08-20 22:48:41 +0000155#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000156# include <pthread.h>
157# define SQLITE_UNIX_THREADS 1
158#endif
159
160/*
161** Default permissions when creating a new file
162*/
163#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
164# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
165#endif
166
danielk1977b4b47412007-08-17 15:53:36 +0000167/*
drh5adc60b2012-04-14 13:25:11 +0000168** Default permissions when creating auto proxy dir
169*/
aswiftaebf4132008-11-21 00:10:35 +0000170#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
171# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
172#endif
173
174/*
danielk1977b4b47412007-08-17 15:53:36 +0000175** Maximum supported path-length.
176*/
177#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000178
drh734c9862008-11-28 15:37:20 +0000179/*
drh734c9862008-11-28 15:37:20 +0000180** Only set the lastErrno if the error code is a real error and not
181** a normal expected return code of SQLITE_BUSY or SQLITE_OK
182*/
183#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
184
drhd91c68f2010-05-14 14:52:25 +0000185/* Forward references */
186typedef struct unixShm unixShm; /* Connection shared memory */
187typedef struct unixShmNode unixShmNode; /* Shared memory instance */
188typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
189typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000190
191/*
dane946c392009-08-22 11:39:46 +0000192** Sometimes, after a file handle is closed by SQLite, the file descriptor
193** cannot be closed immediately. In these cases, instances of the following
194** structure are used to store the file descriptor while waiting for an
195** opportunity to either close or reuse it.
196*/
dane946c392009-08-22 11:39:46 +0000197struct UnixUnusedFd {
198 int fd; /* File descriptor to close */
199 int flags; /* Flags this file descriptor was opened with */
200 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
201};
202
203/*
drh9b35ea62008-11-29 02:20:26 +0000204** The unixFile structure is subclass of sqlite3_file specific to the unix
205** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000206*/
drh054889e2005-11-30 03:20:31 +0000207typedef struct unixFile unixFile;
208struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000209 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000210 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000211 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000212 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000213 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000214 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000215 int lastErrno; /* The unix errno from last I/O error */
216 void *lockingContext; /* Locking style specific state */
217 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000218 const char *zPath; /* Name of the file */
219 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000220 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000221#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000222 int nFetchOut; /* Number of outstanding xFetch refs */
223 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000224 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
225 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000226 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000227#endif
drh537dddf2012-10-26 13:46:24 +0000228#ifdef __QNXNTO__
229 int sectorSize; /* Device sector size */
230 int deviceCharacteristics; /* Precomputed device characteristics */
231#endif
drh08c6d442009-02-09 17:34:07 +0000232#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000233 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000234#endif
drh7ed97b92010-01-20 13:07:21 +0000235#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000236 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000237#endif
238#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000239 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000240#endif
drhd3d8c042012-05-29 17:02:40 +0000241#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000242 /* The next group of variables are used to track whether or not the
243 ** transaction counter in bytes 24-27 of database files are updated
244 ** whenever any part of the database changes. An assertion fault will
245 ** occur if a file is updated without also updating the transaction
246 ** counter. This test is made to avoid new problems similar to the
247 ** one described by ticket #3584.
248 */
249 unsigned char transCntrChng; /* True if the transaction counter changed */
250 unsigned char dbUpdate; /* True if any part of database file changed */
251 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000252
drh8f941bc2009-01-14 23:03:40 +0000253#endif
danf23da962013-03-23 21:00:41 +0000254
danielk1977967a4a12007-08-20 14:23:44 +0000255#ifdef SQLITE_TEST
256 /* In test mode, increase the size of this structure a bit so that
257 ** it is larger than the struct CrashFile defined in test6.c.
258 */
259 char aPadding[32];
260#endif
drh9cbe6352005-11-29 03:13:21 +0000261};
262
drh0ccebe72005-06-07 22:22:50 +0000263/*
drha7e61d82011-03-12 17:02:57 +0000264** Allowed values for the unixFile.ctrlFlags bitmask:
265*/
drhf0b190d2011-07-26 16:03:07 +0000266#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
267#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
268#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000269#ifndef SQLITE_DISABLE_DIRSYNC
270# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
271#else
272# define UNIXFILE_DIRSYNC 0x00
273#endif
drhcb15f352011-12-23 01:04:17 +0000274#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000275#define UNIXFILE_DELETE 0x20 /* Delete on close */
276#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
277#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhfbc7e882013-04-11 01:16:15 +0000278#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
drha7e61d82011-03-12 17:02:57 +0000279
280/*
drh198bf392006-01-06 21:52:49 +0000281** Include code that is common to all os_*.c files
282*/
283#include "os_common.h"
284
285/*
drh0ccebe72005-06-07 22:22:50 +0000286** Define various macros that are missing from some systems.
287*/
drhbbd42a62004-05-22 17:41:58 +0000288#ifndef O_LARGEFILE
289# define O_LARGEFILE 0
290#endif
291#ifdef SQLITE_DISABLE_LFS
292# undef O_LARGEFILE
293# define O_LARGEFILE 0
294#endif
295#ifndef O_NOFOLLOW
296# define O_NOFOLLOW 0
297#endif
298#ifndef O_BINARY
299# define O_BINARY 0
300#endif
301
302/*
drh2b4b5962005-06-15 17:47:55 +0000303** The threadid macro resolves to the thread-id or to 0. Used for
304** testing and debugging only.
305*/
drhd677b3d2007-08-20 22:48:41 +0000306#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000307#define threadid pthread_self()
308#else
309#define threadid 0
310#endif
311
drh99ab3b12011-03-02 15:09:07 +0000312/*
dane6ecd662013-04-01 17:56:59 +0000313** HAVE_MREMAP defaults to true on Linux and false everywhere else.
314*/
315#if !defined(HAVE_MREMAP)
316# if defined(__linux__) && defined(_GNU_SOURCE)
317# define HAVE_MREMAP 1
318# else
319# define HAVE_MREMAP 0
320# endif
321#endif
322
323/*
drh9a3baf12011-04-25 18:01:27 +0000324** Different Unix systems declare open() in different ways. Same use
325** open(const char*,int,mode_t). Others use open(const char*,int,...).
326** The difference is important when using a pointer to the function.
327**
328** The safest way to deal with the problem is to always use this wrapper
329** which always has the same well-defined interface.
330*/
331static int posixOpen(const char *zFile, int flags, int mode){
332 return open(zFile, flags, mode);
333}
334
drhed466822012-05-31 13:10:49 +0000335/*
336** On some systems, calls to fchown() will trigger a message in a security
337** log if they come from non-root processes. So avoid calling fchown() if
338** we are not running as root.
339*/
340static int posixFchown(int fd, uid_t uid, gid_t gid){
341 return geteuid() ? 0 : fchown(fd,uid,gid);
342}
343
drh90315a22011-08-10 01:52:12 +0000344/* Forward reference */
345static int openDirectory(const char*, int*);
346
drh9a3baf12011-04-25 18:01:27 +0000347/*
drh99ab3b12011-03-02 15:09:07 +0000348** Many system calls are accessed through pointer-to-functions so that
349** they may be overridden at runtime to facilitate fault injection during
350** testing and sandboxing. The following array holds the names and pointers
351** to all overrideable system calls.
352*/
353static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000354 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000355 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
356 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000357} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000358 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
359#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000360
drh58ad5802011-03-23 22:02:23 +0000361 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000362#define osClose ((int(*)(int))aSyscall[1].pCurrent)
363
drh58ad5802011-03-23 22:02:23 +0000364 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000365#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
366
drh58ad5802011-03-23 22:02:23 +0000367 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
369
drh58ad5802011-03-23 22:02:23 +0000370 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
372
373/*
374** The DJGPP compiler environment looks mostly like Unix, but it
375** lacks the fcntl() system call. So redefine fcntl() to be something
376** that always succeeds. This means that locking does not occur under
377** DJGPP. But it is DOS - what did you expect?
378*/
379#ifdef __DJGPP__
380 { "fstat", 0, 0 },
381#define osFstat(a,b,c) 0
382#else
drh58ad5802011-03-23 22:02:23 +0000383 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000384#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
385#endif
386
drh58ad5802011-03-23 22:02:23 +0000387 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000388#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
389
drh58ad5802011-03-23 22:02:23 +0000390 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000391#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000392
drh58ad5802011-03-23 22:02:23 +0000393 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000394#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
395
drhd4a80312011-04-15 14:33:20 +0000396#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000397 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000398#else
drh58ad5802011-03-23 22:02:23 +0000399 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000400#endif
401#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
402
403#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000404 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000405#else
drh58ad5802011-03-23 22:02:23 +0000406 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000407#endif
408#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
409
drh58ad5802011-03-23 22:02:23 +0000410 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000411#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
412
drhd4a80312011-04-15 14:33:20 +0000413#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000414 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000415#else
drh58ad5802011-03-23 22:02:23 +0000416 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000417#endif
418#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
419 aSyscall[12].pCurrent)
420
421#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000422 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000423#else
drh58ad5802011-03-23 22:02:23 +0000424 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000425#endif
426#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
427 aSyscall[13].pCurrent)
428
drh58ad5802011-03-23 22:02:23 +0000429 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000430#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000431
432#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000433 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000434#else
drh58ad5802011-03-23 22:02:23 +0000435 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000436#endif
dan0fd7d862011-03-29 10:04:23 +0000437#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000438
drh036ac7f2011-08-08 23:18:05 +0000439 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
440#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
441
drh90315a22011-08-10 01:52:12 +0000442 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
443#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
444
drh9ef6bc42011-11-04 02:24:02 +0000445 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
446#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
447
448 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
449#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
450
drhed466822012-05-31 13:10:49 +0000451 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000452#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000453
dan4dd51442013-08-26 14:30:25 +0000454#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000455 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
456#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
457
drhd1ab8062013-03-25 20:50:25 +0000458 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
459#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
460
dane6ecd662013-04-01 17:56:59 +0000461#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000462 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
463#else
464 { "mremap", (sqlite3_syscall_ptr)0, 0 },
465#endif
466#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
dan4dd51442013-08-26 14:30:25 +0000467#endif
drhd1ab8062013-03-25 20:50:25 +0000468
drhe562be52011-03-02 18:01:10 +0000469}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000470
471/*
472** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000473** "unix" VFSes. Return SQLITE_OK opon successfully updating the
474** system call pointer, or SQLITE_NOTFOUND if there is no configurable
475** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000476*/
477static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000478 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
479 const char *zName, /* Name of system call to override */
480 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000481){
drh58ad5802011-03-23 22:02:23 +0000482 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000483 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000484
485 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000486 if( zName==0 ){
487 /* If no zName is given, restore all system calls to their default
488 ** settings and return NULL
489 */
dan51438a72011-04-02 17:00:47 +0000490 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000491 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
492 if( aSyscall[i].pDefault ){
493 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000494 }
495 }
496 }else{
497 /* If zName is specified, operate on only the one system call
498 ** specified.
499 */
500 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
501 if( strcmp(zName, aSyscall[i].zName)==0 ){
502 if( aSyscall[i].pDefault==0 ){
503 aSyscall[i].pDefault = aSyscall[i].pCurrent;
504 }
drh1df30962011-03-02 19:06:42 +0000505 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000506 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
507 aSyscall[i].pCurrent = pNewFunc;
508 break;
509 }
510 }
511 }
512 return rc;
513}
514
drh1df30962011-03-02 19:06:42 +0000515/*
516** Return the value of a system call. Return NULL if zName is not a
517** recognized system call name. NULL is also returned if the system call
518** is currently undefined.
519*/
drh58ad5802011-03-23 22:02:23 +0000520static sqlite3_syscall_ptr unixGetSystemCall(
521 sqlite3_vfs *pNotUsed,
522 const char *zName
523){
524 unsigned int i;
525
526 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000527 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
528 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
529 }
530 return 0;
531}
532
533/*
534** Return the name of the first system call after zName. If zName==NULL
535** then return the name of the first system call. Return NULL if zName
536** is the last system call or if zName is not the name of a valid
537** system call.
538*/
539static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000540 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000541
542 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000543 if( zName ){
544 for(i=0; i<ArraySize(aSyscall)-1; i++){
545 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000546 }
547 }
dan0fd7d862011-03-29 10:04:23 +0000548 for(i++; i<ArraySize(aSyscall); i++){
549 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000550 }
551 return 0;
552}
553
drhad4f1e52011-03-04 15:43:57 +0000554/*
drh77a3fdc2013-08-30 14:24:12 +0000555** Do not accept any file descriptor less than this value, in order to avoid
556** opening database file using file descriptors that are commonly used for
557** standard input, output, and error.
558*/
559#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
560# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
561#endif
562
563/*
drh8c815d12012-02-13 20:16:37 +0000564** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000565** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000566**
567** If the file creation mode "m" is 0 then set it to the default for
568** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
569** 0644) as modified by the system umask. If m is not 0, then
570** make the file creation mode be exactly m ignoring the umask.
571**
572** The m parameter will be non-zero only when creating -wal, -journal,
573** and -shm files. We want those files to have *exactly* the same
574** permissions as their original database, unadulterated by the umask.
575** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
576** transaction crashes and leaves behind hot journals, then any
577** process that is able to write to the database will also be able to
578** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000579*/
drh8c815d12012-02-13 20:16:37 +0000580static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000581 int fd;
drhe1186ab2013-01-04 20:45:13 +0000582 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000583 while(1){
drh5adc60b2012-04-14 13:25:11 +0000584#if defined(O_CLOEXEC)
585 fd = osOpen(z,f|O_CLOEXEC,m2);
586#else
587 fd = osOpen(z,f,m2);
588#endif
drh5128d002013-08-30 06:20:23 +0000589 if( fd<0 ){
590 if( errno==EINTR ) continue;
591 break;
592 }
drh77a3fdc2013-08-30 14:24:12 +0000593 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000594 osClose(fd);
595 sqlite3_log(SQLITE_WARNING,
596 "attempt to open \"%s\" as file descriptor %d", z, fd);
597 fd = -1;
598 if( osOpen("/dev/null", f, m)<0 ) break;
599 }
drhe1186ab2013-01-04 20:45:13 +0000600 if( fd>=0 ){
601 if( m!=0 ){
602 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000603 if( osFstat(fd, &statbuf)==0
604 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000605 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000606 ){
drhe1186ab2013-01-04 20:45:13 +0000607 osFchmod(fd, m);
608 }
609 }
drh5adc60b2012-04-14 13:25:11 +0000610#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000611 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000612#endif
drhe1186ab2013-01-04 20:45:13 +0000613 }
drh5adc60b2012-04-14 13:25:11 +0000614 return fd;
drhad4f1e52011-03-04 15:43:57 +0000615}
danielk197713adf8a2004-06-03 16:08:41 +0000616
drh107886a2008-11-21 22:21:50 +0000617/*
dan9359c7b2009-08-21 08:29:10 +0000618** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000619** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000620** vxworksFileId objects used by this file, all of which may be
621** shared by multiple threads.
622**
623** Function unixMutexHeld() is used to assert() that the global mutex
624** is held when required. This function is only used as part of assert()
625** statements. e.g.
626**
627** unixEnterMutex()
628** assert( unixMutexHeld() );
629** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000630*/
631static void unixEnterMutex(void){
632 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
633}
634static void unixLeaveMutex(void){
635 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
636}
dan9359c7b2009-08-21 08:29:10 +0000637#ifdef SQLITE_DEBUG
638static int unixMutexHeld(void) {
639 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
640}
641#endif
drh107886a2008-11-21 22:21:50 +0000642
drh734c9862008-11-28 15:37:20 +0000643
drh30ddce62011-10-15 00:16:30 +0000644#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000645/*
646** Helper function for printing out trace information from debugging
647** binaries. This returns the string represetation of the supplied
648** integer lock-type.
649*/
drh308c2a52010-05-14 11:30:18 +0000650static const char *azFileLock(int eFileLock){
651 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000652 case NO_LOCK: return "NONE";
653 case SHARED_LOCK: return "SHARED";
654 case RESERVED_LOCK: return "RESERVED";
655 case PENDING_LOCK: return "PENDING";
656 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000657 }
658 return "ERROR";
659}
660#endif
661
662#ifdef SQLITE_LOCK_TRACE
663/*
664** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000665**
drh734c9862008-11-28 15:37:20 +0000666** This routine is used for troubleshooting locks on multithreaded
667** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
668** command-line option on the compiler. This code is normally
669** turned off.
670*/
671static int lockTrace(int fd, int op, struct flock *p){
672 char *zOpName, *zType;
673 int s;
674 int savedErrno;
675 if( op==F_GETLK ){
676 zOpName = "GETLK";
677 }else if( op==F_SETLK ){
678 zOpName = "SETLK";
679 }else{
drh99ab3b12011-03-02 15:09:07 +0000680 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000681 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
682 return s;
683 }
684 if( p->l_type==F_RDLCK ){
685 zType = "RDLCK";
686 }else if( p->l_type==F_WRLCK ){
687 zType = "WRLCK";
688 }else if( p->l_type==F_UNLCK ){
689 zType = "UNLCK";
690 }else{
691 assert( 0 );
692 }
693 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000694 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000695 savedErrno = errno;
696 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
697 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
698 (int)p->l_pid, s);
699 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
700 struct flock l2;
701 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000702 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000703 if( l2.l_type==F_RDLCK ){
704 zType = "RDLCK";
705 }else if( l2.l_type==F_WRLCK ){
706 zType = "WRLCK";
707 }else if( l2.l_type==F_UNLCK ){
708 zType = "UNLCK";
709 }else{
710 assert( 0 );
711 }
712 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
713 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
714 }
715 errno = savedErrno;
716 return s;
717}
drh99ab3b12011-03-02 15:09:07 +0000718#undef osFcntl
719#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000720#endif /* SQLITE_LOCK_TRACE */
721
drhff812312011-02-23 13:33:46 +0000722/*
723** Retry ftruncate() calls that fail due to EINTR
724*/
drhff812312011-02-23 13:33:46 +0000725static int robust_ftruncate(int h, sqlite3_int64 sz){
726 int rc;
drh99ab3b12011-03-02 15:09:07 +0000727 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000728 return rc;
729}
drh734c9862008-11-28 15:37:20 +0000730
731/*
732** This routine translates a standard POSIX errno code into something
733** useful to the clients of the sqlite3 functions. Specifically, it is
734** intended to translate a variety of "try again" errors into SQLITE_BUSY
735** and a variety of "please close the file descriptor NOW" errors into
736** SQLITE_IOERR
737**
738** Errors during initialization of locks, or file system support for locks,
739** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
740*/
741static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
742 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000743#if 0
744 /* At one point this code was not commented out. In theory, this branch
745 ** should never be hit, as this function should only be called after
746 ** a locking-related function (i.e. fcntl()) has returned non-zero with
747 ** the value of errno as the first argument. Since a system call has failed,
748 ** errno should be non-zero.
749 **
750 ** Despite this, if errno really is zero, we still don't want to return
751 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
752 ** propagated back to the caller. Commenting this branch out means errno==0
753 ** will be handled by the "default:" case below.
754 */
drh734c9862008-11-28 15:37:20 +0000755 case 0:
756 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000757#endif
758
drh734c9862008-11-28 15:37:20 +0000759 case EAGAIN:
760 case ETIMEDOUT:
761 case EBUSY:
762 case EINTR:
763 case ENOLCK:
764 /* random NFS retry error, unless during file system support
765 * introspection, in which it actually means what it says */
766 return SQLITE_BUSY;
767
768 case EACCES:
769 /* EACCES is like EAGAIN during locking operations, but not any other time*/
770 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000771 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
772 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
773 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000774 return SQLITE_BUSY;
775 }
776 /* else fall through */
777 case EPERM:
778 return SQLITE_PERM;
779
danea83bc62011-04-01 11:56:32 +0000780 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
781 ** this module never makes such a call. And the code in SQLite itself
782 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
783 ** this case is also commented out. If the system does set errno to EDEADLK,
784 ** the default SQLITE_IOERR_XXX code will be returned. */
785#if 0
drh734c9862008-11-28 15:37:20 +0000786 case EDEADLK:
787 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000788#endif
drh734c9862008-11-28 15:37:20 +0000789
790#if EOPNOTSUPP!=ENOTSUP
791 case EOPNOTSUPP:
792 /* something went terribly awry, unless during file system support
793 * introspection, in which it actually means what it says */
794#endif
795#ifdef ENOTSUP
796 case ENOTSUP:
797 /* invalid fd, unless during file system support introspection, in which
798 * it actually means what it says */
799#endif
800 case EIO:
801 case EBADF:
802 case EINVAL:
803 case ENOTCONN:
804 case ENODEV:
805 case ENXIO:
806 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000807#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000808 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000809#endif
drh734c9862008-11-28 15:37:20 +0000810 case ENOSYS:
811 /* these should force the client to close the file and reconnect */
812
813 default:
814 return sqliteIOErr;
815 }
816}
817
818
drh734c9862008-11-28 15:37:20 +0000819/******************************************************************************
820****************** Begin Unique File ID Utility Used By VxWorks ***************
821**
822** On most versions of unix, we can get a unique ID for a file by concatenating
823** the device number and the inode number. But this does not work on VxWorks.
824** On VxWorks, a unique file id must be based on the canonical filename.
825**
826** A pointer to an instance of the following structure can be used as a
827** unique file ID in VxWorks. Each instance of this structure contains
828** a copy of the canonical filename. There is also a reference count.
829** The structure is reclaimed when the number of pointers to it drops to
830** zero.
831**
832** There are never very many files open at one time and lookups are not
833** a performance-critical path, so it is sufficient to put these
834** structures on a linked list.
835*/
836struct vxworksFileId {
837 struct vxworksFileId *pNext; /* Next in a list of them all */
838 int nRef; /* Number of references to this one */
839 int nName; /* Length of the zCanonicalName[] string */
840 char *zCanonicalName; /* Canonical filename */
841};
842
843#if OS_VXWORKS
844/*
drh9b35ea62008-11-29 02:20:26 +0000845** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000846** variable:
847*/
848static struct vxworksFileId *vxworksFileList = 0;
849
850/*
851** Simplify a filename into its canonical form
852** by making the following changes:
853**
854** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000855** * convert /./ into just /
856** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000857**
858** Changes are made in-place. Return the new name length.
859**
860** The original filename is in z[0..n-1]. Return the number of
861** characters in the simplified name.
862*/
863static int vxworksSimplifyName(char *z, int n){
864 int i, j;
865 while( n>1 && z[n-1]=='/' ){ n--; }
866 for(i=j=0; i<n; i++){
867 if( z[i]=='/' ){
868 if( z[i+1]=='/' ) continue;
869 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
870 i += 1;
871 continue;
872 }
873 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
874 while( j>0 && z[j-1]!='/' ){ j--; }
875 if( j>0 ){ j--; }
876 i += 2;
877 continue;
878 }
879 }
880 z[j++] = z[i];
881 }
882 z[j] = 0;
883 return j;
884}
885
886/*
887** Find a unique file ID for the given absolute pathname. Return
888** a pointer to the vxworksFileId object. This pointer is the unique
889** file ID.
890**
891** The nRef field of the vxworksFileId object is incremented before
892** the object is returned. A new vxworksFileId object is created
893** and added to the global list if necessary.
894**
895** If a memory allocation error occurs, return NULL.
896*/
897static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
898 struct vxworksFileId *pNew; /* search key and new file ID */
899 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
900 int n; /* Length of zAbsoluteName string */
901
902 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000903 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000904 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
905 if( pNew==0 ) return 0;
906 pNew->zCanonicalName = (char*)&pNew[1];
907 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
908 n = vxworksSimplifyName(pNew->zCanonicalName, n);
909
910 /* Search for an existing entry that matching the canonical name.
911 ** If found, increment the reference count and return a pointer to
912 ** the existing file ID.
913 */
914 unixEnterMutex();
915 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
916 if( pCandidate->nName==n
917 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
918 ){
919 sqlite3_free(pNew);
920 pCandidate->nRef++;
921 unixLeaveMutex();
922 return pCandidate;
923 }
924 }
925
926 /* No match was found. We will make a new file ID */
927 pNew->nRef = 1;
928 pNew->nName = n;
929 pNew->pNext = vxworksFileList;
930 vxworksFileList = pNew;
931 unixLeaveMutex();
932 return pNew;
933}
934
935/*
936** Decrement the reference count on a vxworksFileId object. Free
937** the object when the reference count reaches zero.
938*/
939static void vxworksReleaseFileId(struct vxworksFileId *pId){
940 unixEnterMutex();
941 assert( pId->nRef>0 );
942 pId->nRef--;
943 if( pId->nRef==0 ){
944 struct vxworksFileId **pp;
945 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
946 assert( *pp==pId );
947 *pp = pId->pNext;
948 sqlite3_free(pId);
949 }
950 unixLeaveMutex();
951}
952#endif /* OS_VXWORKS */
953/*************** End of Unique File ID Utility Used By VxWorks ****************
954******************************************************************************/
955
956
957/******************************************************************************
958*************************** Posix Advisory Locking ****************************
959**
drh9b35ea62008-11-29 02:20:26 +0000960** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000961** section 6.5.2.2 lines 483 through 490 specify that when a process
962** sets or clears a lock, that operation overrides any prior locks set
963** by the same process. It does not explicitly say so, but this implies
964** that it overrides locks set by the same process using a different
965** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000966**
967** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000968** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
969**
970** Suppose ./file1 and ./file2 are really the same file (because
971** one is a hard or symbolic link to the other) then if you set
972** an exclusive lock on fd1, then try to get an exclusive lock
973** on fd2, it works. I would have expected the second lock to
974** fail since there was already a lock on the file due to fd1.
975** But not so. Since both locks came from the same process, the
976** second overrides the first, even though they were on different
977** file descriptors opened on different file names.
978**
drh734c9862008-11-28 15:37:20 +0000979** This means that we cannot use POSIX locks to synchronize file access
980** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000981** to synchronize access for threads in separate processes, but not
982** threads within the same process.
983**
984** To work around the problem, SQLite has to manage file locks internally
985** on its own. Whenever a new database is opened, we have to find the
986** specific inode of the database file (the inode is determined by the
987** st_dev and st_ino fields of the stat structure that fstat() fills in)
988** and check for locks already existing on that inode. When locks are
989** created or removed, we have to look at our own internal record of the
990** locks to see if another thread has previously set a lock on that same
991** inode.
992**
drh9b35ea62008-11-29 02:20:26 +0000993** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
994** For VxWorks, we have to use the alternative unique ID system based on
995** canonical filename and implemented in the previous division.)
996**
danielk1977ad94b582007-08-20 06:44:22 +0000997** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000998** descriptor. It is now a structure that holds the integer file
999** descriptor and a pointer to a structure that describes the internal
1000** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001001** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001002** point to the same locking structure. The locking structure keeps
1003** a reference count (so we will know when to delete it) and a "cnt"
1004** field that tells us its internal lock status. cnt==0 means the
1005** file is unlocked. cnt==-1 means the file has an exclusive lock.
1006** cnt>0 means there are cnt shared locks on the file.
1007**
1008** Any attempt to lock or unlock a file first checks the locking
1009** structure. The fcntl() system call is only invoked to set a
1010** POSIX lock if the internal lock structure transitions between
1011** a locked and an unlocked state.
1012**
drh734c9862008-11-28 15:37:20 +00001013** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001014**
1015** If you close a file descriptor that points to a file that has locks,
1016** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001017** released. To work around this problem, each unixInodeInfo object
1018** maintains a count of the number of pending locks on tha inode.
1019** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001020** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001021** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001022** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001023** be closed and that list is walked (and cleared) when the last lock
1024** clears.
1025**
drh9b35ea62008-11-29 02:20:26 +00001026** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001027**
drh9b35ea62008-11-29 02:20:26 +00001028** Many older versions of linux use the LinuxThreads library which is
1029** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001030** A cannot be modified or overridden by a different thread B.
1031** Only thread A can modify the lock. Locking behavior is correct
1032** if the appliation uses the newer Native Posix Thread Library (NPTL)
1033** on linux - with NPTL a lock created by thread A can override locks
1034** in thread B. But there is no way to know at compile-time which
1035** threading library is being used. So there is no way to know at
1036** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001037** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001038** current process.
drh5fdae772004-06-29 03:29:00 +00001039**
drh8af6c222010-05-14 12:43:01 +00001040** SQLite used to support LinuxThreads. But support for LinuxThreads
1041** was dropped beginning with version 3.7.0. SQLite will still work with
1042** LinuxThreads provided that (1) there is no more than one connection
1043** per database file in the same process and (2) database connections
1044** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001045*/
1046
1047/*
1048** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001049** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001050*/
1051struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001052 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001053#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001054 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001055#else
drh107886a2008-11-21 22:21:50 +00001056 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001057#endif
1058};
1059
1060/*
drhbbd42a62004-05-22 17:41:58 +00001061** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001062** inode. Or, on LinuxThreads, there is one of these structures for
1063** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001064**
danielk1977ad94b582007-08-20 06:44:22 +00001065** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001066** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001067** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001068*/
drh8af6c222010-05-14 12:43:01 +00001069struct unixInodeInfo {
1070 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001071 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001072 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1073 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001074 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001075 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1076 int nLock; /* Number of outstanding file locks */
1077 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1078 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1079 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001080#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001081 unsigned long long sharedByte; /* for AFP simulated shared lock */
1082#endif
drh6c7d5c52008-11-21 20:32:33 +00001083#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001084 sem_t *pSem; /* Named POSIX semaphore */
1085 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001086#endif
drhbbd42a62004-05-22 17:41:58 +00001087};
1088
drhda0e7682008-07-30 15:27:54 +00001089/*
drh8af6c222010-05-14 12:43:01 +00001090** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001091*/
drhd91c68f2010-05-14 14:52:25 +00001092static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001093
drh5fdae772004-06-29 03:29:00 +00001094/*
dane18d4952011-02-21 11:46:24 +00001095**
1096** This function - unixLogError_x(), is only ever called via the macro
1097** unixLogError().
1098**
1099** It is invoked after an error occurs in an OS function and errno has been
1100** set. It logs a message using sqlite3_log() containing the current value of
1101** errno and, if possible, the human-readable equivalent from strerror() or
1102** strerror_r().
1103**
1104** The first argument passed to the macro should be the error code that
1105** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1106** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001107** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001108** if any.
1109*/
drh0e9365c2011-03-02 02:08:13 +00001110#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1111static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001112 int errcode, /* SQLite error code */
1113 const char *zFunc, /* Name of OS function that failed */
1114 const char *zPath, /* File path associated with error */
1115 int iLine /* Source line number where error occurred */
1116){
1117 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001118 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001119
1120 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1121 ** the strerror() function to obtain the human-readable error message
1122 ** equivalent to errno. Otherwise, use strerror_r().
1123 */
1124#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1125 char aErr[80];
1126 memset(aErr, 0, sizeof(aErr));
1127 zErr = aErr;
1128
1129 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001130 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001131 ** returns a pointer to a buffer containing the error message. That pointer
1132 ** may point to aErr[], or it may point to some static storage somewhere.
1133 ** Otherwise, assume that the system provides the POSIX version of
1134 ** strerror_r(), which always writes an error message into aErr[].
1135 **
1136 ** If the code incorrectly assumes that it is the POSIX version that is
1137 ** available, the error message will often be an empty string. Not a
1138 ** huge problem. Incorrectly concluding that the GNU version is available
1139 ** could lead to a segfault though.
1140 */
1141#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1142 zErr =
1143# endif
drh0e9365c2011-03-02 02:08:13 +00001144 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001145
1146#elif SQLITE_THREADSAFE
1147 /* This is a threadsafe build, but strerror_r() is not available. */
1148 zErr = "";
1149#else
1150 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001151 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001152#endif
1153
drh0e9365c2011-03-02 02:08:13 +00001154 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001155 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001156 "os_unix.c:%d: (%d) %s(%s) - %s",
1157 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001158 );
1159
1160 return errcode;
1161}
1162
drh0e9365c2011-03-02 02:08:13 +00001163/*
1164** Close a file descriptor.
1165**
1166** We assume that close() almost always works, since it is only in a
1167** very sick application or on a very sick platform that it might fail.
1168** If it does fail, simply leak the file descriptor, but do log the
1169** error.
1170**
1171** Note that it is not safe to retry close() after EINTR since the
1172** file descriptor might have already been reused by another thread.
1173** So we don't even try to recover from an EINTR. Just log the error
1174** and move on.
1175*/
1176static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001177 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001178 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1179 pFile ? pFile->zPath : 0, lineno);
1180 }
1181}
dane18d4952011-02-21 11:46:24 +00001182
1183/*
danb0ac3e32010-06-16 10:55:42 +00001184** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001185*/
drh0e9365c2011-03-02 02:08:13 +00001186static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001187 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001188 UnixUnusedFd *p;
1189 UnixUnusedFd *pNext;
1190 for(p=pInode->pUnused; p; p=pNext){
1191 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001192 robust_close(pFile, p->fd, __LINE__);
1193 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001194 }
drh0e9365c2011-03-02 02:08:13 +00001195 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001196}
1197
1198/*
drh8af6c222010-05-14 12:43:01 +00001199** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001200**
1201** The mutex entered using the unixEnterMutex() function must be held
1202** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001203*/
danb0ac3e32010-06-16 10:55:42 +00001204static void releaseInodeInfo(unixFile *pFile){
1205 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001206 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001207 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001208 pInode->nRef--;
1209 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001210 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001211 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001212 if( pInode->pPrev ){
1213 assert( pInode->pPrev->pNext==pInode );
1214 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001215 }else{
drh8af6c222010-05-14 12:43:01 +00001216 assert( inodeList==pInode );
1217 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001218 }
drh8af6c222010-05-14 12:43:01 +00001219 if( pInode->pNext ){
1220 assert( pInode->pNext->pPrev==pInode );
1221 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001222 }
drh8af6c222010-05-14 12:43:01 +00001223 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001224 }
drhbbd42a62004-05-22 17:41:58 +00001225 }
1226}
1227
1228/*
drh8af6c222010-05-14 12:43:01 +00001229** Given a file descriptor, locate the unixInodeInfo object that
1230** describes that file descriptor. Create a new one if necessary. The
1231** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001232**
dan9359c7b2009-08-21 08:29:10 +00001233** The mutex entered using the unixEnterMutex() function must be held
1234** when this function is called.
1235**
drh6c7d5c52008-11-21 20:32:33 +00001236** Return an appropriate error code.
1237*/
drh8af6c222010-05-14 12:43:01 +00001238static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001239 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001240 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001241){
1242 int rc; /* System call return code */
1243 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001244 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1245 struct stat statbuf; /* Low-level file information */
1246 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001247
dan9359c7b2009-08-21 08:29:10 +00001248 assert( unixMutexHeld() );
1249
drh6c7d5c52008-11-21 20:32:33 +00001250 /* Get low-level information about the file that we can used to
1251 ** create a unique name for the file.
1252 */
1253 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001254 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001255 if( rc!=0 ){
1256 pFile->lastErrno = errno;
1257#ifdef EOVERFLOW
1258 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1259#endif
1260 return SQLITE_IOERR;
1261 }
1262
drheb0d74f2009-02-03 15:27:02 +00001263#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001264 /* On OS X on an msdos filesystem, the inode number is reported
1265 ** incorrectly for zero-size files. See ticket #3260. To work
1266 ** around this problem (we consider it a bug in OS X, not SQLite)
1267 ** we always increase the file size to 1 by writing a single byte
1268 ** prior to accessing the inode number. The one byte written is
1269 ** an ASCII 'S' character which also happens to be the first byte
1270 ** in the header of every SQLite database. In this way, if there
1271 ** is a race condition such that another thread has already populated
1272 ** the first page of the database, no damage is done.
1273 */
drh7ed97b92010-01-20 13:07:21 +00001274 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001275 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001276 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001277 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001278 return SQLITE_IOERR;
1279 }
drh99ab3b12011-03-02 15:09:07 +00001280 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001281 if( rc!=0 ){
1282 pFile->lastErrno = errno;
1283 return SQLITE_IOERR;
1284 }
1285 }
drheb0d74f2009-02-03 15:27:02 +00001286#endif
drh6c7d5c52008-11-21 20:32:33 +00001287
drh8af6c222010-05-14 12:43:01 +00001288 memset(&fileId, 0, sizeof(fileId));
1289 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001290#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001291 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001292#else
drh8af6c222010-05-14 12:43:01 +00001293 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001294#endif
drh8af6c222010-05-14 12:43:01 +00001295 pInode = inodeList;
1296 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1297 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001298 }
drh8af6c222010-05-14 12:43:01 +00001299 if( pInode==0 ){
1300 pInode = sqlite3_malloc( sizeof(*pInode) );
1301 if( pInode==0 ){
1302 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001303 }
drh8af6c222010-05-14 12:43:01 +00001304 memset(pInode, 0, sizeof(*pInode));
1305 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1306 pInode->nRef = 1;
1307 pInode->pNext = inodeList;
1308 pInode->pPrev = 0;
1309 if( inodeList ) inodeList->pPrev = pInode;
1310 inodeList = pInode;
1311 }else{
1312 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001313 }
drh8af6c222010-05-14 12:43:01 +00001314 *ppInode = pInode;
1315 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001316}
drh6c7d5c52008-11-21 20:32:33 +00001317
aswift5b1a2562008-08-22 00:22:35 +00001318
1319/*
drhfbc7e882013-04-11 01:16:15 +00001320** Check a unixFile that is a database. Verify the following:
1321**
1322** (1) There is exactly one hard link on the file
1323** (2) The file is not a symbolic link
1324** (3) The file has not been renamed or unlinked
1325**
1326** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1327*/
1328static void verifyDbFile(unixFile *pFile){
1329 struct stat buf;
1330 int rc;
1331 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1332 /* One or more of the following warnings have already been issued. Do not
1333 ** repeat them so as not to clutter the error log */
1334 return;
1335 }
1336 rc = osFstat(pFile->h, &buf);
1337 if( rc!=0 ){
1338 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1339 pFile->ctrlFlags |= UNIXFILE_WARNED;
1340 return;
1341 }
1342 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
1343 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1344 pFile->ctrlFlags |= UNIXFILE_WARNED;
1345 return;
1346 }
1347 if( buf.st_nlink>1 ){
1348 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1349 pFile->ctrlFlags |= UNIXFILE_WARNED;
1350 return;
1351 }
1352 if( pFile->pInode!=0
1353 && ((rc = osStat(pFile->zPath, &buf))!=0
1354 || buf.st_ino!=pFile->pInode->fileId.ino)
1355 ){
1356 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1357 pFile->ctrlFlags |= UNIXFILE_WARNED;
1358 return;
1359 }
1360}
1361
1362
1363/*
danielk197713adf8a2004-06-03 16:08:41 +00001364** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001365** file by this or any other process. If such a lock is held, set *pResOut
1366** to a non-zero value otherwise *pResOut is set to zero. The return value
1367** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001368*/
danielk1977861f7452008-06-05 11:39:11 +00001369static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001370 int rc = SQLITE_OK;
1371 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001372 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001373
danielk1977861f7452008-06-05 11:39:11 +00001374 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1375
drh054889e2005-11-30 03:20:31 +00001376 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001377 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001378
1379 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001380 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001381 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001382 }
1383
drh2ac3ee92004-06-07 16:27:46 +00001384 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001385 */
danielk197709480a92009-02-09 05:32:32 +00001386#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001387 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001388 struct flock lock;
1389 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001390 lock.l_start = RESERVED_BYTE;
1391 lock.l_len = 1;
1392 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001393 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1394 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1395 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001396 } else if( lock.l_type!=F_UNLCK ){
1397 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001398 }
1399 }
danielk197709480a92009-02-09 05:32:32 +00001400#endif
danielk197713adf8a2004-06-03 16:08:41 +00001401
drh6c7d5c52008-11-21 20:32:33 +00001402 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001403 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001404
aswift5b1a2562008-08-22 00:22:35 +00001405 *pResOut = reserved;
1406 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001407}
1408
1409/*
drha7e61d82011-03-12 17:02:57 +00001410** Attempt to set a system-lock on the file pFile. The lock is
1411** described by pLock.
1412**
drh77197112011-03-15 19:08:48 +00001413** If the pFile was opened read/write from unix-excl, then the only lock
1414** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001415** the first time any lock is attempted. All subsequent system locking
1416** operations become no-ops. Locking operations still happen internally,
1417** in order to coordinate access between separate database connections
1418** within this process, but all of that is handled in memory and the
1419** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001420**
1421** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1422** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1423** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001424**
1425** Zero is returned if the call completes successfully, or -1 if a call
1426** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001427*/
1428static int unixFileLock(unixFile *pFile, struct flock *pLock){
1429 int rc;
drh3cb93392011-03-12 18:10:44 +00001430 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001431 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001432 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001433 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1434 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1435 ){
drh3cb93392011-03-12 18:10:44 +00001436 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001437 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001438 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001439 lock.l_whence = SEEK_SET;
1440 lock.l_start = SHARED_FIRST;
1441 lock.l_len = SHARED_SIZE;
1442 lock.l_type = F_WRLCK;
1443 rc = osFcntl(pFile->h, F_SETLK, &lock);
1444 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001445 pInode->bProcessLock = 1;
1446 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001447 }else{
1448 rc = 0;
1449 }
1450 }else{
1451 rc = osFcntl(pFile->h, F_SETLK, pLock);
1452 }
1453 return rc;
1454}
1455
1456/*
drh308c2a52010-05-14 11:30:18 +00001457** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001458** of the following:
1459**
drh2ac3ee92004-06-07 16:27:46 +00001460** (1) SHARED_LOCK
1461** (2) RESERVED_LOCK
1462** (3) PENDING_LOCK
1463** (4) EXCLUSIVE_LOCK
1464**
drhb3e04342004-06-08 00:47:47 +00001465** Sometimes when requesting one lock state, additional lock states
1466** are inserted in between. The locking might fail on one of the later
1467** transitions leaving the lock state different from what it started but
1468** still short of its goal. The following chart shows the allowed
1469** transitions and the inserted intermediate states:
1470**
1471** UNLOCKED -> SHARED
1472** SHARED -> RESERVED
1473** SHARED -> (PENDING) -> EXCLUSIVE
1474** RESERVED -> (PENDING) -> EXCLUSIVE
1475** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001476**
drha6abd042004-06-09 17:37:22 +00001477** This routine will only increase a lock. Use the sqlite3OsUnlock()
1478** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001479*/
drh308c2a52010-05-14 11:30:18 +00001480static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001481 /* The following describes the implementation of the various locks and
1482 ** lock transitions in terms of the POSIX advisory shared and exclusive
1483 ** lock primitives (called read-locks and write-locks below, to avoid
1484 ** confusion with SQLite lock names). The algorithms are complicated
1485 ** slightly in order to be compatible with windows systems simultaneously
1486 ** accessing the same database file, in case that is ever required.
1487 **
1488 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1489 ** byte', each single bytes at well known offsets, and the 'shared byte
1490 ** range', a range of 510 bytes at a well known offset.
1491 **
1492 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1493 ** byte'. If this is successful, a random byte from the 'shared byte
1494 ** range' is read-locked and the lock on the 'pending byte' released.
1495 **
danielk197790ba3bd2004-06-25 08:32:25 +00001496 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1497 ** A RESERVED lock is implemented by grabbing a write-lock on the
1498 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001499 **
1500 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001501 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1502 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1503 ** obtained, but existing SHARED locks are allowed to persist. A process
1504 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1505 ** This property is used by the algorithm for rolling back a journal file
1506 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001507 **
danielk197790ba3bd2004-06-25 08:32:25 +00001508 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1509 ** implemented by obtaining a write-lock on the entire 'shared byte
1510 ** range'. Since all other locks require a read-lock on one of the bytes
1511 ** within this range, this ensures that no other locks are held on the
1512 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001513 **
1514 ** The reason a single byte cannot be used instead of the 'shared byte
1515 ** range' is that some versions of windows do not support read-locks. By
1516 ** locking a random byte from a range, concurrent SHARED locks may exist
1517 ** even if the locking primitive used is always a write-lock.
1518 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001519 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001520 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001521 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001522 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001523 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001524
drh054889e2005-11-30 03:20:31 +00001525 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001526 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1527 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001528 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001529
1530 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001531 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001532 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001533 */
drh308c2a52010-05-14 11:30:18 +00001534 if( pFile->eFileLock>=eFileLock ){
1535 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1536 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001537 return SQLITE_OK;
1538 }
1539
drh0c2694b2009-09-03 16:23:44 +00001540 /* Make sure the locking sequence is correct.
1541 ** (1) We never move from unlocked to anything higher than shared lock.
1542 ** (2) SQLite never explicitly requests a pendig lock.
1543 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001544 */
drh308c2a52010-05-14 11:30:18 +00001545 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1546 assert( eFileLock!=PENDING_LOCK );
1547 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001548
drh8af6c222010-05-14 12:43:01 +00001549 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001550 */
drh6c7d5c52008-11-21 20:32:33 +00001551 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001552 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001553
danielk1977ad94b582007-08-20 06:44:22 +00001554 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001555 ** handle that precludes the requested lock, return BUSY.
1556 */
drh8af6c222010-05-14 12:43:01 +00001557 if( (pFile->eFileLock!=pInode->eFileLock &&
1558 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001559 ){
1560 rc = SQLITE_BUSY;
1561 goto end_lock;
1562 }
1563
1564 /* If a SHARED lock is requested, and some thread using this PID already
1565 ** has a SHARED or RESERVED lock, then increment reference counts and
1566 ** return SQLITE_OK.
1567 */
drh308c2a52010-05-14 11:30:18 +00001568 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001569 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001570 assert( eFileLock==SHARED_LOCK );
1571 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001572 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001573 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001574 pInode->nShared++;
1575 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001576 goto end_lock;
1577 }
1578
danielk19779a1d0ab2004-06-01 14:09:28 +00001579
drh3cde3bb2004-06-12 02:17:14 +00001580 /* A PENDING lock is needed before acquiring a SHARED lock and before
1581 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1582 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001583 */
drh0c2694b2009-09-03 16:23:44 +00001584 lock.l_len = 1L;
1585 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001586 if( eFileLock==SHARED_LOCK
1587 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001588 ){
drh308c2a52010-05-14 11:30:18 +00001589 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001590 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001591 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001592 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001593 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001594 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001595 pFile->lastErrno = tErrno;
1596 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001597 goto end_lock;
1598 }
drh3cde3bb2004-06-12 02:17:14 +00001599 }
1600
1601
1602 /* If control gets to this point, then actually go ahead and make
1603 ** operating system calls for the specified lock.
1604 */
drh308c2a52010-05-14 11:30:18 +00001605 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001606 assert( pInode->nShared==0 );
1607 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001608 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001609
drh2ac3ee92004-06-07 16:27:46 +00001610 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001611 lock.l_start = SHARED_FIRST;
1612 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001613 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001614 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001615 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001616 }
dan661d71a2011-03-30 19:08:03 +00001617
drh2ac3ee92004-06-07 16:27:46 +00001618 /* Drop the temporary PENDING lock */
1619 lock.l_start = PENDING_BYTE;
1620 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001621 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001622 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1623 /* This could happen with a network mount */
1624 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001625 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001626 }
dan661d71a2011-03-30 19:08:03 +00001627
1628 if( rc ){
1629 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001630 pFile->lastErrno = tErrno;
1631 }
dan661d71a2011-03-30 19:08:03 +00001632 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001633 }else{
drh308c2a52010-05-14 11:30:18 +00001634 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001635 pInode->nLock++;
1636 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001637 }
drh8af6c222010-05-14 12:43:01 +00001638 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001639 /* We are trying for an exclusive lock but another thread in this
1640 ** same process is still holding a shared lock. */
1641 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001642 }else{
drh3cde3bb2004-06-12 02:17:14 +00001643 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001644 ** assumed that there is a SHARED or greater lock on the file
1645 ** already.
1646 */
drh308c2a52010-05-14 11:30:18 +00001647 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001648 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001649
1650 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1651 if( eFileLock==RESERVED_LOCK ){
1652 lock.l_start = RESERVED_BYTE;
1653 lock.l_len = 1L;
1654 }else{
1655 lock.l_start = SHARED_FIRST;
1656 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001657 }
dan661d71a2011-03-30 19:08:03 +00001658
1659 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001660 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001661 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001662 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001663 pFile->lastErrno = tErrno;
1664 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001665 }
drhbbd42a62004-05-22 17:41:58 +00001666 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001667
drh8f941bc2009-01-14 23:03:40 +00001668
drhd3d8c042012-05-29 17:02:40 +00001669#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001670 /* Set up the transaction-counter change checking flags when
1671 ** transitioning from a SHARED to a RESERVED lock. The change
1672 ** from SHARED to RESERVED marks the beginning of a normal
1673 ** write operation (not a hot journal rollback).
1674 */
1675 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001676 && pFile->eFileLock<=SHARED_LOCK
1677 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001678 ){
1679 pFile->transCntrChng = 0;
1680 pFile->dbUpdate = 0;
1681 pFile->inNormalWrite = 1;
1682 }
1683#endif
1684
1685
danielk1977ecb2a962004-06-02 06:30:16 +00001686 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001687 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001688 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001689 }else if( eFileLock==EXCLUSIVE_LOCK ){
1690 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001691 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001692 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001693
1694end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001695 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001696 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1697 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001698 return rc;
1699}
1700
1701/*
dan08da86a2009-08-21 17:18:03 +00001702** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001703** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001704*/
1705static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001706 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001707 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001708 p->pNext = pInode->pUnused;
1709 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001710 pFile->h = -1;
1711 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001712}
1713
1714/*
drh308c2a52010-05-14 11:30:18 +00001715** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001716** must be either NO_LOCK or SHARED_LOCK.
1717**
1718** If the locking level of the file descriptor is already at or below
1719** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001720**
1721** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1722** the byte range is divided into 2 parts and the first part is unlocked then
1723** set to a read lock, then the other part is simply unlocked. This works
1724** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1725** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001726*/
drha7e61d82011-03-12 17:02:57 +00001727static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001728 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001729 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001730 struct flock lock;
1731 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001732
drh054889e2005-11-30 03:20:31 +00001733 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001734 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001735 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001736 getpid()));
drha6abd042004-06-09 17:37:22 +00001737
drh308c2a52010-05-14 11:30:18 +00001738 assert( eFileLock<=SHARED_LOCK );
1739 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001740 return SQLITE_OK;
1741 }
drh6c7d5c52008-11-21 20:32:33 +00001742 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001743 pInode = pFile->pInode;
1744 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001745 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001746 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001747
drhd3d8c042012-05-29 17:02:40 +00001748#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001749 /* When reducing a lock such that other processes can start
1750 ** reading the database file again, make sure that the
1751 ** transaction counter was updated if any part of the database
1752 ** file changed. If the transaction counter is not updated,
1753 ** other connections to the same file might not realize that
1754 ** the file has changed and hence might not know to flush their
1755 ** cache. The use of a stale cache can lead to database corruption.
1756 */
drh8f941bc2009-01-14 23:03:40 +00001757 pFile->inNormalWrite = 0;
1758#endif
1759
drh7ed97b92010-01-20 13:07:21 +00001760 /* downgrading to a shared lock on NFS involves clearing the write lock
1761 ** before establishing the readlock - to avoid a race condition we downgrade
1762 ** the lock in 2 blocks, so that part of the range will be covered by a
1763 ** write lock until the rest is covered by a read lock:
1764 ** 1: [WWWWW]
1765 ** 2: [....W]
1766 ** 3: [RRRRW]
1767 ** 4: [RRRR.]
1768 */
drh308c2a52010-05-14 11:30:18 +00001769 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001770
1771#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001772 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001773 assert( handleNFSUnlock==0 );
1774#endif
1775#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001776 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001777 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001778 off_t divSize = SHARED_SIZE - 1;
1779
1780 lock.l_type = F_UNLCK;
1781 lock.l_whence = SEEK_SET;
1782 lock.l_start = SHARED_FIRST;
1783 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001784 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001785 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001786 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001787 if( IS_LOCK_ERROR(rc) ){
1788 pFile->lastErrno = tErrno;
1789 }
1790 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001791 }
drh7ed97b92010-01-20 13:07:21 +00001792 lock.l_type = F_RDLCK;
1793 lock.l_whence = SEEK_SET;
1794 lock.l_start = SHARED_FIRST;
1795 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001796 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001797 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001798 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1799 if( IS_LOCK_ERROR(rc) ){
1800 pFile->lastErrno = tErrno;
1801 }
1802 goto end_unlock;
1803 }
1804 lock.l_type = F_UNLCK;
1805 lock.l_whence = SEEK_SET;
1806 lock.l_start = SHARED_FIRST+divSize;
1807 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001808 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001809 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001810 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001811 if( IS_LOCK_ERROR(rc) ){
1812 pFile->lastErrno = tErrno;
1813 }
1814 goto end_unlock;
1815 }
drh30f776f2011-02-25 03:25:07 +00001816 }else
1817#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1818 {
drh7ed97b92010-01-20 13:07:21 +00001819 lock.l_type = F_RDLCK;
1820 lock.l_whence = SEEK_SET;
1821 lock.l_start = SHARED_FIRST;
1822 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001823 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001824 /* In theory, the call to unixFileLock() cannot fail because another
1825 ** process is holding an incompatible lock. If it does, this
1826 ** indicates that the other process is not following the locking
1827 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1828 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1829 ** an assert to fail). */
1830 rc = SQLITE_IOERR_RDLOCK;
1831 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001832 goto end_unlock;
1833 }
drh9c105bb2004-10-02 20:38:28 +00001834 }
1835 }
drhbbd42a62004-05-22 17:41:58 +00001836 lock.l_type = F_UNLCK;
1837 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001838 lock.l_start = PENDING_BYTE;
1839 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001840 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001841 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001842 }else{
danea83bc62011-04-01 11:56:32 +00001843 rc = SQLITE_IOERR_UNLOCK;
1844 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001845 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001846 }
drhbbd42a62004-05-22 17:41:58 +00001847 }
drh308c2a52010-05-14 11:30:18 +00001848 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001849 /* Decrement the shared lock counter. Release the lock using an
1850 ** OS call only when all threads in this same process have released
1851 ** the lock.
1852 */
drh8af6c222010-05-14 12:43:01 +00001853 pInode->nShared--;
1854 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001855 lock.l_type = F_UNLCK;
1856 lock.l_whence = SEEK_SET;
1857 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001858 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001859 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001860 }else{
danea83bc62011-04-01 11:56:32 +00001861 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001862 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001863 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001864 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001865 }
drha6abd042004-06-09 17:37:22 +00001866 }
1867
drhbbd42a62004-05-22 17:41:58 +00001868 /* Decrement the count of locks against this same file. When the
1869 ** count reaches zero, close any other file descriptors whose close
1870 ** was deferred because of outstanding locks.
1871 */
drh8af6c222010-05-14 12:43:01 +00001872 pInode->nLock--;
1873 assert( pInode->nLock>=0 );
1874 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001875 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001876 }
1877 }
drhf2f105d2012-08-20 15:53:54 +00001878
aswift5b1a2562008-08-22 00:22:35 +00001879end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001880 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001881 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001882 return rc;
drhbbd42a62004-05-22 17:41:58 +00001883}
1884
1885/*
drh308c2a52010-05-14 11:30:18 +00001886** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001887** must be either NO_LOCK or SHARED_LOCK.
1888**
1889** If the locking level of the file descriptor is already at or below
1890** the requested locking level, this routine is a no-op.
1891*/
drh308c2a52010-05-14 11:30:18 +00001892static int unixUnlock(sqlite3_file *id, int eFileLock){
dana1afc742013-03-25 13:50:49 +00001893 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
drha7e61d82011-03-12 17:02:57 +00001894 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001895}
1896
mistachkine98844f2013-08-24 00:59:24 +00001897#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001898static int unixMapfile(unixFile *pFd, i64 nByte);
1899static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001900#endif
danf23da962013-03-23 21:00:41 +00001901
drh7ed97b92010-01-20 13:07:21 +00001902/*
danielk1977e339d652008-06-28 11:23:00 +00001903** This function performs the parts of the "close file" operation
1904** common to all locking schemes. It closes the directory and file
1905** handles, if they are valid, and sets all fields of the unixFile
1906** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001907**
1908** It is *not* necessary to hold the mutex when this routine is called,
1909** even on VxWorks. A mutex will be acquired on VxWorks by the
1910** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001911*/
1912static int closeUnixFile(sqlite3_file *id){
1913 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001914#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001915 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001916#endif
dan661d71a2011-03-30 19:08:03 +00001917 if( pFile->h>=0 ){
1918 robust_close(pFile, pFile->h, __LINE__);
1919 pFile->h = -1;
1920 }
1921#if OS_VXWORKS
1922 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001923 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001924 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001925 }
1926 vxworksReleaseFileId(pFile->pId);
1927 pFile->pId = 0;
1928 }
1929#endif
1930 OSTRACE(("CLOSE %-3d\n", pFile->h));
1931 OpenCounter(-1);
1932 sqlite3_free(pFile->pUnused);
1933 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001934 return SQLITE_OK;
1935}
1936
1937/*
danielk1977e3026632004-06-22 11:29:02 +00001938** Close a file.
1939*/
danielk197762079062007-08-15 17:08:46 +00001940static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001941 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001942 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001943 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001944 unixUnlock(id, NO_LOCK);
1945 unixEnterMutex();
1946
1947 /* unixFile.pInode is always valid here. Otherwise, a different close
1948 ** routine (e.g. nolockClose()) would be called instead.
1949 */
1950 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1951 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1952 /* If there are outstanding locks, do not actually close the file just
1953 ** yet because that would clear those locks. Instead, add the file
1954 ** descriptor to pInode->pUnused list. It will be automatically closed
1955 ** when the last lock is cleared.
1956 */
1957 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001958 }
dan661d71a2011-03-30 19:08:03 +00001959 releaseInodeInfo(pFile);
1960 rc = closeUnixFile(id);
1961 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001962 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001963}
1964
drh734c9862008-11-28 15:37:20 +00001965/************** End of the posix advisory lock implementation *****************
1966******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001967
drh734c9862008-11-28 15:37:20 +00001968/******************************************************************************
1969****************************** No-op Locking **********************************
1970**
1971** Of the various locking implementations available, this is by far the
1972** simplest: locking is ignored. No attempt is made to lock the database
1973** file for reading or writing.
1974**
1975** This locking mode is appropriate for use on read-only databases
1976** (ex: databases that are burned into CD-ROM, for example.) It can
1977** also be used if the application employs some external mechanism to
1978** prevent simultaneous access of the same database by two or more
1979** database connections. But there is a serious risk of database
1980** corruption if this locking mode is used in situations where multiple
1981** database connections are accessing the same database file at the same
1982** time and one or more of those connections are writing.
1983*/
drhbfe66312006-10-03 17:40:40 +00001984
drh734c9862008-11-28 15:37:20 +00001985static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1986 UNUSED_PARAMETER(NotUsed);
1987 *pResOut = 0;
1988 return SQLITE_OK;
1989}
drh734c9862008-11-28 15:37:20 +00001990static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1991 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1992 return SQLITE_OK;
1993}
drh734c9862008-11-28 15:37:20 +00001994static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1995 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1996 return SQLITE_OK;
1997}
1998
1999/*
drh9b35ea62008-11-29 02:20:26 +00002000** Close the file.
drh734c9862008-11-28 15:37:20 +00002001*/
2002static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002003 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002004}
2005
2006/******************* End of the no-op lock implementation *********************
2007******************************************************************************/
2008
2009/******************************************************************************
2010************************* Begin dot-file Locking ******************************
2011**
mistachkin48864df2013-03-21 21:20:32 +00002012** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002013** files (really a directory) to control access to the database. This works
2014** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002015**
2016** (1) There is zero concurrency. A single reader blocks all other
2017** connections from reading or writing the database.
2018**
2019** (2) An application crash or power loss can leave stale lock files
2020** sitting around that need to be cleared manually.
2021**
2022** Nevertheless, a dotlock is an appropriate locking mode for use if no
2023** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002024**
drh9ef6bc42011-11-04 02:24:02 +00002025** Dotfile locking works by creating a subdirectory in the same directory as
2026** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002027** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002028** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002029*/
2030
2031/*
2032** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002033** lock directory.
drh734c9862008-11-28 15:37:20 +00002034*/
2035#define DOTLOCK_SUFFIX ".lock"
2036
drh7708e972008-11-29 00:56:52 +00002037/*
2038** This routine checks if there is a RESERVED lock held on the specified
2039** file by this or any other process. If such a lock is held, set *pResOut
2040** to a non-zero value otherwise *pResOut is set to zero. The return value
2041** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2042**
2043** In dotfile locking, either a lock exists or it does not. So in this
2044** variation of CheckReservedLock(), *pResOut is set to true if any lock
2045** is held on the file and false if the file is unlocked.
2046*/
drh734c9862008-11-28 15:37:20 +00002047static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2048 int rc = SQLITE_OK;
2049 int reserved = 0;
2050 unixFile *pFile = (unixFile*)id;
2051
2052 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2053
2054 assert( pFile );
2055
2056 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002057 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002058 /* Either this connection or some other connection in the same process
2059 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002060 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002061 }else{
2062 /* The lock is held if and only if the lockfile exists */
2063 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002064 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002065 }
drh308c2a52010-05-14 11:30:18 +00002066 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002067 *pResOut = reserved;
2068 return rc;
2069}
2070
drh7708e972008-11-29 00:56:52 +00002071/*
drh308c2a52010-05-14 11:30:18 +00002072** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002073** of the following:
2074**
2075** (1) SHARED_LOCK
2076** (2) RESERVED_LOCK
2077** (3) PENDING_LOCK
2078** (4) EXCLUSIVE_LOCK
2079**
2080** Sometimes when requesting one lock state, additional lock states
2081** are inserted in between. The locking might fail on one of the later
2082** transitions leaving the lock state different from what it started but
2083** still short of its goal. The following chart shows the allowed
2084** transitions and the inserted intermediate states:
2085**
2086** UNLOCKED -> SHARED
2087** SHARED -> RESERVED
2088** SHARED -> (PENDING) -> EXCLUSIVE
2089** RESERVED -> (PENDING) -> EXCLUSIVE
2090** PENDING -> EXCLUSIVE
2091**
2092** This routine will only increase a lock. Use the sqlite3OsUnlock()
2093** routine to lower a locking level.
2094**
2095** With dotfile locking, we really only support state (4): EXCLUSIVE.
2096** But we track the other locking levels internally.
2097*/
drh308c2a52010-05-14 11:30:18 +00002098static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002099 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002100 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002101 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002102
drh7708e972008-11-29 00:56:52 +00002103
2104 /* If we have any lock, then the lock file already exists. All we have
2105 ** to do is adjust our internal record of the lock level.
2106 */
drh308c2a52010-05-14 11:30:18 +00002107 if( pFile->eFileLock > NO_LOCK ){
2108 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002109 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002110#ifdef HAVE_UTIME
2111 utime(zLockFile, NULL);
2112#else
drh734c9862008-11-28 15:37:20 +00002113 utimes(zLockFile, NULL);
2114#endif
drh7708e972008-11-29 00:56:52 +00002115 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002116 }
2117
2118 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002119 rc = osMkdir(zLockFile, 0777);
2120 if( rc<0 ){
2121 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002122 int tErrno = errno;
2123 if( EEXIST == tErrno ){
2124 rc = SQLITE_BUSY;
2125 } else {
2126 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2127 if( IS_LOCK_ERROR(rc) ){
2128 pFile->lastErrno = tErrno;
2129 }
2130 }
drh7708e972008-11-29 00:56:52 +00002131 return rc;
drh734c9862008-11-28 15:37:20 +00002132 }
drh734c9862008-11-28 15:37:20 +00002133
2134 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002135 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002136 return rc;
2137}
2138
drh7708e972008-11-29 00:56:52 +00002139/*
drh308c2a52010-05-14 11:30:18 +00002140** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002141** must be either NO_LOCK or SHARED_LOCK.
2142**
2143** If the locking level of the file descriptor is already at or below
2144** the requested locking level, this routine is a no-op.
2145**
2146** When the locking level reaches NO_LOCK, delete the lock file.
2147*/
drh308c2a52010-05-14 11:30:18 +00002148static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002149 unixFile *pFile = (unixFile*)id;
2150 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002151 int rc;
drh734c9862008-11-28 15:37:20 +00002152
2153 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002154 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002155 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002156 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002157
2158 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002159 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002160 return SQLITE_OK;
2161 }
drh7708e972008-11-29 00:56:52 +00002162
2163 /* To downgrade to shared, simply update our internal notion of the
2164 ** lock state. No need to mess with the file on disk.
2165 */
drh308c2a52010-05-14 11:30:18 +00002166 if( eFileLock==SHARED_LOCK ){
2167 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002168 return SQLITE_OK;
2169 }
2170
drh7708e972008-11-29 00:56:52 +00002171 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002172 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002173 rc = osRmdir(zLockFile);
2174 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2175 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002176 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002177 rc = 0;
drh734c9862008-11-28 15:37:20 +00002178 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002179 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002180 }
2181 if( IS_LOCK_ERROR(rc) ){
2182 pFile->lastErrno = tErrno;
2183 }
2184 return rc;
2185 }
drh308c2a52010-05-14 11:30:18 +00002186 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002187 return SQLITE_OK;
2188}
2189
2190/*
drh9b35ea62008-11-29 02:20:26 +00002191** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002192*/
2193static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002194 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002195 if( id ){
2196 unixFile *pFile = (unixFile*)id;
2197 dotlockUnlock(id, NO_LOCK);
2198 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002199 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002200 }
drh734c9862008-11-28 15:37:20 +00002201 return rc;
2202}
2203/****************** End of the dot-file lock implementation *******************
2204******************************************************************************/
2205
2206/******************************************************************************
2207************************** Begin flock Locking ********************************
2208**
2209** Use the flock() system call to do file locking.
2210**
drh6b9d6dd2008-12-03 19:34:47 +00002211** flock() locking is like dot-file locking in that the various
2212** fine-grain locking levels supported by SQLite are collapsed into
2213** a single exclusive lock. In other words, SHARED, RESERVED, and
2214** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2215** still works when you do this, but concurrency is reduced since
2216** only a single process can be reading the database at a time.
2217**
drh734c9862008-11-28 15:37:20 +00002218** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2219** compiling for VXWORKS.
2220*/
2221#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002222
drh6b9d6dd2008-12-03 19:34:47 +00002223/*
drhff812312011-02-23 13:33:46 +00002224** Retry flock() calls that fail with EINTR
2225*/
2226#ifdef EINTR
2227static int robust_flock(int fd, int op){
2228 int rc;
2229 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2230 return rc;
2231}
2232#else
drh5c819272011-02-23 14:00:12 +00002233# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002234#endif
2235
2236
2237/*
drh6b9d6dd2008-12-03 19:34:47 +00002238** This routine checks if there is a RESERVED lock held on the specified
2239** file by this or any other process. If such a lock is held, set *pResOut
2240** to a non-zero value otherwise *pResOut is set to zero. The return value
2241** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2242*/
drh734c9862008-11-28 15:37:20 +00002243static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2244 int rc = SQLITE_OK;
2245 int reserved = 0;
2246 unixFile *pFile = (unixFile*)id;
2247
2248 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2249
2250 assert( pFile );
2251
2252 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002253 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002254 reserved = 1;
2255 }
2256
2257 /* Otherwise see if some other process holds it. */
2258 if( !reserved ){
2259 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002260 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002261 if( !lrc ){
2262 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002263 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002264 if ( lrc ) {
2265 int tErrno = errno;
2266 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002267 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002268 if( IS_LOCK_ERROR(lrc) ){
2269 pFile->lastErrno = tErrno;
2270 rc = lrc;
2271 }
2272 }
2273 } else {
2274 int tErrno = errno;
2275 reserved = 1;
2276 /* someone else might have it reserved */
2277 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2278 if( IS_LOCK_ERROR(lrc) ){
2279 pFile->lastErrno = tErrno;
2280 rc = lrc;
2281 }
2282 }
2283 }
drh308c2a52010-05-14 11:30:18 +00002284 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002285
2286#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2287 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2288 rc = SQLITE_OK;
2289 reserved=1;
2290 }
2291#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2292 *pResOut = reserved;
2293 return rc;
2294}
2295
drh6b9d6dd2008-12-03 19:34:47 +00002296/*
drh308c2a52010-05-14 11:30:18 +00002297** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002298** of the following:
2299**
2300** (1) SHARED_LOCK
2301** (2) RESERVED_LOCK
2302** (3) PENDING_LOCK
2303** (4) EXCLUSIVE_LOCK
2304**
2305** Sometimes when requesting one lock state, additional lock states
2306** are inserted in between. The locking might fail on one of the later
2307** transitions leaving the lock state different from what it started but
2308** still short of its goal. The following chart shows the allowed
2309** transitions and the inserted intermediate states:
2310**
2311** UNLOCKED -> SHARED
2312** SHARED -> RESERVED
2313** SHARED -> (PENDING) -> EXCLUSIVE
2314** RESERVED -> (PENDING) -> EXCLUSIVE
2315** PENDING -> EXCLUSIVE
2316**
2317** flock() only really support EXCLUSIVE locks. We track intermediate
2318** lock states in the sqlite3_file structure, but all locks SHARED or
2319** above are really EXCLUSIVE locks and exclude all other processes from
2320** access the file.
2321**
2322** This routine will only increase a lock. Use the sqlite3OsUnlock()
2323** routine to lower a locking level.
2324*/
drh308c2a52010-05-14 11:30:18 +00002325static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002326 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002327 unixFile *pFile = (unixFile*)id;
2328
2329 assert( pFile );
2330
2331 /* if we already have a lock, it is exclusive.
2332 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002333 if (pFile->eFileLock > NO_LOCK) {
2334 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002335 return SQLITE_OK;
2336 }
2337
2338 /* grab an exclusive lock */
2339
drhff812312011-02-23 13:33:46 +00002340 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002341 int tErrno = errno;
2342 /* didn't get, must be busy */
2343 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2344 if( IS_LOCK_ERROR(rc) ){
2345 pFile->lastErrno = tErrno;
2346 }
2347 } else {
2348 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002349 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002350 }
drh308c2a52010-05-14 11:30:18 +00002351 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2352 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002353#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2354 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2355 rc = SQLITE_BUSY;
2356 }
2357#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2358 return rc;
2359}
2360
drh6b9d6dd2008-12-03 19:34:47 +00002361
2362/*
drh308c2a52010-05-14 11:30:18 +00002363** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002364** must be either NO_LOCK or SHARED_LOCK.
2365**
2366** If the locking level of the file descriptor is already at or below
2367** the requested locking level, this routine is a no-op.
2368*/
drh308c2a52010-05-14 11:30:18 +00002369static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002370 unixFile *pFile = (unixFile*)id;
2371
2372 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002373 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2374 pFile->eFileLock, getpid()));
2375 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002376
2377 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002378 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002379 return SQLITE_OK;
2380 }
2381
2382 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002383 if (eFileLock==SHARED_LOCK) {
2384 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002385 return SQLITE_OK;
2386 }
2387
2388 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002389 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002390#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002391 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002392#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002393 return SQLITE_IOERR_UNLOCK;
2394 }else{
drh308c2a52010-05-14 11:30:18 +00002395 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002396 return SQLITE_OK;
2397 }
2398}
2399
2400/*
2401** Close a file.
2402*/
2403static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002404 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002405 if( id ){
2406 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002407 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002408 }
drh5a05be12012-10-09 18:51:44 +00002409 return rc;
drh734c9862008-11-28 15:37:20 +00002410}
2411
2412#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2413
2414/******************* End of the flock lock implementation *********************
2415******************************************************************************/
2416
2417/******************************************************************************
2418************************ Begin Named Semaphore Locking ************************
2419**
2420** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002421**
2422** Semaphore locking is like dot-lock and flock in that it really only
2423** supports EXCLUSIVE locking. Only a single process can read or write
2424** the database file at a time. This reduces potential concurrency, but
2425** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002426*/
2427#if OS_VXWORKS
2428
drh6b9d6dd2008-12-03 19:34:47 +00002429/*
2430** This routine checks if there is a RESERVED lock held on the specified
2431** file by this or any other process. If such a lock is held, set *pResOut
2432** to a non-zero value otherwise *pResOut is set to zero. The return value
2433** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2434*/
drh734c9862008-11-28 15:37:20 +00002435static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2436 int rc = SQLITE_OK;
2437 int reserved = 0;
2438 unixFile *pFile = (unixFile*)id;
2439
2440 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2441
2442 assert( pFile );
2443
2444 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002445 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002446 reserved = 1;
2447 }
2448
2449 /* Otherwise see if some other process holds it. */
2450 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002451 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002452 struct stat statBuf;
2453
2454 if( sem_trywait(pSem)==-1 ){
2455 int tErrno = errno;
2456 if( EAGAIN != tErrno ){
2457 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2458 pFile->lastErrno = tErrno;
2459 } else {
2460 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002461 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002462 }
2463 }else{
2464 /* we could have it if we want it */
2465 sem_post(pSem);
2466 }
2467 }
drh308c2a52010-05-14 11:30:18 +00002468 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002469
2470 *pResOut = reserved;
2471 return rc;
2472}
2473
drh6b9d6dd2008-12-03 19:34:47 +00002474/*
drh308c2a52010-05-14 11:30:18 +00002475** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002476** of the following:
2477**
2478** (1) SHARED_LOCK
2479** (2) RESERVED_LOCK
2480** (3) PENDING_LOCK
2481** (4) EXCLUSIVE_LOCK
2482**
2483** Sometimes when requesting one lock state, additional lock states
2484** are inserted in between. The locking might fail on one of the later
2485** transitions leaving the lock state different from what it started but
2486** still short of its goal. The following chart shows the allowed
2487** transitions and the inserted intermediate states:
2488**
2489** UNLOCKED -> SHARED
2490** SHARED -> RESERVED
2491** SHARED -> (PENDING) -> EXCLUSIVE
2492** RESERVED -> (PENDING) -> EXCLUSIVE
2493** PENDING -> EXCLUSIVE
2494**
2495** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2496** lock states in the sqlite3_file structure, but all locks SHARED or
2497** above are really EXCLUSIVE locks and exclude all other processes from
2498** access the file.
2499**
2500** This routine will only increase a lock. Use the sqlite3OsUnlock()
2501** routine to lower a locking level.
2502*/
drh308c2a52010-05-14 11:30:18 +00002503static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002504 unixFile *pFile = (unixFile*)id;
2505 int fd;
drh8af6c222010-05-14 12:43:01 +00002506 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002507 int rc = SQLITE_OK;
2508
2509 /* if we already have a lock, it is exclusive.
2510 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002511 if (pFile->eFileLock > NO_LOCK) {
2512 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002513 rc = SQLITE_OK;
2514 goto sem_end_lock;
2515 }
2516
2517 /* lock semaphore now but bail out when already locked. */
2518 if( sem_trywait(pSem)==-1 ){
2519 rc = SQLITE_BUSY;
2520 goto sem_end_lock;
2521 }
2522
2523 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002524 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002525
2526 sem_end_lock:
2527 return rc;
2528}
2529
drh6b9d6dd2008-12-03 19:34:47 +00002530/*
drh308c2a52010-05-14 11:30:18 +00002531** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002532** must be either NO_LOCK or SHARED_LOCK.
2533**
2534** If the locking level of the file descriptor is already at or below
2535** the requested locking level, this routine is a no-op.
2536*/
drh308c2a52010-05-14 11:30:18 +00002537static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002538 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002539 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002540
2541 assert( pFile );
2542 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002543 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002544 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002545 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002546
2547 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002548 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002549 return SQLITE_OK;
2550 }
2551
2552 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002553 if (eFileLock==SHARED_LOCK) {
2554 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002555 return SQLITE_OK;
2556 }
2557
2558 /* no, really unlock. */
2559 if ( sem_post(pSem)==-1 ) {
2560 int rc, tErrno = errno;
2561 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2562 if( IS_LOCK_ERROR(rc) ){
2563 pFile->lastErrno = tErrno;
2564 }
2565 return rc;
2566 }
drh308c2a52010-05-14 11:30:18 +00002567 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002568 return SQLITE_OK;
2569}
2570
2571/*
2572 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002573 */
drh734c9862008-11-28 15:37:20 +00002574static int semClose(sqlite3_file *id) {
2575 if( id ){
2576 unixFile *pFile = (unixFile*)id;
2577 semUnlock(id, NO_LOCK);
2578 assert( pFile );
2579 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002580 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002581 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002582 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002583 }
2584 return SQLITE_OK;
2585}
2586
2587#endif /* OS_VXWORKS */
2588/*
2589** Named semaphore locking is only available on VxWorks.
2590**
2591*************** End of the named semaphore lock implementation ****************
2592******************************************************************************/
2593
2594
2595/******************************************************************************
2596*************************** Begin AFP Locking *********************************
2597**
2598** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2599** on Apple Macintosh computers - both OS9 and OSX.
2600**
2601** Third-party implementations of AFP are available. But this code here
2602** only works on OSX.
2603*/
2604
drhd2cb50b2009-01-09 21:41:17 +00002605#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002606/*
2607** The afpLockingContext structure contains all afp lock specific state
2608*/
drhbfe66312006-10-03 17:40:40 +00002609typedef struct afpLockingContext afpLockingContext;
2610struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002611 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002612 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002613};
2614
2615struct ByteRangeLockPB2
2616{
2617 unsigned long long offset; /* offset to first byte to lock */
2618 unsigned long long length; /* nbr of bytes to lock */
2619 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2620 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2621 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2622 int fd; /* file desc to assoc this lock with */
2623};
2624
drhfd131da2007-08-07 17:13:03 +00002625#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002626
drh6b9d6dd2008-12-03 19:34:47 +00002627/*
2628** This is a utility for setting or clearing a bit-range lock on an
2629** AFP filesystem.
2630**
2631** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2632*/
2633static int afpSetLock(
2634 const char *path, /* Name of the file to be locked or unlocked */
2635 unixFile *pFile, /* Open file descriptor on path */
2636 unsigned long long offset, /* First byte to be locked */
2637 unsigned long long length, /* Number of bytes to lock */
2638 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002639){
drh6b9d6dd2008-12-03 19:34:47 +00002640 struct ByteRangeLockPB2 pb;
2641 int err;
drhbfe66312006-10-03 17:40:40 +00002642
2643 pb.unLockFlag = setLockFlag ? 0 : 1;
2644 pb.startEndFlag = 0;
2645 pb.offset = offset;
2646 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002647 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002648
drh308c2a52010-05-14 11:30:18 +00002649 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002650 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002651 offset, length));
drhbfe66312006-10-03 17:40:40 +00002652 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2653 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002654 int rc;
2655 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002656 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2657 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002658#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2659 rc = SQLITE_BUSY;
2660#else
drh734c9862008-11-28 15:37:20 +00002661 rc = sqliteErrorFromPosixError(tErrno,
2662 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002663#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002664 if( IS_LOCK_ERROR(rc) ){
2665 pFile->lastErrno = tErrno;
2666 }
2667 return rc;
drhbfe66312006-10-03 17:40:40 +00002668 } else {
aswift5b1a2562008-08-22 00:22:35 +00002669 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002670 }
2671}
2672
drh6b9d6dd2008-12-03 19:34:47 +00002673/*
2674** This routine checks if there is a RESERVED lock held on the specified
2675** file by this or any other process. If such a lock is held, set *pResOut
2676** to a non-zero value otherwise *pResOut is set to zero. The return value
2677** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2678*/
danielk1977e339d652008-06-28 11:23:00 +00002679static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002680 int rc = SQLITE_OK;
2681 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002682 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002683 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002684
aswift5b1a2562008-08-22 00:22:35 +00002685 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2686
2687 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002688 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002689 if( context->reserved ){
2690 *pResOut = 1;
2691 return SQLITE_OK;
2692 }
drh8af6c222010-05-14 12:43:01 +00002693 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002694
2695 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002696 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002697 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002698 }
2699
2700 /* Otherwise see if some other process holds it.
2701 */
aswift5b1a2562008-08-22 00:22:35 +00002702 if( !reserved ){
2703 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002704 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002705 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002706 /* if we succeeded in taking the reserved lock, unlock it to restore
2707 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002708 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002709 } else {
2710 /* if we failed to get the lock then someone else must have it */
2711 reserved = 1;
2712 }
2713 if( IS_LOCK_ERROR(lrc) ){
2714 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002715 }
2716 }
drhbfe66312006-10-03 17:40:40 +00002717
drh7ed97b92010-01-20 13:07:21 +00002718 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002719 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002720
2721 *pResOut = reserved;
2722 return rc;
drhbfe66312006-10-03 17:40:40 +00002723}
2724
drh6b9d6dd2008-12-03 19:34:47 +00002725/*
drh308c2a52010-05-14 11:30:18 +00002726** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002727** of the following:
2728**
2729** (1) SHARED_LOCK
2730** (2) RESERVED_LOCK
2731** (3) PENDING_LOCK
2732** (4) EXCLUSIVE_LOCK
2733**
2734** Sometimes when requesting one lock state, additional lock states
2735** are inserted in between. The locking might fail on one of the later
2736** transitions leaving the lock state different from what it started but
2737** still short of its goal. The following chart shows the allowed
2738** transitions and the inserted intermediate states:
2739**
2740** UNLOCKED -> SHARED
2741** SHARED -> RESERVED
2742** SHARED -> (PENDING) -> EXCLUSIVE
2743** RESERVED -> (PENDING) -> EXCLUSIVE
2744** PENDING -> EXCLUSIVE
2745**
2746** This routine will only increase a lock. Use the sqlite3OsUnlock()
2747** routine to lower a locking level.
2748*/
drh308c2a52010-05-14 11:30:18 +00002749static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002750 int rc = SQLITE_OK;
2751 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002752 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002753 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002754
2755 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002756 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2757 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002758 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002759
drhbfe66312006-10-03 17:40:40 +00002760 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002761 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002762 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002763 */
drh308c2a52010-05-14 11:30:18 +00002764 if( pFile->eFileLock>=eFileLock ){
2765 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2766 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002767 return SQLITE_OK;
2768 }
2769
2770 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002771 ** (1) We never move from unlocked to anything higher than shared lock.
2772 ** (2) SQLite never explicitly requests a pendig lock.
2773 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002774 */
drh308c2a52010-05-14 11:30:18 +00002775 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2776 assert( eFileLock!=PENDING_LOCK );
2777 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002778
drh8af6c222010-05-14 12:43:01 +00002779 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002780 */
drh6c7d5c52008-11-21 20:32:33 +00002781 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002782 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002783
2784 /* If some thread using this PID has a lock via a different unixFile*
2785 ** handle that precludes the requested lock, return BUSY.
2786 */
drh8af6c222010-05-14 12:43:01 +00002787 if( (pFile->eFileLock!=pInode->eFileLock &&
2788 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002789 ){
2790 rc = SQLITE_BUSY;
2791 goto afp_end_lock;
2792 }
2793
2794 /* If a SHARED lock is requested, and some thread using this PID already
2795 ** has a SHARED or RESERVED lock, then increment reference counts and
2796 ** return SQLITE_OK.
2797 */
drh308c2a52010-05-14 11:30:18 +00002798 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002799 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002800 assert( eFileLock==SHARED_LOCK );
2801 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002802 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002803 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002804 pInode->nShared++;
2805 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002806 goto afp_end_lock;
2807 }
drhbfe66312006-10-03 17:40:40 +00002808
2809 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002810 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2811 ** be released.
2812 */
drh308c2a52010-05-14 11:30:18 +00002813 if( eFileLock==SHARED_LOCK
2814 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002815 ){
2816 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002817 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002818 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002819 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002820 goto afp_end_lock;
2821 }
2822 }
2823
2824 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002825 ** operating system calls for the specified lock.
2826 */
drh308c2a52010-05-14 11:30:18 +00002827 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002828 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002829 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002830
drh8af6c222010-05-14 12:43:01 +00002831 assert( pInode->nShared==0 );
2832 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002833
2834 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002835 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002836 /* note that the quality of the randomness doesn't matter that much */
2837 lk = random();
drh8af6c222010-05-14 12:43:01 +00002838 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002839 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002840 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002841 if( IS_LOCK_ERROR(lrc1) ){
2842 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002843 }
aswift5b1a2562008-08-22 00:22:35 +00002844 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002845 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002846
aswift5b1a2562008-08-22 00:22:35 +00002847 if( IS_LOCK_ERROR(lrc1) ) {
2848 pFile->lastErrno = lrc1Errno;
2849 rc = lrc1;
2850 goto afp_end_lock;
2851 } else if( IS_LOCK_ERROR(lrc2) ){
2852 rc = lrc2;
2853 goto afp_end_lock;
2854 } else if( lrc1 != SQLITE_OK ) {
2855 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002856 } else {
drh308c2a52010-05-14 11:30:18 +00002857 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002858 pInode->nLock++;
2859 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002860 }
drh8af6c222010-05-14 12:43:01 +00002861 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002862 /* We are trying for an exclusive lock but another thread in this
2863 ** same process is still holding a shared lock. */
2864 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002865 }else{
2866 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2867 ** assumed that there is a SHARED or greater lock on the file
2868 ** already.
2869 */
2870 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002871 assert( 0!=pFile->eFileLock );
2872 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002873 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002874 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002875 if( !failed ){
2876 context->reserved = 1;
2877 }
drhbfe66312006-10-03 17:40:40 +00002878 }
drh308c2a52010-05-14 11:30:18 +00002879 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002880 /* Acquire an EXCLUSIVE lock */
2881
2882 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002883 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002884 */
drh6b9d6dd2008-12-03 19:34:47 +00002885 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002886 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002887 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002888 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002889 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002890 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002891 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002892 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002893 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2894 ** a critical I/O error
2895 */
2896 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2897 SQLITE_IOERR_LOCK;
2898 goto afp_end_lock;
2899 }
2900 }else{
aswift5b1a2562008-08-22 00:22:35 +00002901 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002902 }
2903 }
aswift5b1a2562008-08-22 00:22:35 +00002904 if( failed ){
2905 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002906 }
2907 }
2908
2909 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002910 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002911 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002912 }else if( eFileLock==EXCLUSIVE_LOCK ){
2913 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002914 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002915 }
2916
2917afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002918 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002919 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2920 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002921 return rc;
2922}
2923
2924/*
drh308c2a52010-05-14 11:30:18 +00002925** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002926** must be either NO_LOCK or SHARED_LOCK.
2927**
2928** If the locking level of the file descriptor is already at or below
2929** the requested locking level, this routine is a no-op.
2930*/
drh308c2a52010-05-14 11:30:18 +00002931static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002932 int rc = SQLITE_OK;
2933 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002934 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002935 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2936 int skipShared = 0;
2937#ifdef SQLITE_TEST
2938 int h = pFile->h;
2939#endif
drhbfe66312006-10-03 17:40:40 +00002940
2941 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002942 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002943 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002944 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002945
drh308c2a52010-05-14 11:30:18 +00002946 assert( eFileLock<=SHARED_LOCK );
2947 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002948 return SQLITE_OK;
2949 }
drh6c7d5c52008-11-21 20:32:33 +00002950 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002951 pInode = pFile->pInode;
2952 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002953 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002954 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002955 SimulateIOErrorBenign(1);
2956 SimulateIOError( h=(-1) )
2957 SimulateIOErrorBenign(0);
2958
drhd3d8c042012-05-29 17:02:40 +00002959#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002960 /* When reducing a lock such that other processes can start
2961 ** reading the database file again, make sure that the
2962 ** transaction counter was updated if any part of the database
2963 ** file changed. If the transaction counter is not updated,
2964 ** other connections to the same file might not realize that
2965 ** the file has changed and hence might not know to flush their
2966 ** cache. The use of a stale cache can lead to database corruption.
2967 */
2968 assert( pFile->inNormalWrite==0
2969 || pFile->dbUpdate==0
2970 || pFile->transCntrChng==1 );
2971 pFile->inNormalWrite = 0;
2972#endif
aswiftaebf4132008-11-21 00:10:35 +00002973
drh308c2a52010-05-14 11:30:18 +00002974 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002975 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002976 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002977 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002978 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002979 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2980 } else {
2981 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002982 }
2983 }
drh308c2a52010-05-14 11:30:18 +00002984 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002985 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002986 }
drh308c2a52010-05-14 11:30:18 +00002987 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002988 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2989 if( !rc ){
2990 context->reserved = 0;
2991 }
aswiftaebf4132008-11-21 00:10:35 +00002992 }
drh8af6c222010-05-14 12:43:01 +00002993 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2994 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002995 }
aswiftaebf4132008-11-21 00:10:35 +00002996 }
drh308c2a52010-05-14 11:30:18 +00002997 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002998
drh7ed97b92010-01-20 13:07:21 +00002999 /* Decrement the shared lock counter. Release the lock using an
3000 ** OS call only when all threads in this same process have released
3001 ** the lock.
3002 */
drh8af6c222010-05-14 12:43:01 +00003003 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3004 pInode->nShared--;
3005 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003006 SimulateIOErrorBenign(1);
3007 SimulateIOError( h=(-1) )
3008 SimulateIOErrorBenign(0);
3009 if( !skipShared ){
3010 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3011 }
3012 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003013 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003014 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003015 }
3016 }
3017 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003018 pInode->nLock--;
3019 assert( pInode->nLock>=0 );
3020 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003021 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003022 }
3023 }
drhbfe66312006-10-03 17:40:40 +00003024 }
drh7ed97b92010-01-20 13:07:21 +00003025
drh6c7d5c52008-11-21 20:32:33 +00003026 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003027 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003028 return rc;
3029}
3030
3031/*
drh339eb0b2008-03-07 15:34:11 +00003032** Close a file & cleanup AFP specific locking context
3033*/
danielk1977e339d652008-06-28 11:23:00 +00003034static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003035 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003036 if( id ){
3037 unixFile *pFile = (unixFile*)id;
3038 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003039 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003040 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003041 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003042 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003043 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003044 ** the last lock is cleared.
3045 */
dan08da86a2009-08-21 17:18:03 +00003046 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003047 }
danb0ac3e32010-06-16 10:55:42 +00003048 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003049 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003050 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003051 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003052 }
drh7ed97b92010-01-20 13:07:21 +00003053 return rc;
drhbfe66312006-10-03 17:40:40 +00003054}
3055
drhd2cb50b2009-01-09 21:41:17 +00003056#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003057/*
3058** The code above is the AFP lock implementation. The code is specific
3059** to MacOSX and does not work on other unix platforms. No alternative
3060** is available. If you don't compile for a mac, then the "unix-afp"
3061** VFS is not available.
3062**
3063********************* End of the AFP lock implementation **********************
3064******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003065
drh7ed97b92010-01-20 13:07:21 +00003066/******************************************************************************
3067*************************** Begin NFS Locking ********************************/
3068
3069#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3070/*
drh308c2a52010-05-14 11:30:18 +00003071 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003072 ** must be either NO_LOCK or SHARED_LOCK.
3073 **
3074 ** If the locking level of the file descriptor is already at or below
3075 ** the requested locking level, this routine is a no-op.
3076 */
drh308c2a52010-05-14 11:30:18 +00003077static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003078 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003079}
3080
3081#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3082/*
3083** The code above is the NFS lock implementation. The code is specific
3084** to MacOSX and does not work on other unix platforms. No alternative
3085** is available.
3086**
3087********************* End of the NFS lock implementation **********************
3088******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003089
3090/******************************************************************************
3091**************** Non-locking sqlite3_file methods *****************************
3092**
3093** The next division contains implementations for all methods of the
3094** sqlite3_file object other than the locking methods. The locking
3095** methods were defined in divisions above (one locking method per
3096** division). Those methods that are common to all locking modes
3097** are gather together into this division.
3098*/
drhbfe66312006-10-03 17:40:40 +00003099
3100/*
drh734c9862008-11-28 15:37:20 +00003101** Seek to the offset passed as the second argument, then read cnt
3102** bytes into pBuf. Return the number of bytes actually read.
3103**
3104** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3105** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3106** one system to another. Since SQLite does not define USE_PREAD
3107** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3108** See tickets #2741 and #2681.
3109**
3110** To avoid stomping the errno value on a failed read the lastErrno value
3111** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003112*/
drh734c9862008-11-28 15:37:20 +00003113static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3114 int got;
drh58024642011-11-07 18:16:00 +00003115 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003116#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003117 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003118#endif
drh734c9862008-11-28 15:37:20 +00003119 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003120 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003121 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003122 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003123 do{
drh734c9862008-11-28 15:37:20 +00003124#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003125 got = osPread(id->h, pBuf, cnt, offset);
3126 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003127#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003128 got = osPread64(id->h, pBuf, cnt, offset);
3129 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003130#else
drh58024642011-11-07 18:16:00 +00003131 newOffset = lseek(id->h, offset, SEEK_SET);
3132 SimulateIOError( newOffset-- );
3133 if( newOffset!=offset ){
3134 if( newOffset == -1 ){
3135 ((unixFile*)id)->lastErrno = errno;
3136 }else{
drhf2f105d2012-08-20 15:53:54 +00003137 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003138 }
3139 return -1;
drh734c9862008-11-28 15:37:20 +00003140 }
drh58024642011-11-07 18:16:00 +00003141 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003142#endif
drh58024642011-11-07 18:16:00 +00003143 if( got==cnt ) break;
3144 if( got<0 ){
3145 if( errno==EINTR ){ got = 1; continue; }
3146 prior = 0;
3147 ((unixFile*)id)->lastErrno = errno;
3148 break;
3149 }else if( got>0 ){
3150 cnt -= got;
3151 offset += got;
3152 prior += got;
3153 pBuf = (void*)(got + (char*)pBuf);
3154 }
3155 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003156 TIMER_END;
drh58024642011-11-07 18:16:00 +00003157 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3158 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3159 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003160}
3161
3162/*
drh734c9862008-11-28 15:37:20 +00003163** Read data from a file into a buffer. Return SQLITE_OK if all
3164** bytes were read successfully and SQLITE_IOERR if anything goes
3165** wrong.
drh339eb0b2008-03-07 15:34:11 +00003166*/
drh734c9862008-11-28 15:37:20 +00003167static int unixRead(
3168 sqlite3_file *id,
3169 void *pBuf,
3170 int amt,
3171 sqlite3_int64 offset
3172){
dan08da86a2009-08-21 17:18:03 +00003173 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003174 int got;
3175 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003176 assert( offset>=0 );
3177 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003178
dan08da86a2009-08-21 17:18:03 +00003179 /* If this is a database file (not a journal, master-journal or temp
3180 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003181#if 0
dane946c392009-08-22 11:39:46 +00003182 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003183 || offset>=PENDING_BYTE+512
3184 || offset+amt<=PENDING_BYTE
3185 );
dan7c246102010-04-12 19:00:29 +00003186#endif
drh08c6d442009-02-09 17:34:07 +00003187
drh9b4c59f2013-04-15 17:03:42 +00003188#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003189 /* Deal with as much of this read request as possible by transfering
3190 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003191 if( offset<pFile->mmapSize ){
3192 if( offset+amt <= pFile->mmapSize ){
3193 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3194 return SQLITE_OK;
3195 }else{
3196 int nCopy = pFile->mmapSize - offset;
3197 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3198 pBuf = &((u8 *)pBuf)[nCopy];
3199 amt -= nCopy;
3200 offset += nCopy;
3201 }
3202 }
drh6e0b6d52013-04-09 16:19:20 +00003203#endif
danf23da962013-03-23 21:00:41 +00003204
dan08da86a2009-08-21 17:18:03 +00003205 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003206 if( got==amt ){
3207 return SQLITE_OK;
3208 }else if( got<0 ){
3209 /* lastErrno set by seekAndRead */
3210 return SQLITE_IOERR_READ;
3211 }else{
dan08da86a2009-08-21 17:18:03 +00003212 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003213 /* Unread parts of the buffer must be zero-filled */
3214 memset(&((char*)pBuf)[got], 0, amt-got);
3215 return SQLITE_IOERR_SHORT_READ;
3216 }
3217}
3218
3219/*
dan47a2b4a2013-04-26 16:09:29 +00003220** Attempt to seek the file-descriptor passed as the first argument to
3221** absolute offset iOff, then attempt to write nBuf bytes of data from
3222** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3223** return the actual number of bytes written (which may be less than
3224** nBuf).
3225*/
3226static int seekAndWriteFd(
3227 int fd, /* File descriptor to write to */
3228 i64 iOff, /* File offset to begin writing at */
3229 const void *pBuf, /* Copy data from this buffer to the file */
3230 int nBuf, /* Size of buffer pBuf in bytes */
3231 int *piErrno /* OUT: Error number if error occurs */
3232){
3233 int rc = 0; /* Value returned by system call */
3234
3235 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003236 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003237 nBuf &= 0x1ffff;
3238 TIMER_START;
3239
3240#if defined(USE_PREAD)
3241 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3242#elif defined(USE_PREAD64)
3243 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3244#else
3245 do{
3246 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3247 SimulateIOError( iSeek-- );
3248
3249 if( iSeek!=iOff ){
3250 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3251 return -1;
3252 }
3253 rc = osWrite(fd, pBuf, nBuf);
3254 }while( rc<0 && errno==EINTR );
3255#endif
3256
3257 TIMER_END;
3258 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3259
3260 if( rc<0 && piErrno ) *piErrno = errno;
3261 return rc;
3262}
3263
3264
3265/*
drh734c9862008-11-28 15:37:20 +00003266** Seek to the offset in id->offset then read cnt bytes into pBuf.
3267** Return the number of bytes actually read. Update the offset.
3268**
3269** To avoid stomping the errno value on a failed write the lastErrno value
3270** is set before returning.
3271*/
3272static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003273 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003274}
3275
3276
3277/*
3278** Write data from a buffer into a file. Return SQLITE_OK on success
3279** or some other error code on failure.
3280*/
3281static int unixWrite(
3282 sqlite3_file *id,
3283 const void *pBuf,
3284 int amt,
3285 sqlite3_int64 offset
3286){
dan08da86a2009-08-21 17:18:03 +00003287 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003288 int wrote = 0;
3289 assert( id );
3290 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003291
dan08da86a2009-08-21 17:18:03 +00003292 /* If this is a database file (not a journal, master-journal or temp
3293 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003294#if 0
dane946c392009-08-22 11:39:46 +00003295 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003296 || offset>=PENDING_BYTE+512
3297 || offset+amt<=PENDING_BYTE
3298 );
dan7c246102010-04-12 19:00:29 +00003299#endif
drh08c6d442009-02-09 17:34:07 +00003300
drhd3d8c042012-05-29 17:02:40 +00003301#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003302 /* If we are doing a normal write to a database file (as opposed to
3303 ** doing a hot-journal rollback or a write to some file other than a
3304 ** normal database file) then record the fact that the database
3305 ** has changed. If the transaction counter is modified, record that
3306 ** fact too.
3307 */
dan08da86a2009-08-21 17:18:03 +00003308 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003309 pFile->dbUpdate = 1; /* The database has been modified */
3310 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003311 int rc;
drh8f941bc2009-01-14 23:03:40 +00003312 char oldCntr[4];
3313 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003314 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003315 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003316 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003317 pFile->transCntrChng = 1; /* The transaction counter has changed */
3318 }
3319 }
3320 }
3321#endif
3322
drh9b4c59f2013-04-15 17:03:42 +00003323#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003324 /* Deal with as much of this write request as possible by transfering
3325 ** data from the memory mapping using memcpy(). */
3326 if( offset<pFile->mmapSize ){
3327 if( offset+amt <= pFile->mmapSize ){
3328 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3329 return SQLITE_OK;
3330 }else{
3331 int nCopy = pFile->mmapSize - offset;
3332 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3333 pBuf = &((u8 *)pBuf)[nCopy];
3334 amt -= nCopy;
3335 offset += nCopy;
3336 }
3337 }
drh6e0b6d52013-04-09 16:19:20 +00003338#endif
danf23da962013-03-23 21:00:41 +00003339
dan08da86a2009-08-21 17:18:03 +00003340 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003341 amt -= wrote;
3342 offset += wrote;
3343 pBuf = &((char*)pBuf)[wrote];
3344 }
3345 SimulateIOError(( wrote=(-1), amt=1 ));
3346 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003347
drh734c9862008-11-28 15:37:20 +00003348 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003349 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003350 /* lastErrno set by seekAndWrite */
3351 return SQLITE_IOERR_WRITE;
3352 }else{
dan08da86a2009-08-21 17:18:03 +00003353 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003354 return SQLITE_FULL;
3355 }
3356 }
dan6e09d692010-07-27 18:34:15 +00003357
drh734c9862008-11-28 15:37:20 +00003358 return SQLITE_OK;
3359}
3360
3361#ifdef SQLITE_TEST
3362/*
3363** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003364** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003365*/
3366int sqlite3_sync_count = 0;
3367int sqlite3_fullsync_count = 0;
3368#endif
3369
3370/*
drh89240432009-03-25 01:06:01 +00003371** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003372** Others do no. To be safe, we will stick with the (slightly slower)
3373** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003374** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003375*/
drh20f8e132011-08-31 21:01:55 +00003376#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003377# define fdatasync fsync
3378#endif
3379
3380/*
3381** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3382** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3383** only available on Mac OS X. But that could change.
3384*/
3385#ifdef F_FULLFSYNC
3386# define HAVE_FULLFSYNC 1
3387#else
3388# define HAVE_FULLFSYNC 0
3389#endif
3390
3391
3392/*
3393** The fsync() system call does not work as advertised on many
3394** unix systems. The following procedure is an attempt to make
3395** it work better.
3396**
3397** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3398** for testing when we want to run through the test suite quickly.
3399** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3400** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3401** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003402**
3403** SQLite sets the dataOnly flag if the size of the file is unchanged.
3404** The idea behind dataOnly is that it should only write the file content
3405** to disk, not the inode. We only set dataOnly if the file size is
3406** unchanged since the file size is part of the inode. However,
3407** Ted Ts'o tells us that fdatasync() will also write the inode if the
3408** file size has changed. The only real difference between fdatasync()
3409** and fsync(), Ted tells us, is that fdatasync() will not flush the
3410** inode if the mtime or owner or other inode attributes have changed.
3411** We only care about the file size, not the other file attributes, so
3412** as far as SQLite is concerned, an fdatasync() is always adequate.
3413** So, we always use fdatasync() if it is available, regardless of
3414** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003415*/
3416static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003417 int rc;
drh734c9862008-11-28 15:37:20 +00003418
3419 /* The following "ifdef/elif/else/" block has the same structure as
3420 ** the one below. It is replicated here solely to avoid cluttering
3421 ** up the real code with the UNUSED_PARAMETER() macros.
3422 */
3423#ifdef SQLITE_NO_SYNC
3424 UNUSED_PARAMETER(fd);
3425 UNUSED_PARAMETER(fullSync);
3426 UNUSED_PARAMETER(dataOnly);
3427#elif HAVE_FULLFSYNC
3428 UNUSED_PARAMETER(dataOnly);
3429#else
3430 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003431 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003432#endif
3433
3434 /* Record the number of times that we do a normal fsync() and
3435 ** FULLSYNC. This is used during testing to verify that this procedure
3436 ** gets called with the correct arguments.
3437 */
3438#ifdef SQLITE_TEST
3439 if( fullSync ) sqlite3_fullsync_count++;
3440 sqlite3_sync_count++;
3441#endif
3442
3443 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3444 ** no-op
3445 */
3446#ifdef SQLITE_NO_SYNC
3447 rc = SQLITE_OK;
3448#elif HAVE_FULLFSYNC
3449 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003450 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003451 }else{
3452 rc = 1;
3453 }
3454 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003455 ** It shouldn't be possible for fullfsync to fail on the local
3456 ** file system (on OSX), so failure indicates that FULLFSYNC
3457 ** isn't supported for this file system. So, attempt an fsync
3458 ** and (for now) ignore the overhead of a superfluous fcntl call.
3459 ** It'd be better to detect fullfsync support once and avoid
3460 ** the fcntl call every time sync is called.
3461 */
drh734c9862008-11-28 15:37:20 +00003462 if( rc ) rc = fsync(fd);
3463
drh7ed97b92010-01-20 13:07:21 +00003464#elif defined(__APPLE__)
3465 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3466 ** so currently we default to the macro that redefines fdatasync to fsync
3467 */
3468 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003469#else
drh0b647ff2009-03-21 14:41:04 +00003470 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003471#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003472 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003473 rc = fsync(fd);
3474 }
drh0b647ff2009-03-21 14:41:04 +00003475#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003476#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3477
3478 if( OS_VXWORKS && rc!= -1 ){
3479 rc = 0;
3480 }
chw97185482008-11-17 08:05:31 +00003481 return rc;
drhbfe66312006-10-03 17:40:40 +00003482}
3483
drh734c9862008-11-28 15:37:20 +00003484/*
drh0059eae2011-08-08 23:48:40 +00003485** Open a file descriptor to the directory containing file zFilename.
3486** If successful, *pFd is set to the opened file descriptor and
3487** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3488** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3489** value.
3490**
drh90315a22011-08-10 01:52:12 +00003491** The directory file descriptor is used for only one thing - to
3492** fsync() a directory to make sure file creation and deletion events
3493** are flushed to disk. Such fsyncs are not needed on newer
3494** journaling filesystems, but are required on older filesystems.
3495**
3496** This routine can be overridden using the xSetSysCall interface.
3497** The ability to override this routine was added in support of the
3498** chromium sandbox. Opening a directory is a security risk (we are
3499** told) so making it overrideable allows the chromium sandbox to
3500** replace this routine with a harmless no-op. To make this routine
3501** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3502** *pFd set to a negative number.
3503**
drh0059eae2011-08-08 23:48:40 +00003504** If SQLITE_OK is returned, the caller is responsible for closing
3505** the file descriptor *pFd using close().
3506*/
3507static int openDirectory(const char *zFilename, int *pFd){
3508 int ii;
3509 int fd = -1;
3510 char zDirname[MAX_PATHNAME+1];
3511
3512 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3513 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3514 if( ii>0 ){
3515 zDirname[ii] = '\0';
3516 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3517 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003518 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3519 }
3520 }
3521 *pFd = fd;
3522 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3523}
3524
3525/*
drh734c9862008-11-28 15:37:20 +00003526** Make sure all writes to a particular file are committed to disk.
3527**
3528** If dataOnly==0 then both the file itself and its metadata (file
3529** size, access time, etc) are synced. If dataOnly!=0 then only the
3530** file data is synced.
3531**
3532** Under Unix, also make sure that the directory entry for the file
3533** has been created by fsync-ing the directory that contains the file.
3534** If we do not do this and we encounter a power failure, the directory
3535** entry for the journal might not exist after we reboot. The next
3536** SQLite to access the file will not know that the journal exists (because
3537** the directory entry for the journal was never created) and the transaction
3538** will not roll back - possibly leading to database corruption.
3539*/
3540static int unixSync(sqlite3_file *id, int flags){
3541 int rc;
3542 unixFile *pFile = (unixFile*)id;
3543
3544 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3545 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3546
3547 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3548 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3549 || (flags&0x0F)==SQLITE_SYNC_FULL
3550 );
3551
3552 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3553 ** line is to test that doing so does not cause any problems.
3554 */
3555 SimulateDiskfullError( return SQLITE_FULL );
3556
3557 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003558 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003559 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3560 SimulateIOError( rc=1 );
3561 if( rc ){
3562 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003563 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003564 }
drh0059eae2011-08-08 23:48:40 +00003565
3566 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003567 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003568 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003569 */
3570 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3571 int dirfd;
3572 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003573 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003574 rc = osOpenDirectory(pFile->zPath, &dirfd);
3575 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003576 full_fsync(dirfd, 0, 0);
3577 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003578 }else if( rc==SQLITE_CANTOPEN ){
3579 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003580 }
drh0059eae2011-08-08 23:48:40 +00003581 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003582 }
3583 return rc;
3584}
3585
3586/*
3587** Truncate an open file to a specified size
3588*/
3589static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003590 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003591 int rc;
dan6e09d692010-07-27 18:34:15 +00003592 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003593 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003594
3595 /* If the user has configured a chunk-size for this file, truncate the
3596 ** file so that it consists of an integer number of chunks (i.e. the
3597 ** actual file size after the operation may be larger than the requested
3598 ** size).
3599 */
drhb8af4b72012-04-05 20:04:39 +00003600 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003601 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3602 }
3603
drhff812312011-02-23 13:33:46 +00003604 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003605 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003606 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003607 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003608 }else{
drhd3d8c042012-05-29 17:02:40 +00003609#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003610 /* If we are doing a normal write to a database file (as opposed to
3611 ** doing a hot-journal rollback or a write to some file other than a
3612 ** normal database file) and we truncate the file to zero length,
3613 ** that effectively updates the change counter. This might happen
3614 ** when restoring a database using the backup API from a zero-length
3615 ** source.
3616 */
dan6e09d692010-07-27 18:34:15 +00003617 if( pFile->inNormalWrite && nByte==0 ){
3618 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003619 }
danf23da962013-03-23 21:00:41 +00003620#endif
danc0003312013-03-22 17:46:11 +00003621
mistachkine98844f2013-08-24 00:59:24 +00003622#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003623 /* If the file was just truncated to a size smaller than the currently
3624 ** mapped region, reduce the effective mapping size as well. SQLite will
3625 ** use read() and write() to access data beyond this point from now on.
3626 */
3627 if( nByte<pFile->mmapSize ){
3628 pFile->mmapSize = nByte;
3629 }
mistachkine98844f2013-08-24 00:59:24 +00003630#endif
drh3313b142009-11-06 04:13:18 +00003631
drh734c9862008-11-28 15:37:20 +00003632 return SQLITE_OK;
3633 }
3634}
3635
3636/*
3637** Determine the current size of a file in bytes
3638*/
3639static int unixFileSize(sqlite3_file *id, i64 *pSize){
3640 int rc;
3641 struct stat buf;
3642 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003643 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003644 SimulateIOError( rc=1 );
3645 if( rc!=0 ){
3646 ((unixFile*)id)->lastErrno = errno;
3647 return SQLITE_IOERR_FSTAT;
3648 }
3649 *pSize = buf.st_size;
3650
drh8af6c222010-05-14 12:43:01 +00003651 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003652 ** writes a single byte into that file in order to work around a bug
3653 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3654 ** layers, we need to report this file size as zero even though it is
3655 ** really 1. Ticket #3260.
3656 */
3657 if( *pSize==1 ) *pSize = 0;
3658
3659
3660 return SQLITE_OK;
3661}
3662
drhd2cb50b2009-01-09 21:41:17 +00003663#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003664/*
3665** Handler for proxy-locking file-control verbs. Defined below in the
3666** proxying locking division.
3667*/
3668static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003669#endif
drh715ff302008-12-03 22:32:44 +00003670
dan502019c2010-07-28 14:26:17 +00003671/*
3672** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003673** file-control operation. Enlarge the database to nBytes in size
3674** (rounded up to the next chunk-size). If the database is already
3675** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003676*/
3677static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003678 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003679 i64 nSize; /* Required file size */
3680 struct stat buf; /* Used to hold return values of fstat() */
3681
drh99ab3b12011-03-02 15:09:07 +00003682 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003683
3684 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3685 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003686
dan502019c2010-07-28 14:26:17 +00003687#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003688 /* The code below is handling the return value of osFallocate()
3689 ** correctly. posix_fallocate() is defined to "returns zero on success,
3690 ** or an error number on failure". See the manpage for details. */
3691 int err;
drhff812312011-02-23 13:33:46 +00003692 do{
dan661d71a2011-03-30 19:08:03 +00003693 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3694 }while( err==EINTR );
3695 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003696#else
3697 /* If the OS does not have posix_fallocate(), fake it. First use
3698 ** ftruncate() to set the file size, then write a single byte to
3699 ** the last byte in each block within the extended region. This
3700 ** is the same technique used by glibc to implement posix_fallocate()
3701 ** on systems that do not have a real fallocate() system call.
3702 */
3703 int nBlk = buf.st_blksize; /* File-system block size */
3704 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003705
drhff812312011-02-23 13:33:46 +00003706 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003707 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003708 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003709 }
3710 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003711 while( iWrite<nSize ){
3712 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3713 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003714 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003715 }
dan502019c2010-07-28 14:26:17 +00003716#endif
3717 }
3718 }
3719
mistachkine98844f2013-08-24 00:59:24 +00003720#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003721 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003722 int rc;
3723 if( pFile->szChunk<=0 ){
3724 if( robust_ftruncate(pFile->h, nByte) ){
3725 pFile->lastErrno = errno;
3726 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3727 }
3728 }
3729
3730 rc = unixMapfile(pFile, nByte);
3731 return rc;
3732 }
mistachkine98844f2013-08-24 00:59:24 +00003733#endif
danf23da962013-03-23 21:00:41 +00003734
dan502019c2010-07-28 14:26:17 +00003735 return SQLITE_OK;
3736}
danielk1977ad94b582007-08-20 06:44:22 +00003737
danielk1977e3026632004-06-22 11:29:02 +00003738/*
drhf12b3f62011-12-21 14:42:29 +00003739** If *pArg is inititially negative then this is a query. Set *pArg to
3740** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3741**
3742** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3743*/
3744static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3745 if( *pArg<0 ){
3746 *pArg = (pFile->ctrlFlags & mask)!=0;
3747 }else if( (*pArg)==0 ){
3748 pFile->ctrlFlags &= ~mask;
3749 }else{
3750 pFile->ctrlFlags |= mask;
3751 }
3752}
3753
drh696b33e2012-12-06 19:01:42 +00003754/* Forward declaration */
3755static int unixGetTempname(int nBuf, char *zBuf);
3756
drhf12b3f62011-12-21 14:42:29 +00003757/*
drh9e33c2c2007-08-31 18:34:59 +00003758** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003759*/
drhcc6bb3e2007-08-31 16:11:35 +00003760static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003761 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003762 switch( op ){
3763 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003764 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003765 return SQLITE_OK;
3766 }
drh7708e972008-11-29 00:56:52 +00003767 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003768 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003769 return SQLITE_OK;
3770 }
dan6e09d692010-07-27 18:34:15 +00003771 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003772 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003773 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003774 }
drh9ff27ec2010-05-19 19:26:05 +00003775 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003776 int rc;
3777 SimulateIOErrorBenign(1);
3778 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3779 SimulateIOErrorBenign(0);
3780 return rc;
drhf0b190d2011-07-26 16:03:07 +00003781 }
3782 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003783 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3784 return SQLITE_OK;
3785 }
drhcb15f352011-12-23 01:04:17 +00003786 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3787 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003788 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003789 }
drhde60fc22011-12-14 17:53:36 +00003790 case SQLITE_FCNTL_VFSNAME: {
3791 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3792 return SQLITE_OK;
3793 }
drh696b33e2012-12-06 19:01:42 +00003794 case SQLITE_FCNTL_TEMPFILENAME: {
3795 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3796 if( zTFile ){
3797 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3798 *(char**)pArg = zTFile;
3799 }
3800 return SQLITE_OK;
3801 }
mistachkine98844f2013-08-24 00:59:24 +00003802#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003803 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003804 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003805 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003806 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3807 newLimit = sqlite3GlobalConfig.mxMmap;
3808 }
3809 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003810 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003811 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003812 if( pFile->mmapSize>0 ){
3813 unixUnmapfile(pFile);
3814 rc = unixMapfile(pFile, -1);
3815 }
danbcb8a862013-04-08 15:30:41 +00003816 }
drh34e258c2013-05-23 01:40:53 +00003817 return rc;
danb2d3de32013-03-14 18:34:37 +00003818 }
mistachkine98844f2013-08-24 00:59:24 +00003819#endif
drhd3d8c042012-05-29 17:02:40 +00003820#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003821 /* The pager calls this method to signal that it has done
3822 ** a rollback and that the database is therefore unchanged and
3823 ** it hence it is OK for the transaction change counter to be
3824 ** unchanged.
3825 */
3826 case SQLITE_FCNTL_DB_UNCHANGED: {
3827 ((unixFile*)id)->dbUpdate = 0;
3828 return SQLITE_OK;
3829 }
3830#endif
drhd2cb50b2009-01-09 21:41:17 +00003831#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003832 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003833 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003834 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003835 }
drhd2cb50b2009-01-09 21:41:17 +00003836#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003837 }
drh0b52b7d2011-01-26 19:46:22 +00003838 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003839}
3840
3841/*
danielk1977a3d4c882007-03-23 10:08:38 +00003842** Return the sector size in bytes of the underlying block device for
3843** the specified file. This is almost always 512 bytes, but may be
3844** larger for some devices.
3845**
3846** SQLite code assumes this function cannot fail. It also assumes that
3847** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003848** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003849** same for both.
3850*/
drh537dddf2012-10-26 13:46:24 +00003851#ifndef __QNXNTO__
3852static int unixSectorSize(sqlite3_file *NotUsed){
3853 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003854 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003855}
drh537dddf2012-10-26 13:46:24 +00003856#endif
3857
3858/*
3859** The following version of unixSectorSize() is optimized for QNX.
3860*/
3861#ifdef __QNXNTO__
3862#include <sys/dcmd_blk.h>
3863#include <sys/statvfs.h>
3864static int unixSectorSize(sqlite3_file *id){
3865 unixFile *pFile = (unixFile*)id;
3866 if( pFile->sectorSize == 0 ){
3867 struct statvfs fsInfo;
3868
3869 /* Set defaults for non-supported filesystems */
3870 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3871 pFile->deviceCharacteristics = 0;
3872 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3873 return pFile->sectorSize;
3874 }
3875
3876 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3877 pFile->sectorSize = fsInfo.f_bsize;
3878 pFile->deviceCharacteristics =
3879 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3880 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3881 ** the write succeeds */
3882 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3883 ** so it is ordered */
3884 0;
3885 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3886 pFile->sectorSize = fsInfo.f_bsize;
3887 pFile->deviceCharacteristics =
3888 /* etfs cluster size writes are atomic */
3889 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3890 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3891 ** the write succeeds */
3892 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3893 ** so it is ordered */
3894 0;
3895 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3896 pFile->sectorSize = fsInfo.f_bsize;
3897 pFile->deviceCharacteristics =
3898 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3899 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3900 ** the write succeeds */
3901 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3902 ** so it is ordered */
3903 0;
3904 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3905 pFile->sectorSize = fsInfo.f_bsize;
3906 pFile->deviceCharacteristics =
3907 /* full bitset of atomics from max sector size and smaller */
3908 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3909 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3910 ** so it is ordered */
3911 0;
3912 }else if( strstr(fsInfo.f_basetype, "dos") ){
3913 pFile->sectorSize = fsInfo.f_bsize;
3914 pFile->deviceCharacteristics =
3915 /* full bitset of atomics from max sector size and smaller */
3916 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3917 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3918 ** so it is ordered */
3919 0;
3920 }else{
3921 pFile->deviceCharacteristics =
3922 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3923 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3924 ** the write succeeds */
3925 0;
3926 }
3927 }
3928 /* Last chance verification. If the sector size isn't a multiple of 512
3929 ** then it isn't valid.*/
3930 if( pFile->sectorSize % 512 != 0 ){
3931 pFile->deviceCharacteristics = 0;
3932 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3933 }
3934 return pFile->sectorSize;
3935}
3936#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003937
danielk197790949c22007-08-17 16:50:38 +00003938/*
drhf12b3f62011-12-21 14:42:29 +00003939** Return the device characteristics for the file.
3940**
drhcb15f352011-12-23 01:04:17 +00003941** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3942** However, that choice is contraversial since technically the underlying
3943** file system does not always provide powersafe overwrites. (In other
3944** words, after a power-loss event, parts of the file that were never
3945** written might end up being altered.) However, non-PSOW behavior is very,
3946** very rare. And asserting PSOW makes a large reduction in the amount
3947** of required I/O for journaling, since a lot of padding is eliminated.
3948** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3949** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003950*/
drhf12b3f62011-12-21 14:42:29 +00003951static int unixDeviceCharacteristics(sqlite3_file *id){
3952 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003953 int rc = 0;
3954#ifdef __QNXNTO__
3955 if( p->sectorSize==0 ) unixSectorSize(id);
3956 rc = p->deviceCharacteristics;
3957#endif
drhcb15f352011-12-23 01:04:17 +00003958 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003959 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003960 }
drh537dddf2012-10-26 13:46:24 +00003961 return rc;
danielk197762079062007-08-15 17:08:46 +00003962}
3963
drhd9e5c4f2010-05-12 18:01:39 +00003964#ifndef SQLITE_OMIT_WAL
3965
3966
3967/*
drhd91c68f2010-05-14 14:52:25 +00003968** Object used to represent an shared memory buffer.
3969**
3970** When multiple threads all reference the same wal-index, each thread
3971** has its own unixShm object, but they all point to a single instance
3972** of this unixShmNode object. In other words, each wal-index is opened
3973** only once per process.
3974**
3975** Each unixShmNode object is connected to a single unixInodeInfo object.
3976** We could coalesce this object into unixInodeInfo, but that would mean
3977** every open file that does not use shared memory (in other words, most
3978** open files) would have to carry around this extra information. So
3979** the unixInodeInfo object contains a pointer to this unixShmNode object
3980** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003981**
3982** unixMutexHeld() must be true when creating or destroying
3983** this object or while reading or writing the following fields:
3984**
3985** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003986**
3987** The following fields are read-only after the object is created:
3988**
3989** fid
3990** zFilename
3991**
drhd91c68f2010-05-14 14:52:25 +00003992** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003993** unixMutexHeld() is true when reading or writing any other field
3994** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003995*/
drhd91c68f2010-05-14 14:52:25 +00003996struct unixShmNode {
3997 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003998 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003999 char *zFilename; /* Name of the mmapped file */
4000 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004001 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004002 u16 nRegion; /* Size of array apRegion */
4003 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004004 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004005 int nRef; /* Number of unixShm objects pointing to this */
4006 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004007#ifdef SQLITE_DEBUG
4008 u8 exclMask; /* Mask of exclusive locks held */
4009 u8 sharedMask; /* Mask of shared locks held */
4010 u8 nextShmId; /* Next available unixShm.id value */
4011#endif
4012};
4013
4014/*
drhd9e5c4f2010-05-12 18:01:39 +00004015** Structure used internally by this VFS to record the state of an
4016** open shared memory connection.
4017**
drhd91c68f2010-05-14 14:52:25 +00004018** The following fields are initialized when this object is created and
4019** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004020**
drhd91c68f2010-05-14 14:52:25 +00004021** unixShm.pFile
4022** unixShm.id
4023**
4024** All other fields are read/write. The unixShm.pFile->mutex must be held
4025** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004026*/
4027struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004028 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4029 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004030 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004031 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004032 u16 sharedMask; /* Mask of shared locks held */
4033 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004034};
4035
4036/*
drhd9e5c4f2010-05-12 18:01:39 +00004037** Constants used for locking
4038*/
drhbd9676c2010-06-23 17:58:38 +00004039#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004040#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004041
drhd9e5c4f2010-05-12 18:01:39 +00004042/*
drh73b64e42010-05-30 19:55:15 +00004043** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004044**
4045** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4046** otherwise.
4047*/
4048static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004049 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4050 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004051 int ofst, /* First byte of the locking range */
4052 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004053){
4054 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004055 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004056
drhd91c68f2010-05-14 14:52:25 +00004057 /* Access to the unixShmNode object is serialized by the caller */
4058 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004059
drh73b64e42010-05-30 19:55:15 +00004060 /* Shared locks never span more than one byte */
4061 assert( n==1 || lockType!=F_RDLCK );
4062
4063 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004064 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004065
drh3cb93392011-03-12 18:10:44 +00004066 if( pShmNode->h>=0 ){
4067 /* Initialize the locking parameters */
4068 memset(&f, 0, sizeof(f));
4069 f.l_type = lockType;
4070 f.l_whence = SEEK_SET;
4071 f.l_start = ofst;
4072 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004073
drh3cb93392011-03-12 18:10:44 +00004074 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4075 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4076 }
drhd9e5c4f2010-05-12 18:01:39 +00004077
4078 /* Update the global lock state and do debug tracing */
4079#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004080 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004081 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00004082 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004083 if( rc==SQLITE_OK ){
4084 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004085 OSTRACE(("unlock %d ok", ofst));
4086 pShmNode->exclMask &= ~mask;
4087 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004088 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004089 OSTRACE(("read-lock %d ok", ofst));
4090 pShmNode->exclMask &= ~mask;
4091 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004092 }else{
4093 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004094 OSTRACE(("write-lock %d ok", ofst));
4095 pShmNode->exclMask |= mask;
4096 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004097 }
4098 }else{
4099 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004100 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004101 }else if( lockType==F_RDLCK ){
4102 OSTRACE(("read-lock failed"));
4103 }else{
4104 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004105 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004106 }
4107 }
drh20e1f082010-05-31 16:10:12 +00004108 OSTRACE((" - afterwards %03x,%03x\n",
4109 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004110 }
drhd9e5c4f2010-05-12 18:01:39 +00004111#endif
4112
4113 return rc;
4114}
4115
drhd9e5c4f2010-05-12 18:01:39 +00004116
4117/*
drhd91c68f2010-05-14 14:52:25 +00004118** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004119**
4120** This is not a VFS shared-memory method; it is a utility function called
4121** by VFS shared-memory methods.
4122*/
drhd91c68f2010-05-14 14:52:25 +00004123static void unixShmPurge(unixFile *pFd){
4124 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004125 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004126 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00004127 int i;
drhd91c68f2010-05-14 14:52:25 +00004128 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004129 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00004130 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00004131 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004132 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004133 }else{
4134 sqlite3_free(p->apRegion[i]);
4135 }
dan13a3cb82010-06-11 19:04:21 +00004136 }
dan18801912010-06-14 14:07:50 +00004137 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004138 if( p->h>=0 ){
4139 robust_close(pFd, p->h, __LINE__);
4140 p->h = -1;
4141 }
drhd91c68f2010-05-14 14:52:25 +00004142 p->pInode->pShmNode = 0;
4143 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004144 }
4145}
4146
4147/*
danda9fe0c2010-07-13 18:44:03 +00004148** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004149** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004150**
drh7234c6d2010-06-19 15:10:09 +00004151** The file used to implement shared-memory is in the same directory
4152** as the open database file and has the same name as the open database
4153** file with the "-shm" suffix added. For example, if the database file
4154** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004155** for shared memory will be called "/home/user1/config.db-shm".
4156**
4157** Another approach to is to use files in /dev/shm or /dev/tmp or an
4158** some other tmpfs mount. But if a file in a different directory
4159** from the database file is used, then differing access permissions
4160** or a chroot() might cause two different processes on the same
4161** database to end up using different files for shared memory -
4162** meaning that their memory would not really be shared - resulting
4163** in database corruption. Nevertheless, this tmpfs file usage
4164** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4165** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4166** option results in an incompatible build of SQLite; builds of SQLite
4167** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4168** same database file at the same time, database corruption will likely
4169** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4170** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004171**
4172** When opening a new shared-memory file, if no other instances of that
4173** file are currently open, in this process or in other processes, then
4174** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004175**
4176** If the original database file (pDbFd) is using the "unix-excl" VFS
4177** that means that an exclusive lock is held on the database file and
4178** that no other processes are able to read or write the database. In
4179** that case, we do not really need shared memory. No shared memory
4180** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004181*/
danda9fe0c2010-07-13 18:44:03 +00004182static int unixOpenSharedMemory(unixFile *pDbFd){
4183 struct unixShm *p = 0; /* The connection to be opened */
4184 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4185 int rc; /* Result code */
4186 unixInodeInfo *pInode; /* The inode of fd */
4187 char *zShmFilename; /* Name of the file used for SHM */
4188 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004189
danda9fe0c2010-07-13 18:44:03 +00004190 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004191 p = sqlite3_malloc( sizeof(*p) );
4192 if( p==0 ) return SQLITE_NOMEM;
4193 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004194 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004195
danda9fe0c2010-07-13 18:44:03 +00004196 /* Check to see if a unixShmNode object already exists. Reuse an existing
4197 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004198 */
4199 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004200 pInode = pDbFd->pInode;
4201 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004202 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004203 struct stat sStat; /* fstat() info for database file */
4204
4205 /* Call fstat() to figure out the permissions on the database file. If
4206 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004207 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004208 */
drh3cb93392011-03-12 18:10:44 +00004209 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004210 rc = SQLITE_IOERR_FSTAT;
4211 goto shm_open_err;
4212 }
4213
drha4ced192010-07-15 18:32:40 +00004214#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004215 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004216#else
drh52bcde02012-01-03 14:50:45 +00004217 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004218#endif
drh7234c6d2010-06-19 15:10:09 +00004219 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004220 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004221 rc = SQLITE_NOMEM;
4222 goto shm_open_err;
4223 }
drh9cb5a0d2012-01-05 21:19:54 +00004224 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004225 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004226#ifdef SQLITE_SHM_DIRECTORY
4227 sqlite3_snprintf(nShmFilename, zShmFilename,
4228 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4229 (u32)sStat.st_ino, (u32)sStat.st_dev);
4230#else
drh7234c6d2010-06-19 15:10:09 +00004231 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004232 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004233#endif
drhd91c68f2010-05-14 14:52:25 +00004234 pShmNode->h = -1;
4235 pDbFd->pInode->pShmNode = pShmNode;
4236 pShmNode->pInode = pDbFd->pInode;
4237 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4238 if( pShmNode->mutex==0 ){
4239 rc = SQLITE_NOMEM;
4240 goto shm_open_err;
4241 }
drhd9e5c4f2010-05-12 18:01:39 +00004242
drh3cb93392011-03-12 18:10:44 +00004243 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004244 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004245 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004246 openFlags = O_RDONLY;
4247 pShmNode->isReadonly = 1;
4248 }
4249 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004250 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004251 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4252 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004253 }
drhac7c3ac2012-02-11 19:23:48 +00004254
4255 /* If this process is running as root, make sure that the SHM file
4256 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004257 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004258 */
drhed466822012-05-31 13:10:49 +00004259 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004260
4261 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004262 ** If not, truncate the file to zero length.
4263 */
4264 rc = SQLITE_OK;
4265 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4266 if( robust_ftruncate(pShmNode->h, 0) ){
4267 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004268 }
4269 }
drh66dfec8b2011-06-01 20:01:49 +00004270 if( rc==SQLITE_OK ){
4271 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4272 }
4273 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004274 }
drhd9e5c4f2010-05-12 18:01:39 +00004275 }
4276
drhd91c68f2010-05-14 14:52:25 +00004277 /* Make the new connection a child of the unixShmNode */
4278 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004279#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004280 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004281#endif
drhd91c68f2010-05-14 14:52:25 +00004282 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004283 pDbFd->pShm = p;
4284 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004285
4286 /* The reference count on pShmNode has already been incremented under
4287 ** the cover of the unixEnterMutex() mutex and the pointer from the
4288 ** new (struct unixShm) object to the pShmNode has been set. All that is
4289 ** left to do is to link the new object into the linked list starting
4290 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4291 ** mutex.
4292 */
4293 sqlite3_mutex_enter(pShmNode->mutex);
4294 p->pNext = pShmNode->pFirst;
4295 pShmNode->pFirst = p;
4296 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004297 return SQLITE_OK;
4298
4299 /* Jump here on any error */
4300shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004301 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004302 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004303 unixLeaveMutex();
4304 return rc;
4305}
4306
4307/*
danda9fe0c2010-07-13 18:44:03 +00004308** This function is called to obtain a pointer to region iRegion of the
4309** shared-memory associated with the database file fd. Shared-memory regions
4310** are numbered starting from zero. Each shared-memory region is szRegion
4311** bytes in size.
4312**
4313** If an error occurs, an error code is returned and *pp is set to NULL.
4314**
4315** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4316** region has not been allocated (by any client, including one running in a
4317** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4318** bExtend is non-zero and the requested shared-memory region has not yet
4319** been allocated, it is allocated by this function.
4320**
4321** If the shared-memory region has already been allocated or is allocated by
4322** this call as described above, then it is mapped into this processes
4323** address space (if it is not already), *pp is set to point to the mapped
4324** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004325*/
danda9fe0c2010-07-13 18:44:03 +00004326static int unixShmMap(
4327 sqlite3_file *fd, /* Handle open on database file */
4328 int iRegion, /* Region to retrieve */
4329 int szRegion, /* Size of regions */
4330 int bExtend, /* True to extend file if necessary */
4331 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004332){
danda9fe0c2010-07-13 18:44:03 +00004333 unixFile *pDbFd = (unixFile*)fd;
4334 unixShm *p;
4335 unixShmNode *pShmNode;
4336 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004337
danda9fe0c2010-07-13 18:44:03 +00004338 /* If the shared-memory file has not yet been opened, open it now. */
4339 if( pDbFd->pShm==0 ){
4340 rc = unixOpenSharedMemory(pDbFd);
4341 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004342 }
drhd9e5c4f2010-05-12 18:01:39 +00004343
danda9fe0c2010-07-13 18:44:03 +00004344 p = pDbFd->pShm;
4345 pShmNode = p->pShmNode;
4346 sqlite3_mutex_enter(pShmNode->mutex);
4347 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004348 assert( pShmNode->pInode==pDbFd->pInode );
4349 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4350 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004351
4352 if( pShmNode->nRegion<=iRegion ){
4353 char **apNew; /* New apRegion[] array */
4354 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4355 struct stat sStat; /* Used by fstat() */
4356
4357 pShmNode->szRegion = szRegion;
4358
drh3cb93392011-03-12 18:10:44 +00004359 if( pShmNode->h>=0 ){
4360 /* The requested region is not mapped into this processes address space.
4361 ** Check to see if it has been allocated (i.e. if the wal-index file is
4362 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004363 */
drh3cb93392011-03-12 18:10:44 +00004364 if( osFstat(pShmNode->h, &sStat) ){
4365 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004366 goto shmpage_out;
4367 }
drh3cb93392011-03-12 18:10:44 +00004368
4369 if( sStat.st_size<nByte ){
4370 /* The requested memory region does not exist. If bExtend is set to
4371 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004372 */
dan47a2b4a2013-04-26 16:09:29 +00004373 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004374 goto shmpage_out;
4375 }
dan47a2b4a2013-04-26 16:09:29 +00004376
4377 /* Alternatively, if bExtend is true, extend the file. Do this by
4378 ** writing a single byte to the end of each (OS) page being
4379 ** allocated or extended. Technically, we need only write to the
4380 ** last page in order to extend the file. But writing to all new
4381 ** pages forces the OS to allocate them immediately, which reduces
4382 ** the chances of SIGBUS while accessing the mapped region later on.
4383 */
4384 else{
4385 static const int pgsz = 4096;
4386 int iPg;
4387
4388 /* Write to the last byte of each newly allocated or extended page */
4389 assert( (nByte % pgsz)==0 );
4390 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4391 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4392 const char *zFile = pShmNode->zFilename;
4393 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4394 goto shmpage_out;
4395 }
4396 }
drh3cb93392011-03-12 18:10:44 +00004397 }
4398 }
danda9fe0c2010-07-13 18:44:03 +00004399 }
4400
4401 /* Map the requested memory region into this processes address space. */
4402 apNew = (char **)sqlite3_realloc(
4403 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4404 );
4405 if( !apNew ){
4406 rc = SQLITE_IOERR_NOMEM;
4407 goto shmpage_out;
4408 }
4409 pShmNode->apRegion = apNew;
4410 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004411 void *pMem;
4412 if( pShmNode->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004413 pMem = osMmap(0, szRegion,
drh66dfec8b2011-06-01 20:01:49 +00004414 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004415 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004416 );
4417 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004418 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004419 goto shmpage_out;
4420 }
4421 }else{
4422 pMem = sqlite3_malloc(szRegion);
4423 if( pMem==0 ){
4424 rc = SQLITE_NOMEM;
4425 goto shmpage_out;
4426 }
4427 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004428 }
4429 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4430 pShmNode->nRegion++;
4431 }
4432 }
4433
4434shmpage_out:
4435 if( pShmNode->nRegion>iRegion ){
4436 *pp = pShmNode->apRegion[iRegion];
4437 }else{
4438 *pp = 0;
4439 }
drh66dfec8b2011-06-01 20:01:49 +00004440 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004441 sqlite3_mutex_leave(pShmNode->mutex);
4442 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004443}
4444
4445/*
drhd9e5c4f2010-05-12 18:01:39 +00004446** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004447**
4448** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4449** different here than in posix. In xShmLock(), one can go from unlocked
4450** to shared and back or from unlocked to exclusive and back. But one may
4451** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004452*/
4453static int unixShmLock(
4454 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004455 int ofst, /* First lock to acquire or release */
4456 int n, /* Number of locks to acquire or release */
4457 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004458){
drh73b64e42010-05-30 19:55:15 +00004459 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4460 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4461 unixShm *pX; /* For looping over all siblings */
4462 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4463 int rc = SQLITE_OK; /* Result code */
4464 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004465
drhd91c68f2010-05-14 14:52:25 +00004466 assert( pShmNode==pDbFd->pInode->pShmNode );
4467 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004468 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004469 assert( n>=1 );
4470 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4471 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4472 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4473 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4474 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004475 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4476 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004477
drhc99597c2010-05-31 01:41:15 +00004478 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004479 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004480 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004481 if( flags & SQLITE_SHM_UNLOCK ){
4482 u16 allMask = 0; /* Mask of locks held by siblings */
4483
4484 /* See if any siblings hold this same lock */
4485 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4486 if( pX==p ) continue;
4487 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4488 allMask |= pX->sharedMask;
4489 }
4490
4491 /* Unlock the system-level locks */
4492 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004493 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004494 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004495 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004496 }
drh73b64e42010-05-30 19:55:15 +00004497
4498 /* Undo the local locks */
4499 if( rc==SQLITE_OK ){
4500 p->exclMask &= ~mask;
4501 p->sharedMask &= ~mask;
4502 }
4503 }else if( flags & SQLITE_SHM_SHARED ){
4504 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4505
4506 /* Find out which shared locks are already held by sibling connections.
4507 ** If any sibling already holds an exclusive lock, go ahead and return
4508 ** SQLITE_BUSY.
4509 */
4510 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004511 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004512 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004513 break;
4514 }
4515 allShared |= pX->sharedMask;
4516 }
4517
4518 /* Get shared locks at the system level, if necessary */
4519 if( rc==SQLITE_OK ){
4520 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004521 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004522 }else{
drh73b64e42010-05-30 19:55:15 +00004523 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004524 }
drhd9e5c4f2010-05-12 18:01:39 +00004525 }
drh73b64e42010-05-30 19:55:15 +00004526
4527 /* Get the local shared locks */
4528 if( rc==SQLITE_OK ){
4529 p->sharedMask |= mask;
4530 }
4531 }else{
4532 /* Make sure no sibling connections hold locks that will block this
4533 ** lock. If any do, return SQLITE_BUSY right away.
4534 */
4535 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004536 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4537 rc = SQLITE_BUSY;
4538 break;
4539 }
4540 }
4541
4542 /* Get the exclusive locks at the system level. Then if successful
4543 ** also mark the local connection as being locked.
4544 */
4545 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004546 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004547 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004548 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004549 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004550 }
drhd9e5c4f2010-05-12 18:01:39 +00004551 }
4552 }
drhd91c68f2010-05-14 14:52:25 +00004553 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004554 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4555 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004556 return rc;
4557}
4558
drh286a2882010-05-20 23:51:06 +00004559/*
4560** Implement a memory barrier or memory fence on shared memory.
4561**
4562** All loads and stores begun before the barrier must complete before
4563** any load or store begun after the barrier.
4564*/
4565static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004566 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004567){
drhff828942010-06-26 21:34:06 +00004568 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004569 unixEnterMutex();
4570 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004571}
4572
dan18801912010-06-14 14:07:50 +00004573/*
danda9fe0c2010-07-13 18:44:03 +00004574** Close a connection to shared-memory. Delete the underlying
4575** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004576**
4577** If there is no shared memory associated with the connection then this
4578** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004579*/
danda9fe0c2010-07-13 18:44:03 +00004580static int unixShmUnmap(
4581 sqlite3_file *fd, /* The underlying database file */
4582 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004583){
danda9fe0c2010-07-13 18:44:03 +00004584 unixShm *p; /* The connection to be closed */
4585 unixShmNode *pShmNode; /* The underlying shared-memory file */
4586 unixShm **pp; /* For looping over sibling connections */
4587 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004588
danda9fe0c2010-07-13 18:44:03 +00004589 pDbFd = (unixFile*)fd;
4590 p = pDbFd->pShm;
4591 if( p==0 ) return SQLITE_OK;
4592 pShmNode = p->pShmNode;
4593
4594 assert( pShmNode==pDbFd->pInode->pShmNode );
4595 assert( pShmNode->pInode==pDbFd->pInode );
4596
4597 /* Remove connection p from the set of connections associated
4598 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004599 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004600 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4601 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004602
danda9fe0c2010-07-13 18:44:03 +00004603 /* Free the connection p */
4604 sqlite3_free(p);
4605 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004606 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004607
4608 /* If pShmNode->nRef has reached 0, then close the underlying
4609 ** shared-memory file, too */
4610 unixEnterMutex();
4611 assert( pShmNode->nRef>0 );
4612 pShmNode->nRef--;
4613 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004614 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004615 unixShmPurge(pDbFd);
4616 }
4617 unixLeaveMutex();
4618
4619 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004620}
drh286a2882010-05-20 23:51:06 +00004621
danda9fe0c2010-07-13 18:44:03 +00004622
drhd9e5c4f2010-05-12 18:01:39 +00004623#else
drh6b017cc2010-06-14 18:01:46 +00004624# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004625# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004626# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004627# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004628#endif /* #ifndef SQLITE_OMIT_WAL */
4629
mistachkine98844f2013-08-24 00:59:24 +00004630#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004631/*
danaef49d72013-03-25 16:28:54 +00004632** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004633*/
danf23da962013-03-23 21:00:41 +00004634static void unixUnmapfile(unixFile *pFd){
4635 assert( pFd->nFetchOut==0 );
4636 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004637 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004638 pFd->pMapRegion = 0;
4639 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004640 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004641 }
4642}
dan5d8a1372013-03-19 19:28:06 +00004643
danaef49d72013-03-25 16:28:54 +00004644/*
dane6ecd662013-04-01 17:56:59 +00004645** Return the system page size.
4646*/
4647static int unixGetPagesize(void){
4648#if HAVE_MREMAP
4649 return 512;
drh85830a72013-04-03 00:42:01 +00004650#elif defined(_BSD_SOURCE)
dane6ecd662013-04-01 17:56:59 +00004651 return getpagesize();
4652#else
4653 return (int)sysconf(_SC_PAGESIZE);
4654#endif
4655}
4656
4657/*
4658** Attempt to set the size of the memory mapping maintained by file
4659** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4660**
4661** If successful, this function sets the following variables:
4662**
4663** unixFile.pMapRegion
4664** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004665** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004666**
4667** If unsuccessful, an error message is logged via sqlite3_log() and
4668** the three variables above are zeroed. In this case SQLite should
4669** continue accessing the database using the xRead() and xWrite()
4670** methods.
4671*/
4672static void unixRemapfile(
4673 unixFile *pFd, /* File descriptor object */
4674 i64 nNew /* Required mapping size */
4675){
dan4ff7bc42013-04-02 12:04:09 +00004676 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004677 int h = pFd->h; /* File descriptor open on db file */
4678 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004679 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004680 u8 *pNew = 0; /* Location of new mapping */
4681 int flags = PROT_READ; /* Flags to pass to mmap() */
4682
4683 assert( pFd->nFetchOut==0 );
4684 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004685 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004686 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004687 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004688 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004689
4690 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4691
4692 if( pOrig ){
4693 const int szSyspage = unixGetPagesize();
4694 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
4695 u8 *pReq = &pOrig[nReuse];
4696
4697 /* Unmap any pages of the existing mapping that cannot be reused. */
4698 if( nReuse!=nOrig ){
4699 osMunmap(pReq, nOrig-nReuse);
4700 }
4701
4702#if HAVE_MREMAP
4703 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004704 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004705#else
4706 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4707 if( pNew!=MAP_FAILED ){
4708 if( pNew!=pReq ){
4709 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004710 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004711 }else{
4712 pNew = pOrig;
4713 }
4714 }
4715#endif
4716
dan48ccef82013-04-02 20:55:01 +00004717 /* The attempt to extend the existing mapping failed. Free it. */
4718 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004719 osMunmap(pOrig, nReuse);
4720 }
4721 }
4722
4723 /* If pNew is still NULL, try to create an entirely new mapping. */
4724 if( pNew==0 ){
4725 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004726 }
4727
dan4ff7bc42013-04-02 12:04:09 +00004728 if( pNew==MAP_FAILED ){
4729 pNew = 0;
4730 nNew = 0;
4731 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4732
4733 /* If the mmap() above failed, assume that all subsequent mmap() calls
4734 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4735 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004736 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004737 }
dane6ecd662013-04-01 17:56:59 +00004738 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004739 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004740}
4741
4742/*
danaef49d72013-03-25 16:28:54 +00004743** Memory map or remap the file opened by file-descriptor pFd (if the file
4744** is already mapped, the existing mapping is replaced by the new). Or, if
4745** there already exists a mapping for this file, and there are still
4746** outstanding xFetch() references to it, this function is a no-op.
4747**
4748** If parameter nByte is non-negative, then it is the requested size of
4749** the mapping to create. Otherwise, if nByte is less than zero, then the
4750** requested size is the size of the file on disk. The actual size of the
4751** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004752** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004753**
4754** SQLITE_OK is returned if no error occurs (even if the mapping is not
4755** recreated as a result of outstanding references) or an SQLite error
4756** code otherwise.
4757*/
danf23da962013-03-23 21:00:41 +00004758static int unixMapfile(unixFile *pFd, i64 nByte){
4759 i64 nMap = nByte;
4760 int rc;
daneb97b292013-03-20 14:26:59 +00004761
danf23da962013-03-23 21:00:41 +00004762 assert( nMap>=0 || pFd->nFetchOut==0 );
4763 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4764
4765 if( nMap<0 ){
daneb97b292013-03-20 14:26:59 +00004766 struct stat statbuf; /* Low-level file information */
danf23da962013-03-23 21:00:41 +00004767 rc = osFstat(pFd->h, &statbuf);
4768 if( rc!=SQLITE_OK ){
4769 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004770 }
danf23da962013-03-23 21:00:41 +00004771 nMap = statbuf.st_size;
4772 }
drh9b4c59f2013-04-15 17:03:42 +00004773 if( nMap>pFd->mmapSizeMax ){
4774 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004775 }
4776
danf23da962013-03-23 21:00:41 +00004777 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004778 if( nMap>0 ){
4779 unixRemapfile(pFd, nMap);
4780 }else{
danb7e3a322013-03-25 20:30:13 +00004781 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004782 }
4783 }
4784
danf23da962013-03-23 21:00:41 +00004785 return SQLITE_OK;
4786}
mistachkine98844f2013-08-24 00:59:24 +00004787#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004788
danaef49d72013-03-25 16:28:54 +00004789/*
4790** If possible, return a pointer to a mapping of file fd starting at offset
4791** iOff. The mapping must be valid for at least nAmt bytes.
4792**
4793** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4794** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4795** Finally, if an error does occur, return an SQLite error code. The final
4796** value of *pp is undefined in this case.
4797**
4798** If this function does return a pointer, the caller must eventually
4799** release the reference by calling unixUnfetch().
4800*/
danf23da962013-03-23 21:00:41 +00004801static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004802#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004803 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004804#endif
danf23da962013-03-23 21:00:41 +00004805 *pp = 0;
4806
drh9b4c59f2013-04-15 17:03:42 +00004807#if SQLITE_MAX_MMAP_SIZE>0
4808 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004809 if( pFd->pMapRegion==0 ){
4810 int rc = unixMapfile(pFd, -1);
4811 if( rc!=SQLITE_OK ) return rc;
4812 }
4813 if( pFd->mmapSize >= iOff+nAmt ){
4814 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4815 pFd->nFetchOut++;
4816 }
4817 }
drh6e0b6d52013-04-09 16:19:20 +00004818#endif
danf23da962013-03-23 21:00:41 +00004819 return SQLITE_OK;
4820}
4821
danaef49d72013-03-25 16:28:54 +00004822/*
dandf737fe2013-03-25 17:00:24 +00004823** If the third argument is non-NULL, then this function releases a
4824** reference obtained by an earlier call to unixFetch(). The second
4825** argument passed to this function must be the same as the corresponding
4826** argument that was passed to the unixFetch() invocation.
4827**
4828** Or, if the third argument is NULL, then this function is being called
4829** to inform the VFS layer that, according to POSIX, any existing mapping
4830** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004831*/
dandf737fe2013-03-25 17:00:24 +00004832static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
danf23da962013-03-23 21:00:41 +00004833 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhda8caa02013-04-22 23:38:50 +00004834 UNUSED_PARAMETER(iOff);
danf23da962013-03-23 21:00:41 +00004835
mistachkinb5ca3cb2013-08-24 01:12:03 +00004836#if SQLITE_MAX_MMAP_SIZE>0
danaef49d72013-03-25 16:28:54 +00004837 /* If p==0 (unmap the entire file) then there must be no outstanding
4838 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4839 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004840 assert( (p==0)==(pFd->nFetchOut==0) );
4841
dandf737fe2013-03-25 17:00:24 +00004842 /* If p!=0, it must match the iOff value. */
4843 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4844
danf23da962013-03-23 21:00:41 +00004845 if( p ){
4846 pFd->nFetchOut--;
4847 }else{
4848 unixUnmapfile(pFd);
4849 }
4850
4851 assert( pFd->nFetchOut>=0 );
mistachkinb5ca3cb2013-08-24 01:12:03 +00004852#endif
danf23da962013-03-23 21:00:41 +00004853 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004854}
4855
4856/*
drh734c9862008-11-28 15:37:20 +00004857** Here ends the implementation of all sqlite3_file methods.
4858**
4859********************** End sqlite3_file Methods *******************************
4860******************************************************************************/
4861
4862/*
drh6b9d6dd2008-12-03 19:34:47 +00004863** This division contains definitions of sqlite3_io_methods objects that
4864** implement various file locking strategies. It also contains definitions
4865** of "finder" functions. A finder-function is used to locate the appropriate
4866** sqlite3_io_methods object for a particular database file. The pAppData
4867** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4868** the correct finder-function for that VFS.
4869**
4870** Most finder functions return a pointer to a fixed sqlite3_io_methods
4871** object. The only interesting finder-function is autolockIoFinder, which
4872** looks at the filesystem type and tries to guess the best locking
4873** strategy from that.
4874**
drh1875f7a2008-12-08 18:19:17 +00004875** For finder-funtion F, two objects are created:
4876**
4877** (1) The real finder-function named "FImpt()".
4878**
dane946c392009-08-22 11:39:46 +00004879** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004880**
4881**
4882** A pointer to the F pointer is used as the pAppData value for VFS
4883** objects. We have to do this instead of letting pAppData point
4884** directly at the finder-function since C90 rules prevent a void*
4885** from be cast into a function pointer.
4886**
drh6b9d6dd2008-12-03 19:34:47 +00004887**
drh7708e972008-11-29 00:56:52 +00004888** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004889**
drh7708e972008-11-29 00:56:52 +00004890** * A constant sqlite3_io_methods object call METHOD that has locking
4891** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4892**
4893** * An I/O method finder function called FINDER that returns a pointer
4894** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004895*/
drhd9e5c4f2010-05-12 18:01:39 +00004896#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004897static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004898 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004899 CLOSE, /* xClose */ \
4900 unixRead, /* xRead */ \
4901 unixWrite, /* xWrite */ \
4902 unixTruncate, /* xTruncate */ \
4903 unixSync, /* xSync */ \
4904 unixFileSize, /* xFileSize */ \
4905 LOCK, /* xLock */ \
4906 UNLOCK, /* xUnlock */ \
4907 CKLOCK, /* xCheckReservedLock */ \
4908 unixFileControl, /* xFileControl */ \
4909 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004910 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004911 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004912 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004913 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004914 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004915 unixFetch, /* xFetch */ \
4916 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004917}; \
drh0c2694b2009-09-03 16:23:44 +00004918static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4919 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004920 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004921} \
drh0c2694b2009-09-03 16:23:44 +00004922static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004923 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004924
4925/*
4926** Here are all of the sqlite3_io_methods objects for each of the
4927** locking strategies. Functions that return pointers to these methods
4928** are also created.
4929*/
4930IOMETHODS(
4931 posixIoFinder, /* Finder function name */
4932 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004933 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004934 unixClose, /* xClose method */
4935 unixLock, /* xLock method */
4936 unixUnlock, /* xUnlock method */
4937 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004938)
drh7708e972008-11-29 00:56:52 +00004939IOMETHODS(
4940 nolockIoFinder, /* Finder function name */
4941 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004942 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004943 nolockClose, /* xClose method */
4944 nolockLock, /* xLock method */
4945 nolockUnlock, /* xUnlock method */
4946 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004947)
drh7708e972008-11-29 00:56:52 +00004948IOMETHODS(
4949 dotlockIoFinder, /* Finder function name */
4950 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004951 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004952 dotlockClose, /* xClose method */
4953 dotlockLock, /* xLock method */
4954 dotlockUnlock, /* xUnlock method */
4955 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004956)
drh7708e972008-11-29 00:56:52 +00004957
chw78a13182009-04-07 05:35:03 +00004958#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004959IOMETHODS(
4960 flockIoFinder, /* Finder function name */
4961 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004962 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004963 flockClose, /* xClose method */
4964 flockLock, /* xLock method */
4965 flockUnlock, /* xUnlock method */
4966 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004967)
drh7708e972008-11-29 00:56:52 +00004968#endif
4969
drh6c7d5c52008-11-21 20:32:33 +00004970#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004971IOMETHODS(
4972 semIoFinder, /* Finder function name */
4973 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004974 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004975 semClose, /* xClose method */
4976 semLock, /* xLock method */
4977 semUnlock, /* xUnlock method */
4978 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004979)
aswiftaebf4132008-11-21 00:10:35 +00004980#endif
drh7708e972008-11-29 00:56:52 +00004981
drhd2cb50b2009-01-09 21:41:17 +00004982#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004983IOMETHODS(
4984 afpIoFinder, /* Finder function name */
4985 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004986 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004987 afpClose, /* xClose method */
4988 afpLock, /* xLock method */
4989 afpUnlock, /* xUnlock method */
4990 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004991)
drh715ff302008-12-03 22:32:44 +00004992#endif
4993
4994/*
4995** The proxy locking method is a "super-method" in the sense that it
4996** opens secondary file descriptors for the conch and lock files and
4997** it uses proxy, dot-file, AFP, and flock() locking methods on those
4998** secondary files. For this reason, the division that implements
4999** proxy locking is located much further down in the file. But we need
5000** to go ahead and define the sqlite3_io_methods and finder function
5001** for proxy locking here. So we forward declare the I/O methods.
5002*/
drhd2cb50b2009-01-09 21:41:17 +00005003#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005004static int proxyClose(sqlite3_file*);
5005static int proxyLock(sqlite3_file*, int);
5006static int proxyUnlock(sqlite3_file*, int);
5007static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005008IOMETHODS(
5009 proxyIoFinder, /* Finder function name */
5010 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005011 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005012 proxyClose, /* xClose method */
5013 proxyLock, /* xLock method */
5014 proxyUnlock, /* xUnlock method */
5015 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005016)
aswiftaebf4132008-11-21 00:10:35 +00005017#endif
drh7708e972008-11-29 00:56:52 +00005018
drh7ed97b92010-01-20 13:07:21 +00005019/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5020#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5021IOMETHODS(
5022 nfsIoFinder, /* Finder function name */
5023 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005024 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005025 unixClose, /* xClose method */
5026 unixLock, /* xLock method */
5027 nfsUnlock, /* xUnlock method */
5028 unixCheckReservedLock /* xCheckReservedLock method */
5029)
5030#endif
drh7708e972008-11-29 00:56:52 +00005031
drhd2cb50b2009-01-09 21:41:17 +00005032#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005033/*
drh6b9d6dd2008-12-03 19:34:47 +00005034** This "finder" function attempts to determine the best locking strategy
5035** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005036** object that implements that strategy.
5037**
5038** This is for MacOSX only.
5039*/
drh1875f7a2008-12-08 18:19:17 +00005040static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005041 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005042 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005043){
5044 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005045 const char *zFilesystem; /* Filesystem type name */
5046 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005047 } aMap[] = {
5048 { "hfs", &posixIoMethods },
5049 { "ufs", &posixIoMethods },
5050 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005051 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005052 { "webdav", &nolockIoMethods },
5053 { 0, 0 }
5054 };
5055 int i;
5056 struct statfs fsInfo;
5057 struct flock lockInfo;
5058
5059 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005060 /* If filePath==NULL that means we are dealing with a transient file
5061 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005062 return &nolockIoMethods;
5063 }
5064 if( statfs(filePath, &fsInfo) != -1 ){
5065 if( fsInfo.f_flags & MNT_RDONLY ){
5066 return &nolockIoMethods;
5067 }
5068 for(i=0; aMap[i].zFilesystem; i++){
5069 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5070 return aMap[i].pMethods;
5071 }
5072 }
5073 }
5074
5075 /* Default case. Handles, amongst others, "nfs".
5076 ** Test byte-range lock using fcntl(). If the call succeeds,
5077 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005078 */
drh7708e972008-11-29 00:56:52 +00005079 lockInfo.l_len = 1;
5080 lockInfo.l_start = 0;
5081 lockInfo.l_whence = SEEK_SET;
5082 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005083 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005084 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5085 return &nfsIoMethods;
5086 } else {
5087 return &posixIoMethods;
5088 }
drh7708e972008-11-29 00:56:52 +00005089 }else{
5090 return &dotlockIoMethods;
5091 }
5092}
drh0c2694b2009-09-03 16:23:44 +00005093static const sqlite3_io_methods
5094 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005095
drhd2cb50b2009-01-09 21:41:17 +00005096#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005097
chw78a13182009-04-07 05:35:03 +00005098#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5099/*
5100** This "finder" function attempts to determine the best locking strategy
5101** for the database file "filePath". It then returns the sqlite3_io_methods
5102** object that implements that strategy.
5103**
5104** This is for VXWorks only.
5105*/
5106static const sqlite3_io_methods *autolockIoFinderImpl(
5107 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005108 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005109){
5110 struct flock lockInfo;
5111
5112 if( !filePath ){
5113 /* If filePath==NULL that means we are dealing with a transient file
5114 ** that does not need to be locked. */
5115 return &nolockIoMethods;
5116 }
5117
5118 /* Test if fcntl() is supported and use POSIX style locks.
5119 ** Otherwise fall back to the named semaphore method.
5120 */
5121 lockInfo.l_len = 1;
5122 lockInfo.l_start = 0;
5123 lockInfo.l_whence = SEEK_SET;
5124 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005125 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005126 return &posixIoMethods;
5127 }else{
5128 return &semIoMethods;
5129 }
5130}
drh0c2694b2009-09-03 16:23:44 +00005131static const sqlite3_io_methods
5132 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005133
5134#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5135
drh7708e972008-11-29 00:56:52 +00005136/*
5137** An abstract type for a pointer to a IO method finder function:
5138*/
drh0c2694b2009-09-03 16:23:44 +00005139typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005140
aswiftaebf4132008-11-21 00:10:35 +00005141
drh734c9862008-11-28 15:37:20 +00005142/****************************************************************************
5143**************************** sqlite3_vfs methods ****************************
5144**
5145** This division contains the implementation of methods on the
5146** sqlite3_vfs object.
5147*/
5148
danielk1977a3d4c882007-03-23 10:08:38 +00005149/*
danielk1977e339d652008-06-28 11:23:00 +00005150** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005151*/
5152static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005153 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005154 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005155 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005156 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005157 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005158){
drh7708e972008-11-29 00:56:52 +00005159 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005160 unixFile *pNew = (unixFile *)pId;
5161 int rc = SQLITE_OK;
5162
drh8af6c222010-05-14 12:43:01 +00005163 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005164
dan00157392010-10-05 11:33:15 +00005165 /* Usually the path zFilename should not be a relative pathname. The
5166 ** exception is when opening the proxy "conch" file in builds that
5167 ** include the special Apple locking styles.
5168 */
dan00157392010-10-05 11:33:15 +00005169#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005170 assert( zFilename==0 || zFilename[0]=='/'
5171 || pVfs->pAppData==(void*)&autolockIoFinder );
5172#else
5173 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005174#endif
dan00157392010-10-05 11:33:15 +00005175
drhb07028f2011-10-14 21:49:18 +00005176 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005177 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005178
drh308c2a52010-05-14 11:30:18 +00005179 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005180 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005181 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005182 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005183 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005184#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005185 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005186#endif
drhc02a43a2012-01-10 23:18:38 +00005187 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5188 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005189 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005190 }
drh503a6862013-03-01 01:07:17 +00005191 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005192 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005193 }
drh339eb0b2008-03-07 15:34:11 +00005194
drh6c7d5c52008-11-21 20:32:33 +00005195#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005196 pNew->pId = vxworksFindFileId(zFilename);
5197 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005198 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005199 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005200 }
5201#endif
5202
drhc02a43a2012-01-10 23:18:38 +00005203 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005204 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005205 }else{
drh0c2694b2009-09-03 16:23:44 +00005206 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005207#if SQLITE_ENABLE_LOCKING_STYLE
5208 /* Cache zFilename in the locking context (AFP and dotlock override) for
5209 ** proxyLock activation is possible (remote proxy is based on db name)
5210 ** zFilename remains valid until file is closed, to support */
5211 pNew->lockingContext = (void*)zFilename;
5212#endif
drhda0e7682008-07-30 15:27:54 +00005213 }
danielk1977e339d652008-06-28 11:23:00 +00005214
drh7ed97b92010-01-20 13:07:21 +00005215 if( pLockingStyle == &posixIoMethods
5216#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5217 || pLockingStyle == &nfsIoMethods
5218#endif
5219 ){
drh7708e972008-11-29 00:56:52 +00005220 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005221 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005222 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005223 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005224 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005225 ** in two scenarios:
5226 **
5227 ** (a) A call to fstat() failed.
5228 ** (b) A malloc failed.
5229 **
5230 ** Scenario (b) may only occur if the process is holding no other
5231 ** file descriptors open on the same file. If there were other file
5232 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005233 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005234 ** handle h - as it is guaranteed that no posix locks will be released
5235 ** by doing so.
5236 **
5237 ** If scenario (a) caused the error then things are not so safe. The
5238 ** implicit assumption here is that if fstat() fails, things are in
5239 ** such bad shape that dropping a lock or two doesn't matter much.
5240 */
drh0e9365c2011-03-02 02:08:13 +00005241 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005242 h = -1;
5243 }
drh7708e972008-11-29 00:56:52 +00005244 unixLeaveMutex();
5245 }
danielk1977e339d652008-06-28 11:23:00 +00005246
drhd2cb50b2009-01-09 21:41:17 +00005247#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005248 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005249 /* AFP locking uses the file path so it needs to be included in
5250 ** the afpLockingContext.
5251 */
5252 afpLockingContext *pCtx;
5253 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5254 if( pCtx==0 ){
5255 rc = SQLITE_NOMEM;
5256 }else{
5257 /* NB: zFilename exists and remains valid until the file is closed
5258 ** according to requirement F11141. So we do not need to make a
5259 ** copy of the filename. */
5260 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005261 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005262 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005263 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005264 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005265 if( rc!=SQLITE_OK ){
5266 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005267 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005268 h = -1;
5269 }
drh7708e972008-11-29 00:56:52 +00005270 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005271 }
drh7708e972008-11-29 00:56:52 +00005272 }
5273#endif
danielk1977e339d652008-06-28 11:23:00 +00005274
drh7708e972008-11-29 00:56:52 +00005275 else if( pLockingStyle == &dotlockIoMethods ){
5276 /* Dotfile locking uses the file path so it needs to be included in
5277 ** the dotlockLockingContext
5278 */
5279 char *zLockFile;
5280 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005281 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005282 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005283 zLockFile = (char *)sqlite3_malloc(nFilename);
5284 if( zLockFile==0 ){
5285 rc = SQLITE_NOMEM;
5286 }else{
5287 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005288 }
drh7708e972008-11-29 00:56:52 +00005289 pNew->lockingContext = zLockFile;
5290 }
danielk1977e339d652008-06-28 11:23:00 +00005291
drh6c7d5c52008-11-21 20:32:33 +00005292#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005293 else if( pLockingStyle == &semIoMethods ){
5294 /* Named semaphore locking uses the file path so it needs to be
5295 ** included in the semLockingContext
5296 */
5297 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005298 rc = findInodeInfo(pNew, &pNew->pInode);
5299 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5300 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005301 int n;
drh2238dcc2009-08-27 17:56:20 +00005302 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005303 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005304 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005305 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005306 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5307 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005308 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005309 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005310 }
chw97185482008-11-17 08:05:31 +00005311 }
drh7708e972008-11-29 00:56:52 +00005312 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005313 }
drh7708e972008-11-29 00:56:52 +00005314#endif
aswift5b1a2562008-08-22 00:22:35 +00005315
5316 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005317#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005318 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005319 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005320 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005321 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005322 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005323 }
chw97185482008-11-17 08:05:31 +00005324#endif
danielk1977e339d652008-06-28 11:23:00 +00005325 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005326 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005327 }else{
drh7708e972008-11-29 00:56:52 +00005328 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005329 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005330 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005331 }
danielk1977e339d652008-06-28 11:23:00 +00005332 return rc;
drh054889e2005-11-30 03:20:31 +00005333}
drh9c06c952005-11-26 00:25:00 +00005334
danielk1977ad94b582007-08-20 06:44:22 +00005335/*
drh8b3cf822010-06-01 21:02:51 +00005336** Return the name of a directory in which to put temporary files.
5337** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005338*/
drh7234c6d2010-06-19 15:10:09 +00005339static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005340 static const char *azDirs[] = {
5341 0,
aswiftaebf4132008-11-21 00:10:35 +00005342 0,
mistachkind95a3d32013-08-30 21:52:38 +00005343 0,
danielk197717b90b52008-06-06 11:11:25 +00005344 "/var/tmp",
5345 "/usr/tmp",
5346 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005347 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005348 };
drh8b3cf822010-06-01 21:02:51 +00005349 unsigned int i;
5350 struct stat buf;
5351 const char *zDir = 0;
5352
5353 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005354 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5355 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005356 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005357 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005358 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005359 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005360 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005361 break;
5362 }
5363 return zDir;
5364}
5365
5366/*
5367** Create a temporary file name in zBuf. zBuf must be allocated
5368** by the calling process and must be big enough to hold at least
5369** pVfs->mxPathname bytes.
5370*/
5371static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005372 static const unsigned char zChars[] =
5373 "abcdefghijklmnopqrstuvwxyz"
5374 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5375 "0123456789";
drh41022642008-11-21 00:24:42 +00005376 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005377 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005378
5379 /* It's odd to simulate an io-error here, but really this is just
5380 ** using the io-error infrastructure to test that SQLite handles this
5381 ** function failing.
5382 */
5383 SimulateIOError( return SQLITE_IOERR );
5384
drh7234c6d2010-06-19 15:10:09 +00005385 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005386 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005387
5388 /* Check that the output buffer is large enough for the temporary file
5389 ** name. If it is not, return SQLITE_ERROR.
5390 */
drhc02a43a2012-01-10 23:18:38 +00005391 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005392 return SQLITE_ERROR;
5393 }
5394
5395 do{
drhc02a43a2012-01-10 23:18:38 +00005396 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005397 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005398 sqlite3_randomness(15, &zBuf[j]);
5399 for(i=0; i<15; i++, j++){
5400 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5401 }
5402 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005403 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005404 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005405 return SQLITE_OK;
5406}
5407
drhd2cb50b2009-01-09 21:41:17 +00005408#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005409/*
5410** Routine to transform a unixFile into a proxy-locking unixFile.
5411** Implementation in the proxy-lock division, but used by unixOpen()
5412** if SQLITE_PREFER_PROXY_LOCKING is defined.
5413*/
5414static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005415#endif
drhc66d5b62008-12-03 22:48:32 +00005416
dan08da86a2009-08-21 17:18:03 +00005417/*
5418** Search for an unused file descriptor that was opened on the database
5419** file (not a journal or master-journal file) identified by pathname
5420** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5421** argument to this function.
5422**
5423** Such a file descriptor may exist if a database connection was closed
5424** but the associated file descriptor could not be closed because some
5425** other file descriptor open on the same file is holding a file-lock.
5426** Refer to comments in the unixClose() function and the lengthy comment
5427** describing "Posix Advisory Locking" at the start of this file for
5428** further details. Also, ticket #4018.
5429**
5430** If a suitable file descriptor is found, then it is returned. If no
5431** such file descriptor is located, -1 is returned.
5432*/
dane946c392009-08-22 11:39:46 +00005433static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5434 UnixUnusedFd *pUnused = 0;
5435
5436 /* Do not search for an unused file descriptor on vxworks. Not because
5437 ** vxworks would not benefit from the change (it might, we're not sure),
5438 ** but because no way to test it is currently available. It is better
5439 ** not to risk breaking vxworks support for the sake of such an obscure
5440 ** feature. */
5441#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005442 struct stat sStat; /* Results of stat() call */
5443
5444 /* A stat() call may fail for various reasons. If this happens, it is
5445 ** almost certain that an open() call on the same path will also fail.
5446 ** For this reason, if an error occurs in the stat() call here, it is
5447 ** ignored and -1 is returned. The caller will try to open a new file
5448 ** descriptor on the same path, fail, and return an error to SQLite.
5449 **
5450 ** Even if a subsequent open() call does succeed, the consequences of
5451 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005452 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005453 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005454
5455 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005456 pInode = inodeList;
5457 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5458 || pInode->fileId.ino!=sStat.st_ino) ){
5459 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005460 }
drh8af6c222010-05-14 12:43:01 +00005461 if( pInode ){
dane946c392009-08-22 11:39:46 +00005462 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005463 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005464 pUnused = *pp;
5465 if( pUnused ){
5466 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005467 }
5468 }
5469 unixLeaveMutex();
5470 }
dane946c392009-08-22 11:39:46 +00005471#endif /* if !OS_VXWORKS */
5472 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005473}
danielk197717b90b52008-06-06 11:11:25 +00005474
5475/*
danddb0ac42010-07-14 14:48:58 +00005476** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005477** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005478** and a value suitable for passing as the third argument to open(2) is
5479** written to *pMode. If an IO error occurs, an SQLite error code is
5480** returned and the value of *pMode is not modified.
5481**
drh8c815d12012-02-13 20:16:37 +00005482** In most cases cases, this routine sets *pMode to 0, which will become
5483** an indication to robust_open() to create the file using
5484** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5485** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005486** this function queries the file-system for the permissions on the
5487** corresponding database file and sets *pMode to this value. Whenever
5488** possible, WAL and journal files are created using the same permissions
5489** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005490**
5491** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5492** original filename is unavailable. But 8_3_NAMES is only used for
5493** FAT filesystems and permissions do not matter there, so just use
5494** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005495*/
5496static int findCreateFileMode(
5497 const char *zPath, /* Path of file (possibly) being created */
5498 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005499 mode_t *pMode, /* OUT: Permissions to open file with */
5500 uid_t *pUid, /* OUT: uid to set on the file */
5501 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005502){
5503 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005504 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005505 *pUid = 0;
5506 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005507 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005508 char zDb[MAX_PATHNAME+1]; /* Database file path */
5509 int nDb; /* Number of valid bytes in zDb */
5510 struct stat sStat; /* Output of stat() on database file */
5511
dana0c989d2010-11-05 18:07:37 +00005512 /* zPath is a path to a WAL or journal file. The following block derives
5513 ** the path to the associated database file from zPath. This block handles
5514 ** the following naming conventions:
5515 **
5516 ** "<path to db>-journal"
5517 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005518 ** "<path to db>-journalNN"
5519 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005520 **
drhd337c5b2011-10-20 18:23:35 +00005521 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005522 ** used by the test_multiplex.c module.
5523 */
5524 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005525#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005526 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005527 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005528#else
5529 while( zPath[nDb]!='-' ){
5530 assert( nDb>0 );
5531 assert( zPath[nDb]!='\n' );
5532 nDb--;
5533 }
5534#endif
danddb0ac42010-07-14 14:48:58 +00005535 memcpy(zDb, zPath, nDb);
5536 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005537
drh58384f12011-07-28 00:14:45 +00005538 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005539 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005540 *pUid = sStat.st_uid;
5541 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005542 }else{
5543 rc = SQLITE_IOERR_FSTAT;
5544 }
5545 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5546 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005547 }
5548 return rc;
5549}
5550
5551/*
danielk1977ad94b582007-08-20 06:44:22 +00005552** Open the file zPath.
5553**
danielk1977b4b47412007-08-17 15:53:36 +00005554** Previously, the SQLite OS layer used three functions in place of this
5555** one:
5556**
5557** sqlite3OsOpenReadWrite();
5558** sqlite3OsOpenReadOnly();
5559** sqlite3OsOpenExclusive();
5560**
5561** These calls correspond to the following combinations of flags:
5562**
5563** ReadWrite() -> (READWRITE | CREATE)
5564** ReadOnly() -> (READONLY)
5565** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5566**
5567** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5568** true, the file was configured to be automatically deleted when the
5569** file handle closed. To achieve the same effect using this new
5570** interface, add the DELETEONCLOSE flag to those specified above for
5571** OpenExclusive().
5572*/
5573static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005574 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5575 const char *zPath, /* Pathname of file to be opened */
5576 sqlite3_file *pFile, /* The file descriptor to be filled in */
5577 int flags, /* Input flags to control the opening */
5578 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005579){
dan08da86a2009-08-21 17:18:03 +00005580 unixFile *p = (unixFile *)pFile;
5581 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005582 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005583 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005584 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005585 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005586 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005587
5588 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5589 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5590 int isCreate = (flags & SQLITE_OPEN_CREATE);
5591 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5592 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005593#if SQLITE_ENABLE_LOCKING_STYLE
5594 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5595#endif
drh3d4435b2011-08-26 20:55:50 +00005596#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5597 struct statfs fsInfo;
5598#endif
danielk1977b4b47412007-08-17 15:53:36 +00005599
danielk1977fee2d252007-08-18 10:59:19 +00005600 /* If creating a master or main-file journal, this function will open
5601 ** a file-descriptor on the directory too. The first time unixSync()
5602 ** is called the directory file descriptor will be fsync()ed and close()d.
5603 */
drh0059eae2011-08-08 23:48:40 +00005604 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005605 eType==SQLITE_OPEN_MASTER_JOURNAL
5606 || eType==SQLITE_OPEN_MAIN_JOURNAL
5607 || eType==SQLITE_OPEN_WAL
5608 ));
danielk1977fee2d252007-08-18 10:59:19 +00005609
danielk197717b90b52008-06-06 11:11:25 +00005610 /* If argument zPath is a NULL pointer, this function is required to open
5611 ** a temporary file. Use this buffer to store the file name in.
5612 */
drhc02a43a2012-01-10 23:18:38 +00005613 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005614 const char *zName = zPath;
5615
danielk1977fee2d252007-08-18 10:59:19 +00005616 /* Check the following statements are true:
5617 **
5618 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5619 ** (b) if CREATE is set, then READWRITE must also be set, and
5620 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005621 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005622 */
danielk1977b4b47412007-08-17 15:53:36 +00005623 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005624 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005625 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005626 assert(isDelete==0 || isCreate);
5627
danddb0ac42010-07-14 14:48:58 +00005628 /* The main DB, main journal, WAL file and master journal are never
5629 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005630 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5631 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5632 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005633 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005634
danielk1977fee2d252007-08-18 10:59:19 +00005635 /* Assert that the upper layer has set one of the "file-type" flags. */
5636 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5637 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5638 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005639 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005640 );
5641
dan08da86a2009-08-21 17:18:03 +00005642 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005643
dan08da86a2009-08-21 17:18:03 +00005644 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005645 UnixUnusedFd *pUnused;
5646 pUnused = findReusableFd(zName, flags);
5647 if( pUnused ){
5648 fd = pUnused->fd;
5649 }else{
dan6aa657f2009-08-24 18:57:58 +00005650 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005651 if( !pUnused ){
5652 return SQLITE_NOMEM;
5653 }
5654 }
5655 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005656
5657 /* Database filenames are double-zero terminated if they are not
5658 ** URIs with parameters. Hence, they can always be passed into
5659 ** sqlite3_uri_parameter(). */
5660 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5661
dan08da86a2009-08-21 17:18:03 +00005662 }else if( !zName ){
5663 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005664 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005665 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005666 if( rc!=SQLITE_OK ){
5667 return rc;
5668 }
5669 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005670
5671 /* Generated temporary filenames are always double-zero terminated
5672 ** for use by sqlite3_uri_parameter(). */
5673 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005674 }
5675
dan08da86a2009-08-21 17:18:03 +00005676 /* Determine the value of the flags parameter passed to POSIX function
5677 ** open(). These must be calculated even if open() is not called, as
5678 ** they may be stored as part of the file handle and used by the
5679 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005680 if( isReadonly ) openFlags |= O_RDONLY;
5681 if( isReadWrite ) openFlags |= O_RDWR;
5682 if( isCreate ) openFlags |= O_CREAT;
5683 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5684 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005685
danielk1977b4b47412007-08-17 15:53:36 +00005686 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005687 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005688 uid_t uid; /* Userid for the file */
5689 gid_t gid; /* Groupid for the file */
5690 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005691 if( rc!=SQLITE_OK ){
5692 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005693 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005694 return rc;
5695 }
drhad4f1e52011-03-04 15:43:57 +00005696 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005697 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005698 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5699 /* Failed to open the file for read/write access. Try read-only. */
5700 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005701 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005702 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005703 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005704 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005705 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005706 }
5707 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005708 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005709 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005710 }
drhac7c3ac2012-02-11 19:23:48 +00005711
5712 /* If this process is running as root and if creating a new rollback
5713 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005714 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005715 */
5716 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005717 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005718 }
danielk1977b4b47412007-08-17 15:53:36 +00005719 }
dan08da86a2009-08-21 17:18:03 +00005720 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005721 if( pOutFlags ){
5722 *pOutFlags = flags;
5723 }
5724
dane946c392009-08-22 11:39:46 +00005725 if( p->pUnused ){
5726 p->pUnused->fd = fd;
5727 p->pUnused->flags = flags;
5728 }
5729
danielk1977b4b47412007-08-17 15:53:36 +00005730 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005731#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005732 zPath = zName;
5733#else
drh036ac7f2011-08-08 23:18:05 +00005734 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005735#endif
danielk1977b4b47412007-08-17 15:53:36 +00005736 }
drh41022642008-11-21 00:24:42 +00005737#if SQLITE_ENABLE_LOCKING_STYLE
5738 else{
dan08da86a2009-08-21 17:18:03 +00005739 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005740 }
5741#endif
5742
drhda0e7682008-07-30 15:27:54 +00005743 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005744
drh7ed97b92010-01-20 13:07:21 +00005745
5746#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005747 if( fstatfs(fd, &fsInfo) == -1 ){
5748 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005749 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005750 return SQLITE_IOERR_ACCESS;
5751 }
5752 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5753 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5754 }
5755#endif
drhc02a43a2012-01-10 23:18:38 +00005756
5757 /* Set up appropriate ctrlFlags */
5758 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5759 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5760 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5761 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5762 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5763
drh7ed97b92010-01-20 13:07:21 +00005764#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005765#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005766 isAutoProxy = 1;
5767#endif
5768 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005769 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5770 int useProxy = 0;
5771
dan08da86a2009-08-21 17:18:03 +00005772 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5773 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005774 if( envforce!=NULL ){
5775 useProxy = atoi(envforce)>0;
5776 }else{
aswiftaebf4132008-11-21 00:10:35 +00005777 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005778 /* In theory, the close(fd) call is sub-optimal. If the file opened
5779 ** with fd is a database file, and there are other connections open
5780 ** on that file that are currently holding advisory locks on it,
5781 ** then the call to close() will cancel those locks. In practice,
5782 ** we're assuming that statfs() doesn't fail very often. At least
5783 ** not while other file descriptors opened by the same process on
5784 ** the same file are working. */
5785 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005786 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005787 rc = SQLITE_IOERR_ACCESS;
5788 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005789 }
5790 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5791 }
5792 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005793 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005794 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005795 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005796 if( rc!=SQLITE_OK ){
5797 /* Use unixClose to clean up the resources added in fillInUnixFile
5798 ** and clear all the structure's references. Specifically,
5799 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5800 */
5801 unixClose(pFile);
5802 return rc;
5803 }
aswiftaebf4132008-11-21 00:10:35 +00005804 }
dane946c392009-08-22 11:39:46 +00005805 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005806 }
5807 }
5808#endif
5809
drhc02a43a2012-01-10 23:18:38 +00005810 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5811
dane946c392009-08-22 11:39:46 +00005812open_finished:
5813 if( rc!=SQLITE_OK ){
5814 sqlite3_free(p->pUnused);
5815 }
5816 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005817}
5818
dane946c392009-08-22 11:39:46 +00005819
danielk1977b4b47412007-08-17 15:53:36 +00005820/*
danielk1977fee2d252007-08-18 10:59:19 +00005821** Delete the file at zPath. If the dirSync argument is true, fsync()
5822** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005823*/
drh6b9d6dd2008-12-03 19:34:47 +00005824static int unixDelete(
5825 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5826 const char *zPath, /* Name of file to be deleted */
5827 int dirSync /* If true, fsync() directory after deleting file */
5828){
danielk1977fee2d252007-08-18 10:59:19 +00005829 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005830 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005831 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005832 if( osUnlink(zPath)==(-1) ){
5833 if( errno==ENOENT ){
5834 rc = SQLITE_IOERR_DELETE_NOENT;
5835 }else{
drhb4308162012-11-09 21:40:02 +00005836 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005837 }
drhb4308162012-11-09 21:40:02 +00005838 return rc;
drh5d4feff2010-07-14 01:45:22 +00005839 }
danielk1977d39fa702008-10-16 13:27:40 +00005840#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005841 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005842 int fd;
drh90315a22011-08-10 01:52:12 +00005843 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005844 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005845#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005846 if( fsync(fd)==-1 )
5847#else
5848 if( fsync(fd) )
5849#endif
5850 {
dane18d4952011-02-21 11:46:24 +00005851 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005852 }
drh0e9365c2011-03-02 02:08:13 +00005853 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005854 }else if( rc==SQLITE_CANTOPEN ){
5855 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005856 }
5857 }
danielk1977d138dd82008-10-15 16:02:48 +00005858#endif
danielk1977fee2d252007-08-18 10:59:19 +00005859 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005860}
5861
danielk197790949c22007-08-17 16:50:38 +00005862/*
mistachkin48864df2013-03-21 21:20:32 +00005863** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005864** test performed depends on the value of flags:
5865**
5866** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5867** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5868** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5869**
5870** Otherwise return 0.
5871*/
danielk1977861f7452008-06-05 11:39:11 +00005872static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005873 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5874 const char *zPath, /* Path of the file to examine */
5875 int flags, /* What do we want to learn about the zPath file? */
5876 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005877){
rse25c0d1a2007-09-20 08:38:14 +00005878 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005879 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005880 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005881 switch( flags ){
5882 case SQLITE_ACCESS_EXISTS:
5883 amode = F_OK;
5884 break;
5885 case SQLITE_ACCESS_READWRITE:
5886 amode = W_OK|R_OK;
5887 break;
drh50d3f902007-08-27 21:10:36 +00005888 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005889 amode = R_OK;
5890 break;
5891
5892 default:
5893 assert(!"Invalid flags argument");
5894 }
drh99ab3b12011-03-02 15:09:07 +00005895 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005896 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5897 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005898 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005899 *pResOut = 0;
5900 }
5901 }
danielk1977861f7452008-06-05 11:39:11 +00005902 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005903}
5904
danielk1977b4b47412007-08-17 15:53:36 +00005905
5906/*
5907** Turn a relative pathname into a full pathname. The relative path
5908** is stored as a nul-terminated string in the buffer pointed to by
5909** zPath.
5910**
5911** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5912** (in this case, MAX_PATHNAME bytes). The full-path is written to
5913** this buffer before returning.
5914*/
danielk1977adfb9b02007-09-17 07:02:56 +00005915static int unixFullPathname(
5916 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5917 const char *zPath, /* Possibly relative input path */
5918 int nOut, /* Size of output buffer in bytes */
5919 char *zOut /* Output buffer */
5920){
danielk1977843e65f2007-09-01 16:16:15 +00005921
5922 /* It's odd to simulate an io-error here, but really this is just
5923 ** using the io-error infrastructure to test that SQLite handles this
5924 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005925 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005926 */
5927 SimulateIOError( return SQLITE_ERROR );
5928
drh153c62c2007-08-24 03:51:33 +00005929 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005930 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005931
drh3c7f2dc2007-12-06 13:26:20 +00005932 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005933 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005934 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005935 }else{
5936 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005937 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005938 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005939 }
drhea678832008-12-10 19:26:22 +00005940 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005941 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005942 }
5943 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005944}
5945
drh0ccebe72005-06-07 22:22:50 +00005946
drh761df872006-12-21 01:29:22 +00005947#ifndef SQLITE_OMIT_LOAD_EXTENSION
5948/*
5949** Interfaces for opening a shared library, finding entry points
5950** within the shared library, and closing the shared library.
5951*/
5952#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005953static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5954 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005955 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5956}
danielk197795c8a542007-09-01 06:51:27 +00005957
5958/*
5959** SQLite calls this function immediately after a call to unixDlSym() or
5960** unixDlOpen() fails (returns a null pointer). If a more detailed error
5961** message is available, it is written to zBufOut. If no error message
5962** is available, zBufOut is left unmodified and SQLite uses a default
5963** error message.
5964*/
danielk1977397d65f2008-11-19 11:35:39 +00005965static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005966 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005967 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005968 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005969 zErr = dlerror();
5970 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005971 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005972 }
drh6c7d5c52008-11-21 20:32:33 +00005973 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005974}
drh1875f7a2008-12-08 18:19:17 +00005975static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5976 /*
5977 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5978 ** cast into a pointer to a function. And yet the library dlsym() routine
5979 ** returns a void* which is really a pointer to a function. So how do we
5980 ** use dlsym() with -pedantic-errors?
5981 **
5982 ** Variable x below is defined to be a pointer to a function taking
5983 ** parameters void* and const char* and returning a pointer to a function.
5984 ** We initialize x by assigning it a pointer to the dlsym() function.
5985 ** (That assignment requires a cast.) Then we call the function that
5986 ** x points to.
5987 **
5988 ** This work-around is unlikely to work correctly on any system where
5989 ** you really cannot cast a function pointer into void*. But then, on the
5990 ** other hand, dlsym() will not work on such a system either, so we have
5991 ** not really lost anything.
5992 */
5993 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005994 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005995 x = (void(*(*)(void*,const char*))(void))dlsym;
5996 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005997}
danielk1977397d65f2008-11-19 11:35:39 +00005998static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5999 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006000 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006001}
danielk1977b4b47412007-08-17 15:53:36 +00006002#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6003 #define unixDlOpen 0
6004 #define unixDlError 0
6005 #define unixDlSym 0
6006 #define unixDlClose 0
6007#endif
6008
6009/*
danielk197790949c22007-08-17 16:50:38 +00006010** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006011*/
danielk1977397d65f2008-11-19 11:35:39 +00006012static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6013 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006014 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006015
drhbbd42a62004-05-22 17:41:58 +00006016 /* We have to initialize zBuf to prevent valgrind from reporting
6017 ** errors. The reports issued by valgrind are incorrect - we would
6018 ** prefer that the randomness be increased by making use of the
6019 ** uninitialized space in zBuf - but valgrind errors tend to worry
6020 ** some users. Rather than argue, it seems easier just to initialize
6021 ** the whole array and silence valgrind, even if that means less randomness
6022 ** in the random seed.
6023 **
6024 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006025 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006026 ** tests repeatable.
6027 */
danielk1977b4b47412007-08-17 15:53:36 +00006028 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00006029#if !defined(SQLITE_TEST)
6030 {
drhc18b4042012-02-10 03:10:27 +00006031 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00006032 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006033 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006034 time_t t;
6035 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006036 memcpy(zBuf, &t, sizeof(t));
6037 pid = getpid();
6038 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00006039 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00006040 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00006041 }else{
drhc18b4042012-02-10 03:10:27 +00006042 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006043 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006044 }
drhbbd42a62004-05-22 17:41:58 +00006045 }
6046#endif
drh72cbd072008-10-14 17:58:38 +00006047 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006048}
6049
danielk1977b4b47412007-08-17 15:53:36 +00006050
drhbbd42a62004-05-22 17:41:58 +00006051/*
6052** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006053** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006054** The return value is the number of microseconds of sleep actually
6055** requested from the underlying operating system, a number which
6056** might be greater than or equal to the argument, but not less
6057** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006058*/
danielk1977397d65f2008-11-19 11:35:39 +00006059static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006060#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006061 struct timespec sp;
6062
6063 sp.tv_sec = microseconds / 1000000;
6064 sp.tv_nsec = (microseconds % 1000000) * 1000;
6065 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006066 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006067 return microseconds;
6068#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006069 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006070 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006071 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006072#else
danielk1977b4b47412007-08-17 15:53:36 +00006073 int seconds = (microseconds+999999)/1000000;
6074 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006075 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006076 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006077#endif
drh88f474a2006-01-02 20:00:12 +00006078}
6079
6080/*
drh6b9d6dd2008-12-03 19:34:47 +00006081** The following variable, if set to a non-zero value, is interpreted as
6082** the number of seconds since 1970 and is used to set the result of
6083** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006084*/
6085#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006086int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006087#endif
6088
6089/*
drhb7e8ea22010-05-03 14:32:30 +00006090** Find the current time (in Universal Coordinated Time). Write into *piNow
6091** the current time and date as a Julian Day number times 86_400_000. In
6092** other words, write into *piNow the number of milliseconds since the Julian
6093** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6094** proleptic Gregorian calendar.
6095**
drh31702252011-10-12 23:13:43 +00006096** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6097** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006098*/
6099static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6100 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006101 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006102#if defined(NO_GETTOD)
6103 time_t t;
6104 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006105 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006106#elif OS_VXWORKS
6107 struct timespec sNow;
6108 clock_gettime(CLOCK_REALTIME, &sNow);
6109 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6110#else
6111 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006112 if( gettimeofday(&sNow, 0)==0 ){
6113 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6114 }else{
6115 rc = SQLITE_ERROR;
6116 }
drhb7e8ea22010-05-03 14:32:30 +00006117#endif
6118
6119#ifdef SQLITE_TEST
6120 if( sqlite3_current_time ){
6121 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6122 }
6123#endif
6124 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006125 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006126}
6127
6128/*
drhbbd42a62004-05-22 17:41:58 +00006129** Find the current time (in Universal Coordinated Time). Write the
6130** current time and date as a Julian Day number into *prNow and
6131** return 0. Return 1 if the time and date cannot be found.
6132*/
danielk1977397d65f2008-11-19 11:35:39 +00006133static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006134 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006135 int rc;
drhff828942010-06-26 21:34:06 +00006136 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006137 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006138 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006139 return rc;
drhbbd42a62004-05-22 17:41:58 +00006140}
danielk1977b4b47412007-08-17 15:53:36 +00006141
drh6b9d6dd2008-12-03 19:34:47 +00006142/*
6143** We added the xGetLastError() method with the intention of providing
6144** better low-level error messages when operating-system problems come up
6145** during SQLite operation. But so far, none of that has been implemented
6146** in the core. So this routine is never called. For now, it is merely
6147** a place-holder.
6148*/
danielk1977397d65f2008-11-19 11:35:39 +00006149static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6150 UNUSED_PARAMETER(NotUsed);
6151 UNUSED_PARAMETER(NotUsed2);
6152 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006153 return 0;
6154}
6155
drhf2424c52010-04-26 00:04:55 +00006156
6157/*
drh734c9862008-11-28 15:37:20 +00006158************************ End of sqlite3_vfs methods ***************************
6159******************************************************************************/
6160
drh715ff302008-12-03 22:32:44 +00006161/******************************************************************************
6162************************** Begin Proxy Locking ********************************
6163**
6164** Proxy locking is a "uber-locking-method" in this sense: It uses the
6165** other locking methods on secondary lock files. Proxy locking is a
6166** meta-layer over top of the primitive locking implemented above. For
6167** this reason, the division that implements of proxy locking is deferred
6168** until late in the file (here) after all of the other I/O methods have
6169** been defined - so that the primitive locking methods are available
6170** as services to help with the implementation of proxy locking.
6171**
6172****
6173**
6174** The default locking schemes in SQLite use byte-range locks on the
6175** database file to coordinate safe, concurrent access by multiple readers
6176** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6177** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6178** as POSIX read & write locks over fixed set of locations (via fsctl),
6179** on AFP and SMB only exclusive byte-range locks are available via fsctl
6180** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6181** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6182** address in the shared range is taken for a SHARED lock, the entire
6183** shared range is taken for an EXCLUSIVE lock):
6184**
drhf2f105d2012-08-20 15:53:54 +00006185** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006186** RESERVED_BYTE 0x40000001
6187** SHARED_RANGE 0x40000002 -> 0x40000200
6188**
6189** This works well on the local file system, but shows a nearly 100x
6190** slowdown in read performance on AFP because the AFP client disables
6191** the read cache when byte-range locks are present. Enabling the read
6192** cache exposes a cache coherency problem that is present on all OS X
6193** supported network file systems. NFS and AFP both observe the
6194** close-to-open semantics for ensuring cache coherency
6195** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6196** address the requirements for concurrent database access by multiple
6197** readers and writers
6198** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6199**
6200** To address the performance and cache coherency issues, proxy file locking
6201** changes the way database access is controlled by limiting access to a
6202** single host at a time and moving file locks off of the database file
6203** and onto a proxy file on the local file system.
6204**
6205**
6206** Using proxy locks
6207** -----------------
6208**
6209** C APIs
6210**
6211** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6212** <proxy_path> | ":auto:");
6213** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6214**
6215**
6216** SQL pragmas
6217**
6218** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6219** PRAGMA [database.]lock_proxy_file
6220**
6221** Specifying ":auto:" means that if there is a conch file with a matching
6222** host ID in it, the proxy path in the conch file will be used, otherwise
6223** a proxy path based on the user's temp dir
6224** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6225** actual proxy file name is generated from the name and path of the
6226** database file. For example:
6227**
6228** For database path "/Users/me/foo.db"
6229** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6230**
6231** Once a lock proxy is configured for a database connection, it can not
6232** be removed, however it may be switched to a different proxy path via
6233** the above APIs (assuming the conch file is not being held by another
6234** connection or process).
6235**
6236**
6237** How proxy locking works
6238** -----------------------
6239**
6240** Proxy file locking relies primarily on two new supporting files:
6241**
6242** * conch file to limit access to the database file to a single host
6243** at a time
6244**
6245** * proxy file to act as a proxy for the advisory locks normally
6246** taken on the database
6247**
6248** The conch file - to use a proxy file, sqlite must first "hold the conch"
6249** by taking an sqlite-style shared lock on the conch file, reading the
6250** contents and comparing the host's unique host ID (see below) and lock
6251** proxy path against the values stored in the conch. The conch file is
6252** stored in the same directory as the database file and the file name
6253** is patterned after the database file name as ".<databasename>-conch".
6254** If the conch file does not exist, or it's contents do not match the
6255** host ID and/or proxy path, then the lock is escalated to an exclusive
6256** lock and the conch file contents is updated with the host ID and proxy
6257** path and the lock is downgraded to a shared lock again. If the conch
6258** is held by another process (with a shared lock), the exclusive lock
6259** will fail and SQLITE_BUSY is returned.
6260**
6261** The proxy file - a single-byte file used for all advisory file locks
6262** normally taken on the database file. This allows for safe sharing
6263** of the database file for multiple readers and writers on the same
6264** host (the conch ensures that they all use the same local lock file).
6265**
drh715ff302008-12-03 22:32:44 +00006266** Requesting the lock proxy does not immediately take the conch, it is
6267** only taken when the first request to lock database file is made.
6268** This matches the semantics of the traditional locking behavior, where
6269** opening a connection to a database file does not take a lock on it.
6270** The shared lock and an open file descriptor are maintained until
6271** the connection to the database is closed.
6272**
6273** The proxy file and the lock file are never deleted so they only need
6274** to be created the first time they are used.
6275**
6276** Configuration options
6277** ---------------------
6278**
6279** SQLITE_PREFER_PROXY_LOCKING
6280**
6281** Database files accessed on non-local file systems are
6282** automatically configured for proxy locking, lock files are
6283** named automatically using the same logic as
6284** PRAGMA lock_proxy_file=":auto:"
6285**
6286** SQLITE_PROXY_DEBUG
6287**
6288** Enables the logging of error messages during host id file
6289** retrieval and creation
6290**
drh715ff302008-12-03 22:32:44 +00006291** LOCKPROXYDIR
6292**
6293** Overrides the default directory used for lock proxy files that
6294** are named automatically via the ":auto:" setting
6295**
6296** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6297**
6298** Permissions to use when creating a directory for storing the
6299** lock proxy files, only used when LOCKPROXYDIR is not set.
6300**
6301**
6302** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6303** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6304** force proxy locking to be used for every database file opened, and 0
6305** will force automatic proxy locking to be disabled for all database
6306** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6307** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6308*/
6309
6310/*
6311** Proxy locking is only available on MacOSX
6312*/
drhd2cb50b2009-01-09 21:41:17 +00006313#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006314
drh715ff302008-12-03 22:32:44 +00006315/*
6316** The proxyLockingContext has the path and file structures for the remote
6317** and local proxy files in it
6318*/
6319typedef struct proxyLockingContext proxyLockingContext;
6320struct proxyLockingContext {
6321 unixFile *conchFile; /* Open conch file */
6322 char *conchFilePath; /* Name of the conch file */
6323 unixFile *lockProxy; /* Open proxy lock file */
6324 char *lockProxyPath; /* Name of the proxy lock file */
6325 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006326 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006327 void *oldLockingContext; /* Original lockingcontext to restore on close */
6328 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6329};
6330
drh7ed97b92010-01-20 13:07:21 +00006331/*
6332** The proxy lock file path for the database at dbPath is written into lPath,
6333** which must point to valid, writable memory large enough for a maxLen length
6334** file path.
drh715ff302008-12-03 22:32:44 +00006335*/
drh715ff302008-12-03 22:32:44 +00006336static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6337 int len;
6338 int dbLen;
6339 int i;
6340
6341#ifdef LOCKPROXYDIR
6342 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6343#else
6344# ifdef _CS_DARWIN_USER_TEMP_DIR
6345 {
drh7ed97b92010-01-20 13:07:21 +00006346 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006347 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6348 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006349 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006350 }
drh7ed97b92010-01-20 13:07:21 +00006351 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006352 }
6353# else
6354 len = strlcpy(lPath, "/tmp/", maxLen);
6355# endif
6356#endif
6357
6358 if( lPath[len-1]!='/' ){
6359 len = strlcat(lPath, "/", maxLen);
6360 }
6361
6362 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006363 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006364 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006365 char c = dbPath[i];
6366 lPath[i+len] = (c=='/')?'_':c;
6367 }
6368 lPath[i+len]='\0';
6369 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006370 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006371 return SQLITE_OK;
6372}
6373
drh7ed97b92010-01-20 13:07:21 +00006374/*
6375 ** Creates the lock file and any missing directories in lockPath
6376 */
6377static int proxyCreateLockPath(const char *lockPath){
6378 int i, len;
6379 char buf[MAXPATHLEN];
6380 int start = 0;
6381
6382 assert(lockPath!=NULL);
6383 /* try to create all the intermediate directories */
6384 len = (int)strlen(lockPath);
6385 buf[0] = lockPath[0];
6386 for( i=1; i<len; i++ ){
6387 if( lockPath[i] == '/' && (i - start > 0) ){
6388 /* only mkdir if leaf dir != "." or "/" or ".." */
6389 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6390 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6391 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006392 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006393 int err=errno;
6394 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006395 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006396 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006397 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006398 return err;
6399 }
6400 }
6401 }
6402 start=i+1;
6403 }
6404 buf[i] = lockPath[i];
6405 }
drh308c2a52010-05-14 11:30:18 +00006406 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006407 return 0;
6408}
6409
drh715ff302008-12-03 22:32:44 +00006410/*
6411** Create a new VFS file descriptor (stored in memory obtained from
6412** sqlite3_malloc) and open the file named "path" in the file descriptor.
6413**
6414** The caller is responsible not only for closing the file descriptor
6415** but also for freeing the memory associated with the file descriptor.
6416*/
drh7ed97b92010-01-20 13:07:21 +00006417static int proxyCreateUnixFile(
6418 const char *path, /* path for the new unixFile */
6419 unixFile **ppFile, /* unixFile created and returned by ref */
6420 int islockfile /* if non zero missing dirs will be created */
6421) {
6422 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006423 unixFile *pNew;
6424 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006425 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006426 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006427 int terrno = 0;
6428 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006429
drh7ed97b92010-01-20 13:07:21 +00006430 /* 1. first try to open/create the file
6431 ** 2. if that fails, and this is a lock file (not-conch), try creating
6432 ** the parent directories and then try again.
6433 ** 3. if that fails, try to open the file read-only
6434 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6435 */
6436 pUnused = findReusableFd(path, openFlags);
6437 if( pUnused ){
6438 fd = pUnused->fd;
6439 }else{
6440 pUnused = sqlite3_malloc(sizeof(*pUnused));
6441 if( !pUnused ){
6442 return SQLITE_NOMEM;
6443 }
6444 }
6445 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006446 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006447 terrno = errno;
6448 if( fd<0 && errno==ENOENT && islockfile ){
6449 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006450 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006451 }
6452 }
6453 }
6454 if( fd<0 ){
6455 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006456 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006457 terrno = errno;
6458 }
6459 if( fd<0 ){
6460 if( islockfile ){
6461 return SQLITE_BUSY;
6462 }
6463 switch (terrno) {
6464 case EACCES:
6465 return SQLITE_PERM;
6466 case EIO:
6467 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6468 default:
drh9978c972010-02-23 17:36:32 +00006469 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006470 }
6471 }
6472
6473 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6474 if( pNew==NULL ){
6475 rc = SQLITE_NOMEM;
6476 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006477 }
6478 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006479 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006480 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006481 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006482 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006483 pUnused->fd = fd;
6484 pUnused->flags = openFlags;
6485 pNew->pUnused = pUnused;
6486
drhc02a43a2012-01-10 23:18:38 +00006487 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006488 if( rc==SQLITE_OK ){
6489 *ppFile = pNew;
6490 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006491 }
drh7ed97b92010-01-20 13:07:21 +00006492end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006493 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006494 sqlite3_free(pNew);
6495 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006496 return rc;
6497}
6498
drh7ed97b92010-01-20 13:07:21 +00006499#ifdef SQLITE_TEST
6500/* simulate multiple hosts by creating unique hostid file paths */
6501int sqlite3_hostid_num = 0;
6502#endif
6503
6504#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6505
drh0ab216a2010-07-02 17:10:40 +00006506/* Not always defined in the headers as it ought to be */
6507extern int gethostuuid(uuid_t id, const struct timespec *wait);
6508
drh7ed97b92010-01-20 13:07:21 +00006509/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6510** bytes of writable memory.
6511*/
6512static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006513 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6514 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006515#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6516 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006517 {
6518 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6519 if( gethostuuid(pHostID, &timeout) ){
6520 int err = errno;
6521 if( pError ){
6522 *pError = err;
6523 }
6524 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006525 }
drh7ed97b92010-01-20 13:07:21 +00006526 }
drh3d4435b2011-08-26 20:55:50 +00006527#else
6528 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006529#endif
drh7ed97b92010-01-20 13:07:21 +00006530#ifdef SQLITE_TEST
6531 /* simulate multiple hosts by creating unique hostid file paths */
6532 if( sqlite3_hostid_num != 0){
6533 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6534 }
6535#endif
6536
6537 return SQLITE_OK;
6538}
6539
6540/* The conch file contains the header, host id and lock file path
6541 */
6542#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6543#define PROXY_HEADERLEN 1 /* conch file header length */
6544#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6545#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6546
6547/*
6548** Takes an open conch file, copies the contents to a new path and then moves
6549** it back. The newly created file's file descriptor is assigned to the
6550** conch file structure and finally the original conch file descriptor is
6551** closed. Returns zero if successful.
6552*/
6553static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6554 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6555 unixFile *conchFile = pCtx->conchFile;
6556 char tPath[MAXPATHLEN];
6557 char buf[PROXY_MAXCONCHLEN];
6558 char *cPath = pCtx->conchFilePath;
6559 size_t readLen = 0;
6560 size_t pathLen = 0;
6561 char errmsg[64] = "";
6562 int fd = -1;
6563 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006564 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006565
6566 /* create a new path by replace the trailing '-conch' with '-break' */
6567 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6568 if( pathLen>MAXPATHLEN || pathLen<6 ||
6569 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006570 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006571 goto end_breaklock;
6572 }
6573 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006574 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006575 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006576 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006577 goto end_breaklock;
6578 }
6579 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006580 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006581 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006582 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006583 goto end_breaklock;
6584 }
drhe562be52011-03-02 18:01:10 +00006585 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006586 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006587 goto end_breaklock;
6588 }
6589 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006590 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006591 goto end_breaklock;
6592 }
6593 rc = 0;
6594 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006595 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006596 conchFile->h = fd;
6597 conchFile->openFlags = O_RDWR | O_CREAT;
6598
6599end_breaklock:
6600 if( rc ){
6601 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006602 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006603 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006604 }
6605 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6606 }
6607 return rc;
6608}
6609
6610/* Take the requested lock on the conch file and break a stale lock if the
6611** host id matches.
6612*/
6613static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6614 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6615 unixFile *conchFile = pCtx->conchFile;
6616 int rc = SQLITE_OK;
6617 int nTries = 0;
6618 struct timespec conchModTime;
6619
drh3d4435b2011-08-26 20:55:50 +00006620 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006621 do {
6622 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6623 nTries ++;
6624 if( rc==SQLITE_BUSY ){
6625 /* If the lock failed (busy):
6626 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6627 * 2nd try: fail if the mod time changed or host id is different, wait
6628 * 10 sec and try again
6629 * 3rd try: break the lock unless the mod time has changed.
6630 */
6631 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006632 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006633 pFile->lastErrno = errno;
6634 return SQLITE_IOERR_LOCK;
6635 }
6636
6637 if( nTries==1 ){
6638 conchModTime = buf.st_mtimespec;
6639 usleep(500000); /* wait 0.5 sec and try the lock again*/
6640 continue;
6641 }
6642
6643 assert( nTries>1 );
6644 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6645 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6646 return SQLITE_BUSY;
6647 }
6648
6649 if( nTries==2 ){
6650 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006651 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006652 if( len<0 ){
6653 pFile->lastErrno = errno;
6654 return SQLITE_IOERR_LOCK;
6655 }
6656 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6657 /* don't break the lock if the host id doesn't match */
6658 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6659 return SQLITE_BUSY;
6660 }
6661 }else{
6662 /* don't break the lock on short read or a version mismatch */
6663 return SQLITE_BUSY;
6664 }
6665 usleep(10000000); /* wait 10 sec and try the lock again */
6666 continue;
6667 }
6668
6669 assert( nTries==3 );
6670 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6671 rc = SQLITE_OK;
6672 if( lockType==EXCLUSIVE_LOCK ){
6673 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6674 }
6675 if( !rc ){
6676 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6677 }
6678 }
6679 }
6680 } while( rc==SQLITE_BUSY && nTries<3 );
6681
6682 return rc;
6683}
6684
6685/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006686** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6687** lockPath means that the lockPath in the conch file will be used if the
6688** host IDs match, or a new lock path will be generated automatically
6689** and written to the conch file.
6690*/
6691static int proxyTakeConch(unixFile *pFile){
6692 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6693
drh7ed97b92010-01-20 13:07:21 +00006694 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006695 return SQLITE_OK;
6696 }else{
6697 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006698 uuid_t myHostID;
6699 int pError = 0;
6700 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006701 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006702 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006703 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006704 int createConch = 0;
6705 int hostIdMatch = 0;
6706 int readLen = 0;
6707 int tryOldLockPath = 0;
6708 int forceNewLockPath = 0;
6709
drh308c2a52010-05-14 11:30:18 +00006710 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6711 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006712
drh7ed97b92010-01-20 13:07:21 +00006713 rc = proxyGetHostID(myHostID, &pError);
6714 if( (rc&0xff)==SQLITE_IOERR ){
6715 pFile->lastErrno = pError;
6716 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006717 }
drh7ed97b92010-01-20 13:07:21 +00006718 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006719 if( rc!=SQLITE_OK ){
6720 goto end_takeconch;
6721 }
drh7ed97b92010-01-20 13:07:21 +00006722 /* read the existing conch file */
6723 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6724 if( readLen<0 ){
6725 /* I/O error: lastErrno set by seekAndRead */
6726 pFile->lastErrno = conchFile->lastErrno;
6727 rc = SQLITE_IOERR_READ;
6728 goto end_takeconch;
6729 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6730 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6731 /* a short read or version format mismatch means we need to create a new
6732 ** conch file.
6733 */
6734 createConch = 1;
6735 }
6736 /* if the host id matches and the lock path already exists in the conch
6737 ** we'll try to use the path there, if we can't open that path, we'll
6738 ** retry with a new auto-generated path
6739 */
6740 do { /* in case we need to try again for an :auto: named lock file */
6741
6742 if( !createConch && !forceNewLockPath ){
6743 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6744 PROXY_HOSTIDLEN);
6745 /* if the conch has data compare the contents */
6746 if( !pCtx->lockProxyPath ){
6747 /* for auto-named local lock file, just check the host ID and we'll
6748 ** use the local lock file path that's already in there
6749 */
6750 if( hostIdMatch ){
6751 size_t pathLen = (readLen - PROXY_PATHINDEX);
6752
6753 if( pathLen>=MAXPATHLEN ){
6754 pathLen=MAXPATHLEN-1;
6755 }
6756 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6757 lockPath[pathLen] = 0;
6758 tempLockPath = lockPath;
6759 tryOldLockPath = 1;
6760 /* create a copy of the lock path if the conch is taken */
6761 goto end_takeconch;
6762 }
6763 }else if( hostIdMatch
6764 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6765 readLen-PROXY_PATHINDEX)
6766 ){
6767 /* conch host and lock path match */
6768 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006769 }
drh7ed97b92010-01-20 13:07:21 +00006770 }
6771
6772 /* if the conch isn't writable and doesn't match, we can't take it */
6773 if( (conchFile->openFlags&O_RDWR) == 0 ){
6774 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006775 goto end_takeconch;
6776 }
drh7ed97b92010-01-20 13:07:21 +00006777
6778 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006779 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006780 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6781 tempLockPath = lockPath;
6782 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006783 }
drh7ed97b92010-01-20 13:07:21 +00006784
6785 /* update conch with host and path (this will fail if other process
6786 ** has a shared lock already), if the host id matches, use the big
6787 ** stick.
drh715ff302008-12-03 22:32:44 +00006788 */
drh7ed97b92010-01-20 13:07:21 +00006789 futimes(conchFile->h, NULL);
6790 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006791 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006792 /* We are trying for an exclusive lock but another thread in this
6793 ** same process is still holding a shared lock. */
6794 rc = SQLITE_BUSY;
6795 } else {
6796 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006797 }
drh715ff302008-12-03 22:32:44 +00006798 }else{
drh7ed97b92010-01-20 13:07:21 +00006799 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006800 }
drh7ed97b92010-01-20 13:07:21 +00006801 if( rc==SQLITE_OK ){
6802 char writeBuffer[PROXY_MAXCONCHLEN];
6803 int writeSize = 0;
6804
6805 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6806 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6807 if( pCtx->lockProxyPath!=NULL ){
6808 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6809 }else{
6810 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6811 }
6812 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006813 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006814 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6815 fsync(conchFile->h);
6816 /* If we created a new conch file (not just updated the contents of a
6817 ** valid conch file), try to match the permissions of the database
6818 */
6819 if( rc==SQLITE_OK && createConch ){
6820 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006821 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006822 if( err==0 ){
6823 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6824 S_IROTH|S_IWOTH);
6825 /* try to match the database file R/W permissions, ignore failure */
6826#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006827 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006828#else
drhff812312011-02-23 13:33:46 +00006829 do{
drhe562be52011-03-02 18:01:10 +00006830 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006831 }while( rc==(-1) && errno==EINTR );
6832 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006833 int code = errno;
6834 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6835 cmode, code, strerror(code));
6836 } else {
6837 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6838 }
6839 }else{
6840 int code = errno;
6841 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6842 err, code, strerror(code));
6843#endif
6844 }
drh715ff302008-12-03 22:32:44 +00006845 }
6846 }
drh7ed97b92010-01-20 13:07:21 +00006847 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6848
6849 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006850 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006851 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006852 int fd;
drh7ed97b92010-01-20 13:07:21 +00006853 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006854 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006855 }
6856 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006857 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006858 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006859 if( fd>=0 ){
6860 pFile->h = fd;
6861 }else{
drh9978c972010-02-23 17:36:32 +00006862 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006863 during locking */
6864 }
6865 }
6866 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6867 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6868 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6869 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6870 /* we couldn't create the proxy lock file with the old lock file path
6871 ** so try again via auto-naming
6872 */
6873 forceNewLockPath = 1;
6874 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006875 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006876 }
6877 }
6878 if( rc==SQLITE_OK ){
6879 /* Need to make a copy of path if we extracted the value
6880 ** from the conch file or the path was allocated on the stack
6881 */
6882 if( tempLockPath ){
6883 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6884 if( !pCtx->lockProxyPath ){
6885 rc = SQLITE_NOMEM;
6886 }
6887 }
6888 }
6889 if( rc==SQLITE_OK ){
6890 pCtx->conchHeld = 1;
6891
6892 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6893 afpLockingContext *afpCtx;
6894 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6895 afpCtx->dbPath = pCtx->lockProxyPath;
6896 }
6897 } else {
6898 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6899 }
drh308c2a52010-05-14 11:30:18 +00006900 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6901 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006902 return rc;
drh308c2a52010-05-14 11:30:18 +00006903 } while (1); /* in case we need to retry the :auto: lock file -
6904 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006905 }
6906}
6907
6908/*
6909** If pFile holds a lock on a conch file, then release that lock.
6910*/
6911static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006912 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006913 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6914 unixFile *conchFile; /* Name of the conch file */
6915
6916 pCtx = (proxyLockingContext *)pFile->lockingContext;
6917 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006918 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006919 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006920 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006921 if( pCtx->conchHeld>0 ){
6922 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6923 }
drh715ff302008-12-03 22:32:44 +00006924 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006925 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6926 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006927 return rc;
6928}
6929
6930/*
6931** Given the name of a database file, compute the name of its conch file.
6932** Store the conch filename in memory obtained from sqlite3_malloc().
6933** Make *pConchPath point to the new name. Return SQLITE_OK on success
6934** or SQLITE_NOMEM if unable to obtain memory.
6935**
6936** The caller is responsible for ensuring that the allocated memory
6937** space is eventually freed.
6938**
6939** *pConchPath is set to NULL if a memory allocation error occurs.
6940*/
6941static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6942 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006943 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006944 char *conchPath; /* buffer in which to construct conch name */
6945
6946 /* Allocate space for the conch filename and initialize the name to
6947 ** the name of the original database file. */
6948 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6949 if( conchPath==0 ){
6950 return SQLITE_NOMEM;
6951 }
6952 memcpy(conchPath, dbPath, len+1);
6953
6954 /* now insert a "." before the last / character */
6955 for( i=(len-1); i>=0; i-- ){
6956 if( conchPath[i]=='/' ){
6957 i++;
6958 break;
6959 }
6960 }
6961 conchPath[i]='.';
6962 while ( i<len ){
6963 conchPath[i+1]=dbPath[i];
6964 i++;
6965 }
6966
6967 /* append the "-conch" suffix to the file */
6968 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006969 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006970
6971 return SQLITE_OK;
6972}
6973
6974
6975/* Takes a fully configured proxy locking-style unix file and switches
6976** the local lock file path
6977*/
6978static int switchLockProxyPath(unixFile *pFile, const char *path) {
6979 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6980 char *oldPath = pCtx->lockProxyPath;
6981 int rc = SQLITE_OK;
6982
drh308c2a52010-05-14 11:30:18 +00006983 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006984 return SQLITE_BUSY;
6985 }
6986
6987 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6988 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6989 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6990 return SQLITE_OK;
6991 }else{
6992 unixFile *lockProxy = pCtx->lockProxy;
6993 pCtx->lockProxy=NULL;
6994 pCtx->conchHeld = 0;
6995 if( lockProxy!=NULL ){
6996 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6997 if( rc ) return rc;
6998 sqlite3_free(lockProxy);
6999 }
7000 sqlite3_free(oldPath);
7001 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7002 }
7003
7004 return rc;
7005}
7006
7007/*
7008** pFile is a file that has been opened by a prior xOpen call. dbPath
7009** is a string buffer at least MAXPATHLEN+1 characters in size.
7010**
7011** This routine find the filename associated with pFile and writes it
7012** int dbPath.
7013*/
7014static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007015#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007016 if( pFile->pMethod == &afpIoMethods ){
7017 /* afp style keeps a reference to the db path in the filePath field
7018 ** of the struct */
drhea678832008-12-10 19:26:22 +00007019 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007020 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
7021 } else
drh715ff302008-12-03 22:32:44 +00007022#endif
7023 if( pFile->pMethod == &dotlockIoMethods ){
7024 /* dot lock style uses the locking context to store the dot lock
7025 ** file path */
7026 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7027 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7028 }else{
7029 /* all other styles use the locking context to store the db file path */
7030 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007031 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007032 }
7033 return SQLITE_OK;
7034}
7035
7036/*
7037** Takes an already filled in unix file and alters it so all file locking
7038** will be performed on the local proxy lock file. The following fields
7039** are preserved in the locking context so that they can be restored and
7040** the unix structure properly cleaned up at close time:
7041** ->lockingContext
7042** ->pMethod
7043*/
7044static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7045 proxyLockingContext *pCtx;
7046 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7047 char *lockPath=NULL;
7048 int rc = SQLITE_OK;
7049
drh308c2a52010-05-14 11:30:18 +00007050 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007051 return SQLITE_BUSY;
7052 }
7053 proxyGetDbPathForUnixFile(pFile, dbPath);
7054 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7055 lockPath=NULL;
7056 }else{
7057 lockPath=(char *)path;
7058 }
7059
drh308c2a52010-05-14 11:30:18 +00007060 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7061 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007062
7063 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7064 if( pCtx==0 ){
7065 return SQLITE_NOMEM;
7066 }
7067 memset(pCtx, 0, sizeof(*pCtx));
7068
7069 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7070 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007071 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7072 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7073 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7074 ** (c) the file system is read-only, then enable no-locking access.
7075 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7076 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7077 */
7078 struct statfs fsInfo;
7079 struct stat conchInfo;
7080 int goLockless = 0;
7081
drh99ab3b12011-03-02 15:09:07 +00007082 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007083 int err = errno;
7084 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7085 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7086 }
7087 }
7088 if( goLockless ){
7089 pCtx->conchHeld = -1; /* read only FS/ lockless */
7090 rc = SQLITE_OK;
7091 }
7092 }
drh715ff302008-12-03 22:32:44 +00007093 }
7094 if( rc==SQLITE_OK && lockPath ){
7095 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7096 }
7097
7098 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007099 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7100 if( pCtx->dbPath==NULL ){
7101 rc = SQLITE_NOMEM;
7102 }
7103 }
7104 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007105 /* all memory is allocated, proxys are created and assigned,
7106 ** switch the locking context and pMethod then return.
7107 */
drh715ff302008-12-03 22:32:44 +00007108 pCtx->oldLockingContext = pFile->lockingContext;
7109 pFile->lockingContext = pCtx;
7110 pCtx->pOldMethod = pFile->pMethod;
7111 pFile->pMethod = &proxyIoMethods;
7112 }else{
7113 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007114 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007115 sqlite3_free(pCtx->conchFile);
7116 }
drhd56b1212010-08-11 06:14:15 +00007117 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007118 sqlite3_free(pCtx->conchFilePath);
7119 sqlite3_free(pCtx);
7120 }
drh308c2a52010-05-14 11:30:18 +00007121 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7122 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007123 return rc;
7124}
7125
7126
7127/*
7128** This routine handles sqlite3_file_control() calls that are specific
7129** to proxy locking.
7130*/
7131static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7132 switch( op ){
7133 case SQLITE_GET_LOCKPROXYFILE: {
7134 unixFile *pFile = (unixFile*)id;
7135 if( pFile->pMethod == &proxyIoMethods ){
7136 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7137 proxyTakeConch(pFile);
7138 if( pCtx->lockProxyPath ){
7139 *(const char **)pArg = pCtx->lockProxyPath;
7140 }else{
7141 *(const char **)pArg = ":auto: (not held)";
7142 }
7143 } else {
7144 *(const char **)pArg = NULL;
7145 }
7146 return SQLITE_OK;
7147 }
7148 case SQLITE_SET_LOCKPROXYFILE: {
7149 unixFile *pFile = (unixFile*)id;
7150 int rc = SQLITE_OK;
7151 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7152 if( pArg==NULL || (const char *)pArg==0 ){
7153 if( isProxyStyle ){
7154 /* turn off proxy locking - not supported */
7155 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7156 }else{
7157 /* turn off proxy locking - already off - NOOP */
7158 rc = SQLITE_OK;
7159 }
7160 }else{
7161 const char *proxyPath = (const char *)pArg;
7162 if( isProxyStyle ){
7163 proxyLockingContext *pCtx =
7164 (proxyLockingContext*)pFile->lockingContext;
7165 if( !strcmp(pArg, ":auto:")
7166 || (pCtx->lockProxyPath &&
7167 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7168 ){
7169 rc = SQLITE_OK;
7170 }else{
7171 rc = switchLockProxyPath(pFile, proxyPath);
7172 }
7173 }else{
7174 /* turn on proxy file locking */
7175 rc = proxyTransformUnixFile(pFile, proxyPath);
7176 }
7177 }
7178 return rc;
7179 }
7180 default: {
7181 assert( 0 ); /* The call assures that only valid opcodes are sent */
7182 }
7183 }
7184 /*NOTREACHED*/
7185 return SQLITE_ERROR;
7186}
7187
7188/*
7189** Within this division (the proxying locking implementation) the procedures
7190** above this point are all utilities. The lock-related methods of the
7191** proxy-locking sqlite3_io_method object follow.
7192*/
7193
7194
7195/*
7196** This routine checks if there is a RESERVED lock held on the specified
7197** file by this or any other process. If such a lock is held, set *pResOut
7198** to a non-zero value otherwise *pResOut is set to zero. The return value
7199** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7200*/
7201static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7202 unixFile *pFile = (unixFile*)id;
7203 int rc = proxyTakeConch(pFile);
7204 if( rc==SQLITE_OK ){
7205 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007206 if( pCtx->conchHeld>0 ){
7207 unixFile *proxy = pCtx->lockProxy;
7208 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7209 }else{ /* conchHeld < 0 is lockless */
7210 pResOut=0;
7211 }
drh715ff302008-12-03 22:32:44 +00007212 }
7213 return rc;
7214}
7215
7216/*
drh308c2a52010-05-14 11:30:18 +00007217** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007218** of the following:
7219**
7220** (1) SHARED_LOCK
7221** (2) RESERVED_LOCK
7222** (3) PENDING_LOCK
7223** (4) EXCLUSIVE_LOCK
7224**
7225** Sometimes when requesting one lock state, additional lock states
7226** are inserted in between. The locking might fail on one of the later
7227** transitions leaving the lock state different from what it started but
7228** still short of its goal. The following chart shows the allowed
7229** transitions and the inserted intermediate states:
7230**
7231** UNLOCKED -> SHARED
7232** SHARED -> RESERVED
7233** SHARED -> (PENDING) -> EXCLUSIVE
7234** RESERVED -> (PENDING) -> EXCLUSIVE
7235** PENDING -> EXCLUSIVE
7236**
7237** This routine will only increase a lock. Use the sqlite3OsUnlock()
7238** routine to lower a locking level.
7239*/
drh308c2a52010-05-14 11:30:18 +00007240static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007241 unixFile *pFile = (unixFile*)id;
7242 int rc = proxyTakeConch(pFile);
7243 if( rc==SQLITE_OK ){
7244 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007245 if( pCtx->conchHeld>0 ){
7246 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007247 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7248 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007249 }else{
7250 /* conchHeld < 0 is lockless */
7251 }
drh715ff302008-12-03 22:32:44 +00007252 }
7253 return rc;
7254}
7255
7256
7257/*
drh308c2a52010-05-14 11:30:18 +00007258** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007259** must be either NO_LOCK or SHARED_LOCK.
7260**
7261** If the locking level of the file descriptor is already at or below
7262** the requested locking level, this routine is a no-op.
7263*/
drh308c2a52010-05-14 11:30:18 +00007264static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007265 unixFile *pFile = (unixFile*)id;
7266 int rc = proxyTakeConch(pFile);
7267 if( rc==SQLITE_OK ){
7268 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007269 if( pCtx->conchHeld>0 ){
7270 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007271 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7272 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007273 }else{
7274 /* conchHeld < 0 is lockless */
7275 }
drh715ff302008-12-03 22:32:44 +00007276 }
7277 return rc;
7278}
7279
7280/*
7281** Close a file that uses proxy locks.
7282*/
7283static int proxyClose(sqlite3_file *id) {
7284 if( id ){
7285 unixFile *pFile = (unixFile*)id;
7286 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7287 unixFile *lockProxy = pCtx->lockProxy;
7288 unixFile *conchFile = pCtx->conchFile;
7289 int rc = SQLITE_OK;
7290
7291 if( lockProxy ){
7292 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7293 if( rc ) return rc;
7294 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7295 if( rc ) return rc;
7296 sqlite3_free(lockProxy);
7297 pCtx->lockProxy = 0;
7298 }
7299 if( conchFile ){
7300 if( pCtx->conchHeld ){
7301 rc = proxyReleaseConch(pFile);
7302 if( rc ) return rc;
7303 }
7304 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7305 if( rc ) return rc;
7306 sqlite3_free(conchFile);
7307 }
drhd56b1212010-08-11 06:14:15 +00007308 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007309 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007310 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007311 /* restore the original locking context and pMethod then close it */
7312 pFile->lockingContext = pCtx->oldLockingContext;
7313 pFile->pMethod = pCtx->pOldMethod;
7314 sqlite3_free(pCtx);
7315 return pFile->pMethod->xClose(id);
7316 }
7317 return SQLITE_OK;
7318}
7319
7320
7321
drhd2cb50b2009-01-09 21:41:17 +00007322#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007323/*
7324** The proxy locking style is intended for use with AFP filesystems.
7325** And since AFP is only supported on MacOSX, the proxy locking is also
7326** restricted to MacOSX.
7327**
7328**
7329******************* End of the proxy lock implementation **********************
7330******************************************************************************/
7331
drh734c9862008-11-28 15:37:20 +00007332/*
danielk1977e339d652008-06-28 11:23:00 +00007333** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007334**
7335** This routine registers all VFS implementations for unix-like operating
7336** systems. This routine, and the sqlite3_os_end() routine that follows,
7337** should be the only routines in this file that are visible from other
7338** files.
drh6b9d6dd2008-12-03 19:34:47 +00007339**
7340** This routine is called once during SQLite initialization and by a
7341** single thread. The memory allocation and mutex subsystems have not
7342** necessarily been initialized when this routine is called, and so they
7343** should not be used.
drh153c62c2007-08-24 03:51:33 +00007344*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007345int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007346 /*
7347 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007348 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7349 ** to the "finder" function. (pAppData is a pointer to a pointer because
7350 ** silly C90 rules prohibit a void* from being cast to a function pointer
7351 ** and so we have to go through the intermediate pointer to avoid problems
7352 ** when compiling with -pedantic-errors on GCC.)
7353 **
7354 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007355 ** finder-function. The finder-function returns a pointer to the
7356 ** sqlite_io_methods object that implements the desired locking
7357 ** behaviors. See the division above that contains the IOMETHODS
7358 ** macro for addition information on finder-functions.
7359 **
7360 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7361 ** object. But the "autolockIoFinder" available on MacOSX does a little
7362 ** more than that; it looks at the filesystem type that hosts the
7363 ** database file and tries to choose an locking method appropriate for
7364 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007365 */
drh7708e972008-11-29 00:56:52 +00007366 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007367 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007368 sizeof(unixFile), /* szOsFile */ \
7369 MAX_PATHNAME, /* mxPathname */ \
7370 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007371 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007372 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007373 unixOpen, /* xOpen */ \
7374 unixDelete, /* xDelete */ \
7375 unixAccess, /* xAccess */ \
7376 unixFullPathname, /* xFullPathname */ \
7377 unixDlOpen, /* xDlOpen */ \
7378 unixDlError, /* xDlError */ \
7379 unixDlSym, /* xDlSym */ \
7380 unixDlClose, /* xDlClose */ \
7381 unixRandomness, /* xRandomness */ \
7382 unixSleep, /* xSleep */ \
7383 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007384 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007385 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007386 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007387 unixGetSystemCall, /* xGetSystemCall */ \
7388 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007389 }
7390
drh6b9d6dd2008-12-03 19:34:47 +00007391 /*
7392 ** All default VFSes for unix are contained in the following array.
7393 **
7394 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7395 ** by the SQLite core when the VFS is registered. So the following
7396 ** array cannot be const.
7397 */
danielk1977e339d652008-06-28 11:23:00 +00007398 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007399#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007400 UNIXVFS("unix", autolockIoFinder ),
7401#else
7402 UNIXVFS("unix", posixIoFinder ),
7403#endif
7404 UNIXVFS("unix-none", nolockIoFinder ),
7405 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007406 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007407#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007408 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007409#endif
7410#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007411 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007412#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007413 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007414#endif
chw78a13182009-04-07 05:35:03 +00007415#endif
drhd2cb50b2009-01-09 21:41:17 +00007416#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007417 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007418 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007419 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007420#endif
drh153c62c2007-08-24 03:51:33 +00007421 };
drh6b9d6dd2008-12-03 19:34:47 +00007422 unsigned int i; /* Loop counter */
7423
drh2aa5a002011-04-13 13:42:25 +00007424 /* Double-check that the aSyscall[] array has been constructed
7425 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhd1ab8062013-03-25 20:50:25 +00007426 assert( ArraySize(aSyscall)==24 );
drh2aa5a002011-04-13 13:42:25 +00007427
drh6b9d6dd2008-12-03 19:34:47 +00007428 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007429 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007430 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007431 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007432 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007433}
danielk1977e339d652008-06-28 11:23:00 +00007434
7435/*
drh6b9d6dd2008-12-03 19:34:47 +00007436** Shutdown the operating system interface.
7437**
7438** Some operating systems might need to do some cleanup in this routine,
7439** to release dynamically allocated objects. But not on unix.
7440** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007441*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007442int sqlite3_os_end(void){
7443 return SQLITE_OK;
7444}
drhdce8bdb2007-08-16 13:01:44 +00007445
danielk197729bafea2008-06-26 10:41:19 +00007446#endif /* SQLITE_OS_UNIX */