blob: ab657dc7bdc35fa19fe278f7152fc966b49ed855 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +0000122#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
drh1da88f02011-12-17 16:09:16 +0000125
danielk1977e339d652008-06-28 11:23:00 +0000126
drh40bbb0a2008-09-23 10:23:26 +0000127#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000128# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000129# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <semaphore.h>
131# include <limits.h>
132# else
drh9b35ea62008-11-29 02:20:26 +0000133# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000135# endif
drhbfe66312006-10-03 17:40:40 +0000136#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000137
drhf8b4d8c2010-03-05 13:53:22 +0000138#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000139# include <sys/mount.h>
140#endif
141
drhdbe4b882011-06-20 18:00:17 +0000142#ifdef HAVE_UTIME
143# include <utime.h>
144#endif
145
drh9cbe6352005-11-29 03:13:21 +0000146/*
drh7ed97b92010-01-20 13:07:21 +0000147** Allowed values of unixFile.fsFlags
148*/
149#define SQLITE_FSFLAGS_IS_MSDOS 0x1
150
151/*
drhf1a221e2006-01-15 17:27:17 +0000152** If we are to be thread-safe, include the pthreads header and define
153** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000154*/
drhd677b3d2007-08-20 22:48:41 +0000155#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000156# include <pthread.h>
157# define SQLITE_UNIX_THREADS 1
158#endif
159
160/*
161** Default permissions when creating a new file
162*/
163#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
164# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
165#endif
166
danielk1977b4b47412007-08-17 15:53:36 +0000167/*
drh5adc60b2012-04-14 13:25:11 +0000168** Default permissions when creating auto proxy dir
169*/
aswiftaebf4132008-11-21 00:10:35 +0000170#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
171# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
172#endif
173
174/*
danielk1977b4b47412007-08-17 15:53:36 +0000175** Maximum supported path-length.
176*/
177#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000178
drh734c9862008-11-28 15:37:20 +0000179/*
drh734c9862008-11-28 15:37:20 +0000180** Only set the lastErrno if the error code is a real error and not
181** a normal expected return code of SQLITE_BUSY or SQLITE_OK
182*/
183#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
184
drhd91c68f2010-05-14 14:52:25 +0000185/* Forward references */
186typedef struct unixShm unixShm; /* Connection shared memory */
187typedef struct unixShmNode unixShmNode; /* Shared memory instance */
188typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
189typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000190
191/*
dane946c392009-08-22 11:39:46 +0000192** Sometimes, after a file handle is closed by SQLite, the file descriptor
193** cannot be closed immediately. In these cases, instances of the following
194** structure are used to store the file descriptor while waiting for an
195** opportunity to either close or reuse it.
196*/
dane946c392009-08-22 11:39:46 +0000197struct UnixUnusedFd {
198 int fd; /* File descriptor to close */
199 int flags; /* Flags this file descriptor was opened with */
200 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
201};
202
203/*
drh9b35ea62008-11-29 02:20:26 +0000204** The unixFile structure is subclass of sqlite3_file specific to the unix
205** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000206*/
drh054889e2005-11-30 03:20:31 +0000207typedef struct unixFile unixFile;
208struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000209 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000210 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000211 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000212 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000213 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000214 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000215 int lastErrno; /* The unix errno from last I/O error */
216 void *lockingContext; /* Locking style specific state */
217 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000218 const char *zPath; /* Name of the file */
219 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000220 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000221#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000222 int nFetchOut; /* Number of outstanding xFetch refs */
223 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000224 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
225 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000226 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000227#endif
drh537dddf2012-10-26 13:46:24 +0000228#ifdef __QNXNTO__
229 int sectorSize; /* Device sector size */
230 int deviceCharacteristics; /* Precomputed device characteristics */
231#endif
drh08c6d442009-02-09 17:34:07 +0000232#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000233 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000234#endif
drh7ed97b92010-01-20 13:07:21 +0000235#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000236 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000237#endif
238#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000239 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000240#endif
drhd3d8c042012-05-29 17:02:40 +0000241#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000242 /* The next group of variables are used to track whether or not the
243 ** transaction counter in bytes 24-27 of database files are updated
244 ** whenever any part of the database changes. An assertion fault will
245 ** occur if a file is updated without also updating the transaction
246 ** counter. This test is made to avoid new problems similar to the
247 ** one described by ticket #3584.
248 */
249 unsigned char transCntrChng; /* True if the transaction counter changed */
250 unsigned char dbUpdate; /* True if any part of database file changed */
251 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000252
drh8f941bc2009-01-14 23:03:40 +0000253#endif
danf23da962013-03-23 21:00:41 +0000254
danielk1977967a4a12007-08-20 14:23:44 +0000255#ifdef SQLITE_TEST
256 /* In test mode, increase the size of this structure a bit so that
257 ** it is larger than the struct CrashFile defined in test6.c.
258 */
259 char aPadding[32];
260#endif
drh9cbe6352005-11-29 03:13:21 +0000261};
262
drh0ccebe72005-06-07 22:22:50 +0000263/*
drha7e61d82011-03-12 17:02:57 +0000264** Allowed values for the unixFile.ctrlFlags bitmask:
265*/
drhf0b190d2011-07-26 16:03:07 +0000266#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
267#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
268#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000269#ifndef SQLITE_DISABLE_DIRSYNC
270# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
271#else
272# define UNIXFILE_DIRSYNC 0x00
273#endif
drhcb15f352011-12-23 01:04:17 +0000274#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000275#define UNIXFILE_DELETE 0x20 /* Delete on close */
276#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
277#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhfbc7e882013-04-11 01:16:15 +0000278#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
drha7e61d82011-03-12 17:02:57 +0000279
280/*
drh198bf392006-01-06 21:52:49 +0000281** Include code that is common to all os_*.c files
282*/
283#include "os_common.h"
284
285/*
drh0ccebe72005-06-07 22:22:50 +0000286** Define various macros that are missing from some systems.
287*/
drhbbd42a62004-05-22 17:41:58 +0000288#ifndef O_LARGEFILE
289# define O_LARGEFILE 0
290#endif
291#ifdef SQLITE_DISABLE_LFS
292# undef O_LARGEFILE
293# define O_LARGEFILE 0
294#endif
295#ifndef O_NOFOLLOW
296# define O_NOFOLLOW 0
297#endif
298#ifndef O_BINARY
299# define O_BINARY 0
300#endif
301
302/*
drh2b4b5962005-06-15 17:47:55 +0000303** The threadid macro resolves to the thread-id or to 0. Used for
304** testing and debugging only.
305*/
drhd677b3d2007-08-20 22:48:41 +0000306#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000307#define threadid pthread_self()
308#else
309#define threadid 0
310#endif
311
drh99ab3b12011-03-02 15:09:07 +0000312/*
dane6ecd662013-04-01 17:56:59 +0000313** HAVE_MREMAP defaults to true on Linux and false everywhere else.
314*/
315#if !defined(HAVE_MREMAP)
316# if defined(__linux__) && defined(_GNU_SOURCE)
317# define HAVE_MREMAP 1
318# else
319# define HAVE_MREMAP 0
320# endif
321#endif
322
323/*
drh9a3baf12011-04-25 18:01:27 +0000324** Different Unix systems declare open() in different ways. Same use
325** open(const char*,int,mode_t). Others use open(const char*,int,...).
326** The difference is important when using a pointer to the function.
327**
328** The safest way to deal with the problem is to always use this wrapper
329** which always has the same well-defined interface.
330*/
331static int posixOpen(const char *zFile, int flags, int mode){
332 return open(zFile, flags, mode);
333}
334
drhed466822012-05-31 13:10:49 +0000335/*
336** On some systems, calls to fchown() will trigger a message in a security
337** log if they come from non-root processes. So avoid calling fchown() if
338** we are not running as root.
339*/
340static int posixFchown(int fd, uid_t uid, gid_t gid){
341 return geteuid() ? 0 : fchown(fd,uid,gid);
342}
343
drh90315a22011-08-10 01:52:12 +0000344/* Forward reference */
345static int openDirectory(const char*, int*);
346
drh9a3baf12011-04-25 18:01:27 +0000347/*
drh99ab3b12011-03-02 15:09:07 +0000348** Many system calls are accessed through pointer-to-functions so that
349** they may be overridden at runtime to facilitate fault injection during
350** testing and sandboxing. The following array holds the names and pointers
351** to all overrideable system calls.
352*/
353static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000354 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000355 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
356 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000357} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000358 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
359#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000360
drh58ad5802011-03-23 22:02:23 +0000361 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000362#define osClose ((int(*)(int))aSyscall[1].pCurrent)
363
drh58ad5802011-03-23 22:02:23 +0000364 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000365#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
366
drh58ad5802011-03-23 22:02:23 +0000367 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
369
drh58ad5802011-03-23 22:02:23 +0000370 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
372
373/*
374** The DJGPP compiler environment looks mostly like Unix, but it
375** lacks the fcntl() system call. So redefine fcntl() to be something
376** that always succeeds. This means that locking does not occur under
377** DJGPP. But it is DOS - what did you expect?
378*/
379#ifdef __DJGPP__
380 { "fstat", 0, 0 },
381#define osFstat(a,b,c) 0
382#else
drh58ad5802011-03-23 22:02:23 +0000383 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000384#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
385#endif
386
drh58ad5802011-03-23 22:02:23 +0000387 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000388#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
389
drh58ad5802011-03-23 22:02:23 +0000390 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000391#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000392
drh58ad5802011-03-23 22:02:23 +0000393 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000394#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
395
drhd4a80312011-04-15 14:33:20 +0000396#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000397 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000398#else
drh58ad5802011-03-23 22:02:23 +0000399 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000400#endif
401#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
402
403#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000404 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000405#else
drh58ad5802011-03-23 22:02:23 +0000406 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000407#endif
408#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
409
drh58ad5802011-03-23 22:02:23 +0000410 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000411#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
412
drhd4a80312011-04-15 14:33:20 +0000413#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000414 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000415#else
drh58ad5802011-03-23 22:02:23 +0000416 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000417#endif
418#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
419 aSyscall[12].pCurrent)
420
421#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000422 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000423#else
drh58ad5802011-03-23 22:02:23 +0000424 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000425#endif
426#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
427 aSyscall[13].pCurrent)
428
drh58ad5802011-03-23 22:02:23 +0000429 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000430#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000431
432#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000433 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000434#else
drh58ad5802011-03-23 22:02:23 +0000435 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000436#endif
dan0fd7d862011-03-29 10:04:23 +0000437#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000438
drh036ac7f2011-08-08 23:18:05 +0000439 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
440#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
441
drh90315a22011-08-10 01:52:12 +0000442 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
443#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
444
drh9ef6bc42011-11-04 02:24:02 +0000445 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
446#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
447
448 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
449#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
450
drhed466822012-05-31 13:10:49 +0000451 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000452#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000453
dan4dd51442013-08-26 14:30:25 +0000454#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000455 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
456#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
457
drhd1ab8062013-03-25 20:50:25 +0000458 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
459#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
460
dane6ecd662013-04-01 17:56:59 +0000461#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000462 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
463#else
464 { "mremap", (sqlite3_syscall_ptr)0, 0 },
465#endif
466#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
dan4dd51442013-08-26 14:30:25 +0000467#endif
drhd1ab8062013-03-25 20:50:25 +0000468
drhe562be52011-03-02 18:01:10 +0000469}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000470
471/*
472** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000473** "unix" VFSes. Return SQLITE_OK opon successfully updating the
474** system call pointer, or SQLITE_NOTFOUND if there is no configurable
475** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000476*/
477static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000478 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
479 const char *zName, /* Name of system call to override */
480 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000481){
drh58ad5802011-03-23 22:02:23 +0000482 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000483 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000484
485 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000486 if( zName==0 ){
487 /* If no zName is given, restore all system calls to their default
488 ** settings and return NULL
489 */
dan51438a72011-04-02 17:00:47 +0000490 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000491 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
492 if( aSyscall[i].pDefault ){
493 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000494 }
495 }
496 }else{
497 /* If zName is specified, operate on only the one system call
498 ** specified.
499 */
500 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
501 if( strcmp(zName, aSyscall[i].zName)==0 ){
502 if( aSyscall[i].pDefault==0 ){
503 aSyscall[i].pDefault = aSyscall[i].pCurrent;
504 }
drh1df30962011-03-02 19:06:42 +0000505 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000506 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
507 aSyscall[i].pCurrent = pNewFunc;
508 break;
509 }
510 }
511 }
512 return rc;
513}
514
drh1df30962011-03-02 19:06:42 +0000515/*
516** Return the value of a system call. Return NULL if zName is not a
517** recognized system call name. NULL is also returned if the system call
518** is currently undefined.
519*/
drh58ad5802011-03-23 22:02:23 +0000520static sqlite3_syscall_ptr unixGetSystemCall(
521 sqlite3_vfs *pNotUsed,
522 const char *zName
523){
524 unsigned int i;
525
526 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000527 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
528 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
529 }
530 return 0;
531}
532
533/*
534** Return the name of the first system call after zName. If zName==NULL
535** then return the name of the first system call. Return NULL if zName
536** is the last system call or if zName is not the name of a valid
537** system call.
538*/
539static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000540 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000541
542 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000543 if( zName ){
544 for(i=0; i<ArraySize(aSyscall)-1; i++){
545 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000546 }
547 }
dan0fd7d862011-03-29 10:04:23 +0000548 for(i++; i<ArraySize(aSyscall); i++){
549 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000550 }
551 return 0;
552}
553
drhad4f1e52011-03-04 15:43:57 +0000554/*
drh77a3fdc2013-08-30 14:24:12 +0000555** Do not accept any file descriptor less than this value, in order to avoid
556** opening database file using file descriptors that are commonly used for
557** standard input, output, and error.
558*/
559#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
560# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
561#endif
562
563/*
drh8c815d12012-02-13 20:16:37 +0000564** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000565** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000566**
567** If the file creation mode "m" is 0 then set it to the default for
568** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
569** 0644) as modified by the system umask. If m is not 0, then
570** make the file creation mode be exactly m ignoring the umask.
571**
572** The m parameter will be non-zero only when creating -wal, -journal,
573** and -shm files. We want those files to have *exactly* the same
574** permissions as their original database, unadulterated by the umask.
575** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
576** transaction crashes and leaves behind hot journals, then any
577** process that is able to write to the database will also be able to
578** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000579*/
drh8c815d12012-02-13 20:16:37 +0000580static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000581 int fd;
drhe1186ab2013-01-04 20:45:13 +0000582 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000583 while(1){
drh5adc60b2012-04-14 13:25:11 +0000584#if defined(O_CLOEXEC)
585 fd = osOpen(z,f|O_CLOEXEC,m2);
586#else
587 fd = osOpen(z,f,m2);
588#endif
drh5128d002013-08-30 06:20:23 +0000589 if( fd<0 ){
590 if( errno==EINTR ) continue;
591 break;
592 }
drh77a3fdc2013-08-30 14:24:12 +0000593 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000594 osClose(fd);
595 sqlite3_log(SQLITE_WARNING,
596 "attempt to open \"%s\" as file descriptor %d", z, fd);
597 fd = -1;
598 if( osOpen("/dev/null", f, m)<0 ) break;
599 }
drhe1186ab2013-01-04 20:45:13 +0000600 if( fd>=0 ){
601 if( m!=0 ){
602 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000603 if( osFstat(fd, &statbuf)==0
604 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000605 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000606 ){
drhe1186ab2013-01-04 20:45:13 +0000607 osFchmod(fd, m);
608 }
609 }
drh5adc60b2012-04-14 13:25:11 +0000610#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000611 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000612#endif
drhe1186ab2013-01-04 20:45:13 +0000613 }
drh5adc60b2012-04-14 13:25:11 +0000614 return fd;
drhad4f1e52011-03-04 15:43:57 +0000615}
danielk197713adf8a2004-06-03 16:08:41 +0000616
drh107886a2008-11-21 22:21:50 +0000617/*
dan9359c7b2009-08-21 08:29:10 +0000618** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000619** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000620** vxworksFileId objects used by this file, all of which may be
621** shared by multiple threads.
622**
623** Function unixMutexHeld() is used to assert() that the global mutex
624** is held when required. This function is only used as part of assert()
625** statements. e.g.
626**
627** unixEnterMutex()
628** assert( unixMutexHeld() );
629** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000630*/
631static void unixEnterMutex(void){
632 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
633}
634static void unixLeaveMutex(void){
635 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
636}
dan9359c7b2009-08-21 08:29:10 +0000637#ifdef SQLITE_DEBUG
638static int unixMutexHeld(void) {
639 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
640}
641#endif
drh107886a2008-11-21 22:21:50 +0000642
drh734c9862008-11-28 15:37:20 +0000643
drh30ddce62011-10-15 00:16:30 +0000644#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000645/*
646** Helper function for printing out trace information from debugging
647** binaries. This returns the string represetation of the supplied
648** integer lock-type.
649*/
drh308c2a52010-05-14 11:30:18 +0000650static const char *azFileLock(int eFileLock){
651 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000652 case NO_LOCK: return "NONE";
653 case SHARED_LOCK: return "SHARED";
654 case RESERVED_LOCK: return "RESERVED";
655 case PENDING_LOCK: return "PENDING";
656 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000657 }
658 return "ERROR";
659}
660#endif
661
662#ifdef SQLITE_LOCK_TRACE
663/*
664** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000665**
drh734c9862008-11-28 15:37:20 +0000666** This routine is used for troubleshooting locks on multithreaded
667** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
668** command-line option on the compiler. This code is normally
669** turned off.
670*/
671static int lockTrace(int fd, int op, struct flock *p){
672 char *zOpName, *zType;
673 int s;
674 int savedErrno;
675 if( op==F_GETLK ){
676 zOpName = "GETLK";
677 }else if( op==F_SETLK ){
678 zOpName = "SETLK";
679 }else{
drh99ab3b12011-03-02 15:09:07 +0000680 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000681 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
682 return s;
683 }
684 if( p->l_type==F_RDLCK ){
685 zType = "RDLCK";
686 }else if( p->l_type==F_WRLCK ){
687 zType = "WRLCK";
688 }else if( p->l_type==F_UNLCK ){
689 zType = "UNLCK";
690 }else{
691 assert( 0 );
692 }
693 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000694 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000695 savedErrno = errno;
696 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
697 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
698 (int)p->l_pid, s);
699 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
700 struct flock l2;
701 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000702 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000703 if( l2.l_type==F_RDLCK ){
704 zType = "RDLCK";
705 }else if( l2.l_type==F_WRLCK ){
706 zType = "WRLCK";
707 }else if( l2.l_type==F_UNLCK ){
708 zType = "UNLCK";
709 }else{
710 assert( 0 );
711 }
712 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
713 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
714 }
715 errno = savedErrno;
716 return s;
717}
drh99ab3b12011-03-02 15:09:07 +0000718#undef osFcntl
719#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000720#endif /* SQLITE_LOCK_TRACE */
721
drhff812312011-02-23 13:33:46 +0000722/*
723** Retry ftruncate() calls that fail due to EINTR
724*/
drhff812312011-02-23 13:33:46 +0000725static int robust_ftruncate(int h, sqlite3_int64 sz){
726 int rc;
drh99ab3b12011-03-02 15:09:07 +0000727 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000728 return rc;
729}
drh734c9862008-11-28 15:37:20 +0000730
731/*
732** This routine translates a standard POSIX errno code into something
733** useful to the clients of the sqlite3 functions. Specifically, it is
734** intended to translate a variety of "try again" errors into SQLITE_BUSY
735** and a variety of "please close the file descriptor NOW" errors into
736** SQLITE_IOERR
737**
738** Errors during initialization of locks, or file system support for locks,
739** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
740*/
741static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
742 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000743#if 0
744 /* At one point this code was not commented out. In theory, this branch
745 ** should never be hit, as this function should only be called after
746 ** a locking-related function (i.e. fcntl()) has returned non-zero with
747 ** the value of errno as the first argument. Since a system call has failed,
748 ** errno should be non-zero.
749 **
750 ** Despite this, if errno really is zero, we still don't want to return
751 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
752 ** propagated back to the caller. Commenting this branch out means errno==0
753 ** will be handled by the "default:" case below.
754 */
drh734c9862008-11-28 15:37:20 +0000755 case 0:
756 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000757#endif
758
drh734c9862008-11-28 15:37:20 +0000759 case EAGAIN:
760 case ETIMEDOUT:
761 case EBUSY:
762 case EINTR:
763 case ENOLCK:
764 /* random NFS retry error, unless during file system support
765 * introspection, in which it actually means what it says */
766 return SQLITE_BUSY;
767
768 case EACCES:
769 /* EACCES is like EAGAIN during locking operations, but not any other time*/
770 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000771 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
772 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
773 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000774 return SQLITE_BUSY;
775 }
776 /* else fall through */
777 case EPERM:
778 return SQLITE_PERM;
779
danea83bc62011-04-01 11:56:32 +0000780 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
781 ** this module never makes such a call. And the code in SQLite itself
782 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
783 ** this case is also commented out. If the system does set errno to EDEADLK,
784 ** the default SQLITE_IOERR_XXX code will be returned. */
785#if 0
drh734c9862008-11-28 15:37:20 +0000786 case EDEADLK:
787 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000788#endif
drh734c9862008-11-28 15:37:20 +0000789
790#if EOPNOTSUPP!=ENOTSUP
791 case EOPNOTSUPP:
792 /* something went terribly awry, unless during file system support
793 * introspection, in which it actually means what it says */
794#endif
795#ifdef ENOTSUP
796 case ENOTSUP:
797 /* invalid fd, unless during file system support introspection, in which
798 * it actually means what it says */
799#endif
800 case EIO:
801 case EBADF:
802 case EINVAL:
803 case ENOTCONN:
804 case ENODEV:
805 case ENXIO:
806 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000807#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000808 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000809#endif
drh734c9862008-11-28 15:37:20 +0000810 case ENOSYS:
811 /* these should force the client to close the file and reconnect */
812
813 default:
814 return sqliteIOErr;
815 }
816}
817
818
drh734c9862008-11-28 15:37:20 +0000819/******************************************************************************
820****************** Begin Unique File ID Utility Used By VxWorks ***************
821**
822** On most versions of unix, we can get a unique ID for a file by concatenating
823** the device number and the inode number. But this does not work on VxWorks.
824** On VxWorks, a unique file id must be based on the canonical filename.
825**
826** A pointer to an instance of the following structure can be used as a
827** unique file ID in VxWorks. Each instance of this structure contains
828** a copy of the canonical filename. There is also a reference count.
829** The structure is reclaimed when the number of pointers to it drops to
830** zero.
831**
832** There are never very many files open at one time and lookups are not
833** a performance-critical path, so it is sufficient to put these
834** structures on a linked list.
835*/
836struct vxworksFileId {
837 struct vxworksFileId *pNext; /* Next in a list of them all */
838 int nRef; /* Number of references to this one */
839 int nName; /* Length of the zCanonicalName[] string */
840 char *zCanonicalName; /* Canonical filename */
841};
842
843#if OS_VXWORKS
844/*
drh9b35ea62008-11-29 02:20:26 +0000845** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000846** variable:
847*/
848static struct vxworksFileId *vxworksFileList = 0;
849
850/*
851** Simplify a filename into its canonical form
852** by making the following changes:
853**
854** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000855** * convert /./ into just /
856** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000857**
858** Changes are made in-place. Return the new name length.
859**
860** The original filename is in z[0..n-1]. Return the number of
861** characters in the simplified name.
862*/
863static int vxworksSimplifyName(char *z, int n){
864 int i, j;
865 while( n>1 && z[n-1]=='/' ){ n--; }
866 for(i=j=0; i<n; i++){
867 if( z[i]=='/' ){
868 if( z[i+1]=='/' ) continue;
869 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
870 i += 1;
871 continue;
872 }
873 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
874 while( j>0 && z[j-1]!='/' ){ j--; }
875 if( j>0 ){ j--; }
876 i += 2;
877 continue;
878 }
879 }
880 z[j++] = z[i];
881 }
882 z[j] = 0;
883 return j;
884}
885
886/*
887** Find a unique file ID for the given absolute pathname. Return
888** a pointer to the vxworksFileId object. This pointer is the unique
889** file ID.
890**
891** The nRef field of the vxworksFileId object is incremented before
892** the object is returned. A new vxworksFileId object is created
893** and added to the global list if necessary.
894**
895** If a memory allocation error occurs, return NULL.
896*/
897static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
898 struct vxworksFileId *pNew; /* search key and new file ID */
899 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
900 int n; /* Length of zAbsoluteName string */
901
902 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000903 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000904 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
905 if( pNew==0 ) return 0;
906 pNew->zCanonicalName = (char*)&pNew[1];
907 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
908 n = vxworksSimplifyName(pNew->zCanonicalName, n);
909
910 /* Search for an existing entry that matching the canonical name.
911 ** If found, increment the reference count and return a pointer to
912 ** the existing file ID.
913 */
914 unixEnterMutex();
915 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
916 if( pCandidate->nName==n
917 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
918 ){
919 sqlite3_free(pNew);
920 pCandidate->nRef++;
921 unixLeaveMutex();
922 return pCandidate;
923 }
924 }
925
926 /* No match was found. We will make a new file ID */
927 pNew->nRef = 1;
928 pNew->nName = n;
929 pNew->pNext = vxworksFileList;
930 vxworksFileList = pNew;
931 unixLeaveMutex();
932 return pNew;
933}
934
935/*
936** Decrement the reference count on a vxworksFileId object. Free
937** the object when the reference count reaches zero.
938*/
939static void vxworksReleaseFileId(struct vxworksFileId *pId){
940 unixEnterMutex();
941 assert( pId->nRef>0 );
942 pId->nRef--;
943 if( pId->nRef==0 ){
944 struct vxworksFileId **pp;
945 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
946 assert( *pp==pId );
947 *pp = pId->pNext;
948 sqlite3_free(pId);
949 }
950 unixLeaveMutex();
951}
952#endif /* OS_VXWORKS */
953/*************** End of Unique File ID Utility Used By VxWorks ****************
954******************************************************************************/
955
956
957/******************************************************************************
958*************************** Posix Advisory Locking ****************************
959**
drh9b35ea62008-11-29 02:20:26 +0000960** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000961** section 6.5.2.2 lines 483 through 490 specify that when a process
962** sets or clears a lock, that operation overrides any prior locks set
963** by the same process. It does not explicitly say so, but this implies
964** that it overrides locks set by the same process using a different
965** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000966**
967** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000968** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
969**
970** Suppose ./file1 and ./file2 are really the same file (because
971** one is a hard or symbolic link to the other) then if you set
972** an exclusive lock on fd1, then try to get an exclusive lock
973** on fd2, it works. I would have expected the second lock to
974** fail since there was already a lock on the file due to fd1.
975** But not so. Since both locks came from the same process, the
976** second overrides the first, even though they were on different
977** file descriptors opened on different file names.
978**
drh734c9862008-11-28 15:37:20 +0000979** This means that we cannot use POSIX locks to synchronize file access
980** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000981** to synchronize access for threads in separate processes, but not
982** threads within the same process.
983**
984** To work around the problem, SQLite has to manage file locks internally
985** on its own. Whenever a new database is opened, we have to find the
986** specific inode of the database file (the inode is determined by the
987** st_dev and st_ino fields of the stat structure that fstat() fills in)
988** and check for locks already existing on that inode. When locks are
989** created or removed, we have to look at our own internal record of the
990** locks to see if another thread has previously set a lock on that same
991** inode.
992**
drh9b35ea62008-11-29 02:20:26 +0000993** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
994** For VxWorks, we have to use the alternative unique ID system based on
995** canonical filename and implemented in the previous division.)
996**
danielk1977ad94b582007-08-20 06:44:22 +0000997** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000998** descriptor. It is now a structure that holds the integer file
999** descriptor and a pointer to a structure that describes the internal
1000** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001001** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001002** point to the same locking structure. The locking structure keeps
1003** a reference count (so we will know when to delete it) and a "cnt"
1004** field that tells us its internal lock status. cnt==0 means the
1005** file is unlocked. cnt==-1 means the file has an exclusive lock.
1006** cnt>0 means there are cnt shared locks on the file.
1007**
1008** Any attempt to lock or unlock a file first checks the locking
1009** structure. The fcntl() system call is only invoked to set a
1010** POSIX lock if the internal lock structure transitions between
1011** a locked and an unlocked state.
1012**
drh734c9862008-11-28 15:37:20 +00001013** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001014**
1015** If you close a file descriptor that points to a file that has locks,
1016** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001017** released. To work around this problem, each unixInodeInfo object
1018** maintains a count of the number of pending locks on tha inode.
1019** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001020** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001021** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001022** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001023** be closed and that list is walked (and cleared) when the last lock
1024** clears.
1025**
drh9b35ea62008-11-29 02:20:26 +00001026** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001027**
drh9b35ea62008-11-29 02:20:26 +00001028** Many older versions of linux use the LinuxThreads library which is
1029** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001030** A cannot be modified or overridden by a different thread B.
1031** Only thread A can modify the lock. Locking behavior is correct
1032** if the appliation uses the newer Native Posix Thread Library (NPTL)
1033** on linux - with NPTL a lock created by thread A can override locks
1034** in thread B. But there is no way to know at compile-time which
1035** threading library is being used. So there is no way to know at
1036** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001037** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001038** current process.
drh5fdae772004-06-29 03:29:00 +00001039**
drh8af6c222010-05-14 12:43:01 +00001040** SQLite used to support LinuxThreads. But support for LinuxThreads
1041** was dropped beginning with version 3.7.0. SQLite will still work with
1042** LinuxThreads provided that (1) there is no more than one connection
1043** per database file in the same process and (2) database connections
1044** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001045*/
1046
1047/*
1048** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001049** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001050*/
1051struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001052 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001053#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001054 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001055#else
drh107886a2008-11-21 22:21:50 +00001056 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001057#endif
1058};
1059
1060/*
drhbbd42a62004-05-22 17:41:58 +00001061** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001062** inode. Or, on LinuxThreads, there is one of these structures for
1063** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001064**
danielk1977ad94b582007-08-20 06:44:22 +00001065** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001066** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001067** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001068*/
drh8af6c222010-05-14 12:43:01 +00001069struct unixInodeInfo {
1070 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001071 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001072 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1073 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001074 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001075 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1076 int nLock; /* Number of outstanding file locks */
1077 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1078 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1079 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001080#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001081 unsigned long long sharedByte; /* for AFP simulated shared lock */
1082#endif
drh6c7d5c52008-11-21 20:32:33 +00001083#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001084 sem_t *pSem; /* Named POSIX semaphore */
1085 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001086#endif
drhbbd42a62004-05-22 17:41:58 +00001087};
1088
drhda0e7682008-07-30 15:27:54 +00001089/*
drh8af6c222010-05-14 12:43:01 +00001090** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001091*/
drhd91c68f2010-05-14 14:52:25 +00001092static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001093
drh5fdae772004-06-29 03:29:00 +00001094/*
dane18d4952011-02-21 11:46:24 +00001095**
1096** This function - unixLogError_x(), is only ever called via the macro
1097** unixLogError().
1098**
1099** It is invoked after an error occurs in an OS function and errno has been
1100** set. It logs a message using sqlite3_log() containing the current value of
1101** errno and, if possible, the human-readable equivalent from strerror() or
1102** strerror_r().
1103**
1104** The first argument passed to the macro should be the error code that
1105** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1106** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001107** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001108** if any.
1109*/
drh0e9365c2011-03-02 02:08:13 +00001110#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1111static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001112 int errcode, /* SQLite error code */
1113 const char *zFunc, /* Name of OS function that failed */
1114 const char *zPath, /* File path associated with error */
1115 int iLine /* Source line number where error occurred */
1116){
1117 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001118 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001119
1120 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1121 ** the strerror() function to obtain the human-readable error message
1122 ** equivalent to errno. Otherwise, use strerror_r().
1123 */
1124#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1125 char aErr[80];
1126 memset(aErr, 0, sizeof(aErr));
1127 zErr = aErr;
1128
1129 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001130 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001131 ** returns a pointer to a buffer containing the error message. That pointer
1132 ** may point to aErr[], or it may point to some static storage somewhere.
1133 ** Otherwise, assume that the system provides the POSIX version of
1134 ** strerror_r(), which always writes an error message into aErr[].
1135 **
1136 ** If the code incorrectly assumes that it is the POSIX version that is
1137 ** available, the error message will often be an empty string. Not a
1138 ** huge problem. Incorrectly concluding that the GNU version is available
1139 ** could lead to a segfault though.
1140 */
1141#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1142 zErr =
1143# endif
drh0e9365c2011-03-02 02:08:13 +00001144 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001145
1146#elif SQLITE_THREADSAFE
1147 /* This is a threadsafe build, but strerror_r() is not available. */
1148 zErr = "";
1149#else
1150 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001151 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001152#endif
1153
drh0e9365c2011-03-02 02:08:13 +00001154 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001155 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001156 "os_unix.c:%d: (%d) %s(%s) - %s",
1157 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001158 );
1159
1160 return errcode;
1161}
1162
drh0e9365c2011-03-02 02:08:13 +00001163/*
1164** Close a file descriptor.
1165**
1166** We assume that close() almost always works, since it is only in a
1167** very sick application or on a very sick platform that it might fail.
1168** If it does fail, simply leak the file descriptor, but do log the
1169** error.
1170**
1171** Note that it is not safe to retry close() after EINTR since the
1172** file descriptor might have already been reused by another thread.
1173** So we don't even try to recover from an EINTR. Just log the error
1174** and move on.
1175*/
1176static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001177 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001178 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1179 pFile ? pFile->zPath : 0, lineno);
1180 }
1181}
dane18d4952011-02-21 11:46:24 +00001182
1183/*
danb0ac3e32010-06-16 10:55:42 +00001184** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001185*/
drh0e9365c2011-03-02 02:08:13 +00001186static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001187 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001188 UnixUnusedFd *p;
1189 UnixUnusedFd *pNext;
1190 for(p=pInode->pUnused; p; p=pNext){
1191 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001192 robust_close(pFile, p->fd, __LINE__);
1193 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001194 }
drh0e9365c2011-03-02 02:08:13 +00001195 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001196}
1197
1198/*
drh8af6c222010-05-14 12:43:01 +00001199** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001200**
1201** The mutex entered using the unixEnterMutex() function must be held
1202** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001203*/
danb0ac3e32010-06-16 10:55:42 +00001204static void releaseInodeInfo(unixFile *pFile){
1205 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001206 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001207 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001208 pInode->nRef--;
1209 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001210 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001211 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001212 if( pInode->pPrev ){
1213 assert( pInode->pPrev->pNext==pInode );
1214 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001215 }else{
drh8af6c222010-05-14 12:43:01 +00001216 assert( inodeList==pInode );
1217 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001218 }
drh8af6c222010-05-14 12:43:01 +00001219 if( pInode->pNext ){
1220 assert( pInode->pNext->pPrev==pInode );
1221 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001222 }
drh8af6c222010-05-14 12:43:01 +00001223 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001224 }
drhbbd42a62004-05-22 17:41:58 +00001225 }
1226}
1227
1228/*
drh8af6c222010-05-14 12:43:01 +00001229** Given a file descriptor, locate the unixInodeInfo object that
1230** describes that file descriptor. Create a new one if necessary. The
1231** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001232**
dan9359c7b2009-08-21 08:29:10 +00001233** The mutex entered using the unixEnterMutex() function must be held
1234** when this function is called.
1235**
drh6c7d5c52008-11-21 20:32:33 +00001236** Return an appropriate error code.
1237*/
drh8af6c222010-05-14 12:43:01 +00001238static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001239 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001240 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001241){
1242 int rc; /* System call return code */
1243 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001244 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1245 struct stat statbuf; /* Low-level file information */
1246 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001247
dan9359c7b2009-08-21 08:29:10 +00001248 assert( unixMutexHeld() );
1249
drh6c7d5c52008-11-21 20:32:33 +00001250 /* Get low-level information about the file that we can used to
1251 ** create a unique name for the file.
1252 */
1253 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001254 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001255 if( rc!=0 ){
1256 pFile->lastErrno = errno;
1257#ifdef EOVERFLOW
1258 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1259#endif
1260 return SQLITE_IOERR;
1261 }
1262
drheb0d74f2009-02-03 15:27:02 +00001263#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001264 /* On OS X on an msdos filesystem, the inode number is reported
1265 ** incorrectly for zero-size files. See ticket #3260. To work
1266 ** around this problem (we consider it a bug in OS X, not SQLite)
1267 ** we always increase the file size to 1 by writing a single byte
1268 ** prior to accessing the inode number. The one byte written is
1269 ** an ASCII 'S' character which also happens to be the first byte
1270 ** in the header of every SQLite database. In this way, if there
1271 ** is a race condition such that another thread has already populated
1272 ** the first page of the database, no damage is done.
1273 */
drh7ed97b92010-01-20 13:07:21 +00001274 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001275 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001276 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001277 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001278 return SQLITE_IOERR;
1279 }
drh99ab3b12011-03-02 15:09:07 +00001280 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001281 if( rc!=0 ){
1282 pFile->lastErrno = errno;
1283 return SQLITE_IOERR;
1284 }
1285 }
drheb0d74f2009-02-03 15:27:02 +00001286#endif
drh6c7d5c52008-11-21 20:32:33 +00001287
drh8af6c222010-05-14 12:43:01 +00001288 memset(&fileId, 0, sizeof(fileId));
1289 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001290#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001291 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001292#else
drh8af6c222010-05-14 12:43:01 +00001293 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001294#endif
drh8af6c222010-05-14 12:43:01 +00001295 pInode = inodeList;
1296 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1297 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001298 }
drh8af6c222010-05-14 12:43:01 +00001299 if( pInode==0 ){
1300 pInode = sqlite3_malloc( sizeof(*pInode) );
1301 if( pInode==0 ){
1302 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001303 }
drh8af6c222010-05-14 12:43:01 +00001304 memset(pInode, 0, sizeof(*pInode));
1305 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1306 pInode->nRef = 1;
1307 pInode->pNext = inodeList;
1308 pInode->pPrev = 0;
1309 if( inodeList ) inodeList->pPrev = pInode;
1310 inodeList = pInode;
1311 }else{
1312 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001313 }
drh8af6c222010-05-14 12:43:01 +00001314 *ppInode = pInode;
1315 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001316}
drh6c7d5c52008-11-21 20:32:33 +00001317
aswift5b1a2562008-08-22 00:22:35 +00001318
1319/*
drhfbc7e882013-04-11 01:16:15 +00001320** Check a unixFile that is a database. Verify the following:
1321**
1322** (1) There is exactly one hard link on the file
1323** (2) The file is not a symbolic link
1324** (3) The file has not been renamed or unlinked
1325**
1326** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1327*/
1328static void verifyDbFile(unixFile *pFile){
1329 struct stat buf;
1330 int rc;
1331 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1332 /* One or more of the following warnings have already been issued. Do not
1333 ** repeat them so as not to clutter the error log */
1334 return;
1335 }
1336 rc = osFstat(pFile->h, &buf);
1337 if( rc!=0 ){
1338 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1339 pFile->ctrlFlags |= UNIXFILE_WARNED;
1340 return;
1341 }
1342 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
1343 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1344 pFile->ctrlFlags |= UNIXFILE_WARNED;
1345 return;
1346 }
1347 if( buf.st_nlink>1 ){
1348 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1349 pFile->ctrlFlags |= UNIXFILE_WARNED;
1350 return;
1351 }
1352 if( pFile->pInode!=0
1353 && ((rc = osStat(pFile->zPath, &buf))!=0
1354 || buf.st_ino!=pFile->pInode->fileId.ino)
1355 ){
1356 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1357 pFile->ctrlFlags |= UNIXFILE_WARNED;
1358 return;
1359 }
1360}
1361
1362
1363/*
danielk197713adf8a2004-06-03 16:08:41 +00001364** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001365** file by this or any other process. If such a lock is held, set *pResOut
1366** to a non-zero value otherwise *pResOut is set to zero. The return value
1367** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001368*/
danielk1977861f7452008-06-05 11:39:11 +00001369static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001370 int rc = SQLITE_OK;
1371 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001372 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001373
danielk1977861f7452008-06-05 11:39:11 +00001374 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1375
drh054889e2005-11-30 03:20:31 +00001376 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001377 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001378
1379 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001380 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001381 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001382 }
1383
drh2ac3ee92004-06-07 16:27:46 +00001384 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001385 */
danielk197709480a92009-02-09 05:32:32 +00001386#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001387 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001388 struct flock lock;
1389 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001390 lock.l_start = RESERVED_BYTE;
1391 lock.l_len = 1;
1392 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001393 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1394 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1395 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001396 } else if( lock.l_type!=F_UNLCK ){
1397 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001398 }
1399 }
danielk197709480a92009-02-09 05:32:32 +00001400#endif
danielk197713adf8a2004-06-03 16:08:41 +00001401
drh6c7d5c52008-11-21 20:32:33 +00001402 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001403 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001404
aswift5b1a2562008-08-22 00:22:35 +00001405 *pResOut = reserved;
1406 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001407}
1408
1409/*
drha7e61d82011-03-12 17:02:57 +00001410** Attempt to set a system-lock on the file pFile. The lock is
1411** described by pLock.
1412**
drh77197112011-03-15 19:08:48 +00001413** If the pFile was opened read/write from unix-excl, then the only lock
1414** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001415** the first time any lock is attempted. All subsequent system locking
1416** operations become no-ops. Locking operations still happen internally,
1417** in order to coordinate access between separate database connections
1418** within this process, but all of that is handled in memory and the
1419** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001420**
1421** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1422** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1423** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001424**
1425** Zero is returned if the call completes successfully, or -1 if a call
1426** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001427*/
1428static int unixFileLock(unixFile *pFile, struct flock *pLock){
1429 int rc;
drh3cb93392011-03-12 18:10:44 +00001430 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001431 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001432 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001433 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1434 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1435 ){
drh3cb93392011-03-12 18:10:44 +00001436 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001437 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001438 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001439 lock.l_whence = SEEK_SET;
1440 lock.l_start = SHARED_FIRST;
1441 lock.l_len = SHARED_SIZE;
1442 lock.l_type = F_WRLCK;
1443 rc = osFcntl(pFile->h, F_SETLK, &lock);
1444 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001445 pInode->bProcessLock = 1;
1446 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001447 }else{
1448 rc = 0;
1449 }
1450 }else{
1451 rc = osFcntl(pFile->h, F_SETLK, pLock);
1452 }
1453 return rc;
1454}
1455
1456/*
drh308c2a52010-05-14 11:30:18 +00001457** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001458** of the following:
1459**
drh2ac3ee92004-06-07 16:27:46 +00001460** (1) SHARED_LOCK
1461** (2) RESERVED_LOCK
1462** (3) PENDING_LOCK
1463** (4) EXCLUSIVE_LOCK
1464**
drhb3e04342004-06-08 00:47:47 +00001465** Sometimes when requesting one lock state, additional lock states
1466** are inserted in between. The locking might fail on one of the later
1467** transitions leaving the lock state different from what it started but
1468** still short of its goal. The following chart shows the allowed
1469** transitions and the inserted intermediate states:
1470**
1471** UNLOCKED -> SHARED
1472** SHARED -> RESERVED
1473** SHARED -> (PENDING) -> EXCLUSIVE
1474** RESERVED -> (PENDING) -> EXCLUSIVE
1475** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001476**
drha6abd042004-06-09 17:37:22 +00001477** This routine will only increase a lock. Use the sqlite3OsUnlock()
1478** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001479*/
drh308c2a52010-05-14 11:30:18 +00001480static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001481 /* The following describes the implementation of the various locks and
1482 ** lock transitions in terms of the POSIX advisory shared and exclusive
1483 ** lock primitives (called read-locks and write-locks below, to avoid
1484 ** confusion with SQLite lock names). The algorithms are complicated
1485 ** slightly in order to be compatible with windows systems simultaneously
1486 ** accessing the same database file, in case that is ever required.
1487 **
1488 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1489 ** byte', each single bytes at well known offsets, and the 'shared byte
1490 ** range', a range of 510 bytes at a well known offset.
1491 **
1492 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1493 ** byte'. If this is successful, a random byte from the 'shared byte
1494 ** range' is read-locked and the lock on the 'pending byte' released.
1495 **
danielk197790ba3bd2004-06-25 08:32:25 +00001496 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1497 ** A RESERVED lock is implemented by grabbing a write-lock on the
1498 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001499 **
1500 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001501 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1502 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1503 ** obtained, but existing SHARED locks are allowed to persist. A process
1504 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1505 ** This property is used by the algorithm for rolling back a journal file
1506 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001507 **
danielk197790ba3bd2004-06-25 08:32:25 +00001508 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1509 ** implemented by obtaining a write-lock on the entire 'shared byte
1510 ** range'. Since all other locks require a read-lock on one of the bytes
1511 ** within this range, this ensures that no other locks are held on the
1512 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001513 **
1514 ** The reason a single byte cannot be used instead of the 'shared byte
1515 ** range' is that some versions of windows do not support read-locks. By
1516 ** locking a random byte from a range, concurrent SHARED locks may exist
1517 ** even if the locking primitive used is always a write-lock.
1518 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001519 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001520 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001521 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001522 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001523 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001524
drh054889e2005-11-30 03:20:31 +00001525 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001526 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1527 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001528 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001529
1530 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001531 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001532 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001533 */
drh308c2a52010-05-14 11:30:18 +00001534 if( pFile->eFileLock>=eFileLock ){
1535 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1536 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001537 return SQLITE_OK;
1538 }
1539
drh0c2694b2009-09-03 16:23:44 +00001540 /* Make sure the locking sequence is correct.
1541 ** (1) We never move from unlocked to anything higher than shared lock.
1542 ** (2) SQLite never explicitly requests a pendig lock.
1543 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001544 */
drh308c2a52010-05-14 11:30:18 +00001545 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1546 assert( eFileLock!=PENDING_LOCK );
1547 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001548
drh8af6c222010-05-14 12:43:01 +00001549 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001550 */
drh6c7d5c52008-11-21 20:32:33 +00001551 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001552 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001553
danielk1977ad94b582007-08-20 06:44:22 +00001554 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001555 ** handle that precludes the requested lock, return BUSY.
1556 */
drh8af6c222010-05-14 12:43:01 +00001557 if( (pFile->eFileLock!=pInode->eFileLock &&
1558 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001559 ){
1560 rc = SQLITE_BUSY;
1561 goto end_lock;
1562 }
1563
1564 /* If a SHARED lock is requested, and some thread using this PID already
1565 ** has a SHARED or RESERVED lock, then increment reference counts and
1566 ** return SQLITE_OK.
1567 */
drh308c2a52010-05-14 11:30:18 +00001568 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001569 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001570 assert( eFileLock==SHARED_LOCK );
1571 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001572 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001573 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001574 pInode->nShared++;
1575 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001576 goto end_lock;
1577 }
1578
danielk19779a1d0ab2004-06-01 14:09:28 +00001579
drh3cde3bb2004-06-12 02:17:14 +00001580 /* A PENDING lock is needed before acquiring a SHARED lock and before
1581 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1582 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001583 */
drh0c2694b2009-09-03 16:23:44 +00001584 lock.l_len = 1L;
1585 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001586 if( eFileLock==SHARED_LOCK
1587 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001588 ){
drh308c2a52010-05-14 11:30:18 +00001589 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001590 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001591 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001592 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001593 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001594 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001595 pFile->lastErrno = tErrno;
1596 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001597 goto end_lock;
1598 }
drh3cde3bb2004-06-12 02:17:14 +00001599 }
1600
1601
1602 /* If control gets to this point, then actually go ahead and make
1603 ** operating system calls for the specified lock.
1604 */
drh308c2a52010-05-14 11:30:18 +00001605 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001606 assert( pInode->nShared==0 );
1607 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001608 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001609
drh2ac3ee92004-06-07 16:27:46 +00001610 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001611 lock.l_start = SHARED_FIRST;
1612 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001613 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001614 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001615 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001616 }
dan661d71a2011-03-30 19:08:03 +00001617
drh2ac3ee92004-06-07 16:27:46 +00001618 /* Drop the temporary PENDING lock */
1619 lock.l_start = PENDING_BYTE;
1620 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001621 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001622 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1623 /* This could happen with a network mount */
1624 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001625 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001626 }
dan661d71a2011-03-30 19:08:03 +00001627
1628 if( rc ){
1629 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001630 pFile->lastErrno = tErrno;
1631 }
dan661d71a2011-03-30 19:08:03 +00001632 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001633 }else{
drh308c2a52010-05-14 11:30:18 +00001634 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001635 pInode->nLock++;
1636 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001637 }
drh8af6c222010-05-14 12:43:01 +00001638 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001639 /* We are trying for an exclusive lock but another thread in this
1640 ** same process is still holding a shared lock. */
1641 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001642 }else{
drh3cde3bb2004-06-12 02:17:14 +00001643 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001644 ** assumed that there is a SHARED or greater lock on the file
1645 ** already.
1646 */
drh308c2a52010-05-14 11:30:18 +00001647 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001648 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001649
1650 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1651 if( eFileLock==RESERVED_LOCK ){
1652 lock.l_start = RESERVED_BYTE;
1653 lock.l_len = 1L;
1654 }else{
1655 lock.l_start = SHARED_FIRST;
1656 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001657 }
dan661d71a2011-03-30 19:08:03 +00001658
1659 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001660 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001661 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001662 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001663 pFile->lastErrno = tErrno;
1664 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001665 }
drhbbd42a62004-05-22 17:41:58 +00001666 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001667
drh8f941bc2009-01-14 23:03:40 +00001668
drhd3d8c042012-05-29 17:02:40 +00001669#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001670 /* Set up the transaction-counter change checking flags when
1671 ** transitioning from a SHARED to a RESERVED lock. The change
1672 ** from SHARED to RESERVED marks the beginning of a normal
1673 ** write operation (not a hot journal rollback).
1674 */
1675 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001676 && pFile->eFileLock<=SHARED_LOCK
1677 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001678 ){
1679 pFile->transCntrChng = 0;
1680 pFile->dbUpdate = 0;
1681 pFile->inNormalWrite = 1;
1682 }
1683#endif
1684
1685
danielk1977ecb2a962004-06-02 06:30:16 +00001686 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001687 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001688 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001689 }else if( eFileLock==EXCLUSIVE_LOCK ){
1690 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001691 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001692 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001693
1694end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001695 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001696 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1697 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001698 return rc;
1699}
1700
1701/*
dan08da86a2009-08-21 17:18:03 +00001702** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001703** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001704*/
1705static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001706 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001707 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001708 p->pNext = pInode->pUnused;
1709 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001710 pFile->h = -1;
1711 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001712}
1713
1714/*
drh308c2a52010-05-14 11:30:18 +00001715** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001716** must be either NO_LOCK or SHARED_LOCK.
1717**
1718** If the locking level of the file descriptor is already at or below
1719** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001720**
1721** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1722** the byte range is divided into 2 parts and the first part is unlocked then
1723** set to a read lock, then the other part is simply unlocked. This works
1724** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1725** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001726*/
drha7e61d82011-03-12 17:02:57 +00001727static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001728 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001729 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001730 struct flock lock;
1731 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001732
drh054889e2005-11-30 03:20:31 +00001733 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001734 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001735 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001736 getpid()));
drha6abd042004-06-09 17:37:22 +00001737
drh308c2a52010-05-14 11:30:18 +00001738 assert( eFileLock<=SHARED_LOCK );
1739 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001740 return SQLITE_OK;
1741 }
drh6c7d5c52008-11-21 20:32:33 +00001742 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001743 pInode = pFile->pInode;
1744 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001745 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001746 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001747
drhd3d8c042012-05-29 17:02:40 +00001748#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001749 /* When reducing a lock such that other processes can start
1750 ** reading the database file again, make sure that the
1751 ** transaction counter was updated if any part of the database
1752 ** file changed. If the transaction counter is not updated,
1753 ** other connections to the same file might not realize that
1754 ** the file has changed and hence might not know to flush their
1755 ** cache. The use of a stale cache can lead to database corruption.
1756 */
drh8f941bc2009-01-14 23:03:40 +00001757 pFile->inNormalWrite = 0;
1758#endif
1759
drh7ed97b92010-01-20 13:07:21 +00001760 /* downgrading to a shared lock on NFS involves clearing the write lock
1761 ** before establishing the readlock - to avoid a race condition we downgrade
1762 ** the lock in 2 blocks, so that part of the range will be covered by a
1763 ** write lock until the rest is covered by a read lock:
1764 ** 1: [WWWWW]
1765 ** 2: [....W]
1766 ** 3: [RRRRW]
1767 ** 4: [RRRR.]
1768 */
drh308c2a52010-05-14 11:30:18 +00001769 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001770
1771#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001772 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001773 assert( handleNFSUnlock==0 );
1774#endif
1775#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001776 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001777 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001778 off_t divSize = SHARED_SIZE - 1;
1779
1780 lock.l_type = F_UNLCK;
1781 lock.l_whence = SEEK_SET;
1782 lock.l_start = SHARED_FIRST;
1783 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001784 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001785 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001786 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001787 if( IS_LOCK_ERROR(rc) ){
1788 pFile->lastErrno = tErrno;
1789 }
1790 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001791 }
drh7ed97b92010-01-20 13:07:21 +00001792 lock.l_type = F_RDLCK;
1793 lock.l_whence = SEEK_SET;
1794 lock.l_start = SHARED_FIRST;
1795 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001796 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001797 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001798 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1799 if( IS_LOCK_ERROR(rc) ){
1800 pFile->lastErrno = tErrno;
1801 }
1802 goto end_unlock;
1803 }
1804 lock.l_type = F_UNLCK;
1805 lock.l_whence = SEEK_SET;
1806 lock.l_start = SHARED_FIRST+divSize;
1807 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001808 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001809 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001810 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001811 if( IS_LOCK_ERROR(rc) ){
1812 pFile->lastErrno = tErrno;
1813 }
1814 goto end_unlock;
1815 }
drh30f776f2011-02-25 03:25:07 +00001816 }else
1817#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1818 {
drh7ed97b92010-01-20 13:07:21 +00001819 lock.l_type = F_RDLCK;
1820 lock.l_whence = SEEK_SET;
1821 lock.l_start = SHARED_FIRST;
1822 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001823 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001824 /* In theory, the call to unixFileLock() cannot fail because another
1825 ** process is holding an incompatible lock. If it does, this
1826 ** indicates that the other process is not following the locking
1827 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1828 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1829 ** an assert to fail). */
1830 rc = SQLITE_IOERR_RDLOCK;
1831 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001832 goto end_unlock;
1833 }
drh9c105bb2004-10-02 20:38:28 +00001834 }
1835 }
drhbbd42a62004-05-22 17:41:58 +00001836 lock.l_type = F_UNLCK;
1837 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001838 lock.l_start = PENDING_BYTE;
1839 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001840 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001841 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001842 }else{
danea83bc62011-04-01 11:56:32 +00001843 rc = SQLITE_IOERR_UNLOCK;
1844 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001845 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001846 }
drhbbd42a62004-05-22 17:41:58 +00001847 }
drh308c2a52010-05-14 11:30:18 +00001848 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001849 /* Decrement the shared lock counter. Release the lock using an
1850 ** OS call only when all threads in this same process have released
1851 ** the lock.
1852 */
drh8af6c222010-05-14 12:43:01 +00001853 pInode->nShared--;
1854 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001855 lock.l_type = F_UNLCK;
1856 lock.l_whence = SEEK_SET;
1857 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001858 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001859 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001860 }else{
danea83bc62011-04-01 11:56:32 +00001861 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001862 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001863 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001864 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001865 }
drha6abd042004-06-09 17:37:22 +00001866 }
1867
drhbbd42a62004-05-22 17:41:58 +00001868 /* Decrement the count of locks against this same file. When the
1869 ** count reaches zero, close any other file descriptors whose close
1870 ** was deferred because of outstanding locks.
1871 */
drh8af6c222010-05-14 12:43:01 +00001872 pInode->nLock--;
1873 assert( pInode->nLock>=0 );
1874 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001875 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001876 }
1877 }
drhf2f105d2012-08-20 15:53:54 +00001878
aswift5b1a2562008-08-22 00:22:35 +00001879end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001880 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001881 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001882 return rc;
drhbbd42a62004-05-22 17:41:58 +00001883}
1884
1885/*
drh308c2a52010-05-14 11:30:18 +00001886** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001887** must be either NO_LOCK or SHARED_LOCK.
1888**
1889** If the locking level of the file descriptor is already at or below
1890** the requested locking level, this routine is a no-op.
1891*/
drh308c2a52010-05-14 11:30:18 +00001892static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001893#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001894 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001895#endif
drha7e61d82011-03-12 17:02:57 +00001896 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001897}
1898
mistachkine98844f2013-08-24 00:59:24 +00001899#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001900static int unixMapfile(unixFile *pFd, i64 nByte);
1901static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001902#endif
danf23da962013-03-23 21:00:41 +00001903
drh7ed97b92010-01-20 13:07:21 +00001904/*
danielk1977e339d652008-06-28 11:23:00 +00001905** This function performs the parts of the "close file" operation
1906** common to all locking schemes. It closes the directory and file
1907** handles, if they are valid, and sets all fields of the unixFile
1908** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001909**
1910** It is *not* necessary to hold the mutex when this routine is called,
1911** even on VxWorks. A mutex will be acquired on VxWorks by the
1912** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001913*/
1914static int closeUnixFile(sqlite3_file *id){
1915 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001916#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001917 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001918#endif
dan661d71a2011-03-30 19:08:03 +00001919 if( pFile->h>=0 ){
1920 robust_close(pFile, pFile->h, __LINE__);
1921 pFile->h = -1;
1922 }
1923#if OS_VXWORKS
1924 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001925 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001926 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001927 }
1928 vxworksReleaseFileId(pFile->pId);
1929 pFile->pId = 0;
1930 }
1931#endif
1932 OSTRACE(("CLOSE %-3d\n", pFile->h));
1933 OpenCounter(-1);
1934 sqlite3_free(pFile->pUnused);
1935 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001936 return SQLITE_OK;
1937}
1938
1939/*
danielk1977e3026632004-06-22 11:29:02 +00001940** Close a file.
1941*/
danielk197762079062007-08-15 17:08:46 +00001942static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001943 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001944 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001945 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001946 unixUnlock(id, NO_LOCK);
1947 unixEnterMutex();
1948
1949 /* unixFile.pInode is always valid here. Otherwise, a different close
1950 ** routine (e.g. nolockClose()) would be called instead.
1951 */
1952 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1953 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1954 /* If there are outstanding locks, do not actually close the file just
1955 ** yet because that would clear those locks. Instead, add the file
1956 ** descriptor to pInode->pUnused list. It will be automatically closed
1957 ** when the last lock is cleared.
1958 */
1959 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001960 }
dan661d71a2011-03-30 19:08:03 +00001961 releaseInodeInfo(pFile);
1962 rc = closeUnixFile(id);
1963 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001964 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001965}
1966
drh734c9862008-11-28 15:37:20 +00001967/************** End of the posix advisory lock implementation *****************
1968******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001969
drh734c9862008-11-28 15:37:20 +00001970/******************************************************************************
1971****************************** No-op Locking **********************************
1972**
1973** Of the various locking implementations available, this is by far the
1974** simplest: locking is ignored. No attempt is made to lock the database
1975** file for reading or writing.
1976**
1977** This locking mode is appropriate for use on read-only databases
1978** (ex: databases that are burned into CD-ROM, for example.) It can
1979** also be used if the application employs some external mechanism to
1980** prevent simultaneous access of the same database by two or more
1981** database connections. But there is a serious risk of database
1982** corruption if this locking mode is used in situations where multiple
1983** database connections are accessing the same database file at the same
1984** time and one or more of those connections are writing.
1985*/
drhbfe66312006-10-03 17:40:40 +00001986
drh734c9862008-11-28 15:37:20 +00001987static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1988 UNUSED_PARAMETER(NotUsed);
1989 *pResOut = 0;
1990 return SQLITE_OK;
1991}
drh734c9862008-11-28 15:37:20 +00001992static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1993 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1994 return SQLITE_OK;
1995}
drh734c9862008-11-28 15:37:20 +00001996static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1997 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1998 return SQLITE_OK;
1999}
2000
2001/*
drh9b35ea62008-11-29 02:20:26 +00002002** Close the file.
drh734c9862008-11-28 15:37:20 +00002003*/
2004static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002005 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002006}
2007
2008/******************* End of the no-op lock implementation *********************
2009******************************************************************************/
2010
2011/******************************************************************************
2012************************* Begin dot-file Locking ******************************
2013**
mistachkin48864df2013-03-21 21:20:32 +00002014** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002015** files (really a directory) to control access to the database. This works
2016** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002017**
2018** (1) There is zero concurrency. A single reader blocks all other
2019** connections from reading or writing the database.
2020**
2021** (2) An application crash or power loss can leave stale lock files
2022** sitting around that need to be cleared manually.
2023**
2024** Nevertheless, a dotlock is an appropriate locking mode for use if no
2025** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002026**
drh9ef6bc42011-11-04 02:24:02 +00002027** Dotfile locking works by creating a subdirectory in the same directory as
2028** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002029** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002030** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002031*/
2032
2033/*
2034** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002035** lock directory.
drh734c9862008-11-28 15:37:20 +00002036*/
2037#define DOTLOCK_SUFFIX ".lock"
2038
drh7708e972008-11-29 00:56:52 +00002039/*
2040** This routine checks if there is a RESERVED lock held on the specified
2041** file by this or any other process. If such a lock is held, set *pResOut
2042** to a non-zero value otherwise *pResOut is set to zero. The return value
2043** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2044**
2045** In dotfile locking, either a lock exists or it does not. So in this
2046** variation of CheckReservedLock(), *pResOut is set to true if any lock
2047** is held on the file and false if the file is unlocked.
2048*/
drh734c9862008-11-28 15:37:20 +00002049static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2050 int rc = SQLITE_OK;
2051 int reserved = 0;
2052 unixFile *pFile = (unixFile*)id;
2053
2054 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2055
2056 assert( pFile );
2057
2058 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002059 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002060 /* Either this connection or some other connection in the same process
2061 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002062 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002063 }else{
2064 /* The lock is held if and only if the lockfile exists */
2065 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002066 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002067 }
drh308c2a52010-05-14 11:30:18 +00002068 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002069 *pResOut = reserved;
2070 return rc;
2071}
2072
drh7708e972008-11-29 00:56:52 +00002073/*
drh308c2a52010-05-14 11:30:18 +00002074** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002075** of the following:
2076**
2077** (1) SHARED_LOCK
2078** (2) RESERVED_LOCK
2079** (3) PENDING_LOCK
2080** (4) EXCLUSIVE_LOCK
2081**
2082** Sometimes when requesting one lock state, additional lock states
2083** are inserted in between. The locking might fail on one of the later
2084** transitions leaving the lock state different from what it started but
2085** still short of its goal. The following chart shows the allowed
2086** transitions and the inserted intermediate states:
2087**
2088** UNLOCKED -> SHARED
2089** SHARED -> RESERVED
2090** SHARED -> (PENDING) -> EXCLUSIVE
2091** RESERVED -> (PENDING) -> EXCLUSIVE
2092** PENDING -> EXCLUSIVE
2093**
2094** This routine will only increase a lock. Use the sqlite3OsUnlock()
2095** routine to lower a locking level.
2096**
2097** With dotfile locking, we really only support state (4): EXCLUSIVE.
2098** But we track the other locking levels internally.
2099*/
drh308c2a52010-05-14 11:30:18 +00002100static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002101 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002102 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002103 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002104
drh7708e972008-11-29 00:56:52 +00002105
2106 /* If we have any lock, then the lock file already exists. All we have
2107 ** to do is adjust our internal record of the lock level.
2108 */
drh308c2a52010-05-14 11:30:18 +00002109 if( pFile->eFileLock > NO_LOCK ){
2110 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002111 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002112#ifdef HAVE_UTIME
2113 utime(zLockFile, NULL);
2114#else
drh734c9862008-11-28 15:37:20 +00002115 utimes(zLockFile, NULL);
2116#endif
drh7708e972008-11-29 00:56:52 +00002117 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002118 }
2119
2120 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002121 rc = osMkdir(zLockFile, 0777);
2122 if( rc<0 ){
2123 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002124 int tErrno = errno;
2125 if( EEXIST == tErrno ){
2126 rc = SQLITE_BUSY;
2127 } else {
2128 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2129 if( IS_LOCK_ERROR(rc) ){
2130 pFile->lastErrno = tErrno;
2131 }
2132 }
drh7708e972008-11-29 00:56:52 +00002133 return rc;
drh734c9862008-11-28 15:37:20 +00002134 }
drh734c9862008-11-28 15:37:20 +00002135
2136 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002137 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002138 return rc;
2139}
2140
drh7708e972008-11-29 00:56:52 +00002141/*
drh308c2a52010-05-14 11:30:18 +00002142** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002143** must be either NO_LOCK or SHARED_LOCK.
2144**
2145** If the locking level of the file descriptor is already at or below
2146** the requested locking level, this routine is a no-op.
2147**
2148** When the locking level reaches NO_LOCK, delete the lock file.
2149*/
drh308c2a52010-05-14 11:30:18 +00002150static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002151 unixFile *pFile = (unixFile*)id;
2152 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002153 int rc;
drh734c9862008-11-28 15:37:20 +00002154
2155 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002156 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002157 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002158 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002159
2160 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002161 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002162 return SQLITE_OK;
2163 }
drh7708e972008-11-29 00:56:52 +00002164
2165 /* To downgrade to shared, simply update our internal notion of the
2166 ** lock state. No need to mess with the file on disk.
2167 */
drh308c2a52010-05-14 11:30:18 +00002168 if( eFileLock==SHARED_LOCK ){
2169 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002170 return SQLITE_OK;
2171 }
2172
drh7708e972008-11-29 00:56:52 +00002173 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002174 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002175 rc = osRmdir(zLockFile);
2176 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2177 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002178 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002179 rc = 0;
drh734c9862008-11-28 15:37:20 +00002180 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002181 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002182 }
2183 if( IS_LOCK_ERROR(rc) ){
2184 pFile->lastErrno = tErrno;
2185 }
2186 return rc;
2187 }
drh308c2a52010-05-14 11:30:18 +00002188 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002189 return SQLITE_OK;
2190}
2191
2192/*
drh9b35ea62008-11-29 02:20:26 +00002193** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002194*/
2195static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002196 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002197 if( id ){
2198 unixFile *pFile = (unixFile*)id;
2199 dotlockUnlock(id, NO_LOCK);
2200 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002201 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002202 }
drh734c9862008-11-28 15:37:20 +00002203 return rc;
2204}
2205/****************** End of the dot-file lock implementation *******************
2206******************************************************************************/
2207
2208/******************************************************************************
2209************************** Begin flock Locking ********************************
2210**
2211** Use the flock() system call to do file locking.
2212**
drh6b9d6dd2008-12-03 19:34:47 +00002213** flock() locking is like dot-file locking in that the various
2214** fine-grain locking levels supported by SQLite are collapsed into
2215** a single exclusive lock. In other words, SHARED, RESERVED, and
2216** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2217** still works when you do this, but concurrency is reduced since
2218** only a single process can be reading the database at a time.
2219**
drh734c9862008-11-28 15:37:20 +00002220** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2221** compiling for VXWORKS.
2222*/
2223#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002224
drh6b9d6dd2008-12-03 19:34:47 +00002225/*
drhff812312011-02-23 13:33:46 +00002226** Retry flock() calls that fail with EINTR
2227*/
2228#ifdef EINTR
2229static int robust_flock(int fd, int op){
2230 int rc;
2231 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2232 return rc;
2233}
2234#else
drh5c819272011-02-23 14:00:12 +00002235# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002236#endif
2237
2238
2239/*
drh6b9d6dd2008-12-03 19:34:47 +00002240** This routine checks if there is a RESERVED lock held on the specified
2241** file by this or any other process. If such a lock is held, set *pResOut
2242** to a non-zero value otherwise *pResOut is set to zero. The return value
2243** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2244*/
drh734c9862008-11-28 15:37:20 +00002245static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2246 int rc = SQLITE_OK;
2247 int reserved = 0;
2248 unixFile *pFile = (unixFile*)id;
2249
2250 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2251
2252 assert( pFile );
2253
2254 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002255 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002256 reserved = 1;
2257 }
2258
2259 /* Otherwise see if some other process holds it. */
2260 if( !reserved ){
2261 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002262 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002263 if( !lrc ){
2264 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002265 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002266 if ( lrc ) {
2267 int tErrno = errno;
2268 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002269 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002270 if( IS_LOCK_ERROR(lrc) ){
2271 pFile->lastErrno = tErrno;
2272 rc = lrc;
2273 }
2274 }
2275 } else {
2276 int tErrno = errno;
2277 reserved = 1;
2278 /* someone else might have it reserved */
2279 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2280 if( IS_LOCK_ERROR(lrc) ){
2281 pFile->lastErrno = tErrno;
2282 rc = lrc;
2283 }
2284 }
2285 }
drh308c2a52010-05-14 11:30:18 +00002286 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002287
2288#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2289 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2290 rc = SQLITE_OK;
2291 reserved=1;
2292 }
2293#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2294 *pResOut = reserved;
2295 return rc;
2296}
2297
drh6b9d6dd2008-12-03 19:34:47 +00002298/*
drh308c2a52010-05-14 11:30:18 +00002299** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002300** of the following:
2301**
2302** (1) SHARED_LOCK
2303** (2) RESERVED_LOCK
2304** (3) PENDING_LOCK
2305** (4) EXCLUSIVE_LOCK
2306**
2307** Sometimes when requesting one lock state, additional lock states
2308** are inserted in between. The locking might fail on one of the later
2309** transitions leaving the lock state different from what it started but
2310** still short of its goal. The following chart shows the allowed
2311** transitions and the inserted intermediate states:
2312**
2313** UNLOCKED -> SHARED
2314** SHARED -> RESERVED
2315** SHARED -> (PENDING) -> EXCLUSIVE
2316** RESERVED -> (PENDING) -> EXCLUSIVE
2317** PENDING -> EXCLUSIVE
2318**
2319** flock() only really support EXCLUSIVE locks. We track intermediate
2320** lock states in the sqlite3_file structure, but all locks SHARED or
2321** above are really EXCLUSIVE locks and exclude all other processes from
2322** access the file.
2323**
2324** This routine will only increase a lock. Use the sqlite3OsUnlock()
2325** routine to lower a locking level.
2326*/
drh308c2a52010-05-14 11:30:18 +00002327static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002328 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002329 unixFile *pFile = (unixFile*)id;
2330
2331 assert( pFile );
2332
2333 /* if we already have a lock, it is exclusive.
2334 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002335 if (pFile->eFileLock > NO_LOCK) {
2336 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002337 return SQLITE_OK;
2338 }
2339
2340 /* grab an exclusive lock */
2341
drhff812312011-02-23 13:33:46 +00002342 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002343 int tErrno = errno;
2344 /* didn't get, must be busy */
2345 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2346 if( IS_LOCK_ERROR(rc) ){
2347 pFile->lastErrno = tErrno;
2348 }
2349 } else {
2350 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002351 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002352 }
drh308c2a52010-05-14 11:30:18 +00002353 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2354 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002355#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2356 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2357 rc = SQLITE_BUSY;
2358 }
2359#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2360 return rc;
2361}
2362
drh6b9d6dd2008-12-03 19:34:47 +00002363
2364/*
drh308c2a52010-05-14 11:30:18 +00002365** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002366** must be either NO_LOCK or SHARED_LOCK.
2367**
2368** If the locking level of the file descriptor is already at or below
2369** the requested locking level, this routine is a no-op.
2370*/
drh308c2a52010-05-14 11:30:18 +00002371static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002372 unixFile *pFile = (unixFile*)id;
2373
2374 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002375 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2376 pFile->eFileLock, getpid()));
2377 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002378
2379 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002380 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002381 return SQLITE_OK;
2382 }
2383
2384 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002385 if (eFileLock==SHARED_LOCK) {
2386 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002387 return SQLITE_OK;
2388 }
2389
2390 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002391 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002392#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002393 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002394#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002395 return SQLITE_IOERR_UNLOCK;
2396 }else{
drh308c2a52010-05-14 11:30:18 +00002397 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002398 return SQLITE_OK;
2399 }
2400}
2401
2402/*
2403** Close a file.
2404*/
2405static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002406 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002407 if( id ){
2408 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002409 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002410 }
drh5a05be12012-10-09 18:51:44 +00002411 return rc;
drh734c9862008-11-28 15:37:20 +00002412}
2413
2414#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2415
2416/******************* End of the flock lock implementation *********************
2417******************************************************************************/
2418
2419/******************************************************************************
2420************************ Begin Named Semaphore Locking ************************
2421**
2422** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002423**
2424** Semaphore locking is like dot-lock and flock in that it really only
2425** supports EXCLUSIVE locking. Only a single process can read or write
2426** the database file at a time. This reduces potential concurrency, but
2427** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002428*/
2429#if OS_VXWORKS
2430
drh6b9d6dd2008-12-03 19:34:47 +00002431/*
2432** This routine checks if there is a RESERVED lock held on the specified
2433** file by this or any other process. If such a lock is held, set *pResOut
2434** to a non-zero value otherwise *pResOut is set to zero. The return value
2435** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2436*/
drh734c9862008-11-28 15:37:20 +00002437static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2438 int rc = SQLITE_OK;
2439 int reserved = 0;
2440 unixFile *pFile = (unixFile*)id;
2441
2442 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2443
2444 assert( pFile );
2445
2446 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002447 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002448 reserved = 1;
2449 }
2450
2451 /* Otherwise see if some other process holds it. */
2452 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002453 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002454 struct stat statBuf;
2455
2456 if( sem_trywait(pSem)==-1 ){
2457 int tErrno = errno;
2458 if( EAGAIN != tErrno ){
2459 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2460 pFile->lastErrno = tErrno;
2461 } else {
2462 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002463 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002464 }
2465 }else{
2466 /* we could have it if we want it */
2467 sem_post(pSem);
2468 }
2469 }
drh308c2a52010-05-14 11:30:18 +00002470 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002471
2472 *pResOut = reserved;
2473 return rc;
2474}
2475
drh6b9d6dd2008-12-03 19:34:47 +00002476/*
drh308c2a52010-05-14 11:30:18 +00002477** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002478** of the following:
2479**
2480** (1) SHARED_LOCK
2481** (2) RESERVED_LOCK
2482** (3) PENDING_LOCK
2483** (4) EXCLUSIVE_LOCK
2484**
2485** Sometimes when requesting one lock state, additional lock states
2486** are inserted in between. The locking might fail on one of the later
2487** transitions leaving the lock state different from what it started but
2488** still short of its goal. The following chart shows the allowed
2489** transitions and the inserted intermediate states:
2490**
2491** UNLOCKED -> SHARED
2492** SHARED -> RESERVED
2493** SHARED -> (PENDING) -> EXCLUSIVE
2494** RESERVED -> (PENDING) -> EXCLUSIVE
2495** PENDING -> EXCLUSIVE
2496**
2497** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2498** lock states in the sqlite3_file structure, but all locks SHARED or
2499** above are really EXCLUSIVE locks and exclude all other processes from
2500** access the file.
2501**
2502** This routine will only increase a lock. Use the sqlite3OsUnlock()
2503** routine to lower a locking level.
2504*/
drh308c2a52010-05-14 11:30:18 +00002505static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002506 unixFile *pFile = (unixFile*)id;
2507 int fd;
drh8af6c222010-05-14 12:43:01 +00002508 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002509 int rc = SQLITE_OK;
2510
2511 /* if we already have a lock, it is exclusive.
2512 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002513 if (pFile->eFileLock > NO_LOCK) {
2514 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002515 rc = SQLITE_OK;
2516 goto sem_end_lock;
2517 }
2518
2519 /* lock semaphore now but bail out when already locked. */
2520 if( sem_trywait(pSem)==-1 ){
2521 rc = SQLITE_BUSY;
2522 goto sem_end_lock;
2523 }
2524
2525 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002526 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002527
2528 sem_end_lock:
2529 return rc;
2530}
2531
drh6b9d6dd2008-12-03 19:34:47 +00002532/*
drh308c2a52010-05-14 11:30:18 +00002533** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002534** must be either NO_LOCK or SHARED_LOCK.
2535**
2536** If the locking level of the file descriptor is already at or below
2537** the requested locking level, this routine is a no-op.
2538*/
drh308c2a52010-05-14 11:30:18 +00002539static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002540 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002541 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002542
2543 assert( pFile );
2544 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002545 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002546 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002547 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002548
2549 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002550 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002551 return SQLITE_OK;
2552 }
2553
2554 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002555 if (eFileLock==SHARED_LOCK) {
2556 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002557 return SQLITE_OK;
2558 }
2559
2560 /* no, really unlock. */
2561 if ( sem_post(pSem)==-1 ) {
2562 int rc, tErrno = errno;
2563 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2564 if( IS_LOCK_ERROR(rc) ){
2565 pFile->lastErrno = tErrno;
2566 }
2567 return rc;
2568 }
drh308c2a52010-05-14 11:30:18 +00002569 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002570 return SQLITE_OK;
2571}
2572
2573/*
2574 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002575 */
drh734c9862008-11-28 15:37:20 +00002576static int semClose(sqlite3_file *id) {
2577 if( id ){
2578 unixFile *pFile = (unixFile*)id;
2579 semUnlock(id, NO_LOCK);
2580 assert( pFile );
2581 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002582 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002583 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002584 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002585 }
2586 return SQLITE_OK;
2587}
2588
2589#endif /* OS_VXWORKS */
2590/*
2591** Named semaphore locking is only available on VxWorks.
2592**
2593*************** End of the named semaphore lock implementation ****************
2594******************************************************************************/
2595
2596
2597/******************************************************************************
2598*************************** Begin AFP Locking *********************************
2599**
2600** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2601** on Apple Macintosh computers - both OS9 and OSX.
2602**
2603** Third-party implementations of AFP are available. But this code here
2604** only works on OSX.
2605*/
2606
drhd2cb50b2009-01-09 21:41:17 +00002607#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002608/*
2609** The afpLockingContext structure contains all afp lock specific state
2610*/
drhbfe66312006-10-03 17:40:40 +00002611typedef struct afpLockingContext afpLockingContext;
2612struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002613 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002614 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002615};
2616
2617struct ByteRangeLockPB2
2618{
2619 unsigned long long offset; /* offset to first byte to lock */
2620 unsigned long long length; /* nbr of bytes to lock */
2621 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2622 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2623 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2624 int fd; /* file desc to assoc this lock with */
2625};
2626
drhfd131da2007-08-07 17:13:03 +00002627#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002628
drh6b9d6dd2008-12-03 19:34:47 +00002629/*
2630** This is a utility for setting or clearing a bit-range lock on an
2631** AFP filesystem.
2632**
2633** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2634*/
2635static int afpSetLock(
2636 const char *path, /* Name of the file to be locked or unlocked */
2637 unixFile *pFile, /* Open file descriptor on path */
2638 unsigned long long offset, /* First byte to be locked */
2639 unsigned long long length, /* Number of bytes to lock */
2640 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002641){
drh6b9d6dd2008-12-03 19:34:47 +00002642 struct ByteRangeLockPB2 pb;
2643 int err;
drhbfe66312006-10-03 17:40:40 +00002644
2645 pb.unLockFlag = setLockFlag ? 0 : 1;
2646 pb.startEndFlag = 0;
2647 pb.offset = offset;
2648 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002649 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002650
drh308c2a52010-05-14 11:30:18 +00002651 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002652 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002653 offset, length));
drhbfe66312006-10-03 17:40:40 +00002654 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2655 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002656 int rc;
2657 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002658 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2659 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002660#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2661 rc = SQLITE_BUSY;
2662#else
drh734c9862008-11-28 15:37:20 +00002663 rc = sqliteErrorFromPosixError(tErrno,
2664 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002665#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002666 if( IS_LOCK_ERROR(rc) ){
2667 pFile->lastErrno = tErrno;
2668 }
2669 return rc;
drhbfe66312006-10-03 17:40:40 +00002670 } else {
aswift5b1a2562008-08-22 00:22:35 +00002671 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002672 }
2673}
2674
drh6b9d6dd2008-12-03 19:34:47 +00002675/*
2676** This routine checks if there is a RESERVED lock held on the specified
2677** file by this or any other process. If such a lock is held, set *pResOut
2678** to a non-zero value otherwise *pResOut is set to zero. The return value
2679** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2680*/
danielk1977e339d652008-06-28 11:23:00 +00002681static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002682 int rc = SQLITE_OK;
2683 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002684 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002685 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002686
aswift5b1a2562008-08-22 00:22:35 +00002687 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2688
2689 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002690 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002691 if( context->reserved ){
2692 *pResOut = 1;
2693 return SQLITE_OK;
2694 }
drh8af6c222010-05-14 12:43:01 +00002695 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002696
2697 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002698 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002699 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002700 }
2701
2702 /* Otherwise see if some other process holds it.
2703 */
aswift5b1a2562008-08-22 00:22:35 +00002704 if( !reserved ){
2705 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002706 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002707 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002708 /* if we succeeded in taking the reserved lock, unlock it to restore
2709 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002710 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002711 } else {
2712 /* if we failed to get the lock then someone else must have it */
2713 reserved = 1;
2714 }
2715 if( IS_LOCK_ERROR(lrc) ){
2716 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002717 }
2718 }
drhbfe66312006-10-03 17:40:40 +00002719
drh7ed97b92010-01-20 13:07:21 +00002720 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002721 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002722
2723 *pResOut = reserved;
2724 return rc;
drhbfe66312006-10-03 17:40:40 +00002725}
2726
drh6b9d6dd2008-12-03 19:34:47 +00002727/*
drh308c2a52010-05-14 11:30:18 +00002728** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002729** of the following:
2730**
2731** (1) SHARED_LOCK
2732** (2) RESERVED_LOCK
2733** (3) PENDING_LOCK
2734** (4) EXCLUSIVE_LOCK
2735**
2736** Sometimes when requesting one lock state, additional lock states
2737** are inserted in between. The locking might fail on one of the later
2738** transitions leaving the lock state different from what it started but
2739** still short of its goal. The following chart shows the allowed
2740** transitions and the inserted intermediate states:
2741**
2742** UNLOCKED -> SHARED
2743** SHARED -> RESERVED
2744** SHARED -> (PENDING) -> EXCLUSIVE
2745** RESERVED -> (PENDING) -> EXCLUSIVE
2746** PENDING -> EXCLUSIVE
2747**
2748** This routine will only increase a lock. Use the sqlite3OsUnlock()
2749** routine to lower a locking level.
2750*/
drh308c2a52010-05-14 11:30:18 +00002751static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002752 int rc = SQLITE_OK;
2753 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002754 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002755 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002756
2757 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002758 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2759 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002760 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002761
drhbfe66312006-10-03 17:40:40 +00002762 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002763 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002764 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002765 */
drh308c2a52010-05-14 11:30:18 +00002766 if( pFile->eFileLock>=eFileLock ){
2767 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2768 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002769 return SQLITE_OK;
2770 }
2771
2772 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002773 ** (1) We never move from unlocked to anything higher than shared lock.
2774 ** (2) SQLite never explicitly requests a pendig lock.
2775 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002776 */
drh308c2a52010-05-14 11:30:18 +00002777 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2778 assert( eFileLock!=PENDING_LOCK );
2779 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002780
drh8af6c222010-05-14 12:43:01 +00002781 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002782 */
drh6c7d5c52008-11-21 20:32:33 +00002783 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002784 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002785
2786 /* If some thread using this PID has a lock via a different unixFile*
2787 ** handle that precludes the requested lock, return BUSY.
2788 */
drh8af6c222010-05-14 12:43:01 +00002789 if( (pFile->eFileLock!=pInode->eFileLock &&
2790 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002791 ){
2792 rc = SQLITE_BUSY;
2793 goto afp_end_lock;
2794 }
2795
2796 /* If a SHARED lock is requested, and some thread using this PID already
2797 ** has a SHARED or RESERVED lock, then increment reference counts and
2798 ** return SQLITE_OK.
2799 */
drh308c2a52010-05-14 11:30:18 +00002800 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002801 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002802 assert( eFileLock==SHARED_LOCK );
2803 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002804 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002805 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002806 pInode->nShared++;
2807 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002808 goto afp_end_lock;
2809 }
drhbfe66312006-10-03 17:40:40 +00002810
2811 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002812 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2813 ** be released.
2814 */
drh308c2a52010-05-14 11:30:18 +00002815 if( eFileLock==SHARED_LOCK
2816 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002817 ){
2818 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002819 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002820 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002821 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002822 goto afp_end_lock;
2823 }
2824 }
2825
2826 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002827 ** operating system calls for the specified lock.
2828 */
drh308c2a52010-05-14 11:30:18 +00002829 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002830 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002831 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002832
drh8af6c222010-05-14 12:43:01 +00002833 assert( pInode->nShared==0 );
2834 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002835
2836 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002837 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002838 /* note that the quality of the randomness doesn't matter that much */
2839 lk = random();
drh8af6c222010-05-14 12:43:01 +00002840 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002841 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002842 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002843 if( IS_LOCK_ERROR(lrc1) ){
2844 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002845 }
aswift5b1a2562008-08-22 00:22:35 +00002846 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002847 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002848
aswift5b1a2562008-08-22 00:22:35 +00002849 if( IS_LOCK_ERROR(lrc1) ) {
2850 pFile->lastErrno = lrc1Errno;
2851 rc = lrc1;
2852 goto afp_end_lock;
2853 } else if( IS_LOCK_ERROR(lrc2) ){
2854 rc = lrc2;
2855 goto afp_end_lock;
2856 } else if( lrc1 != SQLITE_OK ) {
2857 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002858 } else {
drh308c2a52010-05-14 11:30:18 +00002859 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002860 pInode->nLock++;
2861 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002862 }
drh8af6c222010-05-14 12:43:01 +00002863 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002864 /* We are trying for an exclusive lock but another thread in this
2865 ** same process is still holding a shared lock. */
2866 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002867 }else{
2868 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2869 ** assumed that there is a SHARED or greater lock on the file
2870 ** already.
2871 */
2872 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002873 assert( 0!=pFile->eFileLock );
2874 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002875 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002876 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002877 if( !failed ){
2878 context->reserved = 1;
2879 }
drhbfe66312006-10-03 17:40:40 +00002880 }
drh308c2a52010-05-14 11:30:18 +00002881 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002882 /* Acquire an EXCLUSIVE lock */
2883
2884 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002885 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002886 */
drh6b9d6dd2008-12-03 19:34:47 +00002887 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002888 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002889 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002890 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002891 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002892 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002893 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002894 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002895 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2896 ** a critical I/O error
2897 */
2898 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2899 SQLITE_IOERR_LOCK;
2900 goto afp_end_lock;
2901 }
2902 }else{
aswift5b1a2562008-08-22 00:22:35 +00002903 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002904 }
2905 }
aswift5b1a2562008-08-22 00:22:35 +00002906 if( failed ){
2907 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002908 }
2909 }
2910
2911 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002912 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002913 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002914 }else if( eFileLock==EXCLUSIVE_LOCK ){
2915 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002916 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002917 }
2918
2919afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002920 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002921 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2922 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002923 return rc;
2924}
2925
2926/*
drh308c2a52010-05-14 11:30:18 +00002927** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002928** must be either NO_LOCK or SHARED_LOCK.
2929**
2930** If the locking level of the file descriptor is already at or below
2931** the requested locking level, this routine is a no-op.
2932*/
drh308c2a52010-05-14 11:30:18 +00002933static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002934 int rc = SQLITE_OK;
2935 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002936 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002937 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2938 int skipShared = 0;
2939#ifdef SQLITE_TEST
2940 int h = pFile->h;
2941#endif
drhbfe66312006-10-03 17:40:40 +00002942
2943 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002944 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002945 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002946 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002947
drh308c2a52010-05-14 11:30:18 +00002948 assert( eFileLock<=SHARED_LOCK );
2949 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002950 return SQLITE_OK;
2951 }
drh6c7d5c52008-11-21 20:32:33 +00002952 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002953 pInode = pFile->pInode;
2954 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002955 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002956 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002957 SimulateIOErrorBenign(1);
2958 SimulateIOError( h=(-1) )
2959 SimulateIOErrorBenign(0);
2960
drhd3d8c042012-05-29 17:02:40 +00002961#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002962 /* When reducing a lock such that other processes can start
2963 ** reading the database file again, make sure that the
2964 ** transaction counter was updated if any part of the database
2965 ** file changed. If the transaction counter is not updated,
2966 ** other connections to the same file might not realize that
2967 ** the file has changed and hence might not know to flush their
2968 ** cache. The use of a stale cache can lead to database corruption.
2969 */
2970 assert( pFile->inNormalWrite==0
2971 || pFile->dbUpdate==0
2972 || pFile->transCntrChng==1 );
2973 pFile->inNormalWrite = 0;
2974#endif
aswiftaebf4132008-11-21 00:10:35 +00002975
drh308c2a52010-05-14 11:30:18 +00002976 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002977 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002978 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002979 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002980 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002981 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2982 } else {
2983 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002984 }
2985 }
drh308c2a52010-05-14 11:30:18 +00002986 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002987 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002988 }
drh308c2a52010-05-14 11:30:18 +00002989 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002990 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2991 if( !rc ){
2992 context->reserved = 0;
2993 }
aswiftaebf4132008-11-21 00:10:35 +00002994 }
drh8af6c222010-05-14 12:43:01 +00002995 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2996 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002997 }
aswiftaebf4132008-11-21 00:10:35 +00002998 }
drh308c2a52010-05-14 11:30:18 +00002999 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003000
drh7ed97b92010-01-20 13:07:21 +00003001 /* Decrement the shared lock counter. Release the lock using an
3002 ** OS call only when all threads in this same process have released
3003 ** the lock.
3004 */
drh8af6c222010-05-14 12:43:01 +00003005 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3006 pInode->nShared--;
3007 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003008 SimulateIOErrorBenign(1);
3009 SimulateIOError( h=(-1) )
3010 SimulateIOErrorBenign(0);
3011 if( !skipShared ){
3012 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3013 }
3014 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003015 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003016 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003017 }
3018 }
3019 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003020 pInode->nLock--;
3021 assert( pInode->nLock>=0 );
3022 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003023 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003024 }
3025 }
drhbfe66312006-10-03 17:40:40 +00003026 }
drh7ed97b92010-01-20 13:07:21 +00003027
drh6c7d5c52008-11-21 20:32:33 +00003028 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003029 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003030 return rc;
3031}
3032
3033/*
drh339eb0b2008-03-07 15:34:11 +00003034** Close a file & cleanup AFP specific locking context
3035*/
danielk1977e339d652008-06-28 11:23:00 +00003036static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003037 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003038 if( id ){
3039 unixFile *pFile = (unixFile*)id;
3040 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003041 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003042 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003043 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003044 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003045 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003046 ** the last lock is cleared.
3047 */
dan08da86a2009-08-21 17:18:03 +00003048 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003049 }
danb0ac3e32010-06-16 10:55:42 +00003050 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003051 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003052 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003053 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003054 }
drh7ed97b92010-01-20 13:07:21 +00003055 return rc;
drhbfe66312006-10-03 17:40:40 +00003056}
3057
drhd2cb50b2009-01-09 21:41:17 +00003058#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003059/*
3060** The code above is the AFP lock implementation. The code is specific
3061** to MacOSX and does not work on other unix platforms. No alternative
3062** is available. If you don't compile for a mac, then the "unix-afp"
3063** VFS is not available.
3064**
3065********************* End of the AFP lock implementation **********************
3066******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003067
drh7ed97b92010-01-20 13:07:21 +00003068/******************************************************************************
3069*************************** Begin NFS Locking ********************************/
3070
3071#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3072/*
drh308c2a52010-05-14 11:30:18 +00003073 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003074 ** must be either NO_LOCK or SHARED_LOCK.
3075 **
3076 ** If the locking level of the file descriptor is already at or below
3077 ** the requested locking level, this routine is a no-op.
3078 */
drh308c2a52010-05-14 11:30:18 +00003079static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003080 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003081}
3082
3083#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3084/*
3085** The code above is the NFS lock implementation. The code is specific
3086** to MacOSX and does not work on other unix platforms. No alternative
3087** is available.
3088**
3089********************* End of the NFS lock implementation **********************
3090******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003091
3092/******************************************************************************
3093**************** Non-locking sqlite3_file methods *****************************
3094**
3095** The next division contains implementations for all methods of the
3096** sqlite3_file object other than the locking methods. The locking
3097** methods were defined in divisions above (one locking method per
3098** division). Those methods that are common to all locking modes
3099** are gather together into this division.
3100*/
drhbfe66312006-10-03 17:40:40 +00003101
3102/*
drh734c9862008-11-28 15:37:20 +00003103** Seek to the offset passed as the second argument, then read cnt
3104** bytes into pBuf. Return the number of bytes actually read.
3105**
3106** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3107** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3108** one system to another. Since SQLite does not define USE_PREAD
3109** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3110** See tickets #2741 and #2681.
3111**
3112** To avoid stomping the errno value on a failed read the lastErrno value
3113** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003114*/
drh734c9862008-11-28 15:37:20 +00003115static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3116 int got;
drh58024642011-11-07 18:16:00 +00003117 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003118#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003119 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003120#endif
drh734c9862008-11-28 15:37:20 +00003121 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003122 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003123 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003124 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003125 do{
drh734c9862008-11-28 15:37:20 +00003126#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003127 got = osPread(id->h, pBuf, cnt, offset);
3128 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003129#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003130 got = osPread64(id->h, pBuf, cnt, offset);
3131 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003132#else
drh58024642011-11-07 18:16:00 +00003133 newOffset = lseek(id->h, offset, SEEK_SET);
3134 SimulateIOError( newOffset-- );
3135 if( newOffset!=offset ){
3136 if( newOffset == -1 ){
3137 ((unixFile*)id)->lastErrno = errno;
3138 }else{
drhf2f105d2012-08-20 15:53:54 +00003139 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003140 }
3141 return -1;
drh734c9862008-11-28 15:37:20 +00003142 }
drh58024642011-11-07 18:16:00 +00003143 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003144#endif
drh58024642011-11-07 18:16:00 +00003145 if( got==cnt ) break;
3146 if( got<0 ){
3147 if( errno==EINTR ){ got = 1; continue; }
3148 prior = 0;
3149 ((unixFile*)id)->lastErrno = errno;
3150 break;
3151 }else if( got>0 ){
3152 cnt -= got;
3153 offset += got;
3154 prior += got;
3155 pBuf = (void*)(got + (char*)pBuf);
3156 }
3157 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003158 TIMER_END;
drh58024642011-11-07 18:16:00 +00003159 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3160 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3161 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003162}
3163
3164/*
drh734c9862008-11-28 15:37:20 +00003165** Read data from a file into a buffer. Return SQLITE_OK if all
3166** bytes were read successfully and SQLITE_IOERR if anything goes
3167** wrong.
drh339eb0b2008-03-07 15:34:11 +00003168*/
drh734c9862008-11-28 15:37:20 +00003169static int unixRead(
3170 sqlite3_file *id,
3171 void *pBuf,
3172 int amt,
3173 sqlite3_int64 offset
3174){
dan08da86a2009-08-21 17:18:03 +00003175 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003176 int got;
3177 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003178 assert( offset>=0 );
3179 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003180
dan08da86a2009-08-21 17:18:03 +00003181 /* If this is a database file (not a journal, master-journal or temp
3182 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003183#if 0
dane946c392009-08-22 11:39:46 +00003184 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003185 || offset>=PENDING_BYTE+512
3186 || offset+amt<=PENDING_BYTE
3187 );
dan7c246102010-04-12 19:00:29 +00003188#endif
drh08c6d442009-02-09 17:34:07 +00003189
drh9b4c59f2013-04-15 17:03:42 +00003190#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003191 /* Deal with as much of this read request as possible by transfering
3192 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003193 if( offset<pFile->mmapSize ){
3194 if( offset+amt <= pFile->mmapSize ){
3195 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3196 return SQLITE_OK;
3197 }else{
3198 int nCopy = pFile->mmapSize - offset;
3199 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3200 pBuf = &((u8 *)pBuf)[nCopy];
3201 amt -= nCopy;
3202 offset += nCopy;
3203 }
3204 }
drh6e0b6d52013-04-09 16:19:20 +00003205#endif
danf23da962013-03-23 21:00:41 +00003206
dan08da86a2009-08-21 17:18:03 +00003207 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003208 if( got==amt ){
3209 return SQLITE_OK;
3210 }else if( got<0 ){
3211 /* lastErrno set by seekAndRead */
3212 return SQLITE_IOERR_READ;
3213 }else{
dan08da86a2009-08-21 17:18:03 +00003214 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003215 /* Unread parts of the buffer must be zero-filled */
3216 memset(&((char*)pBuf)[got], 0, amt-got);
3217 return SQLITE_IOERR_SHORT_READ;
3218 }
3219}
3220
3221/*
dan47a2b4a2013-04-26 16:09:29 +00003222** Attempt to seek the file-descriptor passed as the first argument to
3223** absolute offset iOff, then attempt to write nBuf bytes of data from
3224** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3225** return the actual number of bytes written (which may be less than
3226** nBuf).
3227*/
3228static int seekAndWriteFd(
3229 int fd, /* File descriptor to write to */
3230 i64 iOff, /* File offset to begin writing at */
3231 const void *pBuf, /* Copy data from this buffer to the file */
3232 int nBuf, /* Size of buffer pBuf in bytes */
3233 int *piErrno /* OUT: Error number if error occurs */
3234){
3235 int rc = 0; /* Value returned by system call */
3236
3237 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003238 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003239 nBuf &= 0x1ffff;
3240 TIMER_START;
3241
3242#if defined(USE_PREAD)
3243 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3244#elif defined(USE_PREAD64)
3245 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3246#else
3247 do{
3248 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3249 SimulateIOError( iSeek-- );
3250
3251 if( iSeek!=iOff ){
3252 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3253 return -1;
3254 }
3255 rc = osWrite(fd, pBuf, nBuf);
3256 }while( rc<0 && errno==EINTR );
3257#endif
3258
3259 TIMER_END;
3260 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3261
3262 if( rc<0 && piErrno ) *piErrno = errno;
3263 return rc;
3264}
3265
3266
3267/*
drh734c9862008-11-28 15:37:20 +00003268** Seek to the offset in id->offset then read cnt bytes into pBuf.
3269** Return the number of bytes actually read. Update the offset.
3270**
3271** To avoid stomping the errno value on a failed write the lastErrno value
3272** is set before returning.
3273*/
3274static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003275 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003276}
3277
3278
3279/*
3280** Write data from a buffer into a file. Return SQLITE_OK on success
3281** or some other error code on failure.
3282*/
3283static int unixWrite(
3284 sqlite3_file *id,
3285 const void *pBuf,
3286 int amt,
3287 sqlite3_int64 offset
3288){
dan08da86a2009-08-21 17:18:03 +00003289 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003290 int wrote = 0;
3291 assert( id );
3292 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003293
dan08da86a2009-08-21 17:18:03 +00003294 /* If this is a database file (not a journal, master-journal or temp
3295 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003296#if 0
dane946c392009-08-22 11:39:46 +00003297 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003298 || offset>=PENDING_BYTE+512
3299 || offset+amt<=PENDING_BYTE
3300 );
dan7c246102010-04-12 19:00:29 +00003301#endif
drh08c6d442009-02-09 17:34:07 +00003302
drhd3d8c042012-05-29 17:02:40 +00003303#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003304 /* If we are doing a normal write to a database file (as opposed to
3305 ** doing a hot-journal rollback or a write to some file other than a
3306 ** normal database file) then record the fact that the database
3307 ** has changed. If the transaction counter is modified, record that
3308 ** fact too.
3309 */
dan08da86a2009-08-21 17:18:03 +00003310 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003311 pFile->dbUpdate = 1; /* The database has been modified */
3312 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003313 int rc;
drh8f941bc2009-01-14 23:03:40 +00003314 char oldCntr[4];
3315 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003316 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003317 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003318 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003319 pFile->transCntrChng = 1; /* The transaction counter has changed */
3320 }
3321 }
3322 }
3323#endif
3324
drh9b4c59f2013-04-15 17:03:42 +00003325#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003326 /* Deal with as much of this write request as possible by transfering
3327 ** data from the memory mapping using memcpy(). */
3328 if( offset<pFile->mmapSize ){
3329 if( offset+amt <= pFile->mmapSize ){
3330 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3331 return SQLITE_OK;
3332 }else{
3333 int nCopy = pFile->mmapSize - offset;
3334 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3335 pBuf = &((u8 *)pBuf)[nCopy];
3336 amt -= nCopy;
3337 offset += nCopy;
3338 }
3339 }
drh6e0b6d52013-04-09 16:19:20 +00003340#endif
danf23da962013-03-23 21:00:41 +00003341
dan08da86a2009-08-21 17:18:03 +00003342 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003343 amt -= wrote;
3344 offset += wrote;
3345 pBuf = &((char*)pBuf)[wrote];
3346 }
3347 SimulateIOError(( wrote=(-1), amt=1 ));
3348 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003349
drh734c9862008-11-28 15:37:20 +00003350 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003351 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003352 /* lastErrno set by seekAndWrite */
3353 return SQLITE_IOERR_WRITE;
3354 }else{
dan08da86a2009-08-21 17:18:03 +00003355 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003356 return SQLITE_FULL;
3357 }
3358 }
dan6e09d692010-07-27 18:34:15 +00003359
drh734c9862008-11-28 15:37:20 +00003360 return SQLITE_OK;
3361}
3362
3363#ifdef SQLITE_TEST
3364/*
3365** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003366** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003367*/
3368int sqlite3_sync_count = 0;
3369int sqlite3_fullsync_count = 0;
3370#endif
3371
3372/*
drh89240432009-03-25 01:06:01 +00003373** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003374** Others do no. To be safe, we will stick with the (slightly slower)
3375** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003376** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003377*/
drh20f8e132011-08-31 21:01:55 +00003378#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003379# define fdatasync fsync
3380#endif
3381
3382/*
3383** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3384** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3385** only available on Mac OS X. But that could change.
3386*/
3387#ifdef F_FULLFSYNC
3388# define HAVE_FULLFSYNC 1
3389#else
3390# define HAVE_FULLFSYNC 0
3391#endif
3392
3393
3394/*
3395** The fsync() system call does not work as advertised on many
3396** unix systems. The following procedure is an attempt to make
3397** it work better.
3398**
3399** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3400** for testing when we want to run through the test suite quickly.
3401** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3402** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3403** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003404**
3405** SQLite sets the dataOnly flag if the size of the file is unchanged.
3406** The idea behind dataOnly is that it should only write the file content
3407** to disk, not the inode. We only set dataOnly if the file size is
3408** unchanged since the file size is part of the inode. However,
3409** Ted Ts'o tells us that fdatasync() will also write the inode if the
3410** file size has changed. The only real difference between fdatasync()
3411** and fsync(), Ted tells us, is that fdatasync() will not flush the
3412** inode if the mtime or owner or other inode attributes have changed.
3413** We only care about the file size, not the other file attributes, so
3414** as far as SQLite is concerned, an fdatasync() is always adequate.
3415** So, we always use fdatasync() if it is available, regardless of
3416** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003417*/
3418static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003419 int rc;
drh734c9862008-11-28 15:37:20 +00003420
3421 /* The following "ifdef/elif/else/" block has the same structure as
3422 ** the one below. It is replicated here solely to avoid cluttering
3423 ** up the real code with the UNUSED_PARAMETER() macros.
3424 */
3425#ifdef SQLITE_NO_SYNC
3426 UNUSED_PARAMETER(fd);
3427 UNUSED_PARAMETER(fullSync);
3428 UNUSED_PARAMETER(dataOnly);
3429#elif HAVE_FULLFSYNC
3430 UNUSED_PARAMETER(dataOnly);
3431#else
3432 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003433 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003434#endif
3435
3436 /* Record the number of times that we do a normal fsync() and
3437 ** FULLSYNC. This is used during testing to verify that this procedure
3438 ** gets called with the correct arguments.
3439 */
3440#ifdef SQLITE_TEST
3441 if( fullSync ) sqlite3_fullsync_count++;
3442 sqlite3_sync_count++;
3443#endif
3444
3445 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3446 ** no-op
3447 */
3448#ifdef SQLITE_NO_SYNC
3449 rc = SQLITE_OK;
3450#elif HAVE_FULLFSYNC
3451 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003452 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003453 }else{
3454 rc = 1;
3455 }
3456 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003457 ** It shouldn't be possible for fullfsync to fail on the local
3458 ** file system (on OSX), so failure indicates that FULLFSYNC
3459 ** isn't supported for this file system. So, attempt an fsync
3460 ** and (for now) ignore the overhead of a superfluous fcntl call.
3461 ** It'd be better to detect fullfsync support once and avoid
3462 ** the fcntl call every time sync is called.
3463 */
drh734c9862008-11-28 15:37:20 +00003464 if( rc ) rc = fsync(fd);
3465
drh7ed97b92010-01-20 13:07:21 +00003466#elif defined(__APPLE__)
3467 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3468 ** so currently we default to the macro that redefines fdatasync to fsync
3469 */
3470 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003471#else
drh0b647ff2009-03-21 14:41:04 +00003472 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003473#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003474 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003475 rc = fsync(fd);
3476 }
drh0b647ff2009-03-21 14:41:04 +00003477#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003478#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3479
3480 if( OS_VXWORKS && rc!= -1 ){
3481 rc = 0;
3482 }
chw97185482008-11-17 08:05:31 +00003483 return rc;
drhbfe66312006-10-03 17:40:40 +00003484}
3485
drh734c9862008-11-28 15:37:20 +00003486/*
drh0059eae2011-08-08 23:48:40 +00003487** Open a file descriptor to the directory containing file zFilename.
3488** If successful, *pFd is set to the opened file descriptor and
3489** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3490** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3491** value.
3492**
drh90315a22011-08-10 01:52:12 +00003493** The directory file descriptor is used for only one thing - to
3494** fsync() a directory to make sure file creation and deletion events
3495** are flushed to disk. Such fsyncs are not needed on newer
3496** journaling filesystems, but are required on older filesystems.
3497**
3498** This routine can be overridden using the xSetSysCall interface.
3499** The ability to override this routine was added in support of the
3500** chromium sandbox. Opening a directory is a security risk (we are
3501** told) so making it overrideable allows the chromium sandbox to
3502** replace this routine with a harmless no-op. To make this routine
3503** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3504** *pFd set to a negative number.
3505**
drh0059eae2011-08-08 23:48:40 +00003506** If SQLITE_OK is returned, the caller is responsible for closing
3507** the file descriptor *pFd using close().
3508*/
3509static int openDirectory(const char *zFilename, int *pFd){
3510 int ii;
3511 int fd = -1;
3512 char zDirname[MAX_PATHNAME+1];
3513
3514 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3515 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3516 if( ii>0 ){
3517 zDirname[ii] = '\0';
3518 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3519 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003520 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3521 }
3522 }
3523 *pFd = fd;
3524 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3525}
3526
3527/*
drh734c9862008-11-28 15:37:20 +00003528** Make sure all writes to a particular file are committed to disk.
3529**
3530** If dataOnly==0 then both the file itself and its metadata (file
3531** size, access time, etc) are synced. If dataOnly!=0 then only the
3532** file data is synced.
3533**
3534** Under Unix, also make sure that the directory entry for the file
3535** has been created by fsync-ing the directory that contains the file.
3536** If we do not do this and we encounter a power failure, the directory
3537** entry for the journal might not exist after we reboot. The next
3538** SQLite to access the file will not know that the journal exists (because
3539** the directory entry for the journal was never created) and the transaction
3540** will not roll back - possibly leading to database corruption.
3541*/
3542static int unixSync(sqlite3_file *id, int flags){
3543 int rc;
3544 unixFile *pFile = (unixFile*)id;
3545
3546 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3547 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3548
3549 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3550 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3551 || (flags&0x0F)==SQLITE_SYNC_FULL
3552 );
3553
3554 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3555 ** line is to test that doing so does not cause any problems.
3556 */
3557 SimulateDiskfullError( return SQLITE_FULL );
3558
3559 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003560 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003561 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3562 SimulateIOError( rc=1 );
3563 if( rc ){
3564 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003565 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003566 }
drh0059eae2011-08-08 23:48:40 +00003567
3568 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003569 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003570 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003571 */
3572 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3573 int dirfd;
3574 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003575 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003576 rc = osOpenDirectory(pFile->zPath, &dirfd);
3577 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003578 full_fsync(dirfd, 0, 0);
3579 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003580 }else if( rc==SQLITE_CANTOPEN ){
3581 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003582 }
drh0059eae2011-08-08 23:48:40 +00003583 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003584 }
3585 return rc;
3586}
3587
3588/*
3589** Truncate an open file to a specified size
3590*/
3591static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003592 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003593 int rc;
dan6e09d692010-07-27 18:34:15 +00003594 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003595 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003596
3597 /* If the user has configured a chunk-size for this file, truncate the
3598 ** file so that it consists of an integer number of chunks (i.e. the
3599 ** actual file size after the operation may be larger than the requested
3600 ** size).
3601 */
drhb8af4b72012-04-05 20:04:39 +00003602 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003603 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3604 }
3605
drhff812312011-02-23 13:33:46 +00003606 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003607 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003608 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003609 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003610 }else{
drhd3d8c042012-05-29 17:02:40 +00003611#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003612 /* If we are doing a normal write to a database file (as opposed to
3613 ** doing a hot-journal rollback or a write to some file other than a
3614 ** normal database file) and we truncate the file to zero length,
3615 ** that effectively updates the change counter. This might happen
3616 ** when restoring a database using the backup API from a zero-length
3617 ** source.
3618 */
dan6e09d692010-07-27 18:34:15 +00003619 if( pFile->inNormalWrite && nByte==0 ){
3620 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003621 }
danf23da962013-03-23 21:00:41 +00003622#endif
danc0003312013-03-22 17:46:11 +00003623
mistachkine98844f2013-08-24 00:59:24 +00003624#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003625 /* If the file was just truncated to a size smaller than the currently
3626 ** mapped region, reduce the effective mapping size as well. SQLite will
3627 ** use read() and write() to access data beyond this point from now on.
3628 */
3629 if( nByte<pFile->mmapSize ){
3630 pFile->mmapSize = nByte;
3631 }
mistachkine98844f2013-08-24 00:59:24 +00003632#endif
drh3313b142009-11-06 04:13:18 +00003633
drh734c9862008-11-28 15:37:20 +00003634 return SQLITE_OK;
3635 }
3636}
3637
3638/*
3639** Determine the current size of a file in bytes
3640*/
3641static int unixFileSize(sqlite3_file *id, i64 *pSize){
3642 int rc;
3643 struct stat buf;
3644 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003645 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003646 SimulateIOError( rc=1 );
3647 if( rc!=0 ){
3648 ((unixFile*)id)->lastErrno = errno;
3649 return SQLITE_IOERR_FSTAT;
3650 }
3651 *pSize = buf.st_size;
3652
drh8af6c222010-05-14 12:43:01 +00003653 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003654 ** writes a single byte into that file in order to work around a bug
3655 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3656 ** layers, we need to report this file size as zero even though it is
3657 ** really 1. Ticket #3260.
3658 */
3659 if( *pSize==1 ) *pSize = 0;
3660
3661
3662 return SQLITE_OK;
3663}
3664
drhd2cb50b2009-01-09 21:41:17 +00003665#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003666/*
3667** Handler for proxy-locking file-control verbs. Defined below in the
3668** proxying locking division.
3669*/
3670static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003671#endif
drh715ff302008-12-03 22:32:44 +00003672
dan502019c2010-07-28 14:26:17 +00003673/*
3674** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003675** file-control operation. Enlarge the database to nBytes in size
3676** (rounded up to the next chunk-size). If the database is already
3677** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003678*/
3679static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003680 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003681 i64 nSize; /* Required file size */
3682 struct stat buf; /* Used to hold return values of fstat() */
3683
drh99ab3b12011-03-02 15:09:07 +00003684 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003685
3686 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3687 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003688
dan502019c2010-07-28 14:26:17 +00003689#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003690 /* The code below is handling the return value of osFallocate()
3691 ** correctly. posix_fallocate() is defined to "returns zero on success,
3692 ** or an error number on failure". See the manpage for details. */
3693 int err;
drhff812312011-02-23 13:33:46 +00003694 do{
dan661d71a2011-03-30 19:08:03 +00003695 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3696 }while( err==EINTR );
3697 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003698#else
3699 /* If the OS does not have posix_fallocate(), fake it. First use
3700 ** ftruncate() to set the file size, then write a single byte to
3701 ** the last byte in each block within the extended region. This
3702 ** is the same technique used by glibc to implement posix_fallocate()
3703 ** on systems that do not have a real fallocate() system call.
3704 */
3705 int nBlk = buf.st_blksize; /* File-system block size */
3706 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003707
drhff812312011-02-23 13:33:46 +00003708 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003709 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003710 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003711 }
3712 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003713 while( iWrite<nSize ){
3714 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3715 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003716 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003717 }
dan502019c2010-07-28 14:26:17 +00003718#endif
3719 }
3720 }
3721
mistachkine98844f2013-08-24 00:59:24 +00003722#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003723 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003724 int rc;
3725 if( pFile->szChunk<=0 ){
3726 if( robust_ftruncate(pFile->h, nByte) ){
3727 pFile->lastErrno = errno;
3728 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3729 }
3730 }
3731
3732 rc = unixMapfile(pFile, nByte);
3733 return rc;
3734 }
mistachkine98844f2013-08-24 00:59:24 +00003735#endif
danf23da962013-03-23 21:00:41 +00003736
dan502019c2010-07-28 14:26:17 +00003737 return SQLITE_OK;
3738}
danielk1977ad94b582007-08-20 06:44:22 +00003739
danielk1977e3026632004-06-22 11:29:02 +00003740/*
drhf12b3f62011-12-21 14:42:29 +00003741** If *pArg is inititially negative then this is a query. Set *pArg to
3742** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3743**
3744** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3745*/
3746static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3747 if( *pArg<0 ){
3748 *pArg = (pFile->ctrlFlags & mask)!=0;
3749 }else if( (*pArg)==0 ){
3750 pFile->ctrlFlags &= ~mask;
3751 }else{
3752 pFile->ctrlFlags |= mask;
3753 }
3754}
3755
drh696b33e2012-12-06 19:01:42 +00003756/* Forward declaration */
3757static int unixGetTempname(int nBuf, char *zBuf);
3758
drhf12b3f62011-12-21 14:42:29 +00003759/*
drh9e33c2c2007-08-31 18:34:59 +00003760** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003761*/
drhcc6bb3e2007-08-31 16:11:35 +00003762static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003763 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003764 switch( op ){
3765 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003766 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003767 return SQLITE_OK;
3768 }
drh7708e972008-11-29 00:56:52 +00003769 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003770 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003771 return SQLITE_OK;
3772 }
dan6e09d692010-07-27 18:34:15 +00003773 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003774 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003775 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003776 }
drh9ff27ec2010-05-19 19:26:05 +00003777 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003778 int rc;
3779 SimulateIOErrorBenign(1);
3780 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3781 SimulateIOErrorBenign(0);
3782 return rc;
drhf0b190d2011-07-26 16:03:07 +00003783 }
3784 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003785 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3786 return SQLITE_OK;
3787 }
drhcb15f352011-12-23 01:04:17 +00003788 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3789 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003790 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003791 }
drhde60fc22011-12-14 17:53:36 +00003792 case SQLITE_FCNTL_VFSNAME: {
3793 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3794 return SQLITE_OK;
3795 }
drh696b33e2012-12-06 19:01:42 +00003796 case SQLITE_FCNTL_TEMPFILENAME: {
3797 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3798 if( zTFile ){
3799 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3800 *(char**)pArg = zTFile;
3801 }
3802 return SQLITE_OK;
3803 }
mistachkine98844f2013-08-24 00:59:24 +00003804#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003805 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003806 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003807 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003808 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3809 newLimit = sqlite3GlobalConfig.mxMmap;
3810 }
3811 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003812 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003813 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003814 if( pFile->mmapSize>0 ){
3815 unixUnmapfile(pFile);
3816 rc = unixMapfile(pFile, -1);
3817 }
danbcb8a862013-04-08 15:30:41 +00003818 }
drh34e258c2013-05-23 01:40:53 +00003819 return rc;
danb2d3de32013-03-14 18:34:37 +00003820 }
mistachkine98844f2013-08-24 00:59:24 +00003821#endif
drhd3d8c042012-05-29 17:02:40 +00003822#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003823 /* The pager calls this method to signal that it has done
3824 ** a rollback and that the database is therefore unchanged and
3825 ** it hence it is OK for the transaction change counter to be
3826 ** unchanged.
3827 */
3828 case SQLITE_FCNTL_DB_UNCHANGED: {
3829 ((unixFile*)id)->dbUpdate = 0;
3830 return SQLITE_OK;
3831 }
3832#endif
drhd2cb50b2009-01-09 21:41:17 +00003833#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003834 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003835 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003836 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003837 }
drhd2cb50b2009-01-09 21:41:17 +00003838#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003839 }
drh0b52b7d2011-01-26 19:46:22 +00003840 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003841}
3842
3843/*
danielk1977a3d4c882007-03-23 10:08:38 +00003844** Return the sector size in bytes of the underlying block device for
3845** the specified file. This is almost always 512 bytes, but may be
3846** larger for some devices.
3847**
3848** SQLite code assumes this function cannot fail. It also assumes that
3849** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003850** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003851** same for both.
3852*/
drh537dddf2012-10-26 13:46:24 +00003853#ifndef __QNXNTO__
3854static int unixSectorSize(sqlite3_file *NotUsed){
3855 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003856 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003857}
drh537dddf2012-10-26 13:46:24 +00003858#endif
3859
3860/*
3861** The following version of unixSectorSize() is optimized for QNX.
3862*/
3863#ifdef __QNXNTO__
3864#include <sys/dcmd_blk.h>
3865#include <sys/statvfs.h>
3866static int unixSectorSize(sqlite3_file *id){
3867 unixFile *pFile = (unixFile*)id;
3868 if( pFile->sectorSize == 0 ){
3869 struct statvfs fsInfo;
3870
3871 /* Set defaults for non-supported filesystems */
3872 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3873 pFile->deviceCharacteristics = 0;
3874 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3875 return pFile->sectorSize;
3876 }
3877
3878 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3879 pFile->sectorSize = fsInfo.f_bsize;
3880 pFile->deviceCharacteristics =
3881 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3882 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3883 ** the write succeeds */
3884 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3885 ** so it is ordered */
3886 0;
3887 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3888 pFile->sectorSize = fsInfo.f_bsize;
3889 pFile->deviceCharacteristics =
3890 /* etfs cluster size writes are atomic */
3891 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3892 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3893 ** the write succeeds */
3894 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3895 ** so it is ordered */
3896 0;
3897 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3898 pFile->sectorSize = fsInfo.f_bsize;
3899 pFile->deviceCharacteristics =
3900 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3901 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3902 ** the write succeeds */
3903 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3904 ** so it is ordered */
3905 0;
3906 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3907 pFile->sectorSize = fsInfo.f_bsize;
3908 pFile->deviceCharacteristics =
3909 /* full bitset of atomics from max sector size and smaller */
3910 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3911 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3912 ** so it is ordered */
3913 0;
3914 }else if( strstr(fsInfo.f_basetype, "dos") ){
3915 pFile->sectorSize = fsInfo.f_bsize;
3916 pFile->deviceCharacteristics =
3917 /* full bitset of atomics from max sector size and smaller */
3918 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3919 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3920 ** so it is ordered */
3921 0;
3922 }else{
3923 pFile->deviceCharacteristics =
3924 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3925 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3926 ** the write succeeds */
3927 0;
3928 }
3929 }
3930 /* Last chance verification. If the sector size isn't a multiple of 512
3931 ** then it isn't valid.*/
3932 if( pFile->sectorSize % 512 != 0 ){
3933 pFile->deviceCharacteristics = 0;
3934 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3935 }
3936 return pFile->sectorSize;
3937}
3938#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003939
danielk197790949c22007-08-17 16:50:38 +00003940/*
drhf12b3f62011-12-21 14:42:29 +00003941** Return the device characteristics for the file.
3942**
drhcb15f352011-12-23 01:04:17 +00003943** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3944** However, that choice is contraversial since technically the underlying
3945** file system does not always provide powersafe overwrites. (In other
3946** words, after a power-loss event, parts of the file that were never
3947** written might end up being altered.) However, non-PSOW behavior is very,
3948** very rare. And asserting PSOW makes a large reduction in the amount
3949** of required I/O for journaling, since a lot of padding is eliminated.
3950** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3951** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003952*/
drhf12b3f62011-12-21 14:42:29 +00003953static int unixDeviceCharacteristics(sqlite3_file *id){
3954 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003955 int rc = 0;
3956#ifdef __QNXNTO__
3957 if( p->sectorSize==0 ) unixSectorSize(id);
3958 rc = p->deviceCharacteristics;
3959#endif
drhcb15f352011-12-23 01:04:17 +00003960 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003961 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003962 }
drh537dddf2012-10-26 13:46:24 +00003963 return rc;
danielk197762079062007-08-15 17:08:46 +00003964}
3965
drhd9e5c4f2010-05-12 18:01:39 +00003966#ifndef SQLITE_OMIT_WAL
3967
3968
3969/*
drhd91c68f2010-05-14 14:52:25 +00003970** Object used to represent an shared memory buffer.
3971**
3972** When multiple threads all reference the same wal-index, each thread
3973** has its own unixShm object, but they all point to a single instance
3974** of this unixShmNode object. In other words, each wal-index is opened
3975** only once per process.
3976**
3977** Each unixShmNode object is connected to a single unixInodeInfo object.
3978** We could coalesce this object into unixInodeInfo, but that would mean
3979** every open file that does not use shared memory (in other words, most
3980** open files) would have to carry around this extra information. So
3981** the unixInodeInfo object contains a pointer to this unixShmNode object
3982** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003983**
3984** unixMutexHeld() must be true when creating or destroying
3985** this object or while reading or writing the following fields:
3986**
3987** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003988**
3989** The following fields are read-only after the object is created:
3990**
3991** fid
3992** zFilename
3993**
drhd91c68f2010-05-14 14:52:25 +00003994** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003995** unixMutexHeld() is true when reading or writing any other field
3996** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003997*/
drhd91c68f2010-05-14 14:52:25 +00003998struct unixShmNode {
3999 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004000 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004001 char *zFilename; /* Name of the mmapped file */
4002 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004003 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004004 u16 nRegion; /* Size of array apRegion */
4005 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004006 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004007 int nRef; /* Number of unixShm objects pointing to this */
4008 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004009#ifdef SQLITE_DEBUG
4010 u8 exclMask; /* Mask of exclusive locks held */
4011 u8 sharedMask; /* Mask of shared locks held */
4012 u8 nextShmId; /* Next available unixShm.id value */
4013#endif
4014};
4015
4016/*
drhd9e5c4f2010-05-12 18:01:39 +00004017** Structure used internally by this VFS to record the state of an
4018** open shared memory connection.
4019**
drhd91c68f2010-05-14 14:52:25 +00004020** The following fields are initialized when this object is created and
4021** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004022**
drhd91c68f2010-05-14 14:52:25 +00004023** unixShm.pFile
4024** unixShm.id
4025**
4026** All other fields are read/write. The unixShm.pFile->mutex must be held
4027** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004028*/
4029struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004030 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4031 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004032 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004033 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004034 u16 sharedMask; /* Mask of shared locks held */
4035 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004036};
4037
4038/*
drhd9e5c4f2010-05-12 18:01:39 +00004039** Constants used for locking
4040*/
drhbd9676c2010-06-23 17:58:38 +00004041#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004042#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004043
drhd9e5c4f2010-05-12 18:01:39 +00004044/*
drh73b64e42010-05-30 19:55:15 +00004045** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004046**
4047** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4048** otherwise.
4049*/
4050static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004051 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4052 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004053 int ofst, /* First byte of the locking range */
4054 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004055){
4056 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004057 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004058
drhd91c68f2010-05-14 14:52:25 +00004059 /* Access to the unixShmNode object is serialized by the caller */
4060 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004061
drh73b64e42010-05-30 19:55:15 +00004062 /* Shared locks never span more than one byte */
4063 assert( n==1 || lockType!=F_RDLCK );
4064
4065 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004066 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004067
drh3cb93392011-03-12 18:10:44 +00004068 if( pShmNode->h>=0 ){
4069 /* Initialize the locking parameters */
4070 memset(&f, 0, sizeof(f));
4071 f.l_type = lockType;
4072 f.l_whence = SEEK_SET;
4073 f.l_start = ofst;
4074 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004075
drh3cb93392011-03-12 18:10:44 +00004076 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4077 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4078 }
drhd9e5c4f2010-05-12 18:01:39 +00004079
4080 /* Update the global lock state and do debug tracing */
4081#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004082 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004083 OSTRACE(("SHM-LOCK "));
drh47676fe2013-12-05 16:41:55 +00004084 mask = ofst>31 ? 0xffffffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004085 if( rc==SQLITE_OK ){
4086 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004087 OSTRACE(("unlock %d ok", ofst));
4088 pShmNode->exclMask &= ~mask;
4089 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004090 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004091 OSTRACE(("read-lock %d ok", ofst));
4092 pShmNode->exclMask &= ~mask;
4093 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004094 }else{
4095 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004096 OSTRACE(("write-lock %d ok", ofst));
4097 pShmNode->exclMask |= mask;
4098 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004099 }
4100 }else{
4101 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004102 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004103 }else if( lockType==F_RDLCK ){
4104 OSTRACE(("read-lock failed"));
4105 }else{
4106 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004107 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004108 }
4109 }
drh20e1f082010-05-31 16:10:12 +00004110 OSTRACE((" - afterwards %03x,%03x\n",
4111 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004112 }
drhd9e5c4f2010-05-12 18:01:39 +00004113#endif
4114
4115 return rc;
4116}
4117
drhd9e5c4f2010-05-12 18:01:39 +00004118
4119/*
drhd91c68f2010-05-14 14:52:25 +00004120** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004121**
4122** This is not a VFS shared-memory method; it is a utility function called
4123** by VFS shared-memory methods.
4124*/
drhd91c68f2010-05-14 14:52:25 +00004125static void unixShmPurge(unixFile *pFd){
4126 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004127 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004128 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00004129 int i;
drhd91c68f2010-05-14 14:52:25 +00004130 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004131 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00004132 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00004133 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004134 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004135 }else{
4136 sqlite3_free(p->apRegion[i]);
4137 }
dan13a3cb82010-06-11 19:04:21 +00004138 }
dan18801912010-06-14 14:07:50 +00004139 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004140 if( p->h>=0 ){
4141 robust_close(pFd, p->h, __LINE__);
4142 p->h = -1;
4143 }
drhd91c68f2010-05-14 14:52:25 +00004144 p->pInode->pShmNode = 0;
4145 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004146 }
4147}
4148
4149/*
danda9fe0c2010-07-13 18:44:03 +00004150** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004151** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004152**
drh7234c6d2010-06-19 15:10:09 +00004153** The file used to implement shared-memory is in the same directory
4154** as the open database file and has the same name as the open database
4155** file with the "-shm" suffix added. For example, if the database file
4156** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004157** for shared memory will be called "/home/user1/config.db-shm".
4158**
4159** Another approach to is to use files in /dev/shm or /dev/tmp or an
4160** some other tmpfs mount. But if a file in a different directory
4161** from the database file is used, then differing access permissions
4162** or a chroot() might cause two different processes on the same
4163** database to end up using different files for shared memory -
4164** meaning that their memory would not really be shared - resulting
4165** in database corruption. Nevertheless, this tmpfs file usage
4166** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4167** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4168** option results in an incompatible build of SQLite; builds of SQLite
4169** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4170** same database file at the same time, database corruption will likely
4171** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4172** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004173**
4174** When opening a new shared-memory file, if no other instances of that
4175** file are currently open, in this process or in other processes, then
4176** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004177**
4178** If the original database file (pDbFd) is using the "unix-excl" VFS
4179** that means that an exclusive lock is held on the database file and
4180** that no other processes are able to read or write the database. In
4181** that case, we do not really need shared memory. No shared memory
4182** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004183*/
danda9fe0c2010-07-13 18:44:03 +00004184static int unixOpenSharedMemory(unixFile *pDbFd){
4185 struct unixShm *p = 0; /* The connection to be opened */
4186 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4187 int rc; /* Result code */
4188 unixInodeInfo *pInode; /* The inode of fd */
4189 char *zShmFilename; /* Name of the file used for SHM */
4190 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004191
danda9fe0c2010-07-13 18:44:03 +00004192 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004193 p = sqlite3_malloc( sizeof(*p) );
4194 if( p==0 ) return SQLITE_NOMEM;
4195 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004196 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004197
danda9fe0c2010-07-13 18:44:03 +00004198 /* Check to see if a unixShmNode object already exists. Reuse an existing
4199 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004200 */
4201 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004202 pInode = pDbFd->pInode;
4203 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004204 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004205 struct stat sStat; /* fstat() info for database file */
4206
4207 /* Call fstat() to figure out the permissions on the database file. If
4208 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004209 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004210 */
drh3cb93392011-03-12 18:10:44 +00004211 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004212 rc = SQLITE_IOERR_FSTAT;
4213 goto shm_open_err;
4214 }
4215
drha4ced192010-07-15 18:32:40 +00004216#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004217 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004218#else
drh52bcde02012-01-03 14:50:45 +00004219 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004220#endif
drh7234c6d2010-06-19 15:10:09 +00004221 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004222 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004223 rc = SQLITE_NOMEM;
4224 goto shm_open_err;
4225 }
drh9cb5a0d2012-01-05 21:19:54 +00004226 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004227 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004228#ifdef SQLITE_SHM_DIRECTORY
4229 sqlite3_snprintf(nShmFilename, zShmFilename,
4230 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4231 (u32)sStat.st_ino, (u32)sStat.st_dev);
4232#else
drh7234c6d2010-06-19 15:10:09 +00004233 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004234 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004235#endif
drhd91c68f2010-05-14 14:52:25 +00004236 pShmNode->h = -1;
4237 pDbFd->pInode->pShmNode = pShmNode;
4238 pShmNode->pInode = pDbFd->pInode;
4239 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4240 if( pShmNode->mutex==0 ){
4241 rc = SQLITE_NOMEM;
4242 goto shm_open_err;
4243 }
drhd9e5c4f2010-05-12 18:01:39 +00004244
drh3cb93392011-03-12 18:10:44 +00004245 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004246 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004247 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004248 openFlags = O_RDONLY;
4249 pShmNode->isReadonly = 1;
4250 }
4251 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004252 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004253 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4254 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004255 }
drhac7c3ac2012-02-11 19:23:48 +00004256
4257 /* If this process is running as root, make sure that the SHM file
4258 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004259 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004260 */
drhed466822012-05-31 13:10:49 +00004261 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004262
4263 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004264 ** If not, truncate the file to zero length.
4265 */
4266 rc = SQLITE_OK;
4267 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4268 if( robust_ftruncate(pShmNode->h, 0) ){
4269 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004270 }
4271 }
drh66dfec8b2011-06-01 20:01:49 +00004272 if( rc==SQLITE_OK ){
4273 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4274 }
4275 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004276 }
drhd9e5c4f2010-05-12 18:01:39 +00004277 }
4278
drhd91c68f2010-05-14 14:52:25 +00004279 /* Make the new connection a child of the unixShmNode */
4280 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004281#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004282 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004283#endif
drhd91c68f2010-05-14 14:52:25 +00004284 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004285 pDbFd->pShm = p;
4286 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004287
4288 /* The reference count on pShmNode has already been incremented under
4289 ** the cover of the unixEnterMutex() mutex and the pointer from the
4290 ** new (struct unixShm) object to the pShmNode has been set. All that is
4291 ** left to do is to link the new object into the linked list starting
4292 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4293 ** mutex.
4294 */
4295 sqlite3_mutex_enter(pShmNode->mutex);
4296 p->pNext = pShmNode->pFirst;
4297 pShmNode->pFirst = p;
4298 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004299 return SQLITE_OK;
4300
4301 /* Jump here on any error */
4302shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004303 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004304 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004305 unixLeaveMutex();
4306 return rc;
4307}
4308
4309/*
danda9fe0c2010-07-13 18:44:03 +00004310** This function is called to obtain a pointer to region iRegion of the
4311** shared-memory associated with the database file fd. Shared-memory regions
4312** are numbered starting from zero. Each shared-memory region is szRegion
4313** bytes in size.
4314**
4315** If an error occurs, an error code is returned and *pp is set to NULL.
4316**
4317** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4318** region has not been allocated (by any client, including one running in a
4319** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4320** bExtend is non-zero and the requested shared-memory region has not yet
4321** been allocated, it is allocated by this function.
4322**
4323** If the shared-memory region has already been allocated or is allocated by
4324** this call as described above, then it is mapped into this processes
4325** address space (if it is not already), *pp is set to point to the mapped
4326** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004327*/
danda9fe0c2010-07-13 18:44:03 +00004328static int unixShmMap(
4329 sqlite3_file *fd, /* Handle open on database file */
4330 int iRegion, /* Region to retrieve */
4331 int szRegion, /* Size of regions */
4332 int bExtend, /* True to extend file if necessary */
4333 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004334){
danda9fe0c2010-07-13 18:44:03 +00004335 unixFile *pDbFd = (unixFile*)fd;
4336 unixShm *p;
4337 unixShmNode *pShmNode;
4338 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004339
danda9fe0c2010-07-13 18:44:03 +00004340 /* If the shared-memory file has not yet been opened, open it now. */
4341 if( pDbFd->pShm==0 ){
4342 rc = unixOpenSharedMemory(pDbFd);
4343 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004344 }
drhd9e5c4f2010-05-12 18:01:39 +00004345
danda9fe0c2010-07-13 18:44:03 +00004346 p = pDbFd->pShm;
4347 pShmNode = p->pShmNode;
4348 sqlite3_mutex_enter(pShmNode->mutex);
4349 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004350 assert( pShmNode->pInode==pDbFd->pInode );
4351 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4352 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004353
4354 if( pShmNode->nRegion<=iRegion ){
4355 char **apNew; /* New apRegion[] array */
4356 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4357 struct stat sStat; /* Used by fstat() */
4358
4359 pShmNode->szRegion = szRegion;
4360
drh3cb93392011-03-12 18:10:44 +00004361 if( pShmNode->h>=0 ){
4362 /* The requested region is not mapped into this processes address space.
4363 ** Check to see if it has been allocated (i.e. if the wal-index file is
4364 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004365 */
drh3cb93392011-03-12 18:10:44 +00004366 if( osFstat(pShmNode->h, &sStat) ){
4367 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004368 goto shmpage_out;
4369 }
drh3cb93392011-03-12 18:10:44 +00004370
4371 if( sStat.st_size<nByte ){
4372 /* The requested memory region does not exist. If bExtend is set to
4373 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004374 */
dan47a2b4a2013-04-26 16:09:29 +00004375 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004376 goto shmpage_out;
4377 }
dan47a2b4a2013-04-26 16:09:29 +00004378
4379 /* Alternatively, if bExtend is true, extend the file. Do this by
4380 ** writing a single byte to the end of each (OS) page being
4381 ** allocated or extended. Technically, we need only write to the
4382 ** last page in order to extend the file. But writing to all new
4383 ** pages forces the OS to allocate them immediately, which reduces
4384 ** the chances of SIGBUS while accessing the mapped region later on.
4385 */
4386 else{
4387 static const int pgsz = 4096;
4388 int iPg;
4389
4390 /* Write to the last byte of each newly allocated or extended page */
4391 assert( (nByte % pgsz)==0 );
4392 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4393 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4394 const char *zFile = pShmNode->zFilename;
4395 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4396 goto shmpage_out;
4397 }
4398 }
drh3cb93392011-03-12 18:10:44 +00004399 }
4400 }
danda9fe0c2010-07-13 18:44:03 +00004401 }
4402
4403 /* Map the requested memory region into this processes address space. */
4404 apNew = (char **)sqlite3_realloc(
4405 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4406 );
4407 if( !apNew ){
4408 rc = SQLITE_IOERR_NOMEM;
4409 goto shmpage_out;
4410 }
4411 pShmNode->apRegion = apNew;
4412 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004413 void *pMem;
4414 if( pShmNode->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004415 pMem = osMmap(0, szRegion,
drh66dfec8b2011-06-01 20:01:49 +00004416 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004417 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004418 );
4419 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004420 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004421 goto shmpage_out;
4422 }
4423 }else{
4424 pMem = sqlite3_malloc(szRegion);
4425 if( pMem==0 ){
4426 rc = SQLITE_NOMEM;
4427 goto shmpage_out;
4428 }
4429 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004430 }
4431 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4432 pShmNode->nRegion++;
4433 }
4434 }
4435
4436shmpage_out:
4437 if( pShmNode->nRegion>iRegion ){
4438 *pp = pShmNode->apRegion[iRegion];
4439 }else{
4440 *pp = 0;
4441 }
drh66dfec8b2011-06-01 20:01:49 +00004442 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004443 sqlite3_mutex_leave(pShmNode->mutex);
4444 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004445}
4446
4447/*
drhd9e5c4f2010-05-12 18:01:39 +00004448** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004449**
4450** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4451** different here than in posix. In xShmLock(), one can go from unlocked
4452** to shared and back or from unlocked to exclusive and back. But one may
4453** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004454*/
4455static int unixShmLock(
4456 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004457 int ofst, /* First lock to acquire or release */
4458 int n, /* Number of locks to acquire or release */
4459 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004460){
drh73b64e42010-05-30 19:55:15 +00004461 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4462 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4463 unixShm *pX; /* For looping over all siblings */
4464 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4465 int rc = SQLITE_OK; /* Result code */
4466 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004467
drhd91c68f2010-05-14 14:52:25 +00004468 assert( pShmNode==pDbFd->pInode->pShmNode );
4469 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004470 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004471 assert( n>=1 );
4472 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4473 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4474 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4475 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4476 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004477 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4478 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004479
drhc99597c2010-05-31 01:41:15 +00004480 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004481 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004482 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004483 if( flags & SQLITE_SHM_UNLOCK ){
4484 u16 allMask = 0; /* Mask of locks held by siblings */
4485
4486 /* See if any siblings hold this same lock */
4487 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4488 if( pX==p ) continue;
4489 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4490 allMask |= pX->sharedMask;
4491 }
4492
4493 /* Unlock the system-level locks */
4494 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004495 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004496 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004497 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004498 }
drh73b64e42010-05-30 19:55:15 +00004499
4500 /* Undo the local locks */
4501 if( rc==SQLITE_OK ){
4502 p->exclMask &= ~mask;
4503 p->sharedMask &= ~mask;
4504 }
4505 }else if( flags & SQLITE_SHM_SHARED ){
4506 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4507
4508 /* Find out which shared locks are already held by sibling connections.
4509 ** If any sibling already holds an exclusive lock, go ahead and return
4510 ** SQLITE_BUSY.
4511 */
4512 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004513 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004514 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004515 break;
4516 }
4517 allShared |= pX->sharedMask;
4518 }
4519
4520 /* Get shared locks at the system level, if necessary */
4521 if( rc==SQLITE_OK ){
4522 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004523 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004524 }else{
drh73b64e42010-05-30 19:55:15 +00004525 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004526 }
drhd9e5c4f2010-05-12 18:01:39 +00004527 }
drh73b64e42010-05-30 19:55:15 +00004528
4529 /* Get the local shared locks */
4530 if( rc==SQLITE_OK ){
4531 p->sharedMask |= mask;
4532 }
4533 }else{
4534 /* Make sure no sibling connections hold locks that will block this
4535 ** lock. If any do, return SQLITE_BUSY right away.
4536 */
4537 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004538 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4539 rc = SQLITE_BUSY;
4540 break;
4541 }
4542 }
4543
4544 /* Get the exclusive locks at the system level. Then if successful
4545 ** also mark the local connection as being locked.
4546 */
4547 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004548 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004549 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004550 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004551 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004552 }
drhd9e5c4f2010-05-12 18:01:39 +00004553 }
4554 }
drhd91c68f2010-05-14 14:52:25 +00004555 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004556 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4557 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004558 return rc;
4559}
4560
drh286a2882010-05-20 23:51:06 +00004561/*
4562** Implement a memory barrier or memory fence on shared memory.
4563**
4564** All loads and stores begun before the barrier must complete before
4565** any load or store begun after the barrier.
4566*/
4567static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004568 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004569){
drhff828942010-06-26 21:34:06 +00004570 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004571 unixEnterMutex();
4572 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004573}
4574
dan18801912010-06-14 14:07:50 +00004575/*
danda9fe0c2010-07-13 18:44:03 +00004576** Close a connection to shared-memory. Delete the underlying
4577** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004578**
4579** If there is no shared memory associated with the connection then this
4580** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004581*/
danda9fe0c2010-07-13 18:44:03 +00004582static int unixShmUnmap(
4583 sqlite3_file *fd, /* The underlying database file */
4584 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004585){
danda9fe0c2010-07-13 18:44:03 +00004586 unixShm *p; /* The connection to be closed */
4587 unixShmNode *pShmNode; /* The underlying shared-memory file */
4588 unixShm **pp; /* For looping over sibling connections */
4589 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004590
danda9fe0c2010-07-13 18:44:03 +00004591 pDbFd = (unixFile*)fd;
4592 p = pDbFd->pShm;
4593 if( p==0 ) return SQLITE_OK;
4594 pShmNode = p->pShmNode;
4595
4596 assert( pShmNode==pDbFd->pInode->pShmNode );
4597 assert( pShmNode->pInode==pDbFd->pInode );
4598
4599 /* Remove connection p from the set of connections associated
4600 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004601 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004602 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4603 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004604
danda9fe0c2010-07-13 18:44:03 +00004605 /* Free the connection p */
4606 sqlite3_free(p);
4607 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004608 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004609
4610 /* If pShmNode->nRef has reached 0, then close the underlying
4611 ** shared-memory file, too */
4612 unixEnterMutex();
4613 assert( pShmNode->nRef>0 );
4614 pShmNode->nRef--;
4615 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004616 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004617 unixShmPurge(pDbFd);
4618 }
4619 unixLeaveMutex();
4620
4621 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004622}
drh286a2882010-05-20 23:51:06 +00004623
danda9fe0c2010-07-13 18:44:03 +00004624
drhd9e5c4f2010-05-12 18:01:39 +00004625#else
drh6b017cc2010-06-14 18:01:46 +00004626# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004627# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004628# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004629# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004630#endif /* #ifndef SQLITE_OMIT_WAL */
4631
mistachkine98844f2013-08-24 00:59:24 +00004632#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004633/*
danaef49d72013-03-25 16:28:54 +00004634** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004635*/
danf23da962013-03-23 21:00:41 +00004636static void unixUnmapfile(unixFile *pFd){
4637 assert( pFd->nFetchOut==0 );
4638 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004639 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004640 pFd->pMapRegion = 0;
4641 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004642 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004643 }
4644}
dan5d8a1372013-03-19 19:28:06 +00004645
danaef49d72013-03-25 16:28:54 +00004646/*
dane6ecd662013-04-01 17:56:59 +00004647** Return the system page size.
4648*/
4649static int unixGetPagesize(void){
4650#if HAVE_MREMAP
4651 return 512;
drh85830a72013-04-03 00:42:01 +00004652#elif defined(_BSD_SOURCE)
dane6ecd662013-04-01 17:56:59 +00004653 return getpagesize();
4654#else
4655 return (int)sysconf(_SC_PAGESIZE);
4656#endif
4657}
4658
4659/*
4660** Attempt to set the size of the memory mapping maintained by file
4661** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4662**
4663** If successful, this function sets the following variables:
4664**
4665** unixFile.pMapRegion
4666** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004667** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004668**
4669** If unsuccessful, an error message is logged via sqlite3_log() and
4670** the three variables above are zeroed. In this case SQLite should
4671** continue accessing the database using the xRead() and xWrite()
4672** methods.
4673*/
4674static void unixRemapfile(
4675 unixFile *pFd, /* File descriptor object */
4676 i64 nNew /* Required mapping size */
4677){
dan4ff7bc42013-04-02 12:04:09 +00004678 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004679 int h = pFd->h; /* File descriptor open on db file */
4680 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004681 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004682 u8 *pNew = 0; /* Location of new mapping */
4683 int flags = PROT_READ; /* Flags to pass to mmap() */
4684
4685 assert( pFd->nFetchOut==0 );
4686 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004687 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004688 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004689 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004690 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004691
4692 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4693
4694 if( pOrig ){
4695 const int szSyspage = unixGetPagesize();
4696 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
4697 u8 *pReq = &pOrig[nReuse];
4698
4699 /* Unmap any pages of the existing mapping that cannot be reused. */
4700 if( nReuse!=nOrig ){
4701 osMunmap(pReq, nOrig-nReuse);
4702 }
4703
4704#if HAVE_MREMAP
4705 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004706 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004707#else
4708 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4709 if( pNew!=MAP_FAILED ){
4710 if( pNew!=pReq ){
4711 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004712 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004713 }else{
4714 pNew = pOrig;
4715 }
4716 }
4717#endif
4718
dan48ccef82013-04-02 20:55:01 +00004719 /* The attempt to extend the existing mapping failed. Free it. */
4720 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004721 osMunmap(pOrig, nReuse);
4722 }
4723 }
4724
4725 /* If pNew is still NULL, try to create an entirely new mapping. */
4726 if( pNew==0 ){
4727 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004728 }
4729
dan4ff7bc42013-04-02 12:04:09 +00004730 if( pNew==MAP_FAILED ){
4731 pNew = 0;
4732 nNew = 0;
4733 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4734
4735 /* If the mmap() above failed, assume that all subsequent mmap() calls
4736 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4737 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004738 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004739 }
dane6ecd662013-04-01 17:56:59 +00004740 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004741 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004742}
4743
4744/*
danaef49d72013-03-25 16:28:54 +00004745** Memory map or remap the file opened by file-descriptor pFd (if the file
4746** is already mapped, the existing mapping is replaced by the new). Or, if
4747** there already exists a mapping for this file, and there are still
4748** outstanding xFetch() references to it, this function is a no-op.
4749**
4750** If parameter nByte is non-negative, then it is the requested size of
4751** the mapping to create. Otherwise, if nByte is less than zero, then the
4752** requested size is the size of the file on disk. The actual size of the
4753** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004754** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004755**
4756** SQLITE_OK is returned if no error occurs (even if the mapping is not
4757** recreated as a result of outstanding references) or an SQLite error
4758** code otherwise.
4759*/
danf23da962013-03-23 21:00:41 +00004760static int unixMapfile(unixFile *pFd, i64 nByte){
4761 i64 nMap = nByte;
4762 int rc;
daneb97b292013-03-20 14:26:59 +00004763
danf23da962013-03-23 21:00:41 +00004764 assert( nMap>=0 || pFd->nFetchOut==0 );
4765 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4766
4767 if( nMap<0 ){
daneb97b292013-03-20 14:26:59 +00004768 struct stat statbuf; /* Low-level file information */
danf23da962013-03-23 21:00:41 +00004769 rc = osFstat(pFd->h, &statbuf);
4770 if( rc!=SQLITE_OK ){
4771 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004772 }
danf23da962013-03-23 21:00:41 +00004773 nMap = statbuf.st_size;
4774 }
drh9b4c59f2013-04-15 17:03:42 +00004775 if( nMap>pFd->mmapSizeMax ){
4776 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004777 }
4778
danf23da962013-03-23 21:00:41 +00004779 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004780 if( nMap>0 ){
4781 unixRemapfile(pFd, nMap);
4782 }else{
danb7e3a322013-03-25 20:30:13 +00004783 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004784 }
4785 }
4786
danf23da962013-03-23 21:00:41 +00004787 return SQLITE_OK;
4788}
mistachkine98844f2013-08-24 00:59:24 +00004789#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004790
danaef49d72013-03-25 16:28:54 +00004791/*
4792** If possible, return a pointer to a mapping of file fd starting at offset
4793** iOff. The mapping must be valid for at least nAmt bytes.
4794**
4795** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4796** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4797** Finally, if an error does occur, return an SQLite error code. The final
4798** value of *pp is undefined in this case.
4799**
4800** If this function does return a pointer, the caller must eventually
4801** release the reference by calling unixUnfetch().
4802*/
danf23da962013-03-23 21:00:41 +00004803static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004804#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004805 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004806#endif
danf23da962013-03-23 21:00:41 +00004807 *pp = 0;
4808
drh9b4c59f2013-04-15 17:03:42 +00004809#if SQLITE_MAX_MMAP_SIZE>0
4810 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004811 if( pFd->pMapRegion==0 ){
4812 int rc = unixMapfile(pFd, -1);
4813 if( rc!=SQLITE_OK ) return rc;
4814 }
4815 if( pFd->mmapSize >= iOff+nAmt ){
4816 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4817 pFd->nFetchOut++;
4818 }
4819 }
drh6e0b6d52013-04-09 16:19:20 +00004820#endif
danf23da962013-03-23 21:00:41 +00004821 return SQLITE_OK;
4822}
4823
danaef49d72013-03-25 16:28:54 +00004824/*
dandf737fe2013-03-25 17:00:24 +00004825** If the third argument is non-NULL, then this function releases a
4826** reference obtained by an earlier call to unixFetch(). The second
4827** argument passed to this function must be the same as the corresponding
4828** argument that was passed to the unixFetch() invocation.
4829**
4830** Or, if the third argument is NULL, then this function is being called
4831** to inform the VFS layer that, according to POSIX, any existing mapping
4832** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004833*/
dandf737fe2013-03-25 17:00:24 +00004834static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
danf23da962013-03-23 21:00:41 +00004835 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhda8caa02013-04-22 23:38:50 +00004836 UNUSED_PARAMETER(iOff);
danf23da962013-03-23 21:00:41 +00004837
mistachkinb5ca3cb2013-08-24 01:12:03 +00004838#if SQLITE_MAX_MMAP_SIZE>0
danaef49d72013-03-25 16:28:54 +00004839 /* If p==0 (unmap the entire file) then there must be no outstanding
4840 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4841 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004842 assert( (p==0)==(pFd->nFetchOut==0) );
4843
dandf737fe2013-03-25 17:00:24 +00004844 /* If p!=0, it must match the iOff value. */
4845 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4846
danf23da962013-03-23 21:00:41 +00004847 if( p ){
4848 pFd->nFetchOut--;
4849 }else{
4850 unixUnmapfile(pFd);
4851 }
4852
4853 assert( pFd->nFetchOut>=0 );
mistachkinb5ca3cb2013-08-24 01:12:03 +00004854#endif
danf23da962013-03-23 21:00:41 +00004855 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004856}
4857
4858/*
drh734c9862008-11-28 15:37:20 +00004859** Here ends the implementation of all sqlite3_file methods.
4860**
4861********************** End sqlite3_file Methods *******************************
4862******************************************************************************/
4863
4864/*
drh6b9d6dd2008-12-03 19:34:47 +00004865** This division contains definitions of sqlite3_io_methods objects that
4866** implement various file locking strategies. It also contains definitions
4867** of "finder" functions. A finder-function is used to locate the appropriate
4868** sqlite3_io_methods object for a particular database file. The pAppData
4869** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4870** the correct finder-function for that VFS.
4871**
4872** Most finder functions return a pointer to a fixed sqlite3_io_methods
4873** object. The only interesting finder-function is autolockIoFinder, which
4874** looks at the filesystem type and tries to guess the best locking
4875** strategy from that.
4876**
drh1875f7a2008-12-08 18:19:17 +00004877** For finder-funtion F, two objects are created:
4878**
4879** (1) The real finder-function named "FImpt()".
4880**
dane946c392009-08-22 11:39:46 +00004881** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004882**
4883**
4884** A pointer to the F pointer is used as the pAppData value for VFS
4885** objects. We have to do this instead of letting pAppData point
4886** directly at the finder-function since C90 rules prevent a void*
4887** from be cast into a function pointer.
4888**
drh6b9d6dd2008-12-03 19:34:47 +00004889**
drh7708e972008-11-29 00:56:52 +00004890** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004891**
drh7708e972008-11-29 00:56:52 +00004892** * A constant sqlite3_io_methods object call METHOD that has locking
4893** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4894**
4895** * An I/O method finder function called FINDER that returns a pointer
4896** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004897*/
drhd9e5c4f2010-05-12 18:01:39 +00004898#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004899static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004900 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004901 CLOSE, /* xClose */ \
4902 unixRead, /* xRead */ \
4903 unixWrite, /* xWrite */ \
4904 unixTruncate, /* xTruncate */ \
4905 unixSync, /* xSync */ \
4906 unixFileSize, /* xFileSize */ \
4907 LOCK, /* xLock */ \
4908 UNLOCK, /* xUnlock */ \
4909 CKLOCK, /* xCheckReservedLock */ \
4910 unixFileControl, /* xFileControl */ \
4911 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004912 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004913 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004914 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004915 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004916 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004917 unixFetch, /* xFetch */ \
4918 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004919}; \
drh0c2694b2009-09-03 16:23:44 +00004920static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4921 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004922 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004923} \
drh0c2694b2009-09-03 16:23:44 +00004924static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004925 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004926
4927/*
4928** Here are all of the sqlite3_io_methods objects for each of the
4929** locking strategies. Functions that return pointers to these methods
4930** are also created.
4931*/
4932IOMETHODS(
4933 posixIoFinder, /* Finder function name */
4934 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004935 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004936 unixClose, /* xClose method */
4937 unixLock, /* xLock method */
4938 unixUnlock, /* xUnlock method */
4939 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004940)
drh7708e972008-11-29 00:56:52 +00004941IOMETHODS(
4942 nolockIoFinder, /* Finder function name */
4943 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004944 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004945 nolockClose, /* xClose method */
4946 nolockLock, /* xLock method */
4947 nolockUnlock, /* xUnlock method */
4948 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004949)
drh7708e972008-11-29 00:56:52 +00004950IOMETHODS(
4951 dotlockIoFinder, /* Finder function name */
4952 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004953 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004954 dotlockClose, /* xClose method */
4955 dotlockLock, /* xLock method */
4956 dotlockUnlock, /* xUnlock method */
4957 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004958)
drh7708e972008-11-29 00:56:52 +00004959
chw78a13182009-04-07 05:35:03 +00004960#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004961IOMETHODS(
4962 flockIoFinder, /* Finder function name */
4963 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004964 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004965 flockClose, /* xClose method */
4966 flockLock, /* xLock method */
4967 flockUnlock, /* xUnlock method */
4968 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004969)
drh7708e972008-11-29 00:56:52 +00004970#endif
4971
drh6c7d5c52008-11-21 20:32:33 +00004972#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004973IOMETHODS(
4974 semIoFinder, /* Finder function name */
4975 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004976 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004977 semClose, /* xClose method */
4978 semLock, /* xLock method */
4979 semUnlock, /* xUnlock method */
4980 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004981)
aswiftaebf4132008-11-21 00:10:35 +00004982#endif
drh7708e972008-11-29 00:56:52 +00004983
drhd2cb50b2009-01-09 21:41:17 +00004984#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004985IOMETHODS(
4986 afpIoFinder, /* Finder function name */
4987 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004988 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004989 afpClose, /* xClose method */
4990 afpLock, /* xLock method */
4991 afpUnlock, /* xUnlock method */
4992 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004993)
drh715ff302008-12-03 22:32:44 +00004994#endif
4995
4996/*
4997** The proxy locking method is a "super-method" in the sense that it
4998** opens secondary file descriptors for the conch and lock files and
4999** it uses proxy, dot-file, AFP, and flock() locking methods on those
5000** secondary files. For this reason, the division that implements
5001** proxy locking is located much further down in the file. But we need
5002** to go ahead and define the sqlite3_io_methods and finder function
5003** for proxy locking here. So we forward declare the I/O methods.
5004*/
drhd2cb50b2009-01-09 21:41:17 +00005005#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005006static int proxyClose(sqlite3_file*);
5007static int proxyLock(sqlite3_file*, int);
5008static int proxyUnlock(sqlite3_file*, int);
5009static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005010IOMETHODS(
5011 proxyIoFinder, /* Finder function name */
5012 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005013 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005014 proxyClose, /* xClose method */
5015 proxyLock, /* xLock method */
5016 proxyUnlock, /* xUnlock method */
5017 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005018)
aswiftaebf4132008-11-21 00:10:35 +00005019#endif
drh7708e972008-11-29 00:56:52 +00005020
drh7ed97b92010-01-20 13:07:21 +00005021/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5022#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5023IOMETHODS(
5024 nfsIoFinder, /* Finder function name */
5025 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005026 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005027 unixClose, /* xClose method */
5028 unixLock, /* xLock method */
5029 nfsUnlock, /* xUnlock method */
5030 unixCheckReservedLock /* xCheckReservedLock method */
5031)
5032#endif
drh7708e972008-11-29 00:56:52 +00005033
drhd2cb50b2009-01-09 21:41:17 +00005034#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005035/*
drh6b9d6dd2008-12-03 19:34:47 +00005036** This "finder" function attempts to determine the best locking strategy
5037** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005038** object that implements that strategy.
5039**
5040** This is for MacOSX only.
5041*/
drh1875f7a2008-12-08 18:19:17 +00005042static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005043 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005044 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005045){
5046 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005047 const char *zFilesystem; /* Filesystem type name */
5048 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005049 } aMap[] = {
5050 { "hfs", &posixIoMethods },
5051 { "ufs", &posixIoMethods },
5052 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005053 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005054 { "webdav", &nolockIoMethods },
5055 { 0, 0 }
5056 };
5057 int i;
5058 struct statfs fsInfo;
5059 struct flock lockInfo;
5060
5061 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005062 /* If filePath==NULL that means we are dealing with a transient file
5063 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005064 return &nolockIoMethods;
5065 }
5066 if( statfs(filePath, &fsInfo) != -1 ){
5067 if( fsInfo.f_flags & MNT_RDONLY ){
5068 return &nolockIoMethods;
5069 }
5070 for(i=0; aMap[i].zFilesystem; i++){
5071 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5072 return aMap[i].pMethods;
5073 }
5074 }
5075 }
5076
5077 /* Default case. Handles, amongst others, "nfs".
5078 ** Test byte-range lock using fcntl(). If the call succeeds,
5079 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005080 */
drh7708e972008-11-29 00:56:52 +00005081 lockInfo.l_len = 1;
5082 lockInfo.l_start = 0;
5083 lockInfo.l_whence = SEEK_SET;
5084 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005085 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005086 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5087 return &nfsIoMethods;
5088 } else {
5089 return &posixIoMethods;
5090 }
drh7708e972008-11-29 00:56:52 +00005091 }else{
5092 return &dotlockIoMethods;
5093 }
5094}
drh0c2694b2009-09-03 16:23:44 +00005095static const sqlite3_io_methods
5096 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005097
drhd2cb50b2009-01-09 21:41:17 +00005098#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005099
chw78a13182009-04-07 05:35:03 +00005100#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5101/*
5102** This "finder" function attempts to determine the best locking strategy
5103** for the database file "filePath". It then returns the sqlite3_io_methods
5104** object that implements that strategy.
5105**
5106** This is for VXWorks only.
5107*/
5108static const sqlite3_io_methods *autolockIoFinderImpl(
5109 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005110 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005111){
5112 struct flock lockInfo;
5113
5114 if( !filePath ){
5115 /* If filePath==NULL that means we are dealing with a transient file
5116 ** that does not need to be locked. */
5117 return &nolockIoMethods;
5118 }
5119
5120 /* Test if fcntl() is supported and use POSIX style locks.
5121 ** Otherwise fall back to the named semaphore method.
5122 */
5123 lockInfo.l_len = 1;
5124 lockInfo.l_start = 0;
5125 lockInfo.l_whence = SEEK_SET;
5126 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005127 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005128 return &posixIoMethods;
5129 }else{
5130 return &semIoMethods;
5131 }
5132}
drh0c2694b2009-09-03 16:23:44 +00005133static const sqlite3_io_methods
5134 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005135
5136#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5137
drh7708e972008-11-29 00:56:52 +00005138/*
5139** An abstract type for a pointer to a IO method finder function:
5140*/
drh0c2694b2009-09-03 16:23:44 +00005141typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005142
aswiftaebf4132008-11-21 00:10:35 +00005143
drh734c9862008-11-28 15:37:20 +00005144/****************************************************************************
5145**************************** sqlite3_vfs methods ****************************
5146**
5147** This division contains the implementation of methods on the
5148** sqlite3_vfs object.
5149*/
5150
danielk1977a3d4c882007-03-23 10:08:38 +00005151/*
danielk1977e339d652008-06-28 11:23:00 +00005152** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005153*/
5154static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005155 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005156 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005157 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005158 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005159 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005160){
drh7708e972008-11-29 00:56:52 +00005161 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005162 unixFile *pNew = (unixFile *)pId;
5163 int rc = SQLITE_OK;
5164
drh8af6c222010-05-14 12:43:01 +00005165 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005166
dan00157392010-10-05 11:33:15 +00005167 /* Usually the path zFilename should not be a relative pathname. The
5168 ** exception is when opening the proxy "conch" file in builds that
5169 ** include the special Apple locking styles.
5170 */
dan00157392010-10-05 11:33:15 +00005171#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005172 assert( zFilename==0 || zFilename[0]=='/'
5173 || pVfs->pAppData==(void*)&autolockIoFinder );
5174#else
5175 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005176#endif
dan00157392010-10-05 11:33:15 +00005177
drhb07028f2011-10-14 21:49:18 +00005178 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005179 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005180
drh308c2a52010-05-14 11:30:18 +00005181 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005182 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005183 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005184 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005185 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005186#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005187 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005188#endif
drhc02a43a2012-01-10 23:18:38 +00005189 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5190 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005191 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005192 }
drh503a6862013-03-01 01:07:17 +00005193 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005194 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005195 }
drh339eb0b2008-03-07 15:34:11 +00005196
drh6c7d5c52008-11-21 20:32:33 +00005197#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005198 pNew->pId = vxworksFindFileId(zFilename);
5199 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005200 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005201 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005202 }
5203#endif
5204
drhc02a43a2012-01-10 23:18:38 +00005205 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005206 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005207 }else{
drh0c2694b2009-09-03 16:23:44 +00005208 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005209#if SQLITE_ENABLE_LOCKING_STYLE
5210 /* Cache zFilename in the locking context (AFP and dotlock override) for
5211 ** proxyLock activation is possible (remote proxy is based on db name)
5212 ** zFilename remains valid until file is closed, to support */
5213 pNew->lockingContext = (void*)zFilename;
5214#endif
drhda0e7682008-07-30 15:27:54 +00005215 }
danielk1977e339d652008-06-28 11:23:00 +00005216
drh7ed97b92010-01-20 13:07:21 +00005217 if( pLockingStyle == &posixIoMethods
5218#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5219 || pLockingStyle == &nfsIoMethods
5220#endif
5221 ){
drh7708e972008-11-29 00:56:52 +00005222 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005223 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005224 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005225 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005226 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005227 ** in two scenarios:
5228 **
5229 ** (a) A call to fstat() failed.
5230 ** (b) A malloc failed.
5231 **
5232 ** Scenario (b) may only occur if the process is holding no other
5233 ** file descriptors open on the same file. If there were other file
5234 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005235 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005236 ** handle h - as it is guaranteed that no posix locks will be released
5237 ** by doing so.
5238 **
5239 ** If scenario (a) caused the error then things are not so safe. The
5240 ** implicit assumption here is that if fstat() fails, things are in
5241 ** such bad shape that dropping a lock or two doesn't matter much.
5242 */
drh0e9365c2011-03-02 02:08:13 +00005243 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005244 h = -1;
5245 }
drh7708e972008-11-29 00:56:52 +00005246 unixLeaveMutex();
5247 }
danielk1977e339d652008-06-28 11:23:00 +00005248
drhd2cb50b2009-01-09 21:41:17 +00005249#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005250 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005251 /* AFP locking uses the file path so it needs to be included in
5252 ** the afpLockingContext.
5253 */
5254 afpLockingContext *pCtx;
5255 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5256 if( pCtx==0 ){
5257 rc = SQLITE_NOMEM;
5258 }else{
5259 /* NB: zFilename exists and remains valid until the file is closed
5260 ** according to requirement F11141. So we do not need to make a
5261 ** copy of the filename. */
5262 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005263 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005264 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005265 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005266 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005267 if( rc!=SQLITE_OK ){
5268 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005269 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005270 h = -1;
5271 }
drh7708e972008-11-29 00:56:52 +00005272 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005273 }
drh7708e972008-11-29 00:56:52 +00005274 }
5275#endif
danielk1977e339d652008-06-28 11:23:00 +00005276
drh7708e972008-11-29 00:56:52 +00005277 else if( pLockingStyle == &dotlockIoMethods ){
5278 /* Dotfile locking uses the file path so it needs to be included in
5279 ** the dotlockLockingContext
5280 */
5281 char *zLockFile;
5282 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005283 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005284 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005285 zLockFile = (char *)sqlite3_malloc(nFilename);
5286 if( zLockFile==0 ){
5287 rc = SQLITE_NOMEM;
5288 }else{
5289 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005290 }
drh7708e972008-11-29 00:56:52 +00005291 pNew->lockingContext = zLockFile;
5292 }
danielk1977e339d652008-06-28 11:23:00 +00005293
drh6c7d5c52008-11-21 20:32:33 +00005294#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005295 else if( pLockingStyle == &semIoMethods ){
5296 /* Named semaphore locking uses the file path so it needs to be
5297 ** included in the semLockingContext
5298 */
5299 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005300 rc = findInodeInfo(pNew, &pNew->pInode);
5301 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5302 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005303 int n;
drh2238dcc2009-08-27 17:56:20 +00005304 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005305 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005306 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005307 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005308 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5309 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005310 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005311 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005312 }
chw97185482008-11-17 08:05:31 +00005313 }
drh7708e972008-11-29 00:56:52 +00005314 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005315 }
drh7708e972008-11-29 00:56:52 +00005316#endif
aswift5b1a2562008-08-22 00:22:35 +00005317
5318 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005319#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005320 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005321 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005322 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005323 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005324 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005325 }
chw97185482008-11-17 08:05:31 +00005326#endif
danielk1977e339d652008-06-28 11:23:00 +00005327 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005328 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005329 }else{
drh7708e972008-11-29 00:56:52 +00005330 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005331 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005332 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005333 }
danielk1977e339d652008-06-28 11:23:00 +00005334 return rc;
drh054889e2005-11-30 03:20:31 +00005335}
drh9c06c952005-11-26 00:25:00 +00005336
danielk1977ad94b582007-08-20 06:44:22 +00005337/*
drh8b3cf822010-06-01 21:02:51 +00005338** Return the name of a directory in which to put temporary files.
5339** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005340*/
drh7234c6d2010-06-19 15:10:09 +00005341static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005342 static const char *azDirs[] = {
5343 0,
aswiftaebf4132008-11-21 00:10:35 +00005344 0,
mistachkind95a3d32013-08-30 21:52:38 +00005345 0,
danielk197717b90b52008-06-06 11:11:25 +00005346 "/var/tmp",
5347 "/usr/tmp",
5348 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005349 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005350 };
drh8b3cf822010-06-01 21:02:51 +00005351 unsigned int i;
5352 struct stat buf;
5353 const char *zDir = 0;
5354
5355 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005356 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5357 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005358 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005359 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005360 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005361 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005362 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005363 break;
5364 }
5365 return zDir;
5366}
5367
5368/*
5369** Create a temporary file name in zBuf. zBuf must be allocated
5370** by the calling process and must be big enough to hold at least
5371** pVfs->mxPathname bytes.
5372*/
5373static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005374 static const unsigned char zChars[] =
5375 "abcdefghijklmnopqrstuvwxyz"
5376 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5377 "0123456789";
drh41022642008-11-21 00:24:42 +00005378 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005379 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005380
5381 /* It's odd to simulate an io-error here, but really this is just
5382 ** using the io-error infrastructure to test that SQLite handles this
5383 ** function failing.
5384 */
5385 SimulateIOError( return SQLITE_IOERR );
5386
drh7234c6d2010-06-19 15:10:09 +00005387 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005388 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005389
5390 /* Check that the output buffer is large enough for the temporary file
5391 ** name. If it is not, return SQLITE_ERROR.
5392 */
drhc02a43a2012-01-10 23:18:38 +00005393 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005394 return SQLITE_ERROR;
5395 }
5396
5397 do{
drhc02a43a2012-01-10 23:18:38 +00005398 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005399 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005400 sqlite3_randomness(15, &zBuf[j]);
5401 for(i=0; i<15; i++, j++){
5402 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5403 }
5404 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005405 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005406 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005407 return SQLITE_OK;
5408}
5409
drhd2cb50b2009-01-09 21:41:17 +00005410#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005411/*
5412** Routine to transform a unixFile into a proxy-locking unixFile.
5413** Implementation in the proxy-lock division, but used by unixOpen()
5414** if SQLITE_PREFER_PROXY_LOCKING is defined.
5415*/
5416static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005417#endif
drhc66d5b62008-12-03 22:48:32 +00005418
dan08da86a2009-08-21 17:18:03 +00005419/*
5420** Search for an unused file descriptor that was opened on the database
5421** file (not a journal or master-journal file) identified by pathname
5422** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5423** argument to this function.
5424**
5425** Such a file descriptor may exist if a database connection was closed
5426** but the associated file descriptor could not be closed because some
5427** other file descriptor open on the same file is holding a file-lock.
5428** Refer to comments in the unixClose() function and the lengthy comment
5429** describing "Posix Advisory Locking" at the start of this file for
5430** further details. Also, ticket #4018.
5431**
5432** If a suitable file descriptor is found, then it is returned. If no
5433** such file descriptor is located, -1 is returned.
5434*/
dane946c392009-08-22 11:39:46 +00005435static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5436 UnixUnusedFd *pUnused = 0;
5437
5438 /* Do not search for an unused file descriptor on vxworks. Not because
5439 ** vxworks would not benefit from the change (it might, we're not sure),
5440 ** but because no way to test it is currently available. It is better
5441 ** not to risk breaking vxworks support for the sake of such an obscure
5442 ** feature. */
5443#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005444 struct stat sStat; /* Results of stat() call */
5445
5446 /* A stat() call may fail for various reasons. If this happens, it is
5447 ** almost certain that an open() call on the same path will also fail.
5448 ** For this reason, if an error occurs in the stat() call here, it is
5449 ** ignored and -1 is returned. The caller will try to open a new file
5450 ** descriptor on the same path, fail, and return an error to SQLite.
5451 **
5452 ** Even if a subsequent open() call does succeed, the consequences of
5453 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005454 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005455 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005456
5457 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005458 pInode = inodeList;
5459 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5460 || pInode->fileId.ino!=sStat.st_ino) ){
5461 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005462 }
drh8af6c222010-05-14 12:43:01 +00005463 if( pInode ){
dane946c392009-08-22 11:39:46 +00005464 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005465 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005466 pUnused = *pp;
5467 if( pUnused ){
5468 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005469 }
5470 }
5471 unixLeaveMutex();
5472 }
dane946c392009-08-22 11:39:46 +00005473#endif /* if !OS_VXWORKS */
5474 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005475}
danielk197717b90b52008-06-06 11:11:25 +00005476
5477/*
danddb0ac42010-07-14 14:48:58 +00005478** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005479** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005480** and a value suitable for passing as the third argument to open(2) is
5481** written to *pMode. If an IO error occurs, an SQLite error code is
5482** returned and the value of *pMode is not modified.
5483**
drh8c815d12012-02-13 20:16:37 +00005484** In most cases cases, this routine sets *pMode to 0, which will become
5485** an indication to robust_open() to create the file using
5486** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5487** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005488** this function queries the file-system for the permissions on the
5489** corresponding database file and sets *pMode to this value. Whenever
5490** possible, WAL and journal files are created using the same permissions
5491** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005492**
5493** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5494** original filename is unavailable. But 8_3_NAMES is only used for
5495** FAT filesystems and permissions do not matter there, so just use
5496** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005497*/
5498static int findCreateFileMode(
5499 const char *zPath, /* Path of file (possibly) being created */
5500 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005501 mode_t *pMode, /* OUT: Permissions to open file with */
5502 uid_t *pUid, /* OUT: uid to set on the file */
5503 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005504){
5505 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005506 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005507 *pUid = 0;
5508 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005509 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005510 char zDb[MAX_PATHNAME+1]; /* Database file path */
5511 int nDb; /* Number of valid bytes in zDb */
5512 struct stat sStat; /* Output of stat() on database file */
5513
dana0c989d2010-11-05 18:07:37 +00005514 /* zPath is a path to a WAL or journal file. The following block derives
5515 ** the path to the associated database file from zPath. This block handles
5516 ** the following naming conventions:
5517 **
5518 ** "<path to db>-journal"
5519 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005520 ** "<path to db>-journalNN"
5521 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005522 **
drhd337c5b2011-10-20 18:23:35 +00005523 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005524 ** used by the test_multiplex.c module.
5525 */
5526 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005527#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005528 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005529 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005530#else
5531 while( zPath[nDb]!='-' ){
5532 assert( nDb>0 );
5533 assert( zPath[nDb]!='\n' );
5534 nDb--;
5535 }
5536#endif
danddb0ac42010-07-14 14:48:58 +00005537 memcpy(zDb, zPath, nDb);
5538 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005539
drh58384f12011-07-28 00:14:45 +00005540 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005541 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005542 *pUid = sStat.st_uid;
5543 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005544 }else{
5545 rc = SQLITE_IOERR_FSTAT;
5546 }
5547 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5548 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005549 }
5550 return rc;
5551}
5552
5553/*
danielk1977ad94b582007-08-20 06:44:22 +00005554** Open the file zPath.
5555**
danielk1977b4b47412007-08-17 15:53:36 +00005556** Previously, the SQLite OS layer used three functions in place of this
5557** one:
5558**
5559** sqlite3OsOpenReadWrite();
5560** sqlite3OsOpenReadOnly();
5561** sqlite3OsOpenExclusive();
5562**
5563** These calls correspond to the following combinations of flags:
5564**
5565** ReadWrite() -> (READWRITE | CREATE)
5566** ReadOnly() -> (READONLY)
5567** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5568**
5569** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5570** true, the file was configured to be automatically deleted when the
5571** file handle closed. To achieve the same effect using this new
5572** interface, add the DELETEONCLOSE flag to those specified above for
5573** OpenExclusive().
5574*/
5575static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005576 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5577 const char *zPath, /* Pathname of file to be opened */
5578 sqlite3_file *pFile, /* The file descriptor to be filled in */
5579 int flags, /* Input flags to control the opening */
5580 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005581){
dan08da86a2009-08-21 17:18:03 +00005582 unixFile *p = (unixFile *)pFile;
5583 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005584 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005585 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005586 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005587 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005588 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005589
5590 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5591 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5592 int isCreate = (flags & SQLITE_OPEN_CREATE);
5593 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5594 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005595#if SQLITE_ENABLE_LOCKING_STYLE
5596 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5597#endif
drh3d4435b2011-08-26 20:55:50 +00005598#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5599 struct statfs fsInfo;
5600#endif
danielk1977b4b47412007-08-17 15:53:36 +00005601
danielk1977fee2d252007-08-18 10:59:19 +00005602 /* If creating a master or main-file journal, this function will open
5603 ** a file-descriptor on the directory too. The first time unixSync()
5604 ** is called the directory file descriptor will be fsync()ed and close()d.
5605 */
drh0059eae2011-08-08 23:48:40 +00005606 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005607 eType==SQLITE_OPEN_MASTER_JOURNAL
5608 || eType==SQLITE_OPEN_MAIN_JOURNAL
5609 || eType==SQLITE_OPEN_WAL
5610 ));
danielk1977fee2d252007-08-18 10:59:19 +00005611
danielk197717b90b52008-06-06 11:11:25 +00005612 /* If argument zPath is a NULL pointer, this function is required to open
5613 ** a temporary file. Use this buffer to store the file name in.
5614 */
drhc02a43a2012-01-10 23:18:38 +00005615 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005616 const char *zName = zPath;
5617
danielk1977fee2d252007-08-18 10:59:19 +00005618 /* Check the following statements are true:
5619 **
5620 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5621 ** (b) if CREATE is set, then READWRITE must also be set, and
5622 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005623 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005624 */
danielk1977b4b47412007-08-17 15:53:36 +00005625 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005626 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005627 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005628 assert(isDelete==0 || isCreate);
5629
danddb0ac42010-07-14 14:48:58 +00005630 /* The main DB, main journal, WAL file and master journal are never
5631 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005632 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5633 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5634 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005635 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005636
danielk1977fee2d252007-08-18 10:59:19 +00005637 /* Assert that the upper layer has set one of the "file-type" flags. */
5638 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5639 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5640 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005641 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005642 );
5643
dan08da86a2009-08-21 17:18:03 +00005644 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005645
dan08da86a2009-08-21 17:18:03 +00005646 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005647 UnixUnusedFd *pUnused;
5648 pUnused = findReusableFd(zName, flags);
5649 if( pUnused ){
5650 fd = pUnused->fd;
5651 }else{
dan6aa657f2009-08-24 18:57:58 +00005652 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005653 if( !pUnused ){
5654 return SQLITE_NOMEM;
5655 }
5656 }
5657 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005658
5659 /* Database filenames are double-zero terminated if they are not
5660 ** URIs with parameters. Hence, they can always be passed into
5661 ** sqlite3_uri_parameter(). */
5662 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5663
dan08da86a2009-08-21 17:18:03 +00005664 }else if( !zName ){
5665 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005666 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005667 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005668 if( rc!=SQLITE_OK ){
5669 return rc;
5670 }
5671 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005672
5673 /* Generated temporary filenames are always double-zero terminated
5674 ** for use by sqlite3_uri_parameter(). */
5675 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005676 }
5677
dan08da86a2009-08-21 17:18:03 +00005678 /* Determine the value of the flags parameter passed to POSIX function
5679 ** open(). These must be calculated even if open() is not called, as
5680 ** they may be stored as part of the file handle and used by the
5681 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005682 if( isReadonly ) openFlags |= O_RDONLY;
5683 if( isReadWrite ) openFlags |= O_RDWR;
5684 if( isCreate ) openFlags |= O_CREAT;
5685 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5686 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005687
danielk1977b4b47412007-08-17 15:53:36 +00005688 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005689 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005690 uid_t uid; /* Userid for the file */
5691 gid_t gid; /* Groupid for the file */
5692 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005693 if( rc!=SQLITE_OK ){
5694 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005695 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005696 return rc;
5697 }
drhad4f1e52011-03-04 15:43:57 +00005698 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005699 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005700 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5701 /* Failed to open the file for read/write access. Try read-only. */
5702 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005703 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005704 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005705 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005706 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005707 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005708 }
5709 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005710 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005711 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005712 }
drhac7c3ac2012-02-11 19:23:48 +00005713
5714 /* If this process is running as root and if creating a new rollback
5715 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005716 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005717 */
5718 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005719 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005720 }
danielk1977b4b47412007-08-17 15:53:36 +00005721 }
dan08da86a2009-08-21 17:18:03 +00005722 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005723 if( pOutFlags ){
5724 *pOutFlags = flags;
5725 }
5726
dane946c392009-08-22 11:39:46 +00005727 if( p->pUnused ){
5728 p->pUnused->fd = fd;
5729 p->pUnused->flags = flags;
5730 }
5731
danielk1977b4b47412007-08-17 15:53:36 +00005732 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005733#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005734 zPath = zName;
5735#else
drh036ac7f2011-08-08 23:18:05 +00005736 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005737#endif
danielk1977b4b47412007-08-17 15:53:36 +00005738 }
drh41022642008-11-21 00:24:42 +00005739#if SQLITE_ENABLE_LOCKING_STYLE
5740 else{
dan08da86a2009-08-21 17:18:03 +00005741 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005742 }
5743#endif
5744
drhda0e7682008-07-30 15:27:54 +00005745 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005746
drh7ed97b92010-01-20 13:07:21 +00005747
5748#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005749 if( fstatfs(fd, &fsInfo) == -1 ){
5750 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005751 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005752 return SQLITE_IOERR_ACCESS;
5753 }
5754 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5755 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5756 }
5757#endif
drhc02a43a2012-01-10 23:18:38 +00005758
5759 /* Set up appropriate ctrlFlags */
5760 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5761 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5762 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5763 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5764 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5765
drh7ed97b92010-01-20 13:07:21 +00005766#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005767#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005768 isAutoProxy = 1;
5769#endif
5770 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005771 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5772 int useProxy = 0;
5773
dan08da86a2009-08-21 17:18:03 +00005774 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5775 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005776 if( envforce!=NULL ){
5777 useProxy = atoi(envforce)>0;
5778 }else{
aswiftaebf4132008-11-21 00:10:35 +00005779 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005780 /* In theory, the close(fd) call is sub-optimal. If the file opened
5781 ** with fd is a database file, and there are other connections open
5782 ** on that file that are currently holding advisory locks on it,
5783 ** then the call to close() will cancel those locks. In practice,
5784 ** we're assuming that statfs() doesn't fail very often. At least
5785 ** not while other file descriptors opened by the same process on
5786 ** the same file are working. */
5787 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005788 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005789 rc = SQLITE_IOERR_ACCESS;
5790 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005791 }
5792 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5793 }
5794 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005795 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005796 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005797 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005798 if( rc!=SQLITE_OK ){
5799 /* Use unixClose to clean up the resources added in fillInUnixFile
5800 ** and clear all the structure's references. Specifically,
5801 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5802 */
5803 unixClose(pFile);
5804 return rc;
5805 }
aswiftaebf4132008-11-21 00:10:35 +00005806 }
dane946c392009-08-22 11:39:46 +00005807 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005808 }
5809 }
5810#endif
5811
drhc02a43a2012-01-10 23:18:38 +00005812 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5813
dane946c392009-08-22 11:39:46 +00005814open_finished:
5815 if( rc!=SQLITE_OK ){
5816 sqlite3_free(p->pUnused);
5817 }
5818 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005819}
5820
dane946c392009-08-22 11:39:46 +00005821
danielk1977b4b47412007-08-17 15:53:36 +00005822/*
danielk1977fee2d252007-08-18 10:59:19 +00005823** Delete the file at zPath. If the dirSync argument is true, fsync()
5824** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005825*/
drh6b9d6dd2008-12-03 19:34:47 +00005826static int unixDelete(
5827 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5828 const char *zPath, /* Name of file to be deleted */
5829 int dirSync /* If true, fsync() directory after deleting file */
5830){
danielk1977fee2d252007-08-18 10:59:19 +00005831 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005832 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005833 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005834 if( osUnlink(zPath)==(-1) ){
5835 if( errno==ENOENT ){
5836 rc = SQLITE_IOERR_DELETE_NOENT;
5837 }else{
drhb4308162012-11-09 21:40:02 +00005838 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005839 }
drhb4308162012-11-09 21:40:02 +00005840 return rc;
drh5d4feff2010-07-14 01:45:22 +00005841 }
danielk1977d39fa702008-10-16 13:27:40 +00005842#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005843 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005844 int fd;
drh90315a22011-08-10 01:52:12 +00005845 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005846 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005847#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005848 if( fsync(fd)==-1 )
5849#else
5850 if( fsync(fd) )
5851#endif
5852 {
dane18d4952011-02-21 11:46:24 +00005853 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005854 }
drh0e9365c2011-03-02 02:08:13 +00005855 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005856 }else if( rc==SQLITE_CANTOPEN ){
5857 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005858 }
5859 }
danielk1977d138dd82008-10-15 16:02:48 +00005860#endif
danielk1977fee2d252007-08-18 10:59:19 +00005861 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005862}
5863
danielk197790949c22007-08-17 16:50:38 +00005864/*
mistachkin48864df2013-03-21 21:20:32 +00005865** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005866** test performed depends on the value of flags:
5867**
5868** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5869** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5870** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5871**
5872** Otherwise return 0.
5873*/
danielk1977861f7452008-06-05 11:39:11 +00005874static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005875 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5876 const char *zPath, /* Path of the file to examine */
5877 int flags, /* What do we want to learn about the zPath file? */
5878 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005879){
rse25c0d1a2007-09-20 08:38:14 +00005880 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005881 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005882 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005883 switch( flags ){
5884 case SQLITE_ACCESS_EXISTS:
5885 amode = F_OK;
5886 break;
5887 case SQLITE_ACCESS_READWRITE:
5888 amode = W_OK|R_OK;
5889 break;
drh50d3f902007-08-27 21:10:36 +00005890 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005891 amode = R_OK;
5892 break;
5893
5894 default:
5895 assert(!"Invalid flags argument");
5896 }
drh99ab3b12011-03-02 15:09:07 +00005897 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005898 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5899 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005900 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005901 *pResOut = 0;
5902 }
5903 }
danielk1977861f7452008-06-05 11:39:11 +00005904 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005905}
5906
danielk1977b4b47412007-08-17 15:53:36 +00005907
5908/*
5909** Turn a relative pathname into a full pathname. The relative path
5910** is stored as a nul-terminated string in the buffer pointed to by
5911** zPath.
5912**
5913** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5914** (in this case, MAX_PATHNAME bytes). The full-path is written to
5915** this buffer before returning.
5916*/
danielk1977adfb9b02007-09-17 07:02:56 +00005917static int unixFullPathname(
5918 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5919 const char *zPath, /* Possibly relative input path */
5920 int nOut, /* Size of output buffer in bytes */
5921 char *zOut /* Output buffer */
5922){
danielk1977843e65f2007-09-01 16:16:15 +00005923
5924 /* It's odd to simulate an io-error here, but really this is just
5925 ** using the io-error infrastructure to test that SQLite handles this
5926 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005927 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005928 */
5929 SimulateIOError( return SQLITE_ERROR );
5930
drh153c62c2007-08-24 03:51:33 +00005931 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005932 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005933
drh3c7f2dc2007-12-06 13:26:20 +00005934 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005935 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005936 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005937 }else{
5938 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005939 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005940 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005941 }
drhea678832008-12-10 19:26:22 +00005942 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005943 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005944 }
5945 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005946}
5947
drh0ccebe72005-06-07 22:22:50 +00005948
drh761df872006-12-21 01:29:22 +00005949#ifndef SQLITE_OMIT_LOAD_EXTENSION
5950/*
5951** Interfaces for opening a shared library, finding entry points
5952** within the shared library, and closing the shared library.
5953*/
5954#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005955static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5956 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005957 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5958}
danielk197795c8a542007-09-01 06:51:27 +00005959
5960/*
5961** SQLite calls this function immediately after a call to unixDlSym() or
5962** unixDlOpen() fails (returns a null pointer). If a more detailed error
5963** message is available, it is written to zBufOut. If no error message
5964** is available, zBufOut is left unmodified and SQLite uses a default
5965** error message.
5966*/
danielk1977397d65f2008-11-19 11:35:39 +00005967static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005968 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005969 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005970 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005971 zErr = dlerror();
5972 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005973 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005974 }
drh6c7d5c52008-11-21 20:32:33 +00005975 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005976}
drh1875f7a2008-12-08 18:19:17 +00005977static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5978 /*
5979 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5980 ** cast into a pointer to a function. And yet the library dlsym() routine
5981 ** returns a void* which is really a pointer to a function. So how do we
5982 ** use dlsym() with -pedantic-errors?
5983 **
5984 ** Variable x below is defined to be a pointer to a function taking
5985 ** parameters void* and const char* and returning a pointer to a function.
5986 ** We initialize x by assigning it a pointer to the dlsym() function.
5987 ** (That assignment requires a cast.) Then we call the function that
5988 ** x points to.
5989 **
5990 ** This work-around is unlikely to work correctly on any system where
5991 ** you really cannot cast a function pointer into void*. But then, on the
5992 ** other hand, dlsym() will not work on such a system either, so we have
5993 ** not really lost anything.
5994 */
5995 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005996 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005997 x = (void(*(*)(void*,const char*))(void))dlsym;
5998 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005999}
danielk1977397d65f2008-11-19 11:35:39 +00006000static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6001 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006002 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006003}
danielk1977b4b47412007-08-17 15:53:36 +00006004#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6005 #define unixDlOpen 0
6006 #define unixDlError 0
6007 #define unixDlSym 0
6008 #define unixDlClose 0
6009#endif
6010
6011/*
danielk197790949c22007-08-17 16:50:38 +00006012** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006013*/
danielk1977397d65f2008-11-19 11:35:39 +00006014static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6015 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006016 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006017
drhbbd42a62004-05-22 17:41:58 +00006018 /* We have to initialize zBuf to prevent valgrind from reporting
6019 ** errors. The reports issued by valgrind are incorrect - we would
6020 ** prefer that the randomness be increased by making use of the
6021 ** uninitialized space in zBuf - but valgrind errors tend to worry
6022 ** some users. Rather than argue, it seems easier just to initialize
6023 ** the whole array and silence valgrind, even if that means less randomness
6024 ** in the random seed.
6025 **
6026 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006027 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006028 ** tests repeatable.
6029 */
danielk1977b4b47412007-08-17 15:53:36 +00006030 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00006031#if !defined(SQLITE_TEST)
6032 {
drhc18b4042012-02-10 03:10:27 +00006033 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00006034 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006035 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006036 time_t t;
6037 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006038 memcpy(zBuf, &t, sizeof(t));
6039 pid = getpid();
6040 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00006041 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00006042 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00006043 }else{
drhc18b4042012-02-10 03:10:27 +00006044 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006045 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006046 }
drhbbd42a62004-05-22 17:41:58 +00006047 }
6048#endif
drh72cbd072008-10-14 17:58:38 +00006049 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006050}
6051
danielk1977b4b47412007-08-17 15:53:36 +00006052
drhbbd42a62004-05-22 17:41:58 +00006053/*
6054** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006055** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006056** The return value is the number of microseconds of sleep actually
6057** requested from the underlying operating system, a number which
6058** might be greater than or equal to the argument, but not less
6059** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006060*/
danielk1977397d65f2008-11-19 11:35:39 +00006061static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006062#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006063 struct timespec sp;
6064
6065 sp.tv_sec = microseconds / 1000000;
6066 sp.tv_nsec = (microseconds % 1000000) * 1000;
6067 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006068 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006069 return microseconds;
6070#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006071 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006072 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006073 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006074#else
danielk1977b4b47412007-08-17 15:53:36 +00006075 int seconds = (microseconds+999999)/1000000;
6076 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006077 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006078 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006079#endif
drh88f474a2006-01-02 20:00:12 +00006080}
6081
6082/*
drh6b9d6dd2008-12-03 19:34:47 +00006083** The following variable, if set to a non-zero value, is interpreted as
6084** the number of seconds since 1970 and is used to set the result of
6085** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006086*/
6087#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006088int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006089#endif
6090
6091/*
drhb7e8ea22010-05-03 14:32:30 +00006092** Find the current time (in Universal Coordinated Time). Write into *piNow
6093** the current time and date as a Julian Day number times 86_400_000. In
6094** other words, write into *piNow the number of milliseconds since the Julian
6095** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6096** proleptic Gregorian calendar.
6097**
drh31702252011-10-12 23:13:43 +00006098** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6099** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006100*/
6101static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6102 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006103 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006104#if defined(NO_GETTOD)
6105 time_t t;
6106 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006107 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006108#elif OS_VXWORKS
6109 struct timespec sNow;
6110 clock_gettime(CLOCK_REALTIME, &sNow);
6111 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6112#else
6113 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006114 if( gettimeofday(&sNow, 0)==0 ){
6115 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6116 }else{
6117 rc = SQLITE_ERROR;
6118 }
drhb7e8ea22010-05-03 14:32:30 +00006119#endif
6120
6121#ifdef SQLITE_TEST
6122 if( sqlite3_current_time ){
6123 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6124 }
6125#endif
6126 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006127 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006128}
6129
6130/*
drhbbd42a62004-05-22 17:41:58 +00006131** Find the current time (in Universal Coordinated Time). Write the
6132** current time and date as a Julian Day number into *prNow and
6133** return 0. Return 1 if the time and date cannot be found.
6134*/
danielk1977397d65f2008-11-19 11:35:39 +00006135static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006136 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006137 int rc;
drhff828942010-06-26 21:34:06 +00006138 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006139 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006140 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006141 return rc;
drhbbd42a62004-05-22 17:41:58 +00006142}
danielk1977b4b47412007-08-17 15:53:36 +00006143
drh6b9d6dd2008-12-03 19:34:47 +00006144/*
6145** We added the xGetLastError() method with the intention of providing
6146** better low-level error messages when operating-system problems come up
6147** during SQLite operation. But so far, none of that has been implemented
6148** in the core. So this routine is never called. For now, it is merely
6149** a place-holder.
6150*/
danielk1977397d65f2008-11-19 11:35:39 +00006151static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6152 UNUSED_PARAMETER(NotUsed);
6153 UNUSED_PARAMETER(NotUsed2);
6154 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006155 return 0;
6156}
6157
drhf2424c52010-04-26 00:04:55 +00006158
6159/*
drh734c9862008-11-28 15:37:20 +00006160************************ End of sqlite3_vfs methods ***************************
6161******************************************************************************/
6162
drh715ff302008-12-03 22:32:44 +00006163/******************************************************************************
6164************************** Begin Proxy Locking ********************************
6165**
6166** Proxy locking is a "uber-locking-method" in this sense: It uses the
6167** other locking methods on secondary lock files. Proxy locking is a
6168** meta-layer over top of the primitive locking implemented above. For
6169** this reason, the division that implements of proxy locking is deferred
6170** until late in the file (here) after all of the other I/O methods have
6171** been defined - so that the primitive locking methods are available
6172** as services to help with the implementation of proxy locking.
6173**
6174****
6175**
6176** The default locking schemes in SQLite use byte-range locks on the
6177** database file to coordinate safe, concurrent access by multiple readers
6178** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6179** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6180** as POSIX read & write locks over fixed set of locations (via fsctl),
6181** on AFP and SMB only exclusive byte-range locks are available via fsctl
6182** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6183** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6184** address in the shared range is taken for a SHARED lock, the entire
6185** shared range is taken for an EXCLUSIVE lock):
6186**
drhf2f105d2012-08-20 15:53:54 +00006187** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006188** RESERVED_BYTE 0x40000001
6189** SHARED_RANGE 0x40000002 -> 0x40000200
6190**
6191** This works well on the local file system, but shows a nearly 100x
6192** slowdown in read performance on AFP because the AFP client disables
6193** the read cache when byte-range locks are present. Enabling the read
6194** cache exposes a cache coherency problem that is present on all OS X
6195** supported network file systems. NFS and AFP both observe the
6196** close-to-open semantics for ensuring cache coherency
6197** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6198** address the requirements for concurrent database access by multiple
6199** readers and writers
6200** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6201**
6202** To address the performance and cache coherency issues, proxy file locking
6203** changes the way database access is controlled by limiting access to a
6204** single host at a time and moving file locks off of the database file
6205** and onto a proxy file on the local file system.
6206**
6207**
6208** Using proxy locks
6209** -----------------
6210**
6211** C APIs
6212**
6213** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6214** <proxy_path> | ":auto:");
6215** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6216**
6217**
6218** SQL pragmas
6219**
6220** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6221** PRAGMA [database.]lock_proxy_file
6222**
6223** Specifying ":auto:" means that if there is a conch file with a matching
6224** host ID in it, the proxy path in the conch file will be used, otherwise
6225** a proxy path based on the user's temp dir
6226** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6227** actual proxy file name is generated from the name and path of the
6228** database file. For example:
6229**
6230** For database path "/Users/me/foo.db"
6231** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6232**
6233** Once a lock proxy is configured for a database connection, it can not
6234** be removed, however it may be switched to a different proxy path via
6235** the above APIs (assuming the conch file is not being held by another
6236** connection or process).
6237**
6238**
6239** How proxy locking works
6240** -----------------------
6241**
6242** Proxy file locking relies primarily on two new supporting files:
6243**
6244** * conch file to limit access to the database file to a single host
6245** at a time
6246**
6247** * proxy file to act as a proxy for the advisory locks normally
6248** taken on the database
6249**
6250** The conch file - to use a proxy file, sqlite must first "hold the conch"
6251** by taking an sqlite-style shared lock on the conch file, reading the
6252** contents and comparing the host's unique host ID (see below) and lock
6253** proxy path against the values stored in the conch. The conch file is
6254** stored in the same directory as the database file and the file name
6255** is patterned after the database file name as ".<databasename>-conch".
6256** If the conch file does not exist, or it's contents do not match the
6257** host ID and/or proxy path, then the lock is escalated to an exclusive
6258** lock and the conch file contents is updated with the host ID and proxy
6259** path and the lock is downgraded to a shared lock again. If the conch
6260** is held by another process (with a shared lock), the exclusive lock
6261** will fail and SQLITE_BUSY is returned.
6262**
6263** The proxy file - a single-byte file used for all advisory file locks
6264** normally taken on the database file. This allows for safe sharing
6265** of the database file for multiple readers and writers on the same
6266** host (the conch ensures that they all use the same local lock file).
6267**
drh715ff302008-12-03 22:32:44 +00006268** Requesting the lock proxy does not immediately take the conch, it is
6269** only taken when the first request to lock database file is made.
6270** This matches the semantics of the traditional locking behavior, where
6271** opening a connection to a database file does not take a lock on it.
6272** The shared lock and an open file descriptor are maintained until
6273** the connection to the database is closed.
6274**
6275** The proxy file and the lock file are never deleted so they only need
6276** to be created the first time they are used.
6277**
6278** Configuration options
6279** ---------------------
6280**
6281** SQLITE_PREFER_PROXY_LOCKING
6282**
6283** Database files accessed on non-local file systems are
6284** automatically configured for proxy locking, lock files are
6285** named automatically using the same logic as
6286** PRAGMA lock_proxy_file=":auto:"
6287**
6288** SQLITE_PROXY_DEBUG
6289**
6290** Enables the logging of error messages during host id file
6291** retrieval and creation
6292**
drh715ff302008-12-03 22:32:44 +00006293** LOCKPROXYDIR
6294**
6295** Overrides the default directory used for lock proxy files that
6296** are named automatically via the ":auto:" setting
6297**
6298** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6299**
6300** Permissions to use when creating a directory for storing the
6301** lock proxy files, only used when LOCKPROXYDIR is not set.
6302**
6303**
6304** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6305** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6306** force proxy locking to be used for every database file opened, and 0
6307** will force automatic proxy locking to be disabled for all database
6308** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6309** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6310*/
6311
6312/*
6313** Proxy locking is only available on MacOSX
6314*/
drhd2cb50b2009-01-09 21:41:17 +00006315#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006316
drh715ff302008-12-03 22:32:44 +00006317/*
6318** The proxyLockingContext has the path and file structures for the remote
6319** and local proxy files in it
6320*/
6321typedef struct proxyLockingContext proxyLockingContext;
6322struct proxyLockingContext {
6323 unixFile *conchFile; /* Open conch file */
6324 char *conchFilePath; /* Name of the conch file */
6325 unixFile *lockProxy; /* Open proxy lock file */
6326 char *lockProxyPath; /* Name of the proxy lock file */
6327 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006328 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006329 void *oldLockingContext; /* Original lockingcontext to restore on close */
6330 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6331};
6332
drh7ed97b92010-01-20 13:07:21 +00006333/*
6334** The proxy lock file path for the database at dbPath is written into lPath,
6335** which must point to valid, writable memory large enough for a maxLen length
6336** file path.
drh715ff302008-12-03 22:32:44 +00006337*/
drh715ff302008-12-03 22:32:44 +00006338static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6339 int len;
6340 int dbLen;
6341 int i;
6342
6343#ifdef LOCKPROXYDIR
6344 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6345#else
6346# ifdef _CS_DARWIN_USER_TEMP_DIR
6347 {
drh7ed97b92010-01-20 13:07:21 +00006348 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006349 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6350 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006351 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006352 }
drh7ed97b92010-01-20 13:07:21 +00006353 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006354 }
6355# else
6356 len = strlcpy(lPath, "/tmp/", maxLen);
6357# endif
6358#endif
6359
6360 if( lPath[len-1]!='/' ){
6361 len = strlcat(lPath, "/", maxLen);
6362 }
6363
6364 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006365 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006366 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006367 char c = dbPath[i];
6368 lPath[i+len] = (c=='/')?'_':c;
6369 }
6370 lPath[i+len]='\0';
6371 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006372 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006373 return SQLITE_OK;
6374}
6375
drh7ed97b92010-01-20 13:07:21 +00006376/*
6377 ** Creates the lock file and any missing directories in lockPath
6378 */
6379static int proxyCreateLockPath(const char *lockPath){
6380 int i, len;
6381 char buf[MAXPATHLEN];
6382 int start = 0;
6383
6384 assert(lockPath!=NULL);
6385 /* try to create all the intermediate directories */
6386 len = (int)strlen(lockPath);
6387 buf[0] = lockPath[0];
6388 for( i=1; i<len; i++ ){
6389 if( lockPath[i] == '/' && (i - start > 0) ){
6390 /* only mkdir if leaf dir != "." or "/" or ".." */
6391 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6392 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6393 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006394 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006395 int err=errno;
6396 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006397 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006398 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006399 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006400 return err;
6401 }
6402 }
6403 }
6404 start=i+1;
6405 }
6406 buf[i] = lockPath[i];
6407 }
drh308c2a52010-05-14 11:30:18 +00006408 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006409 return 0;
6410}
6411
drh715ff302008-12-03 22:32:44 +00006412/*
6413** Create a new VFS file descriptor (stored in memory obtained from
6414** sqlite3_malloc) and open the file named "path" in the file descriptor.
6415**
6416** The caller is responsible not only for closing the file descriptor
6417** but also for freeing the memory associated with the file descriptor.
6418*/
drh7ed97b92010-01-20 13:07:21 +00006419static int proxyCreateUnixFile(
6420 const char *path, /* path for the new unixFile */
6421 unixFile **ppFile, /* unixFile created and returned by ref */
6422 int islockfile /* if non zero missing dirs will be created */
6423) {
6424 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006425 unixFile *pNew;
6426 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006427 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006428 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006429 int terrno = 0;
6430 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006431
drh7ed97b92010-01-20 13:07:21 +00006432 /* 1. first try to open/create the file
6433 ** 2. if that fails, and this is a lock file (not-conch), try creating
6434 ** the parent directories and then try again.
6435 ** 3. if that fails, try to open the file read-only
6436 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6437 */
6438 pUnused = findReusableFd(path, openFlags);
6439 if( pUnused ){
6440 fd = pUnused->fd;
6441 }else{
6442 pUnused = sqlite3_malloc(sizeof(*pUnused));
6443 if( !pUnused ){
6444 return SQLITE_NOMEM;
6445 }
6446 }
6447 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006448 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006449 terrno = errno;
6450 if( fd<0 && errno==ENOENT && islockfile ){
6451 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006452 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006453 }
6454 }
6455 }
6456 if( fd<0 ){
6457 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006458 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006459 terrno = errno;
6460 }
6461 if( fd<0 ){
6462 if( islockfile ){
6463 return SQLITE_BUSY;
6464 }
6465 switch (terrno) {
6466 case EACCES:
6467 return SQLITE_PERM;
6468 case EIO:
6469 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6470 default:
drh9978c972010-02-23 17:36:32 +00006471 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006472 }
6473 }
6474
6475 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6476 if( pNew==NULL ){
6477 rc = SQLITE_NOMEM;
6478 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006479 }
6480 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006481 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006482 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006483 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006484 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006485 pUnused->fd = fd;
6486 pUnused->flags = openFlags;
6487 pNew->pUnused = pUnused;
6488
drhc02a43a2012-01-10 23:18:38 +00006489 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006490 if( rc==SQLITE_OK ){
6491 *ppFile = pNew;
6492 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006493 }
drh7ed97b92010-01-20 13:07:21 +00006494end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006495 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006496 sqlite3_free(pNew);
6497 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006498 return rc;
6499}
6500
drh7ed97b92010-01-20 13:07:21 +00006501#ifdef SQLITE_TEST
6502/* simulate multiple hosts by creating unique hostid file paths */
6503int sqlite3_hostid_num = 0;
6504#endif
6505
6506#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6507
drh0ab216a2010-07-02 17:10:40 +00006508/* Not always defined in the headers as it ought to be */
6509extern int gethostuuid(uuid_t id, const struct timespec *wait);
6510
drh7ed97b92010-01-20 13:07:21 +00006511/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6512** bytes of writable memory.
6513*/
6514static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006515 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6516 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006517#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6518 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006519 {
6520 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6521 if( gethostuuid(pHostID, &timeout) ){
6522 int err = errno;
6523 if( pError ){
6524 *pError = err;
6525 }
6526 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006527 }
drh7ed97b92010-01-20 13:07:21 +00006528 }
drh3d4435b2011-08-26 20:55:50 +00006529#else
6530 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006531#endif
drh7ed97b92010-01-20 13:07:21 +00006532#ifdef SQLITE_TEST
6533 /* simulate multiple hosts by creating unique hostid file paths */
6534 if( sqlite3_hostid_num != 0){
6535 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6536 }
6537#endif
6538
6539 return SQLITE_OK;
6540}
6541
6542/* The conch file contains the header, host id and lock file path
6543 */
6544#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6545#define PROXY_HEADERLEN 1 /* conch file header length */
6546#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6547#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6548
6549/*
6550** Takes an open conch file, copies the contents to a new path and then moves
6551** it back. The newly created file's file descriptor is assigned to the
6552** conch file structure and finally the original conch file descriptor is
6553** closed. Returns zero if successful.
6554*/
6555static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6556 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6557 unixFile *conchFile = pCtx->conchFile;
6558 char tPath[MAXPATHLEN];
6559 char buf[PROXY_MAXCONCHLEN];
6560 char *cPath = pCtx->conchFilePath;
6561 size_t readLen = 0;
6562 size_t pathLen = 0;
6563 char errmsg[64] = "";
6564 int fd = -1;
6565 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006566 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006567
6568 /* create a new path by replace the trailing '-conch' with '-break' */
6569 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6570 if( pathLen>MAXPATHLEN || pathLen<6 ||
6571 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006572 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006573 goto end_breaklock;
6574 }
6575 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006576 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006577 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006578 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006579 goto end_breaklock;
6580 }
6581 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006582 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006583 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006584 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006585 goto end_breaklock;
6586 }
drhe562be52011-03-02 18:01:10 +00006587 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006588 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006589 goto end_breaklock;
6590 }
6591 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006592 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006593 goto end_breaklock;
6594 }
6595 rc = 0;
6596 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006597 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006598 conchFile->h = fd;
6599 conchFile->openFlags = O_RDWR | O_CREAT;
6600
6601end_breaklock:
6602 if( rc ){
6603 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006604 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006605 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006606 }
6607 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6608 }
6609 return rc;
6610}
6611
6612/* Take the requested lock on the conch file and break a stale lock if the
6613** host id matches.
6614*/
6615static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6616 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6617 unixFile *conchFile = pCtx->conchFile;
6618 int rc = SQLITE_OK;
6619 int nTries = 0;
6620 struct timespec conchModTime;
6621
drh3d4435b2011-08-26 20:55:50 +00006622 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006623 do {
6624 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6625 nTries ++;
6626 if( rc==SQLITE_BUSY ){
6627 /* If the lock failed (busy):
6628 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6629 * 2nd try: fail if the mod time changed or host id is different, wait
6630 * 10 sec and try again
6631 * 3rd try: break the lock unless the mod time has changed.
6632 */
6633 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006634 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006635 pFile->lastErrno = errno;
6636 return SQLITE_IOERR_LOCK;
6637 }
6638
6639 if( nTries==1 ){
6640 conchModTime = buf.st_mtimespec;
6641 usleep(500000); /* wait 0.5 sec and try the lock again*/
6642 continue;
6643 }
6644
6645 assert( nTries>1 );
6646 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6647 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6648 return SQLITE_BUSY;
6649 }
6650
6651 if( nTries==2 ){
6652 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006653 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006654 if( len<0 ){
6655 pFile->lastErrno = errno;
6656 return SQLITE_IOERR_LOCK;
6657 }
6658 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6659 /* don't break the lock if the host id doesn't match */
6660 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6661 return SQLITE_BUSY;
6662 }
6663 }else{
6664 /* don't break the lock on short read or a version mismatch */
6665 return SQLITE_BUSY;
6666 }
6667 usleep(10000000); /* wait 10 sec and try the lock again */
6668 continue;
6669 }
6670
6671 assert( nTries==3 );
6672 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6673 rc = SQLITE_OK;
6674 if( lockType==EXCLUSIVE_LOCK ){
6675 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6676 }
6677 if( !rc ){
6678 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6679 }
6680 }
6681 }
6682 } while( rc==SQLITE_BUSY && nTries<3 );
6683
6684 return rc;
6685}
6686
6687/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006688** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6689** lockPath means that the lockPath in the conch file will be used if the
6690** host IDs match, or a new lock path will be generated automatically
6691** and written to the conch file.
6692*/
6693static int proxyTakeConch(unixFile *pFile){
6694 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6695
drh7ed97b92010-01-20 13:07:21 +00006696 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006697 return SQLITE_OK;
6698 }else{
6699 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006700 uuid_t myHostID;
6701 int pError = 0;
6702 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006703 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006704 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006705 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006706 int createConch = 0;
6707 int hostIdMatch = 0;
6708 int readLen = 0;
6709 int tryOldLockPath = 0;
6710 int forceNewLockPath = 0;
6711
drh308c2a52010-05-14 11:30:18 +00006712 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6713 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006714
drh7ed97b92010-01-20 13:07:21 +00006715 rc = proxyGetHostID(myHostID, &pError);
6716 if( (rc&0xff)==SQLITE_IOERR ){
6717 pFile->lastErrno = pError;
6718 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006719 }
drh7ed97b92010-01-20 13:07:21 +00006720 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006721 if( rc!=SQLITE_OK ){
6722 goto end_takeconch;
6723 }
drh7ed97b92010-01-20 13:07:21 +00006724 /* read the existing conch file */
6725 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6726 if( readLen<0 ){
6727 /* I/O error: lastErrno set by seekAndRead */
6728 pFile->lastErrno = conchFile->lastErrno;
6729 rc = SQLITE_IOERR_READ;
6730 goto end_takeconch;
6731 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6732 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6733 /* a short read or version format mismatch means we need to create a new
6734 ** conch file.
6735 */
6736 createConch = 1;
6737 }
6738 /* if the host id matches and the lock path already exists in the conch
6739 ** we'll try to use the path there, if we can't open that path, we'll
6740 ** retry with a new auto-generated path
6741 */
6742 do { /* in case we need to try again for an :auto: named lock file */
6743
6744 if( !createConch && !forceNewLockPath ){
6745 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6746 PROXY_HOSTIDLEN);
6747 /* if the conch has data compare the contents */
6748 if( !pCtx->lockProxyPath ){
6749 /* for auto-named local lock file, just check the host ID and we'll
6750 ** use the local lock file path that's already in there
6751 */
6752 if( hostIdMatch ){
6753 size_t pathLen = (readLen - PROXY_PATHINDEX);
6754
6755 if( pathLen>=MAXPATHLEN ){
6756 pathLen=MAXPATHLEN-1;
6757 }
6758 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6759 lockPath[pathLen] = 0;
6760 tempLockPath = lockPath;
6761 tryOldLockPath = 1;
6762 /* create a copy of the lock path if the conch is taken */
6763 goto end_takeconch;
6764 }
6765 }else if( hostIdMatch
6766 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6767 readLen-PROXY_PATHINDEX)
6768 ){
6769 /* conch host and lock path match */
6770 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006771 }
drh7ed97b92010-01-20 13:07:21 +00006772 }
6773
6774 /* if the conch isn't writable and doesn't match, we can't take it */
6775 if( (conchFile->openFlags&O_RDWR) == 0 ){
6776 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006777 goto end_takeconch;
6778 }
drh7ed97b92010-01-20 13:07:21 +00006779
6780 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006781 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006782 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6783 tempLockPath = lockPath;
6784 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006785 }
drh7ed97b92010-01-20 13:07:21 +00006786
6787 /* update conch with host and path (this will fail if other process
6788 ** has a shared lock already), if the host id matches, use the big
6789 ** stick.
drh715ff302008-12-03 22:32:44 +00006790 */
drh7ed97b92010-01-20 13:07:21 +00006791 futimes(conchFile->h, NULL);
6792 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006793 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006794 /* We are trying for an exclusive lock but another thread in this
6795 ** same process is still holding a shared lock. */
6796 rc = SQLITE_BUSY;
6797 } else {
6798 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006799 }
drh715ff302008-12-03 22:32:44 +00006800 }else{
drh7ed97b92010-01-20 13:07:21 +00006801 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006802 }
drh7ed97b92010-01-20 13:07:21 +00006803 if( rc==SQLITE_OK ){
6804 char writeBuffer[PROXY_MAXCONCHLEN];
6805 int writeSize = 0;
6806
6807 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6808 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6809 if( pCtx->lockProxyPath!=NULL ){
6810 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6811 }else{
6812 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6813 }
6814 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006815 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006816 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6817 fsync(conchFile->h);
6818 /* If we created a new conch file (not just updated the contents of a
6819 ** valid conch file), try to match the permissions of the database
6820 */
6821 if( rc==SQLITE_OK && createConch ){
6822 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006823 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006824 if( err==0 ){
6825 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6826 S_IROTH|S_IWOTH);
6827 /* try to match the database file R/W permissions, ignore failure */
6828#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006829 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006830#else
drhff812312011-02-23 13:33:46 +00006831 do{
drhe562be52011-03-02 18:01:10 +00006832 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006833 }while( rc==(-1) && errno==EINTR );
6834 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006835 int code = errno;
6836 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6837 cmode, code, strerror(code));
6838 } else {
6839 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6840 }
6841 }else{
6842 int code = errno;
6843 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6844 err, code, strerror(code));
6845#endif
6846 }
drh715ff302008-12-03 22:32:44 +00006847 }
6848 }
drh7ed97b92010-01-20 13:07:21 +00006849 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6850
6851 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006852 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006853 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006854 int fd;
drh7ed97b92010-01-20 13:07:21 +00006855 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006856 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006857 }
6858 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006859 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006860 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006861 if( fd>=0 ){
6862 pFile->h = fd;
6863 }else{
drh9978c972010-02-23 17:36:32 +00006864 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006865 during locking */
6866 }
6867 }
6868 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6869 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6870 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6871 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6872 /* we couldn't create the proxy lock file with the old lock file path
6873 ** so try again via auto-naming
6874 */
6875 forceNewLockPath = 1;
6876 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006877 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006878 }
6879 }
6880 if( rc==SQLITE_OK ){
6881 /* Need to make a copy of path if we extracted the value
6882 ** from the conch file or the path was allocated on the stack
6883 */
6884 if( tempLockPath ){
6885 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6886 if( !pCtx->lockProxyPath ){
6887 rc = SQLITE_NOMEM;
6888 }
6889 }
6890 }
6891 if( rc==SQLITE_OK ){
6892 pCtx->conchHeld = 1;
6893
6894 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6895 afpLockingContext *afpCtx;
6896 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6897 afpCtx->dbPath = pCtx->lockProxyPath;
6898 }
6899 } else {
6900 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6901 }
drh308c2a52010-05-14 11:30:18 +00006902 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6903 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006904 return rc;
drh308c2a52010-05-14 11:30:18 +00006905 } while (1); /* in case we need to retry the :auto: lock file -
6906 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006907 }
6908}
6909
6910/*
6911** If pFile holds a lock on a conch file, then release that lock.
6912*/
6913static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006914 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006915 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6916 unixFile *conchFile; /* Name of the conch file */
6917
6918 pCtx = (proxyLockingContext *)pFile->lockingContext;
6919 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006920 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006921 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006922 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006923 if( pCtx->conchHeld>0 ){
6924 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6925 }
drh715ff302008-12-03 22:32:44 +00006926 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006927 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6928 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006929 return rc;
6930}
6931
6932/*
6933** Given the name of a database file, compute the name of its conch file.
6934** Store the conch filename in memory obtained from sqlite3_malloc().
6935** Make *pConchPath point to the new name. Return SQLITE_OK on success
6936** or SQLITE_NOMEM if unable to obtain memory.
6937**
6938** The caller is responsible for ensuring that the allocated memory
6939** space is eventually freed.
6940**
6941** *pConchPath is set to NULL if a memory allocation error occurs.
6942*/
6943static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6944 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006945 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006946 char *conchPath; /* buffer in which to construct conch name */
6947
6948 /* Allocate space for the conch filename and initialize the name to
6949 ** the name of the original database file. */
6950 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6951 if( conchPath==0 ){
6952 return SQLITE_NOMEM;
6953 }
6954 memcpy(conchPath, dbPath, len+1);
6955
6956 /* now insert a "." before the last / character */
6957 for( i=(len-1); i>=0; i-- ){
6958 if( conchPath[i]=='/' ){
6959 i++;
6960 break;
6961 }
6962 }
6963 conchPath[i]='.';
6964 while ( i<len ){
6965 conchPath[i+1]=dbPath[i];
6966 i++;
6967 }
6968
6969 /* append the "-conch" suffix to the file */
6970 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006971 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006972
6973 return SQLITE_OK;
6974}
6975
6976
6977/* Takes a fully configured proxy locking-style unix file and switches
6978** the local lock file path
6979*/
6980static int switchLockProxyPath(unixFile *pFile, const char *path) {
6981 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6982 char *oldPath = pCtx->lockProxyPath;
6983 int rc = SQLITE_OK;
6984
drh308c2a52010-05-14 11:30:18 +00006985 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006986 return SQLITE_BUSY;
6987 }
6988
6989 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6990 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6991 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6992 return SQLITE_OK;
6993 }else{
6994 unixFile *lockProxy = pCtx->lockProxy;
6995 pCtx->lockProxy=NULL;
6996 pCtx->conchHeld = 0;
6997 if( lockProxy!=NULL ){
6998 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6999 if( rc ) return rc;
7000 sqlite3_free(lockProxy);
7001 }
7002 sqlite3_free(oldPath);
7003 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7004 }
7005
7006 return rc;
7007}
7008
7009/*
7010** pFile is a file that has been opened by a prior xOpen call. dbPath
7011** is a string buffer at least MAXPATHLEN+1 characters in size.
7012**
7013** This routine find the filename associated with pFile and writes it
7014** int dbPath.
7015*/
7016static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007017#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007018 if( pFile->pMethod == &afpIoMethods ){
7019 /* afp style keeps a reference to the db path in the filePath field
7020 ** of the struct */
drhea678832008-12-10 19:26:22 +00007021 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007022 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
7023 } else
drh715ff302008-12-03 22:32:44 +00007024#endif
7025 if( pFile->pMethod == &dotlockIoMethods ){
7026 /* dot lock style uses the locking context to store the dot lock
7027 ** file path */
7028 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7029 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7030 }else{
7031 /* all other styles use the locking context to store the db file path */
7032 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007033 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007034 }
7035 return SQLITE_OK;
7036}
7037
7038/*
7039** Takes an already filled in unix file and alters it so all file locking
7040** will be performed on the local proxy lock file. The following fields
7041** are preserved in the locking context so that they can be restored and
7042** the unix structure properly cleaned up at close time:
7043** ->lockingContext
7044** ->pMethod
7045*/
7046static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7047 proxyLockingContext *pCtx;
7048 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7049 char *lockPath=NULL;
7050 int rc = SQLITE_OK;
7051
drh308c2a52010-05-14 11:30:18 +00007052 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007053 return SQLITE_BUSY;
7054 }
7055 proxyGetDbPathForUnixFile(pFile, dbPath);
7056 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7057 lockPath=NULL;
7058 }else{
7059 lockPath=(char *)path;
7060 }
7061
drh308c2a52010-05-14 11:30:18 +00007062 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7063 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007064
7065 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7066 if( pCtx==0 ){
7067 return SQLITE_NOMEM;
7068 }
7069 memset(pCtx, 0, sizeof(*pCtx));
7070
7071 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7072 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007073 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7074 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7075 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7076 ** (c) the file system is read-only, then enable no-locking access.
7077 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7078 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7079 */
7080 struct statfs fsInfo;
7081 struct stat conchInfo;
7082 int goLockless = 0;
7083
drh99ab3b12011-03-02 15:09:07 +00007084 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007085 int err = errno;
7086 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7087 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7088 }
7089 }
7090 if( goLockless ){
7091 pCtx->conchHeld = -1; /* read only FS/ lockless */
7092 rc = SQLITE_OK;
7093 }
7094 }
drh715ff302008-12-03 22:32:44 +00007095 }
7096 if( rc==SQLITE_OK && lockPath ){
7097 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7098 }
7099
7100 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007101 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7102 if( pCtx->dbPath==NULL ){
7103 rc = SQLITE_NOMEM;
7104 }
7105 }
7106 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007107 /* all memory is allocated, proxys are created and assigned,
7108 ** switch the locking context and pMethod then return.
7109 */
drh715ff302008-12-03 22:32:44 +00007110 pCtx->oldLockingContext = pFile->lockingContext;
7111 pFile->lockingContext = pCtx;
7112 pCtx->pOldMethod = pFile->pMethod;
7113 pFile->pMethod = &proxyIoMethods;
7114 }else{
7115 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007116 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007117 sqlite3_free(pCtx->conchFile);
7118 }
drhd56b1212010-08-11 06:14:15 +00007119 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007120 sqlite3_free(pCtx->conchFilePath);
7121 sqlite3_free(pCtx);
7122 }
drh308c2a52010-05-14 11:30:18 +00007123 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7124 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007125 return rc;
7126}
7127
7128
7129/*
7130** This routine handles sqlite3_file_control() calls that are specific
7131** to proxy locking.
7132*/
7133static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7134 switch( op ){
7135 case SQLITE_GET_LOCKPROXYFILE: {
7136 unixFile *pFile = (unixFile*)id;
7137 if( pFile->pMethod == &proxyIoMethods ){
7138 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7139 proxyTakeConch(pFile);
7140 if( pCtx->lockProxyPath ){
7141 *(const char **)pArg = pCtx->lockProxyPath;
7142 }else{
7143 *(const char **)pArg = ":auto: (not held)";
7144 }
7145 } else {
7146 *(const char **)pArg = NULL;
7147 }
7148 return SQLITE_OK;
7149 }
7150 case SQLITE_SET_LOCKPROXYFILE: {
7151 unixFile *pFile = (unixFile*)id;
7152 int rc = SQLITE_OK;
7153 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7154 if( pArg==NULL || (const char *)pArg==0 ){
7155 if( isProxyStyle ){
7156 /* turn off proxy locking - not supported */
7157 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7158 }else{
7159 /* turn off proxy locking - already off - NOOP */
7160 rc = SQLITE_OK;
7161 }
7162 }else{
7163 const char *proxyPath = (const char *)pArg;
7164 if( isProxyStyle ){
7165 proxyLockingContext *pCtx =
7166 (proxyLockingContext*)pFile->lockingContext;
7167 if( !strcmp(pArg, ":auto:")
7168 || (pCtx->lockProxyPath &&
7169 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7170 ){
7171 rc = SQLITE_OK;
7172 }else{
7173 rc = switchLockProxyPath(pFile, proxyPath);
7174 }
7175 }else{
7176 /* turn on proxy file locking */
7177 rc = proxyTransformUnixFile(pFile, proxyPath);
7178 }
7179 }
7180 return rc;
7181 }
7182 default: {
7183 assert( 0 ); /* The call assures that only valid opcodes are sent */
7184 }
7185 }
7186 /*NOTREACHED*/
7187 return SQLITE_ERROR;
7188}
7189
7190/*
7191** Within this division (the proxying locking implementation) the procedures
7192** above this point are all utilities. The lock-related methods of the
7193** proxy-locking sqlite3_io_method object follow.
7194*/
7195
7196
7197/*
7198** This routine checks if there is a RESERVED lock held on the specified
7199** file by this or any other process. If such a lock is held, set *pResOut
7200** to a non-zero value otherwise *pResOut is set to zero. The return value
7201** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7202*/
7203static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7204 unixFile *pFile = (unixFile*)id;
7205 int rc = proxyTakeConch(pFile);
7206 if( rc==SQLITE_OK ){
7207 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007208 if( pCtx->conchHeld>0 ){
7209 unixFile *proxy = pCtx->lockProxy;
7210 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7211 }else{ /* conchHeld < 0 is lockless */
7212 pResOut=0;
7213 }
drh715ff302008-12-03 22:32:44 +00007214 }
7215 return rc;
7216}
7217
7218/*
drh308c2a52010-05-14 11:30:18 +00007219** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007220** of the following:
7221**
7222** (1) SHARED_LOCK
7223** (2) RESERVED_LOCK
7224** (3) PENDING_LOCK
7225** (4) EXCLUSIVE_LOCK
7226**
7227** Sometimes when requesting one lock state, additional lock states
7228** are inserted in between. The locking might fail on one of the later
7229** transitions leaving the lock state different from what it started but
7230** still short of its goal. The following chart shows the allowed
7231** transitions and the inserted intermediate states:
7232**
7233** UNLOCKED -> SHARED
7234** SHARED -> RESERVED
7235** SHARED -> (PENDING) -> EXCLUSIVE
7236** RESERVED -> (PENDING) -> EXCLUSIVE
7237** PENDING -> EXCLUSIVE
7238**
7239** This routine will only increase a lock. Use the sqlite3OsUnlock()
7240** routine to lower a locking level.
7241*/
drh308c2a52010-05-14 11:30:18 +00007242static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007243 unixFile *pFile = (unixFile*)id;
7244 int rc = proxyTakeConch(pFile);
7245 if( rc==SQLITE_OK ){
7246 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007247 if( pCtx->conchHeld>0 ){
7248 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007249 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7250 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007251 }else{
7252 /* conchHeld < 0 is lockless */
7253 }
drh715ff302008-12-03 22:32:44 +00007254 }
7255 return rc;
7256}
7257
7258
7259/*
drh308c2a52010-05-14 11:30:18 +00007260** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007261** must be either NO_LOCK or SHARED_LOCK.
7262**
7263** If the locking level of the file descriptor is already at or below
7264** the requested locking level, this routine is a no-op.
7265*/
drh308c2a52010-05-14 11:30:18 +00007266static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007267 unixFile *pFile = (unixFile*)id;
7268 int rc = proxyTakeConch(pFile);
7269 if( rc==SQLITE_OK ){
7270 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007271 if( pCtx->conchHeld>0 ){
7272 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007273 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7274 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007275 }else{
7276 /* conchHeld < 0 is lockless */
7277 }
drh715ff302008-12-03 22:32:44 +00007278 }
7279 return rc;
7280}
7281
7282/*
7283** Close a file that uses proxy locks.
7284*/
7285static int proxyClose(sqlite3_file *id) {
7286 if( id ){
7287 unixFile *pFile = (unixFile*)id;
7288 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7289 unixFile *lockProxy = pCtx->lockProxy;
7290 unixFile *conchFile = pCtx->conchFile;
7291 int rc = SQLITE_OK;
7292
7293 if( lockProxy ){
7294 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7295 if( rc ) return rc;
7296 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7297 if( rc ) return rc;
7298 sqlite3_free(lockProxy);
7299 pCtx->lockProxy = 0;
7300 }
7301 if( conchFile ){
7302 if( pCtx->conchHeld ){
7303 rc = proxyReleaseConch(pFile);
7304 if( rc ) return rc;
7305 }
7306 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7307 if( rc ) return rc;
7308 sqlite3_free(conchFile);
7309 }
drhd56b1212010-08-11 06:14:15 +00007310 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007311 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007312 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007313 /* restore the original locking context and pMethod then close it */
7314 pFile->lockingContext = pCtx->oldLockingContext;
7315 pFile->pMethod = pCtx->pOldMethod;
7316 sqlite3_free(pCtx);
7317 return pFile->pMethod->xClose(id);
7318 }
7319 return SQLITE_OK;
7320}
7321
7322
7323
drhd2cb50b2009-01-09 21:41:17 +00007324#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007325/*
7326** The proxy locking style is intended for use with AFP filesystems.
7327** And since AFP is only supported on MacOSX, the proxy locking is also
7328** restricted to MacOSX.
7329**
7330**
7331******************* End of the proxy lock implementation **********************
7332******************************************************************************/
7333
drh734c9862008-11-28 15:37:20 +00007334/*
danielk1977e339d652008-06-28 11:23:00 +00007335** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007336**
7337** This routine registers all VFS implementations for unix-like operating
7338** systems. This routine, and the sqlite3_os_end() routine that follows,
7339** should be the only routines in this file that are visible from other
7340** files.
drh6b9d6dd2008-12-03 19:34:47 +00007341**
7342** This routine is called once during SQLite initialization and by a
7343** single thread. The memory allocation and mutex subsystems have not
7344** necessarily been initialized when this routine is called, and so they
7345** should not be used.
drh153c62c2007-08-24 03:51:33 +00007346*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007347int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007348 /*
7349 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007350 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7351 ** to the "finder" function. (pAppData is a pointer to a pointer because
7352 ** silly C90 rules prohibit a void* from being cast to a function pointer
7353 ** and so we have to go through the intermediate pointer to avoid problems
7354 ** when compiling with -pedantic-errors on GCC.)
7355 **
7356 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007357 ** finder-function. The finder-function returns a pointer to the
7358 ** sqlite_io_methods object that implements the desired locking
7359 ** behaviors. See the division above that contains the IOMETHODS
7360 ** macro for addition information on finder-functions.
7361 **
7362 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7363 ** object. But the "autolockIoFinder" available on MacOSX does a little
7364 ** more than that; it looks at the filesystem type that hosts the
7365 ** database file and tries to choose an locking method appropriate for
7366 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007367 */
drh7708e972008-11-29 00:56:52 +00007368 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007369 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007370 sizeof(unixFile), /* szOsFile */ \
7371 MAX_PATHNAME, /* mxPathname */ \
7372 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007373 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007374 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007375 unixOpen, /* xOpen */ \
7376 unixDelete, /* xDelete */ \
7377 unixAccess, /* xAccess */ \
7378 unixFullPathname, /* xFullPathname */ \
7379 unixDlOpen, /* xDlOpen */ \
7380 unixDlError, /* xDlError */ \
7381 unixDlSym, /* xDlSym */ \
7382 unixDlClose, /* xDlClose */ \
7383 unixRandomness, /* xRandomness */ \
7384 unixSleep, /* xSleep */ \
7385 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007386 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007387 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007388 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007389 unixGetSystemCall, /* xGetSystemCall */ \
7390 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007391 }
7392
drh6b9d6dd2008-12-03 19:34:47 +00007393 /*
7394 ** All default VFSes for unix are contained in the following array.
7395 **
7396 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7397 ** by the SQLite core when the VFS is registered. So the following
7398 ** array cannot be const.
7399 */
danielk1977e339d652008-06-28 11:23:00 +00007400 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007401#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007402 UNIXVFS("unix", autolockIoFinder ),
7403#else
7404 UNIXVFS("unix", posixIoFinder ),
7405#endif
7406 UNIXVFS("unix-none", nolockIoFinder ),
7407 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007408 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007409#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007410 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007411#endif
7412#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007413 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007414#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007415 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007416#endif
chw78a13182009-04-07 05:35:03 +00007417#endif
drhd2cb50b2009-01-09 21:41:17 +00007418#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007419 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007420 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007421 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007422#endif
drh153c62c2007-08-24 03:51:33 +00007423 };
drh6b9d6dd2008-12-03 19:34:47 +00007424 unsigned int i; /* Loop counter */
7425
drh2aa5a002011-04-13 13:42:25 +00007426 /* Double-check that the aSyscall[] array has been constructed
7427 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhd1ab8062013-03-25 20:50:25 +00007428 assert( ArraySize(aSyscall)==24 );
drh2aa5a002011-04-13 13:42:25 +00007429
drh6b9d6dd2008-12-03 19:34:47 +00007430 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007431 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007432 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007433 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007434 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007435}
danielk1977e339d652008-06-28 11:23:00 +00007436
7437/*
drh6b9d6dd2008-12-03 19:34:47 +00007438** Shutdown the operating system interface.
7439**
7440** Some operating systems might need to do some cleanup in this routine,
7441** to release dynamically allocated objects. But not on unix.
7442** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007443*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007444int sqlite3_os_end(void){
7445 return SQLITE_OK;
7446}
drhdce8bdb2007-08-16 13:01:44 +00007447
danielk197729bafea2008-06-26 10:41:19 +00007448#endif /* SQLITE_OS_UNIX */