blob: 0ae88517e4803c2d1e51a392b81ca455b2fc2797 [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
dan893c0ff2013-03-25 19:05:07 +0000454 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
455#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
456
drhd1ab8062013-03-25 20:50:25 +0000457 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
458#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
459
dane6ecd662013-04-01 17:56:59 +0000460#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000461 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
462#else
463 { "mremap", (sqlite3_syscall_ptr)0, 0 },
464#endif
465#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
466
drhe562be52011-03-02 18:01:10 +0000467}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000468
469/*
470** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000471** "unix" VFSes. Return SQLITE_OK opon successfully updating the
472** system call pointer, or SQLITE_NOTFOUND if there is no configurable
473** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000474*/
475static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000476 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
477 const char *zName, /* Name of system call to override */
478 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000479){
drh58ad5802011-03-23 22:02:23 +0000480 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000481 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000482
483 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000484 if( zName==0 ){
485 /* If no zName is given, restore all system calls to their default
486 ** settings and return NULL
487 */
dan51438a72011-04-02 17:00:47 +0000488 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000489 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
490 if( aSyscall[i].pDefault ){
491 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000492 }
493 }
494 }else{
495 /* If zName is specified, operate on only the one system call
496 ** specified.
497 */
498 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
499 if( strcmp(zName, aSyscall[i].zName)==0 ){
500 if( aSyscall[i].pDefault==0 ){
501 aSyscall[i].pDefault = aSyscall[i].pCurrent;
502 }
drh1df30962011-03-02 19:06:42 +0000503 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000504 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
505 aSyscall[i].pCurrent = pNewFunc;
506 break;
507 }
508 }
509 }
510 return rc;
511}
512
drh1df30962011-03-02 19:06:42 +0000513/*
514** Return the value of a system call. Return NULL if zName is not a
515** recognized system call name. NULL is also returned if the system call
516** is currently undefined.
517*/
drh58ad5802011-03-23 22:02:23 +0000518static sqlite3_syscall_ptr unixGetSystemCall(
519 sqlite3_vfs *pNotUsed,
520 const char *zName
521){
522 unsigned int i;
523
524 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000525 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
526 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
527 }
528 return 0;
529}
530
531/*
532** Return the name of the first system call after zName. If zName==NULL
533** then return the name of the first system call. Return NULL if zName
534** is the last system call or if zName is not the name of a valid
535** system call.
536*/
537static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000538 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000539
540 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000541 if( zName ){
542 for(i=0; i<ArraySize(aSyscall)-1; i++){
543 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000544 }
545 }
dan0fd7d862011-03-29 10:04:23 +0000546 for(i++; i<ArraySize(aSyscall); i++){
547 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000548 }
549 return 0;
550}
551
drhad4f1e52011-03-04 15:43:57 +0000552/*
drh8c815d12012-02-13 20:16:37 +0000553** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000554** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000555**
556** If the file creation mode "m" is 0 then set it to the default for
557** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
558** 0644) as modified by the system umask. If m is not 0, then
559** make the file creation mode be exactly m ignoring the umask.
560**
561** The m parameter will be non-zero only when creating -wal, -journal,
562** and -shm files. We want those files to have *exactly* the same
563** permissions as their original database, unadulterated by the umask.
564** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
565** transaction crashes and leaves behind hot journals, then any
566** process that is able to write to the database will also be able to
567** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000568*/
drh8c815d12012-02-13 20:16:37 +0000569static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000570 int fd;
drhe1186ab2013-01-04 20:45:13 +0000571 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5adc60b2012-04-14 13:25:11 +0000572 do{
573#if defined(O_CLOEXEC)
574 fd = osOpen(z,f|O_CLOEXEC,m2);
575#else
576 fd = osOpen(z,f,m2);
577#endif
578 }while( fd<0 && errno==EINTR );
drhe1186ab2013-01-04 20:45:13 +0000579 if( fd>=0 ){
580 if( m!=0 ){
581 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000582 if( osFstat(fd, &statbuf)==0
583 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000584 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000585 ){
drhe1186ab2013-01-04 20:45:13 +0000586 osFchmod(fd, m);
587 }
588 }
drh5adc60b2012-04-14 13:25:11 +0000589#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000590 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000591#endif
drhe1186ab2013-01-04 20:45:13 +0000592 }
drh5adc60b2012-04-14 13:25:11 +0000593 return fd;
drhad4f1e52011-03-04 15:43:57 +0000594}
danielk197713adf8a2004-06-03 16:08:41 +0000595
drh107886a2008-11-21 22:21:50 +0000596/*
dan9359c7b2009-08-21 08:29:10 +0000597** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000598** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000599** vxworksFileId objects used by this file, all of which may be
600** shared by multiple threads.
601**
602** Function unixMutexHeld() is used to assert() that the global mutex
603** is held when required. This function is only used as part of assert()
604** statements. e.g.
605**
606** unixEnterMutex()
607** assert( unixMutexHeld() );
608** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000609*/
610static void unixEnterMutex(void){
611 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
612}
613static void unixLeaveMutex(void){
614 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
615}
dan9359c7b2009-08-21 08:29:10 +0000616#ifdef SQLITE_DEBUG
617static int unixMutexHeld(void) {
618 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
619}
620#endif
drh107886a2008-11-21 22:21:50 +0000621
drh734c9862008-11-28 15:37:20 +0000622
drh30ddce62011-10-15 00:16:30 +0000623#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000624/*
625** Helper function for printing out trace information from debugging
626** binaries. This returns the string represetation of the supplied
627** integer lock-type.
628*/
drh308c2a52010-05-14 11:30:18 +0000629static const char *azFileLock(int eFileLock){
630 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000631 case NO_LOCK: return "NONE";
632 case SHARED_LOCK: return "SHARED";
633 case RESERVED_LOCK: return "RESERVED";
634 case PENDING_LOCK: return "PENDING";
635 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000636 }
637 return "ERROR";
638}
639#endif
640
641#ifdef SQLITE_LOCK_TRACE
642/*
643** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000644**
drh734c9862008-11-28 15:37:20 +0000645** This routine is used for troubleshooting locks on multithreaded
646** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
647** command-line option on the compiler. This code is normally
648** turned off.
649*/
650static int lockTrace(int fd, int op, struct flock *p){
651 char *zOpName, *zType;
652 int s;
653 int savedErrno;
654 if( op==F_GETLK ){
655 zOpName = "GETLK";
656 }else if( op==F_SETLK ){
657 zOpName = "SETLK";
658 }else{
drh99ab3b12011-03-02 15:09:07 +0000659 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000660 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
661 return s;
662 }
663 if( p->l_type==F_RDLCK ){
664 zType = "RDLCK";
665 }else if( p->l_type==F_WRLCK ){
666 zType = "WRLCK";
667 }else if( p->l_type==F_UNLCK ){
668 zType = "UNLCK";
669 }else{
670 assert( 0 );
671 }
672 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000673 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000674 savedErrno = errno;
675 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
676 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
677 (int)p->l_pid, s);
678 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
679 struct flock l2;
680 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000681 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000682 if( l2.l_type==F_RDLCK ){
683 zType = "RDLCK";
684 }else if( l2.l_type==F_WRLCK ){
685 zType = "WRLCK";
686 }else if( l2.l_type==F_UNLCK ){
687 zType = "UNLCK";
688 }else{
689 assert( 0 );
690 }
691 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
692 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
693 }
694 errno = savedErrno;
695 return s;
696}
drh99ab3b12011-03-02 15:09:07 +0000697#undef osFcntl
698#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000699#endif /* SQLITE_LOCK_TRACE */
700
drhff812312011-02-23 13:33:46 +0000701/*
702** Retry ftruncate() calls that fail due to EINTR
703*/
drhff812312011-02-23 13:33:46 +0000704static int robust_ftruncate(int h, sqlite3_int64 sz){
705 int rc;
drh99ab3b12011-03-02 15:09:07 +0000706 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000707 return rc;
708}
drh734c9862008-11-28 15:37:20 +0000709
710/*
711** This routine translates a standard POSIX errno code into something
712** useful to the clients of the sqlite3 functions. Specifically, it is
713** intended to translate a variety of "try again" errors into SQLITE_BUSY
714** and a variety of "please close the file descriptor NOW" errors into
715** SQLITE_IOERR
716**
717** Errors during initialization of locks, or file system support for locks,
718** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
719*/
720static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
721 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000722#if 0
723 /* At one point this code was not commented out. In theory, this branch
724 ** should never be hit, as this function should only be called after
725 ** a locking-related function (i.e. fcntl()) has returned non-zero with
726 ** the value of errno as the first argument. Since a system call has failed,
727 ** errno should be non-zero.
728 **
729 ** Despite this, if errno really is zero, we still don't want to return
730 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
731 ** propagated back to the caller. Commenting this branch out means errno==0
732 ** will be handled by the "default:" case below.
733 */
drh734c9862008-11-28 15:37:20 +0000734 case 0:
735 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000736#endif
737
drh734c9862008-11-28 15:37:20 +0000738 case EAGAIN:
739 case ETIMEDOUT:
740 case EBUSY:
741 case EINTR:
742 case ENOLCK:
743 /* random NFS retry error, unless during file system support
744 * introspection, in which it actually means what it says */
745 return SQLITE_BUSY;
746
747 case EACCES:
748 /* EACCES is like EAGAIN during locking operations, but not any other time*/
749 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000750 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
751 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
752 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000753 return SQLITE_BUSY;
754 }
755 /* else fall through */
756 case EPERM:
757 return SQLITE_PERM;
758
danea83bc62011-04-01 11:56:32 +0000759 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
760 ** this module never makes such a call. And the code in SQLite itself
761 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
762 ** this case is also commented out. If the system does set errno to EDEADLK,
763 ** the default SQLITE_IOERR_XXX code will be returned. */
764#if 0
drh734c9862008-11-28 15:37:20 +0000765 case EDEADLK:
766 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000767#endif
drh734c9862008-11-28 15:37:20 +0000768
769#if EOPNOTSUPP!=ENOTSUP
770 case EOPNOTSUPP:
771 /* something went terribly awry, unless during file system support
772 * introspection, in which it actually means what it says */
773#endif
774#ifdef ENOTSUP
775 case ENOTSUP:
776 /* invalid fd, unless during file system support introspection, in which
777 * it actually means what it says */
778#endif
779 case EIO:
780 case EBADF:
781 case EINVAL:
782 case ENOTCONN:
783 case ENODEV:
784 case ENXIO:
785 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000786#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000787 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000788#endif
drh734c9862008-11-28 15:37:20 +0000789 case ENOSYS:
790 /* these should force the client to close the file and reconnect */
791
792 default:
793 return sqliteIOErr;
794 }
795}
796
797
drh734c9862008-11-28 15:37:20 +0000798/******************************************************************************
799****************** Begin Unique File ID Utility Used By VxWorks ***************
800**
801** On most versions of unix, we can get a unique ID for a file by concatenating
802** the device number and the inode number. But this does not work on VxWorks.
803** On VxWorks, a unique file id must be based on the canonical filename.
804**
805** A pointer to an instance of the following structure can be used as a
806** unique file ID in VxWorks. Each instance of this structure contains
807** a copy of the canonical filename. There is also a reference count.
808** The structure is reclaimed when the number of pointers to it drops to
809** zero.
810**
811** There are never very many files open at one time and lookups are not
812** a performance-critical path, so it is sufficient to put these
813** structures on a linked list.
814*/
815struct vxworksFileId {
816 struct vxworksFileId *pNext; /* Next in a list of them all */
817 int nRef; /* Number of references to this one */
818 int nName; /* Length of the zCanonicalName[] string */
819 char *zCanonicalName; /* Canonical filename */
820};
821
822#if OS_VXWORKS
823/*
drh9b35ea62008-11-29 02:20:26 +0000824** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000825** variable:
826*/
827static struct vxworksFileId *vxworksFileList = 0;
828
829/*
830** Simplify a filename into its canonical form
831** by making the following changes:
832**
833** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000834** * convert /./ into just /
835** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000836**
837** Changes are made in-place. Return the new name length.
838**
839** The original filename is in z[0..n-1]. Return the number of
840** characters in the simplified name.
841*/
842static int vxworksSimplifyName(char *z, int n){
843 int i, j;
844 while( n>1 && z[n-1]=='/' ){ n--; }
845 for(i=j=0; i<n; i++){
846 if( z[i]=='/' ){
847 if( z[i+1]=='/' ) continue;
848 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
849 i += 1;
850 continue;
851 }
852 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
853 while( j>0 && z[j-1]!='/' ){ j--; }
854 if( j>0 ){ j--; }
855 i += 2;
856 continue;
857 }
858 }
859 z[j++] = z[i];
860 }
861 z[j] = 0;
862 return j;
863}
864
865/*
866** Find a unique file ID for the given absolute pathname. Return
867** a pointer to the vxworksFileId object. This pointer is the unique
868** file ID.
869**
870** The nRef field of the vxworksFileId object is incremented before
871** the object is returned. A new vxworksFileId object is created
872** and added to the global list if necessary.
873**
874** If a memory allocation error occurs, return NULL.
875*/
876static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
877 struct vxworksFileId *pNew; /* search key and new file ID */
878 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
879 int n; /* Length of zAbsoluteName string */
880
881 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000882 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000883 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
884 if( pNew==0 ) return 0;
885 pNew->zCanonicalName = (char*)&pNew[1];
886 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
887 n = vxworksSimplifyName(pNew->zCanonicalName, n);
888
889 /* Search for an existing entry that matching the canonical name.
890 ** If found, increment the reference count and return a pointer to
891 ** the existing file ID.
892 */
893 unixEnterMutex();
894 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
895 if( pCandidate->nName==n
896 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
897 ){
898 sqlite3_free(pNew);
899 pCandidate->nRef++;
900 unixLeaveMutex();
901 return pCandidate;
902 }
903 }
904
905 /* No match was found. We will make a new file ID */
906 pNew->nRef = 1;
907 pNew->nName = n;
908 pNew->pNext = vxworksFileList;
909 vxworksFileList = pNew;
910 unixLeaveMutex();
911 return pNew;
912}
913
914/*
915** Decrement the reference count on a vxworksFileId object. Free
916** the object when the reference count reaches zero.
917*/
918static void vxworksReleaseFileId(struct vxworksFileId *pId){
919 unixEnterMutex();
920 assert( pId->nRef>0 );
921 pId->nRef--;
922 if( pId->nRef==0 ){
923 struct vxworksFileId **pp;
924 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
925 assert( *pp==pId );
926 *pp = pId->pNext;
927 sqlite3_free(pId);
928 }
929 unixLeaveMutex();
930}
931#endif /* OS_VXWORKS */
932/*************** End of Unique File ID Utility Used By VxWorks ****************
933******************************************************************************/
934
935
936/******************************************************************************
937*************************** Posix Advisory Locking ****************************
938**
drh9b35ea62008-11-29 02:20:26 +0000939** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000940** section 6.5.2.2 lines 483 through 490 specify that when a process
941** sets or clears a lock, that operation overrides any prior locks set
942** by the same process. It does not explicitly say so, but this implies
943** that it overrides locks set by the same process using a different
944** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000945**
946** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000947** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
948**
949** Suppose ./file1 and ./file2 are really the same file (because
950** one is a hard or symbolic link to the other) then if you set
951** an exclusive lock on fd1, then try to get an exclusive lock
952** on fd2, it works. I would have expected the second lock to
953** fail since there was already a lock on the file due to fd1.
954** But not so. Since both locks came from the same process, the
955** second overrides the first, even though they were on different
956** file descriptors opened on different file names.
957**
drh734c9862008-11-28 15:37:20 +0000958** This means that we cannot use POSIX locks to synchronize file access
959** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000960** to synchronize access for threads in separate processes, but not
961** threads within the same process.
962**
963** To work around the problem, SQLite has to manage file locks internally
964** on its own. Whenever a new database is opened, we have to find the
965** specific inode of the database file (the inode is determined by the
966** st_dev and st_ino fields of the stat structure that fstat() fills in)
967** and check for locks already existing on that inode. When locks are
968** created or removed, we have to look at our own internal record of the
969** locks to see if another thread has previously set a lock on that same
970** inode.
971**
drh9b35ea62008-11-29 02:20:26 +0000972** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
973** For VxWorks, we have to use the alternative unique ID system based on
974** canonical filename and implemented in the previous division.)
975**
danielk1977ad94b582007-08-20 06:44:22 +0000976** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000977** descriptor. It is now a structure that holds the integer file
978** descriptor and a pointer to a structure that describes the internal
979** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000980** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000981** point to the same locking structure. The locking structure keeps
982** a reference count (so we will know when to delete it) and a "cnt"
983** field that tells us its internal lock status. cnt==0 means the
984** file is unlocked. cnt==-1 means the file has an exclusive lock.
985** cnt>0 means there are cnt shared locks on the file.
986**
987** Any attempt to lock or unlock a file first checks the locking
988** structure. The fcntl() system call is only invoked to set a
989** POSIX lock if the internal lock structure transitions between
990** a locked and an unlocked state.
991**
drh734c9862008-11-28 15:37:20 +0000992** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000993**
994** If you close a file descriptor that points to a file that has locks,
995** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000996** released. To work around this problem, each unixInodeInfo object
997** maintains a count of the number of pending locks on tha inode.
998** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000999** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001000** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001001** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001002** be closed and that list is walked (and cleared) when the last lock
1003** clears.
1004**
drh9b35ea62008-11-29 02:20:26 +00001005** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001006**
drh9b35ea62008-11-29 02:20:26 +00001007** Many older versions of linux use the LinuxThreads library which is
1008** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001009** A cannot be modified or overridden by a different thread B.
1010** Only thread A can modify the lock. Locking behavior is correct
1011** if the appliation uses the newer Native Posix Thread Library (NPTL)
1012** on linux - with NPTL a lock created by thread A can override locks
1013** in thread B. But there is no way to know at compile-time which
1014** threading library is being used. So there is no way to know at
1015** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001016** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001017** current process.
drh5fdae772004-06-29 03:29:00 +00001018**
drh8af6c222010-05-14 12:43:01 +00001019** SQLite used to support LinuxThreads. But support for LinuxThreads
1020** was dropped beginning with version 3.7.0. SQLite will still work with
1021** LinuxThreads provided that (1) there is no more than one connection
1022** per database file in the same process and (2) database connections
1023** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001024*/
1025
1026/*
1027** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001028** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001029*/
1030struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001031 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001032#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001033 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001034#else
drh107886a2008-11-21 22:21:50 +00001035 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001036#endif
1037};
1038
1039/*
drhbbd42a62004-05-22 17:41:58 +00001040** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001041** inode. Or, on LinuxThreads, there is one of these structures for
1042** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001043**
danielk1977ad94b582007-08-20 06:44:22 +00001044** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001045** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001046** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001047*/
drh8af6c222010-05-14 12:43:01 +00001048struct unixInodeInfo {
1049 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001050 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001051 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1052 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001053 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001054 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1055 int nLock; /* Number of outstanding file locks */
1056 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1057 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1058 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001059#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001060 unsigned long long sharedByte; /* for AFP simulated shared lock */
1061#endif
drh6c7d5c52008-11-21 20:32:33 +00001062#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001063 sem_t *pSem; /* Named POSIX semaphore */
1064 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001065#endif
drhbbd42a62004-05-22 17:41:58 +00001066};
1067
drhda0e7682008-07-30 15:27:54 +00001068/*
drh8af6c222010-05-14 12:43:01 +00001069** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001070*/
drhd91c68f2010-05-14 14:52:25 +00001071static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001072
drh5fdae772004-06-29 03:29:00 +00001073/*
dane18d4952011-02-21 11:46:24 +00001074**
1075** This function - unixLogError_x(), is only ever called via the macro
1076** unixLogError().
1077**
1078** It is invoked after an error occurs in an OS function and errno has been
1079** set. It logs a message using sqlite3_log() containing the current value of
1080** errno and, if possible, the human-readable equivalent from strerror() or
1081** strerror_r().
1082**
1083** The first argument passed to the macro should be the error code that
1084** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1085** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001086** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001087** if any.
1088*/
drh0e9365c2011-03-02 02:08:13 +00001089#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1090static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001091 int errcode, /* SQLite error code */
1092 const char *zFunc, /* Name of OS function that failed */
1093 const char *zPath, /* File path associated with error */
1094 int iLine /* Source line number where error occurred */
1095){
1096 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001097 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001098
1099 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1100 ** the strerror() function to obtain the human-readable error message
1101 ** equivalent to errno. Otherwise, use strerror_r().
1102 */
1103#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1104 char aErr[80];
1105 memset(aErr, 0, sizeof(aErr));
1106 zErr = aErr;
1107
1108 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001109 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001110 ** returns a pointer to a buffer containing the error message. That pointer
1111 ** may point to aErr[], or it may point to some static storage somewhere.
1112 ** Otherwise, assume that the system provides the POSIX version of
1113 ** strerror_r(), which always writes an error message into aErr[].
1114 **
1115 ** If the code incorrectly assumes that it is the POSIX version that is
1116 ** available, the error message will often be an empty string. Not a
1117 ** huge problem. Incorrectly concluding that the GNU version is available
1118 ** could lead to a segfault though.
1119 */
1120#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1121 zErr =
1122# endif
drh0e9365c2011-03-02 02:08:13 +00001123 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001124
1125#elif SQLITE_THREADSAFE
1126 /* This is a threadsafe build, but strerror_r() is not available. */
1127 zErr = "";
1128#else
1129 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001130 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001131#endif
1132
drh0e9365c2011-03-02 02:08:13 +00001133 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001134 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001135 "os_unix.c:%d: (%d) %s(%s) - %s",
1136 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001137 );
1138
1139 return errcode;
1140}
1141
drh0e9365c2011-03-02 02:08:13 +00001142/*
1143** Close a file descriptor.
1144**
1145** We assume that close() almost always works, since it is only in a
1146** very sick application or on a very sick platform that it might fail.
1147** If it does fail, simply leak the file descriptor, but do log the
1148** error.
1149**
1150** Note that it is not safe to retry close() after EINTR since the
1151** file descriptor might have already been reused by another thread.
1152** So we don't even try to recover from an EINTR. Just log the error
1153** and move on.
1154*/
1155static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001156 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001157 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1158 pFile ? pFile->zPath : 0, lineno);
1159 }
1160}
dane18d4952011-02-21 11:46:24 +00001161
1162/*
danb0ac3e32010-06-16 10:55:42 +00001163** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001164*/
drh0e9365c2011-03-02 02:08:13 +00001165static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001166 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001167 UnixUnusedFd *p;
1168 UnixUnusedFd *pNext;
1169 for(p=pInode->pUnused; p; p=pNext){
1170 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001171 robust_close(pFile, p->fd, __LINE__);
1172 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001173 }
drh0e9365c2011-03-02 02:08:13 +00001174 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001175}
1176
1177/*
drh8af6c222010-05-14 12:43:01 +00001178** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001179**
1180** The mutex entered using the unixEnterMutex() function must be held
1181** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001182*/
danb0ac3e32010-06-16 10:55:42 +00001183static void releaseInodeInfo(unixFile *pFile){
1184 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001185 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001186 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001187 pInode->nRef--;
1188 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001189 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001190 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001191 if( pInode->pPrev ){
1192 assert( pInode->pPrev->pNext==pInode );
1193 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001194 }else{
drh8af6c222010-05-14 12:43:01 +00001195 assert( inodeList==pInode );
1196 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001197 }
drh8af6c222010-05-14 12:43:01 +00001198 if( pInode->pNext ){
1199 assert( pInode->pNext->pPrev==pInode );
1200 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001201 }
drh8af6c222010-05-14 12:43:01 +00001202 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001203 }
drhbbd42a62004-05-22 17:41:58 +00001204 }
1205}
1206
1207/*
drh8af6c222010-05-14 12:43:01 +00001208** Given a file descriptor, locate the unixInodeInfo object that
1209** describes that file descriptor. Create a new one if necessary. The
1210** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001211**
dan9359c7b2009-08-21 08:29:10 +00001212** The mutex entered using the unixEnterMutex() function must be held
1213** when this function is called.
1214**
drh6c7d5c52008-11-21 20:32:33 +00001215** Return an appropriate error code.
1216*/
drh8af6c222010-05-14 12:43:01 +00001217static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001218 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001219 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001220){
1221 int rc; /* System call return code */
1222 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001223 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1224 struct stat statbuf; /* Low-level file information */
1225 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001226
dan9359c7b2009-08-21 08:29:10 +00001227 assert( unixMutexHeld() );
1228
drh6c7d5c52008-11-21 20:32:33 +00001229 /* Get low-level information about the file that we can used to
1230 ** create a unique name for the file.
1231 */
1232 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001233 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001234 if( rc!=0 ){
1235 pFile->lastErrno = errno;
1236#ifdef EOVERFLOW
1237 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1238#endif
1239 return SQLITE_IOERR;
1240 }
1241
drheb0d74f2009-02-03 15:27:02 +00001242#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001243 /* On OS X on an msdos filesystem, the inode number is reported
1244 ** incorrectly for zero-size files. See ticket #3260. To work
1245 ** around this problem (we consider it a bug in OS X, not SQLite)
1246 ** we always increase the file size to 1 by writing a single byte
1247 ** prior to accessing the inode number. The one byte written is
1248 ** an ASCII 'S' character which also happens to be the first byte
1249 ** in the header of every SQLite database. In this way, if there
1250 ** is a race condition such that another thread has already populated
1251 ** the first page of the database, no damage is done.
1252 */
drh7ed97b92010-01-20 13:07:21 +00001253 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001254 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001255 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001256 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001257 return SQLITE_IOERR;
1258 }
drh99ab3b12011-03-02 15:09:07 +00001259 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001260 if( rc!=0 ){
1261 pFile->lastErrno = errno;
1262 return SQLITE_IOERR;
1263 }
1264 }
drheb0d74f2009-02-03 15:27:02 +00001265#endif
drh6c7d5c52008-11-21 20:32:33 +00001266
drh8af6c222010-05-14 12:43:01 +00001267 memset(&fileId, 0, sizeof(fileId));
1268 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001269#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001270 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001271#else
drh8af6c222010-05-14 12:43:01 +00001272 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001273#endif
drh8af6c222010-05-14 12:43:01 +00001274 pInode = inodeList;
1275 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1276 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001277 }
drh8af6c222010-05-14 12:43:01 +00001278 if( pInode==0 ){
1279 pInode = sqlite3_malloc( sizeof(*pInode) );
1280 if( pInode==0 ){
1281 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001282 }
drh8af6c222010-05-14 12:43:01 +00001283 memset(pInode, 0, sizeof(*pInode));
1284 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1285 pInode->nRef = 1;
1286 pInode->pNext = inodeList;
1287 pInode->pPrev = 0;
1288 if( inodeList ) inodeList->pPrev = pInode;
1289 inodeList = pInode;
1290 }else{
1291 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001292 }
drh8af6c222010-05-14 12:43:01 +00001293 *ppInode = pInode;
1294 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001295}
drh6c7d5c52008-11-21 20:32:33 +00001296
aswift5b1a2562008-08-22 00:22:35 +00001297
1298/*
drhfbc7e882013-04-11 01:16:15 +00001299** Check a unixFile that is a database. Verify the following:
1300**
1301** (1) There is exactly one hard link on the file
1302** (2) The file is not a symbolic link
1303** (3) The file has not been renamed or unlinked
1304**
1305** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1306*/
1307static void verifyDbFile(unixFile *pFile){
1308 struct stat buf;
1309 int rc;
1310 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1311 /* One or more of the following warnings have already been issued. Do not
1312 ** repeat them so as not to clutter the error log */
1313 return;
1314 }
1315 rc = osFstat(pFile->h, &buf);
1316 if( rc!=0 ){
1317 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1318 pFile->ctrlFlags |= UNIXFILE_WARNED;
1319 return;
1320 }
1321 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
1322 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1323 pFile->ctrlFlags |= UNIXFILE_WARNED;
1324 return;
1325 }
1326 if( buf.st_nlink>1 ){
1327 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1328 pFile->ctrlFlags |= UNIXFILE_WARNED;
1329 return;
1330 }
1331 if( pFile->pInode!=0
1332 && ((rc = osStat(pFile->zPath, &buf))!=0
1333 || buf.st_ino!=pFile->pInode->fileId.ino)
1334 ){
1335 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1336 pFile->ctrlFlags |= UNIXFILE_WARNED;
1337 return;
1338 }
1339}
1340
1341
1342/*
danielk197713adf8a2004-06-03 16:08:41 +00001343** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001344** file by this or any other process. If such a lock is held, set *pResOut
1345** to a non-zero value otherwise *pResOut is set to zero. The return value
1346** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001347*/
danielk1977861f7452008-06-05 11:39:11 +00001348static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001349 int rc = SQLITE_OK;
1350 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001351 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001352
danielk1977861f7452008-06-05 11:39:11 +00001353 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1354
drh054889e2005-11-30 03:20:31 +00001355 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001356 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001357
1358 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001359 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001360 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001361 }
1362
drh2ac3ee92004-06-07 16:27:46 +00001363 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001364 */
danielk197709480a92009-02-09 05:32:32 +00001365#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001366 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001367 struct flock lock;
1368 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001369 lock.l_start = RESERVED_BYTE;
1370 lock.l_len = 1;
1371 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001372 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1373 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1374 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001375 } else if( lock.l_type!=F_UNLCK ){
1376 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001377 }
1378 }
danielk197709480a92009-02-09 05:32:32 +00001379#endif
danielk197713adf8a2004-06-03 16:08:41 +00001380
drh6c7d5c52008-11-21 20:32:33 +00001381 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001382 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001383
aswift5b1a2562008-08-22 00:22:35 +00001384 *pResOut = reserved;
1385 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001386}
1387
1388/*
drha7e61d82011-03-12 17:02:57 +00001389** Attempt to set a system-lock on the file pFile. The lock is
1390** described by pLock.
1391**
drh77197112011-03-15 19:08:48 +00001392** If the pFile was opened read/write from unix-excl, then the only lock
1393** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001394** the first time any lock is attempted. All subsequent system locking
1395** operations become no-ops. Locking operations still happen internally,
1396** in order to coordinate access between separate database connections
1397** within this process, but all of that is handled in memory and the
1398** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001399**
1400** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1401** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1402** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001403**
1404** Zero is returned if the call completes successfully, or -1 if a call
1405** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001406*/
1407static int unixFileLock(unixFile *pFile, struct flock *pLock){
1408 int rc;
drh3cb93392011-03-12 18:10:44 +00001409 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001410 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001411 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001412 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1413 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1414 ){
drh3cb93392011-03-12 18:10:44 +00001415 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001416 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001417 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001418 lock.l_whence = SEEK_SET;
1419 lock.l_start = SHARED_FIRST;
1420 lock.l_len = SHARED_SIZE;
1421 lock.l_type = F_WRLCK;
1422 rc = osFcntl(pFile->h, F_SETLK, &lock);
1423 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001424 pInode->bProcessLock = 1;
1425 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001426 }else{
1427 rc = 0;
1428 }
1429 }else{
1430 rc = osFcntl(pFile->h, F_SETLK, pLock);
1431 }
1432 return rc;
1433}
1434
1435/*
drh308c2a52010-05-14 11:30:18 +00001436** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001437** of the following:
1438**
drh2ac3ee92004-06-07 16:27:46 +00001439** (1) SHARED_LOCK
1440** (2) RESERVED_LOCK
1441** (3) PENDING_LOCK
1442** (4) EXCLUSIVE_LOCK
1443**
drhb3e04342004-06-08 00:47:47 +00001444** Sometimes when requesting one lock state, additional lock states
1445** are inserted in between. The locking might fail on one of the later
1446** transitions leaving the lock state different from what it started but
1447** still short of its goal. The following chart shows the allowed
1448** transitions and the inserted intermediate states:
1449**
1450** UNLOCKED -> SHARED
1451** SHARED -> RESERVED
1452** SHARED -> (PENDING) -> EXCLUSIVE
1453** RESERVED -> (PENDING) -> EXCLUSIVE
1454** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001455**
drha6abd042004-06-09 17:37:22 +00001456** This routine will only increase a lock. Use the sqlite3OsUnlock()
1457** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001458*/
drh308c2a52010-05-14 11:30:18 +00001459static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001460 /* The following describes the implementation of the various locks and
1461 ** lock transitions in terms of the POSIX advisory shared and exclusive
1462 ** lock primitives (called read-locks and write-locks below, to avoid
1463 ** confusion with SQLite lock names). The algorithms are complicated
1464 ** slightly in order to be compatible with windows systems simultaneously
1465 ** accessing the same database file, in case that is ever required.
1466 **
1467 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1468 ** byte', each single bytes at well known offsets, and the 'shared byte
1469 ** range', a range of 510 bytes at a well known offset.
1470 **
1471 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1472 ** byte'. If this is successful, a random byte from the 'shared byte
1473 ** range' is read-locked and the lock on the 'pending byte' released.
1474 **
danielk197790ba3bd2004-06-25 08:32:25 +00001475 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1476 ** A RESERVED lock is implemented by grabbing a write-lock on the
1477 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001478 **
1479 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001480 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1481 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1482 ** obtained, but existing SHARED locks are allowed to persist. A process
1483 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1484 ** This property is used by the algorithm for rolling back a journal file
1485 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001486 **
danielk197790ba3bd2004-06-25 08:32:25 +00001487 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1488 ** implemented by obtaining a write-lock on the entire 'shared byte
1489 ** range'. Since all other locks require a read-lock on one of the bytes
1490 ** within this range, this ensures that no other locks are held on the
1491 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001492 **
1493 ** The reason a single byte cannot be used instead of the 'shared byte
1494 ** range' is that some versions of windows do not support read-locks. By
1495 ** locking a random byte from a range, concurrent SHARED locks may exist
1496 ** even if the locking primitive used is always a write-lock.
1497 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001498 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001499 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001500 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001501 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001502 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001503
drh054889e2005-11-30 03:20:31 +00001504 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001505 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1506 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001507 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001508
1509 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001510 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001511 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001512 */
drh308c2a52010-05-14 11:30:18 +00001513 if( pFile->eFileLock>=eFileLock ){
1514 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1515 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001516 return SQLITE_OK;
1517 }
1518
drh0c2694b2009-09-03 16:23:44 +00001519 /* Make sure the locking sequence is correct.
1520 ** (1) We never move from unlocked to anything higher than shared lock.
1521 ** (2) SQLite never explicitly requests a pendig lock.
1522 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001523 */
drh308c2a52010-05-14 11:30:18 +00001524 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1525 assert( eFileLock!=PENDING_LOCK );
1526 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001527
drh8af6c222010-05-14 12:43:01 +00001528 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001529 */
drh6c7d5c52008-11-21 20:32:33 +00001530 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001531 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001532
danielk1977ad94b582007-08-20 06:44:22 +00001533 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001534 ** handle that precludes the requested lock, return BUSY.
1535 */
drh8af6c222010-05-14 12:43:01 +00001536 if( (pFile->eFileLock!=pInode->eFileLock &&
1537 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001538 ){
1539 rc = SQLITE_BUSY;
1540 goto end_lock;
1541 }
1542
1543 /* If a SHARED lock is requested, and some thread using this PID already
1544 ** has a SHARED or RESERVED lock, then increment reference counts and
1545 ** return SQLITE_OK.
1546 */
drh308c2a52010-05-14 11:30:18 +00001547 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001548 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001549 assert( eFileLock==SHARED_LOCK );
1550 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001551 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001552 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001553 pInode->nShared++;
1554 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001555 goto end_lock;
1556 }
1557
danielk19779a1d0ab2004-06-01 14:09:28 +00001558
drh3cde3bb2004-06-12 02:17:14 +00001559 /* A PENDING lock is needed before acquiring a SHARED lock and before
1560 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1561 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001562 */
drh0c2694b2009-09-03 16:23:44 +00001563 lock.l_len = 1L;
1564 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001565 if( eFileLock==SHARED_LOCK
1566 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001567 ){
drh308c2a52010-05-14 11:30:18 +00001568 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001569 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001570 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001571 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001572 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001573 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001574 pFile->lastErrno = tErrno;
1575 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001576 goto end_lock;
1577 }
drh3cde3bb2004-06-12 02:17:14 +00001578 }
1579
1580
1581 /* If control gets to this point, then actually go ahead and make
1582 ** operating system calls for the specified lock.
1583 */
drh308c2a52010-05-14 11:30:18 +00001584 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001585 assert( pInode->nShared==0 );
1586 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001587 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001588
drh2ac3ee92004-06-07 16:27:46 +00001589 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001590 lock.l_start = SHARED_FIRST;
1591 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001592 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001593 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001594 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001595 }
dan661d71a2011-03-30 19:08:03 +00001596
drh2ac3ee92004-06-07 16:27:46 +00001597 /* Drop the temporary PENDING lock */
1598 lock.l_start = PENDING_BYTE;
1599 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001600 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001601 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1602 /* This could happen with a network mount */
1603 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001604 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001605 }
dan661d71a2011-03-30 19:08:03 +00001606
1607 if( rc ){
1608 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001609 pFile->lastErrno = tErrno;
1610 }
dan661d71a2011-03-30 19:08:03 +00001611 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001612 }else{
drh308c2a52010-05-14 11:30:18 +00001613 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001614 pInode->nLock++;
1615 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001616 }
drh8af6c222010-05-14 12:43:01 +00001617 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001618 /* We are trying for an exclusive lock but another thread in this
1619 ** same process is still holding a shared lock. */
1620 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001621 }else{
drh3cde3bb2004-06-12 02:17:14 +00001622 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001623 ** assumed that there is a SHARED or greater lock on the file
1624 ** already.
1625 */
drh308c2a52010-05-14 11:30:18 +00001626 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001627 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001628
1629 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1630 if( eFileLock==RESERVED_LOCK ){
1631 lock.l_start = RESERVED_BYTE;
1632 lock.l_len = 1L;
1633 }else{
1634 lock.l_start = SHARED_FIRST;
1635 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001636 }
dan661d71a2011-03-30 19:08:03 +00001637
1638 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001639 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001640 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001641 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001642 pFile->lastErrno = tErrno;
1643 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001644 }
drhbbd42a62004-05-22 17:41:58 +00001645 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001646
drh8f941bc2009-01-14 23:03:40 +00001647
drhd3d8c042012-05-29 17:02:40 +00001648#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001649 /* Set up the transaction-counter change checking flags when
1650 ** transitioning from a SHARED to a RESERVED lock. The change
1651 ** from SHARED to RESERVED marks the beginning of a normal
1652 ** write operation (not a hot journal rollback).
1653 */
1654 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001655 && pFile->eFileLock<=SHARED_LOCK
1656 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001657 ){
1658 pFile->transCntrChng = 0;
1659 pFile->dbUpdate = 0;
1660 pFile->inNormalWrite = 1;
1661 }
1662#endif
1663
1664
danielk1977ecb2a962004-06-02 06:30:16 +00001665 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001666 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001667 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001668 }else if( eFileLock==EXCLUSIVE_LOCK ){
1669 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001670 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001671 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001672
1673end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001674 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001675 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1676 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001677 return rc;
1678}
1679
1680/*
dan08da86a2009-08-21 17:18:03 +00001681** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001682** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001683*/
1684static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001685 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001686 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001687 p->pNext = pInode->pUnused;
1688 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001689 pFile->h = -1;
1690 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001691}
1692
1693/*
drh308c2a52010-05-14 11:30:18 +00001694** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001695** must be either NO_LOCK or SHARED_LOCK.
1696**
1697** If the locking level of the file descriptor is already at or below
1698** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001699**
1700** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1701** the byte range is divided into 2 parts and the first part is unlocked then
1702** set to a read lock, then the other part is simply unlocked. This works
1703** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1704** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001705*/
drha7e61d82011-03-12 17:02:57 +00001706static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001707 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001708 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001709 struct flock lock;
1710 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001711
drh054889e2005-11-30 03:20:31 +00001712 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001713 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001714 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001715 getpid()));
drha6abd042004-06-09 17:37:22 +00001716
drh308c2a52010-05-14 11:30:18 +00001717 assert( eFileLock<=SHARED_LOCK );
1718 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001719 return SQLITE_OK;
1720 }
drh6c7d5c52008-11-21 20:32:33 +00001721 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001722 pInode = pFile->pInode;
1723 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001724 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001725 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001726
drhd3d8c042012-05-29 17:02:40 +00001727#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001728 /* When reducing a lock such that other processes can start
1729 ** reading the database file again, make sure that the
1730 ** transaction counter was updated if any part of the database
1731 ** file changed. If the transaction counter is not updated,
1732 ** other connections to the same file might not realize that
1733 ** the file has changed and hence might not know to flush their
1734 ** cache. The use of a stale cache can lead to database corruption.
1735 */
drh8f941bc2009-01-14 23:03:40 +00001736 pFile->inNormalWrite = 0;
1737#endif
1738
drh7ed97b92010-01-20 13:07:21 +00001739 /* downgrading to a shared lock on NFS involves clearing the write lock
1740 ** before establishing the readlock - to avoid a race condition we downgrade
1741 ** the lock in 2 blocks, so that part of the range will be covered by a
1742 ** write lock until the rest is covered by a read lock:
1743 ** 1: [WWWWW]
1744 ** 2: [....W]
1745 ** 3: [RRRRW]
1746 ** 4: [RRRR.]
1747 */
drh308c2a52010-05-14 11:30:18 +00001748 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001749
1750#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001751 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001752 assert( handleNFSUnlock==0 );
1753#endif
1754#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001755 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001756 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001757 off_t divSize = SHARED_SIZE - 1;
1758
1759 lock.l_type = F_UNLCK;
1760 lock.l_whence = SEEK_SET;
1761 lock.l_start = SHARED_FIRST;
1762 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001763 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001764 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001765 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001766 if( IS_LOCK_ERROR(rc) ){
1767 pFile->lastErrno = tErrno;
1768 }
1769 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001770 }
drh7ed97b92010-01-20 13:07:21 +00001771 lock.l_type = F_RDLCK;
1772 lock.l_whence = SEEK_SET;
1773 lock.l_start = SHARED_FIRST;
1774 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001775 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001776 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001777 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1778 if( IS_LOCK_ERROR(rc) ){
1779 pFile->lastErrno = tErrno;
1780 }
1781 goto end_unlock;
1782 }
1783 lock.l_type = F_UNLCK;
1784 lock.l_whence = SEEK_SET;
1785 lock.l_start = SHARED_FIRST+divSize;
1786 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001787 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001788 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001789 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001790 if( IS_LOCK_ERROR(rc) ){
1791 pFile->lastErrno = tErrno;
1792 }
1793 goto end_unlock;
1794 }
drh30f776f2011-02-25 03:25:07 +00001795 }else
1796#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1797 {
drh7ed97b92010-01-20 13:07:21 +00001798 lock.l_type = F_RDLCK;
1799 lock.l_whence = SEEK_SET;
1800 lock.l_start = SHARED_FIRST;
1801 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001802 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001803 /* In theory, the call to unixFileLock() cannot fail because another
1804 ** process is holding an incompatible lock. If it does, this
1805 ** indicates that the other process is not following the locking
1806 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1807 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1808 ** an assert to fail). */
1809 rc = SQLITE_IOERR_RDLOCK;
1810 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001811 goto end_unlock;
1812 }
drh9c105bb2004-10-02 20:38:28 +00001813 }
1814 }
drhbbd42a62004-05-22 17:41:58 +00001815 lock.l_type = F_UNLCK;
1816 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001817 lock.l_start = PENDING_BYTE;
1818 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001819 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001820 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001821 }else{
danea83bc62011-04-01 11:56:32 +00001822 rc = SQLITE_IOERR_UNLOCK;
1823 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001824 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001825 }
drhbbd42a62004-05-22 17:41:58 +00001826 }
drh308c2a52010-05-14 11:30:18 +00001827 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001828 /* Decrement the shared lock counter. Release the lock using an
1829 ** OS call only when all threads in this same process have released
1830 ** the lock.
1831 */
drh8af6c222010-05-14 12:43:01 +00001832 pInode->nShared--;
1833 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001834 lock.l_type = F_UNLCK;
1835 lock.l_whence = SEEK_SET;
1836 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001837 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001838 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001839 }else{
danea83bc62011-04-01 11:56:32 +00001840 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001841 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001842 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001843 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001844 }
drha6abd042004-06-09 17:37:22 +00001845 }
1846
drhbbd42a62004-05-22 17:41:58 +00001847 /* Decrement the count of locks against this same file. When the
1848 ** count reaches zero, close any other file descriptors whose close
1849 ** was deferred because of outstanding locks.
1850 */
drh8af6c222010-05-14 12:43:01 +00001851 pInode->nLock--;
1852 assert( pInode->nLock>=0 );
1853 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001854 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001855 }
1856 }
drhf2f105d2012-08-20 15:53:54 +00001857
aswift5b1a2562008-08-22 00:22:35 +00001858end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001859 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001860 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001861 return rc;
drhbbd42a62004-05-22 17:41:58 +00001862}
1863
1864/*
drh308c2a52010-05-14 11:30:18 +00001865** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001866** must be either NO_LOCK or SHARED_LOCK.
1867**
1868** If the locking level of the file descriptor is already at or below
1869** the requested locking level, this routine is a no-op.
1870*/
drh308c2a52010-05-14 11:30:18 +00001871static int unixUnlock(sqlite3_file *id, int eFileLock){
dana1afc742013-03-25 13:50:49 +00001872 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
drha7e61d82011-03-12 17:02:57 +00001873 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001874}
1875
mistachkine98844f2013-08-24 00:59:24 +00001876#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001877static int unixMapfile(unixFile *pFd, i64 nByte);
1878static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001879#endif
danf23da962013-03-23 21:00:41 +00001880
drh7ed97b92010-01-20 13:07:21 +00001881/*
danielk1977e339d652008-06-28 11:23:00 +00001882** This function performs the parts of the "close file" operation
1883** common to all locking schemes. It closes the directory and file
1884** handles, if they are valid, and sets all fields of the unixFile
1885** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001886**
1887** It is *not* necessary to hold the mutex when this routine is called,
1888** even on VxWorks. A mutex will be acquired on VxWorks by the
1889** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001890*/
1891static int closeUnixFile(sqlite3_file *id){
1892 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001893#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001894 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001895#endif
dan661d71a2011-03-30 19:08:03 +00001896 if( pFile->h>=0 ){
1897 robust_close(pFile, pFile->h, __LINE__);
1898 pFile->h = -1;
1899 }
1900#if OS_VXWORKS
1901 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001902 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001903 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001904 }
1905 vxworksReleaseFileId(pFile->pId);
1906 pFile->pId = 0;
1907 }
1908#endif
1909 OSTRACE(("CLOSE %-3d\n", pFile->h));
1910 OpenCounter(-1);
1911 sqlite3_free(pFile->pUnused);
1912 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001913 return SQLITE_OK;
1914}
1915
1916/*
danielk1977e3026632004-06-22 11:29:02 +00001917** Close a file.
1918*/
danielk197762079062007-08-15 17:08:46 +00001919static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001920 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001921 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001922 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001923 unixUnlock(id, NO_LOCK);
1924 unixEnterMutex();
1925
1926 /* unixFile.pInode is always valid here. Otherwise, a different close
1927 ** routine (e.g. nolockClose()) would be called instead.
1928 */
1929 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1930 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1931 /* If there are outstanding locks, do not actually close the file just
1932 ** yet because that would clear those locks. Instead, add the file
1933 ** descriptor to pInode->pUnused list. It will be automatically closed
1934 ** when the last lock is cleared.
1935 */
1936 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001937 }
dan661d71a2011-03-30 19:08:03 +00001938 releaseInodeInfo(pFile);
1939 rc = closeUnixFile(id);
1940 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001941 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001942}
1943
drh734c9862008-11-28 15:37:20 +00001944/************** End of the posix advisory lock implementation *****************
1945******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001946
drh734c9862008-11-28 15:37:20 +00001947/******************************************************************************
1948****************************** No-op Locking **********************************
1949**
1950** Of the various locking implementations available, this is by far the
1951** simplest: locking is ignored. No attempt is made to lock the database
1952** file for reading or writing.
1953**
1954** This locking mode is appropriate for use on read-only databases
1955** (ex: databases that are burned into CD-ROM, for example.) It can
1956** also be used if the application employs some external mechanism to
1957** prevent simultaneous access of the same database by two or more
1958** database connections. But there is a serious risk of database
1959** corruption if this locking mode is used in situations where multiple
1960** database connections are accessing the same database file at the same
1961** time and one or more of those connections are writing.
1962*/
drhbfe66312006-10-03 17:40:40 +00001963
drh734c9862008-11-28 15:37:20 +00001964static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1965 UNUSED_PARAMETER(NotUsed);
1966 *pResOut = 0;
1967 return SQLITE_OK;
1968}
drh734c9862008-11-28 15:37:20 +00001969static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1970 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1971 return SQLITE_OK;
1972}
drh734c9862008-11-28 15:37:20 +00001973static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1974 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1975 return SQLITE_OK;
1976}
1977
1978/*
drh9b35ea62008-11-29 02:20:26 +00001979** Close the file.
drh734c9862008-11-28 15:37:20 +00001980*/
1981static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001982 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001983}
1984
1985/******************* End of the no-op lock implementation *********************
1986******************************************************************************/
1987
1988/******************************************************************************
1989************************* Begin dot-file Locking ******************************
1990**
mistachkin48864df2013-03-21 21:20:32 +00001991** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001992** files (really a directory) to control access to the database. This works
1993** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001994**
1995** (1) There is zero concurrency. A single reader blocks all other
1996** connections from reading or writing the database.
1997**
1998** (2) An application crash or power loss can leave stale lock files
1999** sitting around that need to be cleared manually.
2000**
2001** Nevertheless, a dotlock is an appropriate locking mode for use if no
2002** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002003**
drh9ef6bc42011-11-04 02:24:02 +00002004** Dotfile locking works by creating a subdirectory in the same directory as
2005** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002006** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002007** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002008*/
2009
2010/*
2011** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002012** lock directory.
drh734c9862008-11-28 15:37:20 +00002013*/
2014#define DOTLOCK_SUFFIX ".lock"
2015
drh7708e972008-11-29 00:56:52 +00002016/*
2017** This routine checks if there is a RESERVED lock held on the specified
2018** file by this or any other process. If such a lock is held, set *pResOut
2019** to a non-zero value otherwise *pResOut is set to zero. The return value
2020** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2021**
2022** In dotfile locking, either a lock exists or it does not. So in this
2023** variation of CheckReservedLock(), *pResOut is set to true if any lock
2024** is held on the file and false if the file is unlocked.
2025*/
drh734c9862008-11-28 15:37:20 +00002026static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2027 int rc = SQLITE_OK;
2028 int reserved = 0;
2029 unixFile *pFile = (unixFile*)id;
2030
2031 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2032
2033 assert( pFile );
2034
2035 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002036 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002037 /* Either this connection or some other connection in the same process
2038 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002039 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002040 }else{
2041 /* The lock is held if and only if the lockfile exists */
2042 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002043 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002044 }
drh308c2a52010-05-14 11:30:18 +00002045 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002046 *pResOut = reserved;
2047 return rc;
2048}
2049
drh7708e972008-11-29 00:56:52 +00002050/*
drh308c2a52010-05-14 11:30:18 +00002051** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002052** of the following:
2053**
2054** (1) SHARED_LOCK
2055** (2) RESERVED_LOCK
2056** (3) PENDING_LOCK
2057** (4) EXCLUSIVE_LOCK
2058**
2059** Sometimes when requesting one lock state, additional lock states
2060** are inserted in between. The locking might fail on one of the later
2061** transitions leaving the lock state different from what it started but
2062** still short of its goal. The following chart shows the allowed
2063** transitions and the inserted intermediate states:
2064**
2065** UNLOCKED -> SHARED
2066** SHARED -> RESERVED
2067** SHARED -> (PENDING) -> EXCLUSIVE
2068** RESERVED -> (PENDING) -> EXCLUSIVE
2069** PENDING -> EXCLUSIVE
2070**
2071** This routine will only increase a lock. Use the sqlite3OsUnlock()
2072** routine to lower a locking level.
2073**
2074** With dotfile locking, we really only support state (4): EXCLUSIVE.
2075** But we track the other locking levels internally.
2076*/
drh308c2a52010-05-14 11:30:18 +00002077static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002078 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002079 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002080 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002081
drh7708e972008-11-29 00:56:52 +00002082
2083 /* If we have any lock, then the lock file already exists. All we have
2084 ** to do is adjust our internal record of the lock level.
2085 */
drh308c2a52010-05-14 11:30:18 +00002086 if( pFile->eFileLock > NO_LOCK ){
2087 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002088 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002089#ifdef HAVE_UTIME
2090 utime(zLockFile, NULL);
2091#else
drh734c9862008-11-28 15:37:20 +00002092 utimes(zLockFile, NULL);
2093#endif
drh7708e972008-11-29 00:56:52 +00002094 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002095 }
2096
2097 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002098 rc = osMkdir(zLockFile, 0777);
2099 if( rc<0 ){
2100 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002101 int tErrno = errno;
2102 if( EEXIST == tErrno ){
2103 rc = SQLITE_BUSY;
2104 } else {
2105 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2106 if( IS_LOCK_ERROR(rc) ){
2107 pFile->lastErrno = tErrno;
2108 }
2109 }
drh7708e972008-11-29 00:56:52 +00002110 return rc;
drh734c9862008-11-28 15:37:20 +00002111 }
drh734c9862008-11-28 15:37:20 +00002112
2113 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002114 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002115 return rc;
2116}
2117
drh7708e972008-11-29 00:56:52 +00002118/*
drh308c2a52010-05-14 11:30:18 +00002119** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002120** must be either NO_LOCK or SHARED_LOCK.
2121**
2122** If the locking level of the file descriptor is already at or below
2123** the requested locking level, this routine is a no-op.
2124**
2125** When the locking level reaches NO_LOCK, delete the lock file.
2126*/
drh308c2a52010-05-14 11:30:18 +00002127static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002128 unixFile *pFile = (unixFile*)id;
2129 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002130 int rc;
drh734c9862008-11-28 15:37:20 +00002131
2132 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002133 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002134 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002135 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002136
2137 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002138 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002139 return SQLITE_OK;
2140 }
drh7708e972008-11-29 00:56:52 +00002141
2142 /* To downgrade to shared, simply update our internal notion of the
2143 ** lock state. No need to mess with the file on disk.
2144 */
drh308c2a52010-05-14 11:30:18 +00002145 if( eFileLock==SHARED_LOCK ){
2146 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002147 return SQLITE_OK;
2148 }
2149
drh7708e972008-11-29 00:56:52 +00002150 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002151 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002152 rc = osRmdir(zLockFile);
2153 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2154 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002155 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002156 rc = 0;
drh734c9862008-11-28 15:37:20 +00002157 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002158 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002159 }
2160 if( IS_LOCK_ERROR(rc) ){
2161 pFile->lastErrno = tErrno;
2162 }
2163 return rc;
2164 }
drh308c2a52010-05-14 11:30:18 +00002165 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002166 return SQLITE_OK;
2167}
2168
2169/*
drh9b35ea62008-11-29 02:20:26 +00002170** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002171*/
2172static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002173 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002174 if( id ){
2175 unixFile *pFile = (unixFile*)id;
2176 dotlockUnlock(id, NO_LOCK);
2177 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002178 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002179 }
drh734c9862008-11-28 15:37:20 +00002180 return rc;
2181}
2182/****************** End of the dot-file lock implementation *******************
2183******************************************************************************/
2184
2185/******************************************************************************
2186************************** Begin flock Locking ********************************
2187**
2188** Use the flock() system call to do file locking.
2189**
drh6b9d6dd2008-12-03 19:34:47 +00002190** flock() locking is like dot-file locking in that the various
2191** fine-grain locking levels supported by SQLite are collapsed into
2192** a single exclusive lock. In other words, SHARED, RESERVED, and
2193** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2194** still works when you do this, but concurrency is reduced since
2195** only a single process can be reading the database at a time.
2196**
drh734c9862008-11-28 15:37:20 +00002197** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2198** compiling for VXWORKS.
2199*/
2200#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002201
drh6b9d6dd2008-12-03 19:34:47 +00002202/*
drhff812312011-02-23 13:33:46 +00002203** Retry flock() calls that fail with EINTR
2204*/
2205#ifdef EINTR
2206static int robust_flock(int fd, int op){
2207 int rc;
2208 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2209 return rc;
2210}
2211#else
drh5c819272011-02-23 14:00:12 +00002212# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002213#endif
2214
2215
2216/*
drh6b9d6dd2008-12-03 19:34:47 +00002217** This routine checks if there is a RESERVED lock held on the specified
2218** file by this or any other process. If such a lock is held, set *pResOut
2219** to a non-zero value otherwise *pResOut is set to zero. The return value
2220** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2221*/
drh734c9862008-11-28 15:37:20 +00002222static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2223 int rc = SQLITE_OK;
2224 int reserved = 0;
2225 unixFile *pFile = (unixFile*)id;
2226
2227 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2228
2229 assert( pFile );
2230
2231 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002232 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002233 reserved = 1;
2234 }
2235
2236 /* Otherwise see if some other process holds it. */
2237 if( !reserved ){
2238 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002239 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002240 if( !lrc ){
2241 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002242 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002243 if ( lrc ) {
2244 int tErrno = errno;
2245 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002246 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002247 if( IS_LOCK_ERROR(lrc) ){
2248 pFile->lastErrno = tErrno;
2249 rc = lrc;
2250 }
2251 }
2252 } else {
2253 int tErrno = errno;
2254 reserved = 1;
2255 /* someone else might have it reserved */
2256 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2257 if( IS_LOCK_ERROR(lrc) ){
2258 pFile->lastErrno = tErrno;
2259 rc = lrc;
2260 }
2261 }
2262 }
drh308c2a52010-05-14 11:30:18 +00002263 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002264
2265#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2266 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2267 rc = SQLITE_OK;
2268 reserved=1;
2269 }
2270#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2271 *pResOut = reserved;
2272 return rc;
2273}
2274
drh6b9d6dd2008-12-03 19:34:47 +00002275/*
drh308c2a52010-05-14 11:30:18 +00002276** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002277** of the following:
2278**
2279** (1) SHARED_LOCK
2280** (2) RESERVED_LOCK
2281** (3) PENDING_LOCK
2282** (4) EXCLUSIVE_LOCK
2283**
2284** Sometimes when requesting one lock state, additional lock states
2285** are inserted in between. The locking might fail on one of the later
2286** transitions leaving the lock state different from what it started but
2287** still short of its goal. The following chart shows the allowed
2288** transitions and the inserted intermediate states:
2289**
2290** UNLOCKED -> SHARED
2291** SHARED -> RESERVED
2292** SHARED -> (PENDING) -> EXCLUSIVE
2293** RESERVED -> (PENDING) -> EXCLUSIVE
2294** PENDING -> EXCLUSIVE
2295**
2296** flock() only really support EXCLUSIVE locks. We track intermediate
2297** lock states in the sqlite3_file structure, but all locks SHARED or
2298** above are really EXCLUSIVE locks and exclude all other processes from
2299** access the file.
2300**
2301** This routine will only increase a lock. Use the sqlite3OsUnlock()
2302** routine to lower a locking level.
2303*/
drh308c2a52010-05-14 11:30:18 +00002304static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002305 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002306 unixFile *pFile = (unixFile*)id;
2307
2308 assert( pFile );
2309
2310 /* if we already have a lock, it is exclusive.
2311 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002312 if (pFile->eFileLock > NO_LOCK) {
2313 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002314 return SQLITE_OK;
2315 }
2316
2317 /* grab an exclusive lock */
2318
drhff812312011-02-23 13:33:46 +00002319 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002320 int tErrno = errno;
2321 /* didn't get, must be busy */
2322 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2323 if( IS_LOCK_ERROR(rc) ){
2324 pFile->lastErrno = tErrno;
2325 }
2326 } else {
2327 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002328 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002329 }
drh308c2a52010-05-14 11:30:18 +00002330 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2331 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002332#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2333 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2334 rc = SQLITE_BUSY;
2335 }
2336#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2337 return rc;
2338}
2339
drh6b9d6dd2008-12-03 19:34:47 +00002340
2341/*
drh308c2a52010-05-14 11:30:18 +00002342** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002343** must be either NO_LOCK or SHARED_LOCK.
2344**
2345** If the locking level of the file descriptor is already at or below
2346** the requested locking level, this routine is a no-op.
2347*/
drh308c2a52010-05-14 11:30:18 +00002348static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002349 unixFile *pFile = (unixFile*)id;
2350
2351 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002352 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2353 pFile->eFileLock, getpid()));
2354 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002355
2356 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002357 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002358 return SQLITE_OK;
2359 }
2360
2361 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002362 if (eFileLock==SHARED_LOCK) {
2363 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002364 return SQLITE_OK;
2365 }
2366
2367 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002368 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002369#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002370 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002371#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002372 return SQLITE_IOERR_UNLOCK;
2373 }else{
drh308c2a52010-05-14 11:30:18 +00002374 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002375 return SQLITE_OK;
2376 }
2377}
2378
2379/*
2380** Close a file.
2381*/
2382static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002383 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002384 if( id ){
2385 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002386 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002387 }
drh5a05be12012-10-09 18:51:44 +00002388 return rc;
drh734c9862008-11-28 15:37:20 +00002389}
2390
2391#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2392
2393/******************* End of the flock lock implementation *********************
2394******************************************************************************/
2395
2396/******************************************************************************
2397************************ Begin Named Semaphore Locking ************************
2398**
2399** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002400**
2401** Semaphore locking is like dot-lock and flock in that it really only
2402** supports EXCLUSIVE locking. Only a single process can read or write
2403** the database file at a time. This reduces potential concurrency, but
2404** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002405*/
2406#if OS_VXWORKS
2407
drh6b9d6dd2008-12-03 19:34:47 +00002408/*
2409** This routine checks if there is a RESERVED lock held on the specified
2410** file by this or any other process. If such a lock is held, set *pResOut
2411** to a non-zero value otherwise *pResOut is set to zero. The return value
2412** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2413*/
drh734c9862008-11-28 15:37:20 +00002414static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2415 int rc = SQLITE_OK;
2416 int reserved = 0;
2417 unixFile *pFile = (unixFile*)id;
2418
2419 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2420
2421 assert( pFile );
2422
2423 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002424 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002425 reserved = 1;
2426 }
2427
2428 /* Otherwise see if some other process holds it. */
2429 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002430 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002431 struct stat statBuf;
2432
2433 if( sem_trywait(pSem)==-1 ){
2434 int tErrno = errno;
2435 if( EAGAIN != tErrno ){
2436 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2437 pFile->lastErrno = tErrno;
2438 } else {
2439 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002440 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002441 }
2442 }else{
2443 /* we could have it if we want it */
2444 sem_post(pSem);
2445 }
2446 }
drh308c2a52010-05-14 11:30:18 +00002447 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002448
2449 *pResOut = reserved;
2450 return rc;
2451}
2452
drh6b9d6dd2008-12-03 19:34:47 +00002453/*
drh308c2a52010-05-14 11:30:18 +00002454** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002455** of the following:
2456**
2457** (1) SHARED_LOCK
2458** (2) RESERVED_LOCK
2459** (3) PENDING_LOCK
2460** (4) EXCLUSIVE_LOCK
2461**
2462** Sometimes when requesting one lock state, additional lock states
2463** are inserted in between. The locking might fail on one of the later
2464** transitions leaving the lock state different from what it started but
2465** still short of its goal. The following chart shows the allowed
2466** transitions and the inserted intermediate states:
2467**
2468** UNLOCKED -> SHARED
2469** SHARED -> RESERVED
2470** SHARED -> (PENDING) -> EXCLUSIVE
2471** RESERVED -> (PENDING) -> EXCLUSIVE
2472** PENDING -> EXCLUSIVE
2473**
2474** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2475** lock states in the sqlite3_file structure, but all locks SHARED or
2476** above are really EXCLUSIVE locks and exclude all other processes from
2477** access the file.
2478**
2479** This routine will only increase a lock. Use the sqlite3OsUnlock()
2480** routine to lower a locking level.
2481*/
drh308c2a52010-05-14 11:30:18 +00002482static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002483 unixFile *pFile = (unixFile*)id;
2484 int fd;
drh8af6c222010-05-14 12:43:01 +00002485 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002486 int rc = SQLITE_OK;
2487
2488 /* if we already have a lock, it is exclusive.
2489 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002490 if (pFile->eFileLock > NO_LOCK) {
2491 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002492 rc = SQLITE_OK;
2493 goto sem_end_lock;
2494 }
2495
2496 /* lock semaphore now but bail out when already locked. */
2497 if( sem_trywait(pSem)==-1 ){
2498 rc = SQLITE_BUSY;
2499 goto sem_end_lock;
2500 }
2501
2502 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002503 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002504
2505 sem_end_lock:
2506 return rc;
2507}
2508
drh6b9d6dd2008-12-03 19:34:47 +00002509/*
drh308c2a52010-05-14 11:30:18 +00002510** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002511** must be either NO_LOCK or SHARED_LOCK.
2512**
2513** If the locking level of the file descriptor is already at or below
2514** the requested locking level, this routine is a no-op.
2515*/
drh308c2a52010-05-14 11:30:18 +00002516static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002517 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002518 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002519
2520 assert( pFile );
2521 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002522 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002523 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002524 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002525
2526 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002527 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002528 return SQLITE_OK;
2529 }
2530
2531 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002532 if (eFileLock==SHARED_LOCK) {
2533 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002534 return SQLITE_OK;
2535 }
2536
2537 /* no, really unlock. */
2538 if ( sem_post(pSem)==-1 ) {
2539 int rc, tErrno = errno;
2540 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2541 if( IS_LOCK_ERROR(rc) ){
2542 pFile->lastErrno = tErrno;
2543 }
2544 return rc;
2545 }
drh308c2a52010-05-14 11:30:18 +00002546 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002547 return SQLITE_OK;
2548}
2549
2550/*
2551 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002552 */
drh734c9862008-11-28 15:37:20 +00002553static int semClose(sqlite3_file *id) {
2554 if( id ){
2555 unixFile *pFile = (unixFile*)id;
2556 semUnlock(id, NO_LOCK);
2557 assert( pFile );
2558 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002559 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002560 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002561 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002562 }
2563 return SQLITE_OK;
2564}
2565
2566#endif /* OS_VXWORKS */
2567/*
2568** Named semaphore locking is only available on VxWorks.
2569**
2570*************** End of the named semaphore lock implementation ****************
2571******************************************************************************/
2572
2573
2574/******************************************************************************
2575*************************** Begin AFP Locking *********************************
2576**
2577** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2578** on Apple Macintosh computers - both OS9 and OSX.
2579**
2580** Third-party implementations of AFP are available. But this code here
2581** only works on OSX.
2582*/
2583
drhd2cb50b2009-01-09 21:41:17 +00002584#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002585/*
2586** The afpLockingContext structure contains all afp lock specific state
2587*/
drhbfe66312006-10-03 17:40:40 +00002588typedef struct afpLockingContext afpLockingContext;
2589struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002590 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002591 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002592};
2593
2594struct ByteRangeLockPB2
2595{
2596 unsigned long long offset; /* offset to first byte to lock */
2597 unsigned long long length; /* nbr of bytes to lock */
2598 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2599 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2600 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2601 int fd; /* file desc to assoc this lock with */
2602};
2603
drhfd131da2007-08-07 17:13:03 +00002604#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002605
drh6b9d6dd2008-12-03 19:34:47 +00002606/*
2607** This is a utility for setting or clearing a bit-range lock on an
2608** AFP filesystem.
2609**
2610** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2611*/
2612static int afpSetLock(
2613 const char *path, /* Name of the file to be locked or unlocked */
2614 unixFile *pFile, /* Open file descriptor on path */
2615 unsigned long long offset, /* First byte to be locked */
2616 unsigned long long length, /* Number of bytes to lock */
2617 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002618){
drh6b9d6dd2008-12-03 19:34:47 +00002619 struct ByteRangeLockPB2 pb;
2620 int err;
drhbfe66312006-10-03 17:40:40 +00002621
2622 pb.unLockFlag = setLockFlag ? 0 : 1;
2623 pb.startEndFlag = 0;
2624 pb.offset = offset;
2625 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002626 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002627
drh308c2a52010-05-14 11:30:18 +00002628 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002629 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002630 offset, length));
drhbfe66312006-10-03 17:40:40 +00002631 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2632 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002633 int rc;
2634 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002635 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2636 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002637#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2638 rc = SQLITE_BUSY;
2639#else
drh734c9862008-11-28 15:37:20 +00002640 rc = sqliteErrorFromPosixError(tErrno,
2641 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002642#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002643 if( IS_LOCK_ERROR(rc) ){
2644 pFile->lastErrno = tErrno;
2645 }
2646 return rc;
drhbfe66312006-10-03 17:40:40 +00002647 } else {
aswift5b1a2562008-08-22 00:22:35 +00002648 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002649 }
2650}
2651
drh6b9d6dd2008-12-03 19:34:47 +00002652/*
2653** This routine checks if there is a RESERVED lock held on the specified
2654** file by this or any other process. If such a lock is held, set *pResOut
2655** to a non-zero value otherwise *pResOut is set to zero. The return value
2656** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2657*/
danielk1977e339d652008-06-28 11:23:00 +00002658static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002659 int rc = SQLITE_OK;
2660 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002661 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002662 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002663
aswift5b1a2562008-08-22 00:22:35 +00002664 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2665
2666 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002667 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002668 if( context->reserved ){
2669 *pResOut = 1;
2670 return SQLITE_OK;
2671 }
drh8af6c222010-05-14 12:43:01 +00002672 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002673
2674 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002675 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002676 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002677 }
2678
2679 /* Otherwise see if some other process holds it.
2680 */
aswift5b1a2562008-08-22 00:22:35 +00002681 if( !reserved ){
2682 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002683 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002684 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002685 /* if we succeeded in taking the reserved lock, unlock it to restore
2686 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002687 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002688 } else {
2689 /* if we failed to get the lock then someone else must have it */
2690 reserved = 1;
2691 }
2692 if( IS_LOCK_ERROR(lrc) ){
2693 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002694 }
2695 }
drhbfe66312006-10-03 17:40:40 +00002696
drh7ed97b92010-01-20 13:07:21 +00002697 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002698 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002699
2700 *pResOut = reserved;
2701 return rc;
drhbfe66312006-10-03 17:40:40 +00002702}
2703
drh6b9d6dd2008-12-03 19:34:47 +00002704/*
drh308c2a52010-05-14 11:30:18 +00002705** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002706** of the following:
2707**
2708** (1) SHARED_LOCK
2709** (2) RESERVED_LOCK
2710** (3) PENDING_LOCK
2711** (4) EXCLUSIVE_LOCK
2712**
2713** Sometimes when requesting one lock state, additional lock states
2714** are inserted in between. The locking might fail on one of the later
2715** transitions leaving the lock state different from what it started but
2716** still short of its goal. The following chart shows the allowed
2717** transitions and the inserted intermediate states:
2718**
2719** UNLOCKED -> SHARED
2720** SHARED -> RESERVED
2721** SHARED -> (PENDING) -> EXCLUSIVE
2722** RESERVED -> (PENDING) -> EXCLUSIVE
2723** PENDING -> EXCLUSIVE
2724**
2725** This routine will only increase a lock. Use the sqlite3OsUnlock()
2726** routine to lower a locking level.
2727*/
drh308c2a52010-05-14 11:30:18 +00002728static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002729 int rc = SQLITE_OK;
2730 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002731 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002732 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002733
2734 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002735 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2736 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002737 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002738
drhbfe66312006-10-03 17:40:40 +00002739 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002740 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002741 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002742 */
drh308c2a52010-05-14 11:30:18 +00002743 if( pFile->eFileLock>=eFileLock ){
2744 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2745 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002746 return SQLITE_OK;
2747 }
2748
2749 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002750 ** (1) We never move from unlocked to anything higher than shared lock.
2751 ** (2) SQLite never explicitly requests a pendig lock.
2752 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002753 */
drh308c2a52010-05-14 11:30:18 +00002754 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2755 assert( eFileLock!=PENDING_LOCK );
2756 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002757
drh8af6c222010-05-14 12:43:01 +00002758 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002759 */
drh6c7d5c52008-11-21 20:32:33 +00002760 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002761 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002762
2763 /* If some thread using this PID has a lock via a different unixFile*
2764 ** handle that precludes the requested lock, return BUSY.
2765 */
drh8af6c222010-05-14 12:43:01 +00002766 if( (pFile->eFileLock!=pInode->eFileLock &&
2767 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002768 ){
2769 rc = SQLITE_BUSY;
2770 goto afp_end_lock;
2771 }
2772
2773 /* If a SHARED lock is requested, and some thread using this PID already
2774 ** has a SHARED or RESERVED lock, then increment reference counts and
2775 ** return SQLITE_OK.
2776 */
drh308c2a52010-05-14 11:30:18 +00002777 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002778 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002779 assert( eFileLock==SHARED_LOCK );
2780 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002781 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002782 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002783 pInode->nShared++;
2784 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002785 goto afp_end_lock;
2786 }
drhbfe66312006-10-03 17:40:40 +00002787
2788 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002789 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2790 ** be released.
2791 */
drh308c2a52010-05-14 11:30:18 +00002792 if( eFileLock==SHARED_LOCK
2793 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002794 ){
2795 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002796 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002797 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002798 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002799 goto afp_end_lock;
2800 }
2801 }
2802
2803 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002804 ** operating system calls for the specified lock.
2805 */
drh308c2a52010-05-14 11:30:18 +00002806 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002807 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002808 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002809
drh8af6c222010-05-14 12:43:01 +00002810 assert( pInode->nShared==0 );
2811 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002812
2813 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002814 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002815 /* note that the quality of the randomness doesn't matter that much */
2816 lk = random();
drh8af6c222010-05-14 12:43:01 +00002817 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002818 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002819 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002820 if( IS_LOCK_ERROR(lrc1) ){
2821 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002822 }
aswift5b1a2562008-08-22 00:22:35 +00002823 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002824 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002825
aswift5b1a2562008-08-22 00:22:35 +00002826 if( IS_LOCK_ERROR(lrc1) ) {
2827 pFile->lastErrno = lrc1Errno;
2828 rc = lrc1;
2829 goto afp_end_lock;
2830 } else if( IS_LOCK_ERROR(lrc2) ){
2831 rc = lrc2;
2832 goto afp_end_lock;
2833 } else if( lrc1 != SQLITE_OK ) {
2834 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002835 } else {
drh308c2a52010-05-14 11:30:18 +00002836 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002837 pInode->nLock++;
2838 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002839 }
drh8af6c222010-05-14 12:43:01 +00002840 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002841 /* We are trying for an exclusive lock but another thread in this
2842 ** same process is still holding a shared lock. */
2843 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002844 }else{
2845 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2846 ** assumed that there is a SHARED or greater lock on the file
2847 ** already.
2848 */
2849 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002850 assert( 0!=pFile->eFileLock );
2851 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002852 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002853 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002854 if( !failed ){
2855 context->reserved = 1;
2856 }
drhbfe66312006-10-03 17:40:40 +00002857 }
drh308c2a52010-05-14 11:30:18 +00002858 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002859 /* Acquire an EXCLUSIVE lock */
2860
2861 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002862 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002863 */
drh6b9d6dd2008-12-03 19:34:47 +00002864 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002865 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002866 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002867 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002868 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002869 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002870 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002871 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002872 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2873 ** a critical I/O error
2874 */
2875 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2876 SQLITE_IOERR_LOCK;
2877 goto afp_end_lock;
2878 }
2879 }else{
aswift5b1a2562008-08-22 00:22:35 +00002880 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002881 }
2882 }
aswift5b1a2562008-08-22 00:22:35 +00002883 if( failed ){
2884 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002885 }
2886 }
2887
2888 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002889 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002890 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002891 }else if( eFileLock==EXCLUSIVE_LOCK ){
2892 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002893 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002894 }
2895
2896afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002897 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002898 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2899 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002900 return rc;
2901}
2902
2903/*
drh308c2a52010-05-14 11:30:18 +00002904** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002905** must be either NO_LOCK or SHARED_LOCK.
2906**
2907** If the locking level of the file descriptor is already at or below
2908** the requested locking level, this routine is a no-op.
2909*/
drh308c2a52010-05-14 11:30:18 +00002910static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002911 int rc = SQLITE_OK;
2912 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002913 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002914 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2915 int skipShared = 0;
2916#ifdef SQLITE_TEST
2917 int h = pFile->h;
2918#endif
drhbfe66312006-10-03 17:40:40 +00002919
2920 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002921 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002922 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002923 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002924
drh308c2a52010-05-14 11:30:18 +00002925 assert( eFileLock<=SHARED_LOCK );
2926 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002927 return SQLITE_OK;
2928 }
drh6c7d5c52008-11-21 20:32:33 +00002929 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002930 pInode = pFile->pInode;
2931 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002932 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002933 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002934 SimulateIOErrorBenign(1);
2935 SimulateIOError( h=(-1) )
2936 SimulateIOErrorBenign(0);
2937
drhd3d8c042012-05-29 17:02:40 +00002938#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002939 /* When reducing a lock such that other processes can start
2940 ** reading the database file again, make sure that the
2941 ** transaction counter was updated if any part of the database
2942 ** file changed. If the transaction counter is not updated,
2943 ** other connections to the same file might not realize that
2944 ** the file has changed and hence might not know to flush their
2945 ** cache. The use of a stale cache can lead to database corruption.
2946 */
2947 assert( pFile->inNormalWrite==0
2948 || pFile->dbUpdate==0
2949 || pFile->transCntrChng==1 );
2950 pFile->inNormalWrite = 0;
2951#endif
aswiftaebf4132008-11-21 00:10:35 +00002952
drh308c2a52010-05-14 11:30:18 +00002953 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002954 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002955 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002956 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002957 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002958 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2959 } else {
2960 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002961 }
2962 }
drh308c2a52010-05-14 11:30:18 +00002963 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002964 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002965 }
drh308c2a52010-05-14 11:30:18 +00002966 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002967 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2968 if( !rc ){
2969 context->reserved = 0;
2970 }
aswiftaebf4132008-11-21 00:10:35 +00002971 }
drh8af6c222010-05-14 12:43:01 +00002972 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2973 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002974 }
aswiftaebf4132008-11-21 00:10:35 +00002975 }
drh308c2a52010-05-14 11:30:18 +00002976 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002977
drh7ed97b92010-01-20 13:07:21 +00002978 /* Decrement the shared lock counter. Release the lock using an
2979 ** OS call only when all threads in this same process have released
2980 ** the lock.
2981 */
drh8af6c222010-05-14 12:43:01 +00002982 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2983 pInode->nShared--;
2984 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002985 SimulateIOErrorBenign(1);
2986 SimulateIOError( h=(-1) )
2987 SimulateIOErrorBenign(0);
2988 if( !skipShared ){
2989 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2990 }
2991 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002992 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002993 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002994 }
2995 }
2996 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002997 pInode->nLock--;
2998 assert( pInode->nLock>=0 );
2999 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003000 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003001 }
3002 }
drhbfe66312006-10-03 17:40:40 +00003003 }
drh7ed97b92010-01-20 13:07:21 +00003004
drh6c7d5c52008-11-21 20:32:33 +00003005 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003006 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003007 return rc;
3008}
3009
3010/*
drh339eb0b2008-03-07 15:34:11 +00003011** Close a file & cleanup AFP specific locking context
3012*/
danielk1977e339d652008-06-28 11:23:00 +00003013static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003014 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003015 if( id ){
3016 unixFile *pFile = (unixFile*)id;
3017 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003018 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003019 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003020 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003021 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003022 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003023 ** the last lock is cleared.
3024 */
dan08da86a2009-08-21 17:18:03 +00003025 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003026 }
danb0ac3e32010-06-16 10:55:42 +00003027 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003028 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003029 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003030 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003031 }
drh7ed97b92010-01-20 13:07:21 +00003032 return rc;
drhbfe66312006-10-03 17:40:40 +00003033}
3034
drhd2cb50b2009-01-09 21:41:17 +00003035#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003036/*
3037** The code above is the AFP lock implementation. The code is specific
3038** to MacOSX and does not work on other unix platforms. No alternative
3039** is available. If you don't compile for a mac, then the "unix-afp"
3040** VFS is not available.
3041**
3042********************* End of the AFP lock implementation **********************
3043******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003044
drh7ed97b92010-01-20 13:07:21 +00003045/******************************************************************************
3046*************************** Begin NFS Locking ********************************/
3047
3048#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3049/*
drh308c2a52010-05-14 11:30:18 +00003050 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003051 ** must be either NO_LOCK or SHARED_LOCK.
3052 **
3053 ** If the locking level of the file descriptor is already at or below
3054 ** the requested locking level, this routine is a no-op.
3055 */
drh308c2a52010-05-14 11:30:18 +00003056static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003057 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003058}
3059
3060#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3061/*
3062** The code above is the NFS lock implementation. The code is specific
3063** to MacOSX and does not work on other unix platforms. No alternative
3064** is available.
3065**
3066********************* End of the NFS lock implementation **********************
3067******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003068
3069/******************************************************************************
3070**************** Non-locking sqlite3_file methods *****************************
3071**
3072** The next division contains implementations for all methods of the
3073** sqlite3_file object other than the locking methods. The locking
3074** methods were defined in divisions above (one locking method per
3075** division). Those methods that are common to all locking modes
3076** are gather together into this division.
3077*/
drhbfe66312006-10-03 17:40:40 +00003078
3079/*
drh734c9862008-11-28 15:37:20 +00003080** Seek to the offset passed as the second argument, then read cnt
3081** bytes into pBuf. Return the number of bytes actually read.
3082**
3083** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3084** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3085** one system to another. Since SQLite does not define USE_PREAD
3086** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3087** See tickets #2741 and #2681.
3088**
3089** To avoid stomping the errno value on a failed read the lastErrno value
3090** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003091*/
drh734c9862008-11-28 15:37:20 +00003092static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3093 int got;
drh58024642011-11-07 18:16:00 +00003094 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003095#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003096 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003097#endif
drh734c9862008-11-28 15:37:20 +00003098 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003099 assert( cnt==(cnt&0x1ffff) );
3100 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003101 do{
drh734c9862008-11-28 15:37:20 +00003102#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003103 got = osPread(id->h, pBuf, cnt, offset);
3104 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003105#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003106 got = osPread64(id->h, pBuf, cnt, offset);
3107 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003108#else
drh58024642011-11-07 18:16:00 +00003109 newOffset = lseek(id->h, offset, SEEK_SET);
3110 SimulateIOError( newOffset-- );
3111 if( newOffset!=offset ){
3112 if( newOffset == -1 ){
3113 ((unixFile*)id)->lastErrno = errno;
3114 }else{
drhf2f105d2012-08-20 15:53:54 +00003115 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003116 }
3117 return -1;
drh734c9862008-11-28 15:37:20 +00003118 }
drh58024642011-11-07 18:16:00 +00003119 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003120#endif
drh58024642011-11-07 18:16:00 +00003121 if( got==cnt ) break;
3122 if( got<0 ){
3123 if( errno==EINTR ){ got = 1; continue; }
3124 prior = 0;
3125 ((unixFile*)id)->lastErrno = errno;
3126 break;
3127 }else if( got>0 ){
3128 cnt -= got;
3129 offset += got;
3130 prior += got;
3131 pBuf = (void*)(got + (char*)pBuf);
3132 }
3133 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003134 TIMER_END;
drh58024642011-11-07 18:16:00 +00003135 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3136 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3137 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003138}
3139
3140/*
drh734c9862008-11-28 15:37:20 +00003141** Read data from a file into a buffer. Return SQLITE_OK if all
3142** bytes were read successfully and SQLITE_IOERR if anything goes
3143** wrong.
drh339eb0b2008-03-07 15:34:11 +00003144*/
drh734c9862008-11-28 15:37:20 +00003145static int unixRead(
3146 sqlite3_file *id,
3147 void *pBuf,
3148 int amt,
3149 sqlite3_int64 offset
3150){
dan08da86a2009-08-21 17:18:03 +00003151 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003152 int got;
3153 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003154 assert( offset>=0 );
3155 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003156
dan08da86a2009-08-21 17:18:03 +00003157 /* If this is a database file (not a journal, master-journal or temp
3158 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003159#if 0
dane946c392009-08-22 11:39:46 +00003160 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003161 || offset>=PENDING_BYTE+512
3162 || offset+amt<=PENDING_BYTE
3163 );
dan7c246102010-04-12 19:00:29 +00003164#endif
drh08c6d442009-02-09 17:34:07 +00003165
drh9b4c59f2013-04-15 17:03:42 +00003166#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003167 /* Deal with as much of this read request as possible by transfering
3168 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003169 if( offset<pFile->mmapSize ){
3170 if( offset+amt <= pFile->mmapSize ){
3171 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3172 return SQLITE_OK;
3173 }else{
3174 int nCopy = pFile->mmapSize - offset;
3175 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3176 pBuf = &((u8 *)pBuf)[nCopy];
3177 amt -= nCopy;
3178 offset += nCopy;
3179 }
3180 }
drh6e0b6d52013-04-09 16:19:20 +00003181#endif
danf23da962013-03-23 21:00:41 +00003182
dan08da86a2009-08-21 17:18:03 +00003183 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003184 if( got==amt ){
3185 return SQLITE_OK;
3186 }else if( got<0 ){
3187 /* lastErrno set by seekAndRead */
3188 return SQLITE_IOERR_READ;
3189 }else{
dan08da86a2009-08-21 17:18:03 +00003190 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003191 /* Unread parts of the buffer must be zero-filled */
3192 memset(&((char*)pBuf)[got], 0, amt-got);
3193 return SQLITE_IOERR_SHORT_READ;
3194 }
3195}
3196
3197/*
dan47a2b4a2013-04-26 16:09:29 +00003198** Attempt to seek the file-descriptor passed as the first argument to
3199** absolute offset iOff, then attempt to write nBuf bytes of data from
3200** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3201** return the actual number of bytes written (which may be less than
3202** nBuf).
3203*/
3204static int seekAndWriteFd(
3205 int fd, /* File descriptor to write to */
3206 i64 iOff, /* File offset to begin writing at */
3207 const void *pBuf, /* Copy data from this buffer to the file */
3208 int nBuf, /* Size of buffer pBuf in bytes */
3209 int *piErrno /* OUT: Error number if error occurs */
3210){
3211 int rc = 0; /* Value returned by system call */
3212
3213 assert( nBuf==(nBuf&0x1ffff) );
3214 nBuf &= 0x1ffff;
3215 TIMER_START;
3216
3217#if defined(USE_PREAD)
3218 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3219#elif defined(USE_PREAD64)
3220 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3221#else
3222 do{
3223 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3224 SimulateIOError( iSeek-- );
3225
3226 if( iSeek!=iOff ){
3227 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3228 return -1;
3229 }
3230 rc = osWrite(fd, pBuf, nBuf);
3231 }while( rc<0 && errno==EINTR );
3232#endif
3233
3234 TIMER_END;
3235 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3236
3237 if( rc<0 && piErrno ) *piErrno = errno;
3238 return rc;
3239}
3240
3241
3242/*
drh734c9862008-11-28 15:37:20 +00003243** Seek to the offset in id->offset then read cnt bytes into pBuf.
3244** Return the number of bytes actually read. Update the offset.
3245**
3246** To avoid stomping the errno value on a failed write the lastErrno value
3247** is set before returning.
3248*/
3249static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003250 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003251}
3252
3253
3254/*
3255** Write data from a buffer into a file. Return SQLITE_OK on success
3256** or some other error code on failure.
3257*/
3258static int unixWrite(
3259 sqlite3_file *id,
3260 const void *pBuf,
3261 int amt,
3262 sqlite3_int64 offset
3263){
dan08da86a2009-08-21 17:18:03 +00003264 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003265 int wrote = 0;
3266 assert( id );
3267 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003268
dan08da86a2009-08-21 17:18:03 +00003269 /* If this is a database file (not a journal, master-journal or temp
3270 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003271#if 0
dane946c392009-08-22 11:39:46 +00003272 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003273 || offset>=PENDING_BYTE+512
3274 || offset+amt<=PENDING_BYTE
3275 );
dan7c246102010-04-12 19:00:29 +00003276#endif
drh08c6d442009-02-09 17:34:07 +00003277
drhd3d8c042012-05-29 17:02:40 +00003278#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003279 /* If we are doing a normal write to a database file (as opposed to
3280 ** doing a hot-journal rollback or a write to some file other than a
3281 ** normal database file) then record the fact that the database
3282 ** has changed. If the transaction counter is modified, record that
3283 ** fact too.
3284 */
dan08da86a2009-08-21 17:18:03 +00003285 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003286 pFile->dbUpdate = 1; /* The database has been modified */
3287 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003288 int rc;
drh8f941bc2009-01-14 23:03:40 +00003289 char oldCntr[4];
3290 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003291 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003292 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003293 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003294 pFile->transCntrChng = 1; /* The transaction counter has changed */
3295 }
3296 }
3297 }
3298#endif
3299
drh9b4c59f2013-04-15 17:03:42 +00003300#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003301 /* Deal with as much of this write request as possible by transfering
3302 ** data from the memory mapping using memcpy(). */
3303 if( offset<pFile->mmapSize ){
3304 if( offset+amt <= pFile->mmapSize ){
3305 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3306 return SQLITE_OK;
3307 }else{
3308 int nCopy = pFile->mmapSize - offset;
3309 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3310 pBuf = &((u8 *)pBuf)[nCopy];
3311 amt -= nCopy;
3312 offset += nCopy;
3313 }
3314 }
drh6e0b6d52013-04-09 16:19:20 +00003315#endif
danf23da962013-03-23 21:00:41 +00003316
dan08da86a2009-08-21 17:18:03 +00003317 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003318 amt -= wrote;
3319 offset += wrote;
3320 pBuf = &((char*)pBuf)[wrote];
3321 }
3322 SimulateIOError(( wrote=(-1), amt=1 ));
3323 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003324
drh734c9862008-11-28 15:37:20 +00003325 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003326 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003327 /* lastErrno set by seekAndWrite */
3328 return SQLITE_IOERR_WRITE;
3329 }else{
dan08da86a2009-08-21 17:18:03 +00003330 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003331 return SQLITE_FULL;
3332 }
3333 }
dan6e09d692010-07-27 18:34:15 +00003334
drh734c9862008-11-28 15:37:20 +00003335 return SQLITE_OK;
3336}
3337
3338#ifdef SQLITE_TEST
3339/*
3340** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003341** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003342*/
3343int sqlite3_sync_count = 0;
3344int sqlite3_fullsync_count = 0;
3345#endif
3346
3347/*
drh89240432009-03-25 01:06:01 +00003348** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003349** Others do no. To be safe, we will stick with the (slightly slower)
3350** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003351** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003352*/
drh20f8e132011-08-31 21:01:55 +00003353#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003354# define fdatasync fsync
3355#endif
3356
3357/*
3358** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3359** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3360** only available on Mac OS X. But that could change.
3361*/
3362#ifdef F_FULLFSYNC
3363# define HAVE_FULLFSYNC 1
3364#else
3365# define HAVE_FULLFSYNC 0
3366#endif
3367
3368
3369/*
3370** The fsync() system call does not work as advertised on many
3371** unix systems. The following procedure is an attempt to make
3372** it work better.
3373**
3374** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3375** for testing when we want to run through the test suite quickly.
3376** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3377** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3378** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003379**
3380** SQLite sets the dataOnly flag if the size of the file is unchanged.
3381** The idea behind dataOnly is that it should only write the file content
3382** to disk, not the inode. We only set dataOnly if the file size is
3383** unchanged since the file size is part of the inode. However,
3384** Ted Ts'o tells us that fdatasync() will also write the inode if the
3385** file size has changed. The only real difference between fdatasync()
3386** and fsync(), Ted tells us, is that fdatasync() will not flush the
3387** inode if the mtime or owner or other inode attributes have changed.
3388** We only care about the file size, not the other file attributes, so
3389** as far as SQLite is concerned, an fdatasync() is always adequate.
3390** So, we always use fdatasync() if it is available, regardless of
3391** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003392*/
3393static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003394 int rc;
drh734c9862008-11-28 15:37:20 +00003395
3396 /* The following "ifdef/elif/else/" block has the same structure as
3397 ** the one below. It is replicated here solely to avoid cluttering
3398 ** up the real code with the UNUSED_PARAMETER() macros.
3399 */
3400#ifdef SQLITE_NO_SYNC
3401 UNUSED_PARAMETER(fd);
3402 UNUSED_PARAMETER(fullSync);
3403 UNUSED_PARAMETER(dataOnly);
3404#elif HAVE_FULLFSYNC
3405 UNUSED_PARAMETER(dataOnly);
3406#else
3407 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003408 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003409#endif
3410
3411 /* Record the number of times that we do a normal fsync() and
3412 ** FULLSYNC. This is used during testing to verify that this procedure
3413 ** gets called with the correct arguments.
3414 */
3415#ifdef SQLITE_TEST
3416 if( fullSync ) sqlite3_fullsync_count++;
3417 sqlite3_sync_count++;
3418#endif
3419
3420 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3421 ** no-op
3422 */
3423#ifdef SQLITE_NO_SYNC
3424 rc = SQLITE_OK;
3425#elif HAVE_FULLFSYNC
3426 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003427 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003428 }else{
3429 rc = 1;
3430 }
3431 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003432 ** It shouldn't be possible for fullfsync to fail on the local
3433 ** file system (on OSX), so failure indicates that FULLFSYNC
3434 ** isn't supported for this file system. So, attempt an fsync
3435 ** and (for now) ignore the overhead of a superfluous fcntl call.
3436 ** It'd be better to detect fullfsync support once and avoid
3437 ** the fcntl call every time sync is called.
3438 */
drh734c9862008-11-28 15:37:20 +00003439 if( rc ) rc = fsync(fd);
3440
drh7ed97b92010-01-20 13:07:21 +00003441#elif defined(__APPLE__)
3442 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3443 ** so currently we default to the macro that redefines fdatasync to fsync
3444 */
3445 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003446#else
drh0b647ff2009-03-21 14:41:04 +00003447 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003448#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003449 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003450 rc = fsync(fd);
3451 }
drh0b647ff2009-03-21 14:41:04 +00003452#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003453#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3454
3455 if( OS_VXWORKS && rc!= -1 ){
3456 rc = 0;
3457 }
chw97185482008-11-17 08:05:31 +00003458 return rc;
drhbfe66312006-10-03 17:40:40 +00003459}
3460
drh734c9862008-11-28 15:37:20 +00003461/*
drh0059eae2011-08-08 23:48:40 +00003462** Open a file descriptor to the directory containing file zFilename.
3463** If successful, *pFd is set to the opened file descriptor and
3464** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3465** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3466** value.
3467**
drh90315a22011-08-10 01:52:12 +00003468** The directory file descriptor is used for only one thing - to
3469** fsync() a directory to make sure file creation and deletion events
3470** are flushed to disk. Such fsyncs are not needed on newer
3471** journaling filesystems, but are required on older filesystems.
3472**
3473** This routine can be overridden using the xSetSysCall interface.
3474** The ability to override this routine was added in support of the
3475** chromium sandbox. Opening a directory is a security risk (we are
3476** told) so making it overrideable allows the chromium sandbox to
3477** replace this routine with a harmless no-op. To make this routine
3478** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3479** *pFd set to a negative number.
3480**
drh0059eae2011-08-08 23:48:40 +00003481** If SQLITE_OK is returned, the caller is responsible for closing
3482** the file descriptor *pFd using close().
3483*/
3484static int openDirectory(const char *zFilename, int *pFd){
3485 int ii;
3486 int fd = -1;
3487 char zDirname[MAX_PATHNAME+1];
3488
3489 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3490 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3491 if( ii>0 ){
3492 zDirname[ii] = '\0';
3493 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3494 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003495 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3496 }
3497 }
3498 *pFd = fd;
3499 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3500}
3501
3502/*
drh734c9862008-11-28 15:37:20 +00003503** Make sure all writes to a particular file are committed to disk.
3504**
3505** If dataOnly==0 then both the file itself and its metadata (file
3506** size, access time, etc) are synced. If dataOnly!=0 then only the
3507** file data is synced.
3508**
3509** Under Unix, also make sure that the directory entry for the file
3510** has been created by fsync-ing the directory that contains the file.
3511** If we do not do this and we encounter a power failure, the directory
3512** entry for the journal might not exist after we reboot. The next
3513** SQLite to access the file will not know that the journal exists (because
3514** the directory entry for the journal was never created) and the transaction
3515** will not roll back - possibly leading to database corruption.
3516*/
3517static int unixSync(sqlite3_file *id, int flags){
3518 int rc;
3519 unixFile *pFile = (unixFile*)id;
3520
3521 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3522 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3523
3524 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3525 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3526 || (flags&0x0F)==SQLITE_SYNC_FULL
3527 );
3528
3529 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3530 ** line is to test that doing so does not cause any problems.
3531 */
3532 SimulateDiskfullError( return SQLITE_FULL );
3533
3534 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003535 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003536 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3537 SimulateIOError( rc=1 );
3538 if( rc ){
3539 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003540 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003541 }
drh0059eae2011-08-08 23:48:40 +00003542
3543 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003544 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003545 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003546 */
3547 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3548 int dirfd;
3549 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003550 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003551 rc = osOpenDirectory(pFile->zPath, &dirfd);
3552 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003553 full_fsync(dirfd, 0, 0);
3554 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003555 }else if( rc==SQLITE_CANTOPEN ){
3556 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003557 }
drh0059eae2011-08-08 23:48:40 +00003558 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003559 }
3560 return rc;
3561}
3562
3563/*
3564** Truncate an open file to a specified size
3565*/
3566static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003567 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003568 int rc;
dan6e09d692010-07-27 18:34:15 +00003569 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003570 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003571
3572 /* If the user has configured a chunk-size for this file, truncate the
3573 ** file so that it consists of an integer number of chunks (i.e. the
3574 ** actual file size after the operation may be larger than the requested
3575 ** size).
3576 */
drhb8af4b72012-04-05 20:04:39 +00003577 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003578 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3579 }
3580
drhff812312011-02-23 13:33:46 +00003581 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003582 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003583 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003584 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003585 }else{
drhd3d8c042012-05-29 17:02:40 +00003586#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003587 /* If we are doing a normal write to a database file (as opposed to
3588 ** doing a hot-journal rollback or a write to some file other than a
3589 ** normal database file) and we truncate the file to zero length,
3590 ** that effectively updates the change counter. This might happen
3591 ** when restoring a database using the backup API from a zero-length
3592 ** source.
3593 */
dan6e09d692010-07-27 18:34:15 +00003594 if( pFile->inNormalWrite && nByte==0 ){
3595 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003596 }
danf23da962013-03-23 21:00:41 +00003597#endif
danc0003312013-03-22 17:46:11 +00003598
mistachkine98844f2013-08-24 00:59:24 +00003599#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003600 /* If the file was just truncated to a size smaller than the currently
3601 ** mapped region, reduce the effective mapping size as well. SQLite will
3602 ** use read() and write() to access data beyond this point from now on.
3603 */
3604 if( nByte<pFile->mmapSize ){
3605 pFile->mmapSize = nByte;
3606 }
mistachkine98844f2013-08-24 00:59:24 +00003607#endif
drh3313b142009-11-06 04:13:18 +00003608
drh734c9862008-11-28 15:37:20 +00003609 return SQLITE_OK;
3610 }
3611}
3612
3613/*
3614** Determine the current size of a file in bytes
3615*/
3616static int unixFileSize(sqlite3_file *id, i64 *pSize){
3617 int rc;
3618 struct stat buf;
3619 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003620 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003621 SimulateIOError( rc=1 );
3622 if( rc!=0 ){
3623 ((unixFile*)id)->lastErrno = errno;
3624 return SQLITE_IOERR_FSTAT;
3625 }
3626 *pSize = buf.st_size;
3627
drh8af6c222010-05-14 12:43:01 +00003628 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003629 ** writes a single byte into that file in order to work around a bug
3630 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3631 ** layers, we need to report this file size as zero even though it is
3632 ** really 1. Ticket #3260.
3633 */
3634 if( *pSize==1 ) *pSize = 0;
3635
3636
3637 return SQLITE_OK;
3638}
3639
drhd2cb50b2009-01-09 21:41:17 +00003640#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003641/*
3642** Handler for proxy-locking file-control verbs. Defined below in the
3643** proxying locking division.
3644*/
3645static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003646#endif
drh715ff302008-12-03 22:32:44 +00003647
dan502019c2010-07-28 14:26:17 +00003648/*
3649** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003650** file-control operation. Enlarge the database to nBytes in size
3651** (rounded up to the next chunk-size). If the database is already
3652** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003653*/
3654static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003655 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003656 i64 nSize; /* Required file size */
3657 struct stat buf; /* Used to hold return values of fstat() */
3658
drh99ab3b12011-03-02 15:09:07 +00003659 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003660
3661 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3662 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003663
dan502019c2010-07-28 14:26:17 +00003664#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003665 /* The code below is handling the return value of osFallocate()
3666 ** correctly. posix_fallocate() is defined to "returns zero on success,
3667 ** or an error number on failure". See the manpage for details. */
3668 int err;
drhff812312011-02-23 13:33:46 +00003669 do{
dan661d71a2011-03-30 19:08:03 +00003670 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3671 }while( err==EINTR );
3672 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003673#else
3674 /* If the OS does not have posix_fallocate(), fake it. First use
3675 ** ftruncate() to set the file size, then write a single byte to
3676 ** the last byte in each block within the extended region. This
3677 ** is the same technique used by glibc to implement posix_fallocate()
3678 ** on systems that do not have a real fallocate() system call.
3679 */
3680 int nBlk = buf.st_blksize; /* File-system block size */
3681 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003682
drhff812312011-02-23 13:33:46 +00003683 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003684 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003685 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003686 }
3687 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003688 while( iWrite<nSize ){
3689 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3690 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003691 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003692 }
dan502019c2010-07-28 14:26:17 +00003693#endif
3694 }
3695 }
3696
mistachkine98844f2013-08-24 00:59:24 +00003697#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003698 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003699 int rc;
3700 if( pFile->szChunk<=0 ){
3701 if( robust_ftruncate(pFile->h, nByte) ){
3702 pFile->lastErrno = errno;
3703 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3704 }
3705 }
3706
3707 rc = unixMapfile(pFile, nByte);
3708 return rc;
3709 }
mistachkine98844f2013-08-24 00:59:24 +00003710#endif
danf23da962013-03-23 21:00:41 +00003711
dan502019c2010-07-28 14:26:17 +00003712 return SQLITE_OK;
3713}
danielk1977ad94b582007-08-20 06:44:22 +00003714
danielk1977e3026632004-06-22 11:29:02 +00003715/*
drhf12b3f62011-12-21 14:42:29 +00003716** If *pArg is inititially negative then this is a query. Set *pArg to
3717** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3718**
3719** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3720*/
3721static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3722 if( *pArg<0 ){
3723 *pArg = (pFile->ctrlFlags & mask)!=0;
3724 }else if( (*pArg)==0 ){
3725 pFile->ctrlFlags &= ~mask;
3726 }else{
3727 pFile->ctrlFlags |= mask;
3728 }
3729}
3730
drh696b33e2012-12-06 19:01:42 +00003731/* Forward declaration */
3732static int unixGetTempname(int nBuf, char *zBuf);
3733
drhf12b3f62011-12-21 14:42:29 +00003734/*
drh9e33c2c2007-08-31 18:34:59 +00003735** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003736*/
drhcc6bb3e2007-08-31 16:11:35 +00003737static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003738 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003739 switch( op ){
3740 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003741 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003742 return SQLITE_OK;
3743 }
drh7708e972008-11-29 00:56:52 +00003744 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003745 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003746 return SQLITE_OK;
3747 }
dan6e09d692010-07-27 18:34:15 +00003748 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003749 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003750 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003751 }
drh9ff27ec2010-05-19 19:26:05 +00003752 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003753 int rc;
3754 SimulateIOErrorBenign(1);
3755 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3756 SimulateIOErrorBenign(0);
3757 return rc;
drhf0b190d2011-07-26 16:03:07 +00003758 }
3759 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003760 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3761 return SQLITE_OK;
3762 }
drhcb15f352011-12-23 01:04:17 +00003763 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3764 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003765 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003766 }
drhde60fc22011-12-14 17:53:36 +00003767 case SQLITE_FCNTL_VFSNAME: {
3768 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3769 return SQLITE_OK;
3770 }
drh696b33e2012-12-06 19:01:42 +00003771 case SQLITE_FCNTL_TEMPFILENAME: {
3772 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3773 if( zTFile ){
3774 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3775 *(char**)pArg = zTFile;
3776 }
3777 return SQLITE_OK;
3778 }
mistachkine98844f2013-08-24 00:59:24 +00003779#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003780 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003781 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003782 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003783 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3784 newLimit = sqlite3GlobalConfig.mxMmap;
3785 }
3786 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003787 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003788 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003789 if( pFile->mmapSize>0 ){
3790 unixUnmapfile(pFile);
3791 rc = unixMapfile(pFile, -1);
3792 }
danbcb8a862013-04-08 15:30:41 +00003793 }
drh34e258c2013-05-23 01:40:53 +00003794 return rc;
danb2d3de32013-03-14 18:34:37 +00003795 }
mistachkine98844f2013-08-24 00:59:24 +00003796#endif
drhd3d8c042012-05-29 17:02:40 +00003797#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003798 /* The pager calls this method to signal that it has done
3799 ** a rollback and that the database is therefore unchanged and
3800 ** it hence it is OK for the transaction change counter to be
3801 ** unchanged.
3802 */
3803 case SQLITE_FCNTL_DB_UNCHANGED: {
3804 ((unixFile*)id)->dbUpdate = 0;
3805 return SQLITE_OK;
3806 }
3807#endif
drhd2cb50b2009-01-09 21:41:17 +00003808#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003809 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003810 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003811 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003812 }
drhd2cb50b2009-01-09 21:41:17 +00003813#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003814 }
drh0b52b7d2011-01-26 19:46:22 +00003815 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003816}
3817
3818/*
danielk1977a3d4c882007-03-23 10:08:38 +00003819** Return the sector size in bytes of the underlying block device for
3820** the specified file. This is almost always 512 bytes, but may be
3821** larger for some devices.
3822**
3823** SQLite code assumes this function cannot fail. It also assumes that
3824** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003825** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003826** same for both.
3827*/
drh537dddf2012-10-26 13:46:24 +00003828#ifndef __QNXNTO__
3829static int unixSectorSize(sqlite3_file *NotUsed){
3830 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003831 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003832}
drh537dddf2012-10-26 13:46:24 +00003833#endif
3834
3835/*
3836** The following version of unixSectorSize() is optimized for QNX.
3837*/
3838#ifdef __QNXNTO__
3839#include <sys/dcmd_blk.h>
3840#include <sys/statvfs.h>
3841static int unixSectorSize(sqlite3_file *id){
3842 unixFile *pFile = (unixFile*)id;
3843 if( pFile->sectorSize == 0 ){
3844 struct statvfs fsInfo;
3845
3846 /* Set defaults for non-supported filesystems */
3847 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3848 pFile->deviceCharacteristics = 0;
3849 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3850 return pFile->sectorSize;
3851 }
3852
3853 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3854 pFile->sectorSize = fsInfo.f_bsize;
3855 pFile->deviceCharacteristics =
3856 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3857 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3858 ** the write succeeds */
3859 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3860 ** so it is ordered */
3861 0;
3862 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3863 pFile->sectorSize = fsInfo.f_bsize;
3864 pFile->deviceCharacteristics =
3865 /* etfs cluster size writes are atomic */
3866 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3867 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3868 ** the write succeeds */
3869 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3870 ** so it is ordered */
3871 0;
3872 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3873 pFile->sectorSize = fsInfo.f_bsize;
3874 pFile->deviceCharacteristics =
3875 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3876 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3877 ** the write succeeds */
3878 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3879 ** so it is ordered */
3880 0;
3881 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3882 pFile->sectorSize = fsInfo.f_bsize;
3883 pFile->deviceCharacteristics =
3884 /* full bitset of atomics from max sector size and smaller */
3885 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3886 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3887 ** so it is ordered */
3888 0;
3889 }else if( strstr(fsInfo.f_basetype, "dos") ){
3890 pFile->sectorSize = fsInfo.f_bsize;
3891 pFile->deviceCharacteristics =
3892 /* full bitset of atomics from max sector size and smaller */
3893 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3894 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3895 ** so it is ordered */
3896 0;
3897 }else{
3898 pFile->deviceCharacteristics =
3899 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3900 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3901 ** the write succeeds */
3902 0;
3903 }
3904 }
3905 /* Last chance verification. If the sector size isn't a multiple of 512
3906 ** then it isn't valid.*/
3907 if( pFile->sectorSize % 512 != 0 ){
3908 pFile->deviceCharacteristics = 0;
3909 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3910 }
3911 return pFile->sectorSize;
3912}
3913#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003914
danielk197790949c22007-08-17 16:50:38 +00003915/*
drhf12b3f62011-12-21 14:42:29 +00003916** Return the device characteristics for the file.
3917**
drhcb15f352011-12-23 01:04:17 +00003918** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3919** However, that choice is contraversial since technically the underlying
3920** file system does not always provide powersafe overwrites. (In other
3921** words, after a power-loss event, parts of the file that were never
3922** written might end up being altered.) However, non-PSOW behavior is very,
3923** very rare. And asserting PSOW makes a large reduction in the amount
3924** of required I/O for journaling, since a lot of padding is eliminated.
3925** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3926** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003927*/
drhf12b3f62011-12-21 14:42:29 +00003928static int unixDeviceCharacteristics(sqlite3_file *id){
3929 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003930 int rc = 0;
3931#ifdef __QNXNTO__
3932 if( p->sectorSize==0 ) unixSectorSize(id);
3933 rc = p->deviceCharacteristics;
3934#endif
drhcb15f352011-12-23 01:04:17 +00003935 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003936 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003937 }
drh537dddf2012-10-26 13:46:24 +00003938 return rc;
danielk197762079062007-08-15 17:08:46 +00003939}
3940
drhd9e5c4f2010-05-12 18:01:39 +00003941#ifndef SQLITE_OMIT_WAL
3942
3943
3944/*
drhd91c68f2010-05-14 14:52:25 +00003945** Object used to represent an shared memory buffer.
3946**
3947** When multiple threads all reference the same wal-index, each thread
3948** has its own unixShm object, but they all point to a single instance
3949** of this unixShmNode object. In other words, each wal-index is opened
3950** only once per process.
3951**
3952** Each unixShmNode object is connected to a single unixInodeInfo object.
3953** We could coalesce this object into unixInodeInfo, but that would mean
3954** every open file that does not use shared memory (in other words, most
3955** open files) would have to carry around this extra information. So
3956** the unixInodeInfo object contains a pointer to this unixShmNode object
3957** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003958**
3959** unixMutexHeld() must be true when creating or destroying
3960** this object or while reading or writing the following fields:
3961**
3962** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003963**
3964** The following fields are read-only after the object is created:
3965**
3966** fid
3967** zFilename
3968**
drhd91c68f2010-05-14 14:52:25 +00003969** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003970** unixMutexHeld() is true when reading or writing any other field
3971** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003972*/
drhd91c68f2010-05-14 14:52:25 +00003973struct unixShmNode {
3974 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003975 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003976 char *zFilename; /* Name of the mmapped file */
3977 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003978 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003979 u16 nRegion; /* Size of array apRegion */
3980 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003981 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003982 int nRef; /* Number of unixShm objects pointing to this */
3983 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003984#ifdef SQLITE_DEBUG
3985 u8 exclMask; /* Mask of exclusive locks held */
3986 u8 sharedMask; /* Mask of shared locks held */
3987 u8 nextShmId; /* Next available unixShm.id value */
3988#endif
3989};
3990
3991/*
drhd9e5c4f2010-05-12 18:01:39 +00003992** Structure used internally by this VFS to record the state of an
3993** open shared memory connection.
3994**
drhd91c68f2010-05-14 14:52:25 +00003995** The following fields are initialized when this object is created and
3996** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003997**
drhd91c68f2010-05-14 14:52:25 +00003998** unixShm.pFile
3999** unixShm.id
4000**
4001** All other fields are read/write. The unixShm.pFile->mutex must be held
4002** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004003*/
4004struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004005 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4006 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004007 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004008 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004009 u16 sharedMask; /* Mask of shared locks held */
4010 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004011};
4012
4013/*
drhd9e5c4f2010-05-12 18:01:39 +00004014** Constants used for locking
4015*/
drhbd9676c2010-06-23 17:58:38 +00004016#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004017#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004018
drhd9e5c4f2010-05-12 18:01:39 +00004019/*
drh73b64e42010-05-30 19:55:15 +00004020** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004021**
4022** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4023** otherwise.
4024*/
4025static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004026 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4027 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004028 int ofst, /* First byte of the locking range */
4029 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004030){
4031 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004032 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004033
drhd91c68f2010-05-14 14:52:25 +00004034 /* Access to the unixShmNode object is serialized by the caller */
4035 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004036
drh73b64e42010-05-30 19:55:15 +00004037 /* Shared locks never span more than one byte */
4038 assert( n==1 || lockType!=F_RDLCK );
4039
4040 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004041 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004042
drh3cb93392011-03-12 18:10:44 +00004043 if( pShmNode->h>=0 ){
4044 /* Initialize the locking parameters */
4045 memset(&f, 0, sizeof(f));
4046 f.l_type = lockType;
4047 f.l_whence = SEEK_SET;
4048 f.l_start = ofst;
4049 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004050
drh3cb93392011-03-12 18:10:44 +00004051 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4052 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4053 }
drhd9e5c4f2010-05-12 18:01:39 +00004054
4055 /* Update the global lock state and do debug tracing */
4056#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004057 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004058 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00004059 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004060 if( rc==SQLITE_OK ){
4061 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004062 OSTRACE(("unlock %d ok", ofst));
4063 pShmNode->exclMask &= ~mask;
4064 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004065 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004066 OSTRACE(("read-lock %d ok", ofst));
4067 pShmNode->exclMask &= ~mask;
4068 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004069 }else{
4070 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004071 OSTRACE(("write-lock %d ok", ofst));
4072 pShmNode->exclMask |= mask;
4073 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004074 }
4075 }else{
4076 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004077 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004078 }else if( lockType==F_RDLCK ){
4079 OSTRACE(("read-lock failed"));
4080 }else{
4081 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004082 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004083 }
4084 }
drh20e1f082010-05-31 16:10:12 +00004085 OSTRACE((" - afterwards %03x,%03x\n",
4086 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004087 }
drhd9e5c4f2010-05-12 18:01:39 +00004088#endif
4089
4090 return rc;
4091}
4092
drhd9e5c4f2010-05-12 18:01:39 +00004093
4094/*
drhd91c68f2010-05-14 14:52:25 +00004095** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004096**
4097** This is not a VFS shared-memory method; it is a utility function called
4098** by VFS shared-memory methods.
4099*/
drhd91c68f2010-05-14 14:52:25 +00004100static void unixShmPurge(unixFile *pFd){
4101 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004102 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004103 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00004104 int i;
drhd91c68f2010-05-14 14:52:25 +00004105 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004106 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00004107 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00004108 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004109 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004110 }else{
4111 sqlite3_free(p->apRegion[i]);
4112 }
dan13a3cb82010-06-11 19:04:21 +00004113 }
dan18801912010-06-14 14:07:50 +00004114 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004115 if( p->h>=0 ){
4116 robust_close(pFd, p->h, __LINE__);
4117 p->h = -1;
4118 }
drhd91c68f2010-05-14 14:52:25 +00004119 p->pInode->pShmNode = 0;
4120 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004121 }
4122}
4123
4124/*
danda9fe0c2010-07-13 18:44:03 +00004125** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004126** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004127**
drh7234c6d2010-06-19 15:10:09 +00004128** The file used to implement shared-memory is in the same directory
4129** as the open database file and has the same name as the open database
4130** file with the "-shm" suffix added. For example, if the database file
4131** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004132** for shared memory will be called "/home/user1/config.db-shm".
4133**
4134** Another approach to is to use files in /dev/shm or /dev/tmp or an
4135** some other tmpfs mount. But if a file in a different directory
4136** from the database file is used, then differing access permissions
4137** or a chroot() might cause two different processes on the same
4138** database to end up using different files for shared memory -
4139** meaning that their memory would not really be shared - resulting
4140** in database corruption. Nevertheless, this tmpfs file usage
4141** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4142** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4143** option results in an incompatible build of SQLite; builds of SQLite
4144** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4145** same database file at the same time, database corruption will likely
4146** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4147** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004148**
4149** When opening a new shared-memory file, if no other instances of that
4150** file are currently open, in this process or in other processes, then
4151** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004152**
4153** If the original database file (pDbFd) is using the "unix-excl" VFS
4154** that means that an exclusive lock is held on the database file and
4155** that no other processes are able to read or write the database. In
4156** that case, we do not really need shared memory. No shared memory
4157** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004158*/
danda9fe0c2010-07-13 18:44:03 +00004159static int unixOpenSharedMemory(unixFile *pDbFd){
4160 struct unixShm *p = 0; /* The connection to be opened */
4161 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4162 int rc; /* Result code */
4163 unixInodeInfo *pInode; /* The inode of fd */
4164 char *zShmFilename; /* Name of the file used for SHM */
4165 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004166
danda9fe0c2010-07-13 18:44:03 +00004167 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004168 p = sqlite3_malloc( sizeof(*p) );
4169 if( p==0 ) return SQLITE_NOMEM;
4170 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004171 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004172
danda9fe0c2010-07-13 18:44:03 +00004173 /* Check to see if a unixShmNode object already exists. Reuse an existing
4174 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004175 */
4176 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004177 pInode = pDbFd->pInode;
4178 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004179 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004180 struct stat sStat; /* fstat() info for database file */
4181
4182 /* Call fstat() to figure out the permissions on the database file. If
4183 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004184 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004185 */
drh3cb93392011-03-12 18:10:44 +00004186 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004187 rc = SQLITE_IOERR_FSTAT;
4188 goto shm_open_err;
4189 }
4190
drha4ced192010-07-15 18:32:40 +00004191#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004192 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004193#else
drh52bcde02012-01-03 14:50:45 +00004194 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004195#endif
drh7234c6d2010-06-19 15:10:09 +00004196 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004197 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004198 rc = SQLITE_NOMEM;
4199 goto shm_open_err;
4200 }
drh9cb5a0d2012-01-05 21:19:54 +00004201 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004202 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004203#ifdef SQLITE_SHM_DIRECTORY
4204 sqlite3_snprintf(nShmFilename, zShmFilename,
4205 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4206 (u32)sStat.st_ino, (u32)sStat.st_dev);
4207#else
drh7234c6d2010-06-19 15:10:09 +00004208 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004209 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004210#endif
drhd91c68f2010-05-14 14:52:25 +00004211 pShmNode->h = -1;
4212 pDbFd->pInode->pShmNode = pShmNode;
4213 pShmNode->pInode = pDbFd->pInode;
4214 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4215 if( pShmNode->mutex==0 ){
4216 rc = SQLITE_NOMEM;
4217 goto shm_open_err;
4218 }
drhd9e5c4f2010-05-12 18:01:39 +00004219
drh3cb93392011-03-12 18:10:44 +00004220 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004221 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004222 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004223 openFlags = O_RDONLY;
4224 pShmNode->isReadonly = 1;
4225 }
4226 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004227 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004228 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4229 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004230 }
drhac7c3ac2012-02-11 19:23:48 +00004231
4232 /* If this process is running as root, make sure that the SHM file
4233 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004234 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004235 */
drhed466822012-05-31 13:10:49 +00004236 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004237
4238 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004239 ** If not, truncate the file to zero length.
4240 */
4241 rc = SQLITE_OK;
4242 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4243 if( robust_ftruncate(pShmNode->h, 0) ){
4244 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004245 }
4246 }
drh66dfec8b2011-06-01 20:01:49 +00004247 if( rc==SQLITE_OK ){
4248 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4249 }
4250 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004251 }
drhd9e5c4f2010-05-12 18:01:39 +00004252 }
4253
drhd91c68f2010-05-14 14:52:25 +00004254 /* Make the new connection a child of the unixShmNode */
4255 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004256#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004257 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004258#endif
drhd91c68f2010-05-14 14:52:25 +00004259 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004260 pDbFd->pShm = p;
4261 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004262
4263 /* The reference count on pShmNode has already been incremented under
4264 ** the cover of the unixEnterMutex() mutex and the pointer from the
4265 ** new (struct unixShm) object to the pShmNode has been set. All that is
4266 ** left to do is to link the new object into the linked list starting
4267 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4268 ** mutex.
4269 */
4270 sqlite3_mutex_enter(pShmNode->mutex);
4271 p->pNext = pShmNode->pFirst;
4272 pShmNode->pFirst = p;
4273 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004274 return SQLITE_OK;
4275
4276 /* Jump here on any error */
4277shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004278 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004279 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004280 unixLeaveMutex();
4281 return rc;
4282}
4283
4284/*
danda9fe0c2010-07-13 18:44:03 +00004285** This function is called to obtain a pointer to region iRegion of the
4286** shared-memory associated with the database file fd. Shared-memory regions
4287** are numbered starting from zero. Each shared-memory region is szRegion
4288** bytes in size.
4289**
4290** If an error occurs, an error code is returned and *pp is set to NULL.
4291**
4292** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4293** region has not been allocated (by any client, including one running in a
4294** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4295** bExtend is non-zero and the requested shared-memory region has not yet
4296** been allocated, it is allocated by this function.
4297**
4298** If the shared-memory region has already been allocated or is allocated by
4299** this call as described above, then it is mapped into this processes
4300** address space (if it is not already), *pp is set to point to the mapped
4301** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004302*/
danda9fe0c2010-07-13 18:44:03 +00004303static int unixShmMap(
4304 sqlite3_file *fd, /* Handle open on database file */
4305 int iRegion, /* Region to retrieve */
4306 int szRegion, /* Size of regions */
4307 int bExtend, /* True to extend file if necessary */
4308 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004309){
danda9fe0c2010-07-13 18:44:03 +00004310 unixFile *pDbFd = (unixFile*)fd;
4311 unixShm *p;
4312 unixShmNode *pShmNode;
4313 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004314
danda9fe0c2010-07-13 18:44:03 +00004315 /* If the shared-memory file has not yet been opened, open it now. */
4316 if( pDbFd->pShm==0 ){
4317 rc = unixOpenSharedMemory(pDbFd);
4318 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004319 }
drhd9e5c4f2010-05-12 18:01:39 +00004320
danda9fe0c2010-07-13 18:44:03 +00004321 p = pDbFd->pShm;
4322 pShmNode = p->pShmNode;
4323 sqlite3_mutex_enter(pShmNode->mutex);
4324 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004325 assert( pShmNode->pInode==pDbFd->pInode );
4326 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4327 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004328
4329 if( pShmNode->nRegion<=iRegion ){
4330 char **apNew; /* New apRegion[] array */
4331 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4332 struct stat sStat; /* Used by fstat() */
4333
4334 pShmNode->szRegion = szRegion;
4335
drh3cb93392011-03-12 18:10:44 +00004336 if( pShmNode->h>=0 ){
4337 /* The requested region is not mapped into this processes address space.
4338 ** Check to see if it has been allocated (i.e. if the wal-index file is
4339 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004340 */
drh3cb93392011-03-12 18:10:44 +00004341 if( osFstat(pShmNode->h, &sStat) ){
4342 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004343 goto shmpage_out;
4344 }
drh3cb93392011-03-12 18:10:44 +00004345
4346 if( sStat.st_size<nByte ){
4347 /* The requested memory region does not exist. If bExtend is set to
4348 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004349 */
dan47a2b4a2013-04-26 16:09:29 +00004350 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004351 goto shmpage_out;
4352 }
dan47a2b4a2013-04-26 16:09:29 +00004353
4354 /* Alternatively, if bExtend is true, extend the file. Do this by
4355 ** writing a single byte to the end of each (OS) page being
4356 ** allocated or extended. Technically, we need only write to the
4357 ** last page in order to extend the file. But writing to all new
4358 ** pages forces the OS to allocate them immediately, which reduces
4359 ** the chances of SIGBUS while accessing the mapped region later on.
4360 */
4361 else{
4362 static const int pgsz = 4096;
4363 int iPg;
4364
4365 /* Write to the last byte of each newly allocated or extended page */
4366 assert( (nByte % pgsz)==0 );
4367 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4368 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4369 const char *zFile = pShmNode->zFilename;
4370 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4371 goto shmpage_out;
4372 }
4373 }
drh3cb93392011-03-12 18:10:44 +00004374 }
4375 }
danda9fe0c2010-07-13 18:44:03 +00004376 }
4377
4378 /* Map the requested memory region into this processes address space. */
4379 apNew = (char **)sqlite3_realloc(
4380 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4381 );
4382 if( !apNew ){
4383 rc = SQLITE_IOERR_NOMEM;
4384 goto shmpage_out;
4385 }
4386 pShmNode->apRegion = apNew;
4387 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004388 void *pMem;
4389 if( pShmNode->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004390 pMem = osMmap(0, szRegion,
drh66dfec8b2011-06-01 20:01:49 +00004391 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004392 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004393 );
4394 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004395 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004396 goto shmpage_out;
4397 }
4398 }else{
4399 pMem = sqlite3_malloc(szRegion);
4400 if( pMem==0 ){
4401 rc = SQLITE_NOMEM;
4402 goto shmpage_out;
4403 }
4404 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004405 }
4406 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4407 pShmNode->nRegion++;
4408 }
4409 }
4410
4411shmpage_out:
4412 if( pShmNode->nRegion>iRegion ){
4413 *pp = pShmNode->apRegion[iRegion];
4414 }else{
4415 *pp = 0;
4416 }
drh66dfec8b2011-06-01 20:01:49 +00004417 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004418 sqlite3_mutex_leave(pShmNode->mutex);
4419 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004420}
4421
4422/*
drhd9e5c4f2010-05-12 18:01:39 +00004423** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004424**
4425** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4426** different here than in posix. In xShmLock(), one can go from unlocked
4427** to shared and back or from unlocked to exclusive and back. But one may
4428** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004429*/
4430static int unixShmLock(
4431 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004432 int ofst, /* First lock to acquire or release */
4433 int n, /* Number of locks to acquire or release */
4434 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004435){
drh73b64e42010-05-30 19:55:15 +00004436 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4437 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4438 unixShm *pX; /* For looping over all siblings */
4439 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4440 int rc = SQLITE_OK; /* Result code */
4441 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004442
drhd91c68f2010-05-14 14:52:25 +00004443 assert( pShmNode==pDbFd->pInode->pShmNode );
4444 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004445 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004446 assert( n>=1 );
4447 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4448 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4449 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4450 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4451 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004452 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4453 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004454
drhc99597c2010-05-31 01:41:15 +00004455 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004456 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004457 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004458 if( flags & SQLITE_SHM_UNLOCK ){
4459 u16 allMask = 0; /* Mask of locks held by siblings */
4460
4461 /* See if any siblings hold this same lock */
4462 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4463 if( pX==p ) continue;
4464 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4465 allMask |= pX->sharedMask;
4466 }
4467
4468 /* Unlock the system-level locks */
4469 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004470 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004471 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004472 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004473 }
drh73b64e42010-05-30 19:55:15 +00004474
4475 /* Undo the local locks */
4476 if( rc==SQLITE_OK ){
4477 p->exclMask &= ~mask;
4478 p->sharedMask &= ~mask;
4479 }
4480 }else if( flags & SQLITE_SHM_SHARED ){
4481 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4482
4483 /* Find out which shared locks are already held by sibling connections.
4484 ** If any sibling already holds an exclusive lock, go ahead and return
4485 ** SQLITE_BUSY.
4486 */
4487 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004488 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004489 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004490 break;
4491 }
4492 allShared |= pX->sharedMask;
4493 }
4494
4495 /* Get shared locks at the system level, if necessary */
4496 if( rc==SQLITE_OK ){
4497 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004498 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004499 }else{
drh73b64e42010-05-30 19:55:15 +00004500 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004501 }
drhd9e5c4f2010-05-12 18:01:39 +00004502 }
drh73b64e42010-05-30 19:55:15 +00004503
4504 /* Get the local shared locks */
4505 if( rc==SQLITE_OK ){
4506 p->sharedMask |= mask;
4507 }
4508 }else{
4509 /* Make sure no sibling connections hold locks that will block this
4510 ** lock. If any do, return SQLITE_BUSY right away.
4511 */
4512 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004513 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4514 rc = SQLITE_BUSY;
4515 break;
4516 }
4517 }
4518
4519 /* Get the exclusive locks at the system level. Then if successful
4520 ** also mark the local connection as being locked.
4521 */
4522 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004523 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004524 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004525 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004526 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004527 }
drhd9e5c4f2010-05-12 18:01:39 +00004528 }
4529 }
drhd91c68f2010-05-14 14:52:25 +00004530 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004531 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4532 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004533 return rc;
4534}
4535
drh286a2882010-05-20 23:51:06 +00004536/*
4537** Implement a memory barrier or memory fence on shared memory.
4538**
4539** All loads and stores begun before the barrier must complete before
4540** any load or store begun after the barrier.
4541*/
4542static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004543 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004544){
drhff828942010-06-26 21:34:06 +00004545 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004546 unixEnterMutex();
4547 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004548}
4549
dan18801912010-06-14 14:07:50 +00004550/*
danda9fe0c2010-07-13 18:44:03 +00004551** Close a connection to shared-memory. Delete the underlying
4552** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004553**
4554** If there is no shared memory associated with the connection then this
4555** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004556*/
danda9fe0c2010-07-13 18:44:03 +00004557static int unixShmUnmap(
4558 sqlite3_file *fd, /* The underlying database file */
4559 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004560){
danda9fe0c2010-07-13 18:44:03 +00004561 unixShm *p; /* The connection to be closed */
4562 unixShmNode *pShmNode; /* The underlying shared-memory file */
4563 unixShm **pp; /* For looping over sibling connections */
4564 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004565
danda9fe0c2010-07-13 18:44:03 +00004566 pDbFd = (unixFile*)fd;
4567 p = pDbFd->pShm;
4568 if( p==0 ) return SQLITE_OK;
4569 pShmNode = p->pShmNode;
4570
4571 assert( pShmNode==pDbFd->pInode->pShmNode );
4572 assert( pShmNode->pInode==pDbFd->pInode );
4573
4574 /* Remove connection p from the set of connections associated
4575 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004576 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004577 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4578 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004579
danda9fe0c2010-07-13 18:44:03 +00004580 /* Free the connection p */
4581 sqlite3_free(p);
4582 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004583 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004584
4585 /* If pShmNode->nRef has reached 0, then close the underlying
4586 ** shared-memory file, too */
4587 unixEnterMutex();
4588 assert( pShmNode->nRef>0 );
4589 pShmNode->nRef--;
4590 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004591 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004592 unixShmPurge(pDbFd);
4593 }
4594 unixLeaveMutex();
4595
4596 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004597}
drh286a2882010-05-20 23:51:06 +00004598
danda9fe0c2010-07-13 18:44:03 +00004599
drhd9e5c4f2010-05-12 18:01:39 +00004600#else
drh6b017cc2010-06-14 18:01:46 +00004601# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004602# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004603# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004604# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004605#endif /* #ifndef SQLITE_OMIT_WAL */
4606
mistachkine98844f2013-08-24 00:59:24 +00004607#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004608/*
danaef49d72013-03-25 16:28:54 +00004609** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004610*/
danf23da962013-03-23 21:00:41 +00004611static void unixUnmapfile(unixFile *pFd){
4612 assert( pFd->nFetchOut==0 );
4613 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004614 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004615 pFd->pMapRegion = 0;
4616 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004617 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004618 }
4619}
dan5d8a1372013-03-19 19:28:06 +00004620
danaef49d72013-03-25 16:28:54 +00004621/*
dane6ecd662013-04-01 17:56:59 +00004622** Return the system page size.
4623*/
4624static int unixGetPagesize(void){
4625#if HAVE_MREMAP
4626 return 512;
drh85830a72013-04-03 00:42:01 +00004627#elif defined(_BSD_SOURCE)
dane6ecd662013-04-01 17:56:59 +00004628 return getpagesize();
4629#else
4630 return (int)sysconf(_SC_PAGESIZE);
4631#endif
4632}
4633
4634/*
4635** Attempt to set the size of the memory mapping maintained by file
4636** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4637**
4638** If successful, this function sets the following variables:
4639**
4640** unixFile.pMapRegion
4641** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004642** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004643**
4644** If unsuccessful, an error message is logged via sqlite3_log() and
4645** the three variables above are zeroed. In this case SQLite should
4646** continue accessing the database using the xRead() and xWrite()
4647** methods.
4648*/
4649static void unixRemapfile(
4650 unixFile *pFd, /* File descriptor object */
4651 i64 nNew /* Required mapping size */
4652){
dan4ff7bc42013-04-02 12:04:09 +00004653 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004654 int h = pFd->h; /* File descriptor open on db file */
4655 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004656 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004657 u8 *pNew = 0; /* Location of new mapping */
4658 int flags = PROT_READ; /* Flags to pass to mmap() */
4659
4660 assert( pFd->nFetchOut==0 );
4661 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004662 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004663 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004664 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004665 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004666
4667 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4668
4669 if( pOrig ){
4670 const int szSyspage = unixGetPagesize();
4671 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
4672 u8 *pReq = &pOrig[nReuse];
4673
4674 /* Unmap any pages of the existing mapping that cannot be reused. */
4675 if( nReuse!=nOrig ){
4676 osMunmap(pReq, nOrig-nReuse);
4677 }
4678
4679#if HAVE_MREMAP
4680 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004681 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004682#else
4683 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4684 if( pNew!=MAP_FAILED ){
4685 if( pNew!=pReq ){
4686 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004687 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004688 }else{
4689 pNew = pOrig;
4690 }
4691 }
4692#endif
4693
dan48ccef82013-04-02 20:55:01 +00004694 /* The attempt to extend the existing mapping failed. Free it. */
4695 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004696 osMunmap(pOrig, nReuse);
4697 }
4698 }
4699
4700 /* If pNew is still NULL, try to create an entirely new mapping. */
4701 if( pNew==0 ){
4702 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004703 }
4704
dan4ff7bc42013-04-02 12:04:09 +00004705 if( pNew==MAP_FAILED ){
4706 pNew = 0;
4707 nNew = 0;
4708 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4709
4710 /* If the mmap() above failed, assume that all subsequent mmap() calls
4711 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4712 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004713 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004714 }
dane6ecd662013-04-01 17:56:59 +00004715 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004716 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004717}
4718
4719/*
danaef49d72013-03-25 16:28:54 +00004720** Memory map or remap the file opened by file-descriptor pFd (if the file
4721** is already mapped, the existing mapping is replaced by the new). Or, if
4722** there already exists a mapping for this file, and there are still
4723** outstanding xFetch() references to it, this function is a no-op.
4724**
4725** If parameter nByte is non-negative, then it is the requested size of
4726** the mapping to create. Otherwise, if nByte is less than zero, then the
4727** requested size is the size of the file on disk. The actual size of the
4728** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004729** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004730**
4731** SQLITE_OK is returned if no error occurs (even if the mapping is not
4732** recreated as a result of outstanding references) or an SQLite error
4733** code otherwise.
4734*/
danf23da962013-03-23 21:00:41 +00004735static int unixMapfile(unixFile *pFd, i64 nByte){
4736 i64 nMap = nByte;
4737 int rc;
daneb97b292013-03-20 14:26:59 +00004738
danf23da962013-03-23 21:00:41 +00004739 assert( nMap>=0 || pFd->nFetchOut==0 );
4740 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4741
4742 if( nMap<0 ){
daneb97b292013-03-20 14:26:59 +00004743 struct stat statbuf; /* Low-level file information */
danf23da962013-03-23 21:00:41 +00004744 rc = osFstat(pFd->h, &statbuf);
4745 if( rc!=SQLITE_OK ){
4746 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004747 }
danf23da962013-03-23 21:00:41 +00004748 nMap = statbuf.st_size;
4749 }
drh9b4c59f2013-04-15 17:03:42 +00004750 if( nMap>pFd->mmapSizeMax ){
4751 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004752 }
4753
danf23da962013-03-23 21:00:41 +00004754 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004755 if( nMap>0 ){
4756 unixRemapfile(pFd, nMap);
4757 }else{
danb7e3a322013-03-25 20:30:13 +00004758 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004759 }
4760 }
4761
danf23da962013-03-23 21:00:41 +00004762 return SQLITE_OK;
4763}
mistachkine98844f2013-08-24 00:59:24 +00004764#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004765
danaef49d72013-03-25 16:28:54 +00004766/*
4767** If possible, return a pointer to a mapping of file fd starting at offset
4768** iOff. The mapping must be valid for at least nAmt bytes.
4769**
4770** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4771** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4772** Finally, if an error does occur, return an SQLite error code. The final
4773** value of *pp is undefined in this case.
4774**
4775** If this function does return a pointer, the caller must eventually
4776** release the reference by calling unixUnfetch().
4777*/
danf23da962013-03-23 21:00:41 +00004778static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004779#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004780 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004781#endif
danf23da962013-03-23 21:00:41 +00004782 *pp = 0;
4783
drh9b4c59f2013-04-15 17:03:42 +00004784#if SQLITE_MAX_MMAP_SIZE>0
4785 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004786 if( pFd->pMapRegion==0 ){
4787 int rc = unixMapfile(pFd, -1);
4788 if( rc!=SQLITE_OK ) return rc;
4789 }
4790 if( pFd->mmapSize >= iOff+nAmt ){
4791 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4792 pFd->nFetchOut++;
4793 }
4794 }
drh6e0b6d52013-04-09 16:19:20 +00004795#endif
danf23da962013-03-23 21:00:41 +00004796 return SQLITE_OK;
4797}
4798
danaef49d72013-03-25 16:28:54 +00004799/*
dandf737fe2013-03-25 17:00:24 +00004800** If the third argument is non-NULL, then this function releases a
4801** reference obtained by an earlier call to unixFetch(). The second
4802** argument passed to this function must be the same as the corresponding
4803** argument that was passed to the unixFetch() invocation.
4804**
4805** Or, if the third argument is NULL, then this function is being called
4806** to inform the VFS layer that, according to POSIX, any existing mapping
4807** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004808*/
dandf737fe2013-03-25 17:00:24 +00004809static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
danf23da962013-03-23 21:00:41 +00004810 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhda8caa02013-04-22 23:38:50 +00004811 UNUSED_PARAMETER(iOff);
danf23da962013-03-23 21:00:41 +00004812
mistachkinb5ca3cb2013-08-24 01:12:03 +00004813#if SQLITE_MAX_MMAP_SIZE>0
danaef49d72013-03-25 16:28:54 +00004814 /* If p==0 (unmap the entire file) then there must be no outstanding
4815 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4816 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004817 assert( (p==0)==(pFd->nFetchOut==0) );
4818
dandf737fe2013-03-25 17:00:24 +00004819 /* If p!=0, it must match the iOff value. */
4820 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4821
danf23da962013-03-23 21:00:41 +00004822 if( p ){
4823 pFd->nFetchOut--;
4824 }else{
4825 unixUnmapfile(pFd);
4826 }
4827
4828 assert( pFd->nFetchOut>=0 );
mistachkinb5ca3cb2013-08-24 01:12:03 +00004829#endif
danf23da962013-03-23 21:00:41 +00004830 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004831}
4832
4833/*
drh734c9862008-11-28 15:37:20 +00004834** Here ends the implementation of all sqlite3_file methods.
4835**
4836********************** End sqlite3_file Methods *******************************
4837******************************************************************************/
4838
4839/*
drh6b9d6dd2008-12-03 19:34:47 +00004840** This division contains definitions of sqlite3_io_methods objects that
4841** implement various file locking strategies. It also contains definitions
4842** of "finder" functions. A finder-function is used to locate the appropriate
4843** sqlite3_io_methods object for a particular database file. The pAppData
4844** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4845** the correct finder-function for that VFS.
4846**
4847** Most finder functions return a pointer to a fixed sqlite3_io_methods
4848** object. The only interesting finder-function is autolockIoFinder, which
4849** looks at the filesystem type and tries to guess the best locking
4850** strategy from that.
4851**
drh1875f7a2008-12-08 18:19:17 +00004852** For finder-funtion F, two objects are created:
4853**
4854** (1) The real finder-function named "FImpt()".
4855**
dane946c392009-08-22 11:39:46 +00004856** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004857**
4858**
4859** A pointer to the F pointer is used as the pAppData value for VFS
4860** objects. We have to do this instead of letting pAppData point
4861** directly at the finder-function since C90 rules prevent a void*
4862** from be cast into a function pointer.
4863**
drh6b9d6dd2008-12-03 19:34:47 +00004864**
drh7708e972008-11-29 00:56:52 +00004865** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004866**
drh7708e972008-11-29 00:56:52 +00004867** * A constant sqlite3_io_methods object call METHOD that has locking
4868** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4869**
4870** * An I/O method finder function called FINDER that returns a pointer
4871** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004872*/
drhd9e5c4f2010-05-12 18:01:39 +00004873#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004874static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004875 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004876 CLOSE, /* xClose */ \
4877 unixRead, /* xRead */ \
4878 unixWrite, /* xWrite */ \
4879 unixTruncate, /* xTruncate */ \
4880 unixSync, /* xSync */ \
4881 unixFileSize, /* xFileSize */ \
4882 LOCK, /* xLock */ \
4883 UNLOCK, /* xUnlock */ \
4884 CKLOCK, /* xCheckReservedLock */ \
4885 unixFileControl, /* xFileControl */ \
4886 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004887 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004888 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004889 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004890 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004891 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004892 unixFetch, /* xFetch */ \
4893 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004894}; \
drh0c2694b2009-09-03 16:23:44 +00004895static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4896 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004897 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004898} \
drh0c2694b2009-09-03 16:23:44 +00004899static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004900 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004901
4902/*
4903** Here are all of the sqlite3_io_methods objects for each of the
4904** locking strategies. Functions that return pointers to these methods
4905** are also created.
4906*/
4907IOMETHODS(
4908 posixIoFinder, /* Finder function name */
4909 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004910 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004911 unixClose, /* xClose method */
4912 unixLock, /* xLock method */
4913 unixUnlock, /* xUnlock method */
4914 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004915)
drh7708e972008-11-29 00:56:52 +00004916IOMETHODS(
4917 nolockIoFinder, /* Finder function name */
4918 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004919 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004920 nolockClose, /* xClose method */
4921 nolockLock, /* xLock method */
4922 nolockUnlock, /* xUnlock method */
4923 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004924)
drh7708e972008-11-29 00:56:52 +00004925IOMETHODS(
4926 dotlockIoFinder, /* Finder function name */
4927 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004928 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004929 dotlockClose, /* xClose method */
4930 dotlockLock, /* xLock method */
4931 dotlockUnlock, /* xUnlock method */
4932 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004933)
drh7708e972008-11-29 00:56:52 +00004934
chw78a13182009-04-07 05:35:03 +00004935#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004936IOMETHODS(
4937 flockIoFinder, /* Finder function name */
4938 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004939 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004940 flockClose, /* xClose method */
4941 flockLock, /* xLock method */
4942 flockUnlock, /* xUnlock method */
4943 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004944)
drh7708e972008-11-29 00:56:52 +00004945#endif
4946
drh6c7d5c52008-11-21 20:32:33 +00004947#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004948IOMETHODS(
4949 semIoFinder, /* Finder function name */
4950 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004951 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004952 semClose, /* xClose method */
4953 semLock, /* xLock method */
4954 semUnlock, /* xUnlock method */
4955 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004956)
aswiftaebf4132008-11-21 00:10:35 +00004957#endif
drh7708e972008-11-29 00:56:52 +00004958
drhd2cb50b2009-01-09 21:41:17 +00004959#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004960IOMETHODS(
4961 afpIoFinder, /* Finder function name */
4962 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004963 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004964 afpClose, /* xClose method */
4965 afpLock, /* xLock method */
4966 afpUnlock, /* xUnlock method */
4967 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004968)
drh715ff302008-12-03 22:32:44 +00004969#endif
4970
4971/*
4972** The proxy locking method is a "super-method" in the sense that it
4973** opens secondary file descriptors for the conch and lock files and
4974** it uses proxy, dot-file, AFP, and flock() locking methods on those
4975** secondary files. For this reason, the division that implements
4976** proxy locking is located much further down in the file. But we need
4977** to go ahead and define the sqlite3_io_methods and finder function
4978** for proxy locking here. So we forward declare the I/O methods.
4979*/
drhd2cb50b2009-01-09 21:41:17 +00004980#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004981static int proxyClose(sqlite3_file*);
4982static int proxyLock(sqlite3_file*, int);
4983static int proxyUnlock(sqlite3_file*, int);
4984static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004985IOMETHODS(
4986 proxyIoFinder, /* Finder function name */
4987 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004988 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004989 proxyClose, /* xClose method */
4990 proxyLock, /* xLock method */
4991 proxyUnlock, /* xUnlock method */
4992 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004993)
aswiftaebf4132008-11-21 00:10:35 +00004994#endif
drh7708e972008-11-29 00:56:52 +00004995
drh7ed97b92010-01-20 13:07:21 +00004996/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4997#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4998IOMETHODS(
4999 nfsIoFinder, /* Finder function name */
5000 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005001 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005002 unixClose, /* xClose method */
5003 unixLock, /* xLock method */
5004 nfsUnlock, /* xUnlock method */
5005 unixCheckReservedLock /* xCheckReservedLock method */
5006)
5007#endif
drh7708e972008-11-29 00:56:52 +00005008
drhd2cb50b2009-01-09 21:41:17 +00005009#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005010/*
drh6b9d6dd2008-12-03 19:34:47 +00005011** This "finder" function attempts to determine the best locking strategy
5012** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005013** object that implements that strategy.
5014**
5015** This is for MacOSX only.
5016*/
drh1875f7a2008-12-08 18:19:17 +00005017static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005018 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005019 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005020){
5021 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005022 const char *zFilesystem; /* Filesystem type name */
5023 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005024 } aMap[] = {
5025 { "hfs", &posixIoMethods },
5026 { "ufs", &posixIoMethods },
5027 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005028 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005029 { "webdav", &nolockIoMethods },
5030 { 0, 0 }
5031 };
5032 int i;
5033 struct statfs fsInfo;
5034 struct flock lockInfo;
5035
5036 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005037 /* If filePath==NULL that means we are dealing with a transient file
5038 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005039 return &nolockIoMethods;
5040 }
5041 if( statfs(filePath, &fsInfo) != -1 ){
5042 if( fsInfo.f_flags & MNT_RDONLY ){
5043 return &nolockIoMethods;
5044 }
5045 for(i=0; aMap[i].zFilesystem; i++){
5046 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5047 return aMap[i].pMethods;
5048 }
5049 }
5050 }
5051
5052 /* Default case. Handles, amongst others, "nfs".
5053 ** Test byte-range lock using fcntl(). If the call succeeds,
5054 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005055 */
drh7708e972008-11-29 00:56:52 +00005056 lockInfo.l_len = 1;
5057 lockInfo.l_start = 0;
5058 lockInfo.l_whence = SEEK_SET;
5059 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005060 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005061 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5062 return &nfsIoMethods;
5063 } else {
5064 return &posixIoMethods;
5065 }
drh7708e972008-11-29 00:56:52 +00005066 }else{
5067 return &dotlockIoMethods;
5068 }
5069}
drh0c2694b2009-09-03 16:23:44 +00005070static const sqlite3_io_methods
5071 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005072
drhd2cb50b2009-01-09 21:41:17 +00005073#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005074
chw78a13182009-04-07 05:35:03 +00005075#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5076/*
5077** This "finder" function attempts to determine the best locking strategy
5078** for the database file "filePath". It then returns the sqlite3_io_methods
5079** object that implements that strategy.
5080**
5081** This is for VXWorks only.
5082*/
5083static const sqlite3_io_methods *autolockIoFinderImpl(
5084 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005085 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005086){
5087 struct flock lockInfo;
5088
5089 if( !filePath ){
5090 /* If filePath==NULL that means we are dealing with a transient file
5091 ** that does not need to be locked. */
5092 return &nolockIoMethods;
5093 }
5094
5095 /* Test if fcntl() is supported and use POSIX style locks.
5096 ** Otherwise fall back to the named semaphore method.
5097 */
5098 lockInfo.l_len = 1;
5099 lockInfo.l_start = 0;
5100 lockInfo.l_whence = SEEK_SET;
5101 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005102 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005103 return &posixIoMethods;
5104 }else{
5105 return &semIoMethods;
5106 }
5107}
drh0c2694b2009-09-03 16:23:44 +00005108static const sqlite3_io_methods
5109 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005110
5111#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5112
drh7708e972008-11-29 00:56:52 +00005113/*
5114** An abstract type for a pointer to a IO method finder function:
5115*/
drh0c2694b2009-09-03 16:23:44 +00005116typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005117
aswiftaebf4132008-11-21 00:10:35 +00005118
drh734c9862008-11-28 15:37:20 +00005119/****************************************************************************
5120**************************** sqlite3_vfs methods ****************************
5121**
5122** This division contains the implementation of methods on the
5123** sqlite3_vfs object.
5124*/
5125
danielk1977a3d4c882007-03-23 10:08:38 +00005126/*
danielk1977e339d652008-06-28 11:23:00 +00005127** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005128*/
5129static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005130 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005131 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005132 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005133 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005134 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005135){
drh7708e972008-11-29 00:56:52 +00005136 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005137 unixFile *pNew = (unixFile *)pId;
5138 int rc = SQLITE_OK;
5139
drh8af6c222010-05-14 12:43:01 +00005140 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005141
dan00157392010-10-05 11:33:15 +00005142 /* Usually the path zFilename should not be a relative pathname. The
5143 ** exception is when opening the proxy "conch" file in builds that
5144 ** include the special Apple locking styles.
5145 */
dan00157392010-10-05 11:33:15 +00005146#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005147 assert( zFilename==0 || zFilename[0]=='/'
5148 || pVfs->pAppData==(void*)&autolockIoFinder );
5149#else
5150 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005151#endif
dan00157392010-10-05 11:33:15 +00005152
drhb07028f2011-10-14 21:49:18 +00005153 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005154 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005155
drh308c2a52010-05-14 11:30:18 +00005156 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005157 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005158 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005159 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005160 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005161#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005162 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005163#endif
drhc02a43a2012-01-10 23:18:38 +00005164 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5165 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005166 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005167 }
drh503a6862013-03-01 01:07:17 +00005168 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005169 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005170 }
drh339eb0b2008-03-07 15:34:11 +00005171
drh6c7d5c52008-11-21 20:32:33 +00005172#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005173 pNew->pId = vxworksFindFileId(zFilename);
5174 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005175 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005176 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005177 }
5178#endif
5179
drhc02a43a2012-01-10 23:18:38 +00005180 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005181 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005182 }else{
drh0c2694b2009-09-03 16:23:44 +00005183 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005184#if SQLITE_ENABLE_LOCKING_STYLE
5185 /* Cache zFilename in the locking context (AFP and dotlock override) for
5186 ** proxyLock activation is possible (remote proxy is based on db name)
5187 ** zFilename remains valid until file is closed, to support */
5188 pNew->lockingContext = (void*)zFilename;
5189#endif
drhda0e7682008-07-30 15:27:54 +00005190 }
danielk1977e339d652008-06-28 11:23:00 +00005191
drh7ed97b92010-01-20 13:07:21 +00005192 if( pLockingStyle == &posixIoMethods
5193#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5194 || pLockingStyle == &nfsIoMethods
5195#endif
5196 ){
drh7708e972008-11-29 00:56:52 +00005197 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005198 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005199 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005200 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005201 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005202 ** in two scenarios:
5203 **
5204 ** (a) A call to fstat() failed.
5205 ** (b) A malloc failed.
5206 **
5207 ** Scenario (b) may only occur if the process is holding no other
5208 ** file descriptors open on the same file. If there were other file
5209 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005210 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005211 ** handle h - as it is guaranteed that no posix locks will be released
5212 ** by doing so.
5213 **
5214 ** If scenario (a) caused the error then things are not so safe. The
5215 ** implicit assumption here is that if fstat() fails, things are in
5216 ** such bad shape that dropping a lock or two doesn't matter much.
5217 */
drh0e9365c2011-03-02 02:08:13 +00005218 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005219 h = -1;
5220 }
drh7708e972008-11-29 00:56:52 +00005221 unixLeaveMutex();
5222 }
danielk1977e339d652008-06-28 11:23:00 +00005223
drhd2cb50b2009-01-09 21:41:17 +00005224#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005225 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005226 /* AFP locking uses the file path so it needs to be included in
5227 ** the afpLockingContext.
5228 */
5229 afpLockingContext *pCtx;
5230 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5231 if( pCtx==0 ){
5232 rc = SQLITE_NOMEM;
5233 }else{
5234 /* NB: zFilename exists and remains valid until the file is closed
5235 ** according to requirement F11141. So we do not need to make a
5236 ** copy of the filename. */
5237 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005238 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005239 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005240 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005241 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005242 if( rc!=SQLITE_OK ){
5243 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005244 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005245 h = -1;
5246 }
drh7708e972008-11-29 00:56:52 +00005247 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005248 }
drh7708e972008-11-29 00:56:52 +00005249 }
5250#endif
danielk1977e339d652008-06-28 11:23:00 +00005251
drh7708e972008-11-29 00:56:52 +00005252 else if( pLockingStyle == &dotlockIoMethods ){
5253 /* Dotfile locking uses the file path so it needs to be included in
5254 ** the dotlockLockingContext
5255 */
5256 char *zLockFile;
5257 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005258 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005259 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005260 zLockFile = (char *)sqlite3_malloc(nFilename);
5261 if( zLockFile==0 ){
5262 rc = SQLITE_NOMEM;
5263 }else{
5264 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005265 }
drh7708e972008-11-29 00:56:52 +00005266 pNew->lockingContext = zLockFile;
5267 }
danielk1977e339d652008-06-28 11:23:00 +00005268
drh6c7d5c52008-11-21 20:32:33 +00005269#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005270 else if( pLockingStyle == &semIoMethods ){
5271 /* Named semaphore locking uses the file path so it needs to be
5272 ** included in the semLockingContext
5273 */
5274 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005275 rc = findInodeInfo(pNew, &pNew->pInode);
5276 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5277 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005278 int n;
drh2238dcc2009-08-27 17:56:20 +00005279 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005280 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005281 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005282 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005283 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5284 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005285 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005286 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005287 }
chw97185482008-11-17 08:05:31 +00005288 }
drh7708e972008-11-29 00:56:52 +00005289 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005290 }
drh7708e972008-11-29 00:56:52 +00005291#endif
aswift5b1a2562008-08-22 00:22:35 +00005292
5293 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005294#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005295 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005296 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005297 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005298 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005299 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005300 }
chw97185482008-11-17 08:05:31 +00005301#endif
danielk1977e339d652008-06-28 11:23:00 +00005302 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005303 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005304 }else{
drh7708e972008-11-29 00:56:52 +00005305 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005306 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005307 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005308 }
danielk1977e339d652008-06-28 11:23:00 +00005309 return rc;
drh054889e2005-11-30 03:20:31 +00005310}
drh9c06c952005-11-26 00:25:00 +00005311
danielk1977ad94b582007-08-20 06:44:22 +00005312/*
drh8b3cf822010-06-01 21:02:51 +00005313** Return the name of a directory in which to put temporary files.
5314** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005315*/
drh7234c6d2010-06-19 15:10:09 +00005316static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005317 static const char *azDirs[] = {
5318 0,
aswiftaebf4132008-11-21 00:10:35 +00005319 0,
danielk197717b90b52008-06-06 11:11:25 +00005320 "/var/tmp",
5321 "/usr/tmp",
5322 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005323 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005324 };
drh8b3cf822010-06-01 21:02:51 +00005325 unsigned int i;
5326 struct stat buf;
5327 const char *zDir = 0;
5328
5329 azDirs[0] = sqlite3_temp_directory;
5330 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005331 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005332 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005333 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005334 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005335 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005336 break;
5337 }
5338 return zDir;
5339}
5340
5341/*
5342** Create a temporary file name in zBuf. zBuf must be allocated
5343** by the calling process and must be big enough to hold at least
5344** pVfs->mxPathname bytes.
5345*/
5346static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005347 static const unsigned char zChars[] =
5348 "abcdefghijklmnopqrstuvwxyz"
5349 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5350 "0123456789";
drh41022642008-11-21 00:24:42 +00005351 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005352 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005353
5354 /* It's odd to simulate an io-error here, but really this is just
5355 ** using the io-error infrastructure to test that SQLite handles this
5356 ** function failing.
5357 */
5358 SimulateIOError( return SQLITE_IOERR );
5359
drh7234c6d2010-06-19 15:10:09 +00005360 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005361 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005362
5363 /* Check that the output buffer is large enough for the temporary file
5364 ** name. If it is not, return SQLITE_ERROR.
5365 */
drhc02a43a2012-01-10 23:18:38 +00005366 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005367 return SQLITE_ERROR;
5368 }
5369
5370 do{
drhc02a43a2012-01-10 23:18:38 +00005371 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005372 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005373 sqlite3_randomness(15, &zBuf[j]);
5374 for(i=0; i<15; i++, j++){
5375 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5376 }
5377 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005378 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005379 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005380 return SQLITE_OK;
5381}
5382
drhd2cb50b2009-01-09 21:41:17 +00005383#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005384/*
5385** Routine to transform a unixFile into a proxy-locking unixFile.
5386** Implementation in the proxy-lock division, but used by unixOpen()
5387** if SQLITE_PREFER_PROXY_LOCKING is defined.
5388*/
5389static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005390#endif
drhc66d5b62008-12-03 22:48:32 +00005391
dan08da86a2009-08-21 17:18:03 +00005392/*
5393** Search for an unused file descriptor that was opened on the database
5394** file (not a journal or master-journal file) identified by pathname
5395** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5396** argument to this function.
5397**
5398** Such a file descriptor may exist if a database connection was closed
5399** but the associated file descriptor could not be closed because some
5400** other file descriptor open on the same file is holding a file-lock.
5401** Refer to comments in the unixClose() function and the lengthy comment
5402** describing "Posix Advisory Locking" at the start of this file for
5403** further details. Also, ticket #4018.
5404**
5405** If a suitable file descriptor is found, then it is returned. If no
5406** such file descriptor is located, -1 is returned.
5407*/
dane946c392009-08-22 11:39:46 +00005408static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5409 UnixUnusedFd *pUnused = 0;
5410
5411 /* Do not search for an unused file descriptor on vxworks. Not because
5412 ** vxworks would not benefit from the change (it might, we're not sure),
5413 ** but because no way to test it is currently available. It is better
5414 ** not to risk breaking vxworks support for the sake of such an obscure
5415 ** feature. */
5416#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005417 struct stat sStat; /* Results of stat() call */
5418
5419 /* A stat() call may fail for various reasons. If this happens, it is
5420 ** almost certain that an open() call on the same path will also fail.
5421 ** For this reason, if an error occurs in the stat() call here, it is
5422 ** ignored and -1 is returned. The caller will try to open a new file
5423 ** descriptor on the same path, fail, and return an error to SQLite.
5424 **
5425 ** Even if a subsequent open() call does succeed, the consequences of
5426 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005427 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005428 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005429
5430 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005431 pInode = inodeList;
5432 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5433 || pInode->fileId.ino!=sStat.st_ino) ){
5434 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005435 }
drh8af6c222010-05-14 12:43:01 +00005436 if( pInode ){
dane946c392009-08-22 11:39:46 +00005437 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005438 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005439 pUnused = *pp;
5440 if( pUnused ){
5441 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005442 }
5443 }
5444 unixLeaveMutex();
5445 }
dane946c392009-08-22 11:39:46 +00005446#endif /* if !OS_VXWORKS */
5447 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005448}
danielk197717b90b52008-06-06 11:11:25 +00005449
5450/*
danddb0ac42010-07-14 14:48:58 +00005451** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005452** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005453** and a value suitable for passing as the third argument to open(2) is
5454** written to *pMode. If an IO error occurs, an SQLite error code is
5455** returned and the value of *pMode is not modified.
5456**
drh8c815d12012-02-13 20:16:37 +00005457** In most cases cases, this routine sets *pMode to 0, which will become
5458** an indication to robust_open() to create the file using
5459** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5460** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005461** this function queries the file-system for the permissions on the
5462** corresponding database file and sets *pMode to this value. Whenever
5463** possible, WAL and journal files are created using the same permissions
5464** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005465**
5466** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5467** original filename is unavailable. But 8_3_NAMES is only used for
5468** FAT filesystems and permissions do not matter there, so just use
5469** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005470*/
5471static int findCreateFileMode(
5472 const char *zPath, /* Path of file (possibly) being created */
5473 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005474 mode_t *pMode, /* OUT: Permissions to open file with */
5475 uid_t *pUid, /* OUT: uid to set on the file */
5476 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005477){
5478 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005479 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005480 *pUid = 0;
5481 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005482 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005483 char zDb[MAX_PATHNAME+1]; /* Database file path */
5484 int nDb; /* Number of valid bytes in zDb */
5485 struct stat sStat; /* Output of stat() on database file */
5486
dana0c989d2010-11-05 18:07:37 +00005487 /* zPath is a path to a WAL or journal file. The following block derives
5488 ** the path to the associated database file from zPath. This block handles
5489 ** the following naming conventions:
5490 **
5491 ** "<path to db>-journal"
5492 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005493 ** "<path to db>-journalNN"
5494 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005495 **
drhd337c5b2011-10-20 18:23:35 +00005496 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005497 ** used by the test_multiplex.c module.
5498 */
5499 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005500#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005501 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005502 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005503#else
5504 while( zPath[nDb]!='-' ){
5505 assert( nDb>0 );
5506 assert( zPath[nDb]!='\n' );
5507 nDb--;
5508 }
5509#endif
danddb0ac42010-07-14 14:48:58 +00005510 memcpy(zDb, zPath, nDb);
5511 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005512
drh58384f12011-07-28 00:14:45 +00005513 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005514 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005515 *pUid = sStat.st_uid;
5516 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005517 }else{
5518 rc = SQLITE_IOERR_FSTAT;
5519 }
5520 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5521 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005522 }
5523 return rc;
5524}
5525
5526/*
danielk1977ad94b582007-08-20 06:44:22 +00005527** Open the file zPath.
5528**
danielk1977b4b47412007-08-17 15:53:36 +00005529** Previously, the SQLite OS layer used three functions in place of this
5530** one:
5531**
5532** sqlite3OsOpenReadWrite();
5533** sqlite3OsOpenReadOnly();
5534** sqlite3OsOpenExclusive();
5535**
5536** These calls correspond to the following combinations of flags:
5537**
5538** ReadWrite() -> (READWRITE | CREATE)
5539** ReadOnly() -> (READONLY)
5540** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5541**
5542** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5543** true, the file was configured to be automatically deleted when the
5544** file handle closed. To achieve the same effect using this new
5545** interface, add the DELETEONCLOSE flag to those specified above for
5546** OpenExclusive().
5547*/
5548static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005549 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5550 const char *zPath, /* Pathname of file to be opened */
5551 sqlite3_file *pFile, /* The file descriptor to be filled in */
5552 int flags, /* Input flags to control the opening */
5553 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005554){
dan08da86a2009-08-21 17:18:03 +00005555 unixFile *p = (unixFile *)pFile;
5556 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005557 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005558 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005559 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005560 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005561 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005562
5563 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5564 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5565 int isCreate = (flags & SQLITE_OPEN_CREATE);
5566 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5567 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005568#if SQLITE_ENABLE_LOCKING_STYLE
5569 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5570#endif
drh3d4435b2011-08-26 20:55:50 +00005571#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5572 struct statfs fsInfo;
5573#endif
danielk1977b4b47412007-08-17 15:53:36 +00005574
danielk1977fee2d252007-08-18 10:59:19 +00005575 /* If creating a master or main-file journal, this function will open
5576 ** a file-descriptor on the directory too. The first time unixSync()
5577 ** is called the directory file descriptor will be fsync()ed and close()d.
5578 */
drh0059eae2011-08-08 23:48:40 +00005579 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005580 eType==SQLITE_OPEN_MASTER_JOURNAL
5581 || eType==SQLITE_OPEN_MAIN_JOURNAL
5582 || eType==SQLITE_OPEN_WAL
5583 ));
danielk1977fee2d252007-08-18 10:59:19 +00005584
danielk197717b90b52008-06-06 11:11:25 +00005585 /* If argument zPath is a NULL pointer, this function is required to open
5586 ** a temporary file. Use this buffer to store the file name in.
5587 */
drhc02a43a2012-01-10 23:18:38 +00005588 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005589 const char *zName = zPath;
5590
danielk1977fee2d252007-08-18 10:59:19 +00005591 /* Check the following statements are true:
5592 **
5593 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5594 ** (b) if CREATE is set, then READWRITE must also be set, and
5595 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005596 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005597 */
danielk1977b4b47412007-08-17 15:53:36 +00005598 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005599 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005600 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005601 assert(isDelete==0 || isCreate);
5602
danddb0ac42010-07-14 14:48:58 +00005603 /* The main DB, main journal, WAL file and master journal are never
5604 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005605 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5606 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5607 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005608 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005609
danielk1977fee2d252007-08-18 10:59:19 +00005610 /* Assert that the upper layer has set one of the "file-type" flags. */
5611 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5612 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5613 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005614 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005615 );
5616
dan08da86a2009-08-21 17:18:03 +00005617 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005618
dan08da86a2009-08-21 17:18:03 +00005619 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005620 UnixUnusedFd *pUnused;
5621 pUnused = findReusableFd(zName, flags);
5622 if( pUnused ){
5623 fd = pUnused->fd;
5624 }else{
dan6aa657f2009-08-24 18:57:58 +00005625 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005626 if( !pUnused ){
5627 return SQLITE_NOMEM;
5628 }
5629 }
5630 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005631
5632 /* Database filenames are double-zero terminated if they are not
5633 ** URIs with parameters. Hence, they can always be passed into
5634 ** sqlite3_uri_parameter(). */
5635 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5636
dan08da86a2009-08-21 17:18:03 +00005637 }else if( !zName ){
5638 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005639 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005640 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005641 if( rc!=SQLITE_OK ){
5642 return rc;
5643 }
5644 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005645
5646 /* Generated temporary filenames are always double-zero terminated
5647 ** for use by sqlite3_uri_parameter(). */
5648 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005649 }
5650
dan08da86a2009-08-21 17:18:03 +00005651 /* Determine the value of the flags parameter passed to POSIX function
5652 ** open(). These must be calculated even if open() is not called, as
5653 ** they may be stored as part of the file handle and used by the
5654 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005655 if( isReadonly ) openFlags |= O_RDONLY;
5656 if( isReadWrite ) openFlags |= O_RDWR;
5657 if( isCreate ) openFlags |= O_CREAT;
5658 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5659 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005660
danielk1977b4b47412007-08-17 15:53:36 +00005661 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005662 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005663 uid_t uid; /* Userid for the file */
5664 gid_t gid; /* Groupid for the file */
5665 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005666 if( rc!=SQLITE_OK ){
5667 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005668 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005669 return rc;
5670 }
drhad4f1e52011-03-04 15:43:57 +00005671 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005672 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005673 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5674 /* Failed to open the file for read/write access. Try read-only. */
5675 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005676 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005677 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005678 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005679 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005680 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005681 }
5682 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005683 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005684 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005685 }
drhac7c3ac2012-02-11 19:23:48 +00005686
5687 /* If this process is running as root and if creating a new rollback
5688 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005689 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005690 */
5691 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005692 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005693 }
danielk1977b4b47412007-08-17 15:53:36 +00005694 }
dan08da86a2009-08-21 17:18:03 +00005695 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005696 if( pOutFlags ){
5697 *pOutFlags = flags;
5698 }
5699
dane946c392009-08-22 11:39:46 +00005700 if( p->pUnused ){
5701 p->pUnused->fd = fd;
5702 p->pUnused->flags = flags;
5703 }
5704
danielk1977b4b47412007-08-17 15:53:36 +00005705 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005706#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005707 zPath = zName;
5708#else
drh036ac7f2011-08-08 23:18:05 +00005709 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005710#endif
danielk1977b4b47412007-08-17 15:53:36 +00005711 }
drh41022642008-11-21 00:24:42 +00005712#if SQLITE_ENABLE_LOCKING_STYLE
5713 else{
dan08da86a2009-08-21 17:18:03 +00005714 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005715 }
5716#endif
5717
drhda0e7682008-07-30 15:27:54 +00005718 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005719
drh7ed97b92010-01-20 13:07:21 +00005720
5721#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005722 if( fstatfs(fd, &fsInfo) == -1 ){
5723 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005724 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005725 return SQLITE_IOERR_ACCESS;
5726 }
5727 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5728 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5729 }
5730#endif
drhc02a43a2012-01-10 23:18:38 +00005731
5732 /* Set up appropriate ctrlFlags */
5733 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5734 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5735 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5736 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5737 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5738
drh7ed97b92010-01-20 13:07:21 +00005739#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005740#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005741 isAutoProxy = 1;
5742#endif
5743 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005744 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5745 int useProxy = 0;
5746
dan08da86a2009-08-21 17:18:03 +00005747 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5748 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005749 if( envforce!=NULL ){
5750 useProxy = atoi(envforce)>0;
5751 }else{
aswiftaebf4132008-11-21 00:10:35 +00005752 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005753 /* In theory, the close(fd) call is sub-optimal. If the file opened
5754 ** with fd is a database file, and there are other connections open
5755 ** on that file that are currently holding advisory locks on it,
5756 ** then the call to close() will cancel those locks. In practice,
5757 ** we're assuming that statfs() doesn't fail very often. At least
5758 ** not while other file descriptors opened by the same process on
5759 ** the same file are working. */
5760 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005761 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005762 rc = SQLITE_IOERR_ACCESS;
5763 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005764 }
5765 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5766 }
5767 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005768 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005769 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005770 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005771 if( rc!=SQLITE_OK ){
5772 /* Use unixClose to clean up the resources added in fillInUnixFile
5773 ** and clear all the structure's references. Specifically,
5774 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5775 */
5776 unixClose(pFile);
5777 return rc;
5778 }
aswiftaebf4132008-11-21 00:10:35 +00005779 }
dane946c392009-08-22 11:39:46 +00005780 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005781 }
5782 }
5783#endif
5784
drhc02a43a2012-01-10 23:18:38 +00005785 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5786
dane946c392009-08-22 11:39:46 +00005787open_finished:
5788 if( rc!=SQLITE_OK ){
5789 sqlite3_free(p->pUnused);
5790 }
5791 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005792}
5793
dane946c392009-08-22 11:39:46 +00005794
danielk1977b4b47412007-08-17 15:53:36 +00005795/*
danielk1977fee2d252007-08-18 10:59:19 +00005796** Delete the file at zPath. If the dirSync argument is true, fsync()
5797** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005798*/
drh6b9d6dd2008-12-03 19:34:47 +00005799static int unixDelete(
5800 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5801 const char *zPath, /* Name of file to be deleted */
5802 int dirSync /* If true, fsync() directory after deleting file */
5803){
danielk1977fee2d252007-08-18 10:59:19 +00005804 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005805 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005806 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005807 if( osUnlink(zPath)==(-1) ){
5808 if( errno==ENOENT ){
5809 rc = SQLITE_IOERR_DELETE_NOENT;
5810 }else{
drhb4308162012-11-09 21:40:02 +00005811 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005812 }
drhb4308162012-11-09 21:40:02 +00005813 return rc;
drh5d4feff2010-07-14 01:45:22 +00005814 }
danielk1977d39fa702008-10-16 13:27:40 +00005815#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005816 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005817 int fd;
drh90315a22011-08-10 01:52:12 +00005818 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005819 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005820#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005821 if( fsync(fd)==-1 )
5822#else
5823 if( fsync(fd) )
5824#endif
5825 {
dane18d4952011-02-21 11:46:24 +00005826 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005827 }
drh0e9365c2011-03-02 02:08:13 +00005828 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005829 }else if( rc==SQLITE_CANTOPEN ){
5830 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005831 }
5832 }
danielk1977d138dd82008-10-15 16:02:48 +00005833#endif
danielk1977fee2d252007-08-18 10:59:19 +00005834 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005835}
5836
danielk197790949c22007-08-17 16:50:38 +00005837/*
mistachkin48864df2013-03-21 21:20:32 +00005838** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005839** test performed depends on the value of flags:
5840**
5841** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5842** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5843** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5844**
5845** Otherwise return 0.
5846*/
danielk1977861f7452008-06-05 11:39:11 +00005847static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005848 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5849 const char *zPath, /* Path of the file to examine */
5850 int flags, /* What do we want to learn about the zPath file? */
5851 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005852){
rse25c0d1a2007-09-20 08:38:14 +00005853 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005854 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005855 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005856 switch( flags ){
5857 case SQLITE_ACCESS_EXISTS:
5858 amode = F_OK;
5859 break;
5860 case SQLITE_ACCESS_READWRITE:
5861 amode = W_OK|R_OK;
5862 break;
drh50d3f902007-08-27 21:10:36 +00005863 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005864 amode = R_OK;
5865 break;
5866
5867 default:
5868 assert(!"Invalid flags argument");
5869 }
drh99ab3b12011-03-02 15:09:07 +00005870 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005871 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5872 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005873 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005874 *pResOut = 0;
5875 }
5876 }
danielk1977861f7452008-06-05 11:39:11 +00005877 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005878}
5879
danielk1977b4b47412007-08-17 15:53:36 +00005880
5881/*
5882** Turn a relative pathname into a full pathname. The relative path
5883** is stored as a nul-terminated string in the buffer pointed to by
5884** zPath.
5885**
5886** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5887** (in this case, MAX_PATHNAME bytes). The full-path is written to
5888** this buffer before returning.
5889*/
danielk1977adfb9b02007-09-17 07:02:56 +00005890static int unixFullPathname(
5891 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5892 const char *zPath, /* Possibly relative input path */
5893 int nOut, /* Size of output buffer in bytes */
5894 char *zOut /* Output buffer */
5895){
danielk1977843e65f2007-09-01 16:16:15 +00005896
5897 /* It's odd to simulate an io-error here, but really this is just
5898 ** using the io-error infrastructure to test that SQLite handles this
5899 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005900 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005901 */
5902 SimulateIOError( return SQLITE_ERROR );
5903
drh153c62c2007-08-24 03:51:33 +00005904 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005905 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005906
drh3c7f2dc2007-12-06 13:26:20 +00005907 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005908 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005909 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005910 }else{
5911 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005912 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005913 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005914 }
drhea678832008-12-10 19:26:22 +00005915 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005916 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005917 }
5918 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005919}
5920
drh0ccebe72005-06-07 22:22:50 +00005921
drh761df872006-12-21 01:29:22 +00005922#ifndef SQLITE_OMIT_LOAD_EXTENSION
5923/*
5924** Interfaces for opening a shared library, finding entry points
5925** within the shared library, and closing the shared library.
5926*/
5927#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005928static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5929 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005930 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5931}
danielk197795c8a542007-09-01 06:51:27 +00005932
5933/*
5934** SQLite calls this function immediately after a call to unixDlSym() or
5935** unixDlOpen() fails (returns a null pointer). If a more detailed error
5936** message is available, it is written to zBufOut. If no error message
5937** is available, zBufOut is left unmodified and SQLite uses a default
5938** error message.
5939*/
danielk1977397d65f2008-11-19 11:35:39 +00005940static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005941 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005942 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005943 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005944 zErr = dlerror();
5945 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005946 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005947 }
drh6c7d5c52008-11-21 20:32:33 +00005948 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005949}
drh1875f7a2008-12-08 18:19:17 +00005950static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5951 /*
5952 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5953 ** cast into a pointer to a function. And yet the library dlsym() routine
5954 ** returns a void* which is really a pointer to a function. So how do we
5955 ** use dlsym() with -pedantic-errors?
5956 **
5957 ** Variable x below is defined to be a pointer to a function taking
5958 ** parameters void* and const char* and returning a pointer to a function.
5959 ** We initialize x by assigning it a pointer to the dlsym() function.
5960 ** (That assignment requires a cast.) Then we call the function that
5961 ** x points to.
5962 **
5963 ** This work-around is unlikely to work correctly on any system where
5964 ** you really cannot cast a function pointer into void*. But then, on the
5965 ** other hand, dlsym() will not work on such a system either, so we have
5966 ** not really lost anything.
5967 */
5968 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005969 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005970 x = (void(*(*)(void*,const char*))(void))dlsym;
5971 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005972}
danielk1977397d65f2008-11-19 11:35:39 +00005973static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5974 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005975 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005976}
danielk1977b4b47412007-08-17 15:53:36 +00005977#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5978 #define unixDlOpen 0
5979 #define unixDlError 0
5980 #define unixDlSym 0
5981 #define unixDlClose 0
5982#endif
5983
5984/*
danielk197790949c22007-08-17 16:50:38 +00005985** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005986*/
danielk1977397d65f2008-11-19 11:35:39 +00005987static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5988 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005989 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005990
drhbbd42a62004-05-22 17:41:58 +00005991 /* We have to initialize zBuf to prevent valgrind from reporting
5992 ** errors. The reports issued by valgrind are incorrect - we would
5993 ** prefer that the randomness be increased by making use of the
5994 ** uninitialized space in zBuf - but valgrind errors tend to worry
5995 ** some users. Rather than argue, it seems easier just to initialize
5996 ** the whole array and silence valgrind, even if that means less randomness
5997 ** in the random seed.
5998 **
5999 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006000 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006001 ** tests repeatable.
6002 */
danielk1977b4b47412007-08-17 15:53:36 +00006003 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00006004#if !defined(SQLITE_TEST)
6005 {
drhc18b4042012-02-10 03:10:27 +00006006 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00006007 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006008 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006009 time_t t;
6010 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006011 memcpy(zBuf, &t, sizeof(t));
6012 pid = getpid();
6013 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00006014 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00006015 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00006016 }else{
drhc18b4042012-02-10 03:10:27 +00006017 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006018 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006019 }
drhbbd42a62004-05-22 17:41:58 +00006020 }
6021#endif
drh72cbd072008-10-14 17:58:38 +00006022 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006023}
6024
danielk1977b4b47412007-08-17 15:53:36 +00006025
drhbbd42a62004-05-22 17:41:58 +00006026/*
6027** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006028** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006029** The return value is the number of microseconds of sleep actually
6030** requested from the underlying operating system, a number which
6031** might be greater than or equal to the argument, but not less
6032** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006033*/
danielk1977397d65f2008-11-19 11:35:39 +00006034static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006035#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006036 struct timespec sp;
6037
6038 sp.tv_sec = microseconds / 1000000;
6039 sp.tv_nsec = (microseconds % 1000000) * 1000;
6040 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006041 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006042 return microseconds;
6043#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006044 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006045 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006046 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006047#else
danielk1977b4b47412007-08-17 15:53:36 +00006048 int seconds = (microseconds+999999)/1000000;
6049 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006050 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006051 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006052#endif
drh88f474a2006-01-02 20:00:12 +00006053}
6054
6055/*
drh6b9d6dd2008-12-03 19:34:47 +00006056** The following variable, if set to a non-zero value, is interpreted as
6057** the number of seconds since 1970 and is used to set the result of
6058** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006059*/
6060#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006061int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006062#endif
6063
6064/*
drhb7e8ea22010-05-03 14:32:30 +00006065** Find the current time (in Universal Coordinated Time). Write into *piNow
6066** the current time and date as a Julian Day number times 86_400_000. In
6067** other words, write into *piNow the number of milliseconds since the Julian
6068** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6069** proleptic Gregorian calendar.
6070**
drh31702252011-10-12 23:13:43 +00006071** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6072** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006073*/
6074static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6075 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006076 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006077#if defined(NO_GETTOD)
6078 time_t t;
6079 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006080 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006081#elif OS_VXWORKS
6082 struct timespec sNow;
6083 clock_gettime(CLOCK_REALTIME, &sNow);
6084 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6085#else
6086 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006087 if( gettimeofday(&sNow, 0)==0 ){
6088 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6089 }else{
6090 rc = SQLITE_ERROR;
6091 }
drhb7e8ea22010-05-03 14:32:30 +00006092#endif
6093
6094#ifdef SQLITE_TEST
6095 if( sqlite3_current_time ){
6096 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6097 }
6098#endif
6099 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006100 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006101}
6102
6103/*
drhbbd42a62004-05-22 17:41:58 +00006104** Find the current time (in Universal Coordinated Time). Write the
6105** current time and date as a Julian Day number into *prNow and
6106** return 0. Return 1 if the time and date cannot be found.
6107*/
danielk1977397d65f2008-11-19 11:35:39 +00006108static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006109 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006110 int rc;
drhff828942010-06-26 21:34:06 +00006111 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006112 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006113 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006114 return rc;
drhbbd42a62004-05-22 17:41:58 +00006115}
danielk1977b4b47412007-08-17 15:53:36 +00006116
drh6b9d6dd2008-12-03 19:34:47 +00006117/*
6118** We added the xGetLastError() method with the intention of providing
6119** better low-level error messages when operating-system problems come up
6120** during SQLite operation. But so far, none of that has been implemented
6121** in the core. So this routine is never called. For now, it is merely
6122** a place-holder.
6123*/
danielk1977397d65f2008-11-19 11:35:39 +00006124static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6125 UNUSED_PARAMETER(NotUsed);
6126 UNUSED_PARAMETER(NotUsed2);
6127 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006128 return 0;
6129}
6130
drhf2424c52010-04-26 00:04:55 +00006131
6132/*
drh734c9862008-11-28 15:37:20 +00006133************************ End of sqlite3_vfs methods ***************************
6134******************************************************************************/
6135
drh715ff302008-12-03 22:32:44 +00006136/******************************************************************************
6137************************** Begin Proxy Locking ********************************
6138**
6139** Proxy locking is a "uber-locking-method" in this sense: It uses the
6140** other locking methods on secondary lock files. Proxy locking is a
6141** meta-layer over top of the primitive locking implemented above. For
6142** this reason, the division that implements of proxy locking is deferred
6143** until late in the file (here) after all of the other I/O methods have
6144** been defined - so that the primitive locking methods are available
6145** as services to help with the implementation of proxy locking.
6146**
6147****
6148**
6149** The default locking schemes in SQLite use byte-range locks on the
6150** database file to coordinate safe, concurrent access by multiple readers
6151** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6152** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6153** as POSIX read & write locks over fixed set of locations (via fsctl),
6154** on AFP and SMB only exclusive byte-range locks are available via fsctl
6155** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6156** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6157** address in the shared range is taken for a SHARED lock, the entire
6158** shared range is taken for an EXCLUSIVE lock):
6159**
drhf2f105d2012-08-20 15:53:54 +00006160** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006161** RESERVED_BYTE 0x40000001
6162** SHARED_RANGE 0x40000002 -> 0x40000200
6163**
6164** This works well on the local file system, but shows a nearly 100x
6165** slowdown in read performance on AFP because the AFP client disables
6166** the read cache when byte-range locks are present. Enabling the read
6167** cache exposes a cache coherency problem that is present on all OS X
6168** supported network file systems. NFS and AFP both observe the
6169** close-to-open semantics for ensuring cache coherency
6170** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6171** address the requirements for concurrent database access by multiple
6172** readers and writers
6173** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6174**
6175** To address the performance and cache coherency issues, proxy file locking
6176** changes the way database access is controlled by limiting access to a
6177** single host at a time and moving file locks off of the database file
6178** and onto a proxy file on the local file system.
6179**
6180**
6181** Using proxy locks
6182** -----------------
6183**
6184** C APIs
6185**
6186** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6187** <proxy_path> | ":auto:");
6188** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6189**
6190**
6191** SQL pragmas
6192**
6193** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6194** PRAGMA [database.]lock_proxy_file
6195**
6196** Specifying ":auto:" means that if there is a conch file with a matching
6197** host ID in it, the proxy path in the conch file will be used, otherwise
6198** a proxy path based on the user's temp dir
6199** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6200** actual proxy file name is generated from the name and path of the
6201** database file. For example:
6202**
6203** For database path "/Users/me/foo.db"
6204** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6205**
6206** Once a lock proxy is configured for a database connection, it can not
6207** be removed, however it may be switched to a different proxy path via
6208** the above APIs (assuming the conch file is not being held by another
6209** connection or process).
6210**
6211**
6212** How proxy locking works
6213** -----------------------
6214**
6215** Proxy file locking relies primarily on two new supporting files:
6216**
6217** * conch file to limit access to the database file to a single host
6218** at a time
6219**
6220** * proxy file to act as a proxy for the advisory locks normally
6221** taken on the database
6222**
6223** The conch file - to use a proxy file, sqlite must first "hold the conch"
6224** by taking an sqlite-style shared lock on the conch file, reading the
6225** contents and comparing the host's unique host ID (see below) and lock
6226** proxy path against the values stored in the conch. The conch file is
6227** stored in the same directory as the database file and the file name
6228** is patterned after the database file name as ".<databasename>-conch".
6229** If the conch file does not exist, or it's contents do not match the
6230** host ID and/or proxy path, then the lock is escalated to an exclusive
6231** lock and the conch file contents is updated with the host ID and proxy
6232** path and the lock is downgraded to a shared lock again. If the conch
6233** is held by another process (with a shared lock), the exclusive lock
6234** will fail and SQLITE_BUSY is returned.
6235**
6236** The proxy file - a single-byte file used for all advisory file locks
6237** normally taken on the database file. This allows for safe sharing
6238** of the database file for multiple readers and writers on the same
6239** host (the conch ensures that they all use the same local lock file).
6240**
drh715ff302008-12-03 22:32:44 +00006241** Requesting the lock proxy does not immediately take the conch, it is
6242** only taken when the first request to lock database file is made.
6243** This matches the semantics of the traditional locking behavior, where
6244** opening a connection to a database file does not take a lock on it.
6245** The shared lock and an open file descriptor are maintained until
6246** the connection to the database is closed.
6247**
6248** The proxy file and the lock file are never deleted so they only need
6249** to be created the first time they are used.
6250**
6251** Configuration options
6252** ---------------------
6253**
6254** SQLITE_PREFER_PROXY_LOCKING
6255**
6256** Database files accessed on non-local file systems are
6257** automatically configured for proxy locking, lock files are
6258** named automatically using the same logic as
6259** PRAGMA lock_proxy_file=":auto:"
6260**
6261** SQLITE_PROXY_DEBUG
6262**
6263** Enables the logging of error messages during host id file
6264** retrieval and creation
6265**
drh715ff302008-12-03 22:32:44 +00006266** LOCKPROXYDIR
6267**
6268** Overrides the default directory used for lock proxy files that
6269** are named automatically via the ":auto:" setting
6270**
6271** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6272**
6273** Permissions to use when creating a directory for storing the
6274** lock proxy files, only used when LOCKPROXYDIR is not set.
6275**
6276**
6277** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6278** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6279** force proxy locking to be used for every database file opened, and 0
6280** will force automatic proxy locking to be disabled for all database
6281** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6282** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6283*/
6284
6285/*
6286** Proxy locking is only available on MacOSX
6287*/
drhd2cb50b2009-01-09 21:41:17 +00006288#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006289
drh715ff302008-12-03 22:32:44 +00006290/*
6291** The proxyLockingContext has the path and file structures for the remote
6292** and local proxy files in it
6293*/
6294typedef struct proxyLockingContext proxyLockingContext;
6295struct proxyLockingContext {
6296 unixFile *conchFile; /* Open conch file */
6297 char *conchFilePath; /* Name of the conch file */
6298 unixFile *lockProxy; /* Open proxy lock file */
6299 char *lockProxyPath; /* Name of the proxy lock file */
6300 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006301 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006302 void *oldLockingContext; /* Original lockingcontext to restore on close */
6303 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6304};
6305
drh7ed97b92010-01-20 13:07:21 +00006306/*
6307** The proxy lock file path for the database at dbPath is written into lPath,
6308** which must point to valid, writable memory large enough for a maxLen length
6309** file path.
drh715ff302008-12-03 22:32:44 +00006310*/
drh715ff302008-12-03 22:32:44 +00006311static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6312 int len;
6313 int dbLen;
6314 int i;
6315
6316#ifdef LOCKPROXYDIR
6317 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6318#else
6319# ifdef _CS_DARWIN_USER_TEMP_DIR
6320 {
drh7ed97b92010-01-20 13:07:21 +00006321 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006322 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6323 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006324 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006325 }
drh7ed97b92010-01-20 13:07:21 +00006326 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006327 }
6328# else
6329 len = strlcpy(lPath, "/tmp/", maxLen);
6330# endif
6331#endif
6332
6333 if( lPath[len-1]!='/' ){
6334 len = strlcat(lPath, "/", maxLen);
6335 }
6336
6337 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006338 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006339 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006340 char c = dbPath[i];
6341 lPath[i+len] = (c=='/')?'_':c;
6342 }
6343 lPath[i+len]='\0';
6344 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006345 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006346 return SQLITE_OK;
6347}
6348
drh7ed97b92010-01-20 13:07:21 +00006349/*
6350 ** Creates the lock file and any missing directories in lockPath
6351 */
6352static int proxyCreateLockPath(const char *lockPath){
6353 int i, len;
6354 char buf[MAXPATHLEN];
6355 int start = 0;
6356
6357 assert(lockPath!=NULL);
6358 /* try to create all the intermediate directories */
6359 len = (int)strlen(lockPath);
6360 buf[0] = lockPath[0];
6361 for( i=1; i<len; i++ ){
6362 if( lockPath[i] == '/' && (i - start > 0) ){
6363 /* only mkdir if leaf dir != "." or "/" or ".." */
6364 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6365 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6366 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006367 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006368 int err=errno;
6369 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006370 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006371 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006372 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006373 return err;
6374 }
6375 }
6376 }
6377 start=i+1;
6378 }
6379 buf[i] = lockPath[i];
6380 }
drh308c2a52010-05-14 11:30:18 +00006381 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006382 return 0;
6383}
6384
drh715ff302008-12-03 22:32:44 +00006385/*
6386** Create a new VFS file descriptor (stored in memory obtained from
6387** sqlite3_malloc) and open the file named "path" in the file descriptor.
6388**
6389** The caller is responsible not only for closing the file descriptor
6390** but also for freeing the memory associated with the file descriptor.
6391*/
drh7ed97b92010-01-20 13:07:21 +00006392static int proxyCreateUnixFile(
6393 const char *path, /* path for the new unixFile */
6394 unixFile **ppFile, /* unixFile created and returned by ref */
6395 int islockfile /* if non zero missing dirs will be created */
6396) {
6397 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006398 unixFile *pNew;
6399 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006400 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006401 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006402 int terrno = 0;
6403 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006404
drh7ed97b92010-01-20 13:07:21 +00006405 /* 1. first try to open/create the file
6406 ** 2. if that fails, and this is a lock file (not-conch), try creating
6407 ** the parent directories and then try again.
6408 ** 3. if that fails, try to open the file read-only
6409 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6410 */
6411 pUnused = findReusableFd(path, openFlags);
6412 if( pUnused ){
6413 fd = pUnused->fd;
6414 }else{
6415 pUnused = sqlite3_malloc(sizeof(*pUnused));
6416 if( !pUnused ){
6417 return SQLITE_NOMEM;
6418 }
6419 }
6420 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006421 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006422 terrno = errno;
6423 if( fd<0 && errno==ENOENT && islockfile ){
6424 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006425 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006426 }
6427 }
6428 }
6429 if( fd<0 ){
6430 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006431 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006432 terrno = errno;
6433 }
6434 if( fd<0 ){
6435 if( islockfile ){
6436 return SQLITE_BUSY;
6437 }
6438 switch (terrno) {
6439 case EACCES:
6440 return SQLITE_PERM;
6441 case EIO:
6442 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6443 default:
drh9978c972010-02-23 17:36:32 +00006444 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006445 }
6446 }
6447
6448 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6449 if( pNew==NULL ){
6450 rc = SQLITE_NOMEM;
6451 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006452 }
6453 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006454 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006455 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006456 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006457 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006458 pUnused->fd = fd;
6459 pUnused->flags = openFlags;
6460 pNew->pUnused = pUnused;
6461
drhc02a43a2012-01-10 23:18:38 +00006462 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006463 if( rc==SQLITE_OK ){
6464 *ppFile = pNew;
6465 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006466 }
drh7ed97b92010-01-20 13:07:21 +00006467end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006468 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006469 sqlite3_free(pNew);
6470 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006471 return rc;
6472}
6473
drh7ed97b92010-01-20 13:07:21 +00006474#ifdef SQLITE_TEST
6475/* simulate multiple hosts by creating unique hostid file paths */
6476int sqlite3_hostid_num = 0;
6477#endif
6478
6479#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6480
drh0ab216a2010-07-02 17:10:40 +00006481/* Not always defined in the headers as it ought to be */
6482extern int gethostuuid(uuid_t id, const struct timespec *wait);
6483
drh7ed97b92010-01-20 13:07:21 +00006484/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6485** bytes of writable memory.
6486*/
6487static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006488 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6489 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006490#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6491 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006492 {
6493 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6494 if( gethostuuid(pHostID, &timeout) ){
6495 int err = errno;
6496 if( pError ){
6497 *pError = err;
6498 }
6499 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006500 }
drh7ed97b92010-01-20 13:07:21 +00006501 }
drh3d4435b2011-08-26 20:55:50 +00006502#else
6503 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006504#endif
drh7ed97b92010-01-20 13:07:21 +00006505#ifdef SQLITE_TEST
6506 /* simulate multiple hosts by creating unique hostid file paths */
6507 if( sqlite3_hostid_num != 0){
6508 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6509 }
6510#endif
6511
6512 return SQLITE_OK;
6513}
6514
6515/* The conch file contains the header, host id and lock file path
6516 */
6517#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6518#define PROXY_HEADERLEN 1 /* conch file header length */
6519#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6520#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6521
6522/*
6523** Takes an open conch file, copies the contents to a new path and then moves
6524** it back. The newly created file's file descriptor is assigned to the
6525** conch file structure and finally the original conch file descriptor is
6526** closed. Returns zero if successful.
6527*/
6528static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6529 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6530 unixFile *conchFile = pCtx->conchFile;
6531 char tPath[MAXPATHLEN];
6532 char buf[PROXY_MAXCONCHLEN];
6533 char *cPath = pCtx->conchFilePath;
6534 size_t readLen = 0;
6535 size_t pathLen = 0;
6536 char errmsg[64] = "";
6537 int fd = -1;
6538 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006539 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006540
6541 /* create a new path by replace the trailing '-conch' with '-break' */
6542 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6543 if( pathLen>MAXPATHLEN || pathLen<6 ||
6544 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006545 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006546 goto end_breaklock;
6547 }
6548 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006549 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006550 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006551 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006552 goto end_breaklock;
6553 }
6554 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006555 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006556 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006557 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006558 goto end_breaklock;
6559 }
drhe562be52011-03-02 18:01:10 +00006560 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006561 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006562 goto end_breaklock;
6563 }
6564 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006565 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006566 goto end_breaklock;
6567 }
6568 rc = 0;
6569 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006570 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006571 conchFile->h = fd;
6572 conchFile->openFlags = O_RDWR | O_CREAT;
6573
6574end_breaklock:
6575 if( rc ){
6576 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006577 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006578 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006579 }
6580 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6581 }
6582 return rc;
6583}
6584
6585/* Take the requested lock on the conch file and break a stale lock if the
6586** host id matches.
6587*/
6588static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6589 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6590 unixFile *conchFile = pCtx->conchFile;
6591 int rc = SQLITE_OK;
6592 int nTries = 0;
6593 struct timespec conchModTime;
6594
drh3d4435b2011-08-26 20:55:50 +00006595 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006596 do {
6597 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6598 nTries ++;
6599 if( rc==SQLITE_BUSY ){
6600 /* If the lock failed (busy):
6601 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6602 * 2nd try: fail if the mod time changed or host id is different, wait
6603 * 10 sec and try again
6604 * 3rd try: break the lock unless the mod time has changed.
6605 */
6606 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006607 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006608 pFile->lastErrno = errno;
6609 return SQLITE_IOERR_LOCK;
6610 }
6611
6612 if( nTries==1 ){
6613 conchModTime = buf.st_mtimespec;
6614 usleep(500000); /* wait 0.5 sec and try the lock again*/
6615 continue;
6616 }
6617
6618 assert( nTries>1 );
6619 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6620 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6621 return SQLITE_BUSY;
6622 }
6623
6624 if( nTries==2 ){
6625 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006626 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006627 if( len<0 ){
6628 pFile->lastErrno = errno;
6629 return SQLITE_IOERR_LOCK;
6630 }
6631 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6632 /* don't break the lock if the host id doesn't match */
6633 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6634 return SQLITE_BUSY;
6635 }
6636 }else{
6637 /* don't break the lock on short read or a version mismatch */
6638 return SQLITE_BUSY;
6639 }
6640 usleep(10000000); /* wait 10 sec and try the lock again */
6641 continue;
6642 }
6643
6644 assert( nTries==3 );
6645 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6646 rc = SQLITE_OK;
6647 if( lockType==EXCLUSIVE_LOCK ){
6648 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6649 }
6650 if( !rc ){
6651 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6652 }
6653 }
6654 }
6655 } while( rc==SQLITE_BUSY && nTries<3 );
6656
6657 return rc;
6658}
6659
6660/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006661** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6662** lockPath means that the lockPath in the conch file will be used if the
6663** host IDs match, or a new lock path will be generated automatically
6664** and written to the conch file.
6665*/
6666static int proxyTakeConch(unixFile *pFile){
6667 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6668
drh7ed97b92010-01-20 13:07:21 +00006669 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006670 return SQLITE_OK;
6671 }else{
6672 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006673 uuid_t myHostID;
6674 int pError = 0;
6675 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006676 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006677 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006678 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006679 int createConch = 0;
6680 int hostIdMatch = 0;
6681 int readLen = 0;
6682 int tryOldLockPath = 0;
6683 int forceNewLockPath = 0;
6684
drh308c2a52010-05-14 11:30:18 +00006685 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6686 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006687
drh7ed97b92010-01-20 13:07:21 +00006688 rc = proxyGetHostID(myHostID, &pError);
6689 if( (rc&0xff)==SQLITE_IOERR ){
6690 pFile->lastErrno = pError;
6691 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006692 }
drh7ed97b92010-01-20 13:07:21 +00006693 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006694 if( rc!=SQLITE_OK ){
6695 goto end_takeconch;
6696 }
drh7ed97b92010-01-20 13:07:21 +00006697 /* read the existing conch file */
6698 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6699 if( readLen<0 ){
6700 /* I/O error: lastErrno set by seekAndRead */
6701 pFile->lastErrno = conchFile->lastErrno;
6702 rc = SQLITE_IOERR_READ;
6703 goto end_takeconch;
6704 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6705 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6706 /* a short read or version format mismatch means we need to create a new
6707 ** conch file.
6708 */
6709 createConch = 1;
6710 }
6711 /* if the host id matches and the lock path already exists in the conch
6712 ** we'll try to use the path there, if we can't open that path, we'll
6713 ** retry with a new auto-generated path
6714 */
6715 do { /* in case we need to try again for an :auto: named lock file */
6716
6717 if( !createConch && !forceNewLockPath ){
6718 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6719 PROXY_HOSTIDLEN);
6720 /* if the conch has data compare the contents */
6721 if( !pCtx->lockProxyPath ){
6722 /* for auto-named local lock file, just check the host ID and we'll
6723 ** use the local lock file path that's already in there
6724 */
6725 if( hostIdMatch ){
6726 size_t pathLen = (readLen - PROXY_PATHINDEX);
6727
6728 if( pathLen>=MAXPATHLEN ){
6729 pathLen=MAXPATHLEN-1;
6730 }
6731 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6732 lockPath[pathLen] = 0;
6733 tempLockPath = lockPath;
6734 tryOldLockPath = 1;
6735 /* create a copy of the lock path if the conch is taken */
6736 goto end_takeconch;
6737 }
6738 }else if( hostIdMatch
6739 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6740 readLen-PROXY_PATHINDEX)
6741 ){
6742 /* conch host and lock path match */
6743 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006744 }
drh7ed97b92010-01-20 13:07:21 +00006745 }
6746
6747 /* if the conch isn't writable and doesn't match, we can't take it */
6748 if( (conchFile->openFlags&O_RDWR) == 0 ){
6749 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006750 goto end_takeconch;
6751 }
drh7ed97b92010-01-20 13:07:21 +00006752
6753 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006754 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006755 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6756 tempLockPath = lockPath;
6757 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006758 }
drh7ed97b92010-01-20 13:07:21 +00006759
6760 /* update conch with host and path (this will fail if other process
6761 ** has a shared lock already), if the host id matches, use the big
6762 ** stick.
drh715ff302008-12-03 22:32:44 +00006763 */
drh7ed97b92010-01-20 13:07:21 +00006764 futimes(conchFile->h, NULL);
6765 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006766 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006767 /* We are trying for an exclusive lock but another thread in this
6768 ** same process is still holding a shared lock. */
6769 rc = SQLITE_BUSY;
6770 } else {
6771 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006772 }
drh715ff302008-12-03 22:32:44 +00006773 }else{
drh7ed97b92010-01-20 13:07:21 +00006774 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006775 }
drh7ed97b92010-01-20 13:07:21 +00006776 if( rc==SQLITE_OK ){
6777 char writeBuffer[PROXY_MAXCONCHLEN];
6778 int writeSize = 0;
6779
6780 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6781 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6782 if( pCtx->lockProxyPath!=NULL ){
6783 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6784 }else{
6785 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6786 }
6787 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006788 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006789 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6790 fsync(conchFile->h);
6791 /* If we created a new conch file (not just updated the contents of a
6792 ** valid conch file), try to match the permissions of the database
6793 */
6794 if( rc==SQLITE_OK && createConch ){
6795 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006796 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006797 if( err==0 ){
6798 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6799 S_IROTH|S_IWOTH);
6800 /* try to match the database file R/W permissions, ignore failure */
6801#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006802 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006803#else
drhff812312011-02-23 13:33:46 +00006804 do{
drhe562be52011-03-02 18:01:10 +00006805 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006806 }while( rc==(-1) && errno==EINTR );
6807 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006808 int code = errno;
6809 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6810 cmode, code, strerror(code));
6811 } else {
6812 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6813 }
6814 }else{
6815 int code = errno;
6816 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6817 err, code, strerror(code));
6818#endif
6819 }
drh715ff302008-12-03 22:32:44 +00006820 }
6821 }
drh7ed97b92010-01-20 13:07:21 +00006822 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6823
6824 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006825 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006826 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006827 int fd;
drh7ed97b92010-01-20 13:07:21 +00006828 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006829 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006830 }
6831 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006832 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006833 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006834 if( fd>=0 ){
6835 pFile->h = fd;
6836 }else{
drh9978c972010-02-23 17:36:32 +00006837 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006838 during locking */
6839 }
6840 }
6841 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6842 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6843 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6844 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6845 /* we couldn't create the proxy lock file with the old lock file path
6846 ** so try again via auto-naming
6847 */
6848 forceNewLockPath = 1;
6849 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006850 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006851 }
6852 }
6853 if( rc==SQLITE_OK ){
6854 /* Need to make a copy of path if we extracted the value
6855 ** from the conch file or the path was allocated on the stack
6856 */
6857 if( tempLockPath ){
6858 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6859 if( !pCtx->lockProxyPath ){
6860 rc = SQLITE_NOMEM;
6861 }
6862 }
6863 }
6864 if( rc==SQLITE_OK ){
6865 pCtx->conchHeld = 1;
6866
6867 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6868 afpLockingContext *afpCtx;
6869 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6870 afpCtx->dbPath = pCtx->lockProxyPath;
6871 }
6872 } else {
6873 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6874 }
drh308c2a52010-05-14 11:30:18 +00006875 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6876 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006877 return rc;
drh308c2a52010-05-14 11:30:18 +00006878 } while (1); /* in case we need to retry the :auto: lock file -
6879 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006880 }
6881}
6882
6883/*
6884** If pFile holds a lock on a conch file, then release that lock.
6885*/
6886static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006887 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006888 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6889 unixFile *conchFile; /* Name of the conch file */
6890
6891 pCtx = (proxyLockingContext *)pFile->lockingContext;
6892 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006893 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006894 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006895 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006896 if( pCtx->conchHeld>0 ){
6897 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6898 }
drh715ff302008-12-03 22:32:44 +00006899 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006900 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6901 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006902 return rc;
6903}
6904
6905/*
6906** Given the name of a database file, compute the name of its conch file.
6907** Store the conch filename in memory obtained from sqlite3_malloc().
6908** Make *pConchPath point to the new name. Return SQLITE_OK on success
6909** or SQLITE_NOMEM if unable to obtain memory.
6910**
6911** The caller is responsible for ensuring that the allocated memory
6912** space is eventually freed.
6913**
6914** *pConchPath is set to NULL if a memory allocation error occurs.
6915*/
6916static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6917 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006918 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006919 char *conchPath; /* buffer in which to construct conch name */
6920
6921 /* Allocate space for the conch filename and initialize the name to
6922 ** the name of the original database file. */
6923 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6924 if( conchPath==0 ){
6925 return SQLITE_NOMEM;
6926 }
6927 memcpy(conchPath, dbPath, len+1);
6928
6929 /* now insert a "." before the last / character */
6930 for( i=(len-1); i>=0; i-- ){
6931 if( conchPath[i]=='/' ){
6932 i++;
6933 break;
6934 }
6935 }
6936 conchPath[i]='.';
6937 while ( i<len ){
6938 conchPath[i+1]=dbPath[i];
6939 i++;
6940 }
6941
6942 /* append the "-conch" suffix to the file */
6943 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006944 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006945
6946 return SQLITE_OK;
6947}
6948
6949
6950/* Takes a fully configured proxy locking-style unix file and switches
6951** the local lock file path
6952*/
6953static int switchLockProxyPath(unixFile *pFile, const char *path) {
6954 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6955 char *oldPath = pCtx->lockProxyPath;
6956 int rc = SQLITE_OK;
6957
drh308c2a52010-05-14 11:30:18 +00006958 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006959 return SQLITE_BUSY;
6960 }
6961
6962 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6963 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6964 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6965 return SQLITE_OK;
6966 }else{
6967 unixFile *lockProxy = pCtx->lockProxy;
6968 pCtx->lockProxy=NULL;
6969 pCtx->conchHeld = 0;
6970 if( lockProxy!=NULL ){
6971 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6972 if( rc ) return rc;
6973 sqlite3_free(lockProxy);
6974 }
6975 sqlite3_free(oldPath);
6976 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6977 }
6978
6979 return rc;
6980}
6981
6982/*
6983** pFile is a file that has been opened by a prior xOpen call. dbPath
6984** is a string buffer at least MAXPATHLEN+1 characters in size.
6985**
6986** This routine find the filename associated with pFile and writes it
6987** int dbPath.
6988*/
6989static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006990#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006991 if( pFile->pMethod == &afpIoMethods ){
6992 /* afp style keeps a reference to the db path in the filePath field
6993 ** of the struct */
drhea678832008-12-10 19:26:22 +00006994 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006995 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6996 } else
drh715ff302008-12-03 22:32:44 +00006997#endif
6998 if( pFile->pMethod == &dotlockIoMethods ){
6999 /* dot lock style uses the locking context to store the dot lock
7000 ** file path */
7001 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7002 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7003 }else{
7004 /* all other styles use the locking context to store the db file path */
7005 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007006 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007007 }
7008 return SQLITE_OK;
7009}
7010
7011/*
7012** Takes an already filled in unix file and alters it so all file locking
7013** will be performed on the local proxy lock file. The following fields
7014** are preserved in the locking context so that they can be restored and
7015** the unix structure properly cleaned up at close time:
7016** ->lockingContext
7017** ->pMethod
7018*/
7019static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7020 proxyLockingContext *pCtx;
7021 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7022 char *lockPath=NULL;
7023 int rc = SQLITE_OK;
7024
drh308c2a52010-05-14 11:30:18 +00007025 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007026 return SQLITE_BUSY;
7027 }
7028 proxyGetDbPathForUnixFile(pFile, dbPath);
7029 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7030 lockPath=NULL;
7031 }else{
7032 lockPath=(char *)path;
7033 }
7034
drh308c2a52010-05-14 11:30:18 +00007035 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7036 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007037
7038 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7039 if( pCtx==0 ){
7040 return SQLITE_NOMEM;
7041 }
7042 memset(pCtx, 0, sizeof(*pCtx));
7043
7044 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7045 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007046 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7047 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7048 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7049 ** (c) the file system is read-only, then enable no-locking access.
7050 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7051 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7052 */
7053 struct statfs fsInfo;
7054 struct stat conchInfo;
7055 int goLockless = 0;
7056
drh99ab3b12011-03-02 15:09:07 +00007057 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007058 int err = errno;
7059 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7060 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7061 }
7062 }
7063 if( goLockless ){
7064 pCtx->conchHeld = -1; /* read only FS/ lockless */
7065 rc = SQLITE_OK;
7066 }
7067 }
drh715ff302008-12-03 22:32:44 +00007068 }
7069 if( rc==SQLITE_OK && lockPath ){
7070 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7071 }
7072
7073 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007074 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7075 if( pCtx->dbPath==NULL ){
7076 rc = SQLITE_NOMEM;
7077 }
7078 }
7079 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007080 /* all memory is allocated, proxys are created and assigned,
7081 ** switch the locking context and pMethod then return.
7082 */
drh715ff302008-12-03 22:32:44 +00007083 pCtx->oldLockingContext = pFile->lockingContext;
7084 pFile->lockingContext = pCtx;
7085 pCtx->pOldMethod = pFile->pMethod;
7086 pFile->pMethod = &proxyIoMethods;
7087 }else{
7088 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007089 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007090 sqlite3_free(pCtx->conchFile);
7091 }
drhd56b1212010-08-11 06:14:15 +00007092 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007093 sqlite3_free(pCtx->conchFilePath);
7094 sqlite3_free(pCtx);
7095 }
drh308c2a52010-05-14 11:30:18 +00007096 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7097 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007098 return rc;
7099}
7100
7101
7102/*
7103** This routine handles sqlite3_file_control() calls that are specific
7104** to proxy locking.
7105*/
7106static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7107 switch( op ){
7108 case SQLITE_GET_LOCKPROXYFILE: {
7109 unixFile *pFile = (unixFile*)id;
7110 if( pFile->pMethod == &proxyIoMethods ){
7111 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7112 proxyTakeConch(pFile);
7113 if( pCtx->lockProxyPath ){
7114 *(const char **)pArg = pCtx->lockProxyPath;
7115 }else{
7116 *(const char **)pArg = ":auto: (not held)";
7117 }
7118 } else {
7119 *(const char **)pArg = NULL;
7120 }
7121 return SQLITE_OK;
7122 }
7123 case SQLITE_SET_LOCKPROXYFILE: {
7124 unixFile *pFile = (unixFile*)id;
7125 int rc = SQLITE_OK;
7126 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7127 if( pArg==NULL || (const char *)pArg==0 ){
7128 if( isProxyStyle ){
7129 /* turn off proxy locking - not supported */
7130 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7131 }else{
7132 /* turn off proxy locking - already off - NOOP */
7133 rc = SQLITE_OK;
7134 }
7135 }else{
7136 const char *proxyPath = (const char *)pArg;
7137 if( isProxyStyle ){
7138 proxyLockingContext *pCtx =
7139 (proxyLockingContext*)pFile->lockingContext;
7140 if( !strcmp(pArg, ":auto:")
7141 || (pCtx->lockProxyPath &&
7142 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7143 ){
7144 rc = SQLITE_OK;
7145 }else{
7146 rc = switchLockProxyPath(pFile, proxyPath);
7147 }
7148 }else{
7149 /* turn on proxy file locking */
7150 rc = proxyTransformUnixFile(pFile, proxyPath);
7151 }
7152 }
7153 return rc;
7154 }
7155 default: {
7156 assert( 0 ); /* The call assures that only valid opcodes are sent */
7157 }
7158 }
7159 /*NOTREACHED*/
7160 return SQLITE_ERROR;
7161}
7162
7163/*
7164** Within this division (the proxying locking implementation) the procedures
7165** above this point are all utilities. The lock-related methods of the
7166** proxy-locking sqlite3_io_method object follow.
7167*/
7168
7169
7170/*
7171** This routine checks if there is a RESERVED lock held on the specified
7172** file by this or any other process. If such a lock is held, set *pResOut
7173** to a non-zero value otherwise *pResOut is set to zero. The return value
7174** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7175*/
7176static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7177 unixFile *pFile = (unixFile*)id;
7178 int rc = proxyTakeConch(pFile);
7179 if( rc==SQLITE_OK ){
7180 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007181 if( pCtx->conchHeld>0 ){
7182 unixFile *proxy = pCtx->lockProxy;
7183 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7184 }else{ /* conchHeld < 0 is lockless */
7185 pResOut=0;
7186 }
drh715ff302008-12-03 22:32:44 +00007187 }
7188 return rc;
7189}
7190
7191/*
drh308c2a52010-05-14 11:30:18 +00007192** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007193** of the following:
7194**
7195** (1) SHARED_LOCK
7196** (2) RESERVED_LOCK
7197** (3) PENDING_LOCK
7198** (4) EXCLUSIVE_LOCK
7199**
7200** Sometimes when requesting one lock state, additional lock states
7201** are inserted in between. The locking might fail on one of the later
7202** transitions leaving the lock state different from what it started but
7203** still short of its goal. The following chart shows the allowed
7204** transitions and the inserted intermediate states:
7205**
7206** UNLOCKED -> SHARED
7207** SHARED -> RESERVED
7208** SHARED -> (PENDING) -> EXCLUSIVE
7209** RESERVED -> (PENDING) -> EXCLUSIVE
7210** PENDING -> EXCLUSIVE
7211**
7212** This routine will only increase a lock. Use the sqlite3OsUnlock()
7213** routine to lower a locking level.
7214*/
drh308c2a52010-05-14 11:30:18 +00007215static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007216 unixFile *pFile = (unixFile*)id;
7217 int rc = proxyTakeConch(pFile);
7218 if( rc==SQLITE_OK ){
7219 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007220 if( pCtx->conchHeld>0 ){
7221 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007222 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7223 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007224 }else{
7225 /* conchHeld < 0 is lockless */
7226 }
drh715ff302008-12-03 22:32:44 +00007227 }
7228 return rc;
7229}
7230
7231
7232/*
drh308c2a52010-05-14 11:30:18 +00007233** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007234** must be either NO_LOCK or SHARED_LOCK.
7235**
7236** If the locking level of the file descriptor is already at or below
7237** the requested locking level, this routine is a no-op.
7238*/
drh308c2a52010-05-14 11:30:18 +00007239static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007240 unixFile *pFile = (unixFile*)id;
7241 int rc = proxyTakeConch(pFile);
7242 if( rc==SQLITE_OK ){
7243 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007244 if( pCtx->conchHeld>0 ){
7245 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007246 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7247 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007248 }else{
7249 /* conchHeld < 0 is lockless */
7250 }
drh715ff302008-12-03 22:32:44 +00007251 }
7252 return rc;
7253}
7254
7255/*
7256** Close a file that uses proxy locks.
7257*/
7258static int proxyClose(sqlite3_file *id) {
7259 if( id ){
7260 unixFile *pFile = (unixFile*)id;
7261 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7262 unixFile *lockProxy = pCtx->lockProxy;
7263 unixFile *conchFile = pCtx->conchFile;
7264 int rc = SQLITE_OK;
7265
7266 if( lockProxy ){
7267 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7268 if( rc ) return rc;
7269 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7270 if( rc ) return rc;
7271 sqlite3_free(lockProxy);
7272 pCtx->lockProxy = 0;
7273 }
7274 if( conchFile ){
7275 if( pCtx->conchHeld ){
7276 rc = proxyReleaseConch(pFile);
7277 if( rc ) return rc;
7278 }
7279 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7280 if( rc ) return rc;
7281 sqlite3_free(conchFile);
7282 }
drhd56b1212010-08-11 06:14:15 +00007283 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007284 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007285 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007286 /* restore the original locking context and pMethod then close it */
7287 pFile->lockingContext = pCtx->oldLockingContext;
7288 pFile->pMethod = pCtx->pOldMethod;
7289 sqlite3_free(pCtx);
7290 return pFile->pMethod->xClose(id);
7291 }
7292 return SQLITE_OK;
7293}
7294
7295
7296
drhd2cb50b2009-01-09 21:41:17 +00007297#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007298/*
7299** The proxy locking style is intended for use with AFP filesystems.
7300** And since AFP is only supported on MacOSX, the proxy locking is also
7301** restricted to MacOSX.
7302**
7303**
7304******************* End of the proxy lock implementation **********************
7305******************************************************************************/
7306
drh734c9862008-11-28 15:37:20 +00007307/*
danielk1977e339d652008-06-28 11:23:00 +00007308** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007309**
7310** This routine registers all VFS implementations for unix-like operating
7311** systems. This routine, and the sqlite3_os_end() routine that follows,
7312** should be the only routines in this file that are visible from other
7313** files.
drh6b9d6dd2008-12-03 19:34:47 +00007314**
7315** This routine is called once during SQLite initialization and by a
7316** single thread. The memory allocation and mutex subsystems have not
7317** necessarily been initialized when this routine is called, and so they
7318** should not be used.
drh153c62c2007-08-24 03:51:33 +00007319*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007320int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007321 /*
7322 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007323 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7324 ** to the "finder" function. (pAppData is a pointer to a pointer because
7325 ** silly C90 rules prohibit a void* from being cast to a function pointer
7326 ** and so we have to go through the intermediate pointer to avoid problems
7327 ** when compiling with -pedantic-errors on GCC.)
7328 **
7329 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007330 ** finder-function. The finder-function returns a pointer to the
7331 ** sqlite_io_methods object that implements the desired locking
7332 ** behaviors. See the division above that contains the IOMETHODS
7333 ** macro for addition information on finder-functions.
7334 **
7335 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7336 ** object. But the "autolockIoFinder" available on MacOSX does a little
7337 ** more than that; it looks at the filesystem type that hosts the
7338 ** database file and tries to choose an locking method appropriate for
7339 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007340 */
drh7708e972008-11-29 00:56:52 +00007341 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007342 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007343 sizeof(unixFile), /* szOsFile */ \
7344 MAX_PATHNAME, /* mxPathname */ \
7345 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007346 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007347 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007348 unixOpen, /* xOpen */ \
7349 unixDelete, /* xDelete */ \
7350 unixAccess, /* xAccess */ \
7351 unixFullPathname, /* xFullPathname */ \
7352 unixDlOpen, /* xDlOpen */ \
7353 unixDlError, /* xDlError */ \
7354 unixDlSym, /* xDlSym */ \
7355 unixDlClose, /* xDlClose */ \
7356 unixRandomness, /* xRandomness */ \
7357 unixSleep, /* xSleep */ \
7358 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007359 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007360 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007361 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007362 unixGetSystemCall, /* xGetSystemCall */ \
7363 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007364 }
7365
drh6b9d6dd2008-12-03 19:34:47 +00007366 /*
7367 ** All default VFSes for unix are contained in the following array.
7368 **
7369 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7370 ** by the SQLite core when the VFS is registered. So the following
7371 ** array cannot be const.
7372 */
danielk1977e339d652008-06-28 11:23:00 +00007373 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007374#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007375 UNIXVFS("unix", autolockIoFinder ),
7376#else
7377 UNIXVFS("unix", posixIoFinder ),
7378#endif
7379 UNIXVFS("unix-none", nolockIoFinder ),
7380 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007381 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007382#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007383 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007384#endif
7385#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007386 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007387#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007388 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007389#endif
chw78a13182009-04-07 05:35:03 +00007390#endif
drhd2cb50b2009-01-09 21:41:17 +00007391#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007392 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007393 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007394 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007395#endif
drh153c62c2007-08-24 03:51:33 +00007396 };
drh6b9d6dd2008-12-03 19:34:47 +00007397 unsigned int i; /* Loop counter */
7398
drh2aa5a002011-04-13 13:42:25 +00007399 /* Double-check that the aSyscall[] array has been constructed
7400 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhd1ab8062013-03-25 20:50:25 +00007401 assert( ArraySize(aSyscall)==24 );
drh2aa5a002011-04-13 13:42:25 +00007402
drh6b9d6dd2008-12-03 19:34:47 +00007403 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007404 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007405 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007406 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007407 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007408}
danielk1977e339d652008-06-28 11:23:00 +00007409
7410/*
drh6b9d6dd2008-12-03 19:34:47 +00007411** Shutdown the operating system interface.
7412**
7413** Some operating systems might need to do some cleanup in this routine,
7414** to release dynamically allocated objects. But not on unix.
7415** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007416*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007417int sqlite3_os_end(void){
7418 return SQLITE_OK;
7419}
drhdce8bdb2007-08-16 13:01:44 +00007420
danielk197729bafea2008-06-26 10:41:19 +00007421#endif /* SQLITE_OS_UNIX */