blob: a90c8eede59faa5fad5a487b2d85f14255e229d1 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +0000122#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
drh1da88f02011-12-17 16:09:16 +0000125
danielk1977e339d652008-06-28 11:23:00 +0000126
drh40bbb0a2008-09-23 10:23:26 +0000127#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000128# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000129# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <semaphore.h>
131# include <limits.h>
132# else
drh9b35ea62008-11-29 02:20:26 +0000133# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000135# endif
drhbfe66312006-10-03 17:40:40 +0000136#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000137
drhf8b4d8c2010-03-05 13:53:22 +0000138#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000139# include <sys/mount.h>
140#endif
141
drhdbe4b882011-06-20 18:00:17 +0000142#ifdef HAVE_UTIME
143# include <utime.h>
144#endif
145
drh9cbe6352005-11-29 03:13:21 +0000146/*
drh7ed97b92010-01-20 13:07:21 +0000147** Allowed values of unixFile.fsFlags
148*/
149#define SQLITE_FSFLAGS_IS_MSDOS 0x1
150
151/*
drhf1a221e2006-01-15 17:27:17 +0000152** If we are to be thread-safe, include the pthreads header and define
153** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000154*/
drhd677b3d2007-08-20 22:48:41 +0000155#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000156# include <pthread.h>
157# define SQLITE_UNIX_THREADS 1
158#endif
159
160/*
161** Default permissions when creating a new file
162*/
163#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
164# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
165#endif
166
danielk1977b4b47412007-08-17 15:53:36 +0000167/*
drh5adc60b2012-04-14 13:25:11 +0000168** Default permissions when creating auto proxy dir
169*/
aswiftaebf4132008-11-21 00:10:35 +0000170#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
171# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
172#endif
173
174/*
danielk1977b4b47412007-08-17 15:53:36 +0000175** Maximum supported path-length.
176*/
177#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000178
drh734c9862008-11-28 15:37:20 +0000179/*
drh734c9862008-11-28 15:37:20 +0000180** Only set the lastErrno if the error code is a real error and not
181** a normal expected return code of SQLITE_BUSY or SQLITE_OK
182*/
183#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
184
drhd91c68f2010-05-14 14:52:25 +0000185/* Forward references */
186typedef struct unixShm unixShm; /* Connection shared memory */
187typedef struct unixShmNode unixShmNode; /* Shared memory instance */
188typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
189typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000190
191/*
dane946c392009-08-22 11:39:46 +0000192** Sometimes, after a file handle is closed by SQLite, the file descriptor
193** cannot be closed immediately. In these cases, instances of the following
194** structure are used to store the file descriptor while waiting for an
195** opportunity to either close or reuse it.
196*/
dane946c392009-08-22 11:39:46 +0000197struct UnixUnusedFd {
198 int fd; /* File descriptor to close */
199 int flags; /* Flags this file descriptor was opened with */
200 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
201};
202
203/*
drh9b35ea62008-11-29 02:20:26 +0000204** The unixFile structure is subclass of sqlite3_file specific to the unix
205** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000206*/
drh054889e2005-11-30 03:20:31 +0000207typedef struct unixFile unixFile;
208struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000209 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000210 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000211 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000212 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000213 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000214 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000215 int lastErrno; /* The unix errno from last I/O error */
216 void *lockingContext; /* Locking style specific state */
217 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000218 const char *zPath; /* Name of the file */
219 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000220 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000221#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000222 int nFetchOut; /* Number of outstanding xFetch refs */
223 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000224 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
225 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000226 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000227#endif
drh537dddf2012-10-26 13:46:24 +0000228#ifdef __QNXNTO__
229 int sectorSize; /* Device sector size */
230 int deviceCharacteristics; /* Precomputed device characteristics */
231#endif
drh08c6d442009-02-09 17:34:07 +0000232#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000233 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000234#endif
drh7ed97b92010-01-20 13:07:21 +0000235#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000236 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000237#endif
238#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000239 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000240#endif
drhd3d8c042012-05-29 17:02:40 +0000241#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000242 /* The next group of variables are used to track whether or not the
243 ** transaction counter in bytes 24-27 of database files are updated
244 ** whenever any part of the database changes. An assertion fault will
245 ** occur if a file is updated without also updating the transaction
246 ** counter. This test is made to avoid new problems similar to the
247 ** one described by ticket #3584.
248 */
249 unsigned char transCntrChng; /* True if the transaction counter changed */
250 unsigned char dbUpdate; /* True if any part of database file changed */
251 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000252
drh8f941bc2009-01-14 23:03:40 +0000253#endif
danf23da962013-03-23 21:00:41 +0000254
danielk1977967a4a12007-08-20 14:23:44 +0000255#ifdef SQLITE_TEST
256 /* In test mode, increase the size of this structure a bit so that
257 ** it is larger than the struct CrashFile defined in test6.c.
258 */
259 char aPadding[32];
260#endif
drh9cbe6352005-11-29 03:13:21 +0000261};
262
drh0ccebe72005-06-07 22:22:50 +0000263/*
drha7e61d82011-03-12 17:02:57 +0000264** Allowed values for the unixFile.ctrlFlags bitmask:
265*/
drhf0b190d2011-07-26 16:03:07 +0000266#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
267#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
268#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000269#ifndef SQLITE_DISABLE_DIRSYNC
270# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
271#else
272# define UNIXFILE_DIRSYNC 0x00
273#endif
drhcb15f352011-12-23 01:04:17 +0000274#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000275#define UNIXFILE_DELETE 0x20 /* Delete on close */
276#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
277#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhfbc7e882013-04-11 01:16:15 +0000278#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
drha7e61d82011-03-12 17:02:57 +0000279
280/*
drh198bf392006-01-06 21:52:49 +0000281** Include code that is common to all os_*.c files
282*/
283#include "os_common.h"
284
285/*
drh0ccebe72005-06-07 22:22:50 +0000286** Define various macros that are missing from some systems.
287*/
drhbbd42a62004-05-22 17:41:58 +0000288#ifndef O_LARGEFILE
289# define O_LARGEFILE 0
290#endif
291#ifdef SQLITE_DISABLE_LFS
292# undef O_LARGEFILE
293# define O_LARGEFILE 0
294#endif
295#ifndef O_NOFOLLOW
296# define O_NOFOLLOW 0
297#endif
298#ifndef O_BINARY
299# define O_BINARY 0
300#endif
301
302/*
drh2b4b5962005-06-15 17:47:55 +0000303** The threadid macro resolves to the thread-id or to 0. Used for
304** testing and debugging only.
305*/
drhd677b3d2007-08-20 22:48:41 +0000306#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000307#define threadid pthread_self()
308#else
309#define threadid 0
310#endif
311
drh99ab3b12011-03-02 15:09:07 +0000312/*
dane6ecd662013-04-01 17:56:59 +0000313** HAVE_MREMAP defaults to true on Linux and false everywhere else.
314*/
315#if !defined(HAVE_MREMAP)
316# if defined(__linux__) && defined(_GNU_SOURCE)
317# define HAVE_MREMAP 1
318# else
319# define HAVE_MREMAP 0
320# endif
321#endif
322
323/*
drh9a3baf12011-04-25 18:01:27 +0000324** Different Unix systems declare open() in different ways. Same use
325** open(const char*,int,mode_t). Others use open(const char*,int,...).
326** The difference is important when using a pointer to the function.
327**
328** The safest way to deal with the problem is to always use this wrapper
329** which always has the same well-defined interface.
330*/
331static int posixOpen(const char *zFile, int flags, int mode){
332 return open(zFile, flags, mode);
333}
334
drhed466822012-05-31 13:10:49 +0000335/*
336** On some systems, calls to fchown() will trigger a message in a security
337** log if they come from non-root processes. So avoid calling fchown() if
338** we are not running as root.
339*/
340static int posixFchown(int fd, uid_t uid, gid_t gid){
341 return geteuid() ? 0 : fchown(fd,uid,gid);
342}
343
drh90315a22011-08-10 01:52:12 +0000344/* Forward reference */
345static int openDirectory(const char*, int*);
346
drh9a3baf12011-04-25 18:01:27 +0000347/*
drh99ab3b12011-03-02 15:09:07 +0000348** Many system calls are accessed through pointer-to-functions so that
349** they may be overridden at runtime to facilitate fault injection during
350** testing and sandboxing. The following array holds the names and pointers
351** to all overrideable system calls.
352*/
353static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000354 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000355 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
356 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000357} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000358 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
359#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000360
drh58ad5802011-03-23 22:02:23 +0000361 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000362#define osClose ((int(*)(int))aSyscall[1].pCurrent)
363
drh58ad5802011-03-23 22:02:23 +0000364 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000365#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
366
drh58ad5802011-03-23 22:02:23 +0000367 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
369
drh58ad5802011-03-23 22:02:23 +0000370 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
372
373/*
374** The DJGPP compiler environment looks mostly like Unix, but it
375** lacks the fcntl() system call. So redefine fcntl() to be something
376** that always succeeds. This means that locking does not occur under
377** DJGPP. But it is DOS - what did you expect?
378*/
379#ifdef __DJGPP__
380 { "fstat", 0, 0 },
381#define osFstat(a,b,c) 0
382#else
drh58ad5802011-03-23 22:02:23 +0000383 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000384#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
385#endif
386
drh58ad5802011-03-23 22:02:23 +0000387 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000388#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
389
drh58ad5802011-03-23 22:02:23 +0000390 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000391#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000392
drh58ad5802011-03-23 22:02:23 +0000393 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000394#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
395
drhd4a80312011-04-15 14:33:20 +0000396#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000397 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000398#else
drh58ad5802011-03-23 22:02:23 +0000399 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000400#endif
401#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
402
403#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000404 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000405#else
drh58ad5802011-03-23 22:02:23 +0000406 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000407#endif
408#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
409
drh58ad5802011-03-23 22:02:23 +0000410 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000411#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
412
drhd4a80312011-04-15 14:33:20 +0000413#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000414 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000415#else
drh58ad5802011-03-23 22:02:23 +0000416 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000417#endif
418#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
419 aSyscall[12].pCurrent)
420
421#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000422 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000423#else
drh58ad5802011-03-23 22:02:23 +0000424 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000425#endif
426#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
427 aSyscall[13].pCurrent)
428
drh58ad5802011-03-23 22:02:23 +0000429 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000430#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000431
432#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000433 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000434#else
drh58ad5802011-03-23 22:02:23 +0000435 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000436#endif
dan0fd7d862011-03-29 10:04:23 +0000437#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000438
drh036ac7f2011-08-08 23:18:05 +0000439 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
440#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
441
drh90315a22011-08-10 01:52:12 +0000442 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
443#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
444
drh9ef6bc42011-11-04 02:24:02 +0000445 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
446#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
447
448 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
449#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
450
drhed466822012-05-31 13:10:49 +0000451 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000452#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000453
dan4dd51442013-08-26 14:30:25 +0000454#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000455 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
456#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
457
drhd1ab8062013-03-25 20:50:25 +0000458 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
459#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
460
dane6ecd662013-04-01 17:56:59 +0000461#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000462 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
463#else
464 { "mremap", (sqlite3_syscall_ptr)0, 0 },
465#endif
466#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
dan4dd51442013-08-26 14:30:25 +0000467#endif
drhd1ab8062013-03-25 20:50:25 +0000468
drhe562be52011-03-02 18:01:10 +0000469}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000470
471/*
472** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000473** "unix" VFSes. Return SQLITE_OK opon successfully updating the
474** system call pointer, or SQLITE_NOTFOUND if there is no configurable
475** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000476*/
477static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000478 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
479 const char *zName, /* Name of system call to override */
480 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000481){
drh58ad5802011-03-23 22:02:23 +0000482 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000483 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000484
485 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000486 if( zName==0 ){
487 /* If no zName is given, restore all system calls to their default
488 ** settings and return NULL
489 */
dan51438a72011-04-02 17:00:47 +0000490 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000491 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
492 if( aSyscall[i].pDefault ){
493 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000494 }
495 }
496 }else{
497 /* If zName is specified, operate on only the one system call
498 ** specified.
499 */
500 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
501 if( strcmp(zName, aSyscall[i].zName)==0 ){
502 if( aSyscall[i].pDefault==0 ){
503 aSyscall[i].pDefault = aSyscall[i].pCurrent;
504 }
drh1df30962011-03-02 19:06:42 +0000505 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000506 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
507 aSyscall[i].pCurrent = pNewFunc;
508 break;
509 }
510 }
511 }
512 return rc;
513}
514
drh1df30962011-03-02 19:06:42 +0000515/*
516** Return the value of a system call. Return NULL if zName is not a
517** recognized system call name. NULL is also returned if the system call
518** is currently undefined.
519*/
drh58ad5802011-03-23 22:02:23 +0000520static sqlite3_syscall_ptr unixGetSystemCall(
521 sqlite3_vfs *pNotUsed,
522 const char *zName
523){
524 unsigned int i;
525
526 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000527 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
528 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
529 }
530 return 0;
531}
532
533/*
534** Return the name of the first system call after zName. If zName==NULL
535** then return the name of the first system call. Return NULL if zName
536** is the last system call or if zName is not the name of a valid
537** system call.
538*/
539static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000540 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000541
542 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000543 if( zName ){
544 for(i=0; i<ArraySize(aSyscall)-1; i++){
545 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000546 }
547 }
dan0fd7d862011-03-29 10:04:23 +0000548 for(i++; i<ArraySize(aSyscall); i++){
549 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000550 }
551 return 0;
552}
553
drhad4f1e52011-03-04 15:43:57 +0000554/*
drh35a03792013-08-29 23:34:53 +0000555** If fd is a file descriptor that would be dangerous to use for an
556** ordinary file, the close it, reopen it as /dev/null to get it out
557** of the way, then return true.
558**
559** If fd is safe, return 0.
560**
561** It is dangerous to have a database file open of file descriptors 1 or
562** 2 because those normally mean standard output and standard error. Other
563** components of the system might write directly to those file descriptors
564** and overwrite parts of the database file. Something like this happened
565** on 2013-08-29 to the canonical Fossil repository when some error caused
566** the database file to be opened on file descriptor 2 and later an assert()
567** fired and wrote error message text into file descriptor 2, corrupting
568** the repository.
569*/
570static int isReservedFd(int fd, const char *z, int f, int m){
571 if( fd<0 || fd>2 ) return 0;
572 sqlite3_log(SQLITE_WARNING,
573 "attempt to open \"%s\" as file descriptor %d", z, fd);
574 osClose(fd);
575 (void)osOpen("/dev/null",f,m);
576 return 1;
577}
578
579/*
drh8c815d12012-02-13 20:16:37 +0000580** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000581** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000582**
583** If the file creation mode "m" is 0 then set it to the default for
584** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
585** 0644) as modified by the system umask. If m is not 0, then
586** make the file creation mode be exactly m ignoring the umask.
587**
588** The m parameter will be non-zero only when creating -wal, -journal,
589** and -shm files. We want those files to have *exactly* the same
590** permissions as their original database, unadulterated by the umask.
591** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
592** transaction crashes and leaves behind hot journals, then any
593** process that is able to write to the database will also be able to
594** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000595*/
drh8c815d12012-02-13 20:16:37 +0000596static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000597 int fd;
drhe1186ab2013-01-04 20:45:13 +0000598 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5adc60b2012-04-14 13:25:11 +0000599 do{
600#if defined(O_CLOEXEC)
601 fd = osOpen(z,f|O_CLOEXEC,m2);
602#else
603 fd = osOpen(z,f,m2);
604#endif
drh35a03792013-08-29 23:34:53 +0000605 }while( (fd<0 && errno==EINTR) || isReservedFd(fd,z,f,m2) );
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
aswift5b1a2562008-08-22 00:22:35 +00001324
1325/*
drhfbc7e882013-04-11 01:16:15 +00001326** Check a unixFile that is a database. Verify the following:
1327**
1328** (1) There is exactly one hard link on the file
1329** (2) The file is not a symbolic link
1330** (3) The file has not been renamed or unlinked
1331**
1332** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1333*/
1334static void verifyDbFile(unixFile *pFile){
1335 struct stat buf;
1336 int rc;
1337 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1338 /* One or more of the following warnings have already been issued. Do not
1339 ** repeat them so as not to clutter the error log */
1340 return;
1341 }
1342 rc = osFstat(pFile->h, &buf);
1343 if( rc!=0 ){
1344 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1345 pFile->ctrlFlags |= UNIXFILE_WARNED;
1346 return;
1347 }
1348 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
1349 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1350 pFile->ctrlFlags |= UNIXFILE_WARNED;
1351 return;
1352 }
1353 if( buf.st_nlink>1 ){
1354 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1355 pFile->ctrlFlags |= UNIXFILE_WARNED;
1356 return;
1357 }
1358 if( pFile->pInode!=0
1359 && ((rc = osStat(pFile->zPath, &buf))!=0
1360 || buf.st_ino!=pFile->pInode->fileId.ino)
1361 ){
1362 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1363 pFile->ctrlFlags |= UNIXFILE_WARNED;
1364 return;
1365 }
1366}
1367
1368
1369/*
danielk197713adf8a2004-06-03 16:08:41 +00001370** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001371** file by this or any other process. If such a lock is held, set *pResOut
1372** to a non-zero value otherwise *pResOut is set to zero. The return value
1373** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001374*/
danielk1977861f7452008-06-05 11:39:11 +00001375static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001376 int rc = SQLITE_OK;
1377 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001378 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001379
danielk1977861f7452008-06-05 11:39:11 +00001380 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1381
drh054889e2005-11-30 03:20:31 +00001382 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001383 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001384
1385 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001386 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001387 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001388 }
1389
drh2ac3ee92004-06-07 16:27:46 +00001390 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001391 */
danielk197709480a92009-02-09 05:32:32 +00001392#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001393 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001394 struct flock lock;
1395 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001396 lock.l_start = RESERVED_BYTE;
1397 lock.l_len = 1;
1398 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001399 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1400 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1401 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001402 } else if( lock.l_type!=F_UNLCK ){
1403 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001404 }
1405 }
danielk197709480a92009-02-09 05:32:32 +00001406#endif
danielk197713adf8a2004-06-03 16:08:41 +00001407
drh6c7d5c52008-11-21 20:32:33 +00001408 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001409 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001410
aswift5b1a2562008-08-22 00:22:35 +00001411 *pResOut = reserved;
1412 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001413}
1414
1415/*
drha7e61d82011-03-12 17:02:57 +00001416** Attempt to set a system-lock on the file pFile. The lock is
1417** described by pLock.
1418**
drh77197112011-03-15 19:08:48 +00001419** If the pFile was opened read/write from unix-excl, then the only lock
1420** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001421** the first time any lock is attempted. All subsequent system locking
1422** operations become no-ops. Locking operations still happen internally,
1423** in order to coordinate access between separate database connections
1424** within this process, but all of that is handled in memory and the
1425** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001426**
1427** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1428** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1429** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001430**
1431** Zero is returned if the call completes successfully, or -1 if a call
1432** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001433*/
1434static int unixFileLock(unixFile *pFile, struct flock *pLock){
1435 int rc;
drh3cb93392011-03-12 18:10:44 +00001436 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001437 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001438 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001439 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1440 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1441 ){
drh3cb93392011-03-12 18:10:44 +00001442 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001443 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001444 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001445 lock.l_whence = SEEK_SET;
1446 lock.l_start = SHARED_FIRST;
1447 lock.l_len = SHARED_SIZE;
1448 lock.l_type = F_WRLCK;
1449 rc = osFcntl(pFile->h, F_SETLK, &lock);
1450 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001451 pInode->bProcessLock = 1;
1452 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001453 }else{
1454 rc = 0;
1455 }
1456 }else{
1457 rc = osFcntl(pFile->h, F_SETLK, pLock);
1458 }
1459 return rc;
1460}
1461
1462/*
drh308c2a52010-05-14 11:30:18 +00001463** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001464** of the following:
1465**
drh2ac3ee92004-06-07 16:27:46 +00001466** (1) SHARED_LOCK
1467** (2) RESERVED_LOCK
1468** (3) PENDING_LOCK
1469** (4) EXCLUSIVE_LOCK
1470**
drhb3e04342004-06-08 00:47:47 +00001471** Sometimes when requesting one lock state, additional lock states
1472** are inserted in between. The locking might fail on one of the later
1473** transitions leaving the lock state different from what it started but
1474** still short of its goal. The following chart shows the allowed
1475** transitions and the inserted intermediate states:
1476**
1477** UNLOCKED -> SHARED
1478** SHARED -> RESERVED
1479** SHARED -> (PENDING) -> EXCLUSIVE
1480** RESERVED -> (PENDING) -> EXCLUSIVE
1481** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001482**
drha6abd042004-06-09 17:37:22 +00001483** This routine will only increase a lock. Use the sqlite3OsUnlock()
1484** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001485*/
drh308c2a52010-05-14 11:30:18 +00001486static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001487 /* The following describes the implementation of the various locks and
1488 ** lock transitions in terms of the POSIX advisory shared and exclusive
1489 ** lock primitives (called read-locks and write-locks below, to avoid
1490 ** confusion with SQLite lock names). The algorithms are complicated
1491 ** slightly in order to be compatible with windows systems simultaneously
1492 ** accessing the same database file, in case that is ever required.
1493 **
1494 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1495 ** byte', each single bytes at well known offsets, and the 'shared byte
1496 ** range', a range of 510 bytes at a well known offset.
1497 **
1498 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1499 ** byte'. If this is successful, a random byte from the 'shared byte
1500 ** range' is read-locked and the lock on the 'pending byte' released.
1501 **
danielk197790ba3bd2004-06-25 08:32:25 +00001502 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1503 ** A RESERVED lock is implemented by grabbing a write-lock on the
1504 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001505 **
1506 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001507 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1508 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1509 ** obtained, but existing SHARED locks are allowed to persist. A process
1510 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1511 ** This property is used by the algorithm for rolling back a journal file
1512 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001513 **
danielk197790ba3bd2004-06-25 08:32:25 +00001514 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1515 ** implemented by obtaining a write-lock on the entire 'shared byte
1516 ** range'. Since all other locks require a read-lock on one of the bytes
1517 ** within this range, this ensures that no other locks are held on the
1518 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001519 **
1520 ** The reason a single byte cannot be used instead of the 'shared byte
1521 ** range' is that some versions of windows do not support read-locks. By
1522 ** locking a random byte from a range, concurrent SHARED locks may exist
1523 ** even if the locking primitive used is always a write-lock.
1524 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001525 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001526 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001527 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001528 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001529 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001530
drh054889e2005-11-30 03:20:31 +00001531 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001532 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1533 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001534 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001535
1536 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001537 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001538 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001539 */
drh308c2a52010-05-14 11:30:18 +00001540 if( pFile->eFileLock>=eFileLock ){
1541 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1542 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001543 return SQLITE_OK;
1544 }
1545
drh0c2694b2009-09-03 16:23:44 +00001546 /* Make sure the locking sequence is correct.
1547 ** (1) We never move from unlocked to anything higher than shared lock.
1548 ** (2) SQLite never explicitly requests a pendig lock.
1549 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001550 */
drh308c2a52010-05-14 11:30:18 +00001551 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1552 assert( eFileLock!=PENDING_LOCK );
1553 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001554
drh8af6c222010-05-14 12:43:01 +00001555 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001556 */
drh6c7d5c52008-11-21 20:32:33 +00001557 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001558 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001559
danielk1977ad94b582007-08-20 06:44:22 +00001560 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001561 ** handle that precludes the requested lock, return BUSY.
1562 */
drh8af6c222010-05-14 12:43:01 +00001563 if( (pFile->eFileLock!=pInode->eFileLock &&
1564 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001565 ){
1566 rc = SQLITE_BUSY;
1567 goto end_lock;
1568 }
1569
1570 /* If a SHARED lock is requested, and some thread using this PID already
1571 ** has a SHARED or RESERVED lock, then increment reference counts and
1572 ** return SQLITE_OK.
1573 */
drh308c2a52010-05-14 11:30:18 +00001574 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001575 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001576 assert( eFileLock==SHARED_LOCK );
1577 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001578 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001579 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001580 pInode->nShared++;
1581 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001582 goto end_lock;
1583 }
1584
danielk19779a1d0ab2004-06-01 14:09:28 +00001585
drh3cde3bb2004-06-12 02:17:14 +00001586 /* A PENDING lock is needed before acquiring a SHARED lock and before
1587 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1588 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001589 */
drh0c2694b2009-09-03 16:23:44 +00001590 lock.l_len = 1L;
1591 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001592 if( eFileLock==SHARED_LOCK
1593 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001594 ){
drh308c2a52010-05-14 11:30:18 +00001595 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001596 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001597 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001598 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001599 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001600 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001601 pFile->lastErrno = tErrno;
1602 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001603 goto end_lock;
1604 }
drh3cde3bb2004-06-12 02:17:14 +00001605 }
1606
1607
1608 /* If control gets to this point, then actually go ahead and make
1609 ** operating system calls for the specified lock.
1610 */
drh308c2a52010-05-14 11:30:18 +00001611 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001612 assert( pInode->nShared==0 );
1613 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001614 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001615
drh2ac3ee92004-06-07 16:27:46 +00001616 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001617 lock.l_start = SHARED_FIRST;
1618 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001619 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001620 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001621 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001622 }
dan661d71a2011-03-30 19:08:03 +00001623
drh2ac3ee92004-06-07 16:27:46 +00001624 /* Drop the temporary PENDING lock */
1625 lock.l_start = PENDING_BYTE;
1626 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001627 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001628 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1629 /* This could happen with a network mount */
1630 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001631 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001632 }
dan661d71a2011-03-30 19:08:03 +00001633
1634 if( rc ){
1635 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001636 pFile->lastErrno = tErrno;
1637 }
dan661d71a2011-03-30 19:08:03 +00001638 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001639 }else{
drh308c2a52010-05-14 11:30:18 +00001640 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001641 pInode->nLock++;
1642 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001643 }
drh8af6c222010-05-14 12:43:01 +00001644 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001645 /* We are trying for an exclusive lock but another thread in this
1646 ** same process is still holding a shared lock. */
1647 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001648 }else{
drh3cde3bb2004-06-12 02:17:14 +00001649 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001650 ** assumed that there is a SHARED or greater lock on the file
1651 ** already.
1652 */
drh308c2a52010-05-14 11:30:18 +00001653 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001654 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001655
1656 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1657 if( eFileLock==RESERVED_LOCK ){
1658 lock.l_start = RESERVED_BYTE;
1659 lock.l_len = 1L;
1660 }else{
1661 lock.l_start = SHARED_FIRST;
1662 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001663 }
dan661d71a2011-03-30 19:08:03 +00001664
1665 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001666 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001667 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001668 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001669 pFile->lastErrno = tErrno;
1670 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001671 }
drhbbd42a62004-05-22 17:41:58 +00001672 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001673
drh8f941bc2009-01-14 23:03:40 +00001674
drhd3d8c042012-05-29 17:02:40 +00001675#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001676 /* Set up the transaction-counter change checking flags when
1677 ** transitioning from a SHARED to a RESERVED lock. The change
1678 ** from SHARED to RESERVED marks the beginning of a normal
1679 ** write operation (not a hot journal rollback).
1680 */
1681 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001682 && pFile->eFileLock<=SHARED_LOCK
1683 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001684 ){
1685 pFile->transCntrChng = 0;
1686 pFile->dbUpdate = 0;
1687 pFile->inNormalWrite = 1;
1688 }
1689#endif
1690
1691
danielk1977ecb2a962004-06-02 06:30:16 +00001692 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001693 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001694 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001695 }else if( eFileLock==EXCLUSIVE_LOCK ){
1696 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001697 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001698 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001699
1700end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001701 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001702 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1703 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001704 return rc;
1705}
1706
1707/*
dan08da86a2009-08-21 17:18:03 +00001708** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001709** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001710*/
1711static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001712 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001713 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001714 p->pNext = pInode->pUnused;
1715 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001716 pFile->h = -1;
1717 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001718}
1719
1720/*
drh308c2a52010-05-14 11:30:18 +00001721** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001722** must be either NO_LOCK or SHARED_LOCK.
1723**
1724** If the locking level of the file descriptor is already at or below
1725** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001726**
1727** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1728** the byte range is divided into 2 parts and the first part is unlocked then
1729** set to a read lock, then the other part is simply unlocked. This works
1730** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1731** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001732*/
drha7e61d82011-03-12 17:02:57 +00001733static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001734 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001735 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001736 struct flock lock;
1737 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001738
drh054889e2005-11-30 03:20:31 +00001739 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001740 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001741 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001742 getpid()));
drha6abd042004-06-09 17:37:22 +00001743
drh308c2a52010-05-14 11:30:18 +00001744 assert( eFileLock<=SHARED_LOCK );
1745 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001746 return SQLITE_OK;
1747 }
drh6c7d5c52008-11-21 20:32:33 +00001748 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001749 pInode = pFile->pInode;
1750 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001751 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001752 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001753
drhd3d8c042012-05-29 17:02:40 +00001754#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001755 /* When reducing a lock such that other processes can start
1756 ** reading the database file again, make sure that the
1757 ** transaction counter was updated if any part of the database
1758 ** file changed. If the transaction counter is not updated,
1759 ** other connections to the same file might not realize that
1760 ** the file has changed and hence might not know to flush their
1761 ** cache. The use of a stale cache can lead to database corruption.
1762 */
drh8f941bc2009-01-14 23:03:40 +00001763 pFile->inNormalWrite = 0;
1764#endif
1765
drh7ed97b92010-01-20 13:07:21 +00001766 /* downgrading to a shared lock on NFS involves clearing the write lock
1767 ** before establishing the readlock - to avoid a race condition we downgrade
1768 ** the lock in 2 blocks, so that part of the range will be covered by a
1769 ** write lock until the rest is covered by a read lock:
1770 ** 1: [WWWWW]
1771 ** 2: [....W]
1772 ** 3: [RRRRW]
1773 ** 4: [RRRR.]
1774 */
drh308c2a52010-05-14 11:30:18 +00001775 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001776
1777#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001778 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001779 assert( handleNFSUnlock==0 );
1780#endif
1781#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001782 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001783 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001784 off_t divSize = SHARED_SIZE - 1;
1785
1786 lock.l_type = F_UNLCK;
1787 lock.l_whence = SEEK_SET;
1788 lock.l_start = SHARED_FIRST;
1789 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001790 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001791 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001792 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001793 if( IS_LOCK_ERROR(rc) ){
1794 pFile->lastErrno = tErrno;
1795 }
1796 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001797 }
drh7ed97b92010-01-20 13:07:21 +00001798 lock.l_type = F_RDLCK;
1799 lock.l_whence = SEEK_SET;
1800 lock.l_start = SHARED_FIRST;
1801 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001802 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001803 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001804 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1805 if( IS_LOCK_ERROR(rc) ){
1806 pFile->lastErrno = tErrno;
1807 }
1808 goto end_unlock;
1809 }
1810 lock.l_type = F_UNLCK;
1811 lock.l_whence = SEEK_SET;
1812 lock.l_start = SHARED_FIRST+divSize;
1813 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001814 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001815 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001816 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001817 if( IS_LOCK_ERROR(rc) ){
1818 pFile->lastErrno = tErrno;
1819 }
1820 goto end_unlock;
1821 }
drh30f776f2011-02-25 03:25:07 +00001822 }else
1823#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1824 {
drh7ed97b92010-01-20 13:07:21 +00001825 lock.l_type = F_RDLCK;
1826 lock.l_whence = SEEK_SET;
1827 lock.l_start = SHARED_FIRST;
1828 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001829 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001830 /* In theory, the call to unixFileLock() cannot fail because another
1831 ** process is holding an incompatible lock. If it does, this
1832 ** indicates that the other process is not following the locking
1833 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1834 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1835 ** an assert to fail). */
1836 rc = SQLITE_IOERR_RDLOCK;
1837 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001838 goto end_unlock;
1839 }
drh9c105bb2004-10-02 20:38:28 +00001840 }
1841 }
drhbbd42a62004-05-22 17:41:58 +00001842 lock.l_type = F_UNLCK;
1843 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001844 lock.l_start = PENDING_BYTE;
1845 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001846 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001847 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001848 }else{
danea83bc62011-04-01 11:56:32 +00001849 rc = SQLITE_IOERR_UNLOCK;
1850 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001851 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001852 }
drhbbd42a62004-05-22 17:41:58 +00001853 }
drh308c2a52010-05-14 11:30:18 +00001854 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001855 /* Decrement the shared lock counter. Release the lock using an
1856 ** OS call only when all threads in this same process have released
1857 ** the lock.
1858 */
drh8af6c222010-05-14 12:43:01 +00001859 pInode->nShared--;
1860 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001861 lock.l_type = F_UNLCK;
1862 lock.l_whence = SEEK_SET;
1863 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001864 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001865 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001866 }else{
danea83bc62011-04-01 11:56:32 +00001867 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001868 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001869 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001870 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001871 }
drha6abd042004-06-09 17:37:22 +00001872 }
1873
drhbbd42a62004-05-22 17:41:58 +00001874 /* Decrement the count of locks against this same file. When the
1875 ** count reaches zero, close any other file descriptors whose close
1876 ** was deferred because of outstanding locks.
1877 */
drh8af6c222010-05-14 12:43:01 +00001878 pInode->nLock--;
1879 assert( pInode->nLock>=0 );
1880 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001881 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001882 }
1883 }
drhf2f105d2012-08-20 15:53:54 +00001884
aswift5b1a2562008-08-22 00:22:35 +00001885end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001886 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001887 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001888 return rc;
drhbbd42a62004-05-22 17:41:58 +00001889}
1890
1891/*
drh308c2a52010-05-14 11:30:18 +00001892** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001893** must be either NO_LOCK or SHARED_LOCK.
1894**
1895** If the locking level of the file descriptor is already at or below
1896** the requested locking level, this routine is a no-op.
1897*/
drh308c2a52010-05-14 11:30:18 +00001898static int unixUnlock(sqlite3_file *id, int eFileLock){
dana1afc742013-03-25 13:50:49 +00001899 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
drha7e61d82011-03-12 17:02:57 +00001900 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001901}
1902
mistachkine98844f2013-08-24 00:59:24 +00001903#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001904static int unixMapfile(unixFile *pFd, i64 nByte);
1905static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001906#endif
danf23da962013-03-23 21:00:41 +00001907
drh7ed97b92010-01-20 13:07:21 +00001908/*
danielk1977e339d652008-06-28 11:23:00 +00001909** This function performs the parts of the "close file" operation
1910** common to all locking schemes. It closes the directory and file
1911** handles, if they are valid, and sets all fields of the unixFile
1912** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001913**
1914** It is *not* necessary to hold the mutex when this routine is called,
1915** even on VxWorks. A mutex will be acquired on VxWorks by the
1916** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001917*/
1918static int closeUnixFile(sqlite3_file *id){
1919 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001920#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001921 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001922#endif
dan661d71a2011-03-30 19:08:03 +00001923 if( pFile->h>=0 ){
1924 robust_close(pFile, pFile->h, __LINE__);
1925 pFile->h = -1;
1926 }
1927#if OS_VXWORKS
1928 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001929 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001930 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001931 }
1932 vxworksReleaseFileId(pFile->pId);
1933 pFile->pId = 0;
1934 }
1935#endif
1936 OSTRACE(("CLOSE %-3d\n", pFile->h));
1937 OpenCounter(-1);
1938 sqlite3_free(pFile->pUnused);
1939 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001940 return SQLITE_OK;
1941}
1942
1943/*
danielk1977e3026632004-06-22 11:29:02 +00001944** Close a file.
1945*/
danielk197762079062007-08-15 17:08:46 +00001946static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001947 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001948 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001949 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001950 unixUnlock(id, NO_LOCK);
1951 unixEnterMutex();
1952
1953 /* unixFile.pInode is always valid here. Otherwise, a different close
1954 ** routine (e.g. nolockClose()) would be called instead.
1955 */
1956 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1957 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1958 /* If there are outstanding locks, do not actually close the file just
1959 ** yet because that would clear those locks. Instead, add the file
1960 ** descriptor to pInode->pUnused list. It will be automatically closed
1961 ** when the last lock is cleared.
1962 */
1963 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001964 }
dan661d71a2011-03-30 19:08:03 +00001965 releaseInodeInfo(pFile);
1966 rc = closeUnixFile(id);
1967 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001968 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001969}
1970
drh734c9862008-11-28 15:37:20 +00001971/************** End of the posix advisory lock implementation *****************
1972******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001973
drh734c9862008-11-28 15:37:20 +00001974/******************************************************************************
1975****************************** No-op Locking **********************************
1976**
1977** Of the various locking implementations available, this is by far the
1978** simplest: locking is ignored. No attempt is made to lock the database
1979** file for reading or writing.
1980**
1981** This locking mode is appropriate for use on read-only databases
1982** (ex: databases that are burned into CD-ROM, for example.) It can
1983** also be used if the application employs some external mechanism to
1984** prevent simultaneous access of the same database by two or more
1985** database connections. But there is a serious risk of database
1986** corruption if this locking mode is used in situations where multiple
1987** database connections are accessing the same database file at the same
1988** time and one or more of those connections are writing.
1989*/
drhbfe66312006-10-03 17:40:40 +00001990
drh734c9862008-11-28 15:37:20 +00001991static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1992 UNUSED_PARAMETER(NotUsed);
1993 *pResOut = 0;
1994 return SQLITE_OK;
1995}
drh734c9862008-11-28 15:37:20 +00001996static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1997 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1998 return SQLITE_OK;
1999}
drh734c9862008-11-28 15:37:20 +00002000static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2001 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2002 return SQLITE_OK;
2003}
2004
2005/*
drh9b35ea62008-11-29 02:20:26 +00002006** Close the file.
drh734c9862008-11-28 15:37:20 +00002007*/
2008static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002009 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002010}
2011
2012/******************* End of the no-op lock implementation *********************
2013******************************************************************************/
2014
2015/******************************************************************************
2016************************* Begin dot-file Locking ******************************
2017**
mistachkin48864df2013-03-21 21:20:32 +00002018** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002019** files (really a directory) to control access to the database. This works
2020** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002021**
2022** (1) There is zero concurrency. A single reader blocks all other
2023** connections from reading or writing the database.
2024**
2025** (2) An application crash or power loss can leave stale lock files
2026** sitting around that need to be cleared manually.
2027**
2028** Nevertheless, a dotlock is an appropriate locking mode for use if no
2029** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002030**
drh9ef6bc42011-11-04 02:24:02 +00002031** Dotfile locking works by creating a subdirectory in the same directory as
2032** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002033** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002034** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002035*/
2036
2037/*
2038** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002039** lock directory.
drh734c9862008-11-28 15:37:20 +00002040*/
2041#define DOTLOCK_SUFFIX ".lock"
2042
drh7708e972008-11-29 00:56:52 +00002043/*
2044** This routine checks if there is a RESERVED lock held on the specified
2045** file by this or any other process. If such a lock is held, set *pResOut
2046** to a non-zero value otherwise *pResOut is set to zero. The return value
2047** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2048**
2049** In dotfile locking, either a lock exists or it does not. So in this
2050** variation of CheckReservedLock(), *pResOut is set to true if any lock
2051** is held on the file and false if the file is unlocked.
2052*/
drh734c9862008-11-28 15:37:20 +00002053static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2054 int rc = SQLITE_OK;
2055 int reserved = 0;
2056 unixFile *pFile = (unixFile*)id;
2057
2058 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2059
2060 assert( pFile );
2061
2062 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002063 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002064 /* Either this connection or some other connection in the same process
2065 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002066 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002067 }else{
2068 /* The lock is held if and only if the lockfile exists */
2069 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002070 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002071 }
drh308c2a52010-05-14 11:30:18 +00002072 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002073 *pResOut = reserved;
2074 return rc;
2075}
2076
drh7708e972008-11-29 00:56:52 +00002077/*
drh308c2a52010-05-14 11:30:18 +00002078** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002079** of the following:
2080**
2081** (1) SHARED_LOCK
2082** (2) RESERVED_LOCK
2083** (3) PENDING_LOCK
2084** (4) EXCLUSIVE_LOCK
2085**
2086** Sometimes when requesting one lock state, additional lock states
2087** are inserted in between. The locking might fail on one of the later
2088** transitions leaving the lock state different from what it started but
2089** still short of its goal. The following chart shows the allowed
2090** transitions and the inserted intermediate states:
2091**
2092** UNLOCKED -> SHARED
2093** SHARED -> RESERVED
2094** SHARED -> (PENDING) -> EXCLUSIVE
2095** RESERVED -> (PENDING) -> EXCLUSIVE
2096** PENDING -> EXCLUSIVE
2097**
2098** This routine will only increase a lock. Use the sqlite3OsUnlock()
2099** routine to lower a locking level.
2100**
2101** With dotfile locking, we really only support state (4): EXCLUSIVE.
2102** But we track the other locking levels internally.
2103*/
drh308c2a52010-05-14 11:30:18 +00002104static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002105 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002106 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002107 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002108
drh7708e972008-11-29 00:56:52 +00002109
2110 /* If we have any lock, then the lock file already exists. All we have
2111 ** to do is adjust our internal record of the lock level.
2112 */
drh308c2a52010-05-14 11:30:18 +00002113 if( pFile->eFileLock > NO_LOCK ){
2114 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002115 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002116#ifdef HAVE_UTIME
2117 utime(zLockFile, NULL);
2118#else
drh734c9862008-11-28 15:37:20 +00002119 utimes(zLockFile, NULL);
2120#endif
drh7708e972008-11-29 00:56:52 +00002121 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002122 }
2123
2124 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002125 rc = osMkdir(zLockFile, 0777);
2126 if( rc<0 ){
2127 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002128 int tErrno = errno;
2129 if( EEXIST == tErrno ){
2130 rc = SQLITE_BUSY;
2131 } else {
2132 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2133 if( IS_LOCK_ERROR(rc) ){
2134 pFile->lastErrno = tErrno;
2135 }
2136 }
drh7708e972008-11-29 00:56:52 +00002137 return rc;
drh734c9862008-11-28 15:37:20 +00002138 }
drh734c9862008-11-28 15:37:20 +00002139
2140 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002141 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002142 return rc;
2143}
2144
drh7708e972008-11-29 00:56:52 +00002145/*
drh308c2a52010-05-14 11:30:18 +00002146** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002147** must be either NO_LOCK or SHARED_LOCK.
2148**
2149** If the locking level of the file descriptor is already at or below
2150** the requested locking level, this routine is a no-op.
2151**
2152** When the locking level reaches NO_LOCK, delete the lock file.
2153*/
drh308c2a52010-05-14 11:30:18 +00002154static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002155 unixFile *pFile = (unixFile*)id;
2156 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002157 int rc;
drh734c9862008-11-28 15:37:20 +00002158
2159 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002160 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002161 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002162 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002163
2164 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002165 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002166 return SQLITE_OK;
2167 }
drh7708e972008-11-29 00:56:52 +00002168
2169 /* To downgrade to shared, simply update our internal notion of the
2170 ** lock state. No need to mess with the file on disk.
2171 */
drh308c2a52010-05-14 11:30:18 +00002172 if( eFileLock==SHARED_LOCK ){
2173 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002174 return SQLITE_OK;
2175 }
2176
drh7708e972008-11-29 00:56:52 +00002177 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002178 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002179 rc = osRmdir(zLockFile);
2180 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2181 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002182 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002183 rc = 0;
drh734c9862008-11-28 15:37:20 +00002184 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002185 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002186 }
2187 if( IS_LOCK_ERROR(rc) ){
2188 pFile->lastErrno = tErrno;
2189 }
2190 return rc;
2191 }
drh308c2a52010-05-14 11:30:18 +00002192 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002193 return SQLITE_OK;
2194}
2195
2196/*
drh9b35ea62008-11-29 02:20:26 +00002197** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002198*/
2199static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002200 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002201 if( id ){
2202 unixFile *pFile = (unixFile*)id;
2203 dotlockUnlock(id, NO_LOCK);
2204 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002205 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002206 }
drh734c9862008-11-28 15:37:20 +00002207 return rc;
2208}
2209/****************** End of the dot-file lock implementation *******************
2210******************************************************************************/
2211
2212/******************************************************************************
2213************************** Begin flock Locking ********************************
2214**
2215** Use the flock() system call to do file locking.
2216**
drh6b9d6dd2008-12-03 19:34:47 +00002217** flock() locking is like dot-file locking in that the various
2218** fine-grain locking levels supported by SQLite are collapsed into
2219** a single exclusive lock. In other words, SHARED, RESERVED, and
2220** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2221** still works when you do this, but concurrency is reduced since
2222** only a single process can be reading the database at a time.
2223**
drh734c9862008-11-28 15:37:20 +00002224** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2225** compiling for VXWORKS.
2226*/
2227#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002228
drh6b9d6dd2008-12-03 19:34:47 +00002229/*
drhff812312011-02-23 13:33:46 +00002230** Retry flock() calls that fail with EINTR
2231*/
2232#ifdef EINTR
2233static int robust_flock(int fd, int op){
2234 int rc;
2235 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2236 return rc;
2237}
2238#else
drh5c819272011-02-23 14:00:12 +00002239# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002240#endif
2241
2242
2243/*
drh6b9d6dd2008-12-03 19:34:47 +00002244** This routine checks if there is a RESERVED lock held on the specified
2245** file by this or any other process. If such a lock is held, set *pResOut
2246** to a non-zero value otherwise *pResOut is set to zero. The return value
2247** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2248*/
drh734c9862008-11-28 15:37:20 +00002249static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2250 int rc = SQLITE_OK;
2251 int reserved = 0;
2252 unixFile *pFile = (unixFile*)id;
2253
2254 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2255
2256 assert( pFile );
2257
2258 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002259 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002260 reserved = 1;
2261 }
2262
2263 /* Otherwise see if some other process holds it. */
2264 if( !reserved ){
2265 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002266 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002267 if( !lrc ){
2268 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002269 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002270 if ( lrc ) {
2271 int tErrno = errno;
2272 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002273 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002274 if( IS_LOCK_ERROR(lrc) ){
2275 pFile->lastErrno = tErrno;
2276 rc = lrc;
2277 }
2278 }
2279 } else {
2280 int tErrno = errno;
2281 reserved = 1;
2282 /* someone else might have it reserved */
2283 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2284 if( IS_LOCK_ERROR(lrc) ){
2285 pFile->lastErrno = tErrno;
2286 rc = lrc;
2287 }
2288 }
2289 }
drh308c2a52010-05-14 11:30:18 +00002290 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002291
2292#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2293 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2294 rc = SQLITE_OK;
2295 reserved=1;
2296 }
2297#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2298 *pResOut = reserved;
2299 return rc;
2300}
2301
drh6b9d6dd2008-12-03 19:34:47 +00002302/*
drh308c2a52010-05-14 11:30:18 +00002303** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002304** of the following:
2305**
2306** (1) SHARED_LOCK
2307** (2) RESERVED_LOCK
2308** (3) PENDING_LOCK
2309** (4) EXCLUSIVE_LOCK
2310**
2311** Sometimes when requesting one lock state, additional lock states
2312** are inserted in between. The locking might fail on one of the later
2313** transitions leaving the lock state different from what it started but
2314** still short of its goal. The following chart shows the allowed
2315** transitions and the inserted intermediate states:
2316**
2317** UNLOCKED -> SHARED
2318** SHARED -> RESERVED
2319** SHARED -> (PENDING) -> EXCLUSIVE
2320** RESERVED -> (PENDING) -> EXCLUSIVE
2321** PENDING -> EXCLUSIVE
2322**
2323** flock() only really support EXCLUSIVE locks. We track intermediate
2324** lock states in the sqlite3_file structure, but all locks SHARED or
2325** above are really EXCLUSIVE locks and exclude all other processes from
2326** access the file.
2327**
2328** This routine will only increase a lock. Use the sqlite3OsUnlock()
2329** routine to lower a locking level.
2330*/
drh308c2a52010-05-14 11:30:18 +00002331static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002332 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002333 unixFile *pFile = (unixFile*)id;
2334
2335 assert( pFile );
2336
2337 /* if we already have a lock, it is exclusive.
2338 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002339 if (pFile->eFileLock > NO_LOCK) {
2340 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002341 return SQLITE_OK;
2342 }
2343
2344 /* grab an exclusive lock */
2345
drhff812312011-02-23 13:33:46 +00002346 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002347 int tErrno = errno;
2348 /* didn't get, must be busy */
2349 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2350 if( IS_LOCK_ERROR(rc) ){
2351 pFile->lastErrno = tErrno;
2352 }
2353 } else {
2354 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002355 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002356 }
drh308c2a52010-05-14 11:30:18 +00002357 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2358 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002359#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2360 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2361 rc = SQLITE_BUSY;
2362 }
2363#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2364 return rc;
2365}
2366
drh6b9d6dd2008-12-03 19:34:47 +00002367
2368/*
drh308c2a52010-05-14 11:30:18 +00002369** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002370** must be either NO_LOCK or SHARED_LOCK.
2371**
2372** If the locking level of the file descriptor is already at or below
2373** the requested locking level, this routine is a no-op.
2374*/
drh308c2a52010-05-14 11:30:18 +00002375static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002376 unixFile *pFile = (unixFile*)id;
2377
2378 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002379 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2380 pFile->eFileLock, getpid()));
2381 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002382
2383 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002384 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002385 return SQLITE_OK;
2386 }
2387
2388 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002389 if (eFileLock==SHARED_LOCK) {
2390 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002391 return SQLITE_OK;
2392 }
2393
2394 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002395 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002396#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002397 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002398#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002399 return SQLITE_IOERR_UNLOCK;
2400 }else{
drh308c2a52010-05-14 11:30:18 +00002401 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002402 return SQLITE_OK;
2403 }
2404}
2405
2406/*
2407** Close a file.
2408*/
2409static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002410 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002411 if( id ){
2412 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002413 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002414 }
drh5a05be12012-10-09 18:51:44 +00002415 return rc;
drh734c9862008-11-28 15:37:20 +00002416}
2417
2418#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2419
2420/******************* End of the flock lock implementation *********************
2421******************************************************************************/
2422
2423/******************************************************************************
2424************************ Begin Named Semaphore Locking ************************
2425**
2426** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002427**
2428** Semaphore locking is like dot-lock and flock in that it really only
2429** supports EXCLUSIVE locking. Only a single process can read or write
2430** the database file at a time. This reduces potential concurrency, but
2431** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002432*/
2433#if OS_VXWORKS
2434
drh6b9d6dd2008-12-03 19:34:47 +00002435/*
2436** This routine checks if there is a RESERVED lock held on the specified
2437** file by this or any other process. If such a lock is held, set *pResOut
2438** to a non-zero value otherwise *pResOut is set to zero. The return value
2439** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2440*/
drh734c9862008-11-28 15:37:20 +00002441static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2442 int rc = SQLITE_OK;
2443 int reserved = 0;
2444 unixFile *pFile = (unixFile*)id;
2445
2446 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2447
2448 assert( pFile );
2449
2450 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002451 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002452 reserved = 1;
2453 }
2454
2455 /* Otherwise see if some other process holds it. */
2456 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002457 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002458 struct stat statBuf;
2459
2460 if( sem_trywait(pSem)==-1 ){
2461 int tErrno = errno;
2462 if( EAGAIN != tErrno ){
2463 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2464 pFile->lastErrno = tErrno;
2465 } else {
2466 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002467 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002468 }
2469 }else{
2470 /* we could have it if we want it */
2471 sem_post(pSem);
2472 }
2473 }
drh308c2a52010-05-14 11:30:18 +00002474 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002475
2476 *pResOut = reserved;
2477 return rc;
2478}
2479
drh6b9d6dd2008-12-03 19:34:47 +00002480/*
drh308c2a52010-05-14 11:30:18 +00002481** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002482** of the following:
2483**
2484** (1) SHARED_LOCK
2485** (2) RESERVED_LOCK
2486** (3) PENDING_LOCK
2487** (4) EXCLUSIVE_LOCK
2488**
2489** Sometimes when requesting one lock state, additional lock states
2490** are inserted in between. The locking might fail on one of the later
2491** transitions leaving the lock state different from what it started but
2492** still short of its goal. The following chart shows the allowed
2493** transitions and the inserted intermediate states:
2494**
2495** UNLOCKED -> SHARED
2496** SHARED -> RESERVED
2497** SHARED -> (PENDING) -> EXCLUSIVE
2498** RESERVED -> (PENDING) -> EXCLUSIVE
2499** PENDING -> EXCLUSIVE
2500**
2501** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2502** lock states in the sqlite3_file structure, but all locks SHARED or
2503** above are really EXCLUSIVE locks and exclude all other processes from
2504** access the file.
2505**
2506** This routine will only increase a lock. Use the sqlite3OsUnlock()
2507** routine to lower a locking level.
2508*/
drh308c2a52010-05-14 11:30:18 +00002509static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002510 unixFile *pFile = (unixFile*)id;
2511 int fd;
drh8af6c222010-05-14 12:43:01 +00002512 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002513 int rc = SQLITE_OK;
2514
2515 /* if we already have a lock, it is exclusive.
2516 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002517 if (pFile->eFileLock > NO_LOCK) {
2518 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002519 rc = SQLITE_OK;
2520 goto sem_end_lock;
2521 }
2522
2523 /* lock semaphore now but bail out when already locked. */
2524 if( sem_trywait(pSem)==-1 ){
2525 rc = SQLITE_BUSY;
2526 goto sem_end_lock;
2527 }
2528
2529 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002530 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002531
2532 sem_end_lock:
2533 return rc;
2534}
2535
drh6b9d6dd2008-12-03 19:34:47 +00002536/*
drh308c2a52010-05-14 11:30:18 +00002537** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002538** must be either NO_LOCK or SHARED_LOCK.
2539**
2540** If the locking level of the file descriptor is already at or below
2541** the requested locking level, this routine is a no-op.
2542*/
drh308c2a52010-05-14 11:30:18 +00002543static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002544 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002545 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002546
2547 assert( pFile );
2548 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002549 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002550 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002551 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002552
2553 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002554 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002555 return SQLITE_OK;
2556 }
2557
2558 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002559 if (eFileLock==SHARED_LOCK) {
2560 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002561 return SQLITE_OK;
2562 }
2563
2564 /* no, really unlock. */
2565 if ( sem_post(pSem)==-1 ) {
2566 int rc, tErrno = errno;
2567 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2568 if( IS_LOCK_ERROR(rc) ){
2569 pFile->lastErrno = tErrno;
2570 }
2571 return rc;
2572 }
drh308c2a52010-05-14 11:30:18 +00002573 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002574 return SQLITE_OK;
2575}
2576
2577/*
2578 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002579 */
drh734c9862008-11-28 15:37:20 +00002580static int semClose(sqlite3_file *id) {
2581 if( id ){
2582 unixFile *pFile = (unixFile*)id;
2583 semUnlock(id, NO_LOCK);
2584 assert( pFile );
2585 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002586 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002587 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002588 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002589 }
2590 return SQLITE_OK;
2591}
2592
2593#endif /* OS_VXWORKS */
2594/*
2595** Named semaphore locking is only available on VxWorks.
2596**
2597*************** End of the named semaphore lock implementation ****************
2598******************************************************************************/
2599
2600
2601/******************************************************************************
2602*************************** Begin AFP Locking *********************************
2603**
2604** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2605** on Apple Macintosh computers - both OS9 and OSX.
2606**
2607** Third-party implementations of AFP are available. But this code here
2608** only works on OSX.
2609*/
2610
drhd2cb50b2009-01-09 21:41:17 +00002611#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002612/*
2613** The afpLockingContext structure contains all afp lock specific state
2614*/
drhbfe66312006-10-03 17:40:40 +00002615typedef struct afpLockingContext afpLockingContext;
2616struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002617 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002618 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002619};
2620
2621struct ByteRangeLockPB2
2622{
2623 unsigned long long offset; /* offset to first byte to lock */
2624 unsigned long long length; /* nbr of bytes to lock */
2625 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2626 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2627 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2628 int fd; /* file desc to assoc this lock with */
2629};
2630
drhfd131da2007-08-07 17:13:03 +00002631#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002632
drh6b9d6dd2008-12-03 19:34:47 +00002633/*
2634** This is a utility for setting or clearing a bit-range lock on an
2635** AFP filesystem.
2636**
2637** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2638*/
2639static int afpSetLock(
2640 const char *path, /* Name of the file to be locked or unlocked */
2641 unixFile *pFile, /* Open file descriptor on path */
2642 unsigned long long offset, /* First byte to be locked */
2643 unsigned long long length, /* Number of bytes to lock */
2644 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002645){
drh6b9d6dd2008-12-03 19:34:47 +00002646 struct ByteRangeLockPB2 pb;
2647 int err;
drhbfe66312006-10-03 17:40:40 +00002648
2649 pb.unLockFlag = setLockFlag ? 0 : 1;
2650 pb.startEndFlag = 0;
2651 pb.offset = offset;
2652 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002653 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002654
drh308c2a52010-05-14 11:30:18 +00002655 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002656 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002657 offset, length));
drhbfe66312006-10-03 17:40:40 +00002658 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2659 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002660 int rc;
2661 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002662 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2663 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002664#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2665 rc = SQLITE_BUSY;
2666#else
drh734c9862008-11-28 15:37:20 +00002667 rc = sqliteErrorFromPosixError(tErrno,
2668 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002669#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002670 if( IS_LOCK_ERROR(rc) ){
2671 pFile->lastErrno = tErrno;
2672 }
2673 return rc;
drhbfe66312006-10-03 17:40:40 +00002674 } else {
aswift5b1a2562008-08-22 00:22:35 +00002675 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002676 }
2677}
2678
drh6b9d6dd2008-12-03 19:34:47 +00002679/*
2680** This routine checks if there is a RESERVED lock held on the specified
2681** file by this or any other process. If such a lock is held, set *pResOut
2682** to a non-zero value otherwise *pResOut is set to zero. The return value
2683** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2684*/
danielk1977e339d652008-06-28 11:23:00 +00002685static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002686 int rc = SQLITE_OK;
2687 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002688 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002689 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002690
aswift5b1a2562008-08-22 00:22:35 +00002691 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2692
2693 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002694 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002695 if( context->reserved ){
2696 *pResOut = 1;
2697 return SQLITE_OK;
2698 }
drh8af6c222010-05-14 12:43:01 +00002699 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002700
2701 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002702 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002703 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002704 }
2705
2706 /* Otherwise see if some other process holds it.
2707 */
aswift5b1a2562008-08-22 00:22:35 +00002708 if( !reserved ){
2709 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002710 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002711 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002712 /* if we succeeded in taking the reserved lock, unlock it to restore
2713 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002714 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002715 } else {
2716 /* if we failed to get the lock then someone else must have it */
2717 reserved = 1;
2718 }
2719 if( IS_LOCK_ERROR(lrc) ){
2720 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002721 }
2722 }
drhbfe66312006-10-03 17:40:40 +00002723
drh7ed97b92010-01-20 13:07:21 +00002724 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002725 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002726
2727 *pResOut = reserved;
2728 return rc;
drhbfe66312006-10-03 17:40:40 +00002729}
2730
drh6b9d6dd2008-12-03 19:34:47 +00002731/*
drh308c2a52010-05-14 11:30:18 +00002732** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002733** of the following:
2734**
2735** (1) SHARED_LOCK
2736** (2) RESERVED_LOCK
2737** (3) PENDING_LOCK
2738** (4) EXCLUSIVE_LOCK
2739**
2740** Sometimes when requesting one lock state, additional lock states
2741** are inserted in between. The locking might fail on one of the later
2742** transitions leaving the lock state different from what it started but
2743** still short of its goal. The following chart shows the allowed
2744** transitions and the inserted intermediate states:
2745**
2746** UNLOCKED -> SHARED
2747** SHARED -> RESERVED
2748** SHARED -> (PENDING) -> EXCLUSIVE
2749** RESERVED -> (PENDING) -> EXCLUSIVE
2750** PENDING -> EXCLUSIVE
2751**
2752** This routine will only increase a lock. Use the sqlite3OsUnlock()
2753** routine to lower a locking level.
2754*/
drh308c2a52010-05-14 11:30:18 +00002755static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002756 int rc = SQLITE_OK;
2757 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002758 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002759 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002760
2761 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002762 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2763 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002764 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002765
drhbfe66312006-10-03 17:40:40 +00002766 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002767 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002768 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002769 */
drh308c2a52010-05-14 11:30:18 +00002770 if( pFile->eFileLock>=eFileLock ){
2771 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2772 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002773 return SQLITE_OK;
2774 }
2775
2776 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002777 ** (1) We never move from unlocked to anything higher than shared lock.
2778 ** (2) SQLite never explicitly requests a pendig lock.
2779 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002780 */
drh308c2a52010-05-14 11:30:18 +00002781 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2782 assert( eFileLock!=PENDING_LOCK );
2783 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002784
drh8af6c222010-05-14 12:43:01 +00002785 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002786 */
drh6c7d5c52008-11-21 20:32:33 +00002787 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002788 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002789
2790 /* If some thread using this PID has a lock via a different unixFile*
2791 ** handle that precludes the requested lock, return BUSY.
2792 */
drh8af6c222010-05-14 12:43:01 +00002793 if( (pFile->eFileLock!=pInode->eFileLock &&
2794 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002795 ){
2796 rc = SQLITE_BUSY;
2797 goto afp_end_lock;
2798 }
2799
2800 /* If a SHARED lock is requested, and some thread using this PID already
2801 ** has a SHARED or RESERVED lock, then increment reference counts and
2802 ** return SQLITE_OK.
2803 */
drh308c2a52010-05-14 11:30:18 +00002804 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002805 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002806 assert( eFileLock==SHARED_LOCK );
2807 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002808 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002809 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002810 pInode->nShared++;
2811 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002812 goto afp_end_lock;
2813 }
drhbfe66312006-10-03 17:40:40 +00002814
2815 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002816 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2817 ** be released.
2818 */
drh308c2a52010-05-14 11:30:18 +00002819 if( eFileLock==SHARED_LOCK
2820 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002821 ){
2822 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002823 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002824 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002825 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002826 goto afp_end_lock;
2827 }
2828 }
2829
2830 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002831 ** operating system calls for the specified lock.
2832 */
drh308c2a52010-05-14 11:30:18 +00002833 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002834 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002835 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002836
drh8af6c222010-05-14 12:43:01 +00002837 assert( pInode->nShared==0 );
2838 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002839
2840 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002841 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002842 /* note that the quality of the randomness doesn't matter that much */
2843 lk = random();
drh8af6c222010-05-14 12:43:01 +00002844 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002845 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002846 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002847 if( IS_LOCK_ERROR(lrc1) ){
2848 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002849 }
aswift5b1a2562008-08-22 00:22:35 +00002850 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002851 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002852
aswift5b1a2562008-08-22 00:22:35 +00002853 if( IS_LOCK_ERROR(lrc1) ) {
2854 pFile->lastErrno = lrc1Errno;
2855 rc = lrc1;
2856 goto afp_end_lock;
2857 } else if( IS_LOCK_ERROR(lrc2) ){
2858 rc = lrc2;
2859 goto afp_end_lock;
2860 } else if( lrc1 != SQLITE_OK ) {
2861 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002862 } else {
drh308c2a52010-05-14 11:30:18 +00002863 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002864 pInode->nLock++;
2865 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002866 }
drh8af6c222010-05-14 12:43:01 +00002867 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002868 /* We are trying for an exclusive lock but another thread in this
2869 ** same process is still holding a shared lock. */
2870 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002871 }else{
2872 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2873 ** assumed that there is a SHARED or greater lock on the file
2874 ** already.
2875 */
2876 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002877 assert( 0!=pFile->eFileLock );
2878 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002879 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002880 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002881 if( !failed ){
2882 context->reserved = 1;
2883 }
drhbfe66312006-10-03 17:40:40 +00002884 }
drh308c2a52010-05-14 11:30:18 +00002885 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002886 /* Acquire an EXCLUSIVE lock */
2887
2888 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002889 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002890 */
drh6b9d6dd2008-12-03 19:34:47 +00002891 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002892 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002893 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002894 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002895 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002896 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002897 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002898 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002899 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2900 ** a critical I/O error
2901 */
2902 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2903 SQLITE_IOERR_LOCK;
2904 goto afp_end_lock;
2905 }
2906 }else{
aswift5b1a2562008-08-22 00:22:35 +00002907 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002908 }
2909 }
aswift5b1a2562008-08-22 00:22:35 +00002910 if( failed ){
2911 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002912 }
2913 }
2914
2915 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002916 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002917 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002918 }else if( eFileLock==EXCLUSIVE_LOCK ){
2919 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002920 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002921 }
2922
2923afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002924 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002925 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2926 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002927 return rc;
2928}
2929
2930/*
drh308c2a52010-05-14 11:30:18 +00002931** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002932** must be either NO_LOCK or SHARED_LOCK.
2933**
2934** If the locking level of the file descriptor is already at or below
2935** the requested locking level, this routine is a no-op.
2936*/
drh308c2a52010-05-14 11:30:18 +00002937static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002938 int rc = SQLITE_OK;
2939 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002940 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002941 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2942 int skipShared = 0;
2943#ifdef SQLITE_TEST
2944 int h = pFile->h;
2945#endif
drhbfe66312006-10-03 17:40:40 +00002946
2947 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002948 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002949 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002950 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002951
drh308c2a52010-05-14 11:30:18 +00002952 assert( eFileLock<=SHARED_LOCK );
2953 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002954 return SQLITE_OK;
2955 }
drh6c7d5c52008-11-21 20:32:33 +00002956 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002957 pInode = pFile->pInode;
2958 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002959 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002960 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002961 SimulateIOErrorBenign(1);
2962 SimulateIOError( h=(-1) )
2963 SimulateIOErrorBenign(0);
2964
drhd3d8c042012-05-29 17:02:40 +00002965#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002966 /* When reducing a lock such that other processes can start
2967 ** reading the database file again, make sure that the
2968 ** transaction counter was updated if any part of the database
2969 ** file changed. If the transaction counter is not updated,
2970 ** other connections to the same file might not realize that
2971 ** the file has changed and hence might not know to flush their
2972 ** cache. The use of a stale cache can lead to database corruption.
2973 */
2974 assert( pFile->inNormalWrite==0
2975 || pFile->dbUpdate==0
2976 || pFile->transCntrChng==1 );
2977 pFile->inNormalWrite = 0;
2978#endif
aswiftaebf4132008-11-21 00:10:35 +00002979
drh308c2a52010-05-14 11:30:18 +00002980 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002981 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002982 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002983 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002984 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002985 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2986 } else {
2987 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002988 }
2989 }
drh308c2a52010-05-14 11:30:18 +00002990 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002991 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002992 }
drh308c2a52010-05-14 11:30:18 +00002993 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002994 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2995 if( !rc ){
2996 context->reserved = 0;
2997 }
aswiftaebf4132008-11-21 00:10:35 +00002998 }
drh8af6c222010-05-14 12:43:01 +00002999 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3000 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003001 }
aswiftaebf4132008-11-21 00:10:35 +00003002 }
drh308c2a52010-05-14 11:30:18 +00003003 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003004
drh7ed97b92010-01-20 13:07:21 +00003005 /* Decrement the shared lock counter. Release the lock using an
3006 ** OS call only when all threads in this same process have released
3007 ** the lock.
3008 */
drh8af6c222010-05-14 12:43:01 +00003009 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3010 pInode->nShared--;
3011 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003012 SimulateIOErrorBenign(1);
3013 SimulateIOError( h=(-1) )
3014 SimulateIOErrorBenign(0);
3015 if( !skipShared ){
3016 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3017 }
3018 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003019 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003020 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003021 }
3022 }
3023 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003024 pInode->nLock--;
3025 assert( pInode->nLock>=0 );
3026 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003027 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003028 }
3029 }
drhbfe66312006-10-03 17:40:40 +00003030 }
drh7ed97b92010-01-20 13:07:21 +00003031
drh6c7d5c52008-11-21 20:32:33 +00003032 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003033 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003034 return rc;
3035}
3036
3037/*
drh339eb0b2008-03-07 15:34:11 +00003038** Close a file & cleanup AFP specific locking context
3039*/
danielk1977e339d652008-06-28 11:23:00 +00003040static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003041 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003042 if( id ){
3043 unixFile *pFile = (unixFile*)id;
3044 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003045 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003046 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003047 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003048 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003049 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003050 ** the last lock is cleared.
3051 */
dan08da86a2009-08-21 17:18:03 +00003052 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003053 }
danb0ac3e32010-06-16 10:55:42 +00003054 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003055 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003056 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003057 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003058 }
drh7ed97b92010-01-20 13:07:21 +00003059 return rc;
drhbfe66312006-10-03 17:40:40 +00003060}
3061
drhd2cb50b2009-01-09 21:41:17 +00003062#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003063/*
3064** The code above is the AFP lock implementation. The code is specific
3065** to MacOSX and does not work on other unix platforms. No alternative
3066** is available. If you don't compile for a mac, then the "unix-afp"
3067** VFS is not available.
3068**
3069********************* End of the AFP lock implementation **********************
3070******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003071
drh7ed97b92010-01-20 13:07:21 +00003072/******************************************************************************
3073*************************** Begin NFS Locking ********************************/
3074
3075#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3076/*
drh308c2a52010-05-14 11:30:18 +00003077 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003078 ** must be either NO_LOCK or SHARED_LOCK.
3079 **
3080 ** If the locking level of the file descriptor is already at or below
3081 ** the requested locking level, this routine is a no-op.
3082 */
drh308c2a52010-05-14 11:30:18 +00003083static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003084 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003085}
3086
3087#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3088/*
3089** The code above is the NFS lock implementation. The code is specific
3090** to MacOSX and does not work on other unix platforms. No alternative
3091** is available.
3092**
3093********************* End of the NFS lock implementation **********************
3094******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003095
3096/******************************************************************************
3097**************** Non-locking sqlite3_file methods *****************************
3098**
3099** The next division contains implementations for all methods of the
3100** sqlite3_file object other than the locking methods. The locking
3101** methods were defined in divisions above (one locking method per
3102** division). Those methods that are common to all locking modes
3103** are gather together into this division.
3104*/
drhbfe66312006-10-03 17:40:40 +00003105
3106/*
drh734c9862008-11-28 15:37:20 +00003107** Seek to the offset passed as the second argument, then read cnt
3108** bytes into pBuf. Return the number of bytes actually read.
3109**
3110** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3111** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3112** one system to another. Since SQLite does not define USE_PREAD
3113** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3114** See tickets #2741 and #2681.
3115**
3116** To avoid stomping the errno value on a failed read the lastErrno value
3117** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003118*/
drh734c9862008-11-28 15:37:20 +00003119static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3120 int got;
drh58024642011-11-07 18:16:00 +00003121 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003122#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003123 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003124#endif
drh734c9862008-11-28 15:37:20 +00003125 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003126 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003127 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003128 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003129 do{
drh734c9862008-11-28 15:37:20 +00003130#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003131 got = osPread(id->h, pBuf, cnt, offset);
3132 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003133#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003134 got = osPread64(id->h, pBuf, cnt, offset);
3135 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003136#else
drh58024642011-11-07 18:16:00 +00003137 newOffset = lseek(id->h, offset, SEEK_SET);
3138 SimulateIOError( newOffset-- );
3139 if( newOffset!=offset ){
3140 if( newOffset == -1 ){
3141 ((unixFile*)id)->lastErrno = errno;
3142 }else{
drhf2f105d2012-08-20 15:53:54 +00003143 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003144 }
3145 return -1;
drh734c9862008-11-28 15:37:20 +00003146 }
drh58024642011-11-07 18:16:00 +00003147 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003148#endif
drh58024642011-11-07 18:16:00 +00003149 if( got==cnt ) break;
3150 if( got<0 ){
3151 if( errno==EINTR ){ got = 1; continue; }
3152 prior = 0;
3153 ((unixFile*)id)->lastErrno = errno;
3154 break;
3155 }else if( got>0 ){
3156 cnt -= got;
3157 offset += got;
3158 prior += got;
3159 pBuf = (void*)(got + (char*)pBuf);
3160 }
3161 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003162 TIMER_END;
drh58024642011-11-07 18:16:00 +00003163 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3164 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3165 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003166}
3167
3168/*
drh734c9862008-11-28 15:37:20 +00003169** Read data from a file into a buffer. Return SQLITE_OK if all
3170** bytes were read successfully and SQLITE_IOERR if anything goes
3171** wrong.
drh339eb0b2008-03-07 15:34:11 +00003172*/
drh734c9862008-11-28 15:37:20 +00003173static int unixRead(
3174 sqlite3_file *id,
3175 void *pBuf,
3176 int amt,
3177 sqlite3_int64 offset
3178){
dan08da86a2009-08-21 17:18:03 +00003179 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003180 int got;
3181 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003182 assert( offset>=0 );
3183 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003184
dan08da86a2009-08-21 17:18:03 +00003185 /* If this is a database file (not a journal, master-journal or temp
3186 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003187#if 0
dane946c392009-08-22 11:39:46 +00003188 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003189 || offset>=PENDING_BYTE+512
3190 || offset+amt<=PENDING_BYTE
3191 );
dan7c246102010-04-12 19:00:29 +00003192#endif
drh08c6d442009-02-09 17:34:07 +00003193
drh9b4c59f2013-04-15 17:03:42 +00003194#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003195 /* Deal with as much of this read request as possible by transfering
3196 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003197 if( offset<pFile->mmapSize ){
3198 if( offset+amt <= pFile->mmapSize ){
3199 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3200 return SQLITE_OK;
3201 }else{
3202 int nCopy = pFile->mmapSize - offset;
3203 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3204 pBuf = &((u8 *)pBuf)[nCopy];
3205 amt -= nCopy;
3206 offset += nCopy;
3207 }
3208 }
drh6e0b6d52013-04-09 16:19:20 +00003209#endif
danf23da962013-03-23 21:00:41 +00003210
dan08da86a2009-08-21 17:18:03 +00003211 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003212 if( got==amt ){
3213 return SQLITE_OK;
3214 }else if( got<0 ){
3215 /* lastErrno set by seekAndRead */
3216 return SQLITE_IOERR_READ;
3217 }else{
dan08da86a2009-08-21 17:18:03 +00003218 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003219 /* Unread parts of the buffer must be zero-filled */
3220 memset(&((char*)pBuf)[got], 0, amt-got);
3221 return SQLITE_IOERR_SHORT_READ;
3222 }
3223}
3224
3225/*
dan47a2b4a2013-04-26 16:09:29 +00003226** Attempt to seek the file-descriptor passed as the first argument to
3227** absolute offset iOff, then attempt to write nBuf bytes of data from
3228** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3229** return the actual number of bytes written (which may be less than
3230** nBuf).
3231*/
3232static int seekAndWriteFd(
3233 int fd, /* File descriptor to write to */
3234 i64 iOff, /* File offset to begin writing at */
3235 const void *pBuf, /* Copy data from this buffer to the file */
3236 int nBuf, /* Size of buffer pBuf in bytes */
3237 int *piErrno /* OUT: Error number if error occurs */
3238){
3239 int rc = 0; /* Value returned by system call */
3240
3241 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003242 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003243 nBuf &= 0x1ffff;
3244 TIMER_START;
3245
3246#if defined(USE_PREAD)
3247 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3248#elif defined(USE_PREAD64)
3249 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3250#else
3251 do{
3252 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3253 SimulateIOError( iSeek-- );
3254
3255 if( iSeek!=iOff ){
3256 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3257 return -1;
3258 }
3259 rc = osWrite(fd, pBuf, nBuf);
3260 }while( rc<0 && errno==EINTR );
3261#endif
3262
3263 TIMER_END;
3264 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3265
3266 if( rc<0 && piErrno ) *piErrno = errno;
3267 return rc;
3268}
3269
3270
3271/*
drh734c9862008-11-28 15:37:20 +00003272** Seek to the offset in id->offset then read cnt bytes into pBuf.
3273** Return the number of bytes actually read. Update the offset.
3274**
3275** To avoid stomping the errno value on a failed write the lastErrno value
3276** is set before returning.
3277*/
3278static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003279 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003280}
3281
3282
3283/*
3284** Write data from a buffer into a file. Return SQLITE_OK on success
3285** or some other error code on failure.
3286*/
3287static int unixWrite(
3288 sqlite3_file *id,
3289 const void *pBuf,
3290 int amt,
3291 sqlite3_int64 offset
3292){
dan08da86a2009-08-21 17:18:03 +00003293 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003294 int wrote = 0;
3295 assert( id );
3296 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003297
dan08da86a2009-08-21 17:18:03 +00003298 /* If this is a database file (not a journal, master-journal or temp
3299 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003300#if 0
dane946c392009-08-22 11:39:46 +00003301 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003302 || offset>=PENDING_BYTE+512
3303 || offset+amt<=PENDING_BYTE
3304 );
dan7c246102010-04-12 19:00:29 +00003305#endif
drh08c6d442009-02-09 17:34:07 +00003306
drhd3d8c042012-05-29 17:02:40 +00003307#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003308 /* If we are doing a normal write to a database file (as opposed to
3309 ** doing a hot-journal rollback or a write to some file other than a
3310 ** normal database file) then record the fact that the database
3311 ** has changed. If the transaction counter is modified, record that
3312 ** fact too.
3313 */
dan08da86a2009-08-21 17:18:03 +00003314 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003315 pFile->dbUpdate = 1; /* The database has been modified */
3316 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003317 int rc;
drh8f941bc2009-01-14 23:03:40 +00003318 char oldCntr[4];
3319 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003320 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003321 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003322 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003323 pFile->transCntrChng = 1; /* The transaction counter has changed */
3324 }
3325 }
3326 }
3327#endif
3328
drh9b4c59f2013-04-15 17:03:42 +00003329#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003330 /* Deal with as much of this write request as possible by transfering
3331 ** data from the memory mapping using memcpy(). */
3332 if( offset<pFile->mmapSize ){
3333 if( offset+amt <= pFile->mmapSize ){
3334 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3335 return SQLITE_OK;
3336 }else{
3337 int nCopy = pFile->mmapSize - offset;
3338 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3339 pBuf = &((u8 *)pBuf)[nCopy];
3340 amt -= nCopy;
3341 offset += nCopy;
3342 }
3343 }
drh6e0b6d52013-04-09 16:19:20 +00003344#endif
danf23da962013-03-23 21:00:41 +00003345
dan08da86a2009-08-21 17:18:03 +00003346 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003347 amt -= wrote;
3348 offset += wrote;
3349 pBuf = &((char*)pBuf)[wrote];
3350 }
3351 SimulateIOError(( wrote=(-1), amt=1 ));
3352 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003353
drh734c9862008-11-28 15:37:20 +00003354 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003355 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003356 /* lastErrno set by seekAndWrite */
3357 return SQLITE_IOERR_WRITE;
3358 }else{
dan08da86a2009-08-21 17:18:03 +00003359 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003360 return SQLITE_FULL;
3361 }
3362 }
dan6e09d692010-07-27 18:34:15 +00003363
drh734c9862008-11-28 15:37:20 +00003364 return SQLITE_OK;
3365}
3366
3367#ifdef SQLITE_TEST
3368/*
3369** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003370** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003371*/
3372int sqlite3_sync_count = 0;
3373int sqlite3_fullsync_count = 0;
3374#endif
3375
3376/*
drh89240432009-03-25 01:06:01 +00003377** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003378** Others do no. To be safe, we will stick with the (slightly slower)
3379** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003380** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003381*/
drh20f8e132011-08-31 21:01:55 +00003382#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003383# define fdatasync fsync
3384#endif
3385
3386/*
3387** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3388** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3389** only available on Mac OS X. But that could change.
3390*/
3391#ifdef F_FULLFSYNC
3392# define HAVE_FULLFSYNC 1
3393#else
3394# define HAVE_FULLFSYNC 0
3395#endif
3396
3397
3398/*
3399** The fsync() system call does not work as advertised on many
3400** unix systems. The following procedure is an attempt to make
3401** it work better.
3402**
3403** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3404** for testing when we want to run through the test suite quickly.
3405** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3406** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3407** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003408**
3409** SQLite sets the dataOnly flag if the size of the file is unchanged.
3410** The idea behind dataOnly is that it should only write the file content
3411** to disk, not the inode. We only set dataOnly if the file size is
3412** unchanged since the file size is part of the inode. However,
3413** Ted Ts'o tells us that fdatasync() will also write the inode if the
3414** file size has changed. The only real difference between fdatasync()
3415** and fsync(), Ted tells us, is that fdatasync() will not flush the
3416** inode if the mtime or owner or other inode attributes have changed.
3417** We only care about the file size, not the other file attributes, so
3418** as far as SQLite is concerned, an fdatasync() is always adequate.
3419** So, we always use fdatasync() if it is available, regardless of
3420** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003421*/
3422static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003423 int rc;
drh734c9862008-11-28 15:37:20 +00003424
3425 /* The following "ifdef/elif/else/" block has the same structure as
3426 ** the one below. It is replicated here solely to avoid cluttering
3427 ** up the real code with the UNUSED_PARAMETER() macros.
3428 */
3429#ifdef SQLITE_NO_SYNC
3430 UNUSED_PARAMETER(fd);
3431 UNUSED_PARAMETER(fullSync);
3432 UNUSED_PARAMETER(dataOnly);
3433#elif HAVE_FULLFSYNC
3434 UNUSED_PARAMETER(dataOnly);
3435#else
3436 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003437 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003438#endif
3439
3440 /* Record the number of times that we do a normal fsync() and
3441 ** FULLSYNC. This is used during testing to verify that this procedure
3442 ** gets called with the correct arguments.
3443 */
3444#ifdef SQLITE_TEST
3445 if( fullSync ) sqlite3_fullsync_count++;
3446 sqlite3_sync_count++;
3447#endif
3448
3449 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3450 ** no-op
3451 */
3452#ifdef SQLITE_NO_SYNC
3453 rc = SQLITE_OK;
3454#elif HAVE_FULLFSYNC
3455 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003456 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003457 }else{
3458 rc = 1;
3459 }
3460 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003461 ** It shouldn't be possible for fullfsync to fail on the local
3462 ** file system (on OSX), so failure indicates that FULLFSYNC
3463 ** isn't supported for this file system. So, attempt an fsync
3464 ** and (for now) ignore the overhead of a superfluous fcntl call.
3465 ** It'd be better to detect fullfsync support once and avoid
3466 ** the fcntl call every time sync is called.
3467 */
drh734c9862008-11-28 15:37:20 +00003468 if( rc ) rc = fsync(fd);
3469
drh7ed97b92010-01-20 13:07:21 +00003470#elif defined(__APPLE__)
3471 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3472 ** so currently we default to the macro that redefines fdatasync to fsync
3473 */
3474 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003475#else
drh0b647ff2009-03-21 14:41:04 +00003476 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003477#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003478 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003479 rc = fsync(fd);
3480 }
drh0b647ff2009-03-21 14:41:04 +00003481#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003482#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3483
3484 if( OS_VXWORKS && rc!= -1 ){
3485 rc = 0;
3486 }
chw97185482008-11-17 08:05:31 +00003487 return rc;
drhbfe66312006-10-03 17:40:40 +00003488}
3489
drh734c9862008-11-28 15:37:20 +00003490/*
drh0059eae2011-08-08 23:48:40 +00003491** Open a file descriptor to the directory containing file zFilename.
3492** If successful, *pFd is set to the opened file descriptor and
3493** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3494** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3495** value.
3496**
drh90315a22011-08-10 01:52:12 +00003497** The directory file descriptor is used for only one thing - to
3498** fsync() a directory to make sure file creation and deletion events
3499** are flushed to disk. Such fsyncs are not needed on newer
3500** journaling filesystems, but are required on older filesystems.
3501**
3502** This routine can be overridden using the xSetSysCall interface.
3503** The ability to override this routine was added in support of the
3504** chromium sandbox. Opening a directory is a security risk (we are
3505** told) so making it overrideable allows the chromium sandbox to
3506** replace this routine with a harmless no-op. To make this routine
3507** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3508** *pFd set to a negative number.
3509**
drh0059eae2011-08-08 23:48:40 +00003510** If SQLITE_OK is returned, the caller is responsible for closing
3511** the file descriptor *pFd using close().
3512*/
3513static int openDirectory(const char *zFilename, int *pFd){
3514 int ii;
3515 int fd = -1;
3516 char zDirname[MAX_PATHNAME+1];
3517
3518 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3519 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3520 if( ii>0 ){
3521 zDirname[ii] = '\0';
3522 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3523 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003524 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3525 }
3526 }
3527 *pFd = fd;
3528 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3529}
3530
3531/*
drh734c9862008-11-28 15:37:20 +00003532** Make sure all writes to a particular file are committed to disk.
3533**
3534** If dataOnly==0 then both the file itself and its metadata (file
3535** size, access time, etc) are synced. If dataOnly!=0 then only the
3536** file data is synced.
3537**
3538** Under Unix, also make sure that the directory entry for the file
3539** has been created by fsync-ing the directory that contains the file.
3540** If we do not do this and we encounter a power failure, the directory
3541** entry for the journal might not exist after we reboot. The next
3542** SQLite to access the file will not know that the journal exists (because
3543** the directory entry for the journal was never created) and the transaction
3544** will not roll back - possibly leading to database corruption.
3545*/
3546static int unixSync(sqlite3_file *id, int flags){
3547 int rc;
3548 unixFile *pFile = (unixFile*)id;
3549
3550 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3551 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3552
3553 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3554 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3555 || (flags&0x0F)==SQLITE_SYNC_FULL
3556 );
3557
3558 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3559 ** line is to test that doing so does not cause any problems.
3560 */
3561 SimulateDiskfullError( return SQLITE_FULL );
3562
3563 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003564 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003565 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3566 SimulateIOError( rc=1 );
3567 if( rc ){
3568 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003569 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003570 }
drh0059eae2011-08-08 23:48:40 +00003571
3572 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003573 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003574 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003575 */
3576 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3577 int dirfd;
3578 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003579 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003580 rc = osOpenDirectory(pFile->zPath, &dirfd);
3581 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003582 full_fsync(dirfd, 0, 0);
3583 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003584 }else if( rc==SQLITE_CANTOPEN ){
3585 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003586 }
drh0059eae2011-08-08 23:48:40 +00003587 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003588 }
3589 return rc;
3590}
3591
3592/*
3593** Truncate an open file to a specified size
3594*/
3595static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003596 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003597 int rc;
dan6e09d692010-07-27 18:34:15 +00003598 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003599 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003600
3601 /* If the user has configured a chunk-size for this file, truncate the
3602 ** file so that it consists of an integer number of chunks (i.e. the
3603 ** actual file size after the operation may be larger than the requested
3604 ** size).
3605 */
drhb8af4b72012-04-05 20:04:39 +00003606 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003607 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3608 }
3609
drhff812312011-02-23 13:33:46 +00003610 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003611 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003612 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003613 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003614 }else{
drhd3d8c042012-05-29 17:02:40 +00003615#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003616 /* If we are doing a normal write to a database file (as opposed to
3617 ** doing a hot-journal rollback or a write to some file other than a
3618 ** normal database file) and we truncate the file to zero length,
3619 ** that effectively updates the change counter. This might happen
3620 ** when restoring a database using the backup API from a zero-length
3621 ** source.
3622 */
dan6e09d692010-07-27 18:34:15 +00003623 if( pFile->inNormalWrite && nByte==0 ){
3624 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003625 }
danf23da962013-03-23 21:00:41 +00003626#endif
danc0003312013-03-22 17:46:11 +00003627
mistachkine98844f2013-08-24 00:59:24 +00003628#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003629 /* If the file was just truncated to a size smaller than the currently
3630 ** mapped region, reduce the effective mapping size as well. SQLite will
3631 ** use read() and write() to access data beyond this point from now on.
3632 */
3633 if( nByte<pFile->mmapSize ){
3634 pFile->mmapSize = nByte;
3635 }
mistachkine98844f2013-08-24 00:59:24 +00003636#endif
drh3313b142009-11-06 04:13:18 +00003637
drh734c9862008-11-28 15:37:20 +00003638 return SQLITE_OK;
3639 }
3640}
3641
3642/*
3643** Determine the current size of a file in bytes
3644*/
3645static int unixFileSize(sqlite3_file *id, i64 *pSize){
3646 int rc;
3647 struct stat buf;
3648 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003649 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003650 SimulateIOError( rc=1 );
3651 if( rc!=0 ){
3652 ((unixFile*)id)->lastErrno = errno;
3653 return SQLITE_IOERR_FSTAT;
3654 }
3655 *pSize = buf.st_size;
3656
drh8af6c222010-05-14 12:43:01 +00003657 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003658 ** writes a single byte into that file in order to work around a bug
3659 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3660 ** layers, we need to report this file size as zero even though it is
3661 ** really 1. Ticket #3260.
3662 */
3663 if( *pSize==1 ) *pSize = 0;
3664
3665
3666 return SQLITE_OK;
3667}
3668
drhd2cb50b2009-01-09 21:41:17 +00003669#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003670/*
3671** Handler for proxy-locking file-control verbs. Defined below in the
3672** proxying locking division.
3673*/
3674static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003675#endif
drh715ff302008-12-03 22:32:44 +00003676
dan502019c2010-07-28 14:26:17 +00003677/*
3678** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003679** file-control operation. Enlarge the database to nBytes in size
3680** (rounded up to the next chunk-size). If the database is already
3681** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003682*/
3683static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003684 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003685 i64 nSize; /* Required file size */
3686 struct stat buf; /* Used to hold return values of fstat() */
3687
drh99ab3b12011-03-02 15:09:07 +00003688 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003689
3690 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3691 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003692
dan502019c2010-07-28 14:26:17 +00003693#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003694 /* The code below is handling the return value of osFallocate()
3695 ** correctly. posix_fallocate() is defined to "returns zero on success,
3696 ** or an error number on failure". See the manpage for details. */
3697 int err;
drhff812312011-02-23 13:33:46 +00003698 do{
dan661d71a2011-03-30 19:08:03 +00003699 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3700 }while( err==EINTR );
3701 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003702#else
3703 /* If the OS does not have posix_fallocate(), fake it. First use
3704 ** ftruncate() to set the file size, then write a single byte to
3705 ** the last byte in each block within the extended region. This
3706 ** is the same technique used by glibc to implement posix_fallocate()
3707 ** on systems that do not have a real fallocate() system call.
3708 */
3709 int nBlk = buf.st_blksize; /* File-system block size */
3710 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003711
drhff812312011-02-23 13:33:46 +00003712 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003713 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003714 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003715 }
3716 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003717 while( iWrite<nSize ){
3718 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3719 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003720 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003721 }
dan502019c2010-07-28 14:26:17 +00003722#endif
3723 }
3724 }
3725
mistachkine98844f2013-08-24 00:59:24 +00003726#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003727 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003728 int rc;
3729 if( pFile->szChunk<=0 ){
3730 if( robust_ftruncate(pFile->h, nByte) ){
3731 pFile->lastErrno = errno;
3732 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3733 }
3734 }
3735
3736 rc = unixMapfile(pFile, nByte);
3737 return rc;
3738 }
mistachkine98844f2013-08-24 00:59:24 +00003739#endif
danf23da962013-03-23 21:00:41 +00003740
dan502019c2010-07-28 14:26:17 +00003741 return SQLITE_OK;
3742}
danielk1977ad94b582007-08-20 06:44:22 +00003743
danielk1977e3026632004-06-22 11:29:02 +00003744/*
drhf12b3f62011-12-21 14:42:29 +00003745** If *pArg is inititially negative then this is a query. Set *pArg to
3746** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3747**
3748** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3749*/
3750static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3751 if( *pArg<0 ){
3752 *pArg = (pFile->ctrlFlags & mask)!=0;
3753 }else if( (*pArg)==0 ){
3754 pFile->ctrlFlags &= ~mask;
3755 }else{
3756 pFile->ctrlFlags |= mask;
3757 }
3758}
3759
drh696b33e2012-12-06 19:01:42 +00003760/* Forward declaration */
3761static int unixGetTempname(int nBuf, char *zBuf);
3762
drhf12b3f62011-12-21 14:42:29 +00003763/*
drh9e33c2c2007-08-31 18:34:59 +00003764** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003765*/
drhcc6bb3e2007-08-31 16:11:35 +00003766static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003767 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003768 switch( op ){
3769 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003770 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003771 return SQLITE_OK;
3772 }
drh7708e972008-11-29 00:56:52 +00003773 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003774 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003775 return SQLITE_OK;
3776 }
dan6e09d692010-07-27 18:34:15 +00003777 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003778 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003779 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003780 }
drh9ff27ec2010-05-19 19:26:05 +00003781 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003782 int rc;
3783 SimulateIOErrorBenign(1);
3784 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3785 SimulateIOErrorBenign(0);
3786 return rc;
drhf0b190d2011-07-26 16:03:07 +00003787 }
3788 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003789 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3790 return SQLITE_OK;
3791 }
drhcb15f352011-12-23 01:04:17 +00003792 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3793 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003794 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003795 }
drhde60fc22011-12-14 17:53:36 +00003796 case SQLITE_FCNTL_VFSNAME: {
3797 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3798 return SQLITE_OK;
3799 }
drh696b33e2012-12-06 19:01:42 +00003800 case SQLITE_FCNTL_TEMPFILENAME: {
3801 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3802 if( zTFile ){
3803 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3804 *(char**)pArg = zTFile;
3805 }
3806 return SQLITE_OK;
3807 }
mistachkine98844f2013-08-24 00:59:24 +00003808#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003809 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003810 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003811 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003812 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3813 newLimit = sqlite3GlobalConfig.mxMmap;
3814 }
3815 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003816 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003817 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003818 if( pFile->mmapSize>0 ){
3819 unixUnmapfile(pFile);
3820 rc = unixMapfile(pFile, -1);
3821 }
danbcb8a862013-04-08 15:30:41 +00003822 }
drh34e258c2013-05-23 01:40:53 +00003823 return rc;
danb2d3de32013-03-14 18:34:37 +00003824 }
mistachkine98844f2013-08-24 00:59:24 +00003825#endif
drhd3d8c042012-05-29 17:02:40 +00003826#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003827 /* The pager calls this method to signal that it has done
3828 ** a rollback and that the database is therefore unchanged and
3829 ** it hence it is OK for the transaction change counter to be
3830 ** unchanged.
3831 */
3832 case SQLITE_FCNTL_DB_UNCHANGED: {
3833 ((unixFile*)id)->dbUpdate = 0;
3834 return SQLITE_OK;
3835 }
3836#endif
drhd2cb50b2009-01-09 21:41:17 +00003837#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003838 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003839 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003840 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003841 }
drhd2cb50b2009-01-09 21:41:17 +00003842#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003843 }
drh0b52b7d2011-01-26 19:46:22 +00003844 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003845}
3846
3847/*
danielk1977a3d4c882007-03-23 10:08:38 +00003848** Return the sector size in bytes of the underlying block device for
3849** the specified file. This is almost always 512 bytes, but may be
3850** larger for some devices.
3851**
3852** SQLite code assumes this function cannot fail. It also assumes that
3853** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003854** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003855** same for both.
3856*/
drh537dddf2012-10-26 13:46:24 +00003857#ifndef __QNXNTO__
3858static int unixSectorSize(sqlite3_file *NotUsed){
3859 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003860 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003861}
drh537dddf2012-10-26 13:46:24 +00003862#endif
3863
3864/*
3865** The following version of unixSectorSize() is optimized for QNX.
3866*/
3867#ifdef __QNXNTO__
3868#include <sys/dcmd_blk.h>
3869#include <sys/statvfs.h>
3870static int unixSectorSize(sqlite3_file *id){
3871 unixFile *pFile = (unixFile*)id;
3872 if( pFile->sectorSize == 0 ){
3873 struct statvfs fsInfo;
3874
3875 /* Set defaults for non-supported filesystems */
3876 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3877 pFile->deviceCharacteristics = 0;
3878 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3879 return pFile->sectorSize;
3880 }
3881
3882 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3883 pFile->sectorSize = fsInfo.f_bsize;
3884 pFile->deviceCharacteristics =
3885 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3886 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3887 ** the write succeeds */
3888 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3889 ** so it is ordered */
3890 0;
3891 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3892 pFile->sectorSize = fsInfo.f_bsize;
3893 pFile->deviceCharacteristics =
3894 /* etfs cluster size writes are atomic */
3895 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3896 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3897 ** the write succeeds */
3898 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3899 ** so it is ordered */
3900 0;
3901 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3902 pFile->sectorSize = fsInfo.f_bsize;
3903 pFile->deviceCharacteristics =
3904 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3905 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3906 ** the write succeeds */
3907 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3908 ** so it is ordered */
3909 0;
3910 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3911 pFile->sectorSize = fsInfo.f_bsize;
3912 pFile->deviceCharacteristics =
3913 /* full bitset of atomics from max sector size and smaller */
3914 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3915 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3916 ** so it is ordered */
3917 0;
3918 }else if( strstr(fsInfo.f_basetype, "dos") ){
3919 pFile->sectorSize = fsInfo.f_bsize;
3920 pFile->deviceCharacteristics =
3921 /* full bitset of atomics from max sector size and smaller */
3922 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3923 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3924 ** so it is ordered */
3925 0;
3926 }else{
3927 pFile->deviceCharacteristics =
3928 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3929 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3930 ** the write succeeds */
3931 0;
3932 }
3933 }
3934 /* Last chance verification. If the sector size isn't a multiple of 512
3935 ** then it isn't valid.*/
3936 if( pFile->sectorSize % 512 != 0 ){
3937 pFile->deviceCharacteristics = 0;
3938 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3939 }
3940 return pFile->sectorSize;
3941}
3942#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003943
danielk197790949c22007-08-17 16:50:38 +00003944/*
drhf12b3f62011-12-21 14:42:29 +00003945** Return the device characteristics for the file.
3946**
drhcb15f352011-12-23 01:04:17 +00003947** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3948** However, that choice is contraversial since technically the underlying
3949** file system does not always provide powersafe overwrites. (In other
3950** words, after a power-loss event, parts of the file that were never
3951** written might end up being altered.) However, non-PSOW behavior is very,
3952** very rare. And asserting PSOW makes a large reduction in the amount
3953** of required I/O for journaling, since a lot of padding is eliminated.
3954** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3955** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003956*/
drhf12b3f62011-12-21 14:42:29 +00003957static int unixDeviceCharacteristics(sqlite3_file *id){
3958 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003959 int rc = 0;
3960#ifdef __QNXNTO__
3961 if( p->sectorSize==0 ) unixSectorSize(id);
3962 rc = p->deviceCharacteristics;
3963#endif
drhcb15f352011-12-23 01:04:17 +00003964 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003965 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003966 }
drh537dddf2012-10-26 13:46:24 +00003967 return rc;
danielk197762079062007-08-15 17:08:46 +00003968}
3969
drhd9e5c4f2010-05-12 18:01:39 +00003970#ifndef SQLITE_OMIT_WAL
3971
3972
3973/*
drhd91c68f2010-05-14 14:52:25 +00003974** Object used to represent an shared memory buffer.
3975**
3976** When multiple threads all reference the same wal-index, each thread
3977** has its own unixShm object, but they all point to a single instance
3978** of this unixShmNode object. In other words, each wal-index is opened
3979** only once per process.
3980**
3981** Each unixShmNode object is connected to a single unixInodeInfo object.
3982** We could coalesce this object into unixInodeInfo, but that would mean
3983** every open file that does not use shared memory (in other words, most
3984** open files) would have to carry around this extra information. So
3985** the unixInodeInfo object contains a pointer to this unixShmNode object
3986** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003987**
3988** unixMutexHeld() must be true when creating or destroying
3989** this object or while reading or writing the following fields:
3990**
3991** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003992**
3993** The following fields are read-only after the object is created:
3994**
3995** fid
3996** zFilename
3997**
drhd91c68f2010-05-14 14:52:25 +00003998** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003999** unixMutexHeld() is true when reading or writing any other field
4000** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004001*/
drhd91c68f2010-05-14 14:52:25 +00004002struct unixShmNode {
4003 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004004 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004005 char *zFilename; /* Name of the mmapped file */
4006 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004007 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004008 u16 nRegion; /* Size of array apRegion */
4009 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004010 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004011 int nRef; /* Number of unixShm objects pointing to this */
4012 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004013#ifdef SQLITE_DEBUG
4014 u8 exclMask; /* Mask of exclusive locks held */
4015 u8 sharedMask; /* Mask of shared locks held */
4016 u8 nextShmId; /* Next available unixShm.id value */
4017#endif
4018};
4019
4020/*
drhd9e5c4f2010-05-12 18:01:39 +00004021** Structure used internally by this VFS to record the state of an
4022** open shared memory connection.
4023**
drhd91c68f2010-05-14 14:52:25 +00004024** The following fields are initialized when this object is created and
4025** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004026**
drhd91c68f2010-05-14 14:52:25 +00004027** unixShm.pFile
4028** unixShm.id
4029**
4030** All other fields are read/write. The unixShm.pFile->mutex must be held
4031** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004032*/
4033struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004034 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4035 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004036 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004037 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004038 u16 sharedMask; /* Mask of shared locks held */
4039 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004040};
4041
4042/*
drhd9e5c4f2010-05-12 18:01:39 +00004043** Constants used for locking
4044*/
drhbd9676c2010-06-23 17:58:38 +00004045#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004046#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004047
drhd9e5c4f2010-05-12 18:01:39 +00004048/*
drh73b64e42010-05-30 19:55:15 +00004049** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004050**
4051** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4052** otherwise.
4053*/
4054static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004055 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4056 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004057 int ofst, /* First byte of the locking range */
4058 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004059){
4060 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004061 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004062
drhd91c68f2010-05-14 14:52:25 +00004063 /* Access to the unixShmNode object is serialized by the caller */
4064 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004065
drh73b64e42010-05-30 19:55:15 +00004066 /* Shared locks never span more than one byte */
4067 assert( n==1 || lockType!=F_RDLCK );
4068
4069 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004070 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004071
drh3cb93392011-03-12 18:10:44 +00004072 if( pShmNode->h>=0 ){
4073 /* Initialize the locking parameters */
4074 memset(&f, 0, sizeof(f));
4075 f.l_type = lockType;
4076 f.l_whence = SEEK_SET;
4077 f.l_start = ofst;
4078 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004079
drh3cb93392011-03-12 18:10:44 +00004080 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4081 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4082 }
drhd9e5c4f2010-05-12 18:01:39 +00004083
4084 /* Update the global lock state and do debug tracing */
4085#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004086 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004087 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00004088 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004089 if( rc==SQLITE_OK ){
4090 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004091 OSTRACE(("unlock %d ok", ofst));
4092 pShmNode->exclMask &= ~mask;
4093 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004094 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004095 OSTRACE(("read-lock %d ok", ofst));
4096 pShmNode->exclMask &= ~mask;
4097 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004098 }else{
4099 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004100 OSTRACE(("write-lock %d ok", ofst));
4101 pShmNode->exclMask |= mask;
4102 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004103 }
4104 }else{
4105 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004106 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004107 }else if( lockType==F_RDLCK ){
4108 OSTRACE(("read-lock failed"));
4109 }else{
4110 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004111 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004112 }
4113 }
drh20e1f082010-05-31 16:10:12 +00004114 OSTRACE((" - afterwards %03x,%03x\n",
4115 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004116 }
drhd9e5c4f2010-05-12 18:01:39 +00004117#endif
4118
4119 return rc;
4120}
4121
drhd9e5c4f2010-05-12 18:01:39 +00004122
4123/*
drhd91c68f2010-05-14 14:52:25 +00004124** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004125**
4126** This is not a VFS shared-memory method; it is a utility function called
4127** by VFS shared-memory methods.
4128*/
drhd91c68f2010-05-14 14:52:25 +00004129static void unixShmPurge(unixFile *pFd){
4130 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004131 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004132 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00004133 int i;
drhd91c68f2010-05-14 14:52:25 +00004134 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004135 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00004136 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00004137 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004138 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004139 }else{
4140 sqlite3_free(p->apRegion[i]);
4141 }
dan13a3cb82010-06-11 19:04:21 +00004142 }
dan18801912010-06-14 14:07:50 +00004143 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004144 if( p->h>=0 ){
4145 robust_close(pFd, p->h, __LINE__);
4146 p->h = -1;
4147 }
drhd91c68f2010-05-14 14:52:25 +00004148 p->pInode->pShmNode = 0;
4149 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004150 }
4151}
4152
4153/*
danda9fe0c2010-07-13 18:44:03 +00004154** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004155** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004156**
drh7234c6d2010-06-19 15:10:09 +00004157** The file used to implement shared-memory is in the same directory
4158** as the open database file and has the same name as the open database
4159** file with the "-shm" suffix added. For example, if the database file
4160** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004161** for shared memory will be called "/home/user1/config.db-shm".
4162**
4163** Another approach to is to use files in /dev/shm or /dev/tmp or an
4164** some other tmpfs mount. But if a file in a different directory
4165** from the database file is used, then differing access permissions
4166** or a chroot() might cause two different processes on the same
4167** database to end up using different files for shared memory -
4168** meaning that their memory would not really be shared - resulting
4169** in database corruption. Nevertheless, this tmpfs file usage
4170** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4171** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4172** option results in an incompatible build of SQLite; builds of SQLite
4173** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4174** same database file at the same time, database corruption will likely
4175** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4176** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004177**
4178** When opening a new shared-memory file, if no other instances of that
4179** file are currently open, in this process or in other processes, then
4180** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004181**
4182** If the original database file (pDbFd) is using the "unix-excl" VFS
4183** that means that an exclusive lock is held on the database file and
4184** that no other processes are able to read or write the database. In
4185** that case, we do not really need shared memory. No shared memory
4186** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004187*/
danda9fe0c2010-07-13 18:44:03 +00004188static int unixOpenSharedMemory(unixFile *pDbFd){
4189 struct unixShm *p = 0; /* The connection to be opened */
4190 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4191 int rc; /* Result code */
4192 unixInodeInfo *pInode; /* The inode of fd */
4193 char *zShmFilename; /* Name of the file used for SHM */
4194 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004195
danda9fe0c2010-07-13 18:44:03 +00004196 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004197 p = sqlite3_malloc( sizeof(*p) );
4198 if( p==0 ) return SQLITE_NOMEM;
4199 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004200 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004201
danda9fe0c2010-07-13 18:44:03 +00004202 /* Check to see if a unixShmNode object already exists. Reuse an existing
4203 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004204 */
4205 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004206 pInode = pDbFd->pInode;
4207 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004208 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004209 struct stat sStat; /* fstat() info for database file */
4210
4211 /* Call fstat() to figure out the permissions on the database file. If
4212 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004213 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004214 */
drh3cb93392011-03-12 18:10:44 +00004215 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004216 rc = SQLITE_IOERR_FSTAT;
4217 goto shm_open_err;
4218 }
4219
drha4ced192010-07-15 18:32:40 +00004220#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004221 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004222#else
drh52bcde02012-01-03 14:50:45 +00004223 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004224#endif
drh7234c6d2010-06-19 15:10:09 +00004225 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004226 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004227 rc = SQLITE_NOMEM;
4228 goto shm_open_err;
4229 }
drh9cb5a0d2012-01-05 21:19:54 +00004230 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004231 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004232#ifdef SQLITE_SHM_DIRECTORY
4233 sqlite3_snprintf(nShmFilename, zShmFilename,
4234 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4235 (u32)sStat.st_ino, (u32)sStat.st_dev);
4236#else
drh7234c6d2010-06-19 15:10:09 +00004237 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004238 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004239#endif
drhd91c68f2010-05-14 14:52:25 +00004240 pShmNode->h = -1;
4241 pDbFd->pInode->pShmNode = pShmNode;
4242 pShmNode->pInode = pDbFd->pInode;
4243 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4244 if( pShmNode->mutex==0 ){
4245 rc = SQLITE_NOMEM;
4246 goto shm_open_err;
4247 }
drhd9e5c4f2010-05-12 18:01:39 +00004248
drh3cb93392011-03-12 18:10:44 +00004249 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004250 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004251 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004252 openFlags = O_RDONLY;
4253 pShmNode->isReadonly = 1;
4254 }
4255 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004256 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004257 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4258 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004259 }
drhac7c3ac2012-02-11 19:23:48 +00004260
4261 /* If this process is running as root, make sure that the SHM file
4262 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004263 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004264 */
drhed466822012-05-31 13:10:49 +00004265 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004266
4267 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004268 ** If not, truncate the file to zero length.
4269 */
4270 rc = SQLITE_OK;
4271 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4272 if( robust_ftruncate(pShmNode->h, 0) ){
4273 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004274 }
4275 }
drh66dfec8b2011-06-01 20:01:49 +00004276 if( rc==SQLITE_OK ){
4277 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4278 }
4279 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004280 }
drhd9e5c4f2010-05-12 18:01:39 +00004281 }
4282
drhd91c68f2010-05-14 14:52:25 +00004283 /* Make the new connection a child of the unixShmNode */
4284 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004285#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004286 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004287#endif
drhd91c68f2010-05-14 14:52:25 +00004288 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004289 pDbFd->pShm = p;
4290 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004291
4292 /* The reference count on pShmNode has already been incremented under
4293 ** the cover of the unixEnterMutex() mutex and the pointer from the
4294 ** new (struct unixShm) object to the pShmNode has been set. All that is
4295 ** left to do is to link the new object into the linked list starting
4296 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4297 ** mutex.
4298 */
4299 sqlite3_mutex_enter(pShmNode->mutex);
4300 p->pNext = pShmNode->pFirst;
4301 pShmNode->pFirst = p;
4302 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004303 return SQLITE_OK;
4304
4305 /* Jump here on any error */
4306shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004307 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004308 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004309 unixLeaveMutex();
4310 return rc;
4311}
4312
4313/*
danda9fe0c2010-07-13 18:44:03 +00004314** This function is called to obtain a pointer to region iRegion of the
4315** shared-memory associated with the database file fd. Shared-memory regions
4316** are numbered starting from zero. Each shared-memory region is szRegion
4317** bytes in size.
4318**
4319** If an error occurs, an error code is returned and *pp is set to NULL.
4320**
4321** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4322** region has not been allocated (by any client, including one running in a
4323** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4324** bExtend is non-zero and the requested shared-memory region has not yet
4325** been allocated, it is allocated by this function.
4326**
4327** If the shared-memory region has already been allocated or is allocated by
4328** this call as described above, then it is mapped into this processes
4329** address space (if it is not already), *pp is set to point to the mapped
4330** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004331*/
danda9fe0c2010-07-13 18:44:03 +00004332static int unixShmMap(
4333 sqlite3_file *fd, /* Handle open on database file */
4334 int iRegion, /* Region to retrieve */
4335 int szRegion, /* Size of regions */
4336 int bExtend, /* True to extend file if necessary */
4337 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004338){
danda9fe0c2010-07-13 18:44:03 +00004339 unixFile *pDbFd = (unixFile*)fd;
4340 unixShm *p;
4341 unixShmNode *pShmNode;
4342 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004343
danda9fe0c2010-07-13 18:44:03 +00004344 /* If the shared-memory file has not yet been opened, open it now. */
4345 if( pDbFd->pShm==0 ){
4346 rc = unixOpenSharedMemory(pDbFd);
4347 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004348 }
drhd9e5c4f2010-05-12 18:01:39 +00004349
danda9fe0c2010-07-13 18:44:03 +00004350 p = pDbFd->pShm;
4351 pShmNode = p->pShmNode;
4352 sqlite3_mutex_enter(pShmNode->mutex);
4353 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004354 assert( pShmNode->pInode==pDbFd->pInode );
4355 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4356 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004357
4358 if( pShmNode->nRegion<=iRegion ){
4359 char **apNew; /* New apRegion[] array */
4360 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4361 struct stat sStat; /* Used by fstat() */
4362
4363 pShmNode->szRegion = szRegion;
4364
drh3cb93392011-03-12 18:10:44 +00004365 if( pShmNode->h>=0 ){
4366 /* The requested region is not mapped into this processes address space.
4367 ** Check to see if it has been allocated (i.e. if the wal-index file is
4368 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004369 */
drh3cb93392011-03-12 18:10:44 +00004370 if( osFstat(pShmNode->h, &sStat) ){
4371 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004372 goto shmpage_out;
4373 }
drh3cb93392011-03-12 18:10:44 +00004374
4375 if( sStat.st_size<nByte ){
4376 /* The requested memory region does not exist. If bExtend is set to
4377 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004378 */
dan47a2b4a2013-04-26 16:09:29 +00004379 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004380 goto shmpage_out;
4381 }
dan47a2b4a2013-04-26 16:09:29 +00004382
4383 /* Alternatively, if bExtend is true, extend the file. Do this by
4384 ** writing a single byte to the end of each (OS) page being
4385 ** allocated or extended. Technically, we need only write to the
4386 ** last page in order to extend the file. But writing to all new
4387 ** pages forces the OS to allocate them immediately, which reduces
4388 ** the chances of SIGBUS while accessing the mapped region later on.
4389 */
4390 else{
4391 static const int pgsz = 4096;
4392 int iPg;
4393
4394 /* Write to the last byte of each newly allocated or extended page */
4395 assert( (nByte % pgsz)==0 );
4396 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4397 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4398 const char *zFile = pShmNode->zFilename;
4399 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4400 goto shmpage_out;
4401 }
4402 }
drh3cb93392011-03-12 18:10:44 +00004403 }
4404 }
danda9fe0c2010-07-13 18:44:03 +00004405 }
4406
4407 /* Map the requested memory region into this processes address space. */
4408 apNew = (char **)sqlite3_realloc(
4409 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4410 );
4411 if( !apNew ){
4412 rc = SQLITE_IOERR_NOMEM;
4413 goto shmpage_out;
4414 }
4415 pShmNode->apRegion = apNew;
4416 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004417 void *pMem;
4418 if( pShmNode->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004419 pMem = osMmap(0, szRegion,
drh66dfec8b2011-06-01 20:01:49 +00004420 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004421 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004422 );
4423 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004424 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004425 goto shmpage_out;
4426 }
4427 }else{
4428 pMem = sqlite3_malloc(szRegion);
4429 if( pMem==0 ){
4430 rc = SQLITE_NOMEM;
4431 goto shmpage_out;
4432 }
4433 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004434 }
4435 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4436 pShmNode->nRegion++;
4437 }
4438 }
4439
4440shmpage_out:
4441 if( pShmNode->nRegion>iRegion ){
4442 *pp = pShmNode->apRegion[iRegion];
4443 }else{
4444 *pp = 0;
4445 }
drh66dfec8b2011-06-01 20:01:49 +00004446 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004447 sqlite3_mutex_leave(pShmNode->mutex);
4448 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004449}
4450
4451/*
drhd9e5c4f2010-05-12 18:01:39 +00004452** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004453**
4454** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4455** different here than in posix. In xShmLock(), one can go from unlocked
4456** to shared and back or from unlocked to exclusive and back. But one may
4457** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004458*/
4459static int unixShmLock(
4460 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004461 int ofst, /* First lock to acquire or release */
4462 int n, /* Number of locks to acquire or release */
4463 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004464){
drh73b64e42010-05-30 19:55:15 +00004465 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4466 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4467 unixShm *pX; /* For looping over all siblings */
4468 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4469 int rc = SQLITE_OK; /* Result code */
4470 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004471
drhd91c68f2010-05-14 14:52:25 +00004472 assert( pShmNode==pDbFd->pInode->pShmNode );
4473 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004474 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004475 assert( n>=1 );
4476 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4477 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4478 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4479 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4480 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004481 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4482 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004483
drhc99597c2010-05-31 01:41:15 +00004484 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004485 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004486 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004487 if( flags & SQLITE_SHM_UNLOCK ){
4488 u16 allMask = 0; /* Mask of locks held by siblings */
4489
4490 /* See if any siblings hold this same lock */
4491 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4492 if( pX==p ) continue;
4493 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4494 allMask |= pX->sharedMask;
4495 }
4496
4497 /* Unlock the system-level locks */
4498 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004499 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004500 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004501 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004502 }
drh73b64e42010-05-30 19:55:15 +00004503
4504 /* Undo the local locks */
4505 if( rc==SQLITE_OK ){
4506 p->exclMask &= ~mask;
4507 p->sharedMask &= ~mask;
4508 }
4509 }else if( flags & SQLITE_SHM_SHARED ){
4510 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4511
4512 /* Find out which shared locks are already held by sibling connections.
4513 ** If any sibling already holds an exclusive lock, go ahead and return
4514 ** SQLITE_BUSY.
4515 */
4516 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004517 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004518 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004519 break;
4520 }
4521 allShared |= pX->sharedMask;
4522 }
4523
4524 /* Get shared locks at the system level, if necessary */
4525 if( rc==SQLITE_OK ){
4526 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004527 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004528 }else{
drh73b64e42010-05-30 19:55:15 +00004529 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004530 }
drhd9e5c4f2010-05-12 18:01:39 +00004531 }
drh73b64e42010-05-30 19:55:15 +00004532
4533 /* Get the local shared locks */
4534 if( rc==SQLITE_OK ){
4535 p->sharedMask |= mask;
4536 }
4537 }else{
4538 /* Make sure no sibling connections hold locks that will block this
4539 ** lock. If any do, return SQLITE_BUSY right away.
4540 */
4541 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004542 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4543 rc = SQLITE_BUSY;
4544 break;
4545 }
4546 }
4547
4548 /* Get the exclusive locks at the system level. Then if successful
4549 ** also mark the local connection as being locked.
4550 */
4551 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004552 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004553 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004554 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004555 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004556 }
drhd9e5c4f2010-05-12 18:01:39 +00004557 }
4558 }
drhd91c68f2010-05-14 14:52:25 +00004559 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004560 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4561 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004562 return rc;
4563}
4564
drh286a2882010-05-20 23:51:06 +00004565/*
4566** Implement a memory barrier or memory fence on shared memory.
4567**
4568** All loads and stores begun before the barrier must complete before
4569** any load or store begun after the barrier.
4570*/
4571static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004572 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004573){
drhff828942010-06-26 21:34:06 +00004574 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004575 unixEnterMutex();
4576 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004577}
4578
dan18801912010-06-14 14:07:50 +00004579/*
danda9fe0c2010-07-13 18:44:03 +00004580** Close a connection to shared-memory. Delete the underlying
4581** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004582**
4583** If there is no shared memory associated with the connection then this
4584** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004585*/
danda9fe0c2010-07-13 18:44:03 +00004586static int unixShmUnmap(
4587 sqlite3_file *fd, /* The underlying database file */
4588 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004589){
danda9fe0c2010-07-13 18:44:03 +00004590 unixShm *p; /* The connection to be closed */
4591 unixShmNode *pShmNode; /* The underlying shared-memory file */
4592 unixShm **pp; /* For looping over sibling connections */
4593 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004594
danda9fe0c2010-07-13 18:44:03 +00004595 pDbFd = (unixFile*)fd;
4596 p = pDbFd->pShm;
4597 if( p==0 ) return SQLITE_OK;
4598 pShmNode = p->pShmNode;
4599
4600 assert( pShmNode==pDbFd->pInode->pShmNode );
4601 assert( pShmNode->pInode==pDbFd->pInode );
4602
4603 /* Remove connection p from the set of connections associated
4604 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004605 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004606 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4607 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004608
danda9fe0c2010-07-13 18:44:03 +00004609 /* Free the connection p */
4610 sqlite3_free(p);
4611 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004612 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004613
4614 /* If pShmNode->nRef has reached 0, then close the underlying
4615 ** shared-memory file, too */
4616 unixEnterMutex();
4617 assert( pShmNode->nRef>0 );
4618 pShmNode->nRef--;
4619 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004620 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004621 unixShmPurge(pDbFd);
4622 }
4623 unixLeaveMutex();
4624
4625 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004626}
drh286a2882010-05-20 23:51:06 +00004627
danda9fe0c2010-07-13 18:44:03 +00004628
drhd9e5c4f2010-05-12 18:01:39 +00004629#else
drh6b017cc2010-06-14 18:01:46 +00004630# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004631# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004632# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004633# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004634#endif /* #ifndef SQLITE_OMIT_WAL */
4635
mistachkine98844f2013-08-24 00:59:24 +00004636#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004637/*
danaef49d72013-03-25 16:28:54 +00004638** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004639*/
danf23da962013-03-23 21:00:41 +00004640static void unixUnmapfile(unixFile *pFd){
4641 assert( pFd->nFetchOut==0 );
4642 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004643 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004644 pFd->pMapRegion = 0;
4645 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004646 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004647 }
4648}
dan5d8a1372013-03-19 19:28:06 +00004649
danaef49d72013-03-25 16:28:54 +00004650/*
dane6ecd662013-04-01 17:56:59 +00004651** Return the system page size.
4652*/
4653static int unixGetPagesize(void){
4654#if HAVE_MREMAP
4655 return 512;
drh85830a72013-04-03 00:42:01 +00004656#elif defined(_BSD_SOURCE)
dane6ecd662013-04-01 17:56:59 +00004657 return getpagesize();
4658#else
4659 return (int)sysconf(_SC_PAGESIZE);
4660#endif
4661}
4662
4663/*
4664** Attempt to set the size of the memory mapping maintained by file
4665** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4666**
4667** If successful, this function sets the following variables:
4668**
4669** unixFile.pMapRegion
4670** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004671** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004672**
4673** If unsuccessful, an error message is logged via sqlite3_log() and
4674** the three variables above are zeroed. In this case SQLite should
4675** continue accessing the database using the xRead() and xWrite()
4676** methods.
4677*/
4678static void unixRemapfile(
4679 unixFile *pFd, /* File descriptor object */
4680 i64 nNew /* Required mapping size */
4681){
dan4ff7bc42013-04-02 12:04:09 +00004682 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004683 int h = pFd->h; /* File descriptor open on db file */
4684 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004685 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004686 u8 *pNew = 0; /* Location of new mapping */
4687 int flags = PROT_READ; /* Flags to pass to mmap() */
4688
4689 assert( pFd->nFetchOut==0 );
4690 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004691 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004692 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004693 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004694 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004695
4696 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4697
4698 if( pOrig ){
4699 const int szSyspage = unixGetPagesize();
4700 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
4701 u8 *pReq = &pOrig[nReuse];
4702
4703 /* Unmap any pages of the existing mapping that cannot be reused. */
4704 if( nReuse!=nOrig ){
4705 osMunmap(pReq, nOrig-nReuse);
4706 }
4707
4708#if HAVE_MREMAP
4709 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004710 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004711#else
4712 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4713 if( pNew!=MAP_FAILED ){
4714 if( pNew!=pReq ){
4715 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004716 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004717 }else{
4718 pNew = pOrig;
4719 }
4720 }
4721#endif
4722
dan48ccef82013-04-02 20:55:01 +00004723 /* The attempt to extend the existing mapping failed. Free it. */
4724 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004725 osMunmap(pOrig, nReuse);
4726 }
4727 }
4728
4729 /* If pNew is still NULL, try to create an entirely new mapping. */
4730 if( pNew==0 ){
4731 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004732 }
4733
dan4ff7bc42013-04-02 12:04:09 +00004734 if( pNew==MAP_FAILED ){
4735 pNew = 0;
4736 nNew = 0;
4737 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4738
4739 /* If the mmap() above failed, assume that all subsequent mmap() calls
4740 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4741 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004742 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004743 }
dane6ecd662013-04-01 17:56:59 +00004744 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004745 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004746}
4747
4748/*
danaef49d72013-03-25 16:28:54 +00004749** Memory map or remap the file opened by file-descriptor pFd (if the file
4750** is already mapped, the existing mapping is replaced by the new). Or, if
4751** there already exists a mapping for this file, and there are still
4752** outstanding xFetch() references to it, this function is a no-op.
4753**
4754** If parameter nByte is non-negative, then it is the requested size of
4755** the mapping to create. Otherwise, if nByte is less than zero, then the
4756** requested size is the size of the file on disk. The actual size of the
4757** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004758** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004759**
4760** SQLITE_OK is returned if no error occurs (even if the mapping is not
4761** recreated as a result of outstanding references) or an SQLite error
4762** code otherwise.
4763*/
danf23da962013-03-23 21:00:41 +00004764static int unixMapfile(unixFile *pFd, i64 nByte){
4765 i64 nMap = nByte;
4766 int rc;
daneb97b292013-03-20 14:26:59 +00004767
danf23da962013-03-23 21:00:41 +00004768 assert( nMap>=0 || pFd->nFetchOut==0 );
4769 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4770
4771 if( nMap<0 ){
daneb97b292013-03-20 14:26:59 +00004772 struct stat statbuf; /* Low-level file information */
danf23da962013-03-23 21:00:41 +00004773 rc = osFstat(pFd->h, &statbuf);
4774 if( rc!=SQLITE_OK ){
4775 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004776 }
danf23da962013-03-23 21:00:41 +00004777 nMap = statbuf.st_size;
4778 }
drh9b4c59f2013-04-15 17:03:42 +00004779 if( nMap>pFd->mmapSizeMax ){
4780 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004781 }
4782
danf23da962013-03-23 21:00:41 +00004783 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004784 if( nMap>0 ){
4785 unixRemapfile(pFd, nMap);
4786 }else{
danb7e3a322013-03-25 20:30:13 +00004787 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004788 }
4789 }
4790
danf23da962013-03-23 21:00:41 +00004791 return SQLITE_OK;
4792}
mistachkine98844f2013-08-24 00:59:24 +00004793#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004794
danaef49d72013-03-25 16:28:54 +00004795/*
4796** If possible, return a pointer to a mapping of file fd starting at offset
4797** iOff. The mapping must be valid for at least nAmt bytes.
4798**
4799** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4800** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4801** Finally, if an error does occur, return an SQLite error code. The final
4802** value of *pp is undefined in this case.
4803**
4804** If this function does return a pointer, the caller must eventually
4805** release the reference by calling unixUnfetch().
4806*/
danf23da962013-03-23 21:00:41 +00004807static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004808#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004809 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004810#endif
danf23da962013-03-23 21:00:41 +00004811 *pp = 0;
4812
drh9b4c59f2013-04-15 17:03:42 +00004813#if SQLITE_MAX_MMAP_SIZE>0
4814 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004815 if( pFd->pMapRegion==0 ){
4816 int rc = unixMapfile(pFd, -1);
4817 if( rc!=SQLITE_OK ) return rc;
4818 }
4819 if( pFd->mmapSize >= iOff+nAmt ){
4820 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4821 pFd->nFetchOut++;
4822 }
4823 }
drh6e0b6d52013-04-09 16:19:20 +00004824#endif
danf23da962013-03-23 21:00:41 +00004825 return SQLITE_OK;
4826}
4827
danaef49d72013-03-25 16:28:54 +00004828/*
dandf737fe2013-03-25 17:00:24 +00004829** If the third argument is non-NULL, then this function releases a
4830** reference obtained by an earlier call to unixFetch(). The second
4831** argument passed to this function must be the same as the corresponding
4832** argument that was passed to the unixFetch() invocation.
4833**
4834** Or, if the third argument is NULL, then this function is being called
4835** to inform the VFS layer that, according to POSIX, any existing mapping
4836** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004837*/
dandf737fe2013-03-25 17:00:24 +00004838static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
danf23da962013-03-23 21:00:41 +00004839 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhda8caa02013-04-22 23:38:50 +00004840 UNUSED_PARAMETER(iOff);
danf23da962013-03-23 21:00:41 +00004841
mistachkinb5ca3cb2013-08-24 01:12:03 +00004842#if SQLITE_MAX_MMAP_SIZE>0
danaef49d72013-03-25 16:28:54 +00004843 /* If p==0 (unmap the entire file) then there must be no outstanding
4844 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4845 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004846 assert( (p==0)==(pFd->nFetchOut==0) );
4847
dandf737fe2013-03-25 17:00:24 +00004848 /* If p!=0, it must match the iOff value. */
4849 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4850
danf23da962013-03-23 21:00:41 +00004851 if( p ){
4852 pFd->nFetchOut--;
4853 }else{
4854 unixUnmapfile(pFd);
4855 }
4856
4857 assert( pFd->nFetchOut>=0 );
mistachkinb5ca3cb2013-08-24 01:12:03 +00004858#endif
danf23da962013-03-23 21:00:41 +00004859 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004860}
4861
4862/*
drh734c9862008-11-28 15:37:20 +00004863** Here ends the implementation of all sqlite3_file methods.
4864**
4865********************** End sqlite3_file Methods *******************************
4866******************************************************************************/
4867
4868/*
drh6b9d6dd2008-12-03 19:34:47 +00004869** This division contains definitions of sqlite3_io_methods objects that
4870** implement various file locking strategies. It also contains definitions
4871** of "finder" functions. A finder-function is used to locate the appropriate
4872** sqlite3_io_methods object for a particular database file. The pAppData
4873** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4874** the correct finder-function for that VFS.
4875**
4876** Most finder functions return a pointer to a fixed sqlite3_io_methods
4877** object. The only interesting finder-function is autolockIoFinder, which
4878** looks at the filesystem type and tries to guess the best locking
4879** strategy from that.
4880**
drh1875f7a2008-12-08 18:19:17 +00004881** For finder-funtion F, two objects are created:
4882**
4883** (1) The real finder-function named "FImpt()".
4884**
dane946c392009-08-22 11:39:46 +00004885** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004886**
4887**
4888** A pointer to the F pointer is used as the pAppData value for VFS
4889** objects. We have to do this instead of letting pAppData point
4890** directly at the finder-function since C90 rules prevent a void*
4891** from be cast into a function pointer.
4892**
drh6b9d6dd2008-12-03 19:34:47 +00004893**
drh7708e972008-11-29 00:56:52 +00004894** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004895**
drh7708e972008-11-29 00:56:52 +00004896** * A constant sqlite3_io_methods object call METHOD that has locking
4897** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4898**
4899** * An I/O method finder function called FINDER that returns a pointer
4900** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004901*/
drhd9e5c4f2010-05-12 18:01:39 +00004902#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004903static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004904 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004905 CLOSE, /* xClose */ \
4906 unixRead, /* xRead */ \
4907 unixWrite, /* xWrite */ \
4908 unixTruncate, /* xTruncate */ \
4909 unixSync, /* xSync */ \
4910 unixFileSize, /* xFileSize */ \
4911 LOCK, /* xLock */ \
4912 UNLOCK, /* xUnlock */ \
4913 CKLOCK, /* xCheckReservedLock */ \
4914 unixFileControl, /* xFileControl */ \
4915 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004916 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004917 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004918 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004919 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004920 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004921 unixFetch, /* xFetch */ \
4922 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004923}; \
drh0c2694b2009-09-03 16:23:44 +00004924static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4925 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004926 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004927} \
drh0c2694b2009-09-03 16:23:44 +00004928static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004929 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004930
4931/*
4932** Here are all of the sqlite3_io_methods objects for each of the
4933** locking strategies. Functions that return pointers to these methods
4934** are also created.
4935*/
4936IOMETHODS(
4937 posixIoFinder, /* Finder function name */
4938 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004939 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004940 unixClose, /* xClose method */
4941 unixLock, /* xLock method */
4942 unixUnlock, /* xUnlock method */
4943 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004944)
drh7708e972008-11-29 00:56:52 +00004945IOMETHODS(
4946 nolockIoFinder, /* Finder function name */
4947 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004948 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004949 nolockClose, /* xClose method */
4950 nolockLock, /* xLock method */
4951 nolockUnlock, /* xUnlock method */
4952 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004953)
drh7708e972008-11-29 00:56:52 +00004954IOMETHODS(
4955 dotlockIoFinder, /* Finder function name */
4956 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004957 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004958 dotlockClose, /* xClose method */
4959 dotlockLock, /* xLock method */
4960 dotlockUnlock, /* xUnlock method */
4961 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004962)
drh7708e972008-11-29 00:56:52 +00004963
chw78a13182009-04-07 05:35:03 +00004964#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004965IOMETHODS(
4966 flockIoFinder, /* Finder function name */
4967 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004968 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004969 flockClose, /* xClose method */
4970 flockLock, /* xLock method */
4971 flockUnlock, /* xUnlock method */
4972 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004973)
drh7708e972008-11-29 00:56:52 +00004974#endif
4975
drh6c7d5c52008-11-21 20:32:33 +00004976#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004977IOMETHODS(
4978 semIoFinder, /* Finder function name */
4979 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004980 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004981 semClose, /* xClose method */
4982 semLock, /* xLock method */
4983 semUnlock, /* xUnlock method */
4984 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004985)
aswiftaebf4132008-11-21 00:10:35 +00004986#endif
drh7708e972008-11-29 00:56:52 +00004987
drhd2cb50b2009-01-09 21:41:17 +00004988#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004989IOMETHODS(
4990 afpIoFinder, /* Finder function name */
4991 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004992 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004993 afpClose, /* xClose method */
4994 afpLock, /* xLock method */
4995 afpUnlock, /* xUnlock method */
4996 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004997)
drh715ff302008-12-03 22:32:44 +00004998#endif
4999
5000/*
5001** The proxy locking method is a "super-method" in the sense that it
5002** opens secondary file descriptors for the conch and lock files and
5003** it uses proxy, dot-file, AFP, and flock() locking methods on those
5004** secondary files. For this reason, the division that implements
5005** proxy locking is located much further down in the file. But we need
5006** to go ahead and define the sqlite3_io_methods and finder function
5007** for proxy locking here. So we forward declare the I/O methods.
5008*/
drhd2cb50b2009-01-09 21:41:17 +00005009#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005010static int proxyClose(sqlite3_file*);
5011static int proxyLock(sqlite3_file*, int);
5012static int proxyUnlock(sqlite3_file*, int);
5013static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005014IOMETHODS(
5015 proxyIoFinder, /* Finder function name */
5016 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005017 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005018 proxyClose, /* xClose method */
5019 proxyLock, /* xLock method */
5020 proxyUnlock, /* xUnlock method */
5021 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005022)
aswiftaebf4132008-11-21 00:10:35 +00005023#endif
drh7708e972008-11-29 00:56:52 +00005024
drh7ed97b92010-01-20 13:07:21 +00005025/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5026#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5027IOMETHODS(
5028 nfsIoFinder, /* Finder function name */
5029 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005030 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005031 unixClose, /* xClose method */
5032 unixLock, /* xLock method */
5033 nfsUnlock, /* xUnlock method */
5034 unixCheckReservedLock /* xCheckReservedLock method */
5035)
5036#endif
drh7708e972008-11-29 00:56:52 +00005037
drhd2cb50b2009-01-09 21:41:17 +00005038#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005039/*
drh6b9d6dd2008-12-03 19:34:47 +00005040** This "finder" function attempts to determine the best locking strategy
5041** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005042** object that implements that strategy.
5043**
5044** This is for MacOSX only.
5045*/
drh1875f7a2008-12-08 18:19:17 +00005046static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005047 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005048 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005049){
5050 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005051 const char *zFilesystem; /* Filesystem type name */
5052 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005053 } aMap[] = {
5054 { "hfs", &posixIoMethods },
5055 { "ufs", &posixIoMethods },
5056 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005057 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005058 { "webdav", &nolockIoMethods },
5059 { 0, 0 }
5060 };
5061 int i;
5062 struct statfs fsInfo;
5063 struct flock lockInfo;
5064
5065 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005066 /* If filePath==NULL that means we are dealing with a transient file
5067 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005068 return &nolockIoMethods;
5069 }
5070 if( statfs(filePath, &fsInfo) != -1 ){
5071 if( fsInfo.f_flags & MNT_RDONLY ){
5072 return &nolockIoMethods;
5073 }
5074 for(i=0; aMap[i].zFilesystem; i++){
5075 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5076 return aMap[i].pMethods;
5077 }
5078 }
5079 }
5080
5081 /* Default case. Handles, amongst others, "nfs".
5082 ** Test byte-range lock using fcntl(). If the call succeeds,
5083 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005084 */
drh7708e972008-11-29 00:56:52 +00005085 lockInfo.l_len = 1;
5086 lockInfo.l_start = 0;
5087 lockInfo.l_whence = SEEK_SET;
5088 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005089 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005090 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5091 return &nfsIoMethods;
5092 } else {
5093 return &posixIoMethods;
5094 }
drh7708e972008-11-29 00:56:52 +00005095 }else{
5096 return &dotlockIoMethods;
5097 }
5098}
drh0c2694b2009-09-03 16:23:44 +00005099static const sqlite3_io_methods
5100 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005101
drhd2cb50b2009-01-09 21:41:17 +00005102#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005103
chw78a13182009-04-07 05:35:03 +00005104#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5105/*
5106** This "finder" function attempts to determine the best locking strategy
5107** for the database file "filePath". It then returns the sqlite3_io_methods
5108** object that implements that strategy.
5109**
5110** This is for VXWorks only.
5111*/
5112static const sqlite3_io_methods *autolockIoFinderImpl(
5113 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005114 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005115){
5116 struct flock lockInfo;
5117
5118 if( !filePath ){
5119 /* If filePath==NULL that means we are dealing with a transient file
5120 ** that does not need to be locked. */
5121 return &nolockIoMethods;
5122 }
5123
5124 /* Test if fcntl() is supported and use POSIX style locks.
5125 ** Otherwise fall back to the named semaphore method.
5126 */
5127 lockInfo.l_len = 1;
5128 lockInfo.l_start = 0;
5129 lockInfo.l_whence = SEEK_SET;
5130 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005131 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005132 return &posixIoMethods;
5133 }else{
5134 return &semIoMethods;
5135 }
5136}
drh0c2694b2009-09-03 16:23:44 +00005137static const sqlite3_io_methods
5138 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005139
5140#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5141
drh7708e972008-11-29 00:56:52 +00005142/*
5143** An abstract type for a pointer to a IO method finder function:
5144*/
drh0c2694b2009-09-03 16:23:44 +00005145typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005146
aswiftaebf4132008-11-21 00:10:35 +00005147
drh734c9862008-11-28 15:37:20 +00005148/****************************************************************************
5149**************************** sqlite3_vfs methods ****************************
5150**
5151** This division contains the implementation of methods on the
5152** sqlite3_vfs object.
5153*/
5154
danielk1977a3d4c882007-03-23 10:08:38 +00005155/*
danielk1977e339d652008-06-28 11:23:00 +00005156** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005157*/
5158static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005159 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005160 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005161 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005162 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005163 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005164){
drh7708e972008-11-29 00:56:52 +00005165 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005166 unixFile *pNew = (unixFile *)pId;
5167 int rc = SQLITE_OK;
5168
drh8af6c222010-05-14 12:43:01 +00005169 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005170
dan00157392010-10-05 11:33:15 +00005171 /* Usually the path zFilename should not be a relative pathname. The
5172 ** exception is when opening the proxy "conch" file in builds that
5173 ** include the special Apple locking styles.
5174 */
dan00157392010-10-05 11:33:15 +00005175#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005176 assert( zFilename==0 || zFilename[0]=='/'
5177 || pVfs->pAppData==(void*)&autolockIoFinder );
5178#else
5179 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005180#endif
dan00157392010-10-05 11:33:15 +00005181
drhb07028f2011-10-14 21:49:18 +00005182 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005183 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005184
drh308c2a52010-05-14 11:30:18 +00005185 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005186 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005187 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005188 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005189 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005190#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005191 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005192#endif
drhc02a43a2012-01-10 23:18:38 +00005193 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5194 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005195 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005196 }
drh503a6862013-03-01 01:07:17 +00005197 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005198 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005199 }
drh339eb0b2008-03-07 15:34:11 +00005200
drh6c7d5c52008-11-21 20:32:33 +00005201#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005202 pNew->pId = vxworksFindFileId(zFilename);
5203 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005204 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005205 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005206 }
5207#endif
5208
drhc02a43a2012-01-10 23:18:38 +00005209 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005210 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005211 }else{
drh0c2694b2009-09-03 16:23:44 +00005212 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005213#if SQLITE_ENABLE_LOCKING_STYLE
5214 /* Cache zFilename in the locking context (AFP and dotlock override) for
5215 ** proxyLock activation is possible (remote proxy is based on db name)
5216 ** zFilename remains valid until file is closed, to support */
5217 pNew->lockingContext = (void*)zFilename;
5218#endif
drhda0e7682008-07-30 15:27:54 +00005219 }
danielk1977e339d652008-06-28 11:23:00 +00005220
drh7ed97b92010-01-20 13:07:21 +00005221 if( pLockingStyle == &posixIoMethods
5222#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5223 || pLockingStyle == &nfsIoMethods
5224#endif
5225 ){
drh7708e972008-11-29 00:56:52 +00005226 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005227 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005228 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005229 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005230 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005231 ** in two scenarios:
5232 **
5233 ** (a) A call to fstat() failed.
5234 ** (b) A malloc failed.
5235 **
5236 ** Scenario (b) may only occur if the process is holding no other
5237 ** file descriptors open on the same file. If there were other file
5238 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005239 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005240 ** handle h - as it is guaranteed that no posix locks will be released
5241 ** by doing so.
5242 **
5243 ** If scenario (a) caused the error then things are not so safe. The
5244 ** implicit assumption here is that if fstat() fails, things are in
5245 ** such bad shape that dropping a lock or two doesn't matter much.
5246 */
drh0e9365c2011-03-02 02:08:13 +00005247 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005248 h = -1;
5249 }
drh7708e972008-11-29 00:56:52 +00005250 unixLeaveMutex();
5251 }
danielk1977e339d652008-06-28 11:23:00 +00005252
drhd2cb50b2009-01-09 21:41:17 +00005253#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005254 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005255 /* AFP locking uses the file path so it needs to be included in
5256 ** the afpLockingContext.
5257 */
5258 afpLockingContext *pCtx;
5259 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5260 if( pCtx==0 ){
5261 rc = SQLITE_NOMEM;
5262 }else{
5263 /* NB: zFilename exists and remains valid until the file is closed
5264 ** according to requirement F11141. So we do not need to make a
5265 ** copy of the filename. */
5266 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005267 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005268 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005269 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005270 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005271 if( rc!=SQLITE_OK ){
5272 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005273 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005274 h = -1;
5275 }
drh7708e972008-11-29 00:56:52 +00005276 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005277 }
drh7708e972008-11-29 00:56:52 +00005278 }
5279#endif
danielk1977e339d652008-06-28 11:23:00 +00005280
drh7708e972008-11-29 00:56:52 +00005281 else if( pLockingStyle == &dotlockIoMethods ){
5282 /* Dotfile locking uses the file path so it needs to be included in
5283 ** the dotlockLockingContext
5284 */
5285 char *zLockFile;
5286 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005287 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005288 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005289 zLockFile = (char *)sqlite3_malloc(nFilename);
5290 if( zLockFile==0 ){
5291 rc = SQLITE_NOMEM;
5292 }else{
5293 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005294 }
drh7708e972008-11-29 00:56:52 +00005295 pNew->lockingContext = zLockFile;
5296 }
danielk1977e339d652008-06-28 11:23:00 +00005297
drh6c7d5c52008-11-21 20:32:33 +00005298#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005299 else if( pLockingStyle == &semIoMethods ){
5300 /* Named semaphore locking uses the file path so it needs to be
5301 ** included in the semLockingContext
5302 */
5303 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005304 rc = findInodeInfo(pNew, &pNew->pInode);
5305 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5306 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005307 int n;
drh2238dcc2009-08-27 17:56:20 +00005308 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005309 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005310 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005311 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005312 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5313 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005314 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005315 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005316 }
chw97185482008-11-17 08:05:31 +00005317 }
drh7708e972008-11-29 00:56:52 +00005318 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005319 }
drh7708e972008-11-29 00:56:52 +00005320#endif
aswift5b1a2562008-08-22 00:22:35 +00005321
5322 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005323#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005324 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005325 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005326 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005327 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005328 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005329 }
chw97185482008-11-17 08:05:31 +00005330#endif
danielk1977e339d652008-06-28 11:23:00 +00005331 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005332 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005333 }else{
drh7708e972008-11-29 00:56:52 +00005334 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005335 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005336 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005337 }
danielk1977e339d652008-06-28 11:23:00 +00005338 return rc;
drh054889e2005-11-30 03:20:31 +00005339}
drh9c06c952005-11-26 00:25:00 +00005340
danielk1977ad94b582007-08-20 06:44:22 +00005341/*
drh8b3cf822010-06-01 21:02:51 +00005342** Return the name of a directory in which to put temporary files.
5343** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005344*/
drh7234c6d2010-06-19 15:10:09 +00005345static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005346 static const char *azDirs[] = {
5347 0,
aswiftaebf4132008-11-21 00:10:35 +00005348 0,
danielk197717b90b52008-06-06 11:11:25 +00005349 "/var/tmp",
5350 "/usr/tmp",
5351 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005352 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005353 };
drh8b3cf822010-06-01 21:02:51 +00005354 unsigned int i;
5355 struct stat buf;
5356 const char *zDir = 0;
5357
5358 azDirs[0] = sqlite3_temp_directory;
5359 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005360 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005361 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005362 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005363 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005364 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005365 break;
5366 }
5367 return zDir;
5368}
5369
5370/*
5371** Create a temporary file name in zBuf. zBuf must be allocated
5372** by the calling process and must be big enough to hold at least
5373** pVfs->mxPathname bytes.
5374*/
5375static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005376 static const unsigned char zChars[] =
5377 "abcdefghijklmnopqrstuvwxyz"
5378 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5379 "0123456789";
drh41022642008-11-21 00:24:42 +00005380 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005381 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005382
5383 /* It's odd to simulate an io-error here, but really this is just
5384 ** using the io-error infrastructure to test that SQLite handles this
5385 ** function failing.
5386 */
5387 SimulateIOError( return SQLITE_IOERR );
5388
drh7234c6d2010-06-19 15:10:09 +00005389 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005390 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005391
5392 /* Check that the output buffer is large enough for the temporary file
5393 ** name. If it is not, return SQLITE_ERROR.
5394 */
drhc02a43a2012-01-10 23:18:38 +00005395 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005396 return SQLITE_ERROR;
5397 }
5398
5399 do{
drhc02a43a2012-01-10 23:18:38 +00005400 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005401 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005402 sqlite3_randomness(15, &zBuf[j]);
5403 for(i=0; i<15; i++, j++){
5404 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5405 }
5406 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005407 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005408 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005409 return SQLITE_OK;
5410}
5411
drhd2cb50b2009-01-09 21:41:17 +00005412#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005413/*
5414** Routine to transform a unixFile into a proxy-locking unixFile.
5415** Implementation in the proxy-lock division, but used by unixOpen()
5416** if SQLITE_PREFER_PROXY_LOCKING is defined.
5417*/
5418static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005419#endif
drhc66d5b62008-12-03 22:48:32 +00005420
dan08da86a2009-08-21 17:18:03 +00005421/*
5422** Search for an unused file descriptor that was opened on the database
5423** file (not a journal or master-journal file) identified by pathname
5424** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5425** argument to this function.
5426**
5427** Such a file descriptor may exist if a database connection was closed
5428** but the associated file descriptor could not be closed because some
5429** other file descriptor open on the same file is holding a file-lock.
5430** Refer to comments in the unixClose() function and the lengthy comment
5431** describing "Posix Advisory Locking" at the start of this file for
5432** further details. Also, ticket #4018.
5433**
5434** If a suitable file descriptor is found, then it is returned. If no
5435** such file descriptor is located, -1 is returned.
5436*/
dane946c392009-08-22 11:39:46 +00005437static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5438 UnixUnusedFd *pUnused = 0;
5439
5440 /* Do not search for an unused file descriptor on vxworks. Not because
5441 ** vxworks would not benefit from the change (it might, we're not sure),
5442 ** but because no way to test it is currently available. It is better
5443 ** not to risk breaking vxworks support for the sake of such an obscure
5444 ** feature. */
5445#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005446 struct stat sStat; /* Results of stat() call */
5447
5448 /* A stat() call may fail for various reasons. If this happens, it is
5449 ** almost certain that an open() call on the same path will also fail.
5450 ** For this reason, if an error occurs in the stat() call here, it is
5451 ** ignored and -1 is returned. The caller will try to open a new file
5452 ** descriptor on the same path, fail, and return an error to SQLite.
5453 **
5454 ** Even if a subsequent open() call does succeed, the consequences of
5455 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005456 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005457 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005458
5459 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005460 pInode = inodeList;
5461 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5462 || pInode->fileId.ino!=sStat.st_ino) ){
5463 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005464 }
drh8af6c222010-05-14 12:43:01 +00005465 if( pInode ){
dane946c392009-08-22 11:39:46 +00005466 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005467 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005468 pUnused = *pp;
5469 if( pUnused ){
5470 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005471 }
5472 }
5473 unixLeaveMutex();
5474 }
dane946c392009-08-22 11:39:46 +00005475#endif /* if !OS_VXWORKS */
5476 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005477}
danielk197717b90b52008-06-06 11:11:25 +00005478
5479/*
danddb0ac42010-07-14 14:48:58 +00005480** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005481** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005482** and a value suitable for passing as the third argument to open(2) is
5483** written to *pMode. If an IO error occurs, an SQLite error code is
5484** returned and the value of *pMode is not modified.
5485**
drh8c815d12012-02-13 20:16:37 +00005486** In most cases cases, this routine sets *pMode to 0, which will become
5487** an indication to robust_open() to create the file using
5488** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5489** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005490** this function queries the file-system for the permissions on the
5491** corresponding database file and sets *pMode to this value. Whenever
5492** possible, WAL and journal files are created using the same permissions
5493** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005494**
5495** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5496** original filename is unavailable. But 8_3_NAMES is only used for
5497** FAT filesystems and permissions do not matter there, so just use
5498** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005499*/
5500static int findCreateFileMode(
5501 const char *zPath, /* Path of file (possibly) being created */
5502 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005503 mode_t *pMode, /* OUT: Permissions to open file with */
5504 uid_t *pUid, /* OUT: uid to set on the file */
5505 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005506){
5507 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005508 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005509 *pUid = 0;
5510 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005511 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005512 char zDb[MAX_PATHNAME+1]; /* Database file path */
5513 int nDb; /* Number of valid bytes in zDb */
5514 struct stat sStat; /* Output of stat() on database file */
5515
dana0c989d2010-11-05 18:07:37 +00005516 /* zPath is a path to a WAL or journal file. The following block derives
5517 ** the path to the associated database file from zPath. This block handles
5518 ** the following naming conventions:
5519 **
5520 ** "<path to db>-journal"
5521 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005522 ** "<path to db>-journalNN"
5523 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005524 **
drhd337c5b2011-10-20 18:23:35 +00005525 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005526 ** used by the test_multiplex.c module.
5527 */
5528 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005529#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005530 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005531 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005532#else
5533 while( zPath[nDb]!='-' ){
5534 assert( nDb>0 );
5535 assert( zPath[nDb]!='\n' );
5536 nDb--;
5537 }
5538#endif
danddb0ac42010-07-14 14:48:58 +00005539 memcpy(zDb, zPath, nDb);
5540 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005541
drh58384f12011-07-28 00:14:45 +00005542 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005543 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005544 *pUid = sStat.st_uid;
5545 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005546 }else{
5547 rc = SQLITE_IOERR_FSTAT;
5548 }
5549 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5550 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005551 }
5552 return rc;
5553}
5554
5555/*
danielk1977ad94b582007-08-20 06:44:22 +00005556** Open the file zPath.
5557**
danielk1977b4b47412007-08-17 15:53:36 +00005558** Previously, the SQLite OS layer used three functions in place of this
5559** one:
5560**
5561** sqlite3OsOpenReadWrite();
5562** sqlite3OsOpenReadOnly();
5563** sqlite3OsOpenExclusive();
5564**
5565** These calls correspond to the following combinations of flags:
5566**
5567** ReadWrite() -> (READWRITE | CREATE)
5568** ReadOnly() -> (READONLY)
5569** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5570**
5571** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5572** true, the file was configured to be automatically deleted when the
5573** file handle closed. To achieve the same effect using this new
5574** interface, add the DELETEONCLOSE flag to those specified above for
5575** OpenExclusive().
5576*/
5577static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005578 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5579 const char *zPath, /* Pathname of file to be opened */
5580 sqlite3_file *pFile, /* The file descriptor to be filled in */
5581 int flags, /* Input flags to control the opening */
5582 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005583){
dan08da86a2009-08-21 17:18:03 +00005584 unixFile *p = (unixFile *)pFile;
5585 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005586 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005587 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005588 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005589 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005590 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005591
5592 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5593 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5594 int isCreate = (flags & SQLITE_OPEN_CREATE);
5595 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5596 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005597#if SQLITE_ENABLE_LOCKING_STYLE
5598 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5599#endif
drh3d4435b2011-08-26 20:55:50 +00005600#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5601 struct statfs fsInfo;
5602#endif
danielk1977b4b47412007-08-17 15:53:36 +00005603
danielk1977fee2d252007-08-18 10:59:19 +00005604 /* If creating a master or main-file journal, this function will open
5605 ** a file-descriptor on the directory too. The first time unixSync()
5606 ** is called the directory file descriptor will be fsync()ed and close()d.
5607 */
drh0059eae2011-08-08 23:48:40 +00005608 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005609 eType==SQLITE_OPEN_MASTER_JOURNAL
5610 || eType==SQLITE_OPEN_MAIN_JOURNAL
5611 || eType==SQLITE_OPEN_WAL
5612 ));
danielk1977fee2d252007-08-18 10:59:19 +00005613
danielk197717b90b52008-06-06 11:11:25 +00005614 /* If argument zPath is a NULL pointer, this function is required to open
5615 ** a temporary file. Use this buffer to store the file name in.
5616 */
drhc02a43a2012-01-10 23:18:38 +00005617 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005618 const char *zName = zPath;
5619
danielk1977fee2d252007-08-18 10:59:19 +00005620 /* Check the following statements are true:
5621 **
5622 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5623 ** (b) if CREATE is set, then READWRITE must also be set, and
5624 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005625 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005626 */
danielk1977b4b47412007-08-17 15:53:36 +00005627 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005628 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005629 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005630 assert(isDelete==0 || isCreate);
5631
danddb0ac42010-07-14 14:48:58 +00005632 /* The main DB, main journal, WAL file and master journal are never
5633 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005634 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5635 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5636 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005637 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005638
danielk1977fee2d252007-08-18 10:59:19 +00005639 /* Assert that the upper layer has set one of the "file-type" flags. */
5640 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5641 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5642 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005643 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005644 );
5645
dan08da86a2009-08-21 17:18:03 +00005646 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005647
dan08da86a2009-08-21 17:18:03 +00005648 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005649 UnixUnusedFd *pUnused;
5650 pUnused = findReusableFd(zName, flags);
5651 if( pUnused ){
5652 fd = pUnused->fd;
5653 }else{
dan6aa657f2009-08-24 18:57:58 +00005654 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005655 if( !pUnused ){
5656 return SQLITE_NOMEM;
5657 }
5658 }
5659 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005660
5661 /* Database filenames are double-zero terminated if they are not
5662 ** URIs with parameters. Hence, they can always be passed into
5663 ** sqlite3_uri_parameter(). */
5664 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5665
dan08da86a2009-08-21 17:18:03 +00005666 }else if( !zName ){
5667 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005668 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005669 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005670 if( rc!=SQLITE_OK ){
5671 return rc;
5672 }
5673 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005674
5675 /* Generated temporary filenames are always double-zero terminated
5676 ** for use by sqlite3_uri_parameter(). */
5677 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005678 }
5679
dan08da86a2009-08-21 17:18:03 +00005680 /* Determine the value of the flags parameter passed to POSIX function
5681 ** open(). These must be calculated even if open() is not called, as
5682 ** they may be stored as part of the file handle and used by the
5683 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005684 if( isReadonly ) openFlags |= O_RDONLY;
5685 if( isReadWrite ) openFlags |= O_RDWR;
5686 if( isCreate ) openFlags |= O_CREAT;
5687 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5688 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005689
danielk1977b4b47412007-08-17 15:53:36 +00005690 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005691 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005692 uid_t uid; /* Userid for the file */
5693 gid_t gid; /* Groupid for the file */
5694 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005695 if( rc!=SQLITE_OK ){
5696 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005697 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005698 return rc;
5699 }
drhad4f1e52011-03-04 15:43:57 +00005700 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005701 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005702 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5703 /* Failed to open the file for read/write access. Try read-only. */
5704 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005705 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005706 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005707 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005708 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005709 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005710 }
5711 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005712 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005713 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005714 }
drhac7c3ac2012-02-11 19:23:48 +00005715
5716 /* If this process is running as root and if creating a new rollback
5717 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005718 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005719 */
5720 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005721 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005722 }
danielk1977b4b47412007-08-17 15:53:36 +00005723 }
dan08da86a2009-08-21 17:18:03 +00005724 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005725 if( pOutFlags ){
5726 *pOutFlags = flags;
5727 }
5728
dane946c392009-08-22 11:39:46 +00005729 if( p->pUnused ){
5730 p->pUnused->fd = fd;
5731 p->pUnused->flags = flags;
5732 }
5733
danielk1977b4b47412007-08-17 15:53:36 +00005734 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005735#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005736 zPath = zName;
5737#else
drh036ac7f2011-08-08 23:18:05 +00005738 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005739#endif
danielk1977b4b47412007-08-17 15:53:36 +00005740 }
drh41022642008-11-21 00:24:42 +00005741#if SQLITE_ENABLE_LOCKING_STYLE
5742 else{
dan08da86a2009-08-21 17:18:03 +00005743 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005744 }
5745#endif
5746
drhda0e7682008-07-30 15:27:54 +00005747 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005748
drh7ed97b92010-01-20 13:07:21 +00005749
5750#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005751 if( fstatfs(fd, &fsInfo) == -1 ){
5752 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005753 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005754 return SQLITE_IOERR_ACCESS;
5755 }
5756 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5757 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5758 }
5759#endif
drhc02a43a2012-01-10 23:18:38 +00005760
5761 /* Set up appropriate ctrlFlags */
5762 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5763 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5764 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5765 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5766 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5767
drh7ed97b92010-01-20 13:07:21 +00005768#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005769#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005770 isAutoProxy = 1;
5771#endif
5772 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005773 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5774 int useProxy = 0;
5775
dan08da86a2009-08-21 17:18:03 +00005776 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5777 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005778 if( envforce!=NULL ){
5779 useProxy = atoi(envforce)>0;
5780 }else{
aswiftaebf4132008-11-21 00:10:35 +00005781 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005782 /* In theory, the close(fd) call is sub-optimal. If the file opened
5783 ** with fd is a database file, and there are other connections open
5784 ** on that file that are currently holding advisory locks on it,
5785 ** then the call to close() will cancel those locks. In practice,
5786 ** we're assuming that statfs() doesn't fail very often. At least
5787 ** not while other file descriptors opened by the same process on
5788 ** the same file are working. */
5789 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005790 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005791 rc = SQLITE_IOERR_ACCESS;
5792 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005793 }
5794 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5795 }
5796 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005797 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005798 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005799 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005800 if( rc!=SQLITE_OK ){
5801 /* Use unixClose to clean up the resources added in fillInUnixFile
5802 ** and clear all the structure's references. Specifically,
5803 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5804 */
5805 unixClose(pFile);
5806 return rc;
5807 }
aswiftaebf4132008-11-21 00:10:35 +00005808 }
dane946c392009-08-22 11:39:46 +00005809 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005810 }
5811 }
5812#endif
5813
drhc02a43a2012-01-10 23:18:38 +00005814 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5815
dane946c392009-08-22 11:39:46 +00005816open_finished:
5817 if( rc!=SQLITE_OK ){
5818 sqlite3_free(p->pUnused);
5819 }
5820 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005821}
5822
dane946c392009-08-22 11:39:46 +00005823
danielk1977b4b47412007-08-17 15:53:36 +00005824/*
danielk1977fee2d252007-08-18 10:59:19 +00005825** Delete the file at zPath. If the dirSync argument is true, fsync()
5826** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005827*/
drh6b9d6dd2008-12-03 19:34:47 +00005828static int unixDelete(
5829 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5830 const char *zPath, /* Name of file to be deleted */
5831 int dirSync /* If true, fsync() directory after deleting file */
5832){
danielk1977fee2d252007-08-18 10:59:19 +00005833 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005834 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005835 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005836 if( osUnlink(zPath)==(-1) ){
5837 if( errno==ENOENT ){
5838 rc = SQLITE_IOERR_DELETE_NOENT;
5839 }else{
drhb4308162012-11-09 21:40:02 +00005840 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005841 }
drhb4308162012-11-09 21:40:02 +00005842 return rc;
drh5d4feff2010-07-14 01:45:22 +00005843 }
danielk1977d39fa702008-10-16 13:27:40 +00005844#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005845 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005846 int fd;
drh90315a22011-08-10 01:52:12 +00005847 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005848 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005849#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005850 if( fsync(fd)==-1 )
5851#else
5852 if( fsync(fd) )
5853#endif
5854 {
dane18d4952011-02-21 11:46:24 +00005855 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005856 }
drh0e9365c2011-03-02 02:08:13 +00005857 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005858 }else if( rc==SQLITE_CANTOPEN ){
5859 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005860 }
5861 }
danielk1977d138dd82008-10-15 16:02:48 +00005862#endif
danielk1977fee2d252007-08-18 10:59:19 +00005863 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005864}
5865
danielk197790949c22007-08-17 16:50:38 +00005866/*
mistachkin48864df2013-03-21 21:20:32 +00005867** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005868** test performed depends on the value of flags:
5869**
5870** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5871** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5872** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5873**
5874** Otherwise return 0.
5875*/
danielk1977861f7452008-06-05 11:39:11 +00005876static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005877 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5878 const char *zPath, /* Path of the file to examine */
5879 int flags, /* What do we want to learn about the zPath file? */
5880 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005881){
rse25c0d1a2007-09-20 08:38:14 +00005882 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005883 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005884 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005885 switch( flags ){
5886 case SQLITE_ACCESS_EXISTS:
5887 amode = F_OK;
5888 break;
5889 case SQLITE_ACCESS_READWRITE:
5890 amode = W_OK|R_OK;
5891 break;
drh50d3f902007-08-27 21:10:36 +00005892 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005893 amode = R_OK;
5894 break;
5895
5896 default:
5897 assert(!"Invalid flags argument");
5898 }
drh99ab3b12011-03-02 15:09:07 +00005899 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005900 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5901 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005902 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005903 *pResOut = 0;
5904 }
5905 }
danielk1977861f7452008-06-05 11:39:11 +00005906 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005907}
5908
danielk1977b4b47412007-08-17 15:53:36 +00005909
5910/*
5911** Turn a relative pathname into a full pathname. The relative path
5912** is stored as a nul-terminated string in the buffer pointed to by
5913** zPath.
5914**
5915** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5916** (in this case, MAX_PATHNAME bytes). The full-path is written to
5917** this buffer before returning.
5918*/
danielk1977adfb9b02007-09-17 07:02:56 +00005919static int unixFullPathname(
5920 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5921 const char *zPath, /* Possibly relative input path */
5922 int nOut, /* Size of output buffer in bytes */
5923 char *zOut /* Output buffer */
5924){
danielk1977843e65f2007-09-01 16:16:15 +00005925
5926 /* It's odd to simulate an io-error here, but really this is just
5927 ** using the io-error infrastructure to test that SQLite handles this
5928 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005929 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005930 */
5931 SimulateIOError( return SQLITE_ERROR );
5932
drh153c62c2007-08-24 03:51:33 +00005933 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005934 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005935
drh3c7f2dc2007-12-06 13:26:20 +00005936 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005937 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005938 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005939 }else{
5940 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005941 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005942 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005943 }
drhea678832008-12-10 19:26:22 +00005944 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005945 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005946 }
5947 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005948}
5949
drh0ccebe72005-06-07 22:22:50 +00005950
drh761df872006-12-21 01:29:22 +00005951#ifndef SQLITE_OMIT_LOAD_EXTENSION
5952/*
5953** Interfaces for opening a shared library, finding entry points
5954** within the shared library, and closing the shared library.
5955*/
5956#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005957static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5958 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005959 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5960}
danielk197795c8a542007-09-01 06:51:27 +00005961
5962/*
5963** SQLite calls this function immediately after a call to unixDlSym() or
5964** unixDlOpen() fails (returns a null pointer). If a more detailed error
5965** message is available, it is written to zBufOut. If no error message
5966** is available, zBufOut is left unmodified and SQLite uses a default
5967** error message.
5968*/
danielk1977397d65f2008-11-19 11:35:39 +00005969static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005970 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005971 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005972 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005973 zErr = dlerror();
5974 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005975 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005976 }
drh6c7d5c52008-11-21 20:32:33 +00005977 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005978}
drh1875f7a2008-12-08 18:19:17 +00005979static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5980 /*
5981 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5982 ** cast into a pointer to a function. And yet the library dlsym() routine
5983 ** returns a void* which is really a pointer to a function. So how do we
5984 ** use dlsym() with -pedantic-errors?
5985 **
5986 ** Variable x below is defined to be a pointer to a function taking
5987 ** parameters void* and const char* and returning a pointer to a function.
5988 ** We initialize x by assigning it a pointer to the dlsym() function.
5989 ** (That assignment requires a cast.) Then we call the function that
5990 ** x points to.
5991 **
5992 ** This work-around is unlikely to work correctly on any system where
5993 ** you really cannot cast a function pointer into void*. But then, on the
5994 ** other hand, dlsym() will not work on such a system either, so we have
5995 ** not really lost anything.
5996 */
5997 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005998 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005999 x = (void(*(*)(void*,const char*))(void))dlsym;
6000 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006001}
danielk1977397d65f2008-11-19 11:35:39 +00006002static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6003 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006004 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006005}
danielk1977b4b47412007-08-17 15:53:36 +00006006#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6007 #define unixDlOpen 0
6008 #define unixDlError 0
6009 #define unixDlSym 0
6010 #define unixDlClose 0
6011#endif
6012
6013/*
danielk197790949c22007-08-17 16:50:38 +00006014** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006015*/
danielk1977397d65f2008-11-19 11:35:39 +00006016static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6017 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006018 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006019
drhbbd42a62004-05-22 17:41:58 +00006020 /* We have to initialize zBuf to prevent valgrind from reporting
6021 ** errors. The reports issued by valgrind are incorrect - we would
6022 ** prefer that the randomness be increased by making use of the
6023 ** uninitialized space in zBuf - but valgrind errors tend to worry
6024 ** some users. Rather than argue, it seems easier just to initialize
6025 ** the whole array and silence valgrind, even if that means less randomness
6026 ** in the random seed.
6027 **
6028 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006029 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006030 ** tests repeatable.
6031 */
danielk1977b4b47412007-08-17 15:53:36 +00006032 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00006033#if !defined(SQLITE_TEST)
6034 {
drhc18b4042012-02-10 03:10:27 +00006035 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00006036 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006037 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006038 time_t t;
6039 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006040 memcpy(zBuf, &t, sizeof(t));
6041 pid = getpid();
6042 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00006043 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00006044 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00006045 }else{
drhc18b4042012-02-10 03:10:27 +00006046 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006047 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006048 }
drhbbd42a62004-05-22 17:41:58 +00006049 }
6050#endif
drh72cbd072008-10-14 17:58:38 +00006051 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006052}
6053
danielk1977b4b47412007-08-17 15:53:36 +00006054
drhbbd42a62004-05-22 17:41:58 +00006055/*
6056** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006057** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006058** The return value is the number of microseconds of sleep actually
6059** requested from the underlying operating system, a number which
6060** might be greater than or equal to the argument, but not less
6061** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006062*/
danielk1977397d65f2008-11-19 11:35:39 +00006063static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006064#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006065 struct timespec sp;
6066
6067 sp.tv_sec = microseconds / 1000000;
6068 sp.tv_nsec = (microseconds % 1000000) * 1000;
6069 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006070 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006071 return microseconds;
6072#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006073 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006074 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006075 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006076#else
danielk1977b4b47412007-08-17 15:53:36 +00006077 int seconds = (microseconds+999999)/1000000;
6078 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006079 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006080 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006081#endif
drh88f474a2006-01-02 20:00:12 +00006082}
6083
6084/*
drh6b9d6dd2008-12-03 19:34:47 +00006085** The following variable, if set to a non-zero value, is interpreted as
6086** the number of seconds since 1970 and is used to set the result of
6087** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006088*/
6089#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006090int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006091#endif
6092
6093/*
drhb7e8ea22010-05-03 14:32:30 +00006094** Find the current time (in Universal Coordinated Time). Write into *piNow
6095** the current time and date as a Julian Day number times 86_400_000. In
6096** other words, write into *piNow the number of milliseconds since the Julian
6097** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6098** proleptic Gregorian calendar.
6099**
drh31702252011-10-12 23:13:43 +00006100** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6101** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006102*/
6103static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6104 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006105 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006106#if defined(NO_GETTOD)
6107 time_t t;
6108 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006109 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006110#elif OS_VXWORKS
6111 struct timespec sNow;
6112 clock_gettime(CLOCK_REALTIME, &sNow);
6113 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6114#else
6115 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006116 if( gettimeofday(&sNow, 0)==0 ){
6117 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6118 }else{
6119 rc = SQLITE_ERROR;
6120 }
drhb7e8ea22010-05-03 14:32:30 +00006121#endif
6122
6123#ifdef SQLITE_TEST
6124 if( sqlite3_current_time ){
6125 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6126 }
6127#endif
6128 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006129 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006130}
6131
6132/*
drhbbd42a62004-05-22 17:41:58 +00006133** Find the current time (in Universal Coordinated Time). Write the
6134** current time and date as a Julian Day number into *prNow and
6135** return 0. Return 1 if the time and date cannot be found.
6136*/
danielk1977397d65f2008-11-19 11:35:39 +00006137static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006138 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006139 int rc;
drhff828942010-06-26 21:34:06 +00006140 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006141 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006142 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006143 return rc;
drhbbd42a62004-05-22 17:41:58 +00006144}
danielk1977b4b47412007-08-17 15:53:36 +00006145
drh6b9d6dd2008-12-03 19:34:47 +00006146/*
6147** We added the xGetLastError() method with the intention of providing
6148** better low-level error messages when operating-system problems come up
6149** during SQLite operation. But so far, none of that has been implemented
6150** in the core. So this routine is never called. For now, it is merely
6151** a place-holder.
6152*/
danielk1977397d65f2008-11-19 11:35:39 +00006153static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6154 UNUSED_PARAMETER(NotUsed);
6155 UNUSED_PARAMETER(NotUsed2);
6156 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006157 return 0;
6158}
6159
drhf2424c52010-04-26 00:04:55 +00006160
6161/*
drh734c9862008-11-28 15:37:20 +00006162************************ End of sqlite3_vfs methods ***************************
6163******************************************************************************/
6164
drh715ff302008-12-03 22:32:44 +00006165/******************************************************************************
6166************************** Begin Proxy Locking ********************************
6167**
6168** Proxy locking is a "uber-locking-method" in this sense: It uses the
6169** other locking methods on secondary lock files. Proxy locking is a
6170** meta-layer over top of the primitive locking implemented above. For
6171** this reason, the division that implements of proxy locking is deferred
6172** until late in the file (here) after all of the other I/O methods have
6173** been defined - so that the primitive locking methods are available
6174** as services to help with the implementation of proxy locking.
6175**
6176****
6177**
6178** The default locking schemes in SQLite use byte-range locks on the
6179** database file to coordinate safe, concurrent access by multiple readers
6180** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6181** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6182** as POSIX read & write locks over fixed set of locations (via fsctl),
6183** on AFP and SMB only exclusive byte-range locks are available via fsctl
6184** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6185** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6186** address in the shared range is taken for a SHARED lock, the entire
6187** shared range is taken for an EXCLUSIVE lock):
6188**
drhf2f105d2012-08-20 15:53:54 +00006189** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006190** RESERVED_BYTE 0x40000001
6191** SHARED_RANGE 0x40000002 -> 0x40000200
6192**
6193** This works well on the local file system, but shows a nearly 100x
6194** slowdown in read performance on AFP because the AFP client disables
6195** the read cache when byte-range locks are present. Enabling the read
6196** cache exposes a cache coherency problem that is present on all OS X
6197** supported network file systems. NFS and AFP both observe the
6198** close-to-open semantics for ensuring cache coherency
6199** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6200** address the requirements for concurrent database access by multiple
6201** readers and writers
6202** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6203**
6204** To address the performance and cache coherency issues, proxy file locking
6205** changes the way database access is controlled by limiting access to a
6206** single host at a time and moving file locks off of the database file
6207** and onto a proxy file on the local file system.
6208**
6209**
6210** Using proxy locks
6211** -----------------
6212**
6213** C APIs
6214**
6215** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6216** <proxy_path> | ":auto:");
6217** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6218**
6219**
6220** SQL pragmas
6221**
6222** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6223** PRAGMA [database.]lock_proxy_file
6224**
6225** Specifying ":auto:" means that if there is a conch file with a matching
6226** host ID in it, the proxy path in the conch file will be used, otherwise
6227** a proxy path based on the user's temp dir
6228** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6229** actual proxy file name is generated from the name and path of the
6230** database file. For example:
6231**
6232** For database path "/Users/me/foo.db"
6233** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6234**
6235** Once a lock proxy is configured for a database connection, it can not
6236** be removed, however it may be switched to a different proxy path via
6237** the above APIs (assuming the conch file is not being held by another
6238** connection or process).
6239**
6240**
6241** How proxy locking works
6242** -----------------------
6243**
6244** Proxy file locking relies primarily on two new supporting files:
6245**
6246** * conch file to limit access to the database file to a single host
6247** at a time
6248**
6249** * proxy file to act as a proxy for the advisory locks normally
6250** taken on the database
6251**
6252** The conch file - to use a proxy file, sqlite must first "hold the conch"
6253** by taking an sqlite-style shared lock on the conch file, reading the
6254** contents and comparing the host's unique host ID (see below) and lock
6255** proxy path against the values stored in the conch. The conch file is
6256** stored in the same directory as the database file and the file name
6257** is patterned after the database file name as ".<databasename>-conch".
6258** If the conch file does not exist, or it's contents do not match the
6259** host ID and/or proxy path, then the lock is escalated to an exclusive
6260** lock and the conch file contents is updated with the host ID and proxy
6261** path and the lock is downgraded to a shared lock again. If the conch
6262** is held by another process (with a shared lock), the exclusive lock
6263** will fail and SQLITE_BUSY is returned.
6264**
6265** The proxy file - a single-byte file used for all advisory file locks
6266** normally taken on the database file. This allows for safe sharing
6267** of the database file for multiple readers and writers on the same
6268** host (the conch ensures that they all use the same local lock file).
6269**
drh715ff302008-12-03 22:32:44 +00006270** Requesting the lock proxy does not immediately take the conch, it is
6271** only taken when the first request to lock database file is made.
6272** This matches the semantics of the traditional locking behavior, where
6273** opening a connection to a database file does not take a lock on it.
6274** The shared lock and an open file descriptor are maintained until
6275** the connection to the database is closed.
6276**
6277** The proxy file and the lock file are never deleted so they only need
6278** to be created the first time they are used.
6279**
6280** Configuration options
6281** ---------------------
6282**
6283** SQLITE_PREFER_PROXY_LOCKING
6284**
6285** Database files accessed on non-local file systems are
6286** automatically configured for proxy locking, lock files are
6287** named automatically using the same logic as
6288** PRAGMA lock_proxy_file=":auto:"
6289**
6290** SQLITE_PROXY_DEBUG
6291**
6292** Enables the logging of error messages during host id file
6293** retrieval and creation
6294**
drh715ff302008-12-03 22:32:44 +00006295** LOCKPROXYDIR
6296**
6297** Overrides the default directory used for lock proxy files that
6298** are named automatically via the ":auto:" setting
6299**
6300** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6301**
6302** Permissions to use when creating a directory for storing the
6303** lock proxy files, only used when LOCKPROXYDIR is not set.
6304**
6305**
6306** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6307** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6308** force proxy locking to be used for every database file opened, and 0
6309** will force automatic proxy locking to be disabled for all database
6310** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6311** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6312*/
6313
6314/*
6315** Proxy locking is only available on MacOSX
6316*/
drhd2cb50b2009-01-09 21:41:17 +00006317#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006318
drh715ff302008-12-03 22:32:44 +00006319/*
6320** The proxyLockingContext has the path and file structures for the remote
6321** and local proxy files in it
6322*/
6323typedef struct proxyLockingContext proxyLockingContext;
6324struct proxyLockingContext {
6325 unixFile *conchFile; /* Open conch file */
6326 char *conchFilePath; /* Name of the conch file */
6327 unixFile *lockProxy; /* Open proxy lock file */
6328 char *lockProxyPath; /* Name of the proxy lock file */
6329 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006330 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006331 void *oldLockingContext; /* Original lockingcontext to restore on close */
6332 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6333};
6334
drh7ed97b92010-01-20 13:07:21 +00006335/*
6336** The proxy lock file path for the database at dbPath is written into lPath,
6337** which must point to valid, writable memory large enough for a maxLen length
6338** file path.
drh715ff302008-12-03 22:32:44 +00006339*/
drh715ff302008-12-03 22:32:44 +00006340static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6341 int len;
6342 int dbLen;
6343 int i;
6344
6345#ifdef LOCKPROXYDIR
6346 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6347#else
6348# ifdef _CS_DARWIN_USER_TEMP_DIR
6349 {
drh7ed97b92010-01-20 13:07:21 +00006350 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006351 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6352 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006353 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006354 }
drh7ed97b92010-01-20 13:07:21 +00006355 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006356 }
6357# else
6358 len = strlcpy(lPath, "/tmp/", maxLen);
6359# endif
6360#endif
6361
6362 if( lPath[len-1]!='/' ){
6363 len = strlcat(lPath, "/", maxLen);
6364 }
6365
6366 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006367 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006368 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006369 char c = dbPath[i];
6370 lPath[i+len] = (c=='/')?'_':c;
6371 }
6372 lPath[i+len]='\0';
6373 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006374 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006375 return SQLITE_OK;
6376}
6377
drh7ed97b92010-01-20 13:07:21 +00006378/*
6379 ** Creates the lock file and any missing directories in lockPath
6380 */
6381static int proxyCreateLockPath(const char *lockPath){
6382 int i, len;
6383 char buf[MAXPATHLEN];
6384 int start = 0;
6385
6386 assert(lockPath!=NULL);
6387 /* try to create all the intermediate directories */
6388 len = (int)strlen(lockPath);
6389 buf[0] = lockPath[0];
6390 for( i=1; i<len; i++ ){
6391 if( lockPath[i] == '/' && (i - start > 0) ){
6392 /* only mkdir if leaf dir != "." or "/" or ".." */
6393 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6394 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6395 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006396 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006397 int err=errno;
6398 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006399 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006400 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006401 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006402 return err;
6403 }
6404 }
6405 }
6406 start=i+1;
6407 }
6408 buf[i] = lockPath[i];
6409 }
drh308c2a52010-05-14 11:30:18 +00006410 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006411 return 0;
6412}
6413
drh715ff302008-12-03 22:32:44 +00006414/*
6415** Create a new VFS file descriptor (stored in memory obtained from
6416** sqlite3_malloc) and open the file named "path" in the file descriptor.
6417**
6418** The caller is responsible not only for closing the file descriptor
6419** but also for freeing the memory associated with the file descriptor.
6420*/
drh7ed97b92010-01-20 13:07:21 +00006421static int proxyCreateUnixFile(
6422 const char *path, /* path for the new unixFile */
6423 unixFile **ppFile, /* unixFile created and returned by ref */
6424 int islockfile /* if non zero missing dirs will be created */
6425) {
6426 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006427 unixFile *pNew;
6428 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006429 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006430 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006431 int terrno = 0;
6432 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006433
drh7ed97b92010-01-20 13:07:21 +00006434 /* 1. first try to open/create the file
6435 ** 2. if that fails, and this is a lock file (not-conch), try creating
6436 ** the parent directories and then try again.
6437 ** 3. if that fails, try to open the file read-only
6438 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6439 */
6440 pUnused = findReusableFd(path, openFlags);
6441 if( pUnused ){
6442 fd = pUnused->fd;
6443 }else{
6444 pUnused = sqlite3_malloc(sizeof(*pUnused));
6445 if( !pUnused ){
6446 return SQLITE_NOMEM;
6447 }
6448 }
6449 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006450 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006451 terrno = errno;
6452 if( fd<0 && errno==ENOENT && islockfile ){
6453 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006454 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006455 }
6456 }
6457 }
6458 if( fd<0 ){
6459 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006460 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006461 terrno = errno;
6462 }
6463 if( fd<0 ){
6464 if( islockfile ){
6465 return SQLITE_BUSY;
6466 }
6467 switch (terrno) {
6468 case EACCES:
6469 return SQLITE_PERM;
6470 case EIO:
6471 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6472 default:
drh9978c972010-02-23 17:36:32 +00006473 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006474 }
6475 }
6476
6477 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6478 if( pNew==NULL ){
6479 rc = SQLITE_NOMEM;
6480 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006481 }
6482 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006483 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006484 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006485 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006486 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006487 pUnused->fd = fd;
6488 pUnused->flags = openFlags;
6489 pNew->pUnused = pUnused;
6490
drhc02a43a2012-01-10 23:18:38 +00006491 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006492 if( rc==SQLITE_OK ){
6493 *ppFile = pNew;
6494 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006495 }
drh7ed97b92010-01-20 13:07:21 +00006496end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006497 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006498 sqlite3_free(pNew);
6499 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006500 return rc;
6501}
6502
drh7ed97b92010-01-20 13:07:21 +00006503#ifdef SQLITE_TEST
6504/* simulate multiple hosts by creating unique hostid file paths */
6505int sqlite3_hostid_num = 0;
6506#endif
6507
6508#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6509
drh0ab216a2010-07-02 17:10:40 +00006510/* Not always defined in the headers as it ought to be */
6511extern int gethostuuid(uuid_t id, const struct timespec *wait);
6512
drh7ed97b92010-01-20 13:07:21 +00006513/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6514** bytes of writable memory.
6515*/
6516static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006517 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6518 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006519#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6520 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006521 {
6522 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6523 if( gethostuuid(pHostID, &timeout) ){
6524 int err = errno;
6525 if( pError ){
6526 *pError = err;
6527 }
6528 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006529 }
drh7ed97b92010-01-20 13:07:21 +00006530 }
drh3d4435b2011-08-26 20:55:50 +00006531#else
6532 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006533#endif
drh7ed97b92010-01-20 13:07:21 +00006534#ifdef SQLITE_TEST
6535 /* simulate multiple hosts by creating unique hostid file paths */
6536 if( sqlite3_hostid_num != 0){
6537 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6538 }
6539#endif
6540
6541 return SQLITE_OK;
6542}
6543
6544/* The conch file contains the header, host id and lock file path
6545 */
6546#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6547#define PROXY_HEADERLEN 1 /* conch file header length */
6548#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6549#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6550
6551/*
6552** Takes an open conch file, copies the contents to a new path and then moves
6553** it back. The newly created file's file descriptor is assigned to the
6554** conch file structure and finally the original conch file descriptor is
6555** closed. Returns zero if successful.
6556*/
6557static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6558 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6559 unixFile *conchFile = pCtx->conchFile;
6560 char tPath[MAXPATHLEN];
6561 char buf[PROXY_MAXCONCHLEN];
6562 char *cPath = pCtx->conchFilePath;
6563 size_t readLen = 0;
6564 size_t pathLen = 0;
6565 char errmsg[64] = "";
6566 int fd = -1;
6567 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006568 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006569
6570 /* create a new path by replace the trailing '-conch' with '-break' */
6571 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6572 if( pathLen>MAXPATHLEN || pathLen<6 ||
6573 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006574 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006575 goto end_breaklock;
6576 }
6577 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006578 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006579 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006580 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006581 goto end_breaklock;
6582 }
6583 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006584 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006585 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006586 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006587 goto end_breaklock;
6588 }
drhe562be52011-03-02 18:01:10 +00006589 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006590 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006591 goto end_breaklock;
6592 }
6593 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006594 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006595 goto end_breaklock;
6596 }
6597 rc = 0;
6598 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006599 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006600 conchFile->h = fd;
6601 conchFile->openFlags = O_RDWR | O_CREAT;
6602
6603end_breaklock:
6604 if( rc ){
6605 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006606 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006607 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006608 }
6609 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6610 }
6611 return rc;
6612}
6613
6614/* Take the requested lock on the conch file and break a stale lock if the
6615** host id matches.
6616*/
6617static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6618 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6619 unixFile *conchFile = pCtx->conchFile;
6620 int rc = SQLITE_OK;
6621 int nTries = 0;
6622 struct timespec conchModTime;
6623
drh3d4435b2011-08-26 20:55:50 +00006624 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006625 do {
6626 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6627 nTries ++;
6628 if( rc==SQLITE_BUSY ){
6629 /* If the lock failed (busy):
6630 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6631 * 2nd try: fail if the mod time changed or host id is different, wait
6632 * 10 sec and try again
6633 * 3rd try: break the lock unless the mod time has changed.
6634 */
6635 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006636 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006637 pFile->lastErrno = errno;
6638 return SQLITE_IOERR_LOCK;
6639 }
6640
6641 if( nTries==1 ){
6642 conchModTime = buf.st_mtimespec;
6643 usleep(500000); /* wait 0.5 sec and try the lock again*/
6644 continue;
6645 }
6646
6647 assert( nTries>1 );
6648 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6649 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6650 return SQLITE_BUSY;
6651 }
6652
6653 if( nTries==2 ){
6654 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006655 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006656 if( len<0 ){
6657 pFile->lastErrno = errno;
6658 return SQLITE_IOERR_LOCK;
6659 }
6660 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6661 /* don't break the lock if the host id doesn't match */
6662 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6663 return SQLITE_BUSY;
6664 }
6665 }else{
6666 /* don't break the lock on short read or a version mismatch */
6667 return SQLITE_BUSY;
6668 }
6669 usleep(10000000); /* wait 10 sec and try the lock again */
6670 continue;
6671 }
6672
6673 assert( nTries==3 );
6674 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6675 rc = SQLITE_OK;
6676 if( lockType==EXCLUSIVE_LOCK ){
6677 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6678 }
6679 if( !rc ){
6680 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6681 }
6682 }
6683 }
6684 } while( rc==SQLITE_BUSY && nTries<3 );
6685
6686 return rc;
6687}
6688
6689/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006690** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6691** lockPath means that the lockPath in the conch file will be used if the
6692** host IDs match, or a new lock path will be generated automatically
6693** and written to the conch file.
6694*/
6695static int proxyTakeConch(unixFile *pFile){
6696 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6697
drh7ed97b92010-01-20 13:07:21 +00006698 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006699 return SQLITE_OK;
6700 }else{
6701 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006702 uuid_t myHostID;
6703 int pError = 0;
6704 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006705 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006706 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006707 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006708 int createConch = 0;
6709 int hostIdMatch = 0;
6710 int readLen = 0;
6711 int tryOldLockPath = 0;
6712 int forceNewLockPath = 0;
6713
drh308c2a52010-05-14 11:30:18 +00006714 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6715 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006716
drh7ed97b92010-01-20 13:07:21 +00006717 rc = proxyGetHostID(myHostID, &pError);
6718 if( (rc&0xff)==SQLITE_IOERR ){
6719 pFile->lastErrno = pError;
6720 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006721 }
drh7ed97b92010-01-20 13:07:21 +00006722 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006723 if( rc!=SQLITE_OK ){
6724 goto end_takeconch;
6725 }
drh7ed97b92010-01-20 13:07:21 +00006726 /* read the existing conch file */
6727 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6728 if( readLen<0 ){
6729 /* I/O error: lastErrno set by seekAndRead */
6730 pFile->lastErrno = conchFile->lastErrno;
6731 rc = SQLITE_IOERR_READ;
6732 goto end_takeconch;
6733 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6734 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6735 /* a short read or version format mismatch means we need to create a new
6736 ** conch file.
6737 */
6738 createConch = 1;
6739 }
6740 /* if the host id matches and the lock path already exists in the conch
6741 ** we'll try to use the path there, if we can't open that path, we'll
6742 ** retry with a new auto-generated path
6743 */
6744 do { /* in case we need to try again for an :auto: named lock file */
6745
6746 if( !createConch && !forceNewLockPath ){
6747 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6748 PROXY_HOSTIDLEN);
6749 /* if the conch has data compare the contents */
6750 if( !pCtx->lockProxyPath ){
6751 /* for auto-named local lock file, just check the host ID and we'll
6752 ** use the local lock file path that's already in there
6753 */
6754 if( hostIdMatch ){
6755 size_t pathLen = (readLen - PROXY_PATHINDEX);
6756
6757 if( pathLen>=MAXPATHLEN ){
6758 pathLen=MAXPATHLEN-1;
6759 }
6760 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6761 lockPath[pathLen] = 0;
6762 tempLockPath = lockPath;
6763 tryOldLockPath = 1;
6764 /* create a copy of the lock path if the conch is taken */
6765 goto end_takeconch;
6766 }
6767 }else if( hostIdMatch
6768 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6769 readLen-PROXY_PATHINDEX)
6770 ){
6771 /* conch host and lock path match */
6772 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006773 }
drh7ed97b92010-01-20 13:07:21 +00006774 }
6775
6776 /* if the conch isn't writable and doesn't match, we can't take it */
6777 if( (conchFile->openFlags&O_RDWR) == 0 ){
6778 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006779 goto end_takeconch;
6780 }
drh7ed97b92010-01-20 13:07:21 +00006781
6782 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006783 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006784 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6785 tempLockPath = lockPath;
6786 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006787 }
drh7ed97b92010-01-20 13:07:21 +00006788
6789 /* update conch with host and path (this will fail if other process
6790 ** has a shared lock already), if the host id matches, use the big
6791 ** stick.
drh715ff302008-12-03 22:32:44 +00006792 */
drh7ed97b92010-01-20 13:07:21 +00006793 futimes(conchFile->h, NULL);
6794 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006795 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006796 /* We are trying for an exclusive lock but another thread in this
6797 ** same process is still holding a shared lock. */
6798 rc = SQLITE_BUSY;
6799 } else {
6800 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006801 }
drh715ff302008-12-03 22:32:44 +00006802 }else{
drh7ed97b92010-01-20 13:07:21 +00006803 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006804 }
drh7ed97b92010-01-20 13:07:21 +00006805 if( rc==SQLITE_OK ){
6806 char writeBuffer[PROXY_MAXCONCHLEN];
6807 int writeSize = 0;
6808
6809 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6810 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6811 if( pCtx->lockProxyPath!=NULL ){
6812 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6813 }else{
6814 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6815 }
6816 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006817 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006818 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6819 fsync(conchFile->h);
6820 /* If we created a new conch file (not just updated the contents of a
6821 ** valid conch file), try to match the permissions of the database
6822 */
6823 if( rc==SQLITE_OK && createConch ){
6824 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006825 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006826 if( err==0 ){
6827 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6828 S_IROTH|S_IWOTH);
6829 /* try to match the database file R/W permissions, ignore failure */
6830#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006831 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006832#else
drhff812312011-02-23 13:33:46 +00006833 do{
drhe562be52011-03-02 18:01:10 +00006834 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006835 }while( rc==(-1) && errno==EINTR );
6836 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006837 int code = errno;
6838 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6839 cmode, code, strerror(code));
6840 } else {
6841 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6842 }
6843 }else{
6844 int code = errno;
6845 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6846 err, code, strerror(code));
6847#endif
6848 }
drh715ff302008-12-03 22:32:44 +00006849 }
6850 }
drh7ed97b92010-01-20 13:07:21 +00006851 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6852
6853 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006854 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006855 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006856 int fd;
drh7ed97b92010-01-20 13:07:21 +00006857 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006858 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006859 }
6860 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006861 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006862 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006863 if( fd>=0 ){
6864 pFile->h = fd;
6865 }else{
drh9978c972010-02-23 17:36:32 +00006866 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006867 during locking */
6868 }
6869 }
6870 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6871 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6872 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6873 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6874 /* we couldn't create the proxy lock file with the old lock file path
6875 ** so try again via auto-naming
6876 */
6877 forceNewLockPath = 1;
6878 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006879 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006880 }
6881 }
6882 if( rc==SQLITE_OK ){
6883 /* Need to make a copy of path if we extracted the value
6884 ** from the conch file or the path was allocated on the stack
6885 */
6886 if( tempLockPath ){
6887 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6888 if( !pCtx->lockProxyPath ){
6889 rc = SQLITE_NOMEM;
6890 }
6891 }
6892 }
6893 if( rc==SQLITE_OK ){
6894 pCtx->conchHeld = 1;
6895
6896 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6897 afpLockingContext *afpCtx;
6898 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6899 afpCtx->dbPath = pCtx->lockProxyPath;
6900 }
6901 } else {
6902 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6903 }
drh308c2a52010-05-14 11:30:18 +00006904 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6905 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006906 return rc;
drh308c2a52010-05-14 11:30:18 +00006907 } while (1); /* in case we need to retry the :auto: lock file -
6908 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006909 }
6910}
6911
6912/*
6913** If pFile holds a lock on a conch file, then release that lock.
6914*/
6915static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006916 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006917 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6918 unixFile *conchFile; /* Name of the conch file */
6919
6920 pCtx = (proxyLockingContext *)pFile->lockingContext;
6921 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006922 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006923 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006924 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006925 if( pCtx->conchHeld>0 ){
6926 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6927 }
drh715ff302008-12-03 22:32:44 +00006928 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006929 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6930 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006931 return rc;
6932}
6933
6934/*
6935** Given the name of a database file, compute the name of its conch file.
6936** Store the conch filename in memory obtained from sqlite3_malloc().
6937** Make *pConchPath point to the new name. Return SQLITE_OK on success
6938** or SQLITE_NOMEM if unable to obtain memory.
6939**
6940** The caller is responsible for ensuring that the allocated memory
6941** space is eventually freed.
6942**
6943** *pConchPath is set to NULL if a memory allocation error occurs.
6944*/
6945static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6946 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006947 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006948 char *conchPath; /* buffer in which to construct conch name */
6949
6950 /* Allocate space for the conch filename and initialize the name to
6951 ** the name of the original database file. */
6952 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6953 if( conchPath==0 ){
6954 return SQLITE_NOMEM;
6955 }
6956 memcpy(conchPath, dbPath, len+1);
6957
6958 /* now insert a "." before the last / character */
6959 for( i=(len-1); i>=0; i-- ){
6960 if( conchPath[i]=='/' ){
6961 i++;
6962 break;
6963 }
6964 }
6965 conchPath[i]='.';
6966 while ( i<len ){
6967 conchPath[i+1]=dbPath[i];
6968 i++;
6969 }
6970
6971 /* append the "-conch" suffix to the file */
6972 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006973 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006974
6975 return SQLITE_OK;
6976}
6977
6978
6979/* Takes a fully configured proxy locking-style unix file and switches
6980** the local lock file path
6981*/
6982static int switchLockProxyPath(unixFile *pFile, const char *path) {
6983 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6984 char *oldPath = pCtx->lockProxyPath;
6985 int rc = SQLITE_OK;
6986
drh308c2a52010-05-14 11:30:18 +00006987 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006988 return SQLITE_BUSY;
6989 }
6990
6991 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6992 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6993 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6994 return SQLITE_OK;
6995 }else{
6996 unixFile *lockProxy = pCtx->lockProxy;
6997 pCtx->lockProxy=NULL;
6998 pCtx->conchHeld = 0;
6999 if( lockProxy!=NULL ){
7000 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7001 if( rc ) return rc;
7002 sqlite3_free(lockProxy);
7003 }
7004 sqlite3_free(oldPath);
7005 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7006 }
7007
7008 return rc;
7009}
7010
7011/*
7012** pFile is a file that has been opened by a prior xOpen call. dbPath
7013** is a string buffer at least MAXPATHLEN+1 characters in size.
7014**
7015** This routine find the filename associated with pFile and writes it
7016** int dbPath.
7017*/
7018static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007019#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007020 if( pFile->pMethod == &afpIoMethods ){
7021 /* afp style keeps a reference to the db path in the filePath field
7022 ** of the struct */
drhea678832008-12-10 19:26:22 +00007023 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007024 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
7025 } else
drh715ff302008-12-03 22:32:44 +00007026#endif
7027 if( pFile->pMethod == &dotlockIoMethods ){
7028 /* dot lock style uses the locking context to store the dot lock
7029 ** file path */
7030 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7031 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7032 }else{
7033 /* all other styles use the locking context to store the db file path */
7034 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007035 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007036 }
7037 return SQLITE_OK;
7038}
7039
7040/*
7041** Takes an already filled in unix file and alters it so all file locking
7042** will be performed on the local proxy lock file. The following fields
7043** are preserved in the locking context so that they can be restored and
7044** the unix structure properly cleaned up at close time:
7045** ->lockingContext
7046** ->pMethod
7047*/
7048static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7049 proxyLockingContext *pCtx;
7050 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7051 char *lockPath=NULL;
7052 int rc = SQLITE_OK;
7053
drh308c2a52010-05-14 11:30:18 +00007054 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007055 return SQLITE_BUSY;
7056 }
7057 proxyGetDbPathForUnixFile(pFile, dbPath);
7058 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7059 lockPath=NULL;
7060 }else{
7061 lockPath=(char *)path;
7062 }
7063
drh308c2a52010-05-14 11:30:18 +00007064 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7065 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007066
7067 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7068 if( pCtx==0 ){
7069 return SQLITE_NOMEM;
7070 }
7071 memset(pCtx, 0, sizeof(*pCtx));
7072
7073 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7074 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007075 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7076 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7077 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7078 ** (c) the file system is read-only, then enable no-locking access.
7079 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7080 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7081 */
7082 struct statfs fsInfo;
7083 struct stat conchInfo;
7084 int goLockless = 0;
7085
drh99ab3b12011-03-02 15:09:07 +00007086 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007087 int err = errno;
7088 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7089 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7090 }
7091 }
7092 if( goLockless ){
7093 pCtx->conchHeld = -1; /* read only FS/ lockless */
7094 rc = SQLITE_OK;
7095 }
7096 }
drh715ff302008-12-03 22:32:44 +00007097 }
7098 if( rc==SQLITE_OK && lockPath ){
7099 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7100 }
7101
7102 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007103 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7104 if( pCtx->dbPath==NULL ){
7105 rc = SQLITE_NOMEM;
7106 }
7107 }
7108 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007109 /* all memory is allocated, proxys are created and assigned,
7110 ** switch the locking context and pMethod then return.
7111 */
drh715ff302008-12-03 22:32:44 +00007112 pCtx->oldLockingContext = pFile->lockingContext;
7113 pFile->lockingContext = pCtx;
7114 pCtx->pOldMethod = pFile->pMethod;
7115 pFile->pMethod = &proxyIoMethods;
7116 }else{
7117 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007118 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007119 sqlite3_free(pCtx->conchFile);
7120 }
drhd56b1212010-08-11 06:14:15 +00007121 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007122 sqlite3_free(pCtx->conchFilePath);
7123 sqlite3_free(pCtx);
7124 }
drh308c2a52010-05-14 11:30:18 +00007125 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7126 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007127 return rc;
7128}
7129
7130
7131/*
7132** This routine handles sqlite3_file_control() calls that are specific
7133** to proxy locking.
7134*/
7135static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7136 switch( op ){
7137 case SQLITE_GET_LOCKPROXYFILE: {
7138 unixFile *pFile = (unixFile*)id;
7139 if( pFile->pMethod == &proxyIoMethods ){
7140 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7141 proxyTakeConch(pFile);
7142 if( pCtx->lockProxyPath ){
7143 *(const char **)pArg = pCtx->lockProxyPath;
7144 }else{
7145 *(const char **)pArg = ":auto: (not held)";
7146 }
7147 } else {
7148 *(const char **)pArg = NULL;
7149 }
7150 return SQLITE_OK;
7151 }
7152 case SQLITE_SET_LOCKPROXYFILE: {
7153 unixFile *pFile = (unixFile*)id;
7154 int rc = SQLITE_OK;
7155 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7156 if( pArg==NULL || (const char *)pArg==0 ){
7157 if( isProxyStyle ){
7158 /* turn off proxy locking - not supported */
7159 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7160 }else{
7161 /* turn off proxy locking - already off - NOOP */
7162 rc = SQLITE_OK;
7163 }
7164 }else{
7165 const char *proxyPath = (const char *)pArg;
7166 if( isProxyStyle ){
7167 proxyLockingContext *pCtx =
7168 (proxyLockingContext*)pFile->lockingContext;
7169 if( !strcmp(pArg, ":auto:")
7170 || (pCtx->lockProxyPath &&
7171 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7172 ){
7173 rc = SQLITE_OK;
7174 }else{
7175 rc = switchLockProxyPath(pFile, proxyPath);
7176 }
7177 }else{
7178 /* turn on proxy file locking */
7179 rc = proxyTransformUnixFile(pFile, proxyPath);
7180 }
7181 }
7182 return rc;
7183 }
7184 default: {
7185 assert( 0 ); /* The call assures that only valid opcodes are sent */
7186 }
7187 }
7188 /*NOTREACHED*/
7189 return SQLITE_ERROR;
7190}
7191
7192/*
7193** Within this division (the proxying locking implementation) the procedures
7194** above this point are all utilities. The lock-related methods of the
7195** proxy-locking sqlite3_io_method object follow.
7196*/
7197
7198
7199/*
7200** This routine checks if there is a RESERVED lock held on the specified
7201** file by this or any other process. If such a lock is held, set *pResOut
7202** to a non-zero value otherwise *pResOut is set to zero. The return value
7203** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7204*/
7205static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7206 unixFile *pFile = (unixFile*)id;
7207 int rc = proxyTakeConch(pFile);
7208 if( rc==SQLITE_OK ){
7209 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007210 if( pCtx->conchHeld>0 ){
7211 unixFile *proxy = pCtx->lockProxy;
7212 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7213 }else{ /* conchHeld < 0 is lockless */
7214 pResOut=0;
7215 }
drh715ff302008-12-03 22:32:44 +00007216 }
7217 return rc;
7218}
7219
7220/*
drh308c2a52010-05-14 11:30:18 +00007221** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007222** of the following:
7223**
7224** (1) SHARED_LOCK
7225** (2) RESERVED_LOCK
7226** (3) PENDING_LOCK
7227** (4) EXCLUSIVE_LOCK
7228**
7229** Sometimes when requesting one lock state, additional lock states
7230** are inserted in between. The locking might fail on one of the later
7231** transitions leaving the lock state different from what it started but
7232** still short of its goal. The following chart shows the allowed
7233** transitions and the inserted intermediate states:
7234**
7235** UNLOCKED -> SHARED
7236** SHARED -> RESERVED
7237** SHARED -> (PENDING) -> EXCLUSIVE
7238** RESERVED -> (PENDING) -> EXCLUSIVE
7239** PENDING -> EXCLUSIVE
7240**
7241** This routine will only increase a lock. Use the sqlite3OsUnlock()
7242** routine to lower a locking level.
7243*/
drh308c2a52010-05-14 11:30:18 +00007244static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007245 unixFile *pFile = (unixFile*)id;
7246 int rc = proxyTakeConch(pFile);
7247 if( rc==SQLITE_OK ){
7248 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007249 if( pCtx->conchHeld>0 ){
7250 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007251 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7252 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007253 }else{
7254 /* conchHeld < 0 is lockless */
7255 }
drh715ff302008-12-03 22:32:44 +00007256 }
7257 return rc;
7258}
7259
7260
7261/*
drh308c2a52010-05-14 11:30:18 +00007262** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007263** must be either NO_LOCK or SHARED_LOCK.
7264**
7265** If the locking level of the file descriptor is already at or below
7266** the requested locking level, this routine is a no-op.
7267*/
drh308c2a52010-05-14 11:30:18 +00007268static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007269 unixFile *pFile = (unixFile*)id;
7270 int rc = proxyTakeConch(pFile);
7271 if( rc==SQLITE_OK ){
7272 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007273 if( pCtx->conchHeld>0 ){
7274 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007275 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7276 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007277 }else{
7278 /* conchHeld < 0 is lockless */
7279 }
drh715ff302008-12-03 22:32:44 +00007280 }
7281 return rc;
7282}
7283
7284/*
7285** Close a file that uses proxy locks.
7286*/
7287static int proxyClose(sqlite3_file *id) {
7288 if( id ){
7289 unixFile *pFile = (unixFile*)id;
7290 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7291 unixFile *lockProxy = pCtx->lockProxy;
7292 unixFile *conchFile = pCtx->conchFile;
7293 int rc = SQLITE_OK;
7294
7295 if( lockProxy ){
7296 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7297 if( rc ) return rc;
7298 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7299 if( rc ) return rc;
7300 sqlite3_free(lockProxy);
7301 pCtx->lockProxy = 0;
7302 }
7303 if( conchFile ){
7304 if( pCtx->conchHeld ){
7305 rc = proxyReleaseConch(pFile);
7306 if( rc ) return rc;
7307 }
7308 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7309 if( rc ) return rc;
7310 sqlite3_free(conchFile);
7311 }
drhd56b1212010-08-11 06:14:15 +00007312 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007313 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007314 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007315 /* restore the original locking context and pMethod then close it */
7316 pFile->lockingContext = pCtx->oldLockingContext;
7317 pFile->pMethod = pCtx->pOldMethod;
7318 sqlite3_free(pCtx);
7319 return pFile->pMethod->xClose(id);
7320 }
7321 return SQLITE_OK;
7322}
7323
7324
7325
drhd2cb50b2009-01-09 21:41:17 +00007326#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007327/*
7328** The proxy locking style is intended for use with AFP filesystems.
7329** And since AFP is only supported on MacOSX, the proxy locking is also
7330** restricted to MacOSX.
7331**
7332**
7333******************* End of the proxy lock implementation **********************
7334******************************************************************************/
7335
drh734c9862008-11-28 15:37:20 +00007336/*
danielk1977e339d652008-06-28 11:23:00 +00007337** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007338**
7339** This routine registers all VFS implementations for unix-like operating
7340** systems. This routine, and the sqlite3_os_end() routine that follows,
7341** should be the only routines in this file that are visible from other
7342** files.
drh6b9d6dd2008-12-03 19:34:47 +00007343**
7344** This routine is called once during SQLite initialization and by a
7345** single thread. The memory allocation and mutex subsystems have not
7346** necessarily been initialized when this routine is called, and so they
7347** should not be used.
drh153c62c2007-08-24 03:51:33 +00007348*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007349int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007350 /*
7351 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007352 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7353 ** to the "finder" function. (pAppData is a pointer to a pointer because
7354 ** silly C90 rules prohibit a void* from being cast to a function pointer
7355 ** and so we have to go through the intermediate pointer to avoid problems
7356 ** when compiling with -pedantic-errors on GCC.)
7357 **
7358 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007359 ** finder-function. The finder-function returns a pointer to the
7360 ** sqlite_io_methods object that implements the desired locking
7361 ** behaviors. See the division above that contains the IOMETHODS
7362 ** macro for addition information on finder-functions.
7363 **
7364 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7365 ** object. But the "autolockIoFinder" available on MacOSX does a little
7366 ** more than that; it looks at the filesystem type that hosts the
7367 ** database file and tries to choose an locking method appropriate for
7368 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007369 */
drh7708e972008-11-29 00:56:52 +00007370 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007371 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007372 sizeof(unixFile), /* szOsFile */ \
7373 MAX_PATHNAME, /* mxPathname */ \
7374 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007375 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007376 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007377 unixOpen, /* xOpen */ \
7378 unixDelete, /* xDelete */ \
7379 unixAccess, /* xAccess */ \
7380 unixFullPathname, /* xFullPathname */ \
7381 unixDlOpen, /* xDlOpen */ \
7382 unixDlError, /* xDlError */ \
7383 unixDlSym, /* xDlSym */ \
7384 unixDlClose, /* xDlClose */ \
7385 unixRandomness, /* xRandomness */ \
7386 unixSleep, /* xSleep */ \
7387 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007388 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007389 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007390 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007391 unixGetSystemCall, /* xGetSystemCall */ \
7392 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007393 }
7394
drh6b9d6dd2008-12-03 19:34:47 +00007395 /*
7396 ** All default VFSes for unix are contained in the following array.
7397 **
7398 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7399 ** by the SQLite core when the VFS is registered. So the following
7400 ** array cannot be const.
7401 */
danielk1977e339d652008-06-28 11:23:00 +00007402 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007403#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007404 UNIXVFS("unix", autolockIoFinder ),
7405#else
7406 UNIXVFS("unix", posixIoFinder ),
7407#endif
7408 UNIXVFS("unix-none", nolockIoFinder ),
7409 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007410 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007411#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007412 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007413#endif
7414#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007415 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007416#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007417 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007418#endif
chw78a13182009-04-07 05:35:03 +00007419#endif
drhd2cb50b2009-01-09 21:41:17 +00007420#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007421 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007422 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007423 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007424#endif
drh153c62c2007-08-24 03:51:33 +00007425 };
drh6b9d6dd2008-12-03 19:34:47 +00007426 unsigned int i; /* Loop counter */
7427
drh2aa5a002011-04-13 13:42:25 +00007428 /* Double-check that the aSyscall[] array has been constructed
7429 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhd1ab8062013-03-25 20:50:25 +00007430 assert( ArraySize(aSyscall)==24 );
drh2aa5a002011-04-13 13:42:25 +00007431
drh6b9d6dd2008-12-03 19:34:47 +00007432 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007433 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007434 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007435 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007436 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007437}
danielk1977e339d652008-06-28 11:23:00 +00007438
7439/*
drh6b9d6dd2008-12-03 19:34:47 +00007440** Shutdown the operating system interface.
7441**
7442** Some operating systems might need to do some cleanup in this routine,
7443** to release dynamically allocated objects. But not on unix.
7444** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007445*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007446int sqlite3_os_end(void){
7447 return SQLITE_OK;
7448}
drhdce8bdb2007-08-16 13:01:44 +00007449
danielk197729bafea2008-06-26 10:41:19 +00007450#endif /* SQLITE_OS_UNIX */