blob: b539550220343fc2662b61229395763894a85a46 [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
drhb00d8622014-01-01 15:18:36 +0000263/* This variable holds the process id (pid) from when the xRandomness()
264** method was called. If xOpen() is called from a different process id,
265** indicating that a fork() has occurred, the PRNG will be reset.
266*/
267static int randomnessPid = 0;
268
drh0ccebe72005-06-07 22:22:50 +0000269/*
drha7e61d82011-03-12 17:02:57 +0000270** Allowed values for the unixFile.ctrlFlags bitmask:
271*/
drhf0b190d2011-07-26 16:03:07 +0000272#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
273#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
274#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000275#ifndef SQLITE_DISABLE_DIRSYNC
276# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
277#else
278# define UNIXFILE_DIRSYNC 0x00
279#endif
drhcb15f352011-12-23 01:04:17 +0000280#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000281#define UNIXFILE_DELETE 0x20 /* Delete on close */
282#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
283#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhfbc7e882013-04-11 01:16:15 +0000284#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
drha7e61d82011-03-12 17:02:57 +0000285
286/*
drh198bf392006-01-06 21:52:49 +0000287** Include code that is common to all os_*.c files
288*/
289#include "os_common.h"
290
291/*
drh0ccebe72005-06-07 22:22:50 +0000292** Define various macros that are missing from some systems.
293*/
drhbbd42a62004-05-22 17:41:58 +0000294#ifndef O_LARGEFILE
295# define O_LARGEFILE 0
296#endif
297#ifdef SQLITE_DISABLE_LFS
298# undef O_LARGEFILE
299# define O_LARGEFILE 0
300#endif
301#ifndef O_NOFOLLOW
302# define O_NOFOLLOW 0
303#endif
304#ifndef O_BINARY
305# define O_BINARY 0
306#endif
307
308/*
drh2b4b5962005-06-15 17:47:55 +0000309** The threadid macro resolves to the thread-id or to 0. Used for
310** testing and debugging only.
311*/
drhd677b3d2007-08-20 22:48:41 +0000312#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000313#define threadid pthread_self()
314#else
315#define threadid 0
316#endif
317
drh99ab3b12011-03-02 15:09:07 +0000318/*
dane6ecd662013-04-01 17:56:59 +0000319** HAVE_MREMAP defaults to true on Linux and false everywhere else.
320*/
321#if !defined(HAVE_MREMAP)
322# if defined(__linux__) && defined(_GNU_SOURCE)
323# define HAVE_MREMAP 1
324# else
325# define HAVE_MREMAP 0
326# endif
327#endif
328
329/*
drh9a3baf12011-04-25 18:01:27 +0000330** Different Unix systems declare open() in different ways. Same use
331** open(const char*,int,mode_t). Others use open(const char*,int,...).
332** The difference is important when using a pointer to the function.
333**
334** The safest way to deal with the problem is to always use this wrapper
335** which always has the same well-defined interface.
336*/
337static int posixOpen(const char *zFile, int flags, int mode){
338 return open(zFile, flags, mode);
339}
340
drhed466822012-05-31 13:10:49 +0000341/*
342** On some systems, calls to fchown() will trigger a message in a security
343** log if they come from non-root processes. So avoid calling fchown() if
344** we are not running as root.
345*/
346static int posixFchown(int fd, uid_t uid, gid_t gid){
347 return geteuid() ? 0 : fchown(fd,uid,gid);
348}
349
drh90315a22011-08-10 01:52:12 +0000350/* Forward reference */
351static int openDirectory(const char*, int*);
352
drh9a3baf12011-04-25 18:01:27 +0000353/*
drh99ab3b12011-03-02 15:09:07 +0000354** Many system calls are accessed through pointer-to-functions so that
355** they may be overridden at runtime to facilitate fault injection during
356** testing and sandboxing. The following array holds the names and pointers
357** to all overrideable system calls.
358*/
359static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000360 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000361 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
362 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000363} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000364 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
365#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000366
drh58ad5802011-03-23 22:02:23 +0000367 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osClose ((int(*)(int))aSyscall[1].pCurrent)
369
drh58ad5802011-03-23 22:02:23 +0000370 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
372
drh58ad5802011-03-23 22:02:23 +0000373 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000374#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
375
drh58ad5802011-03-23 22:02:23 +0000376 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000377#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
378
379/*
380** The DJGPP compiler environment looks mostly like Unix, but it
381** lacks the fcntl() system call. So redefine fcntl() to be something
382** that always succeeds. This means that locking does not occur under
383** DJGPP. But it is DOS - what did you expect?
384*/
385#ifdef __DJGPP__
386 { "fstat", 0, 0 },
387#define osFstat(a,b,c) 0
388#else
drh58ad5802011-03-23 22:02:23 +0000389 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000390#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
391#endif
392
drh58ad5802011-03-23 22:02:23 +0000393 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000394#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
395
drh58ad5802011-03-23 22:02:23 +0000396 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000397#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000398
drh58ad5802011-03-23 22:02:23 +0000399 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000400#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
401
drhd4a80312011-04-15 14:33:20 +0000402#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000403 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000404#else
drh58ad5802011-03-23 22:02:23 +0000405 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000406#endif
407#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
408
409#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000410 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000411#else
drh58ad5802011-03-23 22:02:23 +0000412 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000413#endif
414#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
415
drh58ad5802011-03-23 22:02:23 +0000416 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000417#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
418
drhd4a80312011-04-15 14:33:20 +0000419#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000420 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000421#else
drh58ad5802011-03-23 22:02:23 +0000422 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000423#endif
424#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
425 aSyscall[12].pCurrent)
426
427#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000428 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000429#else
drh58ad5802011-03-23 22:02:23 +0000430 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000431#endif
432#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
433 aSyscall[13].pCurrent)
434
drh58ad5802011-03-23 22:02:23 +0000435 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000436#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000437
438#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000439 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000440#else
drh58ad5802011-03-23 22:02:23 +0000441 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000442#endif
dan0fd7d862011-03-29 10:04:23 +0000443#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000444
drh036ac7f2011-08-08 23:18:05 +0000445 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
446#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
447
drh90315a22011-08-10 01:52:12 +0000448 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
449#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
450
drh9ef6bc42011-11-04 02:24:02 +0000451 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
452#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
453
454 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
455#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
456
drhed466822012-05-31 13:10:49 +0000457 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000458#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000459
dan4dd51442013-08-26 14:30:25 +0000460#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000461 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
462#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
463
drhd1ab8062013-03-25 20:50:25 +0000464 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
465#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
466
dane6ecd662013-04-01 17:56:59 +0000467#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000468 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
469#else
470 { "mremap", (sqlite3_syscall_ptr)0, 0 },
471#endif
472#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
dan4dd51442013-08-26 14:30:25 +0000473#endif
drhd1ab8062013-03-25 20:50:25 +0000474
drhe562be52011-03-02 18:01:10 +0000475}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000476
477/*
478** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000479** "unix" VFSes. Return SQLITE_OK opon successfully updating the
480** system call pointer, or SQLITE_NOTFOUND if there is no configurable
481** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000482*/
483static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000484 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
485 const char *zName, /* Name of system call to override */
486 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000487){
drh58ad5802011-03-23 22:02:23 +0000488 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000489 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000490
491 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000492 if( zName==0 ){
493 /* If no zName is given, restore all system calls to their default
494 ** settings and return NULL
495 */
dan51438a72011-04-02 17:00:47 +0000496 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000497 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
498 if( aSyscall[i].pDefault ){
499 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000500 }
501 }
502 }else{
503 /* If zName is specified, operate on only the one system call
504 ** specified.
505 */
506 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
507 if( strcmp(zName, aSyscall[i].zName)==0 ){
508 if( aSyscall[i].pDefault==0 ){
509 aSyscall[i].pDefault = aSyscall[i].pCurrent;
510 }
drh1df30962011-03-02 19:06:42 +0000511 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000512 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
513 aSyscall[i].pCurrent = pNewFunc;
514 break;
515 }
516 }
517 }
518 return rc;
519}
520
drh1df30962011-03-02 19:06:42 +0000521/*
522** Return the value of a system call. Return NULL if zName is not a
523** recognized system call name. NULL is also returned if the system call
524** is currently undefined.
525*/
drh58ad5802011-03-23 22:02:23 +0000526static sqlite3_syscall_ptr unixGetSystemCall(
527 sqlite3_vfs *pNotUsed,
528 const char *zName
529){
530 unsigned int i;
531
532 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000533 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
534 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
535 }
536 return 0;
537}
538
539/*
540** Return the name of the first system call after zName. If zName==NULL
541** then return the name of the first system call. Return NULL if zName
542** is the last system call or if zName is not the name of a valid
543** system call.
544*/
545static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000546 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000547
548 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000549 if( zName ){
550 for(i=0; i<ArraySize(aSyscall)-1; i++){
551 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000552 }
553 }
dan0fd7d862011-03-29 10:04:23 +0000554 for(i++; i<ArraySize(aSyscall); i++){
555 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000556 }
557 return 0;
558}
559
drhad4f1e52011-03-04 15:43:57 +0000560/*
drh77a3fdc2013-08-30 14:24:12 +0000561** Do not accept any file descriptor less than this value, in order to avoid
562** opening database file using file descriptors that are commonly used for
563** standard input, output, and error.
564*/
565#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
566# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
567#endif
568
569/*
drh8c815d12012-02-13 20:16:37 +0000570** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000571** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000572**
573** If the file creation mode "m" is 0 then set it to the default for
574** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
575** 0644) as modified by the system umask. If m is not 0, then
576** make the file creation mode be exactly m ignoring the umask.
577**
578** The m parameter will be non-zero only when creating -wal, -journal,
579** and -shm files. We want those files to have *exactly* the same
580** permissions as their original database, unadulterated by the umask.
581** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
582** transaction crashes and leaves behind hot journals, then any
583** process that is able to write to the database will also be able to
584** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000585*/
drh8c815d12012-02-13 20:16:37 +0000586static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000587 int fd;
drhe1186ab2013-01-04 20:45:13 +0000588 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000589 while(1){
drh5adc60b2012-04-14 13:25:11 +0000590#if defined(O_CLOEXEC)
591 fd = osOpen(z,f|O_CLOEXEC,m2);
592#else
593 fd = osOpen(z,f,m2);
594#endif
drh5128d002013-08-30 06:20:23 +0000595 if( fd<0 ){
596 if( errno==EINTR ) continue;
597 break;
598 }
drh77a3fdc2013-08-30 14:24:12 +0000599 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000600 osClose(fd);
601 sqlite3_log(SQLITE_WARNING,
602 "attempt to open \"%s\" as file descriptor %d", z, fd);
603 fd = -1;
604 if( osOpen("/dev/null", f, m)<0 ) break;
605 }
drhe1186ab2013-01-04 20:45:13 +0000606 if( fd>=0 ){
607 if( m!=0 ){
608 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000609 if( osFstat(fd, &statbuf)==0
610 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000611 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000612 ){
drhe1186ab2013-01-04 20:45:13 +0000613 osFchmod(fd, m);
614 }
615 }
drh5adc60b2012-04-14 13:25:11 +0000616#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000617 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000618#endif
drhe1186ab2013-01-04 20:45:13 +0000619 }
drh5adc60b2012-04-14 13:25:11 +0000620 return fd;
drhad4f1e52011-03-04 15:43:57 +0000621}
danielk197713adf8a2004-06-03 16:08:41 +0000622
drh107886a2008-11-21 22:21:50 +0000623/*
dan9359c7b2009-08-21 08:29:10 +0000624** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000625** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000626** vxworksFileId objects used by this file, all of which may be
627** shared by multiple threads.
628**
629** Function unixMutexHeld() is used to assert() that the global mutex
630** is held when required. This function is only used as part of assert()
631** statements. e.g.
632**
633** unixEnterMutex()
634** assert( unixMutexHeld() );
635** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000636*/
637static void unixEnterMutex(void){
638 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
639}
640static void unixLeaveMutex(void){
641 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
642}
dan9359c7b2009-08-21 08:29:10 +0000643#ifdef SQLITE_DEBUG
644static int unixMutexHeld(void) {
645 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
646}
647#endif
drh107886a2008-11-21 22:21:50 +0000648
drh734c9862008-11-28 15:37:20 +0000649
drh30ddce62011-10-15 00:16:30 +0000650#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000651/*
652** Helper function for printing out trace information from debugging
653** binaries. This returns the string represetation of the supplied
654** integer lock-type.
655*/
drh308c2a52010-05-14 11:30:18 +0000656static const char *azFileLock(int eFileLock){
657 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000658 case NO_LOCK: return "NONE";
659 case SHARED_LOCK: return "SHARED";
660 case RESERVED_LOCK: return "RESERVED";
661 case PENDING_LOCK: return "PENDING";
662 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000663 }
664 return "ERROR";
665}
666#endif
667
668#ifdef SQLITE_LOCK_TRACE
669/*
670** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000671**
drh734c9862008-11-28 15:37:20 +0000672** This routine is used for troubleshooting locks on multithreaded
673** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
674** command-line option on the compiler. This code is normally
675** turned off.
676*/
677static int lockTrace(int fd, int op, struct flock *p){
678 char *zOpName, *zType;
679 int s;
680 int savedErrno;
681 if( op==F_GETLK ){
682 zOpName = "GETLK";
683 }else if( op==F_SETLK ){
684 zOpName = "SETLK";
685 }else{
drh99ab3b12011-03-02 15:09:07 +0000686 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000687 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
688 return s;
689 }
690 if( p->l_type==F_RDLCK ){
691 zType = "RDLCK";
692 }else if( p->l_type==F_WRLCK ){
693 zType = "WRLCK";
694 }else if( p->l_type==F_UNLCK ){
695 zType = "UNLCK";
696 }else{
697 assert( 0 );
698 }
699 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000700 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000701 savedErrno = errno;
702 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
703 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
704 (int)p->l_pid, s);
705 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
706 struct flock l2;
707 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000708 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000709 if( l2.l_type==F_RDLCK ){
710 zType = "RDLCK";
711 }else if( l2.l_type==F_WRLCK ){
712 zType = "WRLCK";
713 }else if( l2.l_type==F_UNLCK ){
714 zType = "UNLCK";
715 }else{
716 assert( 0 );
717 }
718 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
719 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
720 }
721 errno = savedErrno;
722 return s;
723}
drh99ab3b12011-03-02 15:09:07 +0000724#undef osFcntl
725#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000726#endif /* SQLITE_LOCK_TRACE */
727
drhff812312011-02-23 13:33:46 +0000728/*
729** Retry ftruncate() calls that fail due to EINTR
730*/
drhff812312011-02-23 13:33:46 +0000731static int robust_ftruncate(int h, sqlite3_int64 sz){
732 int rc;
drh99ab3b12011-03-02 15:09:07 +0000733 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000734 return rc;
735}
drh734c9862008-11-28 15:37:20 +0000736
737/*
738** This routine translates a standard POSIX errno code into something
739** useful to the clients of the sqlite3 functions. Specifically, it is
740** intended to translate a variety of "try again" errors into SQLITE_BUSY
741** and a variety of "please close the file descriptor NOW" errors into
742** SQLITE_IOERR
743**
744** Errors during initialization of locks, or file system support for locks,
745** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
746*/
747static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
748 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000749#if 0
750 /* At one point this code was not commented out. In theory, this branch
751 ** should never be hit, as this function should only be called after
752 ** a locking-related function (i.e. fcntl()) has returned non-zero with
753 ** the value of errno as the first argument. Since a system call has failed,
754 ** errno should be non-zero.
755 **
756 ** Despite this, if errno really is zero, we still don't want to return
757 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
758 ** propagated back to the caller. Commenting this branch out means errno==0
759 ** will be handled by the "default:" case below.
760 */
drh734c9862008-11-28 15:37:20 +0000761 case 0:
762 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000763#endif
764
drh734c9862008-11-28 15:37:20 +0000765 case EAGAIN:
766 case ETIMEDOUT:
767 case EBUSY:
768 case EINTR:
769 case ENOLCK:
770 /* random NFS retry error, unless during file system support
771 * introspection, in which it actually means what it says */
772 return SQLITE_BUSY;
773
774 case EACCES:
775 /* EACCES is like EAGAIN during locking operations, but not any other time*/
776 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000777 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
778 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
779 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000780 return SQLITE_BUSY;
781 }
782 /* else fall through */
783 case EPERM:
784 return SQLITE_PERM;
785
danea83bc62011-04-01 11:56:32 +0000786 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
787 ** this module never makes such a call. And the code in SQLite itself
788 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
789 ** this case is also commented out. If the system does set errno to EDEADLK,
790 ** the default SQLITE_IOERR_XXX code will be returned. */
791#if 0
drh734c9862008-11-28 15:37:20 +0000792 case EDEADLK:
793 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000794#endif
drh734c9862008-11-28 15:37:20 +0000795
796#if EOPNOTSUPP!=ENOTSUP
797 case EOPNOTSUPP:
798 /* something went terribly awry, unless during file system support
799 * introspection, in which it actually means what it says */
800#endif
801#ifdef ENOTSUP
802 case ENOTSUP:
803 /* invalid fd, unless during file system support introspection, in which
804 * it actually means what it says */
805#endif
806 case EIO:
807 case EBADF:
808 case EINVAL:
809 case ENOTCONN:
810 case ENODEV:
811 case ENXIO:
812 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000813#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000814 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000815#endif
drh734c9862008-11-28 15:37:20 +0000816 case ENOSYS:
817 /* these should force the client to close the file and reconnect */
818
819 default:
820 return sqliteIOErr;
821 }
822}
823
824
drh734c9862008-11-28 15:37:20 +0000825/******************************************************************************
826****************** Begin Unique File ID Utility Used By VxWorks ***************
827**
828** On most versions of unix, we can get a unique ID for a file by concatenating
829** the device number and the inode number. But this does not work on VxWorks.
830** On VxWorks, a unique file id must be based on the canonical filename.
831**
832** A pointer to an instance of the following structure can be used as a
833** unique file ID in VxWorks. Each instance of this structure contains
834** a copy of the canonical filename. There is also a reference count.
835** The structure is reclaimed when the number of pointers to it drops to
836** zero.
837**
838** There are never very many files open at one time and lookups are not
839** a performance-critical path, so it is sufficient to put these
840** structures on a linked list.
841*/
842struct vxworksFileId {
843 struct vxworksFileId *pNext; /* Next in a list of them all */
844 int nRef; /* Number of references to this one */
845 int nName; /* Length of the zCanonicalName[] string */
846 char *zCanonicalName; /* Canonical filename */
847};
848
849#if OS_VXWORKS
850/*
drh9b35ea62008-11-29 02:20:26 +0000851** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000852** variable:
853*/
854static struct vxworksFileId *vxworksFileList = 0;
855
856/*
857** Simplify a filename into its canonical form
858** by making the following changes:
859**
860** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000861** * convert /./ into just /
862** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000863**
864** Changes are made in-place. Return the new name length.
865**
866** The original filename is in z[0..n-1]. Return the number of
867** characters in the simplified name.
868*/
869static int vxworksSimplifyName(char *z, int n){
870 int i, j;
871 while( n>1 && z[n-1]=='/' ){ n--; }
872 for(i=j=0; i<n; i++){
873 if( z[i]=='/' ){
874 if( z[i+1]=='/' ) continue;
875 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
876 i += 1;
877 continue;
878 }
879 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
880 while( j>0 && z[j-1]!='/' ){ j--; }
881 if( j>0 ){ j--; }
882 i += 2;
883 continue;
884 }
885 }
886 z[j++] = z[i];
887 }
888 z[j] = 0;
889 return j;
890}
891
892/*
893** Find a unique file ID for the given absolute pathname. Return
894** a pointer to the vxworksFileId object. This pointer is the unique
895** file ID.
896**
897** The nRef field of the vxworksFileId object is incremented before
898** the object is returned. A new vxworksFileId object is created
899** and added to the global list if necessary.
900**
901** If a memory allocation error occurs, return NULL.
902*/
903static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
904 struct vxworksFileId *pNew; /* search key and new file ID */
905 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
906 int n; /* Length of zAbsoluteName string */
907
908 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000909 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000910 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
911 if( pNew==0 ) return 0;
912 pNew->zCanonicalName = (char*)&pNew[1];
913 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
914 n = vxworksSimplifyName(pNew->zCanonicalName, n);
915
916 /* Search for an existing entry that matching the canonical name.
917 ** If found, increment the reference count and return a pointer to
918 ** the existing file ID.
919 */
920 unixEnterMutex();
921 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
922 if( pCandidate->nName==n
923 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
924 ){
925 sqlite3_free(pNew);
926 pCandidate->nRef++;
927 unixLeaveMutex();
928 return pCandidate;
929 }
930 }
931
932 /* No match was found. We will make a new file ID */
933 pNew->nRef = 1;
934 pNew->nName = n;
935 pNew->pNext = vxworksFileList;
936 vxworksFileList = pNew;
937 unixLeaveMutex();
938 return pNew;
939}
940
941/*
942** Decrement the reference count on a vxworksFileId object. Free
943** the object when the reference count reaches zero.
944*/
945static void vxworksReleaseFileId(struct vxworksFileId *pId){
946 unixEnterMutex();
947 assert( pId->nRef>0 );
948 pId->nRef--;
949 if( pId->nRef==0 ){
950 struct vxworksFileId **pp;
951 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
952 assert( *pp==pId );
953 *pp = pId->pNext;
954 sqlite3_free(pId);
955 }
956 unixLeaveMutex();
957}
958#endif /* OS_VXWORKS */
959/*************** End of Unique File ID Utility Used By VxWorks ****************
960******************************************************************************/
961
962
963/******************************************************************************
964*************************** Posix Advisory Locking ****************************
965**
drh9b35ea62008-11-29 02:20:26 +0000966** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000967** section 6.5.2.2 lines 483 through 490 specify that when a process
968** sets or clears a lock, that operation overrides any prior locks set
969** by the same process. It does not explicitly say so, but this implies
970** that it overrides locks set by the same process using a different
971** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000972**
973** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000974** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
975**
976** Suppose ./file1 and ./file2 are really the same file (because
977** one is a hard or symbolic link to the other) then if you set
978** an exclusive lock on fd1, then try to get an exclusive lock
979** on fd2, it works. I would have expected the second lock to
980** fail since there was already a lock on the file due to fd1.
981** But not so. Since both locks came from the same process, the
982** second overrides the first, even though they were on different
983** file descriptors opened on different file names.
984**
drh734c9862008-11-28 15:37:20 +0000985** This means that we cannot use POSIX locks to synchronize file access
986** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000987** to synchronize access for threads in separate processes, but not
988** threads within the same process.
989**
990** To work around the problem, SQLite has to manage file locks internally
991** on its own. Whenever a new database is opened, we have to find the
992** specific inode of the database file (the inode is determined by the
993** st_dev and st_ino fields of the stat structure that fstat() fills in)
994** and check for locks already existing on that inode. When locks are
995** created or removed, we have to look at our own internal record of the
996** locks to see if another thread has previously set a lock on that same
997** inode.
998**
drh9b35ea62008-11-29 02:20:26 +0000999** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1000** For VxWorks, we have to use the alternative unique ID system based on
1001** canonical filename and implemented in the previous division.)
1002**
danielk1977ad94b582007-08-20 06:44:22 +00001003** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001004** descriptor. It is now a structure that holds the integer file
1005** descriptor and a pointer to a structure that describes the internal
1006** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001007** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001008** point to the same locking structure. The locking structure keeps
1009** a reference count (so we will know when to delete it) and a "cnt"
1010** field that tells us its internal lock status. cnt==0 means the
1011** file is unlocked. cnt==-1 means the file has an exclusive lock.
1012** cnt>0 means there are cnt shared locks on the file.
1013**
1014** Any attempt to lock or unlock a file first checks the locking
1015** structure. The fcntl() system call is only invoked to set a
1016** POSIX lock if the internal lock structure transitions between
1017** a locked and an unlocked state.
1018**
drh734c9862008-11-28 15:37:20 +00001019** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001020**
1021** If you close a file descriptor that points to a file that has locks,
1022** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001023** released. To work around this problem, each unixInodeInfo object
1024** maintains a count of the number of pending locks on tha inode.
1025** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001026** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001027** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001028** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001029** be closed and that list is walked (and cleared) when the last lock
1030** clears.
1031**
drh9b35ea62008-11-29 02:20:26 +00001032** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001033**
drh9b35ea62008-11-29 02:20:26 +00001034** Many older versions of linux use the LinuxThreads library which is
1035** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001036** A cannot be modified or overridden by a different thread B.
1037** Only thread A can modify the lock. Locking behavior is correct
1038** if the appliation uses the newer Native Posix Thread Library (NPTL)
1039** on linux - with NPTL a lock created by thread A can override locks
1040** in thread B. But there is no way to know at compile-time which
1041** threading library is being used. So there is no way to know at
1042** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001043** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001044** current process.
drh5fdae772004-06-29 03:29:00 +00001045**
drh8af6c222010-05-14 12:43:01 +00001046** SQLite used to support LinuxThreads. But support for LinuxThreads
1047** was dropped beginning with version 3.7.0. SQLite will still work with
1048** LinuxThreads provided that (1) there is no more than one connection
1049** per database file in the same process and (2) database connections
1050** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001051*/
1052
1053/*
1054** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001055** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001056*/
1057struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001058 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001059#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001060 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001061#else
drh107886a2008-11-21 22:21:50 +00001062 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001063#endif
1064};
1065
1066/*
drhbbd42a62004-05-22 17:41:58 +00001067** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001068** inode. Or, on LinuxThreads, there is one of these structures for
1069** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001070**
danielk1977ad94b582007-08-20 06:44:22 +00001071** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001072** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001073** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001074*/
drh8af6c222010-05-14 12:43:01 +00001075struct unixInodeInfo {
1076 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001077 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001078 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1079 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001080 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001081 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1082 int nLock; /* Number of outstanding file locks */
1083 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1084 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1085 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001086#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001087 unsigned long long sharedByte; /* for AFP simulated shared lock */
1088#endif
drh6c7d5c52008-11-21 20:32:33 +00001089#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001090 sem_t *pSem; /* Named POSIX semaphore */
1091 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001092#endif
drhbbd42a62004-05-22 17:41:58 +00001093};
1094
drhda0e7682008-07-30 15:27:54 +00001095/*
drh8af6c222010-05-14 12:43:01 +00001096** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001097*/
drhd91c68f2010-05-14 14:52:25 +00001098static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001099
drh5fdae772004-06-29 03:29:00 +00001100/*
dane18d4952011-02-21 11:46:24 +00001101**
1102** This function - unixLogError_x(), is only ever called via the macro
1103** unixLogError().
1104**
1105** It is invoked after an error occurs in an OS function and errno has been
1106** set. It logs a message using sqlite3_log() containing the current value of
1107** errno and, if possible, the human-readable equivalent from strerror() or
1108** strerror_r().
1109**
1110** The first argument passed to the macro should be the error code that
1111** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1112** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001113** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001114** if any.
1115*/
drh0e9365c2011-03-02 02:08:13 +00001116#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1117static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001118 int errcode, /* SQLite error code */
1119 const char *zFunc, /* Name of OS function that failed */
1120 const char *zPath, /* File path associated with error */
1121 int iLine /* Source line number where error occurred */
1122){
1123 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001124 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001125
1126 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1127 ** the strerror() function to obtain the human-readable error message
1128 ** equivalent to errno. Otherwise, use strerror_r().
1129 */
1130#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1131 char aErr[80];
1132 memset(aErr, 0, sizeof(aErr));
1133 zErr = aErr;
1134
1135 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001136 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001137 ** returns a pointer to a buffer containing the error message. That pointer
1138 ** may point to aErr[], or it may point to some static storage somewhere.
1139 ** Otherwise, assume that the system provides the POSIX version of
1140 ** strerror_r(), which always writes an error message into aErr[].
1141 **
1142 ** If the code incorrectly assumes that it is the POSIX version that is
1143 ** available, the error message will often be an empty string. Not a
1144 ** huge problem. Incorrectly concluding that the GNU version is available
1145 ** could lead to a segfault though.
1146 */
1147#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1148 zErr =
1149# endif
drh0e9365c2011-03-02 02:08:13 +00001150 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001151
1152#elif SQLITE_THREADSAFE
1153 /* This is a threadsafe build, but strerror_r() is not available. */
1154 zErr = "";
1155#else
1156 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001157 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001158#endif
1159
drh0e9365c2011-03-02 02:08:13 +00001160 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001161 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001162 "os_unix.c:%d: (%d) %s(%s) - %s",
1163 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001164 );
1165
1166 return errcode;
1167}
1168
drh0e9365c2011-03-02 02:08:13 +00001169/*
1170** Close a file descriptor.
1171**
1172** We assume that close() almost always works, since it is only in a
1173** very sick application or on a very sick platform that it might fail.
1174** If it does fail, simply leak the file descriptor, but do log the
1175** error.
1176**
1177** Note that it is not safe to retry close() after EINTR since the
1178** file descriptor might have already been reused by another thread.
1179** So we don't even try to recover from an EINTR. Just log the error
1180** and move on.
1181*/
1182static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001183 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001184 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1185 pFile ? pFile->zPath : 0, lineno);
1186 }
1187}
dane18d4952011-02-21 11:46:24 +00001188
1189/*
danb0ac3e32010-06-16 10:55:42 +00001190** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001191*/
drh0e9365c2011-03-02 02:08:13 +00001192static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001193 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001194 UnixUnusedFd *p;
1195 UnixUnusedFd *pNext;
1196 for(p=pInode->pUnused; p; p=pNext){
1197 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001198 robust_close(pFile, p->fd, __LINE__);
1199 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001200 }
drh0e9365c2011-03-02 02:08:13 +00001201 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001202}
1203
1204/*
drh8af6c222010-05-14 12:43:01 +00001205** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001206**
1207** The mutex entered using the unixEnterMutex() function must be held
1208** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001209*/
danb0ac3e32010-06-16 10:55:42 +00001210static void releaseInodeInfo(unixFile *pFile){
1211 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001212 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001213 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001214 pInode->nRef--;
1215 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001216 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001217 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001218 if( pInode->pPrev ){
1219 assert( pInode->pPrev->pNext==pInode );
1220 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001221 }else{
drh8af6c222010-05-14 12:43:01 +00001222 assert( inodeList==pInode );
1223 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001224 }
drh8af6c222010-05-14 12:43:01 +00001225 if( pInode->pNext ){
1226 assert( pInode->pNext->pPrev==pInode );
1227 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001228 }
drh8af6c222010-05-14 12:43:01 +00001229 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001230 }
drhbbd42a62004-05-22 17:41:58 +00001231 }
1232}
1233
1234/*
drh8af6c222010-05-14 12:43:01 +00001235** Given a file descriptor, locate the unixInodeInfo object that
1236** describes that file descriptor. Create a new one if necessary. The
1237** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001238**
dan9359c7b2009-08-21 08:29:10 +00001239** The mutex entered using the unixEnterMutex() function must be held
1240** when this function is called.
1241**
drh6c7d5c52008-11-21 20:32:33 +00001242** Return an appropriate error code.
1243*/
drh8af6c222010-05-14 12:43:01 +00001244static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001245 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001246 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001247){
1248 int rc; /* System call return code */
1249 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001250 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1251 struct stat statbuf; /* Low-level file information */
1252 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001253
dan9359c7b2009-08-21 08:29:10 +00001254 assert( unixMutexHeld() );
1255
drh6c7d5c52008-11-21 20:32:33 +00001256 /* Get low-level information about the file that we can used to
1257 ** create a unique name for the file.
1258 */
1259 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001260 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001261 if( rc!=0 ){
1262 pFile->lastErrno = errno;
1263#ifdef EOVERFLOW
1264 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1265#endif
1266 return SQLITE_IOERR;
1267 }
1268
drheb0d74f2009-02-03 15:27:02 +00001269#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001270 /* On OS X on an msdos filesystem, the inode number is reported
1271 ** incorrectly for zero-size files. See ticket #3260. To work
1272 ** around this problem (we consider it a bug in OS X, not SQLite)
1273 ** we always increase the file size to 1 by writing a single byte
1274 ** prior to accessing the inode number. The one byte written is
1275 ** an ASCII 'S' character which also happens to be the first byte
1276 ** in the header of every SQLite database. In this way, if there
1277 ** is a race condition such that another thread has already populated
1278 ** the first page of the database, no damage is done.
1279 */
drh7ed97b92010-01-20 13:07:21 +00001280 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001281 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001282 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001283 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001284 return SQLITE_IOERR;
1285 }
drh99ab3b12011-03-02 15:09:07 +00001286 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001287 if( rc!=0 ){
1288 pFile->lastErrno = errno;
1289 return SQLITE_IOERR;
1290 }
1291 }
drheb0d74f2009-02-03 15:27:02 +00001292#endif
drh6c7d5c52008-11-21 20:32:33 +00001293
drh8af6c222010-05-14 12:43:01 +00001294 memset(&fileId, 0, sizeof(fileId));
1295 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001296#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001297 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001298#else
drh8af6c222010-05-14 12:43:01 +00001299 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001300#endif
drh8af6c222010-05-14 12:43:01 +00001301 pInode = inodeList;
1302 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1303 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001304 }
drh8af6c222010-05-14 12:43:01 +00001305 if( pInode==0 ){
1306 pInode = sqlite3_malloc( sizeof(*pInode) );
1307 if( pInode==0 ){
1308 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001309 }
drh8af6c222010-05-14 12:43:01 +00001310 memset(pInode, 0, sizeof(*pInode));
1311 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1312 pInode->nRef = 1;
1313 pInode->pNext = inodeList;
1314 pInode->pPrev = 0;
1315 if( inodeList ) inodeList->pPrev = pInode;
1316 inodeList = pInode;
1317 }else{
1318 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001319 }
drh8af6c222010-05-14 12:43:01 +00001320 *ppInode = pInode;
1321 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001322}
drh6c7d5c52008-11-21 20:32:33 +00001323
drhb959a012013-12-07 12:29:22 +00001324/*
1325** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1326*/
1327static int fileHasMoved(unixFile *pFile){
1328 struct stat buf;
1329 return pFile->pInode!=0 &&
1330 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
1331}
1332
aswift5b1a2562008-08-22 00:22:35 +00001333
1334/*
drhfbc7e882013-04-11 01:16:15 +00001335** Check a unixFile that is a database. Verify the following:
1336**
1337** (1) There is exactly one hard link on the file
1338** (2) The file is not a symbolic link
1339** (3) The file has not been renamed or unlinked
1340**
1341** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1342*/
1343static void verifyDbFile(unixFile *pFile){
1344 struct stat buf;
1345 int rc;
1346 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1347 /* One or more of the following warnings have already been issued. Do not
1348 ** repeat them so as not to clutter the error log */
1349 return;
1350 }
1351 rc = osFstat(pFile->h, &buf);
1352 if( rc!=0 ){
1353 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1354 pFile->ctrlFlags |= UNIXFILE_WARNED;
1355 return;
1356 }
1357 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
1358 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1359 pFile->ctrlFlags |= UNIXFILE_WARNED;
1360 return;
1361 }
1362 if( buf.st_nlink>1 ){
1363 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1364 pFile->ctrlFlags |= UNIXFILE_WARNED;
1365 return;
1366 }
drhb959a012013-12-07 12:29:22 +00001367 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001368 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1369 pFile->ctrlFlags |= UNIXFILE_WARNED;
1370 return;
1371 }
1372}
1373
1374
1375/*
danielk197713adf8a2004-06-03 16:08:41 +00001376** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001377** file by this or any other process. If such a lock is held, set *pResOut
1378** to a non-zero value otherwise *pResOut is set to zero. The return value
1379** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001380*/
danielk1977861f7452008-06-05 11:39:11 +00001381static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001382 int rc = SQLITE_OK;
1383 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001384 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001385
danielk1977861f7452008-06-05 11:39:11 +00001386 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1387
drh054889e2005-11-30 03:20:31 +00001388 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001389 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001390
1391 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001392 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001393 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001394 }
1395
drh2ac3ee92004-06-07 16:27:46 +00001396 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001397 */
danielk197709480a92009-02-09 05:32:32 +00001398#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001399 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001400 struct flock lock;
1401 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001402 lock.l_start = RESERVED_BYTE;
1403 lock.l_len = 1;
1404 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001405 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1406 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1407 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001408 } else if( lock.l_type!=F_UNLCK ){
1409 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001410 }
1411 }
danielk197709480a92009-02-09 05:32:32 +00001412#endif
danielk197713adf8a2004-06-03 16:08:41 +00001413
drh6c7d5c52008-11-21 20:32:33 +00001414 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001415 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001416
aswift5b1a2562008-08-22 00:22:35 +00001417 *pResOut = reserved;
1418 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001419}
1420
1421/*
drha7e61d82011-03-12 17:02:57 +00001422** Attempt to set a system-lock on the file pFile. The lock is
1423** described by pLock.
1424**
drh77197112011-03-15 19:08:48 +00001425** If the pFile was opened read/write from unix-excl, then the only lock
1426** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001427** the first time any lock is attempted. All subsequent system locking
1428** operations become no-ops. Locking operations still happen internally,
1429** in order to coordinate access between separate database connections
1430** within this process, but all of that is handled in memory and the
1431** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001432**
1433** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1434** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1435** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001436**
1437** Zero is returned if the call completes successfully, or -1 if a call
1438** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001439*/
1440static int unixFileLock(unixFile *pFile, struct flock *pLock){
1441 int rc;
drh3cb93392011-03-12 18:10:44 +00001442 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001443 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001444 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001445 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1446 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1447 ){
drh3cb93392011-03-12 18:10:44 +00001448 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001449 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001450 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001451 lock.l_whence = SEEK_SET;
1452 lock.l_start = SHARED_FIRST;
1453 lock.l_len = SHARED_SIZE;
1454 lock.l_type = F_WRLCK;
1455 rc = osFcntl(pFile->h, F_SETLK, &lock);
1456 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001457 pInode->bProcessLock = 1;
1458 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001459 }else{
1460 rc = 0;
1461 }
1462 }else{
1463 rc = osFcntl(pFile->h, F_SETLK, pLock);
1464 }
1465 return rc;
1466}
1467
1468/*
drh308c2a52010-05-14 11:30:18 +00001469** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001470** of the following:
1471**
drh2ac3ee92004-06-07 16:27:46 +00001472** (1) SHARED_LOCK
1473** (2) RESERVED_LOCK
1474** (3) PENDING_LOCK
1475** (4) EXCLUSIVE_LOCK
1476**
drhb3e04342004-06-08 00:47:47 +00001477** Sometimes when requesting one lock state, additional lock states
1478** are inserted in between. The locking might fail on one of the later
1479** transitions leaving the lock state different from what it started but
1480** still short of its goal. The following chart shows the allowed
1481** transitions and the inserted intermediate states:
1482**
1483** UNLOCKED -> SHARED
1484** SHARED -> RESERVED
1485** SHARED -> (PENDING) -> EXCLUSIVE
1486** RESERVED -> (PENDING) -> EXCLUSIVE
1487** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001488**
drha6abd042004-06-09 17:37:22 +00001489** This routine will only increase a lock. Use the sqlite3OsUnlock()
1490** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001491*/
drh308c2a52010-05-14 11:30:18 +00001492static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001493 /* The following describes the implementation of the various locks and
1494 ** lock transitions in terms of the POSIX advisory shared and exclusive
1495 ** lock primitives (called read-locks and write-locks below, to avoid
1496 ** confusion with SQLite lock names). The algorithms are complicated
1497 ** slightly in order to be compatible with windows systems simultaneously
1498 ** accessing the same database file, in case that is ever required.
1499 **
1500 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1501 ** byte', each single bytes at well known offsets, and the 'shared byte
1502 ** range', a range of 510 bytes at a well known offset.
1503 **
1504 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1505 ** byte'. If this is successful, a random byte from the 'shared byte
1506 ** range' is read-locked and the lock on the 'pending byte' released.
1507 **
danielk197790ba3bd2004-06-25 08:32:25 +00001508 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1509 ** A RESERVED lock is implemented by grabbing a write-lock on the
1510 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001511 **
1512 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001513 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1514 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1515 ** obtained, but existing SHARED locks are allowed to persist. A process
1516 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1517 ** This property is used by the algorithm for rolling back a journal file
1518 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001519 **
danielk197790ba3bd2004-06-25 08:32:25 +00001520 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1521 ** implemented by obtaining a write-lock on the entire 'shared byte
1522 ** range'. Since all other locks require a read-lock on one of the bytes
1523 ** within this range, this ensures that no other locks are held on the
1524 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001525 **
1526 ** The reason a single byte cannot be used instead of the 'shared byte
1527 ** range' is that some versions of windows do not support read-locks. By
1528 ** locking a random byte from a range, concurrent SHARED locks may exist
1529 ** even if the locking primitive used is always a write-lock.
1530 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001531 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001532 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001533 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001534 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001535 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001536
drh054889e2005-11-30 03:20:31 +00001537 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001538 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1539 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001540 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001541
1542 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001543 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001544 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001545 */
drh308c2a52010-05-14 11:30:18 +00001546 if( pFile->eFileLock>=eFileLock ){
1547 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1548 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001549 return SQLITE_OK;
1550 }
1551
drh0c2694b2009-09-03 16:23:44 +00001552 /* Make sure the locking sequence is correct.
1553 ** (1) We never move from unlocked to anything higher than shared lock.
1554 ** (2) SQLite never explicitly requests a pendig lock.
1555 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001556 */
drh308c2a52010-05-14 11:30:18 +00001557 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1558 assert( eFileLock!=PENDING_LOCK );
1559 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001560
drh8af6c222010-05-14 12:43:01 +00001561 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001562 */
drh6c7d5c52008-11-21 20:32:33 +00001563 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001564 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001565
danielk1977ad94b582007-08-20 06:44:22 +00001566 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001567 ** handle that precludes the requested lock, return BUSY.
1568 */
drh8af6c222010-05-14 12:43:01 +00001569 if( (pFile->eFileLock!=pInode->eFileLock &&
1570 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001571 ){
1572 rc = SQLITE_BUSY;
1573 goto end_lock;
1574 }
1575
1576 /* If a SHARED lock is requested, and some thread using this PID already
1577 ** has a SHARED or RESERVED lock, then increment reference counts and
1578 ** return SQLITE_OK.
1579 */
drh308c2a52010-05-14 11:30:18 +00001580 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001581 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001582 assert( eFileLock==SHARED_LOCK );
1583 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001584 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001585 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001586 pInode->nShared++;
1587 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001588 goto end_lock;
1589 }
1590
danielk19779a1d0ab2004-06-01 14:09:28 +00001591
drh3cde3bb2004-06-12 02:17:14 +00001592 /* A PENDING lock is needed before acquiring a SHARED lock and before
1593 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1594 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001595 */
drh0c2694b2009-09-03 16:23:44 +00001596 lock.l_len = 1L;
1597 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001598 if( eFileLock==SHARED_LOCK
1599 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001600 ){
drh308c2a52010-05-14 11:30:18 +00001601 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001602 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001603 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001604 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001605 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001606 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001607 pFile->lastErrno = tErrno;
1608 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001609 goto end_lock;
1610 }
drh3cde3bb2004-06-12 02:17:14 +00001611 }
1612
1613
1614 /* If control gets to this point, then actually go ahead and make
1615 ** operating system calls for the specified lock.
1616 */
drh308c2a52010-05-14 11:30:18 +00001617 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001618 assert( pInode->nShared==0 );
1619 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001620 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001621
drh2ac3ee92004-06-07 16:27:46 +00001622 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001623 lock.l_start = SHARED_FIRST;
1624 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001625 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001626 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001627 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001628 }
dan661d71a2011-03-30 19:08:03 +00001629
drh2ac3ee92004-06-07 16:27:46 +00001630 /* Drop the temporary PENDING lock */
1631 lock.l_start = PENDING_BYTE;
1632 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001633 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001634 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1635 /* This could happen with a network mount */
1636 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001637 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001638 }
dan661d71a2011-03-30 19:08:03 +00001639
1640 if( rc ){
1641 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001642 pFile->lastErrno = tErrno;
1643 }
dan661d71a2011-03-30 19:08:03 +00001644 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001645 }else{
drh308c2a52010-05-14 11:30:18 +00001646 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001647 pInode->nLock++;
1648 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001649 }
drh8af6c222010-05-14 12:43:01 +00001650 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001651 /* We are trying for an exclusive lock but another thread in this
1652 ** same process is still holding a shared lock. */
1653 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001654 }else{
drh3cde3bb2004-06-12 02:17:14 +00001655 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001656 ** assumed that there is a SHARED or greater lock on the file
1657 ** already.
1658 */
drh308c2a52010-05-14 11:30:18 +00001659 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001660 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001661
1662 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1663 if( eFileLock==RESERVED_LOCK ){
1664 lock.l_start = RESERVED_BYTE;
1665 lock.l_len = 1L;
1666 }else{
1667 lock.l_start = SHARED_FIRST;
1668 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001669 }
dan661d71a2011-03-30 19:08:03 +00001670
1671 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001672 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001673 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001674 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001675 pFile->lastErrno = tErrno;
1676 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001677 }
drhbbd42a62004-05-22 17:41:58 +00001678 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001679
drh8f941bc2009-01-14 23:03:40 +00001680
drhd3d8c042012-05-29 17:02:40 +00001681#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001682 /* Set up the transaction-counter change checking flags when
1683 ** transitioning from a SHARED to a RESERVED lock. The change
1684 ** from SHARED to RESERVED marks the beginning of a normal
1685 ** write operation (not a hot journal rollback).
1686 */
1687 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001688 && pFile->eFileLock<=SHARED_LOCK
1689 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001690 ){
1691 pFile->transCntrChng = 0;
1692 pFile->dbUpdate = 0;
1693 pFile->inNormalWrite = 1;
1694 }
1695#endif
1696
1697
danielk1977ecb2a962004-06-02 06:30:16 +00001698 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001699 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001700 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001701 }else if( eFileLock==EXCLUSIVE_LOCK ){
1702 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001703 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001704 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001705
1706end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001707 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001708 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1709 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001710 return rc;
1711}
1712
1713/*
dan08da86a2009-08-21 17:18:03 +00001714** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001715** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001716*/
1717static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001718 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001719 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001720 p->pNext = pInode->pUnused;
1721 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001722 pFile->h = -1;
1723 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001724}
1725
1726/*
drh308c2a52010-05-14 11:30:18 +00001727** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001728** must be either NO_LOCK or SHARED_LOCK.
1729**
1730** If the locking level of the file descriptor is already at or below
1731** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001732**
1733** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1734** the byte range is divided into 2 parts and the first part is unlocked then
1735** set to a read lock, then the other part is simply unlocked. This works
1736** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1737** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001738*/
drha7e61d82011-03-12 17:02:57 +00001739static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001740 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001741 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001742 struct flock lock;
1743 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001744
drh054889e2005-11-30 03:20:31 +00001745 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001746 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001747 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001748 getpid()));
drha6abd042004-06-09 17:37:22 +00001749
drh308c2a52010-05-14 11:30:18 +00001750 assert( eFileLock<=SHARED_LOCK );
1751 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001752 return SQLITE_OK;
1753 }
drh6c7d5c52008-11-21 20:32:33 +00001754 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001755 pInode = pFile->pInode;
1756 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001757 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001758 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001759
drhd3d8c042012-05-29 17:02:40 +00001760#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001761 /* When reducing a lock such that other processes can start
1762 ** reading the database file again, make sure that the
1763 ** transaction counter was updated if any part of the database
1764 ** file changed. If the transaction counter is not updated,
1765 ** other connections to the same file might not realize that
1766 ** the file has changed and hence might not know to flush their
1767 ** cache. The use of a stale cache can lead to database corruption.
1768 */
drh8f941bc2009-01-14 23:03:40 +00001769 pFile->inNormalWrite = 0;
1770#endif
1771
drh7ed97b92010-01-20 13:07:21 +00001772 /* downgrading to a shared lock on NFS involves clearing the write lock
1773 ** before establishing the readlock - to avoid a race condition we downgrade
1774 ** the lock in 2 blocks, so that part of the range will be covered by a
1775 ** write lock until the rest is covered by a read lock:
1776 ** 1: [WWWWW]
1777 ** 2: [....W]
1778 ** 3: [RRRRW]
1779 ** 4: [RRRR.]
1780 */
drh308c2a52010-05-14 11:30:18 +00001781 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001782
1783#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001784 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001785 assert( handleNFSUnlock==0 );
1786#endif
1787#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001788 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001789 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001790 off_t divSize = SHARED_SIZE - 1;
1791
1792 lock.l_type = F_UNLCK;
1793 lock.l_whence = SEEK_SET;
1794 lock.l_start = SHARED_FIRST;
1795 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001796 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001797 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001798 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001799 if( IS_LOCK_ERROR(rc) ){
1800 pFile->lastErrno = tErrno;
1801 }
1802 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001803 }
drh7ed97b92010-01-20 13:07:21 +00001804 lock.l_type = F_RDLCK;
1805 lock.l_whence = SEEK_SET;
1806 lock.l_start = SHARED_FIRST;
1807 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001808 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001809 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001810 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1811 if( IS_LOCK_ERROR(rc) ){
1812 pFile->lastErrno = tErrno;
1813 }
1814 goto end_unlock;
1815 }
1816 lock.l_type = F_UNLCK;
1817 lock.l_whence = SEEK_SET;
1818 lock.l_start = SHARED_FIRST+divSize;
1819 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001820 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001821 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001822 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001823 if( IS_LOCK_ERROR(rc) ){
1824 pFile->lastErrno = tErrno;
1825 }
1826 goto end_unlock;
1827 }
drh30f776f2011-02-25 03:25:07 +00001828 }else
1829#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1830 {
drh7ed97b92010-01-20 13:07:21 +00001831 lock.l_type = F_RDLCK;
1832 lock.l_whence = SEEK_SET;
1833 lock.l_start = SHARED_FIRST;
1834 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001835 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001836 /* In theory, the call to unixFileLock() cannot fail because another
1837 ** process is holding an incompatible lock. If it does, this
1838 ** indicates that the other process is not following the locking
1839 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1840 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1841 ** an assert to fail). */
1842 rc = SQLITE_IOERR_RDLOCK;
1843 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001844 goto end_unlock;
1845 }
drh9c105bb2004-10-02 20:38:28 +00001846 }
1847 }
drhbbd42a62004-05-22 17:41:58 +00001848 lock.l_type = F_UNLCK;
1849 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001850 lock.l_start = PENDING_BYTE;
1851 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001852 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001853 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001854 }else{
danea83bc62011-04-01 11:56:32 +00001855 rc = SQLITE_IOERR_UNLOCK;
1856 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001857 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001858 }
drhbbd42a62004-05-22 17:41:58 +00001859 }
drh308c2a52010-05-14 11:30:18 +00001860 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001861 /* Decrement the shared lock counter. Release the lock using an
1862 ** OS call only when all threads in this same process have released
1863 ** the lock.
1864 */
drh8af6c222010-05-14 12:43:01 +00001865 pInode->nShared--;
1866 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001867 lock.l_type = F_UNLCK;
1868 lock.l_whence = SEEK_SET;
1869 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001870 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001871 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001872 }else{
danea83bc62011-04-01 11:56:32 +00001873 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001874 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001875 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001876 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001877 }
drha6abd042004-06-09 17:37:22 +00001878 }
1879
drhbbd42a62004-05-22 17:41:58 +00001880 /* Decrement the count of locks against this same file. When the
1881 ** count reaches zero, close any other file descriptors whose close
1882 ** was deferred because of outstanding locks.
1883 */
drh8af6c222010-05-14 12:43:01 +00001884 pInode->nLock--;
1885 assert( pInode->nLock>=0 );
1886 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001887 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001888 }
1889 }
drhf2f105d2012-08-20 15:53:54 +00001890
aswift5b1a2562008-08-22 00:22:35 +00001891end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001892 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001893 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001894 return rc;
drhbbd42a62004-05-22 17:41:58 +00001895}
1896
1897/*
drh308c2a52010-05-14 11:30:18 +00001898** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001899** must be either NO_LOCK or SHARED_LOCK.
1900**
1901** If the locking level of the file descriptor is already at or below
1902** the requested locking level, this routine is a no-op.
1903*/
drh308c2a52010-05-14 11:30:18 +00001904static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001905#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001906 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001907#endif
drha7e61d82011-03-12 17:02:57 +00001908 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001909}
1910
mistachkine98844f2013-08-24 00:59:24 +00001911#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001912static int unixMapfile(unixFile *pFd, i64 nByte);
1913static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001914#endif
danf23da962013-03-23 21:00:41 +00001915
drh7ed97b92010-01-20 13:07:21 +00001916/*
danielk1977e339d652008-06-28 11:23:00 +00001917** This function performs the parts of the "close file" operation
1918** common to all locking schemes. It closes the directory and file
1919** handles, if they are valid, and sets all fields of the unixFile
1920** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001921**
1922** It is *not* necessary to hold the mutex when this routine is called,
1923** even on VxWorks. A mutex will be acquired on VxWorks by the
1924** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001925*/
1926static int closeUnixFile(sqlite3_file *id){
1927 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001928#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001929 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001930#endif
dan661d71a2011-03-30 19:08:03 +00001931 if( pFile->h>=0 ){
1932 robust_close(pFile, pFile->h, __LINE__);
1933 pFile->h = -1;
1934 }
1935#if OS_VXWORKS
1936 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001937 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001938 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001939 }
1940 vxworksReleaseFileId(pFile->pId);
1941 pFile->pId = 0;
1942 }
1943#endif
1944 OSTRACE(("CLOSE %-3d\n", pFile->h));
1945 OpenCounter(-1);
1946 sqlite3_free(pFile->pUnused);
1947 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001948 return SQLITE_OK;
1949}
1950
1951/*
danielk1977e3026632004-06-22 11:29:02 +00001952** Close a file.
1953*/
danielk197762079062007-08-15 17:08:46 +00001954static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001955 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001956 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001957 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001958 unixUnlock(id, NO_LOCK);
1959 unixEnterMutex();
1960
1961 /* unixFile.pInode is always valid here. Otherwise, a different close
1962 ** routine (e.g. nolockClose()) would be called instead.
1963 */
1964 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1965 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1966 /* If there are outstanding locks, do not actually close the file just
1967 ** yet because that would clear those locks. Instead, add the file
1968 ** descriptor to pInode->pUnused list. It will be automatically closed
1969 ** when the last lock is cleared.
1970 */
1971 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001972 }
dan661d71a2011-03-30 19:08:03 +00001973 releaseInodeInfo(pFile);
1974 rc = closeUnixFile(id);
1975 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001976 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001977}
1978
drh734c9862008-11-28 15:37:20 +00001979/************** End of the posix advisory lock implementation *****************
1980******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001981
drh734c9862008-11-28 15:37:20 +00001982/******************************************************************************
1983****************************** No-op Locking **********************************
1984**
1985** Of the various locking implementations available, this is by far the
1986** simplest: locking is ignored. No attempt is made to lock the database
1987** file for reading or writing.
1988**
1989** This locking mode is appropriate for use on read-only databases
1990** (ex: databases that are burned into CD-ROM, for example.) It can
1991** also be used if the application employs some external mechanism to
1992** prevent simultaneous access of the same database by two or more
1993** database connections. But there is a serious risk of database
1994** corruption if this locking mode is used in situations where multiple
1995** database connections are accessing the same database file at the same
1996** time and one or more of those connections are writing.
1997*/
drhbfe66312006-10-03 17:40:40 +00001998
drh734c9862008-11-28 15:37:20 +00001999static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2000 UNUSED_PARAMETER(NotUsed);
2001 *pResOut = 0;
2002 return SQLITE_OK;
2003}
drh734c9862008-11-28 15:37:20 +00002004static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2005 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2006 return SQLITE_OK;
2007}
drh734c9862008-11-28 15:37:20 +00002008static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2009 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2010 return SQLITE_OK;
2011}
2012
2013/*
drh9b35ea62008-11-29 02:20:26 +00002014** Close the file.
drh734c9862008-11-28 15:37:20 +00002015*/
2016static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002017 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002018}
2019
2020/******************* End of the no-op lock implementation *********************
2021******************************************************************************/
2022
2023/******************************************************************************
2024************************* Begin dot-file Locking ******************************
2025**
mistachkin48864df2013-03-21 21:20:32 +00002026** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002027** files (really a directory) to control access to the database. This works
2028** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002029**
2030** (1) There is zero concurrency. A single reader blocks all other
2031** connections from reading or writing the database.
2032**
2033** (2) An application crash or power loss can leave stale lock files
2034** sitting around that need to be cleared manually.
2035**
2036** Nevertheless, a dotlock is an appropriate locking mode for use if no
2037** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002038**
drh9ef6bc42011-11-04 02:24:02 +00002039** Dotfile locking works by creating a subdirectory in the same directory as
2040** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002041** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002042** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002043*/
2044
2045/*
2046** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002047** lock directory.
drh734c9862008-11-28 15:37:20 +00002048*/
2049#define DOTLOCK_SUFFIX ".lock"
2050
drh7708e972008-11-29 00:56:52 +00002051/*
2052** This routine checks if there is a RESERVED lock held on the specified
2053** file by this or any other process. If such a lock is held, set *pResOut
2054** to a non-zero value otherwise *pResOut is set to zero. The return value
2055** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2056**
2057** In dotfile locking, either a lock exists or it does not. So in this
2058** variation of CheckReservedLock(), *pResOut is set to true if any lock
2059** is held on the file and false if the file is unlocked.
2060*/
drh734c9862008-11-28 15:37:20 +00002061static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2062 int rc = SQLITE_OK;
2063 int reserved = 0;
2064 unixFile *pFile = (unixFile*)id;
2065
2066 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2067
2068 assert( pFile );
2069
2070 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002071 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002072 /* Either this connection or some other connection in the same process
2073 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002074 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002075 }else{
2076 /* The lock is held if and only if the lockfile exists */
2077 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002078 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002079 }
drh308c2a52010-05-14 11:30:18 +00002080 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002081 *pResOut = reserved;
2082 return rc;
2083}
2084
drh7708e972008-11-29 00:56:52 +00002085/*
drh308c2a52010-05-14 11:30:18 +00002086** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002087** of the following:
2088**
2089** (1) SHARED_LOCK
2090** (2) RESERVED_LOCK
2091** (3) PENDING_LOCK
2092** (4) EXCLUSIVE_LOCK
2093**
2094** Sometimes when requesting one lock state, additional lock states
2095** are inserted in between. The locking might fail on one of the later
2096** transitions leaving the lock state different from what it started but
2097** still short of its goal. The following chart shows the allowed
2098** transitions and the inserted intermediate states:
2099**
2100** UNLOCKED -> SHARED
2101** SHARED -> RESERVED
2102** SHARED -> (PENDING) -> EXCLUSIVE
2103** RESERVED -> (PENDING) -> EXCLUSIVE
2104** PENDING -> EXCLUSIVE
2105**
2106** This routine will only increase a lock. Use the sqlite3OsUnlock()
2107** routine to lower a locking level.
2108**
2109** With dotfile locking, we really only support state (4): EXCLUSIVE.
2110** But we track the other locking levels internally.
2111*/
drh308c2a52010-05-14 11:30:18 +00002112static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002113 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002114 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002115 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002116
drh7708e972008-11-29 00:56:52 +00002117
2118 /* If we have any lock, then the lock file already exists. All we have
2119 ** to do is adjust our internal record of the lock level.
2120 */
drh308c2a52010-05-14 11:30:18 +00002121 if( pFile->eFileLock > NO_LOCK ){
2122 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002123 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002124#ifdef HAVE_UTIME
2125 utime(zLockFile, NULL);
2126#else
drh734c9862008-11-28 15:37:20 +00002127 utimes(zLockFile, NULL);
2128#endif
drh7708e972008-11-29 00:56:52 +00002129 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002130 }
2131
2132 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002133 rc = osMkdir(zLockFile, 0777);
2134 if( rc<0 ){
2135 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002136 int tErrno = errno;
2137 if( EEXIST == tErrno ){
2138 rc = SQLITE_BUSY;
2139 } else {
2140 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2141 if( IS_LOCK_ERROR(rc) ){
2142 pFile->lastErrno = tErrno;
2143 }
2144 }
drh7708e972008-11-29 00:56:52 +00002145 return rc;
drh734c9862008-11-28 15:37:20 +00002146 }
drh734c9862008-11-28 15:37:20 +00002147
2148 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002149 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002150 return rc;
2151}
2152
drh7708e972008-11-29 00:56:52 +00002153/*
drh308c2a52010-05-14 11:30:18 +00002154** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002155** must be either NO_LOCK or SHARED_LOCK.
2156**
2157** If the locking level of the file descriptor is already at or below
2158** the requested locking level, this routine is a no-op.
2159**
2160** When the locking level reaches NO_LOCK, delete the lock file.
2161*/
drh308c2a52010-05-14 11:30:18 +00002162static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002163 unixFile *pFile = (unixFile*)id;
2164 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002165 int rc;
drh734c9862008-11-28 15:37:20 +00002166
2167 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002168 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002169 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002170 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002171
2172 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002173 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002174 return SQLITE_OK;
2175 }
drh7708e972008-11-29 00:56:52 +00002176
2177 /* To downgrade to shared, simply update our internal notion of the
2178 ** lock state. No need to mess with the file on disk.
2179 */
drh308c2a52010-05-14 11:30:18 +00002180 if( eFileLock==SHARED_LOCK ){
2181 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002182 return SQLITE_OK;
2183 }
2184
drh7708e972008-11-29 00:56:52 +00002185 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002186 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002187 rc = osRmdir(zLockFile);
2188 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2189 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002190 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002191 rc = 0;
drh734c9862008-11-28 15:37:20 +00002192 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002193 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002194 }
2195 if( IS_LOCK_ERROR(rc) ){
2196 pFile->lastErrno = tErrno;
2197 }
2198 return rc;
2199 }
drh308c2a52010-05-14 11:30:18 +00002200 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002201 return SQLITE_OK;
2202}
2203
2204/*
drh9b35ea62008-11-29 02:20:26 +00002205** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002206*/
2207static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002208 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002209 if( id ){
2210 unixFile *pFile = (unixFile*)id;
2211 dotlockUnlock(id, NO_LOCK);
2212 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002213 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002214 }
drh734c9862008-11-28 15:37:20 +00002215 return rc;
2216}
2217/****************** End of the dot-file lock implementation *******************
2218******************************************************************************/
2219
2220/******************************************************************************
2221************************** Begin flock Locking ********************************
2222**
2223** Use the flock() system call to do file locking.
2224**
drh6b9d6dd2008-12-03 19:34:47 +00002225** flock() locking is like dot-file locking in that the various
2226** fine-grain locking levels supported by SQLite are collapsed into
2227** a single exclusive lock. In other words, SHARED, RESERVED, and
2228** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2229** still works when you do this, but concurrency is reduced since
2230** only a single process can be reading the database at a time.
2231**
drh734c9862008-11-28 15:37:20 +00002232** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2233** compiling for VXWORKS.
2234*/
2235#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002236
drh6b9d6dd2008-12-03 19:34:47 +00002237/*
drhff812312011-02-23 13:33:46 +00002238** Retry flock() calls that fail with EINTR
2239*/
2240#ifdef EINTR
2241static int robust_flock(int fd, int op){
2242 int rc;
2243 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2244 return rc;
2245}
2246#else
drh5c819272011-02-23 14:00:12 +00002247# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002248#endif
2249
2250
2251/*
drh6b9d6dd2008-12-03 19:34:47 +00002252** This routine checks if there is a RESERVED lock held on the specified
2253** file by this or any other process. If such a lock is held, set *pResOut
2254** to a non-zero value otherwise *pResOut is set to zero. The return value
2255** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2256*/
drh734c9862008-11-28 15:37:20 +00002257static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2258 int rc = SQLITE_OK;
2259 int reserved = 0;
2260 unixFile *pFile = (unixFile*)id;
2261
2262 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2263
2264 assert( pFile );
2265
2266 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002267 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002268 reserved = 1;
2269 }
2270
2271 /* Otherwise see if some other process holds it. */
2272 if( !reserved ){
2273 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002274 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002275 if( !lrc ){
2276 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002277 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002278 if ( lrc ) {
2279 int tErrno = errno;
2280 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002281 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002282 if( IS_LOCK_ERROR(lrc) ){
2283 pFile->lastErrno = tErrno;
2284 rc = lrc;
2285 }
2286 }
2287 } else {
2288 int tErrno = errno;
2289 reserved = 1;
2290 /* someone else might have it reserved */
2291 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2292 if( IS_LOCK_ERROR(lrc) ){
2293 pFile->lastErrno = tErrno;
2294 rc = lrc;
2295 }
2296 }
2297 }
drh308c2a52010-05-14 11:30:18 +00002298 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002299
2300#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2301 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2302 rc = SQLITE_OK;
2303 reserved=1;
2304 }
2305#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2306 *pResOut = reserved;
2307 return rc;
2308}
2309
drh6b9d6dd2008-12-03 19:34:47 +00002310/*
drh308c2a52010-05-14 11:30:18 +00002311** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002312** of the following:
2313**
2314** (1) SHARED_LOCK
2315** (2) RESERVED_LOCK
2316** (3) PENDING_LOCK
2317** (4) EXCLUSIVE_LOCK
2318**
2319** Sometimes when requesting one lock state, additional lock states
2320** are inserted in between. The locking might fail on one of the later
2321** transitions leaving the lock state different from what it started but
2322** still short of its goal. The following chart shows the allowed
2323** transitions and the inserted intermediate states:
2324**
2325** UNLOCKED -> SHARED
2326** SHARED -> RESERVED
2327** SHARED -> (PENDING) -> EXCLUSIVE
2328** RESERVED -> (PENDING) -> EXCLUSIVE
2329** PENDING -> EXCLUSIVE
2330**
2331** flock() only really support EXCLUSIVE locks. We track intermediate
2332** lock states in the sqlite3_file structure, but all locks SHARED or
2333** above are really EXCLUSIVE locks and exclude all other processes from
2334** access the file.
2335**
2336** This routine will only increase a lock. Use the sqlite3OsUnlock()
2337** routine to lower a locking level.
2338*/
drh308c2a52010-05-14 11:30:18 +00002339static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002340 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002341 unixFile *pFile = (unixFile*)id;
2342
2343 assert( pFile );
2344
2345 /* if we already have a lock, it is exclusive.
2346 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002347 if (pFile->eFileLock > NO_LOCK) {
2348 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002349 return SQLITE_OK;
2350 }
2351
2352 /* grab an exclusive lock */
2353
drhff812312011-02-23 13:33:46 +00002354 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002355 int tErrno = errno;
2356 /* didn't get, must be busy */
2357 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2358 if( IS_LOCK_ERROR(rc) ){
2359 pFile->lastErrno = tErrno;
2360 }
2361 } else {
2362 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002363 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002364 }
drh308c2a52010-05-14 11:30:18 +00002365 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2366 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002367#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2368 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2369 rc = SQLITE_BUSY;
2370 }
2371#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2372 return rc;
2373}
2374
drh6b9d6dd2008-12-03 19:34:47 +00002375
2376/*
drh308c2a52010-05-14 11:30:18 +00002377** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002378** must be either NO_LOCK or SHARED_LOCK.
2379**
2380** If the locking level of the file descriptor is already at or below
2381** the requested locking level, this routine is a no-op.
2382*/
drh308c2a52010-05-14 11:30:18 +00002383static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002384 unixFile *pFile = (unixFile*)id;
2385
2386 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002387 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2388 pFile->eFileLock, getpid()));
2389 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002390
2391 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002392 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002393 return SQLITE_OK;
2394 }
2395
2396 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002397 if (eFileLock==SHARED_LOCK) {
2398 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002399 return SQLITE_OK;
2400 }
2401
2402 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002403 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002404#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002405 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002406#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002407 return SQLITE_IOERR_UNLOCK;
2408 }else{
drh308c2a52010-05-14 11:30:18 +00002409 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002410 return SQLITE_OK;
2411 }
2412}
2413
2414/*
2415** Close a file.
2416*/
2417static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002418 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002419 if( id ){
2420 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002421 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002422 }
drh5a05be12012-10-09 18:51:44 +00002423 return rc;
drh734c9862008-11-28 15:37:20 +00002424}
2425
2426#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2427
2428/******************* End of the flock lock implementation *********************
2429******************************************************************************/
2430
2431/******************************************************************************
2432************************ Begin Named Semaphore Locking ************************
2433**
2434** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002435**
2436** Semaphore locking is like dot-lock and flock in that it really only
2437** supports EXCLUSIVE locking. Only a single process can read or write
2438** the database file at a time. This reduces potential concurrency, but
2439** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002440*/
2441#if OS_VXWORKS
2442
drh6b9d6dd2008-12-03 19:34:47 +00002443/*
2444** This routine checks if there is a RESERVED lock held on the specified
2445** file by this or any other process. If such a lock is held, set *pResOut
2446** to a non-zero value otherwise *pResOut is set to zero. The return value
2447** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2448*/
drh734c9862008-11-28 15:37:20 +00002449static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2450 int rc = SQLITE_OK;
2451 int reserved = 0;
2452 unixFile *pFile = (unixFile*)id;
2453
2454 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2455
2456 assert( pFile );
2457
2458 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002459 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002460 reserved = 1;
2461 }
2462
2463 /* Otherwise see if some other process holds it. */
2464 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002465 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002466 struct stat statBuf;
2467
2468 if( sem_trywait(pSem)==-1 ){
2469 int tErrno = errno;
2470 if( EAGAIN != tErrno ){
2471 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2472 pFile->lastErrno = tErrno;
2473 } else {
2474 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002475 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002476 }
2477 }else{
2478 /* we could have it if we want it */
2479 sem_post(pSem);
2480 }
2481 }
drh308c2a52010-05-14 11:30:18 +00002482 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002483
2484 *pResOut = reserved;
2485 return rc;
2486}
2487
drh6b9d6dd2008-12-03 19:34:47 +00002488/*
drh308c2a52010-05-14 11:30:18 +00002489** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002490** of the following:
2491**
2492** (1) SHARED_LOCK
2493** (2) RESERVED_LOCK
2494** (3) PENDING_LOCK
2495** (4) EXCLUSIVE_LOCK
2496**
2497** Sometimes when requesting one lock state, additional lock states
2498** are inserted in between. The locking might fail on one of the later
2499** transitions leaving the lock state different from what it started but
2500** still short of its goal. The following chart shows the allowed
2501** transitions and the inserted intermediate states:
2502**
2503** UNLOCKED -> SHARED
2504** SHARED -> RESERVED
2505** SHARED -> (PENDING) -> EXCLUSIVE
2506** RESERVED -> (PENDING) -> EXCLUSIVE
2507** PENDING -> EXCLUSIVE
2508**
2509** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2510** lock states in the sqlite3_file structure, but all locks SHARED or
2511** above are really EXCLUSIVE locks and exclude all other processes from
2512** access the file.
2513**
2514** This routine will only increase a lock. Use the sqlite3OsUnlock()
2515** routine to lower a locking level.
2516*/
drh308c2a52010-05-14 11:30:18 +00002517static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002518 unixFile *pFile = (unixFile*)id;
2519 int fd;
drh8af6c222010-05-14 12:43:01 +00002520 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002521 int rc = SQLITE_OK;
2522
2523 /* if we already have a lock, it is exclusive.
2524 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002525 if (pFile->eFileLock > NO_LOCK) {
2526 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002527 rc = SQLITE_OK;
2528 goto sem_end_lock;
2529 }
2530
2531 /* lock semaphore now but bail out when already locked. */
2532 if( sem_trywait(pSem)==-1 ){
2533 rc = SQLITE_BUSY;
2534 goto sem_end_lock;
2535 }
2536
2537 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002538 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002539
2540 sem_end_lock:
2541 return rc;
2542}
2543
drh6b9d6dd2008-12-03 19:34:47 +00002544/*
drh308c2a52010-05-14 11:30:18 +00002545** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002546** must be either NO_LOCK or SHARED_LOCK.
2547**
2548** If the locking level of the file descriptor is already at or below
2549** the requested locking level, this routine is a no-op.
2550*/
drh308c2a52010-05-14 11:30:18 +00002551static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002552 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002553 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002554
2555 assert( pFile );
2556 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002557 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002558 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002559 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002560
2561 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002562 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002563 return SQLITE_OK;
2564 }
2565
2566 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002567 if (eFileLock==SHARED_LOCK) {
2568 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002569 return SQLITE_OK;
2570 }
2571
2572 /* no, really unlock. */
2573 if ( sem_post(pSem)==-1 ) {
2574 int rc, tErrno = errno;
2575 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2576 if( IS_LOCK_ERROR(rc) ){
2577 pFile->lastErrno = tErrno;
2578 }
2579 return rc;
2580 }
drh308c2a52010-05-14 11:30:18 +00002581 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002582 return SQLITE_OK;
2583}
2584
2585/*
2586 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002587 */
drh734c9862008-11-28 15:37:20 +00002588static int semClose(sqlite3_file *id) {
2589 if( id ){
2590 unixFile *pFile = (unixFile*)id;
2591 semUnlock(id, NO_LOCK);
2592 assert( pFile );
2593 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002594 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002595 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002596 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002597 }
2598 return SQLITE_OK;
2599}
2600
2601#endif /* OS_VXWORKS */
2602/*
2603** Named semaphore locking is only available on VxWorks.
2604**
2605*************** End of the named semaphore lock implementation ****************
2606******************************************************************************/
2607
2608
2609/******************************************************************************
2610*************************** Begin AFP Locking *********************************
2611**
2612** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2613** on Apple Macintosh computers - both OS9 and OSX.
2614**
2615** Third-party implementations of AFP are available. But this code here
2616** only works on OSX.
2617*/
2618
drhd2cb50b2009-01-09 21:41:17 +00002619#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002620/*
2621** The afpLockingContext structure contains all afp lock specific state
2622*/
drhbfe66312006-10-03 17:40:40 +00002623typedef struct afpLockingContext afpLockingContext;
2624struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002625 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002626 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002627};
2628
2629struct ByteRangeLockPB2
2630{
2631 unsigned long long offset; /* offset to first byte to lock */
2632 unsigned long long length; /* nbr of bytes to lock */
2633 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2634 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2635 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2636 int fd; /* file desc to assoc this lock with */
2637};
2638
drhfd131da2007-08-07 17:13:03 +00002639#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002640
drh6b9d6dd2008-12-03 19:34:47 +00002641/*
2642** This is a utility for setting or clearing a bit-range lock on an
2643** AFP filesystem.
2644**
2645** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2646*/
2647static int afpSetLock(
2648 const char *path, /* Name of the file to be locked or unlocked */
2649 unixFile *pFile, /* Open file descriptor on path */
2650 unsigned long long offset, /* First byte to be locked */
2651 unsigned long long length, /* Number of bytes to lock */
2652 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002653){
drh6b9d6dd2008-12-03 19:34:47 +00002654 struct ByteRangeLockPB2 pb;
2655 int err;
drhbfe66312006-10-03 17:40:40 +00002656
2657 pb.unLockFlag = setLockFlag ? 0 : 1;
2658 pb.startEndFlag = 0;
2659 pb.offset = offset;
2660 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002661 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002662
drh308c2a52010-05-14 11:30:18 +00002663 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002664 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002665 offset, length));
drhbfe66312006-10-03 17:40:40 +00002666 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2667 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002668 int rc;
2669 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002670 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2671 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002672#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2673 rc = SQLITE_BUSY;
2674#else
drh734c9862008-11-28 15:37:20 +00002675 rc = sqliteErrorFromPosixError(tErrno,
2676 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002677#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002678 if( IS_LOCK_ERROR(rc) ){
2679 pFile->lastErrno = tErrno;
2680 }
2681 return rc;
drhbfe66312006-10-03 17:40:40 +00002682 } else {
aswift5b1a2562008-08-22 00:22:35 +00002683 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002684 }
2685}
2686
drh6b9d6dd2008-12-03 19:34:47 +00002687/*
2688** This routine checks if there is a RESERVED lock held on the specified
2689** file by this or any other process. If such a lock is held, set *pResOut
2690** to a non-zero value otherwise *pResOut is set to zero. The return value
2691** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2692*/
danielk1977e339d652008-06-28 11:23:00 +00002693static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002694 int rc = SQLITE_OK;
2695 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002696 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002697 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002698
aswift5b1a2562008-08-22 00:22:35 +00002699 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2700
2701 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002702 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002703 if( context->reserved ){
2704 *pResOut = 1;
2705 return SQLITE_OK;
2706 }
drh8af6c222010-05-14 12:43:01 +00002707 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002708
2709 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002710 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002711 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002712 }
2713
2714 /* Otherwise see if some other process holds it.
2715 */
aswift5b1a2562008-08-22 00:22:35 +00002716 if( !reserved ){
2717 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002718 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002719 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002720 /* if we succeeded in taking the reserved lock, unlock it to restore
2721 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002722 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002723 } else {
2724 /* if we failed to get the lock then someone else must have it */
2725 reserved = 1;
2726 }
2727 if( IS_LOCK_ERROR(lrc) ){
2728 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002729 }
2730 }
drhbfe66312006-10-03 17:40:40 +00002731
drh7ed97b92010-01-20 13:07:21 +00002732 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002733 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002734
2735 *pResOut = reserved;
2736 return rc;
drhbfe66312006-10-03 17:40:40 +00002737}
2738
drh6b9d6dd2008-12-03 19:34:47 +00002739/*
drh308c2a52010-05-14 11:30:18 +00002740** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002741** of the following:
2742**
2743** (1) SHARED_LOCK
2744** (2) RESERVED_LOCK
2745** (3) PENDING_LOCK
2746** (4) EXCLUSIVE_LOCK
2747**
2748** Sometimes when requesting one lock state, additional lock states
2749** are inserted in between. The locking might fail on one of the later
2750** transitions leaving the lock state different from what it started but
2751** still short of its goal. The following chart shows the allowed
2752** transitions and the inserted intermediate states:
2753**
2754** UNLOCKED -> SHARED
2755** SHARED -> RESERVED
2756** SHARED -> (PENDING) -> EXCLUSIVE
2757** RESERVED -> (PENDING) -> EXCLUSIVE
2758** PENDING -> EXCLUSIVE
2759**
2760** This routine will only increase a lock. Use the sqlite3OsUnlock()
2761** routine to lower a locking level.
2762*/
drh308c2a52010-05-14 11:30:18 +00002763static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002764 int rc = SQLITE_OK;
2765 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002766 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002767 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002768
2769 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002770 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2771 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002772 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002773
drhbfe66312006-10-03 17:40:40 +00002774 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002775 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002776 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002777 */
drh308c2a52010-05-14 11:30:18 +00002778 if( pFile->eFileLock>=eFileLock ){
2779 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2780 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002781 return SQLITE_OK;
2782 }
2783
2784 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002785 ** (1) We never move from unlocked to anything higher than shared lock.
2786 ** (2) SQLite never explicitly requests a pendig lock.
2787 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002788 */
drh308c2a52010-05-14 11:30:18 +00002789 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2790 assert( eFileLock!=PENDING_LOCK );
2791 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002792
drh8af6c222010-05-14 12:43:01 +00002793 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002794 */
drh6c7d5c52008-11-21 20:32:33 +00002795 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002796 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002797
2798 /* If some thread using this PID has a lock via a different unixFile*
2799 ** handle that precludes the requested lock, return BUSY.
2800 */
drh8af6c222010-05-14 12:43:01 +00002801 if( (pFile->eFileLock!=pInode->eFileLock &&
2802 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002803 ){
2804 rc = SQLITE_BUSY;
2805 goto afp_end_lock;
2806 }
2807
2808 /* If a SHARED lock is requested, and some thread using this PID already
2809 ** has a SHARED or RESERVED lock, then increment reference counts and
2810 ** return SQLITE_OK.
2811 */
drh308c2a52010-05-14 11:30:18 +00002812 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002813 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002814 assert( eFileLock==SHARED_LOCK );
2815 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002816 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002817 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002818 pInode->nShared++;
2819 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002820 goto afp_end_lock;
2821 }
drhbfe66312006-10-03 17:40:40 +00002822
2823 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002824 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2825 ** be released.
2826 */
drh308c2a52010-05-14 11:30:18 +00002827 if( eFileLock==SHARED_LOCK
2828 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002829 ){
2830 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002831 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002832 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002833 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002834 goto afp_end_lock;
2835 }
2836 }
2837
2838 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002839 ** operating system calls for the specified lock.
2840 */
drh308c2a52010-05-14 11:30:18 +00002841 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002842 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002843 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002844
drh8af6c222010-05-14 12:43:01 +00002845 assert( pInode->nShared==0 );
2846 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002847
2848 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002849 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002850 /* note that the quality of the randomness doesn't matter that much */
2851 lk = random();
drh8af6c222010-05-14 12:43:01 +00002852 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002853 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002854 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002855 if( IS_LOCK_ERROR(lrc1) ){
2856 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002857 }
aswift5b1a2562008-08-22 00:22:35 +00002858 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002859 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002860
aswift5b1a2562008-08-22 00:22:35 +00002861 if( IS_LOCK_ERROR(lrc1) ) {
2862 pFile->lastErrno = lrc1Errno;
2863 rc = lrc1;
2864 goto afp_end_lock;
2865 } else if( IS_LOCK_ERROR(lrc2) ){
2866 rc = lrc2;
2867 goto afp_end_lock;
2868 } else if( lrc1 != SQLITE_OK ) {
2869 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002870 } else {
drh308c2a52010-05-14 11:30:18 +00002871 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002872 pInode->nLock++;
2873 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002874 }
drh8af6c222010-05-14 12:43:01 +00002875 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002876 /* We are trying for an exclusive lock but another thread in this
2877 ** same process is still holding a shared lock. */
2878 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002879 }else{
2880 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2881 ** assumed that there is a SHARED or greater lock on the file
2882 ** already.
2883 */
2884 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002885 assert( 0!=pFile->eFileLock );
2886 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002887 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002888 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002889 if( !failed ){
2890 context->reserved = 1;
2891 }
drhbfe66312006-10-03 17:40:40 +00002892 }
drh308c2a52010-05-14 11:30:18 +00002893 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002894 /* Acquire an EXCLUSIVE lock */
2895
2896 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002897 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002898 */
drh6b9d6dd2008-12-03 19:34:47 +00002899 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002900 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002901 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002902 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002903 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002904 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002905 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002906 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002907 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2908 ** a critical I/O error
2909 */
2910 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2911 SQLITE_IOERR_LOCK;
2912 goto afp_end_lock;
2913 }
2914 }else{
aswift5b1a2562008-08-22 00:22:35 +00002915 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002916 }
2917 }
aswift5b1a2562008-08-22 00:22:35 +00002918 if( failed ){
2919 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002920 }
2921 }
2922
2923 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002924 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002925 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002926 }else if( eFileLock==EXCLUSIVE_LOCK ){
2927 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002928 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002929 }
2930
2931afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002932 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002933 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2934 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002935 return rc;
2936}
2937
2938/*
drh308c2a52010-05-14 11:30:18 +00002939** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002940** must be either NO_LOCK or SHARED_LOCK.
2941**
2942** If the locking level of the file descriptor is already at or below
2943** the requested locking level, this routine is a no-op.
2944*/
drh308c2a52010-05-14 11:30:18 +00002945static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002946 int rc = SQLITE_OK;
2947 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002948 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002949 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2950 int skipShared = 0;
2951#ifdef SQLITE_TEST
2952 int h = pFile->h;
2953#endif
drhbfe66312006-10-03 17:40:40 +00002954
2955 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002956 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002957 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002958 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002959
drh308c2a52010-05-14 11:30:18 +00002960 assert( eFileLock<=SHARED_LOCK );
2961 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002962 return SQLITE_OK;
2963 }
drh6c7d5c52008-11-21 20:32:33 +00002964 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002965 pInode = pFile->pInode;
2966 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002967 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002968 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002969 SimulateIOErrorBenign(1);
2970 SimulateIOError( h=(-1) )
2971 SimulateIOErrorBenign(0);
2972
drhd3d8c042012-05-29 17:02:40 +00002973#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002974 /* When reducing a lock such that other processes can start
2975 ** reading the database file again, make sure that the
2976 ** transaction counter was updated if any part of the database
2977 ** file changed. If the transaction counter is not updated,
2978 ** other connections to the same file might not realize that
2979 ** the file has changed and hence might not know to flush their
2980 ** cache. The use of a stale cache can lead to database corruption.
2981 */
2982 assert( pFile->inNormalWrite==0
2983 || pFile->dbUpdate==0
2984 || pFile->transCntrChng==1 );
2985 pFile->inNormalWrite = 0;
2986#endif
aswiftaebf4132008-11-21 00:10:35 +00002987
drh308c2a52010-05-14 11:30:18 +00002988 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002989 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002990 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002991 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002992 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002993 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2994 } else {
2995 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002996 }
2997 }
drh308c2a52010-05-14 11:30:18 +00002998 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002999 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003000 }
drh308c2a52010-05-14 11:30:18 +00003001 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003002 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3003 if( !rc ){
3004 context->reserved = 0;
3005 }
aswiftaebf4132008-11-21 00:10:35 +00003006 }
drh8af6c222010-05-14 12:43:01 +00003007 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3008 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003009 }
aswiftaebf4132008-11-21 00:10:35 +00003010 }
drh308c2a52010-05-14 11:30:18 +00003011 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003012
drh7ed97b92010-01-20 13:07:21 +00003013 /* Decrement the shared lock counter. Release the lock using an
3014 ** OS call only when all threads in this same process have released
3015 ** the lock.
3016 */
drh8af6c222010-05-14 12:43:01 +00003017 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3018 pInode->nShared--;
3019 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003020 SimulateIOErrorBenign(1);
3021 SimulateIOError( h=(-1) )
3022 SimulateIOErrorBenign(0);
3023 if( !skipShared ){
3024 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3025 }
3026 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003027 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003028 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003029 }
3030 }
3031 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003032 pInode->nLock--;
3033 assert( pInode->nLock>=0 );
3034 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003035 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003036 }
3037 }
drhbfe66312006-10-03 17:40:40 +00003038 }
drh7ed97b92010-01-20 13:07:21 +00003039
drh6c7d5c52008-11-21 20:32:33 +00003040 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003041 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003042 return rc;
3043}
3044
3045/*
drh339eb0b2008-03-07 15:34:11 +00003046** Close a file & cleanup AFP specific locking context
3047*/
danielk1977e339d652008-06-28 11:23:00 +00003048static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003049 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003050 if( id ){
3051 unixFile *pFile = (unixFile*)id;
3052 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003053 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003054 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003055 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003056 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003057 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003058 ** the last lock is cleared.
3059 */
dan08da86a2009-08-21 17:18:03 +00003060 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003061 }
danb0ac3e32010-06-16 10:55:42 +00003062 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003063 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003064 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003065 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003066 }
drh7ed97b92010-01-20 13:07:21 +00003067 return rc;
drhbfe66312006-10-03 17:40:40 +00003068}
3069
drhd2cb50b2009-01-09 21:41:17 +00003070#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003071/*
3072** The code above is the AFP lock implementation. The code is specific
3073** to MacOSX and does not work on other unix platforms. No alternative
3074** is available. If you don't compile for a mac, then the "unix-afp"
3075** VFS is not available.
3076**
3077********************* End of the AFP lock implementation **********************
3078******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003079
drh7ed97b92010-01-20 13:07:21 +00003080/******************************************************************************
3081*************************** Begin NFS Locking ********************************/
3082
3083#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3084/*
drh308c2a52010-05-14 11:30:18 +00003085 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003086 ** must be either NO_LOCK or SHARED_LOCK.
3087 **
3088 ** If the locking level of the file descriptor is already at or below
3089 ** the requested locking level, this routine is a no-op.
3090 */
drh308c2a52010-05-14 11:30:18 +00003091static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003092 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003093}
3094
3095#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3096/*
3097** The code above is the NFS lock implementation. The code is specific
3098** to MacOSX and does not work on other unix platforms. No alternative
3099** is available.
3100**
3101********************* End of the NFS lock implementation **********************
3102******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003103
3104/******************************************************************************
3105**************** Non-locking sqlite3_file methods *****************************
3106**
3107** The next division contains implementations for all methods of the
3108** sqlite3_file object other than the locking methods. The locking
3109** methods were defined in divisions above (one locking method per
3110** division). Those methods that are common to all locking modes
3111** are gather together into this division.
3112*/
drhbfe66312006-10-03 17:40:40 +00003113
3114/*
drh734c9862008-11-28 15:37:20 +00003115** Seek to the offset passed as the second argument, then read cnt
3116** bytes into pBuf. Return the number of bytes actually read.
3117**
3118** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3119** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3120** one system to another. Since SQLite does not define USE_PREAD
3121** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3122** See tickets #2741 and #2681.
3123**
3124** To avoid stomping the errno value on a failed read the lastErrno value
3125** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003126*/
drh734c9862008-11-28 15:37:20 +00003127static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3128 int got;
drh58024642011-11-07 18:16:00 +00003129 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003130#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003131 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003132#endif
drh734c9862008-11-28 15:37:20 +00003133 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003134 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003135 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003136 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003137 do{
drh734c9862008-11-28 15:37:20 +00003138#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003139 got = osPread(id->h, pBuf, cnt, offset);
3140 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003141#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003142 got = osPread64(id->h, pBuf, cnt, offset);
3143 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003144#else
drh58024642011-11-07 18:16:00 +00003145 newOffset = lseek(id->h, offset, SEEK_SET);
3146 SimulateIOError( newOffset-- );
3147 if( newOffset!=offset ){
3148 if( newOffset == -1 ){
3149 ((unixFile*)id)->lastErrno = errno;
3150 }else{
drhf2f105d2012-08-20 15:53:54 +00003151 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003152 }
3153 return -1;
drh734c9862008-11-28 15:37:20 +00003154 }
drh58024642011-11-07 18:16:00 +00003155 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003156#endif
drh58024642011-11-07 18:16:00 +00003157 if( got==cnt ) break;
3158 if( got<0 ){
3159 if( errno==EINTR ){ got = 1; continue; }
3160 prior = 0;
3161 ((unixFile*)id)->lastErrno = errno;
3162 break;
3163 }else if( got>0 ){
3164 cnt -= got;
3165 offset += got;
3166 prior += got;
3167 pBuf = (void*)(got + (char*)pBuf);
3168 }
3169 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003170 TIMER_END;
drh58024642011-11-07 18:16:00 +00003171 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3172 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3173 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003174}
3175
3176/*
drh734c9862008-11-28 15:37:20 +00003177** Read data from a file into a buffer. Return SQLITE_OK if all
3178** bytes were read successfully and SQLITE_IOERR if anything goes
3179** wrong.
drh339eb0b2008-03-07 15:34:11 +00003180*/
drh734c9862008-11-28 15:37:20 +00003181static int unixRead(
3182 sqlite3_file *id,
3183 void *pBuf,
3184 int amt,
3185 sqlite3_int64 offset
3186){
dan08da86a2009-08-21 17:18:03 +00003187 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003188 int got;
3189 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003190 assert( offset>=0 );
3191 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003192
dan08da86a2009-08-21 17:18:03 +00003193 /* If this is a database file (not a journal, master-journal or temp
3194 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003195#if 0
dane946c392009-08-22 11:39:46 +00003196 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003197 || offset>=PENDING_BYTE+512
3198 || offset+amt<=PENDING_BYTE
3199 );
dan7c246102010-04-12 19:00:29 +00003200#endif
drh08c6d442009-02-09 17:34:07 +00003201
drh9b4c59f2013-04-15 17:03:42 +00003202#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003203 /* Deal with as much of this read request as possible by transfering
3204 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003205 if( offset<pFile->mmapSize ){
3206 if( offset+amt <= pFile->mmapSize ){
3207 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3208 return SQLITE_OK;
3209 }else{
3210 int nCopy = pFile->mmapSize - offset;
3211 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3212 pBuf = &((u8 *)pBuf)[nCopy];
3213 amt -= nCopy;
3214 offset += nCopy;
3215 }
3216 }
drh6e0b6d52013-04-09 16:19:20 +00003217#endif
danf23da962013-03-23 21:00:41 +00003218
dan08da86a2009-08-21 17:18:03 +00003219 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003220 if( got==amt ){
3221 return SQLITE_OK;
3222 }else if( got<0 ){
3223 /* lastErrno set by seekAndRead */
3224 return SQLITE_IOERR_READ;
3225 }else{
dan08da86a2009-08-21 17:18:03 +00003226 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003227 /* Unread parts of the buffer must be zero-filled */
3228 memset(&((char*)pBuf)[got], 0, amt-got);
3229 return SQLITE_IOERR_SHORT_READ;
3230 }
3231}
3232
3233/*
dan47a2b4a2013-04-26 16:09:29 +00003234** Attempt to seek the file-descriptor passed as the first argument to
3235** absolute offset iOff, then attempt to write nBuf bytes of data from
3236** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3237** return the actual number of bytes written (which may be less than
3238** nBuf).
3239*/
3240static int seekAndWriteFd(
3241 int fd, /* File descriptor to write to */
3242 i64 iOff, /* File offset to begin writing at */
3243 const void *pBuf, /* Copy data from this buffer to the file */
3244 int nBuf, /* Size of buffer pBuf in bytes */
3245 int *piErrno /* OUT: Error number if error occurs */
3246){
3247 int rc = 0; /* Value returned by system call */
3248
3249 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003250 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003251 nBuf &= 0x1ffff;
3252 TIMER_START;
3253
3254#if defined(USE_PREAD)
3255 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3256#elif defined(USE_PREAD64)
3257 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3258#else
3259 do{
3260 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3261 SimulateIOError( iSeek-- );
3262
3263 if( iSeek!=iOff ){
3264 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3265 return -1;
3266 }
3267 rc = osWrite(fd, pBuf, nBuf);
3268 }while( rc<0 && errno==EINTR );
3269#endif
3270
3271 TIMER_END;
3272 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3273
3274 if( rc<0 && piErrno ) *piErrno = errno;
3275 return rc;
3276}
3277
3278
3279/*
drh734c9862008-11-28 15:37:20 +00003280** Seek to the offset in id->offset then read cnt bytes into pBuf.
3281** Return the number of bytes actually read. Update the offset.
3282**
3283** To avoid stomping the errno value on a failed write the lastErrno value
3284** is set before returning.
3285*/
3286static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003287 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003288}
3289
3290
3291/*
3292** Write data from a buffer into a file. Return SQLITE_OK on success
3293** or some other error code on failure.
3294*/
3295static int unixWrite(
3296 sqlite3_file *id,
3297 const void *pBuf,
3298 int amt,
3299 sqlite3_int64 offset
3300){
dan08da86a2009-08-21 17:18:03 +00003301 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003302 int wrote = 0;
3303 assert( id );
3304 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003305
dan08da86a2009-08-21 17:18:03 +00003306 /* If this is a database file (not a journal, master-journal or temp
3307 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003308#if 0
dane946c392009-08-22 11:39:46 +00003309 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003310 || offset>=PENDING_BYTE+512
3311 || offset+amt<=PENDING_BYTE
3312 );
dan7c246102010-04-12 19:00:29 +00003313#endif
drh08c6d442009-02-09 17:34:07 +00003314
drhd3d8c042012-05-29 17:02:40 +00003315#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003316 /* If we are doing a normal write to a database file (as opposed to
3317 ** doing a hot-journal rollback or a write to some file other than a
3318 ** normal database file) then record the fact that the database
3319 ** has changed. If the transaction counter is modified, record that
3320 ** fact too.
3321 */
dan08da86a2009-08-21 17:18:03 +00003322 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003323 pFile->dbUpdate = 1; /* The database has been modified */
3324 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003325 int rc;
drh8f941bc2009-01-14 23:03:40 +00003326 char oldCntr[4];
3327 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003328 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003329 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003330 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003331 pFile->transCntrChng = 1; /* The transaction counter has changed */
3332 }
3333 }
3334 }
3335#endif
3336
drh9b4c59f2013-04-15 17:03:42 +00003337#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003338 /* Deal with as much of this write request as possible by transfering
3339 ** data from the memory mapping using memcpy(). */
3340 if( offset<pFile->mmapSize ){
3341 if( offset+amt <= pFile->mmapSize ){
3342 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3343 return SQLITE_OK;
3344 }else{
3345 int nCopy = pFile->mmapSize - offset;
3346 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3347 pBuf = &((u8 *)pBuf)[nCopy];
3348 amt -= nCopy;
3349 offset += nCopy;
3350 }
3351 }
drh6e0b6d52013-04-09 16:19:20 +00003352#endif
danf23da962013-03-23 21:00:41 +00003353
dan08da86a2009-08-21 17:18:03 +00003354 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003355 amt -= wrote;
3356 offset += wrote;
3357 pBuf = &((char*)pBuf)[wrote];
3358 }
3359 SimulateIOError(( wrote=(-1), amt=1 ));
3360 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003361
drh734c9862008-11-28 15:37:20 +00003362 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003363 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003364 /* lastErrno set by seekAndWrite */
3365 return SQLITE_IOERR_WRITE;
3366 }else{
dan08da86a2009-08-21 17:18:03 +00003367 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003368 return SQLITE_FULL;
3369 }
3370 }
dan6e09d692010-07-27 18:34:15 +00003371
drh734c9862008-11-28 15:37:20 +00003372 return SQLITE_OK;
3373}
3374
3375#ifdef SQLITE_TEST
3376/*
3377** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003378** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003379*/
3380int sqlite3_sync_count = 0;
3381int sqlite3_fullsync_count = 0;
3382#endif
3383
3384/*
drh89240432009-03-25 01:06:01 +00003385** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003386** Others do no. To be safe, we will stick with the (slightly slower)
3387** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003388** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003389*/
drh20f8e132011-08-31 21:01:55 +00003390#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003391# define fdatasync fsync
3392#endif
3393
3394/*
3395** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3396** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3397** only available on Mac OS X. But that could change.
3398*/
3399#ifdef F_FULLFSYNC
3400# define HAVE_FULLFSYNC 1
3401#else
3402# define HAVE_FULLFSYNC 0
3403#endif
3404
3405
3406/*
3407** The fsync() system call does not work as advertised on many
3408** unix systems. The following procedure is an attempt to make
3409** it work better.
3410**
3411** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3412** for testing when we want to run through the test suite quickly.
3413** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3414** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3415** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003416**
3417** SQLite sets the dataOnly flag if the size of the file is unchanged.
3418** The idea behind dataOnly is that it should only write the file content
3419** to disk, not the inode. We only set dataOnly if the file size is
3420** unchanged since the file size is part of the inode. However,
3421** Ted Ts'o tells us that fdatasync() will also write the inode if the
3422** file size has changed. The only real difference between fdatasync()
3423** and fsync(), Ted tells us, is that fdatasync() will not flush the
3424** inode if the mtime or owner or other inode attributes have changed.
3425** We only care about the file size, not the other file attributes, so
3426** as far as SQLite is concerned, an fdatasync() is always adequate.
3427** So, we always use fdatasync() if it is available, regardless of
3428** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003429*/
3430static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003431 int rc;
drh734c9862008-11-28 15:37:20 +00003432
3433 /* The following "ifdef/elif/else/" block has the same structure as
3434 ** the one below. It is replicated here solely to avoid cluttering
3435 ** up the real code with the UNUSED_PARAMETER() macros.
3436 */
3437#ifdef SQLITE_NO_SYNC
3438 UNUSED_PARAMETER(fd);
3439 UNUSED_PARAMETER(fullSync);
3440 UNUSED_PARAMETER(dataOnly);
3441#elif HAVE_FULLFSYNC
3442 UNUSED_PARAMETER(dataOnly);
3443#else
3444 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003445 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003446#endif
3447
3448 /* Record the number of times that we do a normal fsync() and
3449 ** FULLSYNC. This is used during testing to verify that this procedure
3450 ** gets called with the correct arguments.
3451 */
3452#ifdef SQLITE_TEST
3453 if( fullSync ) sqlite3_fullsync_count++;
3454 sqlite3_sync_count++;
3455#endif
3456
3457 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3458 ** no-op
3459 */
3460#ifdef SQLITE_NO_SYNC
3461 rc = SQLITE_OK;
3462#elif HAVE_FULLFSYNC
3463 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003464 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003465 }else{
3466 rc = 1;
3467 }
3468 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003469 ** It shouldn't be possible for fullfsync to fail on the local
3470 ** file system (on OSX), so failure indicates that FULLFSYNC
3471 ** isn't supported for this file system. So, attempt an fsync
3472 ** and (for now) ignore the overhead of a superfluous fcntl call.
3473 ** It'd be better to detect fullfsync support once and avoid
3474 ** the fcntl call every time sync is called.
3475 */
drh734c9862008-11-28 15:37:20 +00003476 if( rc ) rc = fsync(fd);
3477
drh7ed97b92010-01-20 13:07:21 +00003478#elif defined(__APPLE__)
3479 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3480 ** so currently we default to the macro that redefines fdatasync to fsync
3481 */
3482 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003483#else
drh0b647ff2009-03-21 14:41:04 +00003484 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003485#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003486 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003487 rc = fsync(fd);
3488 }
drh0b647ff2009-03-21 14:41:04 +00003489#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003490#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3491
3492 if( OS_VXWORKS && rc!= -1 ){
3493 rc = 0;
3494 }
chw97185482008-11-17 08:05:31 +00003495 return rc;
drhbfe66312006-10-03 17:40:40 +00003496}
3497
drh734c9862008-11-28 15:37:20 +00003498/*
drh0059eae2011-08-08 23:48:40 +00003499** Open a file descriptor to the directory containing file zFilename.
3500** If successful, *pFd is set to the opened file descriptor and
3501** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3502** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3503** value.
3504**
drh90315a22011-08-10 01:52:12 +00003505** The directory file descriptor is used for only one thing - to
3506** fsync() a directory to make sure file creation and deletion events
3507** are flushed to disk. Such fsyncs are not needed on newer
3508** journaling filesystems, but are required on older filesystems.
3509**
3510** This routine can be overridden using the xSetSysCall interface.
3511** The ability to override this routine was added in support of the
3512** chromium sandbox. Opening a directory is a security risk (we are
3513** told) so making it overrideable allows the chromium sandbox to
3514** replace this routine with a harmless no-op. To make this routine
3515** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3516** *pFd set to a negative number.
3517**
drh0059eae2011-08-08 23:48:40 +00003518** If SQLITE_OK is returned, the caller is responsible for closing
3519** the file descriptor *pFd using close().
3520*/
3521static int openDirectory(const char *zFilename, int *pFd){
3522 int ii;
3523 int fd = -1;
3524 char zDirname[MAX_PATHNAME+1];
3525
3526 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3527 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3528 if( ii>0 ){
3529 zDirname[ii] = '\0';
3530 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3531 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003532 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3533 }
3534 }
3535 *pFd = fd;
3536 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3537}
3538
3539/*
drh734c9862008-11-28 15:37:20 +00003540** Make sure all writes to a particular file are committed to disk.
3541**
3542** If dataOnly==0 then both the file itself and its metadata (file
3543** size, access time, etc) are synced. If dataOnly!=0 then only the
3544** file data is synced.
3545**
3546** Under Unix, also make sure that the directory entry for the file
3547** has been created by fsync-ing the directory that contains the file.
3548** If we do not do this and we encounter a power failure, the directory
3549** entry for the journal might not exist after we reboot. The next
3550** SQLite to access the file will not know that the journal exists (because
3551** the directory entry for the journal was never created) and the transaction
3552** will not roll back - possibly leading to database corruption.
3553*/
3554static int unixSync(sqlite3_file *id, int flags){
3555 int rc;
3556 unixFile *pFile = (unixFile*)id;
3557
3558 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3559 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3560
3561 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3562 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3563 || (flags&0x0F)==SQLITE_SYNC_FULL
3564 );
3565
3566 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3567 ** line is to test that doing so does not cause any problems.
3568 */
3569 SimulateDiskfullError( return SQLITE_FULL );
3570
3571 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003572 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003573 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3574 SimulateIOError( rc=1 );
3575 if( rc ){
3576 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003577 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003578 }
drh0059eae2011-08-08 23:48:40 +00003579
3580 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003581 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003582 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003583 */
3584 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3585 int dirfd;
3586 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003587 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003588 rc = osOpenDirectory(pFile->zPath, &dirfd);
3589 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003590 full_fsync(dirfd, 0, 0);
3591 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003592 }else if( rc==SQLITE_CANTOPEN ){
3593 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003594 }
drh0059eae2011-08-08 23:48:40 +00003595 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003596 }
3597 return rc;
3598}
3599
3600/*
3601** Truncate an open file to a specified size
3602*/
3603static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003604 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003605 int rc;
dan6e09d692010-07-27 18:34:15 +00003606 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003607 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003608
3609 /* If the user has configured a chunk-size for this file, truncate the
3610 ** file so that it consists of an integer number of chunks (i.e. the
3611 ** actual file size after the operation may be larger than the requested
3612 ** size).
3613 */
drhb8af4b72012-04-05 20:04:39 +00003614 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003615 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3616 }
3617
drhff812312011-02-23 13:33:46 +00003618 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003619 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003620 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003621 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003622 }else{
drhd3d8c042012-05-29 17:02:40 +00003623#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003624 /* If we are doing a normal write to a database file (as opposed to
3625 ** doing a hot-journal rollback or a write to some file other than a
3626 ** normal database file) and we truncate the file to zero length,
3627 ** that effectively updates the change counter. This might happen
3628 ** when restoring a database using the backup API from a zero-length
3629 ** source.
3630 */
dan6e09d692010-07-27 18:34:15 +00003631 if( pFile->inNormalWrite && nByte==0 ){
3632 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003633 }
danf23da962013-03-23 21:00:41 +00003634#endif
danc0003312013-03-22 17:46:11 +00003635
mistachkine98844f2013-08-24 00:59:24 +00003636#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003637 /* If the file was just truncated to a size smaller than the currently
3638 ** mapped region, reduce the effective mapping size as well. SQLite will
3639 ** use read() and write() to access data beyond this point from now on.
3640 */
3641 if( nByte<pFile->mmapSize ){
3642 pFile->mmapSize = nByte;
3643 }
mistachkine98844f2013-08-24 00:59:24 +00003644#endif
drh3313b142009-11-06 04:13:18 +00003645
drh734c9862008-11-28 15:37:20 +00003646 return SQLITE_OK;
3647 }
3648}
3649
3650/*
3651** Determine the current size of a file in bytes
3652*/
3653static int unixFileSize(sqlite3_file *id, i64 *pSize){
3654 int rc;
3655 struct stat buf;
3656 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003657 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003658 SimulateIOError( rc=1 );
3659 if( rc!=0 ){
3660 ((unixFile*)id)->lastErrno = errno;
3661 return SQLITE_IOERR_FSTAT;
3662 }
3663 *pSize = buf.st_size;
3664
drh8af6c222010-05-14 12:43:01 +00003665 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003666 ** writes a single byte into that file in order to work around a bug
3667 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3668 ** layers, we need to report this file size as zero even though it is
3669 ** really 1. Ticket #3260.
3670 */
3671 if( *pSize==1 ) *pSize = 0;
3672
3673
3674 return SQLITE_OK;
3675}
3676
drhd2cb50b2009-01-09 21:41:17 +00003677#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003678/*
3679** Handler for proxy-locking file-control verbs. Defined below in the
3680** proxying locking division.
3681*/
3682static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003683#endif
drh715ff302008-12-03 22:32:44 +00003684
dan502019c2010-07-28 14:26:17 +00003685/*
3686** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003687** file-control operation. Enlarge the database to nBytes in size
3688** (rounded up to the next chunk-size). If the database is already
3689** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003690*/
3691static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003692 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003693 i64 nSize; /* Required file size */
3694 struct stat buf; /* Used to hold return values of fstat() */
3695
drh99ab3b12011-03-02 15:09:07 +00003696 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003697
3698 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3699 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003700
dan502019c2010-07-28 14:26:17 +00003701#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003702 /* The code below is handling the return value of osFallocate()
3703 ** correctly. posix_fallocate() is defined to "returns zero on success,
3704 ** or an error number on failure". See the manpage for details. */
3705 int err;
drhff812312011-02-23 13:33:46 +00003706 do{
dan661d71a2011-03-30 19:08:03 +00003707 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3708 }while( err==EINTR );
3709 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003710#else
3711 /* If the OS does not have posix_fallocate(), fake it. First use
3712 ** ftruncate() to set the file size, then write a single byte to
3713 ** the last byte in each block within the extended region. This
3714 ** is the same technique used by glibc to implement posix_fallocate()
3715 ** on systems that do not have a real fallocate() system call.
3716 */
3717 int nBlk = buf.st_blksize; /* File-system block size */
3718 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003719
drhff812312011-02-23 13:33:46 +00003720 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003721 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003722 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003723 }
3724 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003725 while( iWrite<nSize ){
3726 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3727 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003728 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003729 }
dan502019c2010-07-28 14:26:17 +00003730#endif
3731 }
3732 }
3733
mistachkine98844f2013-08-24 00:59:24 +00003734#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003735 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003736 int rc;
3737 if( pFile->szChunk<=0 ){
3738 if( robust_ftruncate(pFile->h, nByte) ){
3739 pFile->lastErrno = errno;
3740 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3741 }
3742 }
3743
3744 rc = unixMapfile(pFile, nByte);
3745 return rc;
3746 }
mistachkine98844f2013-08-24 00:59:24 +00003747#endif
danf23da962013-03-23 21:00:41 +00003748
dan502019c2010-07-28 14:26:17 +00003749 return SQLITE_OK;
3750}
danielk1977ad94b582007-08-20 06:44:22 +00003751
danielk1977e3026632004-06-22 11:29:02 +00003752/*
drhf12b3f62011-12-21 14:42:29 +00003753** If *pArg is inititially negative then this is a query. Set *pArg to
3754** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3755**
3756** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3757*/
3758static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3759 if( *pArg<0 ){
3760 *pArg = (pFile->ctrlFlags & mask)!=0;
3761 }else if( (*pArg)==0 ){
3762 pFile->ctrlFlags &= ~mask;
3763 }else{
3764 pFile->ctrlFlags |= mask;
3765 }
3766}
3767
drh696b33e2012-12-06 19:01:42 +00003768/* Forward declaration */
3769static int unixGetTempname(int nBuf, char *zBuf);
3770
drhf12b3f62011-12-21 14:42:29 +00003771/*
drh9e33c2c2007-08-31 18:34:59 +00003772** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003773*/
drhcc6bb3e2007-08-31 16:11:35 +00003774static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003775 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003776 switch( op ){
3777 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003778 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003779 return SQLITE_OK;
3780 }
drh7708e972008-11-29 00:56:52 +00003781 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003782 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003783 return SQLITE_OK;
3784 }
dan6e09d692010-07-27 18:34:15 +00003785 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003786 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003787 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003788 }
drh9ff27ec2010-05-19 19:26:05 +00003789 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003790 int rc;
3791 SimulateIOErrorBenign(1);
3792 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3793 SimulateIOErrorBenign(0);
3794 return rc;
drhf0b190d2011-07-26 16:03:07 +00003795 }
3796 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003797 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3798 return SQLITE_OK;
3799 }
drhcb15f352011-12-23 01:04:17 +00003800 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3801 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003802 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003803 }
drhde60fc22011-12-14 17:53:36 +00003804 case SQLITE_FCNTL_VFSNAME: {
3805 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3806 return SQLITE_OK;
3807 }
drh696b33e2012-12-06 19:01:42 +00003808 case SQLITE_FCNTL_TEMPFILENAME: {
3809 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3810 if( zTFile ){
3811 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3812 *(char**)pArg = zTFile;
3813 }
3814 return SQLITE_OK;
3815 }
drhb959a012013-12-07 12:29:22 +00003816 case SQLITE_FCNTL_HAS_MOVED: {
3817 *(int*)pArg = fileHasMoved(pFile);
3818 return SQLITE_OK;
3819 }
mistachkine98844f2013-08-24 00:59:24 +00003820#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003821 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003822 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003823 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003824 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3825 newLimit = sqlite3GlobalConfig.mxMmap;
3826 }
3827 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003828 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003829 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003830 if( pFile->mmapSize>0 ){
3831 unixUnmapfile(pFile);
3832 rc = unixMapfile(pFile, -1);
3833 }
danbcb8a862013-04-08 15:30:41 +00003834 }
drh34e258c2013-05-23 01:40:53 +00003835 return rc;
danb2d3de32013-03-14 18:34:37 +00003836 }
mistachkine98844f2013-08-24 00:59:24 +00003837#endif
drhd3d8c042012-05-29 17:02:40 +00003838#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003839 /* The pager calls this method to signal that it has done
3840 ** a rollback and that the database is therefore unchanged and
3841 ** it hence it is OK for the transaction change counter to be
3842 ** unchanged.
3843 */
3844 case SQLITE_FCNTL_DB_UNCHANGED: {
3845 ((unixFile*)id)->dbUpdate = 0;
3846 return SQLITE_OK;
3847 }
3848#endif
drhd2cb50b2009-01-09 21:41:17 +00003849#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003850 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003851 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003852 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003853 }
drhd2cb50b2009-01-09 21:41:17 +00003854#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003855 }
drh0b52b7d2011-01-26 19:46:22 +00003856 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003857}
3858
3859/*
danielk1977a3d4c882007-03-23 10:08:38 +00003860** Return the sector size in bytes of the underlying block device for
3861** the specified file. This is almost always 512 bytes, but may be
3862** larger for some devices.
3863**
3864** SQLite code assumes this function cannot fail. It also assumes that
3865** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003866** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003867** same for both.
3868*/
drh537dddf2012-10-26 13:46:24 +00003869#ifndef __QNXNTO__
3870static int unixSectorSize(sqlite3_file *NotUsed){
3871 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003872 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003873}
drh537dddf2012-10-26 13:46:24 +00003874#endif
3875
3876/*
3877** The following version of unixSectorSize() is optimized for QNX.
3878*/
3879#ifdef __QNXNTO__
3880#include <sys/dcmd_blk.h>
3881#include <sys/statvfs.h>
3882static int unixSectorSize(sqlite3_file *id){
3883 unixFile *pFile = (unixFile*)id;
3884 if( pFile->sectorSize == 0 ){
3885 struct statvfs fsInfo;
3886
3887 /* Set defaults for non-supported filesystems */
3888 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3889 pFile->deviceCharacteristics = 0;
3890 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3891 return pFile->sectorSize;
3892 }
3893
3894 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3895 pFile->sectorSize = fsInfo.f_bsize;
3896 pFile->deviceCharacteristics =
3897 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3898 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3899 ** the write succeeds */
3900 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3901 ** so it is ordered */
3902 0;
3903 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3904 pFile->sectorSize = fsInfo.f_bsize;
3905 pFile->deviceCharacteristics =
3906 /* etfs cluster size writes are atomic */
3907 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3908 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3909 ** the write succeeds */
3910 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3911 ** so it is ordered */
3912 0;
3913 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3914 pFile->sectorSize = fsInfo.f_bsize;
3915 pFile->deviceCharacteristics =
3916 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3917 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3918 ** the write succeeds */
3919 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3920 ** so it is ordered */
3921 0;
3922 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3923 pFile->sectorSize = fsInfo.f_bsize;
3924 pFile->deviceCharacteristics =
3925 /* full bitset of atomics from max sector size and smaller */
3926 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3927 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3928 ** so it is ordered */
3929 0;
3930 }else if( strstr(fsInfo.f_basetype, "dos") ){
3931 pFile->sectorSize = fsInfo.f_bsize;
3932 pFile->deviceCharacteristics =
3933 /* full bitset of atomics from max sector size and smaller */
3934 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3935 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3936 ** so it is ordered */
3937 0;
3938 }else{
3939 pFile->deviceCharacteristics =
3940 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3941 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3942 ** the write succeeds */
3943 0;
3944 }
3945 }
3946 /* Last chance verification. If the sector size isn't a multiple of 512
3947 ** then it isn't valid.*/
3948 if( pFile->sectorSize % 512 != 0 ){
3949 pFile->deviceCharacteristics = 0;
3950 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3951 }
3952 return pFile->sectorSize;
3953}
3954#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003955
danielk197790949c22007-08-17 16:50:38 +00003956/*
drhf12b3f62011-12-21 14:42:29 +00003957** Return the device characteristics for the file.
3958**
drhcb15f352011-12-23 01:04:17 +00003959** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3960** However, that choice is contraversial since technically the underlying
3961** file system does not always provide powersafe overwrites. (In other
3962** words, after a power-loss event, parts of the file that were never
3963** written might end up being altered.) However, non-PSOW behavior is very,
3964** very rare. And asserting PSOW makes a large reduction in the amount
3965** of required I/O for journaling, since a lot of padding is eliminated.
3966** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3967** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003968*/
drhf12b3f62011-12-21 14:42:29 +00003969static int unixDeviceCharacteristics(sqlite3_file *id){
3970 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003971 int rc = 0;
3972#ifdef __QNXNTO__
3973 if( p->sectorSize==0 ) unixSectorSize(id);
3974 rc = p->deviceCharacteristics;
3975#endif
drhcb15f352011-12-23 01:04:17 +00003976 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003977 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003978 }
drh537dddf2012-10-26 13:46:24 +00003979 return rc;
danielk197762079062007-08-15 17:08:46 +00003980}
3981
drhd9e5c4f2010-05-12 18:01:39 +00003982#ifndef SQLITE_OMIT_WAL
3983
3984
3985/*
drhd91c68f2010-05-14 14:52:25 +00003986** Object used to represent an shared memory buffer.
3987**
3988** When multiple threads all reference the same wal-index, each thread
3989** has its own unixShm object, but they all point to a single instance
3990** of this unixShmNode object. In other words, each wal-index is opened
3991** only once per process.
3992**
3993** Each unixShmNode object is connected to a single unixInodeInfo object.
3994** We could coalesce this object into unixInodeInfo, but that would mean
3995** every open file that does not use shared memory (in other words, most
3996** open files) would have to carry around this extra information. So
3997** the unixInodeInfo object contains a pointer to this unixShmNode object
3998** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003999**
4000** unixMutexHeld() must be true when creating or destroying
4001** this object or while reading or writing the following fields:
4002**
4003** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004004**
4005** The following fields are read-only after the object is created:
4006**
4007** fid
4008** zFilename
4009**
drhd91c68f2010-05-14 14:52:25 +00004010** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004011** unixMutexHeld() is true when reading or writing any other field
4012** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004013*/
drhd91c68f2010-05-14 14:52:25 +00004014struct unixShmNode {
4015 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004016 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004017 char *zFilename; /* Name of the mmapped file */
4018 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004019 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004020 u16 nRegion; /* Size of array apRegion */
4021 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004022 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004023 int nRef; /* Number of unixShm objects pointing to this */
4024 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004025#ifdef SQLITE_DEBUG
4026 u8 exclMask; /* Mask of exclusive locks held */
4027 u8 sharedMask; /* Mask of shared locks held */
4028 u8 nextShmId; /* Next available unixShm.id value */
4029#endif
4030};
4031
4032/*
drhd9e5c4f2010-05-12 18:01:39 +00004033** Structure used internally by this VFS to record the state of an
4034** open shared memory connection.
4035**
drhd91c68f2010-05-14 14:52:25 +00004036** The following fields are initialized when this object is created and
4037** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004038**
drhd91c68f2010-05-14 14:52:25 +00004039** unixShm.pFile
4040** unixShm.id
4041**
4042** All other fields are read/write. The unixShm.pFile->mutex must be held
4043** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004044*/
4045struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004046 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4047 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004048 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004049 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004050 u16 sharedMask; /* Mask of shared locks held */
4051 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004052};
4053
4054/*
drhd9e5c4f2010-05-12 18:01:39 +00004055** Constants used for locking
4056*/
drhbd9676c2010-06-23 17:58:38 +00004057#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004058#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004059
drhd9e5c4f2010-05-12 18:01:39 +00004060/*
drh73b64e42010-05-30 19:55:15 +00004061** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004062**
4063** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4064** otherwise.
4065*/
4066static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004067 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4068 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004069 int ofst, /* First byte of the locking range */
4070 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004071){
4072 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004073 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004074
drhd91c68f2010-05-14 14:52:25 +00004075 /* Access to the unixShmNode object is serialized by the caller */
4076 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004077
drh73b64e42010-05-30 19:55:15 +00004078 /* Shared locks never span more than one byte */
4079 assert( n==1 || lockType!=F_RDLCK );
4080
4081 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004082 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004083
drh3cb93392011-03-12 18:10:44 +00004084 if( pShmNode->h>=0 ){
4085 /* Initialize the locking parameters */
4086 memset(&f, 0, sizeof(f));
4087 f.l_type = lockType;
4088 f.l_whence = SEEK_SET;
4089 f.l_start = ofst;
4090 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004091
drh3cb93392011-03-12 18:10:44 +00004092 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4093 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4094 }
drhd9e5c4f2010-05-12 18:01:39 +00004095
4096 /* Update the global lock state and do debug tracing */
4097#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004098 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004099 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004100 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004101 if( rc==SQLITE_OK ){
4102 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004103 OSTRACE(("unlock %d ok", ofst));
4104 pShmNode->exclMask &= ~mask;
4105 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004106 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004107 OSTRACE(("read-lock %d ok", ofst));
4108 pShmNode->exclMask &= ~mask;
4109 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004110 }else{
4111 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004112 OSTRACE(("write-lock %d ok", ofst));
4113 pShmNode->exclMask |= mask;
4114 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004115 }
4116 }else{
4117 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004118 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004119 }else if( lockType==F_RDLCK ){
4120 OSTRACE(("read-lock failed"));
4121 }else{
4122 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004123 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004124 }
4125 }
drh20e1f082010-05-31 16:10:12 +00004126 OSTRACE((" - afterwards %03x,%03x\n",
4127 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004128 }
drhd9e5c4f2010-05-12 18:01:39 +00004129#endif
4130
4131 return rc;
4132}
4133
drhd9e5c4f2010-05-12 18:01:39 +00004134
4135/*
drhd91c68f2010-05-14 14:52:25 +00004136** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004137**
4138** This is not a VFS shared-memory method; it is a utility function called
4139** by VFS shared-memory methods.
4140*/
drhd91c68f2010-05-14 14:52:25 +00004141static void unixShmPurge(unixFile *pFd){
4142 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004143 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004144 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00004145 int i;
drhd91c68f2010-05-14 14:52:25 +00004146 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004147 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00004148 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00004149 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004150 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004151 }else{
4152 sqlite3_free(p->apRegion[i]);
4153 }
dan13a3cb82010-06-11 19:04:21 +00004154 }
dan18801912010-06-14 14:07:50 +00004155 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004156 if( p->h>=0 ){
4157 robust_close(pFd, p->h, __LINE__);
4158 p->h = -1;
4159 }
drhd91c68f2010-05-14 14:52:25 +00004160 p->pInode->pShmNode = 0;
4161 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004162 }
4163}
4164
4165/*
danda9fe0c2010-07-13 18:44:03 +00004166** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004167** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004168**
drh7234c6d2010-06-19 15:10:09 +00004169** The file used to implement shared-memory is in the same directory
4170** as the open database file and has the same name as the open database
4171** file with the "-shm" suffix added. For example, if the database file
4172** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004173** for shared memory will be called "/home/user1/config.db-shm".
4174**
4175** Another approach to is to use files in /dev/shm or /dev/tmp or an
4176** some other tmpfs mount. But if a file in a different directory
4177** from the database file is used, then differing access permissions
4178** or a chroot() might cause two different processes on the same
4179** database to end up using different files for shared memory -
4180** meaning that their memory would not really be shared - resulting
4181** in database corruption. Nevertheless, this tmpfs file usage
4182** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4183** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4184** option results in an incompatible build of SQLite; builds of SQLite
4185** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4186** same database file at the same time, database corruption will likely
4187** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4188** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004189**
4190** When opening a new shared-memory file, if no other instances of that
4191** file are currently open, in this process or in other processes, then
4192** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004193**
4194** If the original database file (pDbFd) is using the "unix-excl" VFS
4195** that means that an exclusive lock is held on the database file and
4196** that no other processes are able to read or write the database. In
4197** that case, we do not really need shared memory. No shared memory
4198** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004199*/
danda9fe0c2010-07-13 18:44:03 +00004200static int unixOpenSharedMemory(unixFile *pDbFd){
4201 struct unixShm *p = 0; /* The connection to be opened */
4202 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4203 int rc; /* Result code */
4204 unixInodeInfo *pInode; /* The inode of fd */
4205 char *zShmFilename; /* Name of the file used for SHM */
4206 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004207
danda9fe0c2010-07-13 18:44:03 +00004208 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004209 p = sqlite3_malloc( sizeof(*p) );
4210 if( p==0 ) return SQLITE_NOMEM;
4211 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004212 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004213
danda9fe0c2010-07-13 18:44:03 +00004214 /* Check to see if a unixShmNode object already exists. Reuse an existing
4215 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004216 */
4217 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004218 pInode = pDbFd->pInode;
4219 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004220 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004221 struct stat sStat; /* fstat() info for database file */
4222
4223 /* Call fstat() to figure out the permissions on the database file. If
4224 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004225 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004226 */
drh3cb93392011-03-12 18:10:44 +00004227 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004228 rc = SQLITE_IOERR_FSTAT;
4229 goto shm_open_err;
4230 }
4231
drha4ced192010-07-15 18:32:40 +00004232#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004233 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004234#else
drh52bcde02012-01-03 14:50:45 +00004235 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004236#endif
drh7234c6d2010-06-19 15:10:09 +00004237 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004238 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004239 rc = SQLITE_NOMEM;
4240 goto shm_open_err;
4241 }
drh9cb5a0d2012-01-05 21:19:54 +00004242 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004243 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004244#ifdef SQLITE_SHM_DIRECTORY
4245 sqlite3_snprintf(nShmFilename, zShmFilename,
4246 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4247 (u32)sStat.st_ino, (u32)sStat.st_dev);
4248#else
drh7234c6d2010-06-19 15:10:09 +00004249 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004250 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004251#endif
drhd91c68f2010-05-14 14:52:25 +00004252 pShmNode->h = -1;
4253 pDbFd->pInode->pShmNode = pShmNode;
4254 pShmNode->pInode = pDbFd->pInode;
4255 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4256 if( pShmNode->mutex==0 ){
4257 rc = SQLITE_NOMEM;
4258 goto shm_open_err;
4259 }
drhd9e5c4f2010-05-12 18:01:39 +00004260
drh3cb93392011-03-12 18:10:44 +00004261 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004262 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004263 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004264 openFlags = O_RDONLY;
4265 pShmNode->isReadonly = 1;
4266 }
4267 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004268 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004269 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4270 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004271 }
drhac7c3ac2012-02-11 19:23:48 +00004272
4273 /* If this process is running as root, make sure that the SHM file
4274 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004275 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004276 */
drhed466822012-05-31 13:10:49 +00004277 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004278
4279 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004280 ** If not, truncate the file to zero length.
4281 */
4282 rc = SQLITE_OK;
4283 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4284 if( robust_ftruncate(pShmNode->h, 0) ){
4285 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004286 }
4287 }
drh66dfec8b2011-06-01 20:01:49 +00004288 if( rc==SQLITE_OK ){
4289 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4290 }
4291 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004292 }
drhd9e5c4f2010-05-12 18:01:39 +00004293 }
4294
drhd91c68f2010-05-14 14:52:25 +00004295 /* Make the new connection a child of the unixShmNode */
4296 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004297#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004298 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004299#endif
drhd91c68f2010-05-14 14:52:25 +00004300 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004301 pDbFd->pShm = p;
4302 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004303
4304 /* The reference count on pShmNode has already been incremented under
4305 ** the cover of the unixEnterMutex() mutex and the pointer from the
4306 ** new (struct unixShm) object to the pShmNode has been set. All that is
4307 ** left to do is to link the new object into the linked list starting
4308 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4309 ** mutex.
4310 */
4311 sqlite3_mutex_enter(pShmNode->mutex);
4312 p->pNext = pShmNode->pFirst;
4313 pShmNode->pFirst = p;
4314 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004315 return SQLITE_OK;
4316
4317 /* Jump here on any error */
4318shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004319 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004320 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004321 unixLeaveMutex();
4322 return rc;
4323}
4324
4325/*
danda9fe0c2010-07-13 18:44:03 +00004326** This function is called to obtain a pointer to region iRegion of the
4327** shared-memory associated with the database file fd. Shared-memory regions
4328** are numbered starting from zero. Each shared-memory region is szRegion
4329** bytes in size.
4330**
4331** If an error occurs, an error code is returned and *pp is set to NULL.
4332**
4333** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4334** region has not been allocated (by any client, including one running in a
4335** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4336** bExtend is non-zero and the requested shared-memory region has not yet
4337** been allocated, it is allocated by this function.
4338**
4339** If the shared-memory region has already been allocated or is allocated by
4340** this call as described above, then it is mapped into this processes
4341** address space (if it is not already), *pp is set to point to the mapped
4342** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004343*/
danda9fe0c2010-07-13 18:44:03 +00004344static int unixShmMap(
4345 sqlite3_file *fd, /* Handle open on database file */
4346 int iRegion, /* Region to retrieve */
4347 int szRegion, /* Size of regions */
4348 int bExtend, /* True to extend file if necessary */
4349 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004350){
danda9fe0c2010-07-13 18:44:03 +00004351 unixFile *pDbFd = (unixFile*)fd;
4352 unixShm *p;
4353 unixShmNode *pShmNode;
4354 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004355
danda9fe0c2010-07-13 18:44:03 +00004356 /* If the shared-memory file has not yet been opened, open it now. */
4357 if( pDbFd->pShm==0 ){
4358 rc = unixOpenSharedMemory(pDbFd);
4359 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004360 }
drhd9e5c4f2010-05-12 18:01:39 +00004361
danda9fe0c2010-07-13 18:44:03 +00004362 p = pDbFd->pShm;
4363 pShmNode = p->pShmNode;
4364 sqlite3_mutex_enter(pShmNode->mutex);
4365 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004366 assert( pShmNode->pInode==pDbFd->pInode );
4367 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4368 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004369
4370 if( pShmNode->nRegion<=iRegion ){
4371 char **apNew; /* New apRegion[] array */
4372 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4373 struct stat sStat; /* Used by fstat() */
4374
4375 pShmNode->szRegion = szRegion;
4376
drh3cb93392011-03-12 18:10:44 +00004377 if( pShmNode->h>=0 ){
4378 /* The requested region is not mapped into this processes address space.
4379 ** Check to see if it has been allocated (i.e. if the wal-index file is
4380 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004381 */
drh3cb93392011-03-12 18:10:44 +00004382 if( osFstat(pShmNode->h, &sStat) ){
4383 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004384 goto shmpage_out;
4385 }
drh3cb93392011-03-12 18:10:44 +00004386
4387 if( sStat.st_size<nByte ){
4388 /* The requested memory region does not exist. If bExtend is set to
4389 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004390 */
dan47a2b4a2013-04-26 16:09:29 +00004391 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004392 goto shmpage_out;
4393 }
dan47a2b4a2013-04-26 16:09:29 +00004394
4395 /* Alternatively, if bExtend is true, extend the file. Do this by
4396 ** writing a single byte to the end of each (OS) page being
4397 ** allocated or extended. Technically, we need only write to the
4398 ** last page in order to extend the file. But writing to all new
4399 ** pages forces the OS to allocate them immediately, which reduces
4400 ** the chances of SIGBUS while accessing the mapped region later on.
4401 */
4402 else{
4403 static const int pgsz = 4096;
4404 int iPg;
4405
4406 /* Write to the last byte of each newly allocated or extended page */
4407 assert( (nByte % pgsz)==0 );
4408 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4409 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4410 const char *zFile = pShmNode->zFilename;
4411 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4412 goto shmpage_out;
4413 }
4414 }
drh3cb93392011-03-12 18:10:44 +00004415 }
4416 }
danda9fe0c2010-07-13 18:44:03 +00004417 }
4418
4419 /* Map the requested memory region into this processes address space. */
4420 apNew = (char **)sqlite3_realloc(
4421 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4422 );
4423 if( !apNew ){
4424 rc = SQLITE_IOERR_NOMEM;
4425 goto shmpage_out;
4426 }
4427 pShmNode->apRegion = apNew;
4428 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004429 void *pMem;
4430 if( pShmNode->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004431 pMem = osMmap(0, szRegion,
drh66dfec8b2011-06-01 20:01:49 +00004432 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004433 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004434 );
4435 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004436 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004437 goto shmpage_out;
4438 }
4439 }else{
4440 pMem = sqlite3_malloc(szRegion);
4441 if( pMem==0 ){
4442 rc = SQLITE_NOMEM;
4443 goto shmpage_out;
4444 }
4445 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004446 }
4447 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4448 pShmNode->nRegion++;
4449 }
4450 }
4451
4452shmpage_out:
4453 if( pShmNode->nRegion>iRegion ){
4454 *pp = pShmNode->apRegion[iRegion];
4455 }else{
4456 *pp = 0;
4457 }
drh66dfec8b2011-06-01 20:01:49 +00004458 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004459 sqlite3_mutex_leave(pShmNode->mutex);
4460 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004461}
4462
4463/*
drhd9e5c4f2010-05-12 18:01:39 +00004464** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004465**
4466** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4467** different here than in posix. In xShmLock(), one can go from unlocked
4468** to shared and back or from unlocked to exclusive and back. But one may
4469** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004470*/
4471static int unixShmLock(
4472 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004473 int ofst, /* First lock to acquire or release */
4474 int n, /* Number of locks to acquire or release */
4475 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004476){
drh73b64e42010-05-30 19:55:15 +00004477 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4478 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4479 unixShm *pX; /* For looping over all siblings */
4480 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4481 int rc = SQLITE_OK; /* Result code */
4482 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004483
drhd91c68f2010-05-14 14:52:25 +00004484 assert( pShmNode==pDbFd->pInode->pShmNode );
4485 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004486 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004487 assert( n>=1 );
4488 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4489 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4490 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4491 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4492 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004493 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4494 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004495
drhc99597c2010-05-31 01:41:15 +00004496 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004497 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004498 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004499 if( flags & SQLITE_SHM_UNLOCK ){
4500 u16 allMask = 0; /* Mask of locks held by siblings */
4501
4502 /* See if any siblings hold this same lock */
4503 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4504 if( pX==p ) continue;
4505 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4506 allMask |= pX->sharedMask;
4507 }
4508
4509 /* Unlock the system-level locks */
4510 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004511 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004512 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004513 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004514 }
drh73b64e42010-05-30 19:55:15 +00004515
4516 /* Undo the local locks */
4517 if( rc==SQLITE_OK ){
4518 p->exclMask &= ~mask;
4519 p->sharedMask &= ~mask;
4520 }
4521 }else if( flags & SQLITE_SHM_SHARED ){
4522 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4523
4524 /* Find out which shared locks are already held by sibling connections.
4525 ** If any sibling already holds an exclusive lock, go ahead and return
4526 ** SQLITE_BUSY.
4527 */
4528 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004529 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004530 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004531 break;
4532 }
4533 allShared |= pX->sharedMask;
4534 }
4535
4536 /* Get shared locks at the system level, if necessary */
4537 if( rc==SQLITE_OK ){
4538 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004539 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004540 }else{
drh73b64e42010-05-30 19:55:15 +00004541 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004542 }
drhd9e5c4f2010-05-12 18:01:39 +00004543 }
drh73b64e42010-05-30 19:55:15 +00004544
4545 /* Get the local shared locks */
4546 if( rc==SQLITE_OK ){
4547 p->sharedMask |= mask;
4548 }
4549 }else{
4550 /* Make sure no sibling connections hold locks that will block this
4551 ** lock. If any do, return SQLITE_BUSY right away.
4552 */
4553 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004554 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4555 rc = SQLITE_BUSY;
4556 break;
4557 }
4558 }
4559
4560 /* Get the exclusive locks at the system level. Then if successful
4561 ** also mark the local connection as being locked.
4562 */
4563 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004564 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004565 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004566 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004567 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004568 }
drhd9e5c4f2010-05-12 18:01:39 +00004569 }
4570 }
drhd91c68f2010-05-14 14:52:25 +00004571 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004572 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4573 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004574 return rc;
4575}
4576
drh286a2882010-05-20 23:51:06 +00004577/*
4578** Implement a memory barrier or memory fence on shared memory.
4579**
4580** All loads and stores begun before the barrier must complete before
4581** any load or store begun after the barrier.
4582*/
4583static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004584 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004585){
drhff828942010-06-26 21:34:06 +00004586 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004587 unixEnterMutex();
4588 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004589}
4590
dan18801912010-06-14 14:07:50 +00004591/*
danda9fe0c2010-07-13 18:44:03 +00004592** Close a connection to shared-memory. Delete the underlying
4593** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004594**
4595** If there is no shared memory associated with the connection then this
4596** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004597*/
danda9fe0c2010-07-13 18:44:03 +00004598static int unixShmUnmap(
4599 sqlite3_file *fd, /* The underlying database file */
4600 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004601){
danda9fe0c2010-07-13 18:44:03 +00004602 unixShm *p; /* The connection to be closed */
4603 unixShmNode *pShmNode; /* The underlying shared-memory file */
4604 unixShm **pp; /* For looping over sibling connections */
4605 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004606
danda9fe0c2010-07-13 18:44:03 +00004607 pDbFd = (unixFile*)fd;
4608 p = pDbFd->pShm;
4609 if( p==0 ) return SQLITE_OK;
4610 pShmNode = p->pShmNode;
4611
4612 assert( pShmNode==pDbFd->pInode->pShmNode );
4613 assert( pShmNode->pInode==pDbFd->pInode );
4614
4615 /* Remove connection p from the set of connections associated
4616 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004617 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004618 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4619 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004620
danda9fe0c2010-07-13 18:44:03 +00004621 /* Free the connection p */
4622 sqlite3_free(p);
4623 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004624 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004625
4626 /* If pShmNode->nRef has reached 0, then close the underlying
4627 ** shared-memory file, too */
4628 unixEnterMutex();
4629 assert( pShmNode->nRef>0 );
4630 pShmNode->nRef--;
4631 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004632 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004633 unixShmPurge(pDbFd);
4634 }
4635 unixLeaveMutex();
4636
4637 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004638}
drh286a2882010-05-20 23:51:06 +00004639
danda9fe0c2010-07-13 18:44:03 +00004640
drhd9e5c4f2010-05-12 18:01:39 +00004641#else
drh6b017cc2010-06-14 18:01:46 +00004642# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004643# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004644# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004645# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004646#endif /* #ifndef SQLITE_OMIT_WAL */
4647
mistachkine98844f2013-08-24 00:59:24 +00004648#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004649/*
danaef49d72013-03-25 16:28:54 +00004650** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004651*/
danf23da962013-03-23 21:00:41 +00004652static void unixUnmapfile(unixFile *pFd){
4653 assert( pFd->nFetchOut==0 );
4654 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004655 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004656 pFd->pMapRegion = 0;
4657 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004658 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004659 }
4660}
dan5d8a1372013-03-19 19:28:06 +00004661
danaef49d72013-03-25 16:28:54 +00004662/*
dane6ecd662013-04-01 17:56:59 +00004663** Return the system page size.
4664*/
4665static int unixGetPagesize(void){
4666#if HAVE_MREMAP
4667 return 512;
drh85830a72013-04-03 00:42:01 +00004668#elif defined(_BSD_SOURCE)
dane6ecd662013-04-01 17:56:59 +00004669 return getpagesize();
4670#else
4671 return (int)sysconf(_SC_PAGESIZE);
4672#endif
4673}
4674
4675/*
4676** Attempt to set the size of the memory mapping maintained by file
4677** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4678**
4679** If successful, this function sets the following variables:
4680**
4681** unixFile.pMapRegion
4682** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004683** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004684**
4685** If unsuccessful, an error message is logged via sqlite3_log() and
4686** the three variables above are zeroed. In this case SQLite should
4687** continue accessing the database using the xRead() and xWrite()
4688** methods.
4689*/
4690static void unixRemapfile(
4691 unixFile *pFd, /* File descriptor object */
4692 i64 nNew /* Required mapping size */
4693){
dan4ff7bc42013-04-02 12:04:09 +00004694 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004695 int h = pFd->h; /* File descriptor open on db file */
4696 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004697 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004698 u8 *pNew = 0; /* Location of new mapping */
4699 int flags = PROT_READ; /* Flags to pass to mmap() */
4700
4701 assert( pFd->nFetchOut==0 );
4702 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004703 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004704 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004705 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004706 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004707
4708 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4709
4710 if( pOrig ){
4711 const int szSyspage = unixGetPagesize();
4712 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
4713 u8 *pReq = &pOrig[nReuse];
4714
4715 /* Unmap any pages of the existing mapping that cannot be reused. */
4716 if( nReuse!=nOrig ){
4717 osMunmap(pReq, nOrig-nReuse);
4718 }
4719
4720#if HAVE_MREMAP
4721 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004722 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004723#else
4724 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4725 if( pNew!=MAP_FAILED ){
4726 if( pNew!=pReq ){
4727 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004728 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004729 }else{
4730 pNew = pOrig;
4731 }
4732 }
4733#endif
4734
dan48ccef82013-04-02 20:55:01 +00004735 /* The attempt to extend the existing mapping failed. Free it. */
4736 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004737 osMunmap(pOrig, nReuse);
4738 }
4739 }
4740
4741 /* If pNew is still NULL, try to create an entirely new mapping. */
4742 if( pNew==0 ){
4743 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004744 }
4745
dan4ff7bc42013-04-02 12:04:09 +00004746 if( pNew==MAP_FAILED ){
4747 pNew = 0;
4748 nNew = 0;
4749 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4750
4751 /* If the mmap() above failed, assume that all subsequent mmap() calls
4752 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4753 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004754 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004755 }
dane6ecd662013-04-01 17:56:59 +00004756 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004757 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004758}
4759
4760/*
danaef49d72013-03-25 16:28:54 +00004761** Memory map or remap the file opened by file-descriptor pFd (if the file
4762** is already mapped, the existing mapping is replaced by the new). Or, if
4763** there already exists a mapping for this file, and there are still
4764** outstanding xFetch() references to it, this function is a no-op.
4765**
4766** If parameter nByte is non-negative, then it is the requested size of
4767** the mapping to create. Otherwise, if nByte is less than zero, then the
4768** requested size is the size of the file on disk. The actual size of the
4769** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004770** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004771**
4772** SQLITE_OK is returned if no error occurs (even if the mapping is not
4773** recreated as a result of outstanding references) or an SQLite error
4774** code otherwise.
4775*/
danf23da962013-03-23 21:00:41 +00004776static int unixMapfile(unixFile *pFd, i64 nByte){
4777 i64 nMap = nByte;
4778 int rc;
daneb97b292013-03-20 14:26:59 +00004779
danf23da962013-03-23 21:00:41 +00004780 assert( nMap>=0 || pFd->nFetchOut==0 );
4781 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4782
4783 if( nMap<0 ){
daneb97b292013-03-20 14:26:59 +00004784 struct stat statbuf; /* Low-level file information */
danf23da962013-03-23 21:00:41 +00004785 rc = osFstat(pFd->h, &statbuf);
4786 if( rc!=SQLITE_OK ){
4787 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004788 }
danf23da962013-03-23 21:00:41 +00004789 nMap = statbuf.st_size;
4790 }
drh9b4c59f2013-04-15 17:03:42 +00004791 if( nMap>pFd->mmapSizeMax ){
4792 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004793 }
4794
danf23da962013-03-23 21:00:41 +00004795 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004796 if( nMap>0 ){
4797 unixRemapfile(pFd, nMap);
4798 }else{
danb7e3a322013-03-25 20:30:13 +00004799 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004800 }
4801 }
4802
danf23da962013-03-23 21:00:41 +00004803 return SQLITE_OK;
4804}
mistachkine98844f2013-08-24 00:59:24 +00004805#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004806
danaef49d72013-03-25 16:28:54 +00004807/*
4808** If possible, return a pointer to a mapping of file fd starting at offset
4809** iOff. The mapping must be valid for at least nAmt bytes.
4810**
4811** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4812** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4813** Finally, if an error does occur, return an SQLite error code. The final
4814** value of *pp is undefined in this case.
4815**
4816** If this function does return a pointer, the caller must eventually
4817** release the reference by calling unixUnfetch().
4818*/
danf23da962013-03-23 21:00:41 +00004819static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004820#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004821 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004822#endif
danf23da962013-03-23 21:00:41 +00004823 *pp = 0;
4824
drh9b4c59f2013-04-15 17:03:42 +00004825#if SQLITE_MAX_MMAP_SIZE>0
4826 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004827 if( pFd->pMapRegion==0 ){
4828 int rc = unixMapfile(pFd, -1);
4829 if( rc!=SQLITE_OK ) return rc;
4830 }
4831 if( pFd->mmapSize >= iOff+nAmt ){
4832 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4833 pFd->nFetchOut++;
4834 }
4835 }
drh6e0b6d52013-04-09 16:19:20 +00004836#endif
danf23da962013-03-23 21:00:41 +00004837 return SQLITE_OK;
4838}
4839
danaef49d72013-03-25 16:28:54 +00004840/*
dandf737fe2013-03-25 17:00:24 +00004841** If the third argument is non-NULL, then this function releases a
4842** reference obtained by an earlier call to unixFetch(). The second
4843** argument passed to this function must be the same as the corresponding
4844** argument that was passed to the unixFetch() invocation.
4845**
4846** Or, if the third argument is NULL, then this function is being called
4847** to inform the VFS layer that, according to POSIX, any existing mapping
4848** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004849*/
dandf737fe2013-03-25 17:00:24 +00004850static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004851#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004852 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004853 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004854
danaef49d72013-03-25 16:28:54 +00004855 /* If p==0 (unmap the entire file) then there must be no outstanding
4856 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4857 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004858 assert( (p==0)==(pFd->nFetchOut==0) );
4859
dandf737fe2013-03-25 17:00:24 +00004860 /* If p!=0, it must match the iOff value. */
4861 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4862
danf23da962013-03-23 21:00:41 +00004863 if( p ){
4864 pFd->nFetchOut--;
4865 }else{
4866 unixUnmapfile(pFd);
4867 }
4868
4869 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004870#else
4871 UNUSED_PARAMETER(fd);
4872 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004873 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004874#endif
danf23da962013-03-23 21:00:41 +00004875 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004876}
4877
4878/*
drh734c9862008-11-28 15:37:20 +00004879** Here ends the implementation of all sqlite3_file methods.
4880**
4881********************** End sqlite3_file Methods *******************************
4882******************************************************************************/
4883
4884/*
drh6b9d6dd2008-12-03 19:34:47 +00004885** This division contains definitions of sqlite3_io_methods objects that
4886** implement various file locking strategies. It also contains definitions
4887** of "finder" functions. A finder-function is used to locate the appropriate
4888** sqlite3_io_methods object for a particular database file. The pAppData
4889** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4890** the correct finder-function for that VFS.
4891**
4892** Most finder functions return a pointer to a fixed sqlite3_io_methods
4893** object. The only interesting finder-function is autolockIoFinder, which
4894** looks at the filesystem type and tries to guess the best locking
4895** strategy from that.
4896**
drh1875f7a2008-12-08 18:19:17 +00004897** For finder-funtion F, two objects are created:
4898**
4899** (1) The real finder-function named "FImpt()".
4900**
dane946c392009-08-22 11:39:46 +00004901** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004902**
4903**
4904** A pointer to the F pointer is used as the pAppData value for VFS
4905** objects. We have to do this instead of letting pAppData point
4906** directly at the finder-function since C90 rules prevent a void*
4907** from be cast into a function pointer.
4908**
drh6b9d6dd2008-12-03 19:34:47 +00004909**
drh7708e972008-11-29 00:56:52 +00004910** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004911**
drh7708e972008-11-29 00:56:52 +00004912** * A constant sqlite3_io_methods object call METHOD that has locking
4913** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4914**
4915** * An I/O method finder function called FINDER that returns a pointer
4916** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004917*/
drhd9e5c4f2010-05-12 18:01:39 +00004918#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004919static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004920 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004921 CLOSE, /* xClose */ \
4922 unixRead, /* xRead */ \
4923 unixWrite, /* xWrite */ \
4924 unixTruncate, /* xTruncate */ \
4925 unixSync, /* xSync */ \
4926 unixFileSize, /* xFileSize */ \
4927 LOCK, /* xLock */ \
4928 UNLOCK, /* xUnlock */ \
4929 CKLOCK, /* xCheckReservedLock */ \
4930 unixFileControl, /* xFileControl */ \
4931 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004932 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004933 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004934 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004935 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004936 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004937 unixFetch, /* xFetch */ \
4938 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004939}; \
drh0c2694b2009-09-03 16:23:44 +00004940static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4941 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004942 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004943} \
drh0c2694b2009-09-03 16:23:44 +00004944static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004945 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004946
4947/*
4948** Here are all of the sqlite3_io_methods objects for each of the
4949** locking strategies. Functions that return pointers to these methods
4950** are also created.
4951*/
4952IOMETHODS(
4953 posixIoFinder, /* Finder function name */
4954 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004955 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004956 unixClose, /* xClose method */
4957 unixLock, /* xLock method */
4958 unixUnlock, /* xUnlock method */
4959 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004960)
drh7708e972008-11-29 00:56:52 +00004961IOMETHODS(
4962 nolockIoFinder, /* Finder function name */
4963 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004964 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004965 nolockClose, /* xClose method */
4966 nolockLock, /* xLock method */
4967 nolockUnlock, /* xUnlock method */
4968 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004969)
drh7708e972008-11-29 00:56:52 +00004970IOMETHODS(
4971 dotlockIoFinder, /* Finder function name */
4972 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004973 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004974 dotlockClose, /* xClose method */
4975 dotlockLock, /* xLock method */
4976 dotlockUnlock, /* xUnlock method */
4977 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004978)
drh7708e972008-11-29 00:56:52 +00004979
chw78a13182009-04-07 05:35:03 +00004980#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004981IOMETHODS(
4982 flockIoFinder, /* Finder function name */
4983 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004984 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004985 flockClose, /* xClose method */
4986 flockLock, /* xLock method */
4987 flockUnlock, /* xUnlock method */
4988 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004989)
drh7708e972008-11-29 00:56:52 +00004990#endif
4991
drh6c7d5c52008-11-21 20:32:33 +00004992#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004993IOMETHODS(
4994 semIoFinder, /* Finder function name */
4995 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004996 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004997 semClose, /* xClose method */
4998 semLock, /* xLock method */
4999 semUnlock, /* xUnlock method */
5000 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005001)
aswiftaebf4132008-11-21 00:10:35 +00005002#endif
drh7708e972008-11-29 00:56:52 +00005003
drhd2cb50b2009-01-09 21:41:17 +00005004#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005005IOMETHODS(
5006 afpIoFinder, /* Finder function name */
5007 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005008 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005009 afpClose, /* xClose method */
5010 afpLock, /* xLock method */
5011 afpUnlock, /* xUnlock method */
5012 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005013)
drh715ff302008-12-03 22:32:44 +00005014#endif
5015
5016/*
5017** The proxy locking method is a "super-method" in the sense that it
5018** opens secondary file descriptors for the conch and lock files and
5019** it uses proxy, dot-file, AFP, and flock() locking methods on those
5020** secondary files. For this reason, the division that implements
5021** proxy locking is located much further down in the file. But we need
5022** to go ahead and define the sqlite3_io_methods and finder function
5023** for proxy locking here. So we forward declare the I/O methods.
5024*/
drhd2cb50b2009-01-09 21:41:17 +00005025#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005026static int proxyClose(sqlite3_file*);
5027static int proxyLock(sqlite3_file*, int);
5028static int proxyUnlock(sqlite3_file*, int);
5029static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005030IOMETHODS(
5031 proxyIoFinder, /* Finder function name */
5032 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005033 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005034 proxyClose, /* xClose method */
5035 proxyLock, /* xLock method */
5036 proxyUnlock, /* xUnlock method */
5037 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005038)
aswiftaebf4132008-11-21 00:10:35 +00005039#endif
drh7708e972008-11-29 00:56:52 +00005040
drh7ed97b92010-01-20 13:07:21 +00005041/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5042#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5043IOMETHODS(
5044 nfsIoFinder, /* Finder function name */
5045 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005046 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005047 unixClose, /* xClose method */
5048 unixLock, /* xLock method */
5049 nfsUnlock, /* xUnlock method */
5050 unixCheckReservedLock /* xCheckReservedLock method */
5051)
5052#endif
drh7708e972008-11-29 00:56:52 +00005053
drhd2cb50b2009-01-09 21:41:17 +00005054#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005055/*
drh6b9d6dd2008-12-03 19:34:47 +00005056** This "finder" function attempts to determine the best locking strategy
5057** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005058** object that implements that strategy.
5059**
5060** This is for MacOSX only.
5061*/
drh1875f7a2008-12-08 18:19:17 +00005062static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005063 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005064 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005065){
5066 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005067 const char *zFilesystem; /* Filesystem type name */
5068 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005069 } aMap[] = {
5070 { "hfs", &posixIoMethods },
5071 { "ufs", &posixIoMethods },
5072 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005073 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005074 { "webdav", &nolockIoMethods },
5075 { 0, 0 }
5076 };
5077 int i;
5078 struct statfs fsInfo;
5079 struct flock lockInfo;
5080
5081 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005082 /* If filePath==NULL that means we are dealing with a transient file
5083 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005084 return &nolockIoMethods;
5085 }
5086 if( statfs(filePath, &fsInfo) != -1 ){
5087 if( fsInfo.f_flags & MNT_RDONLY ){
5088 return &nolockIoMethods;
5089 }
5090 for(i=0; aMap[i].zFilesystem; i++){
5091 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5092 return aMap[i].pMethods;
5093 }
5094 }
5095 }
5096
5097 /* Default case. Handles, amongst others, "nfs".
5098 ** Test byte-range lock using fcntl(). If the call succeeds,
5099 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005100 */
drh7708e972008-11-29 00:56:52 +00005101 lockInfo.l_len = 1;
5102 lockInfo.l_start = 0;
5103 lockInfo.l_whence = SEEK_SET;
5104 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005105 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005106 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5107 return &nfsIoMethods;
5108 } else {
5109 return &posixIoMethods;
5110 }
drh7708e972008-11-29 00:56:52 +00005111 }else{
5112 return &dotlockIoMethods;
5113 }
5114}
drh0c2694b2009-09-03 16:23:44 +00005115static const sqlite3_io_methods
5116 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005117
drhd2cb50b2009-01-09 21:41:17 +00005118#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005119
chw78a13182009-04-07 05:35:03 +00005120#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5121/*
5122** This "finder" function attempts to determine the best locking strategy
5123** for the database file "filePath". It then returns the sqlite3_io_methods
5124** object that implements that strategy.
5125**
5126** This is for VXWorks only.
5127*/
5128static const sqlite3_io_methods *autolockIoFinderImpl(
5129 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005130 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005131){
5132 struct flock lockInfo;
5133
5134 if( !filePath ){
5135 /* If filePath==NULL that means we are dealing with a transient file
5136 ** that does not need to be locked. */
5137 return &nolockIoMethods;
5138 }
5139
5140 /* Test if fcntl() is supported and use POSIX style locks.
5141 ** Otherwise fall back to the named semaphore method.
5142 */
5143 lockInfo.l_len = 1;
5144 lockInfo.l_start = 0;
5145 lockInfo.l_whence = SEEK_SET;
5146 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005147 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005148 return &posixIoMethods;
5149 }else{
5150 return &semIoMethods;
5151 }
5152}
drh0c2694b2009-09-03 16:23:44 +00005153static const sqlite3_io_methods
5154 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005155
5156#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5157
drh7708e972008-11-29 00:56:52 +00005158/*
5159** An abstract type for a pointer to a IO method finder function:
5160*/
drh0c2694b2009-09-03 16:23:44 +00005161typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005162
aswiftaebf4132008-11-21 00:10:35 +00005163
drh734c9862008-11-28 15:37:20 +00005164/****************************************************************************
5165**************************** sqlite3_vfs methods ****************************
5166**
5167** This division contains the implementation of methods on the
5168** sqlite3_vfs object.
5169*/
5170
danielk1977a3d4c882007-03-23 10:08:38 +00005171/*
danielk1977e339d652008-06-28 11:23:00 +00005172** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005173*/
5174static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005175 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005176 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005177 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005178 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005179 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005180){
drh7708e972008-11-29 00:56:52 +00005181 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005182 unixFile *pNew = (unixFile *)pId;
5183 int rc = SQLITE_OK;
5184
drh8af6c222010-05-14 12:43:01 +00005185 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005186
dan00157392010-10-05 11:33:15 +00005187 /* Usually the path zFilename should not be a relative pathname. The
5188 ** exception is when opening the proxy "conch" file in builds that
5189 ** include the special Apple locking styles.
5190 */
dan00157392010-10-05 11:33:15 +00005191#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005192 assert( zFilename==0 || zFilename[0]=='/'
5193 || pVfs->pAppData==(void*)&autolockIoFinder );
5194#else
5195 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005196#endif
dan00157392010-10-05 11:33:15 +00005197
drhb07028f2011-10-14 21:49:18 +00005198 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005199 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005200
drh308c2a52010-05-14 11:30:18 +00005201 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005202 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005203 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005204 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005205 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005206#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005207 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005208#endif
drhc02a43a2012-01-10 23:18:38 +00005209 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5210 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005211 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005212 }
drh503a6862013-03-01 01:07:17 +00005213 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005214 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005215 }
drh339eb0b2008-03-07 15:34:11 +00005216
drh6c7d5c52008-11-21 20:32:33 +00005217#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005218 pNew->pId = vxworksFindFileId(zFilename);
5219 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005220 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005221 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005222 }
5223#endif
5224
drhc02a43a2012-01-10 23:18:38 +00005225 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005226 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005227 }else{
drh0c2694b2009-09-03 16:23:44 +00005228 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005229#if SQLITE_ENABLE_LOCKING_STYLE
5230 /* Cache zFilename in the locking context (AFP and dotlock override) for
5231 ** proxyLock activation is possible (remote proxy is based on db name)
5232 ** zFilename remains valid until file is closed, to support */
5233 pNew->lockingContext = (void*)zFilename;
5234#endif
drhda0e7682008-07-30 15:27:54 +00005235 }
danielk1977e339d652008-06-28 11:23:00 +00005236
drh7ed97b92010-01-20 13:07:21 +00005237 if( pLockingStyle == &posixIoMethods
5238#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5239 || pLockingStyle == &nfsIoMethods
5240#endif
5241 ){
drh7708e972008-11-29 00:56:52 +00005242 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005243 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005244 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005245 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005246 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005247 ** in two scenarios:
5248 **
5249 ** (a) A call to fstat() failed.
5250 ** (b) A malloc failed.
5251 **
5252 ** Scenario (b) may only occur if the process is holding no other
5253 ** file descriptors open on the same file. If there were other file
5254 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005255 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005256 ** handle h - as it is guaranteed that no posix locks will be released
5257 ** by doing so.
5258 **
5259 ** If scenario (a) caused the error then things are not so safe. The
5260 ** implicit assumption here is that if fstat() fails, things are in
5261 ** such bad shape that dropping a lock or two doesn't matter much.
5262 */
drh0e9365c2011-03-02 02:08:13 +00005263 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005264 h = -1;
5265 }
drh7708e972008-11-29 00:56:52 +00005266 unixLeaveMutex();
5267 }
danielk1977e339d652008-06-28 11:23:00 +00005268
drhd2cb50b2009-01-09 21:41:17 +00005269#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005270 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005271 /* AFP locking uses the file path so it needs to be included in
5272 ** the afpLockingContext.
5273 */
5274 afpLockingContext *pCtx;
5275 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5276 if( pCtx==0 ){
5277 rc = SQLITE_NOMEM;
5278 }else{
5279 /* NB: zFilename exists and remains valid until the file is closed
5280 ** according to requirement F11141. So we do not need to make a
5281 ** copy of the filename. */
5282 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005283 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005284 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005285 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005286 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005287 if( rc!=SQLITE_OK ){
5288 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005289 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005290 h = -1;
5291 }
drh7708e972008-11-29 00:56:52 +00005292 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005293 }
drh7708e972008-11-29 00:56:52 +00005294 }
5295#endif
danielk1977e339d652008-06-28 11:23:00 +00005296
drh7708e972008-11-29 00:56:52 +00005297 else if( pLockingStyle == &dotlockIoMethods ){
5298 /* Dotfile locking uses the file path so it needs to be included in
5299 ** the dotlockLockingContext
5300 */
5301 char *zLockFile;
5302 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005303 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005304 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005305 zLockFile = (char *)sqlite3_malloc(nFilename);
5306 if( zLockFile==0 ){
5307 rc = SQLITE_NOMEM;
5308 }else{
5309 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005310 }
drh7708e972008-11-29 00:56:52 +00005311 pNew->lockingContext = zLockFile;
5312 }
danielk1977e339d652008-06-28 11:23:00 +00005313
drh6c7d5c52008-11-21 20:32:33 +00005314#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005315 else if( pLockingStyle == &semIoMethods ){
5316 /* Named semaphore locking uses the file path so it needs to be
5317 ** included in the semLockingContext
5318 */
5319 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005320 rc = findInodeInfo(pNew, &pNew->pInode);
5321 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5322 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005323 int n;
drh2238dcc2009-08-27 17:56:20 +00005324 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005325 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005326 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005327 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005328 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5329 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005330 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005331 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005332 }
chw97185482008-11-17 08:05:31 +00005333 }
drh7708e972008-11-29 00:56:52 +00005334 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005335 }
drh7708e972008-11-29 00:56:52 +00005336#endif
aswift5b1a2562008-08-22 00:22:35 +00005337
5338 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005339#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005340 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005341 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005342 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005343 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005344 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005345 }
chw97185482008-11-17 08:05:31 +00005346#endif
danielk1977e339d652008-06-28 11:23:00 +00005347 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005348 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005349 }else{
drh7708e972008-11-29 00:56:52 +00005350 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005351 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005352 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005353 }
danielk1977e339d652008-06-28 11:23:00 +00005354 return rc;
drh054889e2005-11-30 03:20:31 +00005355}
drh9c06c952005-11-26 00:25:00 +00005356
danielk1977ad94b582007-08-20 06:44:22 +00005357/*
drh8b3cf822010-06-01 21:02:51 +00005358** Return the name of a directory in which to put temporary files.
5359** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005360*/
drh7234c6d2010-06-19 15:10:09 +00005361static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005362 static const char *azDirs[] = {
5363 0,
aswiftaebf4132008-11-21 00:10:35 +00005364 0,
mistachkind95a3d32013-08-30 21:52:38 +00005365 0,
danielk197717b90b52008-06-06 11:11:25 +00005366 "/var/tmp",
5367 "/usr/tmp",
5368 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005369 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005370 };
drh8b3cf822010-06-01 21:02:51 +00005371 unsigned int i;
5372 struct stat buf;
5373 const char *zDir = 0;
5374
5375 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005376 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5377 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005378 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005379 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005380 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005381 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005382 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005383 break;
5384 }
5385 return zDir;
5386}
5387
5388/*
5389** Create a temporary file name in zBuf. zBuf must be allocated
5390** by the calling process and must be big enough to hold at least
5391** pVfs->mxPathname bytes.
5392*/
5393static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005394 static const unsigned char zChars[] =
5395 "abcdefghijklmnopqrstuvwxyz"
5396 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5397 "0123456789";
drh41022642008-11-21 00:24:42 +00005398 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005399 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005400
5401 /* It's odd to simulate an io-error here, but really this is just
5402 ** using the io-error infrastructure to test that SQLite handles this
5403 ** function failing.
5404 */
5405 SimulateIOError( return SQLITE_IOERR );
5406
drh7234c6d2010-06-19 15:10:09 +00005407 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005408 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005409
5410 /* Check that the output buffer is large enough for the temporary file
5411 ** name. If it is not, return SQLITE_ERROR.
5412 */
drhc02a43a2012-01-10 23:18:38 +00005413 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005414 return SQLITE_ERROR;
5415 }
5416
5417 do{
drhc02a43a2012-01-10 23:18:38 +00005418 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005419 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005420 sqlite3_randomness(15, &zBuf[j]);
5421 for(i=0; i<15; i++, j++){
5422 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5423 }
5424 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005425 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005426 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005427 return SQLITE_OK;
5428}
5429
drhd2cb50b2009-01-09 21:41:17 +00005430#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005431/*
5432** Routine to transform a unixFile into a proxy-locking unixFile.
5433** Implementation in the proxy-lock division, but used by unixOpen()
5434** if SQLITE_PREFER_PROXY_LOCKING is defined.
5435*/
5436static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005437#endif
drhc66d5b62008-12-03 22:48:32 +00005438
dan08da86a2009-08-21 17:18:03 +00005439/*
5440** Search for an unused file descriptor that was opened on the database
5441** file (not a journal or master-journal file) identified by pathname
5442** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5443** argument to this function.
5444**
5445** Such a file descriptor may exist if a database connection was closed
5446** but the associated file descriptor could not be closed because some
5447** other file descriptor open on the same file is holding a file-lock.
5448** Refer to comments in the unixClose() function and the lengthy comment
5449** describing "Posix Advisory Locking" at the start of this file for
5450** further details. Also, ticket #4018.
5451**
5452** If a suitable file descriptor is found, then it is returned. If no
5453** such file descriptor is located, -1 is returned.
5454*/
dane946c392009-08-22 11:39:46 +00005455static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5456 UnixUnusedFd *pUnused = 0;
5457
5458 /* Do not search for an unused file descriptor on vxworks. Not because
5459 ** vxworks would not benefit from the change (it might, we're not sure),
5460 ** but because no way to test it is currently available. It is better
5461 ** not to risk breaking vxworks support for the sake of such an obscure
5462 ** feature. */
5463#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005464 struct stat sStat; /* Results of stat() call */
5465
5466 /* A stat() call may fail for various reasons. If this happens, it is
5467 ** almost certain that an open() call on the same path will also fail.
5468 ** For this reason, if an error occurs in the stat() call here, it is
5469 ** ignored and -1 is returned. The caller will try to open a new file
5470 ** descriptor on the same path, fail, and return an error to SQLite.
5471 **
5472 ** Even if a subsequent open() call does succeed, the consequences of
5473 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005474 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005475 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005476
5477 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005478 pInode = inodeList;
5479 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5480 || pInode->fileId.ino!=sStat.st_ino) ){
5481 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005482 }
drh8af6c222010-05-14 12:43:01 +00005483 if( pInode ){
dane946c392009-08-22 11:39:46 +00005484 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005485 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005486 pUnused = *pp;
5487 if( pUnused ){
5488 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005489 }
5490 }
5491 unixLeaveMutex();
5492 }
dane946c392009-08-22 11:39:46 +00005493#endif /* if !OS_VXWORKS */
5494 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005495}
danielk197717b90b52008-06-06 11:11:25 +00005496
5497/*
danddb0ac42010-07-14 14:48:58 +00005498** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005499** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005500** and a value suitable for passing as the third argument to open(2) is
5501** written to *pMode. If an IO error occurs, an SQLite error code is
5502** returned and the value of *pMode is not modified.
5503**
drh8c815d12012-02-13 20:16:37 +00005504** In most cases cases, this routine sets *pMode to 0, which will become
5505** an indication to robust_open() to create the file using
5506** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5507** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005508** this function queries the file-system for the permissions on the
5509** corresponding database file and sets *pMode to this value. Whenever
5510** possible, WAL and journal files are created using the same permissions
5511** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005512**
5513** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5514** original filename is unavailable. But 8_3_NAMES is only used for
5515** FAT filesystems and permissions do not matter there, so just use
5516** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005517*/
5518static int findCreateFileMode(
5519 const char *zPath, /* Path of file (possibly) being created */
5520 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005521 mode_t *pMode, /* OUT: Permissions to open file with */
5522 uid_t *pUid, /* OUT: uid to set on the file */
5523 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005524){
5525 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005526 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005527 *pUid = 0;
5528 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005529 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005530 char zDb[MAX_PATHNAME+1]; /* Database file path */
5531 int nDb; /* Number of valid bytes in zDb */
5532 struct stat sStat; /* Output of stat() on database file */
5533
dana0c989d2010-11-05 18:07:37 +00005534 /* zPath is a path to a WAL or journal file. The following block derives
5535 ** the path to the associated database file from zPath. This block handles
5536 ** the following naming conventions:
5537 **
5538 ** "<path to db>-journal"
5539 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005540 ** "<path to db>-journalNN"
5541 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005542 **
drhd337c5b2011-10-20 18:23:35 +00005543 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005544 ** used by the test_multiplex.c module.
5545 */
5546 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005547#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005548 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005549 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005550#else
5551 while( zPath[nDb]!='-' ){
5552 assert( nDb>0 );
5553 assert( zPath[nDb]!='\n' );
5554 nDb--;
5555 }
5556#endif
danddb0ac42010-07-14 14:48:58 +00005557 memcpy(zDb, zPath, nDb);
5558 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005559
drh58384f12011-07-28 00:14:45 +00005560 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005561 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005562 *pUid = sStat.st_uid;
5563 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005564 }else{
5565 rc = SQLITE_IOERR_FSTAT;
5566 }
5567 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5568 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005569 }
5570 return rc;
5571}
5572
5573/*
danielk1977ad94b582007-08-20 06:44:22 +00005574** Open the file zPath.
5575**
danielk1977b4b47412007-08-17 15:53:36 +00005576** Previously, the SQLite OS layer used three functions in place of this
5577** one:
5578**
5579** sqlite3OsOpenReadWrite();
5580** sqlite3OsOpenReadOnly();
5581** sqlite3OsOpenExclusive();
5582**
5583** These calls correspond to the following combinations of flags:
5584**
5585** ReadWrite() -> (READWRITE | CREATE)
5586** ReadOnly() -> (READONLY)
5587** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5588**
5589** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5590** true, the file was configured to be automatically deleted when the
5591** file handle closed. To achieve the same effect using this new
5592** interface, add the DELETEONCLOSE flag to those specified above for
5593** OpenExclusive().
5594*/
5595static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005596 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5597 const char *zPath, /* Pathname of file to be opened */
5598 sqlite3_file *pFile, /* The file descriptor to be filled in */
5599 int flags, /* Input flags to control the opening */
5600 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005601){
dan08da86a2009-08-21 17:18:03 +00005602 unixFile *p = (unixFile *)pFile;
5603 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005604 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005605 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005606 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005607 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005608 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005609
5610 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5611 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5612 int isCreate = (flags & SQLITE_OPEN_CREATE);
5613 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5614 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005615#if SQLITE_ENABLE_LOCKING_STYLE
5616 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5617#endif
drh3d4435b2011-08-26 20:55:50 +00005618#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5619 struct statfs fsInfo;
5620#endif
danielk1977b4b47412007-08-17 15:53:36 +00005621
danielk1977fee2d252007-08-18 10:59:19 +00005622 /* If creating a master or main-file journal, this function will open
5623 ** a file-descriptor on the directory too. The first time unixSync()
5624 ** is called the directory file descriptor will be fsync()ed and close()d.
5625 */
drh0059eae2011-08-08 23:48:40 +00005626 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005627 eType==SQLITE_OPEN_MASTER_JOURNAL
5628 || eType==SQLITE_OPEN_MAIN_JOURNAL
5629 || eType==SQLITE_OPEN_WAL
5630 ));
danielk1977fee2d252007-08-18 10:59:19 +00005631
danielk197717b90b52008-06-06 11:11:25 +00005632 /* If argument zPath is a NULL pointer, this function is required to open
5633 ** a temporary file. Use this buffer to store the file name in.
5634 */
drhc02a43a2012-01-10 23:18:38 +00005635 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005636 const char *zName = zPath;
5637
danielk1977fee2d252007-08-18 10:59:19 +00005638 /* Check the following statements are true:
5639 **
5640 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5641 ** (b) if CREATE is set, then READWRITE must also be set, and
5642 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005643 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005644 */
danielk1977b4b47412007-08-17 15:53:36 +00005645 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005646 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005647 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005648 assert(isDelete==0 || isCreate);
5649
danddb0ac42010-07-14 14:48:58 +00005650 /* The main DB, main journal, WAL file and master journal are never
5651 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005652 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5653 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5654 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005655 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005656
danielk1977fee2d252007-08-18 10:59:19 +00005657 /* Assert that the upper layer has set one of the "file-type" flags. */
5658 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5659 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5660 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005661 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005662 );
5663
drhb00d8622014-01-01 15:18:36 +00005664 /* Detect a pid change and reset the PRNG. There is a race condition
5665 ** here such that two or more threads all trying to open databases at
5666 ** the same instant might all reset the PRNG. But multiple resets
5667 ** are harmless.
5668 */
5669 if( randomnessPid!=getpid() ){
5670 randomnessPid = getpid();
5671 sqlite3_randomness(0,0);
5672 }
5673
dan08da86a2009-08-21 17:18:03 +00005674 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005675
dan08da86a2009-08-21 17:18:03 +00005676 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005677 UnixUnusedFd *pUnused;
5678 pUnused = findReusableFd(zName, flags);
5679 if( pUnused ){
5680 fd = pUnused->fd;
5681 }else{
dan6aa657f2009-08-24 18:57:58 +00005682 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005683 if( !pUnused ){
5684 return SQLITE_NOMEM;
5685 }
5686 }
5687 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005688
5689 /* Database filenames are double-zero terminated if they are not
5690 ** URIs with parameters. Hence, they can always be passed into
5691 ** sqlite3_uri_parameter(). */
5692 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5693
dan08da86a2009-08-21 17:18:03 +00005694 }else if( !zName ){
5695 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005696 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005697 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005698 if( rc!=SQLITE_OK ){
5699 return rc;
5700 }
5701 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005702
5703 /* Generated temporary filenames are always double-zero terminated
5704 ** for use by sqlite3_uri_parameter(). */
5705 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005706 }
5707
dan08da86a2009-08-21 17:18:03 +00005708 /* Determine the value of the flags parameter passed to POSIX function
5709 ** open(). These must be calculated even if open() is not called, as
5710 ** they may be stored as part of the file handle and used by the
5711 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005712 if( isReadonly ) openFlags |= O_RDONLY;
5713 if( isReadWrite ) openFlags |= O_RDWR;
5714 if( isCreate ) openFlags |= O_CREAT;
5715 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5716 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005717
danielk1977b4b47412007-08-17 15:53:36 +00005718 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005719 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005720 uid_t uid; /* Userid for the file */
5721 gid_t gid; /* Groupid for the file */
5722 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005723 if( rc!=SQLITE_OK ){
5724 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005725 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005726 return rc;
5727 }
drhad4f1e52011-03-04 15:43:57 +00005728 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005729 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005730 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5731 /* Failed to open the file for read/write access. Try read-only. */
5732 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005733 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005734 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005735 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005736 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005737 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005738 }
5739 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005740 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005741 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005742 }
drhac7c3ac2012-02-11 19:23:48 +00005743
5744 /* If this process is running as root and if creating a new rollback
5745 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005746 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005747 */
5748 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005749 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005750 }
danielk1977b4b47412007-08-17 15:53:36 +00005751 }
dan08da86a2009-08-21 17:18:03 +00005752 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005753 if( pOutFlags ){
5754 *pOutFlags = flags;
5755 }
5756
dane946c392009-08-22 11:39:46 +00005757 if( p->pUnused ){
5758 p->pUnused->fd = fd;
5759 p->pUnused->flags = flags;
5760 }
5761
danielk1977b4b47412007-08-17 15:53:36 +00005762 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005763#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005764 zPath = zName;
5765#else
drh036ac7f2011-08-08 23:18:05 +00005766 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005767#endif
danielk1977b4b47412007-08-17 15:53:36 +00005768 }
drh41022642008-11-21 00:24:42 +00005769#if SQLITE_ENABLE_LOCKING_STYLE
5770 else{
dan08da86a2009-08-21 17:18:03 +00005771 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005772 }
5773#endif
5774
drhda0e7682008-07-30 15:27:54 +00005775 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005776
drh7ed97b92010-01-20 13:07:21 +00005777
5778#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005779 if( fstatfs(fd, &fsInfo) == -1 ){
5780 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005781 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005782 return SQLITE_IOERR_ACCESS;
5783 }
5784 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5785 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5786 }
5787#endif
drhc02a43a2012-01-10 23:18:38 +00005788
5789 /* Set up appropriate ctrlFlags */
5790 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5791 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5792 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5793 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5794 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5795
drh7ed97b92010-01-20 13:07:21 +00005796#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005797#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005798 isAutoProxy = 1;
5799#endif
5800 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005801 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5802 int useProxy = 0;
5803
dan08da86a2009-08-21 17:18:03 +00005804 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5805 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005806 if( envforce!=NULL ){
5807 useProxy = atoi(envforce)>0;
5808 }else{
aswiftaebf4132008-11-21 00:10:35 +00005809 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005810 /* In theory, the close(fd) call is sub-optimal. If the file opened
5811 ** with fd is a database file, and there are other connections open
5812 ** on that file that are currently holding advisory locks on it,
5813 ** then the call to close() will cancel those locks. In practice,
5814 ** we're assuming that statfs() doesn't fail very often. At least
5815 ** not while other file descriptors opened by the same process on
5816 ** the same file are working. */
5817 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005818 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005819 rc = SQLITE_IOERR_ACCESS;
5820 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005821 }
5822 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5823 }
5824 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005825 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005826 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005827 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005828 if( rc!=SQLITE_OK ){
5829 /* Use unixClose to clean up the resources added in fillInUnixFile
5830 ** and clear all the structure's references. Specifically,
5831 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5832 */
5833 unixClose(pFile);
5834 return rc;
5835 }
aswiftaebf4132008-11-21 00:10:35 +00005836 }
dane946c392009-08-22 11:39:46 +00005837 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005838 }
5839 }
5840#endif
5841
drhc02a43a2012-01-10 23:18:38 +00005842 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5843
dane946c392009-08-22 11:39:46 +00005844open_finished:
5845 if( rc!=SQLITE_OK ){
5846 sqlite3_free(p->pUnused);
5847 }
5848 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005849}
5850
dane946c392009-08-22 11:39:46 +00005851
danielk1977b4b47412007-08-17 15:53:36 +00005852/*
danielk1977fee2d252007-08-18 10:59:19 +00005853** Delete the file at zPath. If the dirSync argument is true, fsync()
5854** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005855*/
drh6b9d6dd2008-12-03 19:34:47 +00005856static int unixDelete(
5857 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5858 const char *zPath, /* Name of file to be deleted */
5859 int dirSync /* If true, fsync() directory after deleting file */
5860){
danielk1977fee2d252007-08-18 10:59:19 +00005861 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005862 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005863 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005864 if( osUnlink(zPath)==(-1) ){
5865 if( errno==ENOENT ){
5866 rc = SQLITE_IOERR_DELETE_NOENT;
5867 }else{
drhb4308162012-11-09 21:40:02 +00005868 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005869 }
drhb4308162012-11-09 21:40:02 +00005870 return rc;
drh5d4feff2010-07-14 01:45:22 +00005871 }
danielk1977d39fa702008-10-16 13:27:40 +00005872#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005873 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005874 int fd;
drh90315a22011-08-10 01:52:12 +00005875 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005876 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005877#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005878 if( fsync(fd)==-1 )
5879#else
5880 if( fsync(fd) )
5881#endif
5882 {
dane18d4952011-02-21 11:46:24 +00005883 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005884 }
drh0e9365c2011-03-02 02:08:13 +00005885 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005886 }else if( rc==SQLITE_CANTOPEN ){
5887 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005888 }
5889 }
danielk1977d138dd82008-10-15 16:02:48 +00005890#endif
danielk1977fee2d252007-08-18 10:59:19 +00005891 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005892}
5893
danielk197790949c22007-08-17 16:50:38 +00005894/*
mistachkin48864df2013-03-21 21:20:32 +00005895** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005896** test performed depends on the value of flags:
5897**
5898** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5899** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5900** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5901**
5902** Otherwise return 0.
5903*/
danielk1977861f7452008-06-05 11:39:11 +00005904static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005905 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5906 const char *zPath, /* Path of the file to examine */
5907 int flags, /* What do we want to learn about the zPath file? */
5908 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005909){
rse25c0d1a2007-09-20 08:38:14 +00005910 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005911 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005912 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005913 switch( flags ){
5914 case SQLITE_ACCESS_EXISTS:
5915 amode = F_OK;
5916 break;
5917 case SQLITE_ACCESS_READWRITE:
5918 amode = W_OK|R_OK;
5919 break;
drh50d3f902007-08-27 21:10:36 +00005920 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005921 amode = R_OK;
5922 break;
5923
5924 default:
5925 assert(!"Invalid flags argument");
5926 }
drh99ab3b12011-03-02 15:09:07 +00005927 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005928 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5929 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005930 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005931 *pResOut = 0;
5932 }
5933 }
danielk1977861f7452008-06-05 11:39:11 +00005934 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005935}
5936
danielk1977b4b47412007-08-17 15:53:36 +00005937
5938/*
5939** Turn a relative pathname into a full pathname. The relative path
5940** is stored as a nul-terminated string in the buffer pointed to by
5941** zPath.
5942**
5943** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5944** (in this case, MAX_PATHNAME bytes). The full-path is written to
5945** this buffer before returning.
5946*/
danielk1977adfb9b02007-09-17 07:02:56 +00005947static int unixFullPathname(
5948 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5949 const char *zPath, /* Possibly relative input path */
5950 int nOut, /* Size of output buffer in bytes */
5951 char *zOut /* Output buffer */
5952){
danielk1977843e65f2007-09-01 16:16:15 +00005953
5954 /* It's odd to simulate an io-error here, but really this is just
5955 ** using the io-error infrastructure to test that SQLite handles this
5956 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005957 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005958 */
5959 SimulateIOError( return SQLITE_ERROR );
5960
drh153c62c2007-08-24 03:51:33 +00005961 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005962 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005963
drh3c7f2dc2007-12-06 13:26:20 +00005964 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005965 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005966 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005967 }else{
5968 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005969 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005970 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005971 }
drhea678832008-12-10 19:26:22 +00005972 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005973 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005974 }
5975 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005976}
5977
drh0ccebe72005-06-07 22:22:50 +00005978
drh761df872006-12-21 01:29:22 +00005979#ifndef SQLITE_OMIT_LOAD_EXTENSION
5980/*
5981** Interfaces for opening a shared library, finding entry points
5982** within the shared library, and closing the shared library.
5983*/
5984#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005985static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5986 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005987 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5988}
danielk197795c8a542007-09-01 06:51:27 +00005989
5990/*
5991** SQLite calls this function immediately after a call to unixDlSym() or
5992** unixDlOpen() fails (returns a null pointer). If a more detailed error
5993** message is available, it is written to zBufOut. If no error message
5994** is available, zBufOut is left unmodified and SQLite uses a default
5995** error message.
5996*/
danielk1977397d65f2008-11-19 11:35:39 +00005997static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005998 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005999 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006000 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006001 zErr = dlerror();
6002 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006003 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006004 }
drh6c7d5c52008-11-21 20:32:33 +00006005 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006006}
drh1875f7a2008-12-08 18:19:17 +00006007static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6008 /*
6009 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6010 ** cast into a pointer to a function. And yet the library dlsym() routine
6011 ** returns a void* which is really a pointer to a function. So how do we
6012 ** use dlsym() with -pedantic-errors?
6013 **
6014 ** Variable x below is defined to be a pointer to a function taking
6015 ** parameters void* and const char* and returning a pointer to a function.
6016 ** We initialize x by assigning it a pointer to the dlsym() function.
6017 ** (That assignment requires a cast.) Then we call the function that
6018 ** x points to.
6019 **
6020 ** This work-around is unlikely to work correctly on any system where
6021 ** you really cannot cast a function pointer into void*. But then, on the
6022 ** other hand, dlsym() will not work on such a system either, so we have
6023 ** not really lost anything.
6024 */
6025 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006026 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006027 x = (void(*(*)(void*,const char*))(void))dlsym;
6028 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006029}
danielk1977397d65f2008-11-19 11:35:39 +00006030static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6031 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006032 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006033}
danielk1977b4b47412007-08-17 15:53:36 +00006034#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6035 #define unixDlOpen 0
6036 #define unixDlError 0
6037 #define unixDlSym 0
6038 #define unixDlClose 0
6039#endif
6040
6041/*
danielk197790949c22007-08-17 16:50:38 +00006042** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006043*/
danielk1977397d65f2008-11-19 11:35:39 +00006044static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6045 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006046 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006047
drhbbd42a62004-05-22 17:41:58 +00006048 /* We have to initialize zBuf to prevent valgrind from reporting
6049 ** errors. The reports issued by valgrind are incorrect - we would
6050 ** prefer that the randomness be increased by making use of the
6051 ** uninitialized space in zBuf - but valgrind errors tend to worry
6052 ** some users. Rather than argue, it seems easier just to initialize
6053 ** the whole array and silence valgrind, even if that means less randomness
6054 ** in the random seed.
6055 **
6056 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006057 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006058 ** tests repeatable.
6059 */
danielk1977b4b47412007-08-17 15:53:36 +00006060 memset(zBuf, 0, nBuf);
drhb00d8622014-01-01 15:18:36 +00006061 randomnessPid = getpid();
drhbbd42a62004-05-22 17:41:58 +00006062#if !defined(SQLITE_TEST)
6063 {
drhb00d8622014-01-01 15:18:36 +00006064 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006065 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006066 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006067 time_t t;
6068 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006069 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006070 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6071 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6072 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006073 }else{
drhc18b4042012-02-10 03:10:27 +00006074 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006075 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006076 }
drhbbd42a62004-05-22 17:41:58 +00006077 }
6078#endif
drh72cbd072008-10-14 17:58:38 +00006079 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006080}
6081
danielk1977b4b47412007-08-17 15:53:36 +00006082
drhbbd42a62004-05-22 17:41:58 +00006083/*
6084** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006085** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006086** The return value is the number of microseconds of sleep actually
6087** requested from the underlying operating system, a number which
6088** might be greater than or equal to the argument, but not less
6089** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006090*/
danielk1977397d65f2008-11-19 11:35:39 +00006091static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006092#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006093 struct timespec sp;
6094
6095 sp.tv_sec = microseconds / 1000000;
6096 sp.tv_nsec = (microseconds % 1000000) * 1000;
6097 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006098 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006099 return microseconds;
6100#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006101 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006102 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006103 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006104#else
danielk1977b4b47412007-08-17 15:53:36 +00006105 int seconds = (microseconds+999999)/1000000;
6106 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006107 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006108 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006109#endif
drh88f474a2006-01-02 20:00:12 +00006110}
6111
6112/*
drh6b9d6dd2008-12-03 19:34:47 +00006113** The following variable, if set to a non-zero value, is interpreted as
6114** the number of seconds since 1970 and is used to set the result of
6115** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006116*/
6117#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006118int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006119#endif
6120
6121/*
drhb7e8ea22010-05-03 14:32:30 +00006122** Find the current time (in Universal Coordinated Time). Write into *piNow
6123** the current time and date as a Julian Day number times 86_400_000. In
6124** other words, write into *piNow the number of milliseconds since the Julian
6125** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6126** proleptic Gregorian calendar.
6127**
drh31702252011-10-12 23:13:43 +00006128** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6129** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006130*/
6131static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6132 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006133 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006134#if defined(NO_GETTOD)
6135 time_t t;
6136 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006137 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006138#elif OS_VXWORKS
6139 struct timespec sNow;
6140 clock_gettime(CLOCK_REALTIME, &sNow);
6141 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6142#else
6143 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006144 if( gettimeofday(&sNow, 0)==0 ){
6145 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6146 }else{
6147 rc = SQLITE_ERROR;
6148 }
drhb7e8ea22010-05-03 14:32:30 +00006149#endif
6150
6151#ifdef SQLITE_TEST
6152 if( sqlite3_current_time ){
6153 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6154 }
6155#endif
6156 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006157 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006158}
6159
6160/*
drhbbd42a62004-05-22 17:41:58 +00006161** Find the current time (in Universal Coordinated Time). Write the
6162** current time and date as a Julian Day number into *prNow and
6163** return 0. Return 1 if the time and date cannot be found.
6164*/
danielk1977397d65f2008-11-19 11:35:39 +00006165static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006166 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006167 int rc;
drhff828942010-06-26 21:34:06 +00006168 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006169 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006170 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006171 return rc;
drhbbd42a62004-05-22 17:41:58 +00006172}
danielk1977b4b47412007-08-17 15:53:36 +00006173
drh6b9d6dd2008-12-03 19:34:47 +00006174/*
6175** We added the xGetLastError() method with the intention of providing
6176** better low-level error messages when operating-system problems come up
6177** during SQLite operation. But so far, none of that has been implemented
6178** in the core. So this routine is never called. For now, it is merely
6179** a place-holder.
6180*/
danielk1977397d65f2008-11-19 11:35:39 +00006181static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6182 UNUSED_PARAMETER(NotUsed);
6183 UNUSED_PARAMETER(NotUsed2);
6184 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006185 return 0;
6186}
6187
drhf2424c52010-04-26 00:04:55 +00006188
6189/*
drh734c9862008-11-28 15:37:20 +00006190************************ End of sqlite3_vfs methods ***************************
6191******************************************************************************/
6192
drh715ff302008-12-03 22:32:44 +00006193/******************************************************************************
6194************************** Begin Proxy Locking ********************************
6195**
6196** Proxy locking is a "uber-locking-method" in this sense: It uses the
6197** other locking methods on secondary lock files. Proxy locking is a
6198** meta-layer over top of the primitive locking implemented above. For
6199** this reason, the division that implements of proxy locking is deferred
6200** until late in the file (here) after all of the other I/O methods have
6201** been defined - so that the primitive locking methods are available
6202** as services to help with the implementation of proxy locking.
6203**
6204****
6205**
6206** The default locking schemes in SQLite use byte-range locks on the
6207** database file to coordinate safe, concurrent access by multiple readers
6208** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6209** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6210** as POSIX read & write locks over fixed set of locations (via fsctl),
6211** on AFP and SMB only exclusive byte-range locks are available via fsctl
6212** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6213** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6214** address in the shared range is taken for a SHARED lock, the entire
6215** shared range is taken for an EXCLUSIVE lock):
6216**
drhf2f105d2012-08-20 15:53:54 +00006217** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006218** RESERVED_BYTE 0x40000001
6219** SHARED_RANGE 0x40000002 -> 0x40000200
6220**
6221** This works well on the local file system, but shows a nearly 100x
6222** slowdown in read performance on AFP because the AFP client disables
6223** the read cache when byte-range locks are present. Enabling the read
6224** cache exposes a cache coherency problem that is present on all OS X
6225** supported network file systems. NFS and AFP both observe the
6226** close-to-open semantics for ensuring cache coherency
6227** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6228** address the requirements for concurrent database access by multiple
6229** readers and writers
6230** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6231**
6232** To address the performance and cache coherency issues, proxy file locking
6233** changes the way database access is controlled by limiting access to a
6234** single host at a time and moving file locks off of the database file
6235** and onto a proxy file on the local file system.
6236**
6237**
6238** Using proxy locks
6239** -----------------
6240**
6241** C APIs
6242**
6243** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6244** <proxy_path> | ":auto:");
6245** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6246**
6247**
6248** SQL pragmas
6249**
6250** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6251** PRAGMA [database.]lock_proxy_file
6252**
6253** Specifying ":auto:" means that if there is a conch file with a matching
6254** host ID in it, the proxy path in the conch file will be used, otherwise
6255** a proxy path based on the user's temp dir
6256** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6257** actual proxy file name is generated from the name and path of the
6258** database file. For example:
6259**
6260** For database path "/Users/me/foo.db"
6261** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6262**
6263** Once a lock proxy is configured for a database connection, it can not
6264** be removed, however it may be switched to a different proxy path via
6265** the above APIs (assuming the conch file is not being held by another
6266** connection or process).
6267**
6268**
6269** How proxy locking works
6270** -----------------------
6271**
6272** Proxy file locking relies primarily on two new supporting files:
6273**
6274** * conch file to limit access to the database file to a single host
6275** at a time
6276**
6277** * proxy file to act as a proxy for the advisory locks normally
6278** taken on the database
6279**
6280** The conch file - to use a proxy file, sqlite must first "hold the conch"
6281** by taking an sqlite-style shared lock on the conch file, reading the
6282** contents and comparing the host's unique host ID (see below) and lock
6283** proxy path against the values stored in the conch. The conch file is
6284** stored in the same directory as the database file and the file name
6285** is patterned after the database file name as ".<databasename>-conch".
6286** If the conch file does not exist, or it's contents do not match the
6287** host ID and/or proxy path, then the lock is escalated to an exclusive
6288** lock and the conch file contents is updated with the host ID and proxy
6289** path and the lock is downgraded to a shared lock again. If the conch
6290** is held by another process (with a shared lock), the exclusive lock
6291** will fail and SQLITE_BUSY is returned.
6292**
6293** The proxy file - a single-byte file used for all advisory file locks
6294** normally taken on the database file. This allows for safe sharing
6295** of the database file for multiple readers and writers on the same
6296** host (the conch ensures that they all use the same local lock file).
6297**
drh715ff302008-12-03 22:32:44 +00006298** Requesting the lock proxy does not immediately take the conch, it is
6299** only taken when the first request to lock database file is made.
6300** This matches the semantics of the traditional locking behavior, where
6301** opening a connection to a database file does not take a lock on it.
6302** The shared lock and an open file descriptor are maintained until
6303** the connection to the database is closed.
6304**
6305** The proxy file and the lock file are never deleted so they only need
6306** to be created the first time they are used.
6307**
6308** Configuration options
6309** ---------------------
6310**
6311** SQLITE_PREFER_PROXY_LOCKING
6312**
6313** Database files accessed on non-local file systems are
6314** automatically configured for proxy locking, lock files are
6315** named automatically using the same logic as
6316** PRAGMA lock_proxy_file=":auto:"
6317**
6318** SQLITE_PROXY_DEBUG
6319**
6320** Enables the logging of error messages during host id file
6321** retrieval and creation
6322**
drh715ff302008-12-03 22:32:44 +00006323** LOCKPROXYDIR
6324**
6325** Overrides the default directory used for lock proxy files that
6326** are named automatically via the ":auto:" setting
6327**
6328** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6329**
6330** Permissions to use when creating a directory for storing the
6331** lock proxy files, only used when LOCKPROXYDIR is not set.
6332**
6333**
6334** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6335** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6336** force proxy locking to be used for every database file opened, and 0
6337** will force automatic proxy locking to be disabled for all database
6338** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6339** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6340*/
6341
6342/*
6343** Proxy locking is only available on MacOSX
6344*/
drhd2cb50b2009-01-09 21:41:17 +00006345#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006346
drh715ff302008-12-03 22:32:44 +00006347/*
6348** The proxyLockingContext has the path and file structures for the remote
6349** and local proxy files in it
6350*/
6351typedef struct proxyLockingContext proxyLockingContext;
6352struct proxyLockingContext {
6353 unixFile *conchFile; /* Open conch file */
6354 char *conchFilePath; /* Name of the conch file */
6355 unixFile *lockProxy; /* Open proxy lock file */
6356 char *lockProxyPath; /* Name of the proxy lock file */
6357 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006358 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006359 void *oldLockingContext; /* Original lockingcontext to restore on close */
6360 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6361};
6362
drh7ed97b92010-01-20 13:07:21 +00006363/*
6364** The proxy lock file path for the database at dbPath is written into lPath,
6365** which must point to valid, writable memory large enough for a maxLen length
6366** file path.
drh715ff302008-12-03 22:32:44 +00006367*/
drh715ff302008-12-03 22:32:44 +00006368static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6369 int len;
6370 int dbLen;
6371 int i;
6372
6373#ifdef LOCKPROXYDIR
6374 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6375#else
6376# ifdef _CS_DARWIN_USER_TEMP_DIR
6377 {
drh7ed97b92010-01-20 13:07:21 +00006378 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006379 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6380 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006381 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006382 }
drh7ed97b92010-01-20 13:07:21 +00006383 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006384 }
6385# else
6386 len = strlcpy(lPath, "/tmp/", maxLen);
6387# endif
6388#endif
6389
6390 if( lPath[len-1]!='/' ){
6391 len = strlcat(lPath, "/", maxLen);
6392 }
6393
6394 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006395 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006396 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006397 char c = dbPath[i];
6398 lPath[i+len] = (c=='/')?'_':c;
6399 }
6400 lPath[i+len]='\0';
6401 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006402 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006403 return SQLITE_OK;
6404}
6405
drh7ed97b92010-01-20 13:07:21 +00006406/*
6407 ** Creates the lock file and any missing directories in lockPath
6408 */
6409static int proxyCreateLockPath(const char *lockPath){
6410 int i, len;
6411 char buf[MAXPATHLEN];
6412 int start = 0;
6413
6414 assert(lockPath!=NULL);
6415 /* try to create all the intermediate directories */
6416 len = (int)strlen(lockPath);
6417 buf[0] = lockPath[0];
6418 for( i=1; i<len; i++ ){
6419 if( lockPath[i] == '/' && (i - start > 0) ){
6420 /* only mkdir if leaf dir != "." or "/" or ".." */
6421 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6422 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6423 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006424 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006425 int err=errno;
6426 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006427 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006428 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006429 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006430 return err;
6431 }
6432 }
6433 }
6434 start=i+1;
6435 }
6436 buf[i] = lockPath[i];
6437 }
drh308c2a52010-05-14 11:30:18 +00006438 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006439 return 0;
6440}
6441
drh715ff302008-12-03 22:32:44 +00006442/*
6443** Create a new VFS file descriptor (stored in memory obtained from
6444** sqlite3_malloc) and open the file named "path" in the file descriptor.
6445**
6446** The caller is responsible not only for closing the file descriptor
6447** but also for freeing the memory associated with the file descriptor.
6448*/
drh7ed97b92010-01-20 13:07:21 +00006449static int proxyCreateUnixFile(
6450 const char *path, /* path for the new unixFile */
6451 unixFile **ppFile, /* unixFile created and returned by ref */
6452 int islockfile /* if non zero missing dirs will be created */
6453) {
6454 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006455 unixFile *pNew;
6456 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006457 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006458 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006459 int terrno = 0;
6460 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006461
drh7ed97b92010-01-20 13:07:21 +00006462 /* 1. first try to open/create the file
6463 ** 2. if that fails, and this is a lock file (not-conch), try creating
6464 ** the parent directories and then try again.
6465 ** 3. if that fails, try to open the file read-only
6466 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6467 */
6468 pUnused = findReusableFd(path, openFlags);
6469 if( pUnused ){
6470 fd = pUnused->fd;
6471 }else{
6472 pUnused = sqlite3_malloc(sizeof(*pUnused));
6473 if( !pUnused ){
6474 return SQLITE_NOMEM;
6475 }
6476 }
6477 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006478 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006479 terrno = errno;
6480 if( fd<0 && errno==ENOENT && islockfile ){
6481 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006482 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006483 }
6484 }
6485 }
6486 if( fd<0 ){
6487 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006488 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006489 terrno = errno;
6490 }
6491 if( fd<0 ){
6492 if( islockfile ){
6493 return SQLITE_BUSY;
6494 }
6495 switch (terrno) {
6496 case EACCES:
6497 return SQLITE_PERM;
6498 case EIO:
6499 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6500 default:
drh9978c972010-02-23 17:36:32 +00006501 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006502 }
6503 }
6504
6505 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6506 if( pNew==NULL ){
6507 rc = SQLITE_NOMEM;
6508 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006509 }
6510 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006511 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006512 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006513 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006514 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006515 pUnused->fd = fd;
6516 pUnused->flags = openFlags;
6517 pNew->pUnused = pUnused;
6518
drhc02a43a2012-01-10 23:18:38 +00006519 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006520 if( rc==SQLITE_OK ){
6521 *ppFile = pNew;
6522 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006523 }
drh7ed97b92010-01-20 13:07:21 +00006524end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006525 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006526 sqlite3_free(pNew);
6527 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006528 return rc;
6529}
6530
drh7ed97b92010-01-20 13:07:21 +00006531#ifdef SQLITE_TEST
6532/* simulate multiple hosts by creating unique hostid file paths */
6533int sqlite3_hostid_num = 0;
6534#endif
6535
6536#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6537
drh0ab216a2010-07-02 17:10:40 +00006538/* Not always defined in the headers as it ought to be */
6539extern int gethostuuid(uuid_t id, const struct timespec *wait);
6540
drh7ed97b92010-01-20 13:07:21 +00006541/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6542** bytes of writable memory.
6543*/
6544static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006545 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6546 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006547#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6548 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006549 {
6550 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6551 if( gethostuuid(pHostID, &timeout) ){
6552 int err = errno;
6553 if( pError ){
6554 *pError = err;
6555 }
6556 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006557 }
drh7ed97b92010-01-20 13:07:21 +00006558 }
drh3d4435b2011-08-26 20:55:50 +00006559#else
6560 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006561#endif
drh7ed97b92010-01-20 13:07:21 +00006562#ifdef SQLITE_TEST
6563 /* simulate multiple hosts by creating unique hostid file paths */
6564 if( sqlite3_hostid_num != 0){
6565 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6566 }
6567#endif
6568
6569 return SQLITE_OK;
6570}
6571
6572/* The conch file contains the header, host id and lock file path
6573 */
6574#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6575#define PROXY_HEADERLEN 1 /* conch file header length */
6576#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6577#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6578
6579/*
6580** Takes an open conch file, copies the contents to a new path and then moves
6581** it back. The newly created file's file descriptor is assigned to the
6582** conch file structure and finally the original conch file descriptor is
6583** closed. Returns zero if successful.
6584*/
6585static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6586 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6587 unixFile *conchFile = pCtx->conchFile;
6588 char tPath[MAXPATHLEN];
6589 char buf[PROXY_MAXCONCHLEN];
6590 char *cPath = pCtx->conchFilePath;
6591 size_t readLen = 0;
6592 size_t pathLen = 0;
6593 char errmsg[64] = "";
6594 int fd = -1;
6595 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006596 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006597
6598 /* create a new path by replace the trailing '-conch' with '-break' */
6599 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6600 if( pathLen>MAXPATHLEN || pathLen<6 ||
6601 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006602 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006603 goto end_breaklock;
6604 }
6605 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006606 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006607 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006608 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006609 goto end_breaklock;
6610 }
6611 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006612 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006613 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006614 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006615 goto end_breaklock;
6616 }
drhe562be52011-03-02 18:01:10 +00006617 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006618 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006619 goto end_breaklock;
6620 }
6621 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006622 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006623 goto end_breaklock;
6624 }
6625 rc = 0;
6626 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006627 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006628 conchFile->h = fd;
6629 conchFile->openFlags = O_RDWR | O_CREAT;
6630
6631end_breaklock:
6632 if( rc ){
6633 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006634 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006635 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006636 }
6637 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6638 }
6639 return rc;
6640}
6641
6642/* Take the requested lock on the conch file and break a stale lock if the
6643** host id matches.
6644*/
6645static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6646 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6647 unixFile *conchFile = pCtx->conchFile;
6648 int rc = SQLITE_OK;
6649 int nTries = 0;
6650 struct timespec conchModTime;
6651
drh3d4435b2011-08-26 20:55:50 +00006652 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006653 do {
6654 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6655 nTries ++;
6656 if( rc==SQLITE_BUSY ){
6657 /* If the lock failed (busy):
6658 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6659 * 2nd try: fail if the mod time changed or host id is different, wait
6660 * 10 sec and try again
6661 * 3rd try: break the lock unless the mod time has changed.
6662 */
6663 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006664 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006665 pFile->lastErrno = errno;
6666 return SQLITE_IOERR_LOCK;
6667 }
6668
6669 if( nTries==1 ){
6670 conchModTime = buf.st_mtimespec;
6671 usleep(500000); /* wait 0.5 sec and try the lock again*/
6672 continue;
6673 }
6674
6675 assert( nTries>1 );
6676 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6677 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6678 return SQLITE_BUSY;
6679 }
6680
6681 if( nTries==2 ){
6682 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006683 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006684 if( len<0 ){
6685 pFile->lastErrno = errno;
6686 return SQLITE_IOERR_LOCK;
6687 }
6688 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6689 /* don't break the lock if the host id doesn't match */
6690 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6691 return SQLITE_BUSY;
6692 }
6693 }else{
6694 /* don't break the lock on short read or a version mismatch */
6695 return SQLITE_BUSY;
6696 }
6697 usleep(10000000); /* wait 10 sec and try the lock again */
6698 continue;
6699 }
6700
6701 assert( nTries==3 );
6702 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6703 rc = SQLITE_OK;
6704 if( lockType==EXCLUSIVE_LOCK ){
6705 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6706 }
6707 if( !rc ){
6708 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6709 }
6710 }
6711 }
6712 } while( rc==SQLITE_BUSY && nTries<3 );
6713
6714 return rc;
6715}
6716
6717/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006718** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6719** lockPath means that the lockPath in the conch file will be used if the
6720** host IDs match, or a new lock path will be generated automatically
6721** and written to the conch file.
6722*/
6723static int proxyTakeConch(unixFile *pFile){
6724 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6725
drh7ed97b92010-01-20 13:07:21 +00006726 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006727 return SQLITE_OK;
6728 }else{
6729 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006730 uuid_t myHostID;
6731 int pError = 0;
6732 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006733 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006734 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006735 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006736 int createConch = 0;
6737 int hostIdMatch = 0;
6738 int readLen = 0;
6739 int tryOldLockPath = 0;
6740 int forceNewLockPath = 0;
6741
drh308c2a52010-05-14 11:30:18 +00006742 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6743 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006744
drh7ed97b92010-01-20 13:07:21 +00006745 rc = proxyGetHostID(myHostID, &pError);
6746 if( (rc&0xff)==SQLITE_IOERR ){
6747 pFile->lastErrno = pError;
6748 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006749 }
drh7ed97b92010-01-20 13:07:21 +00006750 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006751 if( rc!=SQLITE_OK ){
6752 goto end_takeconch;
6753 }
drh7ed97b92010-01-20 13:07:21 +00006754 /* read the existing conch file */
6755 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6756 if( readLen<0 ){
6757 /* I/O error: lastErrno set by seekAndRead */
6758 pFile->lastErrno = conchFile->lastErrno;
6759 rc = SQLITE_IOERR_READ;
6760 goto end_takeconch;
6761 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6762 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6763 /* a short read or version format mismatch means we need to create a new
6764 ** conch file.
6765 */
6766 createConch = 1;
6767 }
6768 /* if the host id matches and the lock path already exists in the conch
6769 ** we'll try to use the path there, if we can't open that path, we'll
6770 ** retry with a new auto-generated path
6771 */
6772 do { /* in case we need to try again for an :auto: named lock file */
6773
6774 if( !createConch && !forceNewLockPath ){
6775 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6776 PROXY_HOSTIDLEN);
6777 /* if the conch has data compare the contents */
6778 if( !pCtx->lockProxyPath ){
6779 /* for auto-named local lock file, just check the host ID and we'll
6780 ** use the local lock file path that's already in there
6781 */
6782 if( hostIdMatch ){
6783 size_t pathLen = (readLen - PROXY_PATHINDEX);
6784
6785 if( pathLen>=MAXPATHLEN ){
6786 pathLen=MAXPATHLEN-1;
6787 }
6788 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6789 lockPath[pathLen] = 0;
6790 tempLockPath = lockPath;
6791 tryOldLockPath = 1;
6792 /* create a copy of the lock path if the conch is taken */
6793 goto end_takeconch;
6794 }
6795 }else if( hostIdMatch
6796 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6797 readLen-PROXY_PATHINDEX)
6798 ){
6799 /* conch host and lock path match */
6800 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006801 }
drh7ed97b92010-01-20 13:07:21 +00006802 }
6803
6804 /* if the conch isn't writable and doesn't match, we can't take it */
6805 if( (conchFile->openFlags&O_RDWR) == 0 ){
6806 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006807 goto end_takeconch;
6808 }
drh7ed97b92010-01-20 13:07:21 +00006809
6810 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006811 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006812 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6813 tempLockPath = lockPath;
6814 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006815 }
drh7ed97b92010-01-20 13:07:21 +00006816
6817 /* update conch with host and path (this will fail if other process
6818 ** has a shared lock already), if the host id matches, use the big
6819 ** stick.
drh715ff302008-12-03 22:32:44 +00006820 */
drh7ed97b92010-01-20 13:07:21 +00006821 futimes(conchFile->h, NULL);
6822 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006823 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006824 /* We are trying for an exclusive lock but another thread in this
6825 ** same process is still holding a shared lock. */
6826 rc = SQLITE_BUSY;
6827 } else {
6828 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006829 }
drh715ff302008-12-03 22:32:44 +00006830 }else{
drh7ed97b92010-01-20 13:07:21 +00006831 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006832 }
drh7ed97b92010-01-20 13:07:21 +00006833 if( rc==SQLITE_OK ){
6834 char writeBuffer[PROXY_MAXCONCHLEN];
6835 int writeSize = 0;
6836
6837 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6838 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6839 if( pCtx->lockProxyPath!=NULL ){
6840 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6841 }else{
6842 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6843 }
6844 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006845 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006846 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6847 fsync(conchFile->h);
6848 /* If we created a new conch file (not just updated the contents of a
6849 ** valid conch file), try to match the permissions of the database
6850 */
6851 if( rc==SQLITE_OK && createConch ){
6852 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006853 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006854 if( err==0 ){
6855 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6856 S_IROTH|S_IWOTH);
6857 /* try to match the database file R/W permissions, ignore failure */
6858#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006859 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006860#else
drhff812312011-02-23 13:33:46 +00006861 do{
drhe562be52011-03-02 18:01:10 +00006862 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006863 }while( rc==(-1) && errno==EINTR );
6864 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006865 int code = errno;
6866 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6867 cmode, code, strerror(code));
6868 } else {
6869 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6870 }
6871 }else{
6872 int code = errno;
6873 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6874 err, code, strerror(code));
6875#endif
6876 }
drh715ff302008-12-03 22:32:44 +00006877 }
6878 }
drh7ed97b92010-01-20 13:07:21 +00006879 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6880
6881 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006882 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006883 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006884 int fd;
drh7ed97b92010-01-20 13:07:21 +00006885 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006886 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006887 }
6888 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006889 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006890 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006891 if( fd>=0 ){
6892 pFile->h = fd;
6893 }else{
drh9978c972010-02-23 17:36:32 +00006894 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006895 during locking */
6896 }
6897 }
6898 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6899 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6900 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6901 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6902 /* we couldn't create the proxy lock file with the old lock file path
6903 ** so try again via auto-naming
6904 */
6905 forceNewLockPath = 1;
6906 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006907 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006908 }
6909 }
6910 if( rc==SQLITE_OK ){
6911 /* Need to make a copy of path if we extracted the value
6912 ** from the conch file or the path was allocated on the stack
6913 */
6914 if( tempLockPath ){
6915 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6916 if( !pCtx->lockProxyPath ){
6917 rc = SQLITE_NOMEM;
6918 }
6919 }
6920 }
6921 if( rc==SQLITE_OK ){
6922 pCtx->conchHeld = 1;
6923
6924 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6925 afpLockingContext *afpCtx;
6926 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6927 afpCtx->dbPath = pCtx->lockProxyPath;
6928 }
6929 } else {
6930 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6931 }
drh308c2a52010-05-14 11:30:18 +00006932 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6933 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006934 return rc;
drh308c2a52010-05-14 11:30:18 +00006935 } while (1); /* in case we need to retry the :auto: lock file -
6936 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006937 }
6938}
6939
6940/*
6941** If pFile holds a lock on a conch file, then release that lock.
6942*/
6943static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006944 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006945 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6946 unixFile *conchFile; /* Name of the conch file */
6947
6948 pCtx = (proxyLockingContext *)pFile->lockingContext;
6949 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006950 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006951 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006952 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006953 if( pCtx->conchHeld>0 ){
6954 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6955 }
drh715ff302008-12-03 22:32:44 +00006956 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006957 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6958 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006959 return rc;
6960}
6961
6962/*
6963** Given the name of a database file, compute the name of its conch file.
6964** Store the conch filename in memory obtained from sqlite3_malloc().
6965** Make *pConchPath point to the new name. Return SQLITE_OK on success
6966** or SQLITE_NOMEM if unable to obtain memory.
6967**
6968** The caller is responsible for ensuring that the allocated memory
6969** space is eventually freed.
6970**
6971** *pConchPath is set to NULL if a memory allocation error occurs.
6972*/
6973static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6974 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006975 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006976 char *conchPath; /* buffer in which to construct conch name */
6977
6978 /* Allocate space for the conch filename and initialize the name to
6979 ** the name of the original database file. */
6980 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6981 if( conchPath==0 ){
6982 return SQLITE_NOMEM;
6983 }
6984 memcpy(conchPath, dbPath, len+1);
6985
6986 /* now insert a "." before the last / character */
6987 for( i=(len-1); i>=0; i-- ){
6988 if( conchPath[i]=='/' ){
6989 i++;
6990 break;
6991 }
6992 }
6993 conchPath[i]='.';
6994 while ( i<len ){
6995 conchPath[i+1]=dbPath[i];
6996 i++;
6997 }
6998
6999 /* append the "-conch" suffix to the file */
7000 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007001 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007002
7003 return SQLITE_OK;
7004}
7005
7006
7007/* Takes a fully configured proxy locking-style unix file and switches
7008** the local lock file path
7009*/
7010static int switchLockProxyPath(unixFile *pFile, const char *path) {
7011 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7012 char *oldPath = pCtx->lockProxyPath;
7013 int rc = SQLITE_OK;
7014
drh308c2a52010-05-14 11:30:18 +00007015 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007016 return SQLITE_BUSY;
7017 }
7018
7019 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7020 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7021 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7022 return SQLITE_OK;
7023 }else{
7024 unixFile *lockProxy = pCtx->lockProxy;
7025 pCtx->lockProxy=NULL;
7026 pCtx->conchHeld = 0;
7027 if( lockProxy!=NULL ){
7028 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7029 if( rc ) return rc;
7030 sqlite3_free(lockProxy);
7031 }
7032 sqlite3_free(oldPath);
7033 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7034 }
7035
7036 return rc;
7037}
7038
7039/*
7040** pFile is a file that has been opened by a prior xOpen call. dbPath
7041** is a string buffer at least MAXPATHLEN+1 characters in size.
7042**
7043** This routine find the filename associated with pFile and writes it
7044** int dbPath.
7045*/
7046static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007047#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007048 if( pFile->pMethod == &afpIoMethods ){
7049 /* afp style keeps a reference to the db path in the filePath field
7050 ** of the struct */
drhea678832008-12-10 19:26:22 +00007051 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007052 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
7053 } else
drh715ff302008-12-03 22:32:44 +00007054#endif
7055 if( pFile->pMethod == &dotlockIoMethods ){
7056 /* dot lock style uses the locking context to store the dot lock
7057 ** file path */
7058 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7059 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7060 }else{
7061 /* all other styles use the locking context to store the db file path */
7062 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007063 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007064 }
7065 return SQLITE_OK;
7066}
7067
7068/*
7069** Takes an already filled in unix file and alters it so all file locking
7070** will be performed on the local proxy lock file. The following fields
7071** are preserved in the locking context so that they can be restored and
7072** the unix structure properly cleaned up at close time:
7073** ->lockingContext
7074** ->pMethod
7075*/
7076static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7077 proxyLockingContext *pCtx;
7078 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7079 char *lockPath=NULL;
7080 int rc = SQLITE_OK;
7081
drh308c2a52010-05-14 11:30:18 +00007082 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007083 return SQLITE_BUSY;
7084 }
7085 proxyGetDbPathForUnixFile(pFile, dbPath);
7086 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7087 lockPath=NULL;
7088 }else{
7089 lockPath=(char *)path;
7090 }
7091
drh308c2a52010-05-14 11:30:18 +00007092 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7093 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007094
7095 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7096 if( pCtx==0 ){
7097 return SQLITE_NOMEM;
7098 }
7099 memset(pCtx, 0, sizeof(*pCtx));
7100
7101 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7102 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007103 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7104 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7105 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7106 ** (c) the file system is read-only, then enable no-locking access.
7107 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7108 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7109 */
7110 struct statfs fsInfo;
7111 struct stat conchInfo;
7112 int goLockless = 0;
7113
drh99ab3b12011-03-02 15:09:07 +00007114 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007115 int err = errno;
7116 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7117 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7118 }
7119 }
7120 if( goLockless ){
7121 pCtx->conchHeld = -1; /* read only FS/ lockless */
7122 rc = SQLITE_OK;
7123 }
7124 }
drh715ff302008-12-03 22:32:44 +00007125 }
7126 if( rc==SQLITE_OK && lockPath ){
7127 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7128 }
7129
7130 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007131 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7132 if( pCtx->dbPath==NULL ){
7133 rc = SQLITE_NOMEM;
7134 }
7135 }
7136 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007137 /* all memory is allocated, proxys are created and assigned,
7138 ** switch the locking context and pMethod then return.
7139 */
drh715ff302008-12-03 22:32:44 +00007140 pCtx->oldLockingContext = pFile->lockingContext;
7141 pFile->lockingContext = pCtx;
7142 pCtx->pOldMethod = pFile->pMethod;
7143 pFile->pMethod = &proxyIoMethods;
7144 }else{
7145 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007146 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007147 sqlite3_free(pCtx->conchFile);
7148 }
drhd56b1212010-08-11 06:14:15 +00007149 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007150 sqlite3_free(pCtx->conchFilePath);
7151 sqlite3_free(pCtx);
7152 }
drh308c2a52010-05-14 11:30:18 +00007153 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7154 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007155 return rc;
7156}
7157
7158
7159/*
7160** This routine handles sqlite3_file_control() calls that are specific
7161** to proxy locking.
7162*/
7163static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7164 switch( op ){
7165 case SQLITE_GET_LOCKPROXYFILE: {
7166 unixFile *pFile = (unixFile*)id;
7167 if( pFile->pMethod == &proxyIoMethods ){
7168 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7169 proxyTakeConch(pFile);
7170 if( pCtx->lockProxyPath ){
7171 *(const char **)pArg = pCtx->lockProxyPath;
7172 }else{
7173 *(const char **)pArg = ":auto: (not held)";
7174 }
7175 } else {
7176 *(const char **)pArg = NULL;
7177 }
7178 return SQLITE_OK;
7179 }
7180 case SQLITE_SET_LOCKPROXYFILE: {
7181 unixFile *pFile = (unixFile*)id;
7182 int rc = SQLITE_OK;
7183 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7184 if( pArg==NULL || (const char *)pArg==0 ){
7185 if( isProxyStyle ){
7186 /* turn off proxy locking - not supported */
7187 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7188 }else{
7189 /* turn off proxy locking - already off - NOOP */
7190 rc = SQLITE_OK;
7191 }
7192 }else{
7193 const char *proxyPath = (const char *)pArg;
7194 if( isProxyStyle ){
7195 proxyLockingContext *pCtx =
7196 (proxyLockingContext*)pFile->lockingContext;
7197 if( !strcmp(pArg, ":auto:")
7198 || (pCtx->lockProxyPath &&
7199 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7200 ){
7201 rc = SQLITE_OK;
7202 }else{
7203 rc = switchLockProxyPath(pFile, proxyPath);
7204 }
7205 }else{
7206 /* turn on proxy file locking */
7207 rc = proxyTransformUnixFile(pFile, proxyPath);
7208 }
7209 }
7210 return rc;
7211 }
7212 default: {
7213 assert( 0 ); /* The call assures that only valid opcodes are sent */
7214 }
7215 }
7216 /*NOTREACHED*/
7217 return SQLITE_ERROR;
7218}
7219
7220/*
7221** Within this division (the proxying locking implementation) the procedures
7222** above this point are all utilities. The lock-related methods of the
7223** proxy-locking sqlite3_io_method object follow.
7224*/
7225
7226
7227/*
7228** This routine checks if there is a RESERVED lock held on the specified
7229** file by this or any other process. If such a lock is held, set *pResOut
7230** to a non-zero value otherwise *pResOut is set to zero. The return value
7231** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7232*/
7233static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7234 unixFile *pFile = (unixFile*)id;
7235 int rc = proxyTakeConch(pFile);
7236 if( rc==SQLITE_OK ){
7237 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007238 if( pCtx->conchHeld>0 ){
7239 unixFile *proxy = pCtx->lockProxy;
7240 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7241 }else{ /* conchHeld < 0 is lockless */
7242 pResOut=0;
7243 }
drh715ff302008-12-03 22:32:44 +00007244 }
7245 return rc;
7246}
7247
7248/*
drh308c2a52010-05-14 11:30:18 +00007249** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007250** of the following:
7251**
7252** (1) SHARED_LOCK
7253** (2) RESERVED_LOCK
7254** (3) PENDING_LOCK
7255** (4) EXCLUSIVE_LOCK
7256**
7257** Sometimes when requesting one lock state, additional lock states
7258** are inserted in between. The locking might fail on one of the later
7259** transitions leaving the lock state different from what it started but
7260** still short of its goal. The following chart shows the allowed
7261** transitions and the inserted intermediate states:
7262**
7263** UNLOCKED -> SHARED
7264** SHARED -> RESERVED
7265** SHARED -> (PENDING) -> EXCLUSIVE
7266** RESERVED -> (PENDING) -> EXCLUSIVE
7267** PENDING -> EXCLUSIVE
7268**
7269** This routine will only increase a lock. Use the sqlite3OsUnlock()
7270** routine to lower a locking level.
7271*/
drh308c2a52010-05-14 11:30:18 +00007272static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007273 unixFile *pFile = (unixFile*)id;
7274 int rc = proxyTakeConch(pFile);
7275 if( rc==SQLITE_OK ){
7276 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007277 if( pCtx->conchHeld>0 ){
7278 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007279 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7280 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007281 }else{
7282 /* conchHeld < 0 is lockless */
7283 }
drh715ff302008-12-03 22:32:44 +00007284 }
7285 return rc;
7286}
7287
7288
7289/*
drh308c2a52010-05-14 11:30:18 +00007290** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007291** must be either NO_LOCK or SHARED_LOCK.
7292**
7293** If the locking level of the file descriptor is already at or below
7294** the requested locking level, this routine is a no-op.
7295*/
drh308c2a52010-05-14 11:30:18 +00007296static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007297 unixFile *pFile = (unixFile*)id;
7298 int rc = proxyTakeConch(pFile);
7299 if( rc==SQLITE_OK ){
7300 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007301 if( pCtx->conchHeld>0 ){
7302 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007303 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7304 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007305 }else{
7306 /* conchHeld < 0 is lockless */
7307 }
drh715ff302008-12-03 22:32:44 +00007308 }
7309 return rc;
7310}
7311
7312/*
7313** Close a file that uses proxy locks.
7314*/
7315static int proxyClose(sqlite3_file *id) {
7316 if( id ){
7317 unixFile *pFile = (unixFile*)id;
7318 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7319 unixFile *lockProxy = pCtx->lockProxy;
7320 unixFile *conchFile = pCtx->conchFile;
7321 int rc = SQLITE_OK;
7322
7323 if( lockProxy ){
7324 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7325 if( rc ) return rc;
7326 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7327 if( rc ) return rc;
7328 sqlite3_free(lockProxy);
7329 pCtx->lockProxy = 0;
7330 }
7331 if( conchFile ){
7332 if( pCtx->conchHeld ){
7333 rc = proxyReleaseConch(pFile);
7334 if( rc ) return rc;
7335 }
7336 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7337 if( rc ) return rc;
7338 sqlite3_free(conchFile);
7339 }
drhd56b1212010-08-11 06:14:15 +00007340 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007341 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007342 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007343 /* restore the original locking context and pMethod then close it */
7344 pFile->lockingContext = pCtx->oldLockingContext;
7345 pFile->pMethod = pCtx->pOldMethod;
7346 sqlite3_free(pCtx);
7347 return pFile->pMethod->xClose(id);
7348 }
7349 return SQLITE_OK;
7350}
7351
7352
7353
drhd2cb50b2009-01-09 21:41:17 +00007354#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007355/*
7356** The proxy locking style is intended for use with AFP filesystems.
7357** And since AFP is only supported on MacOSX, the proxy locking is also
7358** restricted to MacOSX.
7359**
7360**
7361******************* End of the proxy lock implementation **********************
7362******************************************************************************/
7363
drh734c9862008-11-28 15:37:20 +00007364/*
danielk1977e339d652008-06-28 11:23:00 +00007365** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007366**
7367** This routine registers all VFS implementations for unix-like operating
7368** systems. This routine, and the sqlite3_os_end() routine that follows,
7369** should be the only routines in this file that are visible from other
7370** files.
drh6b9d6dd2008-12-03 19:34:47 +00007371**
7372** This routine is called once during SQLite initialization and by a
7373** single thread. The memory allocation and mutex subsystems have not
7374** necessarily been initialized when this routine is called, and so they
7375** should not be used.
drh153c62c2007-08-24 03:51:33 +00007376*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007377int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007378 /*
7379 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007380 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7381 ** to the "finder" function. (pAppData is a pointer to a pointer because
7382 ** silly C90 rules prohibit a void* from being cast to a function pointer
7383 ** and so we have to go through the intermediate pointer to avoid problems
7384 ** when compiling with -pedantic-errors on GCC.)
7385 **
7386 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007387 ** finder-function. The finder-function returns a pointer to the
7388 ** sqlite_io_methods object that implements the desired locking
7389 ** behaviors. See the division above that contains the IOMETHODS
7390 ** macro for addition information on finder-functions.
7391 **
7392 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7393 ** object. But the "autolockIoFinder" available on MacOSX does a little
7394 ** more than that; it looks at the filesystem type that hosts the
7395 ** database file and tries to choose an locking method appropriate for
7396 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007397 */
drh7708e972008-11-29 00:56:52 +00007398 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007399 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007400 sizeof(unixFile), /* szOsFile */ \
7401 MAX_PATHNAME, /* mxPathname */ \
7402 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007403 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007404 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007405 unixOpen, /* xOpen */ \
7406 unixDelete, /* xDelete */ \
7407 unixAccess, /* xAccess */ \
7408 unixFullPathname, /* xFullPathname */ \
7409 unixDlOpen, /* xDlOpen */ \
7410 unixDlError, /* xDlError */ \
7411 unixDlSym, /* xDlSym */ \
7412 unixDlClose, /* xDlClose */ \
7413 unixRandomness, /* xRandomness */ \
7414 unixSleep, /* xSleep */ \
7415 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007416 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007417 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007418 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007419 unixGetSystemCall, /* xGetSystemCall */ \
7420 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007421 }
7422
drh6b9d6dd2008-12-03 19:34:47 +00007423 /*
7424 ** All default VFSes for unix are contained in the following array.
7425 **
7426 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7427 ** by the SQLite core when the VFS is registered. So the following
7428 ** array cannot be const.
7429 */
danielk1977e339d652008-06-28 11:23:00 +00007430 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007431#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007432 UNIXVFS("unix", autolockIoFinder ),
7433#else
7434 UNIXVFS("unix", posixIoFinder ),
7435#endif
7436 UNIXVFS("unix-none", nolockIoFinder ),
7437 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007438 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007439#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007440 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007441#endif
7442#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007443 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007444#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007445 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007446#endif
chw78a13182009-04-07 05:35:03 +00007447#endif
drhd2cb50b2009-01-09 21:41:17 +00007448#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007449 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007450 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007451 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007452#endif
drh153c62c2007-08-24 03:51:33 +00007453 };
drh6b9d6dd2008-12-03 19:34:47 +00007454 unsigned int i; /* Loop counter */
7455
drh2aa5a002011-04-13 13:42:25 +00007456 /* Double-check that the aSyscall[] array has been constructed
7457 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhd1ab8062013-03-25 20:50:25 +00007458 assert( ArraySize(aSyscall)==24 );
drh2aa5a002011-04-13 13:42:25 +00007459
drh6b9d6dd2008-12-03 19:34:47 +00007460 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007461 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007462 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007463 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007464 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007465}
danielk1977e339d652008-06-28 11:23:00 +00007466
7467/*
drh6b9d6dd2008-12-03 19:34:47 +00007468** Shutdown the operating system interface.
7469**
7470** Some operating systems might need to do some cleanup in this routine,
7471** to release dynamically allocated objects. But not on unix.
7472** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007473*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007474int sqlite3_os_end(void){
7475 return SQLITE_OK;
7476}
drhdce8bdb2007-08-16 13:01:44 +00007477
danielk197729bafea2008-06-26 10:41:19 +00007478#endif /* SQLITE_OS_UNIX */