blob: 8688a652f55c41da5dbae8073ef59eb55d60f04f [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +0000122#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
drh1da88f02011-12-17 16:09:16 +0000125
danielk1977e339d652008-06-28 11:23:00 +0000126
drh40bbb0a2008-09-23 10:23:26 +0000127#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000128# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000129# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <semaphore.h>
131# include <limits.h>
132# else
drh9b35ea62008-11-29 02:20:26 +0000133# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000135# endif
drhbfe66312006-10-03 17:40:40 +0000136#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000137
drhf8b4d8c2010-03-05 13:53:22 +0000138#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000139# include <sys/mount.h>
140#endif
141
drhdbe4b882011-06-20 18:00:17 +0000142#ifdef HAVE_UTIME
143# include <utime.h>
144#endif
145
drh9cbe6352005-11-29 03:13:21 +0000146/*
drh7ed97b92010-01-20 13:07:21 +0000147** Allowed values of unixFile.fsFlags
148*/
149#define SQLITE_FSFLAGS_IS_MSDOS 0x1
150
151/*
drhf1a221e2006-01-15 17:27:17 +0000152** If we are to be thread-safe, include the pthreads header and define
153** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000154*/
drhd677b3d2007-08-20 22:48:41 +0000155#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000156# include <pthread.h>
157# define SQLITE_UNIX_THREADS 1
158#endif
159
160/*
161** Default permissions when creating a new file
162*/
163#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
164# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
165#endif
166
danielk1977b4b47412007-08-17 15:53:36 +0000167/*
drh5adc60b2012-04-14 13:25:11 +0000168** Default permissions when creating auto proxy dir
169*/
aswiftaebf4132008-11-21 00:10:35 +0000170#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
171# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
172#endif
173
174/*
danielk1977b4b47412007-08-17 15:53:36 +0000175** Maximum supported path-length.
176*/
177#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000178
drh734c9862008-11-28 15:37:20 +0000179/*
drh734c9862008-11-28 15:37:20 +0000180** Only set the lastErrno if the error code is a real error and not
181** a normal expected return code of SQLITE_BUSY or SQLITE_OK
182*/
183#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
184
drhd91c68f2010-05-14 14:52:25 +0000185/* Forward references */
186typedef struct unixShm unixShm; /* Connection shared memory */
187typedef struct unixShmNode unixShmNode; /* Shared memory instance */
188typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
189typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000190
191/*
dane946c392009-08-22 11:39:46 +0000192** Sometimes, after a file handle is closed by SQLite, the file descriptor
193** cannot be closed immediately. In these cases, instances of the following
194** structure are used to store the file descriptor while waiting for an
195** opportunity to either close or reuse it.
196*/
dane946c392009-08-22 11:39:46 +0000197struct UnixUnusedFd {
198 int fd; /* File descriptor to close */
199 int flags; /* Flags this file descriptor was opened with */
200 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
201};
202
203/*
drh9b35ea62008-11-29 02:20:26 +0000204** The unixFile structure is subclass of sqlite3_file specific to the unix
205** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000206*/
drh054889e2005-11-30 03:20:31 +0000207typedef struct unixFile unixFile;
208struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000209 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000210 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000211 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000212 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000213 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000214 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000215 int lastErrno; /* The unix errno from last I/O error */
216 void *lockingContext; /* Locking style specific state */
217 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000218 const char *zPath; /* Name of the file */
219 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000220 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000221#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000222 int nFetchOut; /* Number of outstanding xFetch refs */
223 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000224 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
225 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000226 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000227#endif
drh537dddf2012-10-26 13:46:24 +0000228#ifdef __QNXNTO__
229 int sectorSize; /* Device sector size */
230 int deviceCharacteristics; /* Precomputed device characteristics */
231#endif
drh08c6d442009-02-09 17:34:07 +0000232#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000233 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000234#endif
drh7ed97b92010-01-20 13:07:21 +0000235#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000236 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000237#endif
238#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000239 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000240#endif
drhd3d8c042012-05-29 17:02:40 +0000241#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000242 /* The next group of variables are used to track whether or not the
243 ** transaction counter in bytes 24-27 of database files are updated
244 ** whenever any part of the database changes. An assertion fault will
245 ** occur if a file is updated without also updating the transaction
246 ** counter. This test is made to avoid new problems similar to the
247 ** one described by ticket #3584.
248 */
249 unsigned char transCntrChng; /* True if the transaction counter changed */
250 unsigned char dbUpdate; /* True if any part of database file changed */
251 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000252
drh8f941bc2009-01-14 23:03:40 +0000253#endif
danf23da962013-03-23 21:00:41 +0000254
danielk1977967a4a12007-08-20 14:23:44 +0000255#ifdef SQLITE_TEST
256 /* In test mode, increase the size of this structure a bit so that
257 ** it is larger than the struct CrashFile defined in test6.c.
258 */
259 char aPadding[32];
260#endif
drh9cbe6352005-11-29 03:13:21 +0000261};
262
drh0ccebe72005-06-07 22:22:50 +0000263/*
drha7e61d82011-03-12 17:02:57 +0000264** Allowed values for the unixFile.ctrlFlags bitmask:
265*/
drhf0b190d2011-07-26 16:03:07 +0000266#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
267#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
268#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000269#ifndef SQLITE_DISABLE_DIRSYNC
270# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
271#else
272# define UNIXFILE_DIRSYNC 0x00
273#endif
drhcb15f352011-12-23 01:04:17 +0000274#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000275#define UNIXFILE_DELETE 0x20 /* Delete on close */
276#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
277#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhfbc7e882013-04-11 01:16:15 +0000278#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
drha7e61d82011-03-12 17:02:57 +0000279
280/*
drh198bf392006-01-06 21:52:49 +0000281** Include code that is common to all os_*.c files
282*/
283#include "os_common.h"
284
285/*
drh0ccebe72005-06-07 22:22:50 +0000286** Define various macros that are missing from some systems.
287*/
drhbbd42a62004-05-22 17:41:58 +0000288#ifndef O_LARGEFILE
289# define O_LARGEFILE 0
290#endif
291#ifdef SQLITE_DISABLE_LFS
292# undef O_LARGEFILE
293# define O_LARGEFILE 0
294#endif
295#ifndef O_NOFOLLOW
296# define O_NOFOLLOW 0
297#endif
298#ifndef O_BINARY
299# define O_BINARY 0
300#endif
301
302/*
drh2b4b5962005-06-15 17:47:55 +0000303** The threadid macro resolves to the thread-id or to 0. Used for
304** testing and debugging only.
305*/
drhd677b3d2007-08-20 22:48:41 +0000306#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000307#define threadid pthread_self()
308#else
309#define threadid 0
310#endif
311
drh99ab3b12011-03-02 15:09:07 +0000312/*
dane6ecd662013-04-01 17:56:59 +0000313** HAVE_MREMAP defaults to true on Linux and false everywhere else.
314*/
315#if !defined(HAVE_MREMAP)
316# if defined(__linux__) && defined(_GNU_SOURCE)
317# define HAVE_MREMAP 1
318# else
319# define HAVE_MREMAP 0
320# endif
321#endif
322
323/*
drh9a3baf12011-04-25 18:01:27 +0000324** Different Unix systems declare open() in different ways. Same use
325** open(const char*,int,mode_t). Others use open(const char*,int,...).
326** The difference is important when using a pointer to the function.
327**
328** The safest way to deal with the problem is to always use this wrapper
329** which always has the same well-defined interface.
330*/
331static int posixOpen(const char *zFile, int flags, int mode){
332 return open(zFile, flags, mode);
333}
334
drhed466822012-05-31 13:10:49 +0000335/*
336** On some systems, calls to fchown() will trigger a message in a security
337** log if they come from non-root processes. So avoid calling fchown() if
338** we are not running as root.
339*/
340static int posixFchown(int fd, uid_t uid, gid_t gid){
341 return geteuid() ? 0 : fchown(fd,uid,gid);
342}
343
drh90315a22011-08-10 01:52:12 +0000344/* Forward reference */
345static int openDirectory(const char*, int*);
346
drh9a3baf12011-04-25 18:01:27 +0000347/*
drh99ab3b12011-03-02 15:09:07 +0000348** Many system calls are accessed through pointer-to-functions so that
349** they may be overridden at runtime to facilitate fault injection during
350** testing and sandboxing. The following array holds the names and pointers
351** to all overrideable system calls.
352*/
353static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000354 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000355 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
356 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000357} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000358 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
359#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000360
drh58ad5802011-03-23 22:02:23 +0000361 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000362#define osClose ((int(*)(int))aSyscall[1].pCurrent)
363
drh58ad5802011-03-23 22:02:23 +0000364 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000365#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
366
drh58ad5802011-03-23 22:02:23 +0000367 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
369
drh58ad5802011-03-23 22:02:23 +0000370 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
372
373/*
374** The DJGPP compiler environment looks mostly like Unix, but it
375** lacks the fcntl() system call. So redefine fcntl() to be something
376** that always succeeds. This means that locking does not occur under
377** DJGPP. But it is DOS - what did you expect?
378*/
379#ifdef __DJGPP__
380 { "fstat", 0, 0 },
381#define osFstat(a,b,c) 0
382#else
drh58ad5802011-03-23 22:02:23 +0000383 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000384#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
385#endif
386
drh58ad5802011-03-23 22:02:23 +0000387 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000388#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
389
drh58ad5802011-03-23 22:02:23 +0000390 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000391#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000392
drh58ad5802011-03-23 22:02:23 +0000393 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000394#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
395
drhd4a80312011-04-15 14:33:20 +0000396#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000397 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000398#else
drh58ad5802011-03-23 22:02:23 +0000399 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000400#endif
401#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
402
403#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000404 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000405#else
drh58ad5802011-03-23 22:02:23 +0000406 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000407#endif
408#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
409
drh58ad5802011-03-23 22:02:23 +0000410 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000411#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
412
drhd4a80312011-04-15 14:33:20 +0000413#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000414 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000415#else
drh58ad5802011-03-23 22:02:23 +0000416 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000417#endif
418#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
419 aSyscall[12].pCurrent)
420
421#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000422 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000423#else
drh58ad5802011-03-23 22:02:23 +0000424 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000425#endif
426#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
427 aSyscall[13].pCurrent)
428
drh58ad5802011-03-23 22:02:23 +0000429 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000430#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000431
432#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000433 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000434#else
drh58ad5802011-03-23 22:02:23 +0000435 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000436#endif
dan0fd7d862011-03-29 10:04:23 +0000437#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000438
drh036ac7f2011-08-08 23:18:05 +0000439 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
440#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
441
drh90315a22011-08-10 01:52:12 +0000442 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
443#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
444
drh9ef6bc42011-11-04 02:24:02 +0000445 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
446#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
447
448 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
449#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
450
drhed466822012-05-31 13:10:49 +0000451 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000452#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000453
dan4dd51442013-08-26 14:30:25 +0000454#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000455 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
456#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
457
drhd1ab8062013-03-25 20:50:25 +0000458 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
459#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
460
dane6ecd662013-04-01 17:56:59 +0000461#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000462 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
463#else
464 { "mremap", (sqlite3_syscall_ptr)0, 0 },
465#endif
466#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
dan4dd51442013-08-26 14:30:25 +0000467#endif
drhd1ab8062013-03-25 20:50:25 +0000468
drhe562be52011-03-02 18:01:10 +0000469}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000470
471/*
472** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000473** "unix" VFSes. Return SQLITE_OK opon successfully updating the
474** system call pointer, or SQLITE_NOTFOUND if there is no configurable
475** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000476*/
477static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000478 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
479 const char *zName, /* Name of system call to override */
480 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000481){
drh58ad5802011-03-23 22:02:23 +0000482 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000483 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000484
485 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000486 if( zName==0 ){
487 /* If no zName is given, restore all system calls to their default
488 ** settings and return NULL
489 */
dan51438a72011-04-02 17:00:47 +0000490 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000491 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
492 if( aSyscall[i].pDefault ){
493 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000494 }
495 }
496 }else{
497 /* If zName is specified, operate on only the one system call
498 ** specified.
499 */
500 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
501 if( strcmp(zName, aSyscall[i].zName)==0 ){
502 if( aSyscall[i].pDefault==0 ){
503 aSyscall[i].pDefault = aSyscall[i].pCurrent;
504 }
drh1df30962011-03-02 19:06:42 +0000505 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000506 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
507 aSyscall[i].pCurrent = pNewFunc;
508 break;
509 }
510 }
511 }
512 return rc;
513}
514
drh1df30962011-03-02 19:06:42 +0000515/*
516** Return the value of a system call. Return NULL if zName is not a
517** recognized system call name. NULL is also returned if the system call
518** is currently undefined.
519*/
drh58ad5802011-03-23 22:02:23 +0000520static sqlite3_syscall_ptr unixGetSystemCall(
521 sqlite3_vfs *pNotUsed,
522 const char *zName
523){
524 unsigned int i;
525
526 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000527 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
528 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
529 }
530 return 0;
531}
532
533/*
534** Return the name of the first system call after zName. If zName==NULL
535** then return the name of the first system call. Return NULL if zName
536** is the last system call or if zName is not the name of a valid
537** system call.
538*/
539static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000540 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000541
542 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000543 if( zName ){
544 for(i=0; i<ArraySize(aSyscall)-1; i++){
545 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000546 }
547 }
dan0fd7d862011-03-29 10:04:23 +0000548 for(i++; i<ArraySize(aSyscall); i++){
549 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000550 }
551 return 0;
552}
553
drhad4f1e52011-03-04 15:43:57 +0000554/*
drh8c815d12012-02-13 20:16:37 +0000555** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000556** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000557**
558** If the file creation mode "m" is 0 then set it to the default for
559** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
560** 0644) as modified by the system umask. If m is not 0, then
561** make the file creation mode be exactly m ignoring the umask.
562**
563** The m parameter will be non-zero only when creating -wal, -journal,
564** and -shm files. We want those files to have *exactly* the same
565** permissions as their original database, unadulterated by the umask.
566** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
567** transaction crashes and leaves behind hot journals, then any
568** process that is able to write to the database will also be able to
569** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000570*/
drh8c815d12012-02-13 20:16:37 +0000571static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000572 int fd;
drhe1186ab2013-01-04 20:45:13 +0000573 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000574 while(1){
drh5adc60b2012-04-14 13:25:11 +0000575#if defined(O_CLOEXEC)
576 fd = osOpen(z,f|O_CLOEXEC,m2);
577#else
578 fd = osOpen(z,f,m2);
579#endif
drh5128d002013-08-30 06:20:23 +0000580 if( fd<0 ){
581 if( errno==EINTR ) continue;
582 break;
583 }
584 if( fd>2 ) break;
585 osClose(fd);
586 sqlite3_log(SQLITE_WARNING,
587 "attempt to open \"%s\" as file descriptor %d", z, fd);
588 fd = -1;
589 if( osOpen("/dev/null", f, m)<0 ) break;
590 }
drhe1186ab2013-01-04 20:45:13 +0000591 if( fd>=0 ){
592 if( m!=0 ){
593 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000594 if( osFstat(fd, &statbuf)==0
595 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000596 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000597 ){
drhe1186ab2013-01-04 20:45:13 +0000598 osFchmod(fd, m);
599 }
600 }
drh5adc60b2012-04-14 13:25:11 +0000601#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000602 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000603#endif
drhe1186ab2013-01-04 20:45:13 +0000604 }
drh5adc60b2012-04-14 13:25:11 +0000605 return fd;
drhad4f1e52011-03-04 15:43:57 +0000606}
danielk197713adf8a2004-06-03 16:08:41 +0000607
drh107886a2008-11-21 22:21:50 +0000608/*
dan9359c7b2009-08-21 08:29:10 +0000609** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000610** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000611** vxworksFileId objects used by this file, all of which may be
612** shared by multiple threads.
613**
614** Function unixMutexHeld() is used to assert() that the global mutex
615** is held when required. This function is only used as part of assert()
616** statements. e.g.
617**
618** unixEnterMutex()
619** assert( unixMutexHeld() );
620** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000621*/
622static void unixEnterMutex(void){
623 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
624}
625static void unixLeaveMutex(void){
626 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
627}
dan9359c7b2009-08-21 08:29:10 +0000628#ifdef SQLITE_DEBUG
629static int unixMutexHeld(void) {
630 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
631}
632#endif
drh107886a2008-11-21 22:21:50 +0000633
drh734c9862008-11-28 15:37:20 +0000634
drh30ddce62011-10-15 00:16:30 +0000635#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000636/*
637** Helper function for printing out trace information from debugging
638** binaries. This returns the string represetation of the supplied
639** integer lock-type.
640*/
drh308c2a52010-05-14 11:30:18 +0000641static const char *azFileLock(int eFileLock){
642 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000643 case NO_LOCK: return "NONE";
644 case SHARED_LOCK: return "SHARED";
645 case RESERVED_LOCK: return "RESERVED";
646 case PENDING_LOCK: return "PENDING";
647 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000648 }
649 return "ERROR";
650}
651#endif
652
653#ifdef SQLITE_LOCK_TRACE
654/*
655** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000656**
drh734c9862008-11-28 15:37:20 +0000657** This routine is used for troubleshooting locks on multithreaded
658** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
659** command-line option on the compiler. This code is normally
660** turned off.
661*/
662static int lockTrace(int fd, int op, struct flock *p){
663 char *zOpName, *zType;
664 int s;
665 int savedErrno;
666 if( op==F_GETLK ){
667 zOpName = "GETLK";
668 }else if( op==F_SETLK ){
669 zOpName = "SETLK";
670 }else{
drh99ab3b12011-03-02 15:09:07 +0000671 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000672 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
673 return s;
674 }
675 if( p->l_type==F_RDLCK ){
676 zType = "RDLCK";
677 }else if( p->l_type==F_WRLCK ){
678 zType = "WRLCK";
679 }else if( p->l_type==F_UNLCK ){
680 zType = "UNLCK";
681 }else{
682 assert( 0 );
683 }
684 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000685 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000686 savedErrno = errno;
687 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
688 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
689 (int)p->l_pid, s);
690 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
691 struct flock l2;
692 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000693 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000694 if( l2.l_type==F_RDLCK ){
695 zType = "RDLCK";
696 }else if( l2.l_type==F_WRLCK ){
697 zType = "WRLCK";
698 }else if( l2.l_type==F_UNLCK ){
699 zType = "UNLCK";
700 }else{
701 assert( 0 );
702 }
703 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
704 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
705 }
706 errno = savedErrno;
707 return s;
708}
drh99ab3b12011-03-02 15:09:07 +0000709#undef osFcntl
710#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000711#endif /* SQLITE_LOCK_TRACE */
712
drhff812312011-02-23 13:33:46 +0000713/*
714** Retry ftruncate() calls that fail due to EINTR
715*/
drhff812312011-02-23 13:33:46 +0000716static int robust_ftruncate(int h, sqlite3_int64 sz){
717 int rc;
drh99ab3b12011-03-02 15:09:07 +0000718 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000719 return rc;
720}
drh734c9862008-11-28 15:37:20 +0000721
722/*
723** This routine translates a standard POSIX errno code into something
724** useful to the clients of the sqlite3 functions. Specifically, it is
725** intended to translate a variety of "try again" errors into SQLITE_BUSY
726** and a variety of "please close the file descriptor NOW" errors into
727** SQLITE_IOERR
728**
729** Errors during initialization of locks, or file system support for locks,
730** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
731*/
732static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
733 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000734#if 0
735 /* At one point this code was not commented out. In theory, this branch
736 ** should never be hit, as this function should only be called after
737 ** a locking-related function (i.e. fcntl()) has returned non-zero with
738 ** the value of errno as the first argument. Since a system call has failed,
739 ** errno should be non-zero.
740 **
741 ** Despite this, if errno really is zero, we still don't want to return
742 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
743 ** propagated back to the caller. Commenting this branch out means errno==0
744 ** will be handled by the "default:" case below.
745 */
drh734c9862008-11-28 15:37:20 +0000746 case 0:
747 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000748#endif
749
drh734c9862008-11-28 15:37:20 +0000750 case EAGAIN:
751 case ETIMEDOUT:
752 case EBUSY:
753 case EINTR:
754 case ENOLCK:
755 /* random NFS retry error, unless during file system support
756 * introspection, in which it actually means what it says */
757 return SQLITE_BUSY;
758
759 case EACCES:
760 /* EACCES is like EAGAIN during locking operations, but not any other time*/
761 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000762 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
763 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
764 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000765 return SQLITE_BUSY;
766 }
767 /* else fall through */
768 case EPERM:
769 return SQLITE_PERM;
770
danea83bc62011-04-01 11:56:32 +0000771 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
772 ** this module never makes such a call. And the code in SQLite itself
773 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
774 ** this case is also commented out. If the system does set errno to EDEADLK,
775 ** the default SQLITE_IOERR_XXX code will be returned. */
776#if 0
drh734c9862008-11-28 15:37:20 +0000777 case EDEADLK:
778 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000779#endif
drh734c9862008-11-28 15:37:20 +0000780
781#if EOPNOTSUPP!=ENOTSUP
782 case EOPNOTSUPP:
783 /* something went terribly awry, unless during file system support
784 * introspection, in which it actually means what it says */
785#endif
786#ifdef ENOTSUP
787 case ENOTSUP:
788 /* invalid fd, unless during file system support introspection, in which
789 * it actually means what it says */
790#endif
791 case EIO:
792 case EBADF:
793 case EINVAL:
794 case ENOTCONN:
795 case ENODEV:
796 case ENXIO:
797 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000798#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000799 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000800#endif
drh734c9862008-11-28 15:37:20 +0000801 case ENOSYS:
802 /* these should force the client to close the file and reconnect */
803
804 default:
805 return sqliteIOErr;
806 }
807}
808
809
drh734c9862008-11-28 15:37:20 +0000810/******************************************************************************
811****************** Begin Unique File ID Utility Used By VxWorks ***************
812**
813** On most versions of unix, we can get a unique ID for a file by concatenating
814** the device number and the inode number. But this does not work on VxWorks.
815** On VxWorks, a unique file id must be based on the canonical filename.
816**
817** A pointer to an instance of the following structure can be used as a
818** unique file ID in VxWorks. Each instance of this structure contains
819** a copy of the canonical filename. There is also a reference count.
820** The structure is reclaimed when the number of pointers to it drops to
821** zero.
822**
823** There are never very many files open at one time and lookups are not
824** a performance-critical path, so it is sufficient to put these
825** structures on a linked list.
826*/
827struct vxworksFileId {
828 struct vxworksFileId *pNext; /* Next in a list of them all */
829 int nRef; /* Number of references to this one */
830 int nName; /* Length of the zCanonicalName[] string */
831 char *zCanonicalName; /* Canonical filename */
832};
833
834#if OS_VXWORKS
835/*
drh9b35ea62008-11-29 02:20:26 +0000836** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000837** variable:
838*/
839static struct vxworksFileId *vxworksFileList = 0;
840
841/*
842** Simplify a filename into its canonical form
843** by making the following changes:
844**
845** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000846** * convert /./ into just /
847** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000848**
849** Changes are made in-place. Return the new name length.
850**
851** The original filename is in z[0..n-1]. Return the number of
852** characters in the simplified name.
853*/
854static int vxworksSimplifyName(char *z, int n){
855 int i, j;
856 while( n>1 && z[n-1]=='/' ){ n--; }
857 for(i=j=0; i<n; i++){
858 if( z[i]=='/' ){
859 if( z[i+1]=='/' ) continue;
860 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
861 i += 1;
862 continue;
863 }
864 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
865 while( j>0 && z[j-1]!='/' ){ j--; }
866 if( j>0 ){ j--; }
867 i += 2;
868 continue;
869 }
870 }
871 z[j++] = z[i];
872 }
873 z[j] = 0;
874 return j;
875}
876
877/*
878** Find a unique file ID for the given absolute pathname. Return
879** a pointer to the vxworksFileId object. This pointer is the unique
880** file ID.
881**
882** The nRef field of the vxworksFileId object is incremented before
883** the object is returned. A new vxworksFileId object is created
884** and added to the global list if necessary.
885**
886** If a memory allocation error occurs, return NULL.
887*/
888static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
889 struct vxworksFileId *pNew; /* search key and new file ID */
890 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
891 int n; /* Length of zAbsoluteName string */
892
893 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000894 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000895 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
896 if( pNew==0 ) return 0;
897 pNew->zCanonicalName = (char*)&pNew[1];
898 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
899 n = vxworksSimplifyName(pNew->zCanonicalName, n);
900
901 /* Search for an existing entry that matching the canonical name.
902 ** If found, increment the reference count and return a pointer to
903 ** the existing file ID.
904 */
905 unixEnterMutex();
906 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
907 if( pCandidate->nName==n
908 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
909 ){
910 sqlite3_free(pNew);
911 pCandidate->nRef++;
912 unixLeaveMutex();
913 return pCandidate;
914 }
915 }
916
917 /* No match was found. We will make a new file ID */
918 pNew->nRef = 1;
919 pNew->nName = n;
920 pNew->pNext = vxworksFileList;
921 vxworksFileList = pNew;
922 unixLeaveMutex();
923 return pNew;
924}
925
926/*
927** Decrement the reference count on a vxworksFileId object. Free
928** the object when the reference count reaches zero.
929*/
930static void vxworksReleaseFileId(struct vxworksFileId *pId){
931 unixEnterMutex();
932 assert( pId->nRef>0 );
933 pId->nRef--;
934 if( pId->nRef==0 ){
935 struct vxworksFileId **pp;
936 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
937 assert( *pp==pId );
938 *pp = pId->pNext;
939 sqlite3_free(pId);
940 }
941 unixLeaveMutex();
942}
943#endif /* OS_VXWORKS */
944/*************** End of Unique File ID Utility Used By VxWorks ****************
945******************************************************************************/
946
947
948/******************************************************************************
949*************************** Posix Advisory Locking ****************************
950**
drh9b35ea62008-11-29 02:20:26 +0000951** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000952** section 6.5.2.2 lines 483 through 490 specify that when a process
953** sets or clears a lock, that operation overrides any prior locks set
954** by the same process. It does not explicitly say so, but this implies
955** that it overrides locks set by the same process using a different
956** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000957**
958** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000959** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
960**
961** Suppose ./file1 and ./file2 are really the same file (because
962** one is a hard or symbolic link to the other) then if you set
963** an exclusive lock on fd1, then try to get an exclusive lock
964** on fd2, it works. I would have expected the second lock to
965** fail since there was already a lock on the file due to fd1.
966** But not so. Since both locks came from the same process, the
967** second overrides the first, even though they were on different
968** file descriptors opened on different file names.
969**
drh734c9862008-11-28 15:37:20 +0000970** This means that we cannot use POSIX locks to synchronize file access
971** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000972** to synchronize access for threads in separate processes, but not
973** threads within the same process.
974**
975** To work around the problem, SQLite has to manage file locks internally
976** on its own. Whenever a new database is opened, we have to find the
977** specific inode of the database file (the inode is determined by the
978** st_dev and st_ino fields of the stat structure that fstat() fills in)
979** and check for locks already existing on that inode. When locks are
980** created or removed, we have to look at our own internal record of the
981** locks to see if another thread has previously set a lock on that same
982** inode.
983**
drh9b35ea62008-11-29 02:20:26 +0000984** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
985** For VxWorks, we have to use the alternative unique ID system based on
986** canonical filename and implemented in the previous division.)
987**
danielk1977ad94b582007-08-20 06:44:22 +0000988** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000989** descriptor. It is now a structure that holds the integer file
990** descriptor and a pointer to a structure that describes the internal
991** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000992** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000993** point to the same locking structure. The locking structure keeps
994** a reference count (so we will know when to delete it) and a "cnt"
995** field that tells us its internal lock status. cnt==0 means the
996** file is unlocked. cnt==-1 means the file has an exclusive lock.
997** cnt>0 means there are cnt shared locks on the file.
998**
999** Any attempt to lock or unlock a file first checks the locking
1000** structure. The fcntl() system call is only invoked to set a
1001** POSIX lock if the internal lock structure transitions between
1002** a locked and an unlocked state.
1003**
drh734c9862008-11-28 15:37:20 +00001004** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001005**
1006** If you close a file descriptor that points to a file that has locks,
1007** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001008** released. To work around this problem, each unixInodeInfo object
1009** maintains a count of the number of pending locks on tha inode.
1010** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001011** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001012** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001013** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001014** be closed and that list is walked (and cleared) when the last lock
1015** clears.
1016**
drh9b35ea62008-11-29 02:20:26 +00001017** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001018**
drh9b35ea62008-11-29 02:20:26 +00001019** Many older versions of linux use the LinuxThreads library which is
1020** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001021** A cannot be modified or overridden by a different thread B.
1022** Only thread A can modify the lock. Locking behavior is correct
1023** if the appliation uses the newer Native Posix Thread Library (NPTL)
1024** on linux - with NPTL a lock created by thread A can override locks
1025** in thread B. But there is no way to know at compile-time which
1026** threading library is being used. So there is no way to know at
1027** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001028** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001029** current process.
drh5fdae772004-06-29 03:29:00 +00001030**
drh8af6c222010-05-14 12:43:01 +00001031** SQLite used to support LinuxThreads. But support for LinuxThreads
1032** was dropped beginning with version 3.7.0. SQLite will still work with
1033** LinuxThreads provided that (1) there is no more than one connection
1034** per database file in the same process and (2) database connections
1035** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001036*/
1037
1038/*
1039** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001040** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001041*/
1042struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001043 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001044#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001045 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001046#else
drh107886a2008-11-21 22:21:50 +00001047 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001048#endif
1049};
1050
1051/*
drhbbd42a62004-05-22 17:41:58 +00001052** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001053** inode. Or, on LinuxThreads, there is one of these structures for
1054** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001055**
danielk1977ad94b582007-08-20 06:44:22 +00001056** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001057** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001058** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001059*/
drh8af6c222010-05-14 12:43:01 +00001060struct unixInodeInfo {
1061 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001062 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001063 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1064 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001065 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001066 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1067 int nLock; /* Number of outstanding file locks */
1068 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1069 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1070 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001071#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001072 unsigned long long sharedByte; /* for AFP simulated shared lock */
1073#endif
drh6c7d5c52008-11-21 20:32:33 +00001074#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001075 sem_t *pSem; /* Named POSIX semaphore */
1076 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001077#endif
drhbbd42a62004-05-22 17:41:58 +00001078};
1079
drhda0e7682008-07-30 15:27:54 +00001080/*
drh8af6c222010-05-14 12:43:01 +00001081** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001082*/
drhd91c68f2010-05-14 14:52:25 +00001083static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001084
drh5fdae772004-06-29 03:29:00 +00001085/*
dane18d4952011-02-21 11:46:24 +00001086**
1087** This function - unixLogError_x(), is only ever called via the macro
1088** unixLogError().
1089**
1090** It is invoked after an error occurs in an OS function and errno has been
1091** set. It logs a message using sqlite3_log() containing the current value of
1092** errno and, if possible, the human-readable equivalent from strerror() or
1093** strerror_r().
1094**
1095** The first argument passed to the macro should be the error code that
1096** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1097** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001098** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001099** if any.
1100*/
drh0e9365c2011-03-02 02:08:13 +00001101#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1102static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001103 int errcode, /* SQLite error code */
1104 const char *zFunc, /* Name of OS function that failed */
1105 const char *zPath, /* File path associated with error */
1106 int iLine /* Source line number where error occurred */
1107){
1108 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001109 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001110
1111 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1112 ** the strerror() function to obtain the human-readable error message
1113 ** equivalent to errno. Otherwise, use strerror_r().
1114 */
1115#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1116 char aErr[80];
1117 memset(aErr, 0, sizeof(aErr));
1118 zErr = aErr;
1119
1120 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001121 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001122 ** returns a pointer to a buffer containing the error message. That pointer
1123 ** may point to aErr[], or it may point to some static storage somewhere.
1124 ** Otherwise, assume that the system provides the POSIX version of
1125 ** strerror_r(), which always writes an error message into aErr[].
1126 **
1127 ** If the code incorrectly assumes that it is the POSIX version that is
1128 ** available, the error message will often be an empty string. Not a
1129 ** huge problem. Incorrectly concluding that the GNU version is available
1130 ** could lead to a segfault though.
1131 */
1132#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1133 zErr =
1134# endif
drh0e9365c2011-03-02 02:08:13 +00001135 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001136
1137#elif SQLITE_THREADSAFE
1138 /* This is a threadsafe build, but strerror_r() is not available. */
1139 zErr = "";
1140#else
1141 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001142 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001143#endif
1144
drh0e9365c2011-03-02 02:08:13 +00001145 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001146 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001147 "os_unix.c:%d: (%d) %s(%s) - %s",
1148 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001149 );
1150
1151 return errcode;
1152}
1153
drh0e9365c2011-03-02 02:08:13 +00001154/*
1155** Close a file descriptor.
1156**
1157** We assume that close() almost always works, since it is only in a
1158** very sick application or on a very sick platform that it might fail.
1159** If it does fail, simply leak the file descriptor, but do log the
1160** error.
1161**
1162** Note that it is not safe to retry close() after EINTR since the
1163** file descriptor might have already been reused by another thread.
1164** So we don't even try to recover from an EINTR. Just log the error
1165** and move on.
1166*/
1167static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001168 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001169 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1170 pFile ? pFile->zPath : 0, lineno);
1171 }
1172}
dane18d4952011-02-21 11:46:24 +00001173
1174/*
danb0ac3e32010-06-16 10:55:42 +00001175** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001176*/
drh0e9365c2011-03-02 02:08:13 +00001177static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001178 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001179 UnixUnusedFd *p;
1180 UnixUnusedFd *pNext;
1181 for(p=pInode->pUnused; p; p=pNext){
1182 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001183 robust_close(pFile, p->fd, __LINE__);
1184 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001185 }
drh0e9365c2011-03-02 02:08:13 +00001186 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001187}
1188
1189/*
drh8af6c222010-05-14 12:43:01 +00001190** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001191**
1192** The mutex entered using the unixEnterMutex() function must be held
1193** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001194*/
danb0ac3e32010-06-16 10:55:42 +00001195static void releaseInodeInfo(unixFile *pFile){
1196 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001197 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001198 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001199 pInode->nRef--;
1200 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001201 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001202 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001203 if( pInode->pPrev ){
1204 assert( pInode->pPrev->pNext==pInode );
1205 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001206 }else{
drh8af6c222010-05-14 12:43:01 +00001207 assert( inodeList==pInode );
1208 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001209 }
drh8af6c222010-05-14 12:43:01 +00001210 if( pInode->pNext ){
1211 assert( pInode->pNext->pPrev==pInode );
1212 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001213 }
drh8af6c222010-05-14 12:43:01 +00001214 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001215 }
drhbbd42a62004-05-22 17:41:58 +00001216 }
1217}
1218
1219/*
drh8af6c222010-05-14 12:43:01 +00001220** Given a file descriptor, locate the unixInodeInfo object that
1221** describes that file descriptor. Create a new one if necessary. The
1222** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001223**
dan9359c7b2009-08-21 08:29:10 +00001224** The mutex entered using the unixEnterMutex() function must be held
1225** when this function is called.
1226**
drh6c7d5c52008-11-21 20:32:33 +00001227** Return an appropriate error code.
1228*/
drh8af6c222010-05-14 12:43:01 +00001229static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001230 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001231 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001232){
1233 int rc; /* System call return code */
1234 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001235 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1236 struct stat statbuf; /* Low-level file information */
1237 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001238
dan9359c7b2009-08-21 08:29:10 +00001239 assert( unixMutexHeld() );
1240
drh6c7d5c52008-11-21 20:32:33 +00001241 /* Get low-level information about the file that we can used to
1242 ** create a unique name for the file.
1243 */
1244 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001245 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001246 if( rc!=0 ){
1247 pFile->lastErrno = errno;
1248#ifdef EOVERFLOW
1249 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1250#endif
1251 return SQLITE_IOERR;
1252 }
1253
drheb0d74f2009-02-03 15:27:02 +00001254#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001255 /* On OS X on an msdos filesystem, the inode number is reported
1256 ** incorrectly for zero-size files. See ticket #3260. To work
1257 ** around this problem (we consider it a bug in OS X, not SQLite)
1258 ** we always increase the file size to 1 by writing a single byte
1259 ** prior to accessing the inode number. The one byte written is
1260 ** an ASCII 'S' character which also happens to be the first byte
1261 ** in the header of every SQLite database. In this way, if there
1262 ** is a race condition such that another thread has already populated
1263 ** the first page of the database, no damage is done.
1264 */
drh7ed97b92010-01-20 13:07:21 +00001265 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001266 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001267 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001268 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001269 return SQLITE_IOERR;
1270 }
drh99ab3b12011-03-02 15:09:07 +00001271 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001272 if( rc!=0 ){
1273 pFile->lastErrno = errno;
1274 return SQLITE_IOERR;
1275 }
1276 }
drheb0d74f2009-02-03 15:27:02 +00001277#endif
drh6c7d5c52008-11-21 20:32:33 +00001278
drh8af6c222010-05-14 12:43:01 +00001279 memset(&fileId, 0, sizeof(fileId));
1280 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001281#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001282 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001283#else
drh8af6c222010-05-14 12:43:01 +00001284 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001285#endif
drh8af6c222010-05-14 12:43:01 +00001286 pInode = inodeList;
1287 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1288 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001289 }
drh8af6c222010-05-14 12:43:01 +00001290 if( pInode==0 ){
1291 pInode = sqlite3_malloc( sizeof(*pInode) );
1292 if( pInode==0 ){
1293 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001294 }
drh8af6c222010-05-14 12:43:01 +00001295 memset(pInode, 0, sizeof(*pInode));
1296 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1297 pInode->nRef = 1;
1298 pInode->pNext = inodeList;
1299 pInode->pPrev = 0;
1300 if( inodeList ) inodeList->pPrev = pInode;
1301 inodeList = pInode;
1302 }else{
1303 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001304 }
drh8af6c222010-05-14 12:43:01 +00001305 *ppInode = pInode;
1306 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001307}
drh6c7d5c52008-11-21 20:32:33 +00001308
aswift5b1a2562008-08-22 00:22:35 +00001309
1310/*
drhfbc7e882013-04-11 01:16:15 +00001311** Check a unixFile that is a database. Verify the following:
1312**
1313** (1) There is exactly one hard link on the file
1314** (2) The file is not a symbolic link
1315** (3) The file has not been renamed or unlinked
1316**
1317** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1318*/
1319static void verifyDbFile(unixFile *pFile){
1320 struct stat buf;
1321 int rc;
1322 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1323 /* One or more of the following warnings have already been issued. Do not
1324 ** repeat them so as not to clutter the error log */
1325 return;
1326 }
1327 rc = osFstat(pFile->h, &buf);
1328 if( rc!=0 ){
1329 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1330 pFile->ctrlFlags |= UNIXFILE_WARNED;
1331 return;
1332 }
1333 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
1334 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1335 pFile->ctrlFlags |= UNIXFILE_WARNED;
1336 return;
1337 }
1338 if( buf.st_nlink>1 ){
1339 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1340 pFile->ctrlFlags |= UNIXFILE_WARNED;
1341 return;
1342 }
1343 if( pFile->pInode!=0
1344 && ((rc = osStat(pFile->zPath, &buf))!=0
1345 || buf.st_ino!=pFile->pInode->fileId.ino)
1346 ){
1347 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1348 pFile->ctrlFlags |= UNIXFILE_WARNED;
1349 return;
1350 }
1351}
1352
1353
1354/*
danielk197713adf8a2004-06-03 16:08:41 +00001355** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001356** file by this or any other process. If such a lock is held, set *pResOut
1357** to a non-zero value otherwise *pResOut is set to zero. The return value
1358** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001359*/
danielk1977861f7452008-06-05 11:39:11 +00001360static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001361 int rc = SQLITE_OK;
1362 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001363 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001364
danielk1977861f7452008-06-05 11:39:11 +00001365 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1366
drh054889e2005-11-30 03:20:31 +00001367 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001368 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001369
1370 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001371 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001372 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001373 }
1374
drh2ac3ee92004-06-07 16:27:46 +00001375 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001376 */
danielk197709480a92009-02-09 05:32:32 +00001377#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001378 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001379 struct flock lock;
1380 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001381 lock.l_start = RESERVED_BYTE;
1382 lock.l_len = 1;
1383 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001384 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1385 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1386 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001387 } else if( lock.l_type!=F_UNLCK ){
1388 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001389 }
1390 }
danielk197709480a92009-02-09 05:32:32 +00001391#endif
danielk197713adf8a2004-06-03 16:08:41 +00001392
drh6c7d5c52008-11-21 20:32:33 +00001393 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001394 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001395
aswift5b1a2562008-08-22 00:22:35 +00001396 *pResOut = reserved;
1397 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001398}
1399
1400/*
drha7e61d82011-03-12 17:02:57 +00001401** Attempt to set a system-lock on the file pFile. The lock is
1402** described by pLock.
1403**
drh77197112011-03-15 19:08:48 +00001404** If the pFile was opened read/write from unix-excl, then the only lock
1405** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001406** the first time any lock is attempted. All subsequent system locking
1407** operations become no-ops. Locking operations still happen internally,
1408** in order to coordinate access between separate database connections
1409** within this process, but all of that is handled in memory and the
1410** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001411**
1412** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1413** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1414** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001415**
1416** Zero is returned if the call completes successfully, or -1 if a call
1417** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001418*/
1419static int unixFileLock(unixFile *pFile, struct flock *pLock){
1420 int rc;
drh3cb93392011-03-12 18:10:44 +00001421 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001422 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001423 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001424 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1425 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1426 ){
drh3cb93392011-03-12 18:10:44 +00001427 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001428 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001429 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001430 lock.l_whence = SEEK_SET;
1431 lock.l_start = SHARED_FIRST;
1432 lock.l_len = SHARED_SIZE;
1433 lock.l_type = F_WRLCK;
1434 rc = osFcntl(pFile->h, F_SETLK, &lock);
1435 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001436 pInode->bProcessLock = 1;
1437 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001438 }else{
1439 rc = 0;
1440 }
1441 }else{
1442 rc = osFcntl(pFile->h, F_SETLK, pLock);
1443 }
1444 return rc;
1445}
1446
1447/*
drh308c2a52010-05-14 11:30:18 +00001448** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001449** of the following:
1450**
drh2ac3ee92004-06-07 16:27:46 +00001451** (1) SHARED_LOCK
1452** (2) RESERVED_LOCK
1453** (3) PENDING_LOCK
1454** (4) EXCLUSIVE_LOCK
1455**
drhb3e04342004-06-08 00:47:47 +00001456** Sometimes when requesting one lock state, additional lock states
1457** are inserted in between. The locking might fail on one of the later
1458** transitions leaving the lock state different from what it started but
1459** still short of its goal. The following chart shows the allowed
1460** transitions and the inserted intermediate states:
1461**
1462** UNLOCKED -> SHARED
1463** SHARED -> RESERVED
1464** SHARED -> (PENDING) -> EXCLUSIVE
1465** RESERVED -> (PENDING) -> EXCLUSIVE
1466** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001467**
drha6abd042004-06-09 17:37:22 +00001468** This routine will only increase a lock. Use the sqlite3OsUnlock()
1469** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001470*/
drh308c2a52010-05-14 11:30:18 +00001471static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001472 /* The following describes the implementation of the various locks and
1473 ** lock transitions in terms of the POSIX advisory shared and exclusive
1474 ** lock primitives (called read-locks and write-locks below, to avoid
1475 ** confusion with SQLite lock names). The algorithms are complicated
1476 ** slightly in order to be compatible with windows systems simultaneously
1477 ** accessing the same database file, in case that is ever required.
1478 **
1479 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1480 ** byte', each single bytes at well known offsets, and the 'shared byte
1481 ** range', a range of 510 bytes at a well known offset.
1482 **
1483 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1484 ** byte'. If this is successful, a random byte from the 'shared byte
1485 ** range' is read-locked and the lock on the 'pending byte' released.
1486 **
danielk197790ba3bd2004-06-25 08:32:25 +00001487 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1488 ** A RESERVED lock is implemented by grabbing a write-lock on the
1489 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001490 **
1491 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001492 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1493 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1494 ** obtained, but existing SHARED locks are allowed to persist. A process
1495 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1496 ** This property is used by the algorithm for rolling back a journal file
1497 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001498 **
danielk197790ba3bd2004-06-25 08:32:25 +00001499 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1500 ** implemented by obtaining a write-lock on the entire 'shared byte
1501 ** range'. Since all other locks require a read-lock on one of the bytes
1502 ** within this range, this ensures that no other locks are held on the
1503 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001504 **
1505 ** The reason a single byte cannot be used instead of the 'shared byte
1506 ** range' is that some versions of windows do not support read-locks. By
1507 ** locking a random byte from a range, concurrent SHARED locks may exist
1508 ** even if the locking primitive used is always a write-lock.
1509 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001510 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001511 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001512 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001513 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001514 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001515
drh054889e2005-11-30 03:20:31 +00001516 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001517 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1518 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001519 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001520
1521 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001522 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001523 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001524 */
drh308c2a52010-05-14 11:30:18 +00001525 if( pFile->eFileLock>=eFileLock ){
1526 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1527 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001528 return SQLITE_OK;
1529 }
1530
drh0c2694b2009-09-03 16:23:44 +00001531 /* Make sure the locking sequence is correct.
1532 ** (1) We never move from unlocked to anything higher than shared lock.
1533 ** (2) SQLite never explicitly requests a pendig lock.
1534 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001535 */
drh308c2a52010-05-14 11:30:18 +00001536 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1537 assert( eFileLock!=PENDING_LOCK );
1538 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001539
drh8af6c222010-05-14 12:43:01 +00001540 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001541 */
drh6c7d5c52008-11-21 20:32:33 +00001542 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001543 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001544
danielk1977ad94b582007-08-20 06:44:22 +00001545 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001546 ** handle that precludes the requested lock, return BUSY.
1547 */
drh8af6c222010-05-14 12:43:01 +00001548 if( (pFile->eFileLock!=pInode->eFileLock &&
1549 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001550 ){
1551 rc = SQLITE_BUSY;
1552 goto end_lock;
1553 }
1554
1555 /* If a SHARED lock is requested, and some thread using this PID already
1556 ** has a SHARED or RESERVED lock, then increment reference counts and
1557 ** return SQLITE_OK.
1558 */
drh308c2a52010-05-14 11:30:18 +00001559 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001560 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001561 assert( eFileLock==SHARED_LOCK );
1562 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001563 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001564 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001565 pInode->nShared++;
1566 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001567 goto end_lock;
1568 }
1569
danielk19779a1d0ab2004-06-01 14:09:28 +00001570
drh3cde3bb2004-06-12 02:17:14 +00001571 /* A PENDING lock is needed before acquiring a SHARED lock and before
1572 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1573 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001574 */
drh0c2694b2009-09-03 16:23:44 +00001575 lock.l_len = 1L;
1576 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001577 if( eFileLock==SHARED_LOCK
1578 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001579 ){
drh308c2a52010-05-14 11:30:18 +00001580 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001581 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001582 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001583 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001584 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001585 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001586 pFile->lastErrno = tErrno;
1587 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001588 goto end_lock;
1589 }
drh3cde3bb2004-06-12 02:17:14 +00001590 }
1591
1592
1593 /* If control gets to this point, then actually go ahead and make
1594 ** operating system calls for the specified lock.
1595 */
drh308c2a52010-05-14 11:30:18 +00001596 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001597 assert( pInode->nShared==0 );
1598 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001599 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001600
drh2ac3ee92004-06-07 16:27:46 +00001601 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001602 lock.l_start = SHARED_FIRST;
1603 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001604 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001605 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001606 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001607 }
dan661d71a2011-03-30 19:08:03 +00001608
drh2ac3ee92004-06-07 16:27:46 +00001609 /* Drop the temporary PENDING lock */
1610 lock.l_start = PENDING_BYTE;
1611 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001612 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001613 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1614 /* This could happen with a network mount */
1615 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001616 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001617 }
dan661d71a2011-03-30 19:08:03 +00001618
1619 if( rc ){
1620 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001621 pFile->lastErrno = tErrno;
1622 }
dan661d71a2011-03-30 19:08:03 +00001623 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001624 }else{
drh308c2a52010-05-14 11:30:18 +00001625 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001626 pInode->nLock++;
1627 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001628 }
drh8af6c222010-05-14 12:43:01 +00001629 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001630 /* We are trying for an exclusive lock but another thread in this
1631 ** same process is still holding a shared lock. */
1632 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001633 }else{
drh3cde3bb2004-06-12 02:17:14 +00001634 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001635 ** assumed that there is a SHARED or greater lock on the file
1636 ** already.
1637 */
drh308c2a52010-05-14 11:30:18 +00001638 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001639 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001640
1641 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1642 if( eFileLock==RESERVED_LOCK ){
1643 lock.l_start = RESERVED_BYTE;
1644 lock.l_len = 1L;
1645 }else{
1646 lock.l_start = SHARED_FIRST;
1647 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001648 }
dan661d71a2011-03-30 19:08:03 +00001649
1650 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001651 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001652 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001653 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001654 pFile->lastErrno = tErrno;
1655 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001656 }
drhbbd42a62004-05-22 17:41:58 +00001657 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001658
drh8f941bc2009-01-14 23:03:40 +00001659
drhd3d8c042012-05-29 17:02:40 +00001660#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001661 /* Set up the transaction-counter change checking flags when
1662 ** transitioning from a SHARED to a RESERVED lock. The change
1663 ** from SHARED to RESERVED marks the beginning of a normal
1664 ** write operation (not a hot journal rollback).
1665 */
1666 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001667 && pFile->eFileLock<=SHARED_LOCK
1668 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001669 ){
1670 pFile->transCntrChng = 0;
1671 pFile->dbUpdate = 0;
1672 pFile->inNormalWrite = 1;
1673 }
1674#endif
1675
1676
danielk1977ecb2a962004-06-02 06:30:16 +00001677 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001678 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001679 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001680 }else if( eFileLock==EXCLUSIVE_LOCK ){
1681 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001682 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001683 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001684
1685end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001686 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001687 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1688 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001689 return rc;
1690}
1691
1692/*
dan08da86a2009-08-21 17:18:03 +00001693** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001694** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001695*/
1696static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001697 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001698 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001699 p->pNext = pInode->pUnused;
1700 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001701 pFile->h = -1;
1702 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001703}
1704
1705/*
drh308c2a52010-05-14 11:30:18 +00001706** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001707** must be either NO_LOCK or SHARED_LOCK.
1708**
1709** If the locking level of the file descriptor is already at or below
1710** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001711**
1712** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1713** the byte range is divided into 2 parts and the first part is unlocked then
1714** set to a read lock, then the other part is simply unlocked. This works
1715** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1716** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001717*/
drha7e61d82011-03-12 17:02:57 +00001718static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001719 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001720 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001721 struct flock lock;
1722 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001723
drh054889e2005-11-30 03:20:31 +00001724 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001725 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001726 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001727 getpid()));
drha6abd042004-06-09 17:37:22 +00001728
drh308c2a52010-05-14 11:30:18 +00001729 assert( eFileLock<=SHARED_LOCK );
1730 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001731 return SQLITE_OK;
1732 }
drh6c7d5c52008-11-21 20:32:33 +00001733 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001734 pInode = pFile->pInode;
1735 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001736 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001737 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001738
drhd3d8c042012-05-29 17:02:40 +00001739#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001740 /* When reducing a lock such that other processes can start
1741 ** reading the database file again, make sure that the
1742 ** transaction counter was updated if any part of the database
1743 ** file changed. If the transaction counter is not updated,
1744 ** other connections to the same file might not realize that
1745 ** the file has changed and hence might not know to flush their
1746 ** cache. The use of a stale cache can lead to database corruption.
1747 */
drh8f941bc2009-01-14 23:03:40 +00001748 pFile->inNormalWrite = 0;
1749#endif
1750
drh7ed97b92010-01-20 13:07:21 +00001751 /* downgrading to a shared lock on NFS involves clearing the write lock
1752 ** before establishing the readlock - to avoid a race condition we downgrade
1753 ** the lock in 2 blocks, so that part of the range will be covered by a
1754 ** write lock until the rest is covered by a read lock:
1755 ** 1: [WWWWW]
1756 ** 2: [....W]
1757 ** 3: [RRRRW]
1758 ** 4: [RRRR.]
1759 */
drh308c2a52010-05-14 11:30:18 +00001760 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001761
1762#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001763 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001764 assert( handleNFSUnlock==0 );
1765#endif
1766#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001767 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001768 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001769 off_t divSize = SHARED_SIZE - 1;
1770
1771 lock.l_type = F_UNLCK;
1772 lock.l_whence = SEEK_SET;
1773 lock.l_start = SHARED_FIRST;
1774 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001775 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001776 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001777 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001778 if( IS_LOCK_ERROR(rc) ){
1779 pFile->lastErrno = tErrno;
1780 }
1781 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001782 }
drh7ed97b92010-01-20 13:07:21 +00001783 lock.l_type = F_RDLCK;
1784 lock.l_whence = SEEK_SET;
1785 lock.l_start = SHARED_FIRST;
1786 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001787 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001788 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001789 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1790 if( IS_LOCK_ERROR(rc) ){
1791 pFile->lastErrno = tErrno;
1792 }
1793 goto end_unlock;
1794 }
1795 lock.l_type = F_UNLCK;
1796 lock.l_whence = SEEK_SET;
1797 lock.l_start = SHARED_FIRST+divSize;
1798 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001799 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001800 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001801 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001802 if( IS_LOCK_ERROR(rc) ){
1803 pFile->lastErrno = tErrno;
1804 }
1805 goto end_unlock;
1806 }
drh30f776f2011-02-25 03:25:07 +00001807 }else
1808#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1809 {
drh7ed97b92010-01-20 13:07:21 +00001810 lock.l_type = F_RDLCK;
1811 lock.l_whence = SEEK_SET;
1812 lock.l_start = SHARED_FIRST;
1813 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001814 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001815 /* In theory, the call to unixFileLock() cannot fail because another
1816 ** process is holding an incompatible lock. If it does, this
1817 ** indicates that the other process is not following the locking
1818 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1819 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1820 ** an assert to fail). */
1821 rc = SQLITE_IOERR_RDLOCK;
1822 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001823 goto end_unlock;
1824 }
drh9c105bb2004-10-02 20:38:28 +00001825 }
1826 }
drhbbd42a62004-05-22 17:41:58 +00001827 lock.l_type = F_UNLCK;
1828 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001829 lock.l_start = PENDING_BYTE;
1830 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001831 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001832 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001833 }else{
danea83bc62011-04-01 11:56:32 +00001834 rc = SQLITE_IOERR_UNLOCK;
1835 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001836 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001837 }
drhbbd42a62004-05-22 17:41:58 +00001838 }
drh308c2a52010-05-14 11:30:18 +00001839 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001840 /* Decrement the shared lock counter. Release the lock using an
1841 ** OS call only when all threads in this same process have released
1842 ** the lock.
1843 */
drh8af6c222010-05-14 12:43:01 +00001844 pInode->nShared--;
1845 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001846 lock.l_type = F_UNLCK;
1847 lock.l_whence = SEEK_SET;
1848 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001849 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001850 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001851 }else{
danea83bc62011-04-01 11:56:32 +00001852 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001853 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001854 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001855 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001856 }
drha6abd042004-06-09 17:37:22 +00001857 }
1858
drhbbd42a62004-05-22 17:41:58 +00001859 /* Decrement the count of locks against this same file. When the
1860 ** count reaches zero, close any other file descriptors whose close
1861 ** was deferred because of outstanding locks.
1862 */
drh8af6c222010-05-14 12:43:01 +00001863 pInode->nLock--;
1864 assert( pInode->nLock>=0 );
1865 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001866 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001867 }
1868 }
drhf2f105d2012-08-20 15:53:54 +00001869
aswift5b1a2562008-08-22 00:22:35 +00001870end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001871 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001872 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001873 return rc;
drhbbd42a62004-05-22 17:41:58 +00001874}
1875
1876/*
drh308c2a52010-05-14 11:30:18 +00001877** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001878** must be either NO_LOCK or SHARED_LOCK.
1879**
1880** If the locking level of the file descriptor is already at or below
1881** the requested locking level, this routine is a no-op.
1882*/
drh308c2a52010-05-14 11:30:18 +00001883static int unixUnlock(sqlite3_file *id, int eFileLock){
dana1afc742013-03-25 13:50:49 +00001884 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
drha7e61d82011-03-12 17:02:57 +00001885 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001886}
1887
mistachkine98844f2013-08-24 00:59:24 +00001888#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001889static int unixMapfile(unixFile *pFd, i64 nByte);
1890static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001891#endif
danf23da962013-03-23 21:00:41 +00001892
drh7ed97b92010-01-20 13:07:21 +00001893/*
danielk1977e339d652008-06-28 11:23:00 +00001894** This function performs the parts of the "close file" operation
1895** common to all locking schemes. It closes the directory and file
1896** handles, if they are valid, and sets all fields of the unixFile
1897** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001898**
1899** It is *not* necessary to hold the mutex when this routine is called,
1900** even on VxWorks. A mutex will be acquired on VxWorks by the
1901** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001902*/
1903static int closeUnixFile(sqlite3_file *id){
1904 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001905#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001906 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001907#endif
dan661d71a2011-03-30 19:08:03 +00001908 if( pFile->h>=0 ){
1909 robust_close(pFile, pFile->h, __LINE__);
1910 pFile->h = -1;
1911 }
1912#if OS_VXWORKS
1913 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001914 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001915 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001916 }
1917 vxworksReleaseFileId(pFile->pId);
1918 pFile->pId = 0;
1919 }
1920#endif
1921 OSTRACE(("CLOSE %-3d\n", pFile->h));
1922 OpenCounter(-1);
1923 sqlite3_free(pFile->pUnused);
1924 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001925 return SQLITE_OK;
1926}
1927
1928/*
danielk1977e3026632004-06-22 11:29:02 +00001929** Close a file.
1930*/
danielk197762079062007-08-15 17:08:46 +00001931static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001932 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001933 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001934 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001935 unixUnlock(id, NO_LOCK);
1936 unixEnterMutex();
1937
1938 /* unixFile.pInode is always valid here. Otherwise, a different close
1939 ** routine (e.g. nolockClose()) would be called instead.
1940 */
1941 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1942 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1943 /* If there are outstanding locks, do not actually close the file just
1944 ** yet because that would clear those locks. Instead, add the file
1945 ** descriptor to pInode->pUnused list. It will be automatically closed
1946 ** when the last lock is cleared.
1947 */
1948 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001949 }
dan661d71a2011-03-30 19:08:03 +00001950 releaseInodeInfo(pFile);
1951 rc = closeUnixFile(id);
1952 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001953 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001954}
1955
drh734c9862008-11-28 15:37:20 +00001956/************** End of the posix advisory lock implementation *****************
1957******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001958
drh734c9862008-11-28 15:37:20 +00001959/******************************************************************************
1960****************************** No-op Locking **********************************
1961**
1962** Of the various locking implementations available, this is by far the
1963** simplest: locking is ignored. No attempt is made to lock the database
1964** file for reading or writing.
1965**
1966** This locking mode is appropriate for use on read-only databases
1967** (ex: databases that are burned into CD-ROM, for example.) It can
1968** also be used if the application employs some external mechanism to
1969** prevent simultaneous access of the same database by two or more
1970** database connections. But there is a serious risk of database
1971** corruption if this locking mode is used in situations where multiple
1972** database connections are accessing the same database file at the same
1973** time and one or more of those connections are writing.
1974*/
drhbfe66312006-10-03 17:40:40 +00001975
drh734c9862008-11-28 15:37:20 +00001976static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1977 UNUSED_PARAMETER(NotUsed);
1978 *pResOut = 0;
1979 return SQLITE_OK;
1980}
drh734c9862008-11-28 15:37:20 +00001981static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1982 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1983 return SQLITE_OK;
1984}
drh734c9862008-11-28 15:37:20 +00001985static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1986 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1987 return SQLITE_OK;
1988}
1989
1990/*
drh9b35ea62008-11-29 02:20:26 +00001991** Close the file.
drh734c9862008-11-28 15:37:20 +00001992*/
1993static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001994 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001995}
1996
1997/******************* End of the no-op lock implementation *********************
1998******************************************************************************/
1999
2000/******************************************************************************
2001************************* Begin dot-file Locking ******************************
2002**
mistachkin48864df2013-03-21 21:20:32 +00002003** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002004** files (really a directory) to control access to the database. This works
2005** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002006**
2007** (1) There is zero concurrency. A single reader blocks all other
2008** connections from reading or writing the database.
2009**
2010** (2) An application crash or power loss can leave stale lock files
2011** sitting around that need to be cleared manually.
2012**
2013** Nevertheless, a dotlock is an appropriate locking mode for use if no
2014** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002015**
drh9ef6bc42011-11-04 02:24:02 +00002016** Dotfile locking works by creating a subdirectory in the same directory as
2017** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002018** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002019** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002020*/
2021
2022/*
2023** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002024** lock directory.
drh734c9862008-11-28 15:37:20 +00002025*/
2026#define DOTLOCK_SUFFIX ".lock"
2027
drh7708e972008-11-29 00:56:52 +00002028/*
2029** This routine checks if there is a RESERVED lock held on the specified
2030** file by this or any other process. If such a lock is held, set *pResOut
2031** to a non-zero value otherwise *pResOut is set to zero. The return value
2032** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2033**
2034** In dotfile locking, either a lock exists or it does not. So in this
2035** variation of CheckReservedLock(), *pResOut is set to true if any lock
2036** is held on the file and false if the file is unlocked.
2037*/
drh734c9862008-11-28 15:37:20 +00002038static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2039 int rc = SQLITE_OK;
2040 int reserved = 0;
2041 unixFile *pFile = (unixFile*)id;
2042
2043 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2044
2045 assert( pFile );
2046
2047 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002048 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002049 /* Either this connection or some other connection in the same process
2050 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002051 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002052 }else{
2053 /* The lock is held if and only if the lockfile exists */
2054 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002055 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002056 }
drh308c2a52010-05-14 11:30:18 +00002057 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002058 *pResOut = reserved;
2059 return rc;
2060}
2061
drh7708e972008-11-29 00:56:52 +00002062/*
drh308c2a52010-05-14 11:30:18 +00002063** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002064** of the following:
2065**
2066** (1) SHARED_LOCK
2067** (2) RESERVED_LOCK
2068** (3) PENDING_LOCK
2069** (4) EXCLUSIVE_LOCK
2070**
2071** Sometimes when requesting one lock state, additional lock states
2072** are inserted in between. The locking might fail on one of the later
2073** transitions leaving the lock state different from what it started but
2074** still short of its goal. The following chart shows the allowed
2075** transitions and the inserted intermediate states:
2076**
2077** UNLOCKED -> SHARED
2078** SHARED -> RESERVED
2079** SHARED -> (PENDING) -> EXCLUSIVE
2080** RESERVED -> (PENDING) -> EXCLUSIVE
2081** PENDING -> EXCLUSIVE
2082**
2083** This routine will only increase a lock. Use the sqlite3OsUnlock()
2084** routine to lower a locking level.
2085**
2086** With dotfile locking, we really only support state (4): EXCLUSIVE.
2087** But we track the other locking levels internally.
2088*/
drh308c2a52010-05-14 11:30:18 +00002089static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002090 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002091 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002092 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002093
drh7708e972008-11-29 00:56:52 +00002094
2095 /* If we have any lock, then the lock file already exists. All we have
2096 ** to do is adjust our internal record of the lock level.
2097 */
drh308c2a52010-05-14 11:30:18 +00002098 if( pFile->eFileLock > NO_LOCK ){
2099 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002100 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002101#ifdef HAVE_UTIME
2102 utime(zLockFile, NULL);
2103#else
drh734c9862008-11-28 15:37:20 +00002104 utimes(zLockFile, NULL);
2105#endif
drh7708e972008-11-29 00:56:52 +00002106 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002107 }
2108
2109 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002110 rc = osMkdir(zLockFile, 0777);
2111 if( rc<0 ){
2112 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002113 int tErrno = errno;
2114 if( EEXIST == tErrno ){
2115 rc = SQLITE_BUSY;
2116 } else {
2117 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2118 if( IS_LOCK_ERROR(rc) ){
2119 pFile->lastErrno = tErrno;
2120 }
2121 }
drh7708e972008-11-29 00:56:52 +00002122 return rc;
drh734c9862008-11-28 15:37:20 +00002123 }
drh734c9862008-11-28 15:37:20 +00002124
2125 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002126 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002127 return rc;
2128}
2129
drh7708e972008-11-29 00:56:52 +00002130/*
drh308c2a52010-05-14 11:30:18 +00002131** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002132** must be either NO_LOCK or SHARED_LOCK.
2133**
2134** If the locking level of the file descriptor is already at or below
2135** the requested locking level, this routine is a no-op.
2136**
2137** When the locking level reaches NO_LOCK, delete the lock file.
2138*/
drh308c2a52010-05-14 11:30:18 +00002139static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002140 unixFile *pFile = (unixFile*)id;
2141 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002142 int rc;
drh734c9862008-11-28 15:37:20 +00002143
2144 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002145 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002146 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002147 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002148
2149 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002150 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002151 return SQLITE_OK;
2152 }
drh7708e972008-11-29 00:56:52 +00002153
2154 /* To downgrade to shared, simply update our internal notion of the
2155 ** lock state. No need to mess with the file on disk.
2156 */
drh308c2a52010-05-14 11:30:18 +00002157 if( eFileLock==SHARED_LOCK ){
2158 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002159 return SQLITE_OK;
2160 }
2161
drh7708e972008-11-29 00:56:52 +00002162 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002163 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002164 rc = osRmdir(zLockFile);
2165 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2166 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002167 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002168 rc = 0;
drh734c9862008-11-28 15:37:20 +00002169 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002170 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002171 }
2172 if( IS_LOCK_ERROR(rc) ){
2173 pFile->lastErrno = tErrno;
2174 }
2175 return rc;
2176 }
drh308c2a52010-05-14 11:30:18 +00002177 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002178 return SQLITE_OK;
2179}
2180
2181/*
drh9b35ea62008-11-29 02:20:26 +00002182** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002183*/
2184static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002185 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002186 if( id ){
2187 unixFile *pFile = (unixFile*)id;
2188 dotlockUnlock(id, NO_LOCK);
2189 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002190 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002191 }
drh734c9862008-11-28 15:37:20 +00002192 return rc;
2193}
2194/****************** End of the dot-file lock implementation *******************
2195******************************************************************************/
2196
2197/******************************************************************************
2198************************** Begin flock Locking ********************************
2199**
2200** Use the flock() system call to do file locking.
2201**
drh6b9d6dd2008-12-03 19:34:47 +00002202** flock() locking is like dot-file locking in that the various
2203** fine-grain locking levels supported by SQLite are collapsed into
2204** a single exclusive lock. In other words, SHARED, RESERVED, and
2205** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2206** still works when you do this, but concurrency is reduced since
2207** only a single process can be reading the database at a time.
2208**
drh734c9862008-11-28 15:37:20 +00002209** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2210** compiling for VXWORKS.
2211*/
2212#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002213
drh6b9d6dd2008-12-03 19:34:47 +00002214/*
drhff812312011-02-23 13:33:46 +00002215** Retry flock() calls that fail with EINTR
2216*/
2217#ifdef EINTR
2218static int robust_flock(int fd, int op){
2219 int rc;
2220 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2221 return rc;
2222}
2223#else
drh5c819272011-02-23 14:00:12 +00002224# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002225#endif
2226
2227
2228/*
drh6b9d6dd2008-12-03 19:34:47 +00002229** This routine checks if there is a RESERVED lock held on the specified
2230** file by this or any other process. If such a lock is held, set *pResOut
2231** to a non-zero value otherwise *pResOut is set to zero. The return value
2232** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2233*/
drh734c9862008-11-28 15:37:20 +00002234static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2235 int rc = SQLITE_OK;
2236 int reserved = 0;
2237 unixFile *pFile = (unixFile*)id;
2238
2239 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2240
2241 assert( pFile );
2242
2243 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002244 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002245 reserved = 1;
2246 }
2247
2248 /* Otherwise see if some other process holds it. */
2249 if( !reserved ){
2250 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002251 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002252 if( !lrc ){
2253 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002254 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002255 if ( lrc ) {
2256 int tErrno = errno;
2257 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002258 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002259 if( IS_LOCK_ERROR(lrc) ){
2260 pFile->lastErrno = tErrno;
2261 rc = lrc;
2262 }
2263 }
2264 } else {
2265 int tErrno = errno;
2266 reserved = 1;
2267 /* someone else might have it reserved */
2268 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2269 if( IS_LOCK_ERROR(lrc) ){
2270 pFile->lastErrno = tErrno;
2271 rc = lrc;
2272 }
2273 }
2274 }
drh308c2a52010-05-14 11:30:18 +00002275 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002276
2277#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2278 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2279 rc = SQLITE_OK;
2280 reserved=1;
2281 }
2282#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2283 *pResOut = reserved;
2284 return rc;
2285}
2286
drh6b9d6dd2008-12-03 19:34:47 +00002287/*
drh308c2a52010-05-14 11:30:18 +00002288** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002289** of the following:
2290**
2291** (1) SHARED_LOCK
2292** (2) RESERVED_LOCK
2293** (3) PENDING_LOCK
2294** (4) EXCLUSIVE_LOCK
2295**
2296** Sometimes when requesting one lock state, additional lock states
2297** are inserted in between. The locking might fail on one of the later
2298** transitions leaving the lock state different from what it started but
2299** still short of its goal. The following chart shows the allowed
2300** transitions and the inserted intermediate states:
2301**
2302** UNLOCKED -> SHARED
2303** SHARED -> RESERVED
2304** SHARED -> (PENDING) -> EXCLUSIVE
2305** RESERVED -> (PENDING) -> EXCLUSIVE
2306** PENDING -> EXCLUSIVE
2307**
2308** flock() only really support EXCLUSIVE locks. We track intermediate
2309** lock states in the sqlite3_file structure, but all locks SHARED or
2310** above are really EXCLUSIVE locks and exclude all other processes from
2311** access the file.
2312**
2313** This routine will only increase a lock. Use the sqlite3OsUnlock()
2314** routine to lower a locking level.
2315*/
drh308c2a52010-05-14 11:30:18 +00002316static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002317 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002318 unixFile *pFile = (unixFile*)id;
2319
2320 assert( pFile );
2321
2322 /* if we already have a lock, it is exclusive.
2323 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002324 if (pFile->eFileLock > NO_LOCK) {
2325 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002326 return SQLITE_OK;
2327 }
2328
2329 /* grab an exclusive lock */
2330
drhff812312011-02-23 13:33:46 +00002331 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002332 int tErrno = errno;
2333 /* didn't get, must be busy */
2334 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2335 if( IS_LOCK_ERROR(rc) ){
2336 pFile->lastErrno = tErrno;
2337 }
2338 } else {
2339 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002340 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002341 }
drh308c2a52010-05-14 11:30:18 +00002342 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2343 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002344#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2345 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2346 rc = SQLITE_BUSY;
2347 }
2348#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2349 return rc;
2350}
2351
drh6b9d6dd2008-12-03 19:34:47 +00002352
2353/*
drh308c2a52010-05-14 11:30:18 +00002354** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002355** must be either NO_LOCK or SHARED_LOCK.
2356**
2357** If the locking level of the file descriptor is already at or below
2358** the requested locking level, this routine is a no-op.
2359*/
drh308c2a52010-05-14 11:30:18 +00002360static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002361 unixFile *pFile = (unixFile*)id;
2362
2363 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002364 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2365 pFile->eFileLock, getpid()));
2366 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002367
2368 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002369 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002370 return SQLITE_OK;
2371 }
2372
2373 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002374 if (eFileLock==SHARED_LOCK) {
2375 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002376 return SQLITE_OK;
2377 }
2378
2379 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002380 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002381#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002382 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002383#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002384 return SQLITE_IOERR_UNLOCK;
2385 }else{
drh308c2a52010-05-14 11:30:18 +00002386 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002387 return SQLITE_OK;
2388 }
2389}
2390
2391/*
2392** Close a file.
2393*/
2394static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002395 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002396 if( id ){
2397 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002398 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002399 }
drh5a05be12012-10-09 18:51:44 +00002400 return rc;
drh734c9862008-11-28 15:37:20 +00002401}
2402
2403#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2404
2405/******************* End of the flock lock implementation *********************
2406******************************************************************************/
2407
2408/******************************************************************************
2409************************ Begin Named Semaphore Locking ************************
2410**
2411** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002412**
2413** Semaphore locking is like dot-lock and flock in that it really only
2414** supports EXCLUSIVE locking. Only a single process can read or write
2415** the database file at a time. This reduces potential concurrency, but
2416** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002417*/
2418#if OS_VXWORKS
2419
drh6b9d6dd2008-12-03 19:34:47 +00002420/*
2421** This routine checks if there is a RESERVED lock held on the specified
2422** file by this or any other process. If such a lock is held, set *pResOut
2423** to a non-zero value otherwise *pResOut is set to zero. The return value
2424** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2425*/
drh734c9862008-11-28 15:37:20 +00002426static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2427 int rc = SQLITE_OK;
2428 int reserved = 0;
2429 unixFile *pFile = (unixFile*)id;
2430
2431 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2432
2433 assert( pFile );
2434
2435 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002436 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002437 reserved = 1;
2438 }
2439
2440 /* Otherwise see if some other process holds it. */
2441 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002442 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002443 struct stat statBuf;
2444
2445 if( sem_trywait(pSem)==-1 ){
2446 int tErrno = errno;
2447 if( EAGAIN != tErrno ){
2448 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2449 pFile->lastErrno = tErrno;
2450 } else {
2451 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002452 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002453 }
2454 }else{
2455 /* we could have it if we want it */
2456 sem_post(pSem);
2457 }
2458 }
drh308c2a52010-05-14 11:30:18 +00002459 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002460
2461 *pResOut = reserved;
2462 return rc;
2463}
2464
drh6b9d6dd2008-12-03 19:34:47 +00002465/*
drh308c2a52010-05-14 11:30:18 +00002466** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002467** of the following:
2468**
2469** (1) SHARED_LOCK
2470** (2) RESERVED_LOCK
2471** (3) PENDING_LOCK
2472** (4) EXCLUSIVE_LOCK
2473**
2474** Sometimes when requesting one lock state, additional lock states
2475** are inserted in between. The locking might fail on one of the later
2476** transitions leaving the lock state different from what it started but
2477** still short of its goal. The following chart shows the allowed
2478** transitions and the inserted intermediate states:
2479**
2480** UNLOCKED -> SHARED
2481** SHARED -> RESERVED
2482** SHARED -> (PENDING) -> EXCLUSIVE
2483** RESERVED -> (PENDING) -> EXCLUSIVE
2484** PENDING -> EXCLUSIVE
2485**
2486** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2487** lock states in the sqlite3_file structure, but all locks SHARED or
2488** above are really EXCLUSIVE locks and exclude all other processes from
2489** access the file.
2490**
2491** This routine will only increase a lock. Use the sqlite3OsUnlock()
2492** routine to lower a locking level.
2493*/
drh308c2a52010-05-14 11:30:18 +00002494static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002495 unixFile *pFile = (unixFile*)id;
2496 int fd;
drh8af6c222010-05-14 12:43:01 +00002497 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002498 int rc = SQLITE_OK;
2499
2500 /* if we already have a lock, it is exclusive.
2501 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002502 if (pFile->eFileLock > NO_LOCK) {
2503 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002504 rc = SQLITE_OK;
2505 goto sem_end_lock;
2506 }
2507
2508 /* lock semaphore now but bail out when already locked. */
2509 if( sem_trywait(pSem)==-1 ){
2510 rc = SQLITE_BUSY;
2511 goto sem_end_lock;
2512 }
2513
2514 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002515 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002516
2517 sem_end_lock:
2518 return rc;
2519}
2520
drh6b9d6dd2008-12-03 19:34:47 +00002521/*
drh308c2a52010-05-14 11:30:18 +00002522** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002523** must be either NO_LOCK or SHARED_LOCK.
2524**
2525** If the locking level of the file descriptor is already at or below
2526** the requested locking level, this routine is a no-op.
2527*/
drh308c2a52010-05-14 11:30:18 +00002528static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002529 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002530 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002531
2532 assert( pFile );
2533 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002534 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002535 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002536 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002537
2538 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002539 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002540 return SQLITE_OK;
2541 }
2542
2543 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002544 if (eFileLock==SHARED_LOCK) {
2545 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002546 return SQLITE_OK;
2547 }
2548
2549 /* no, really unlock. */
2550 if ( sem_post(pSem)==-1 ) {
2551 int rc, tErrno = errno;
2552 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2553 if( IS_LOCK_ERROR(rc) ){
2554 pFile->lastErrno = tErrno;
2555 }
2556 return rc;
2557 }
drh308c2a52010-05-14 11:30:18 +00002558 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002559 return SQLITE_OK;
2560}
2561
2562/*
2563 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002564 */
drh734c9862008-11-28 15:37:20 +00002565static int semClose(sqlite3_file *id) {
2566 if( id ){
2567 unixFile *pFile = (unixFile*)id;
2568 semUnlock(id, NO_LOCK);
2569 assert( pFile );
2570 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002571 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002572 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002573 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002574 }
2575 return SQLITE_OK;
2576}
2577
2578#endif /* OS_VXWORKS */
2579/*
2580** Named semaphore locking is only available on VxWorks.
2581**
2582*************** End of the named semaphore lock implementation ****************
2583******************************************************************************/
2584
2585
2586/******************************************************************************
2587*************************** Begin AFP Locking *********************************
2588**
2589** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2590** on Apple Macintosh computers - both OS9 and OSX.
2591**
2592** Third-party implementations of AFP are available. But this code here
2593** only works on OSX.
2594*/
2595
drhd2cb50b2009-01-09 21:41:17 +00002596#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002597/*
2598** The afpLockingContext structure contains all afp lock specific state
2599*/
drhbfe66312006-10-03 17:40:40 +00002600typedef struct afpLockingContext afpLockingContext;
2601struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002602 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002603 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002604};
2605
2606struct ByteRangeLockPB2
2607{
2608 unsigned long long offset; /* offset to first byte to lock */
2609 unsigned long long length; /* nbr of bytes to lock */
2610 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2611 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2612 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2613 int fd; /* file desc to assoc this lock with */
2614};
2615
drhfd131da2007-08-07 17:13:03 +00002616#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002617
drh6b9d6dd2008-12-03 19:34:47 +00002618/*
2619** This is a utility for setting or clearing a bit-range lock on an
2620** AFP filesystem.
2621**
2622** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2623*/
2624static int afpSetLock(
2625 const char *path, /* Name of the file to be locked or unlocked */
2626 unixFile *pFile, /* Open file descriptor on path */
2627 unsigned long long offset, /* First byte to be locked */
2628 unsigned long long length, /* Number of bytes to lock */
2629 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002630){
drh6b9d6dd2008-12-03 19:34:47 +00002631 struct ByteRangeLockPB2 pb;
2632 int err;
drhbfe66312006-10-03 17:40:40 +00002633
2634 pb.unLockFlag = setLockFlag ? 0 : 1;
2635 pb.startEndFlag = 0;
2636 pb.offset = offset;
2637 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002638 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002639
drh308c2a52010-05-14 11:30:18 +00002640 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002641 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002642 offset, length));
drhbfe66312006-10-03 17:40:40 +00002643 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2644 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002645 int rc;
2646 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002647 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2648 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002649#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2650 rc = SQLITE_BUSY;
2651#else
drh734c9862008-11-28 15:37:20 +00002652 rc = sqliteErrorFromPosixError(tErrno,
2653 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002654#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002655 if( IS_LOCK_ERROR(rc) ){
2656 pFile->lastErrno = tErrno;
2657 }
2658 return rc;
drhbfe66312006-10-03 17:40:40 +00002659 } else {
aswift5b1a2562008-08-22 00:22:35 +00002660 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002661 }
2662}
2663
drh6b9d6dd2008-12-03 19:34:47 +00002664/*
2665** This routine checks if there is a RESERVED lock held on the specified
2666** file by this or any other process. If such a lock is held, set *pResOut
2667** to a non-zero value otherwise *pResOut is set to zero. The return value
2668** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2669*/
danielk1977e339d652008-06-28 11:23:00 +00002670static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002671 int rc = SQLITE_OK;
2672 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002673 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002674 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002675
aswift5b1a2562008-08-22 00:22:35 +00002676 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2677
2678 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002679 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002680 if( context->reserved ){
2681 *pResOut = 1;
2682 return SQLITE_OK;
2683 }
drh8af6c222010-05-14 12:43:01 +00002684 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002685
2686 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002687 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002688 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002689 }
2690
2691 /* Otherwise see if some other process holds it.
2692 */
aswift5b1a2562008-08-22 00:22:35 +00002693 if( !reserved ){
2694 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002695 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002696 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002697 /* if we succeeded in taking the reserved lock, unlock it to restore
2698 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002699 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002700 } else {
2701 /* if we failed to get the lock then someone else must have it */
2702 reserved = 1;
2703 }
2704 if( IS_LOCK_ERROR(lrc) ){
2705 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002706 }
2707 }
drhbfe66312006-10-03 17:40:40 +00002708
drh7ed97b92010-01-20 13:07:21 +00002709 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002710 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002711
2712 *pResOut = reserved;
2713 return rc;
drhbfe66312006-10-03 17:40:40 +00002714}
2715
drh6b9d6dd2008-12-03 19:34:47 +00002716/*
drh308c2a52010-05-14 11:30:18 +00002717** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002718** of the following:
2719**
2720** (1) SHARED_LOCK
2721** (2) RESERVED_LOCK
2722** (3) PENDING_LOCK
2723** (4) EXCLUSIVE_LOCK
2724**
2725** Sometimes when requesting one lock state, additional lock states
2726** are inserted in between. The locking might fail on one of the later
2727** transitions leaving the lock state different from what it started but
2728** still short of its goal. The following chart shows the allowed
2729** transitions and the inserted intermediate states:
2730**
2731** UNLOCKED -> SHARED
2732** SHARED -> RESERVED
2733** SHARED -> (PENDING) -> EXCLUSIVE
2734** RESERVED -> (PENDING) -> EXCLUSIVE
2735** PENDING -> EXCLUSIVE
2736**
2737** This routine will only increase a lock. Use the sqlite3OsUnlock()
2738** routine to lower a locking level.
2739*/
drh308c2a52010-05-14 11:30:18 +00002740static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002741 int rc = SQLITE_OK;
2742 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002743 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002744 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002745
2746 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002747 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2748 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002749 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002750
drhbfe66312006-10-03 17:40:40 +00002751 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002752 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002753 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002754 */
drh308c2a52010-05-14 11:30:18 +00002755 if( pFile->eFileLock>=eFileLock ){
2756 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2757 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002758 return SQLITE_OK;
2759 }
2760
2761 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002762 ** (1) We never move from unlocked to anything higher than shared lock.
2763 ** (2) SQLite never explicitly requests a pendig lock.
2764 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002765 */
drh308c2a52010-05-14 11:30:18 +00002766 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2767 assert( eFileLock!=PENDING_LOCK );
2768 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002769
drh8af6c222010-05-14 12:43:01 +00002770 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002771 */
drh6c7d5c52008-11-21 20:32:33 +00002772 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002773 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002774
2775 /* If some thread using this PID has a lock via a different unixFile*
2776 ** handle that precludes the requested lock, return BUSY.
2777 */
drh8af6c222010-05-14 12:43:01 +00002778 if( (pFile->eFileLock!=pInode->eFileLock &&
2779 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002780 ){
2781 rc = SQLITE_BUSY;
2782 goto afp_end_lock;
2783 }
2784
2785 /* If a SHARED lock is requested, and some thread using this PID already
2786 ** has a SHARED or RESERVED lock, then increment reference counts and
2787 ** return SQLITE_OK.
2788 */
drh308c2a52010-05-14 11:30:18 +00002789 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002790 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002791 assert( eFileLock==SHARED_LOCK );
2792 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002793 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002794 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002795 pInode->nShared++;
2796 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002797 goto afp_end_lock;
2798 }
drhbfe66312006-10-03 17:40:40 +00002799
2800 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002801 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2802 ** be released.
2803 */
drh308c2a52010-05-14 11:30:18 +00002804 if( eFileLock==SHARED_LOCK
2805 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002806 ){
2807 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002808 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002809 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002810 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002811 goto afp_end_lock;
2812 }
2813 }
2814
2815 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002816 ** operating system calls for the specified lock.
2817 */
drh308c2a52010-05-14 11:30:18 +00002818 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002819 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002820 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002821
drh8af6c222010-05-14 12:43:01 +00002822 assert( pInode->nShared==0 );
2823 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002824
2825 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002826 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002827 /* note that the quality of the randomness doesn't matter that much */
2828 lk = random();
drh8af6c222010-05-14 12:43:01 +00002829 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002830 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002831 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002832 if( IS_LOCK_ERROR(lrc1) ){
2833 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002834 }
aswift5b1a2562008-08-22 00:22:35 +00002835 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002836 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002837
aswift5b1a2562008-08-22 00:22:35 +00002838 if( IS_LOCK_ERROR(lrc1) ) {
2839 pFile->lastErrno = lrc1Errno;
2840 rc = lrc1;
2841 goto afp_end_lock;
2842 } else if( IS_LOCK_ERROR(lrc2) ){
2843 rc = lrc2;
2844 goto afp_end_lock;
2845 } else if( lrc1 != SQLITE_OK ) {
2846 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002847 } else {
drh308c2a52010-05-14 11:30:18 +00002848 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002849 pInode->nLock++;
2850 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002851 }
drh8af6c222010-05-14 12:43:01 +00002852 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002853 /* We are trying for an exclusive lock but another thread in this
2854 ** same process is still holding a shared lock. */
2855 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002856 }else{
2857 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2858 ** assumed that there is a SHARED or greater lock on the file
2859 ** already.
2860 */
2861 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002862 assert( 0!=pFile->eFileLock );
2863 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002864 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002865 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002866 if( !failed ){
2867 context->reserved = 1;
2868 }
drhbfe66312006-10-03 17:40:40 +00002869 }
drh308c2a52010-05-14 11:30:18 +00002870 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002871 /* Acquire an EXCLUSIVE lock */
2872
2873 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002874 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002875 */
drh6b9d6dd2008-12-03 19:34:47 +00002876 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002877 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002878 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002879 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002880 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002881 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002882 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002883 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002884 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2885 ** a critical I/O error
2886 */
2887 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2888 SQLITE_IOERR_LOCK;
2889 goto afp_end_lock;
2890 }
2891 }else{
aswift5b1a2562008-08-22 00:22:35 +00002892 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002893 }
2894 }
aswift5b1a2562008-08-22 00:22:35 +00002895 if( failed ){
2896 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002897 }
2898 }
2899
2900 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002901 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002902 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002903 }else if( eFileLock==EXCLUSIVE_LOCK ){
2904 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002905 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002906 }
2907
2908afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002909 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002910 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2911 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002912 return rc;
2913}
2914
2915/*
drh308c2a52010-05-14 11:30:18 +00002916** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002917** must be either NO_LOCK or SHARED_LOCK.
2918**
2919** If the locking level of the file descriptor is already at or below
2920** the requested locking level, this routine is a no-op.
2921*/
drh308c2a52010-05-14 11:30:18 +00002922static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002923 int rc = SQLITE_OK;
2924 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002925 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002926 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2927 int skipShared = 0;
2928#ifdef SQLITE_TEST
2929 int h = pFile->h;
2930#endif
drhbfe66312006-10-03 17:40:40 +00002931
2932 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002933 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002934 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002935 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002936
drh308c2a52010-05-14 11:30:18 +00002937 assert( eFileLock<=SHARED_LOCK );
2938 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002939 return SQLITE_OK;
2940 }
drh6c7d5c52008-11-21 20:32:33 +00002941 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002942 pInode = pFile->pInode;
2943 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002944 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002945 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002946 SimulateIOErrorBenign(1);
2947 SimulateIOError( h=(-1) )
2948 SimulateIOErrorBenign(0);
2949
drhd3d8c042012-05-29 17:02:40 +00002950#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002951 /* When reducing a lock such that other processes can start
2952 ** reading the database file again, make sure that the
2953 ** transaction counter was updated if any part of the database
2954 ** file changed. If the transaction counter is not updated,
2955 ** other connections to the same file might not realize that
2956 ** the file has changed and hence might not know to flush their
2957 ** cache. The use of a stale cache can lead to database corruption.
2958 */
2959 assert( pFile->inNormalWrite==0
2960 || pFile->dbUpdate==0
2961 || pFile->transCntrChng==1 );
2962 pFile->inNormalWrite = 0;
2963#endif
aswiftaebf4132008-11-21 00:10:35 +00002964
drh308c2a52010-05-14 11:30:18 +00002965 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002966 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002967 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002968 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002969 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002970 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2971 } else {
2972 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002973 }
2974 }
drh308c2a52010-05-14 11:30:18 +00002975 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002976 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002977 }
drh308c2a52010-05-14 11:30:18 +00002978 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002979 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2980 if( !rc ){
2981 context->reserved = 0;
2982 }
aswiftaebf4132008-11-21 00:10:35 +00002983 }
drh8af6c222010-05-14 12:43:01 +00002984 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2985 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002986 }
aswiftaebf4132008-11-21 00:10:35 +00002987 }
drh308c2a52010-05-14 11:30:18 +00002988 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002989
drh7ed97b92010-01-20 13:07:21 +00002990 /* Decrement the shared lock counter. Release the lock using an
2991 ** OS call only when all threads in this same process have released
2992 ** the lock.
2993 */
drh8af6c222010-05-14 12:43:01 +00002994 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2995 pInode->nShared--;
2996 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002997 SimulateIOErrorBenign(1);
2998 SimulateIOError( h=(-1) )
2999 SimulateIOErrorBenign(0);
3000 if( !skipShared ){
3001 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3002 }
3003 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003004 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003005 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003006 }
3007 }
3008 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003009 pInode->nLock--;
3010 assert( pInode->nLock>=0 );
3011 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003012 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003013 }
3014 }
drhbfe66312006-10-03 17:40:40 +00003015 }
drh7ed97b92010-01-20 13:07:21 +00003016
drh6c7d5c52008-11-21 20:32:33 +00003017 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003018 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003019 return rc;
3020}
3021
3022/*
drh339eb0b2008-03-07 15:34:11 +00003023** Close a file & cleanup AFP specific locking context
3024*/
danielk1977e339d652008-06-28 11:23:00 +00003025static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003026 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003027 if( id ){
3028 unixFile *pFile = (unixFile*)id;
3029 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003030 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003031 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003032 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003033 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003034 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003035 ** the last lock is cleared.
3036 */
dan08da86a2009-08-21 17:18:03 +00003037 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003038 }
danb0ac3e32010-06-16 10:55:42 +00003039 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003040 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003041 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003042 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003043 }
drh7ed97b92010-01-20 13:07:21 +00003044 return rc;
drhbfe66312006-10-03 17:40:40 +00003045}
3046
drhd2cb50b2009-01-09 21:41:17 +00003047#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003048/*
3049** The code above is the AFP lock implementation. The code is specific
3050** to MacOSX and does not work on other unix platforms. No alternative
3051** is available. If you don't compile for a mac, then the "unix-afp"
3052** VFS is not available.
3053**
3054********************* End of the AFP lock implementation **********************
3055******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003056
drh7ed97b92010-01-20 13:07:21 +00003057/******************************************************************************
3058*************************** Begin NFS Locking ********************************/
3059
3060#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3061/*
drh308c2a52010-05-14 11:30:18 +00003062 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003063 ** must be either NO_LOCK or SHARED_LOCK.
3064 **
3065 ** If the locking level of the file descriptor is already at or below
3066 ** the requested locking level, this routine is a no-op.
3067 */
drh308c2a52010-05-14 11:30:18 +00003068static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003069 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003070}
3071
3072#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3073/*
3074** The code above is the NFS lock implementation. The code is specific
3075** to MacOSX and does not work on other unix platforms. No alternative
3076** is available.
3077**
3078********************* End of the NFS lock implementation **********************
3079******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003080
3081/******************************************************************************
3082**************** Non-locking sqlite3_file methods *****************************
3083**
3084** The next division contains implementations for all methods of the
3085** sqlite3_file object other than the locking methods. The locking
3086** methods were defined in divisions above (one locking method per
3087** division). Those methods that are common to all locking modes
3088** are gather together into this division.
3089*/
drhbfe66312006-10-03 17:40:40 +00003090
3091/*
drh734c9862008-11-28 15:37:20 +00003092** Seek to the offset passed as the second argument, then read cnt
3093** bytes into pBuf. Return the number of bytes actually read.
3094**
3095** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3096** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3097** one system to another. Since SQLite does not define USE_PREAD
3098** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3099** See tickets #2741 and #2681.
3100**
3101** To avoid stomping the errno value on a failed read the lastErrno value
3102** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003103*/
drh734c9862008-11-28 15:37:20 +00003104static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3105 int got;
drh58024642011-11-07 18:16:00 +00003106 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003107#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003108 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003109#endif
drh734c9862008-11-28 15:37:20 +00003110 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003111 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003112 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003113 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003114 do{
drh734c9862008-11-28 15:37:20 +00003115#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003116 got = osPread(id->h, pBuf, cnt, offset);
3117 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003118#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003119 got = osPread64(id->h, pBuf, cnt, offset);
3120 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003121#else
drh58024642011-11-07 18:16:00 +00003122 newOffset = lseek(id->h, offset, SEEK_SET);
3123 SimulateIOError( newOffset-- );
3124 if( newOffset!=offset ){
3125 if( newOffset == -1 ){
3126 ((unixFile*)id)->lastErrno = errno;
3127 }else{
drhf2f105d2012-08-20 15:53:54 +00003128 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003129 }
3130 return -1;
drh734c9862008-11-28 15:37:20 +00003131 }
drh58024642011-11-07 18:16:00 +00003132 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003133#endif
drh58024642011-11-07 18:16:00 +00003134 if( got==cnt ) break;
3135 if( got<0 ){
3136 if( errno==EINTR ){ got = 1; continue; }
3137 prior = 0;
3138 ((unixFile*)id)->lastErrno = errno;
3139 break;
3140 }else if( got>0 ){
3141 cnt -= got;
3142 offset += got;
3143 prior += got;
3144 pBuf = (void*)(got + (char*)pBuf);
3145 }
3146 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003147 TIMER_END;
drh58024642011-11-07 18:16:00 +00003148 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3149 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3150 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003151}
3152
3153/*
drh734c9862008-11-28 15:37:20 +00003154** Read data from a file into a buffer. Return SQLITE_OK if all
3155** bytes were read successfully and SQLITE_IOERR if anything goes
3156** wrong.
drh339eb0b2008-03-07 15:34:11 +00003157*/
drh734c9862008-11-28 15:37:20 +00003158static int unixRead(
3159 sqlite3_file *id,
3160 void *pBuf,
3161 int amt,
3162 sqlite3_int64 offset
3163){
dan08da86a2009-08-21 17:18:03 +00003164 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003165 int got;
3166 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003167 assert( offset>=0 );
3168 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003169
dan08da86a2009-08-21 17:18:03 +00003170 /* If this is a database file (not a journal, master-journal or temp
3171 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003172#if 0
dane946c392009-08-22 11:39:46 +00003173 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003174 || offset>=PENDING_BYTE+512
3175 || offset+amt<=PENDING_BYTE
3176 );
dan7c246102010-04-12 19:00:29 +00003177#endif
drh08c6d442009-02-09 17:34:07 +00003178
drh9b4c59f2013-04-15 17:03:42 +00003179#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003180 /* Deal with as much of this read request as possible by transfering
3181 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003182 if( offset<pFile->mmapSize ){
3183 if( offset+amt <= pFile->mmapSize ){
3184 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3185 return SQLITE_OK;
3186 }else{
3187 int nCopy = pFile->mmapSize - offset;
3188 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3189 pBuf = &((u8 *)pBuf)[nCopy];
3190 amt -= nCopy;
3191 offset += nCopy;
3192 }
3193 }
drh6e0b6d52013-04-09 16:19:20 +00003194#endif
danf23da962013-03-23 21:00:41 +00003195
dan08da86a2009-08-21 17:18:03 +00003196 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003197 if( got==amt ){
3198 return SQLITE_OK;
3199 }else if( got<0 ){
3200 /* lastErrno set by seekAndRead */
3201 return SQLITE_IOERR_READ;
3202 }else{
dan08da86a2009-08-21 17:18:03 +00003203 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003204 /* Unread parts of the buffer must be zero-filled */
3205 memset(&((char*)pBuf)[got], 0, amt-got);
3206 return SQLITE_IOERR_SHORT_READ;
3207 }
3208}
3209
3210/*
dan47a2b4a2013-04-26 16:09:29 +00003211** Attempt to seek the file-descriptor passed as the first argument to
3212** absolute offset iOff, then attempt to write nBuf bytes of data from
3213** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3214** return the actual number of bytes written (which may be less than
3215** nBuf).
3216*/
3217static int seekAndWriteFd(
3218 int fd, /* File descriptor to write to */
3219 i64 iOff, /* File offset to begin writing at */
3220 const void *pBuf, /* Copy data from this buffer to the file */
3221 int nBuf, /* Size of buffer pBuf in bytes */
3222 int *piErrno /* OUT: Error number if error occurs */
3223){
3224 int rc = 0; /* Value returned by system call */
3225
3226 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003227 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003228 nBuf &= 0x1ffff;
3229 TIMER_START;
3230
3231#if defined(USE_PREAD)
3232 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3233#elif defined(USE_PREAD64)
3234 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3235#else
3236 do{
3237 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3238 SimulateIOError( iSeek-- );
3239
3240 if( iSeek!=iOff ){
3241 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3242 return -1;
3243 }
3244 rc = osWrite(fd, pBuf, nBuf);
3245 }while( rc<0 && errno==EINTR );
3246#endif
3247
3248 TIMER_END;
3249 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3250
3251 if( rc<0 && piErrno ) *piErrno = errno;
3252 return rc;
3253}
3254
3255
3256/*
drh734c9862008-11-28 15:37:20 +00003257** Seek to the offset in id->offset then read cnt bytes into pBuf.
3258** Return the number of bytes actually read. Update the offset.
3259**
3260** To avoid stomping the errno value on a failed write the lastErrno value
3261** is set before returning.
3262*/
3263static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003264 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003265}
3266
3267
3268/*
3269** Write data from a buffer into a file. Return SQLITE_OK on success
3270** or some other error code on failure.
3271*/
3272static int unixWrite(
3273 sqlite3_file *id,
3274 const void *pBuf,
3275 int amt,
3276 sqlite3_int64 offset
3277){
dan08da86a2009-08-21 17:18:03 +00003278 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003279 int wrote = 0;
3280 assert( id );
3281 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003282
dan08da86a2009-08-21 17:18:03 +00003283 /* If this is a database file (not a journal, master-journal or temp
3284 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003285#if 0
dane946c392009-08-22 11:39:46 +00003286 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003287 || offset>=PENDING_BYTE+512
3288 || offset+amt<=PENDING_BYTE
3289 );
dan7c246102010-04-12 19:00:29 +00003290#endif
drh08c6d442009-02-09 17:34:07 +00003291
drhd3d8c042012-05-29 17:02:40 +00003292#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003293 /* If we are doing a normal write to a database file (as opposed to
3294 ** doing a hot-journal rollback or a write to some file other than a
3295 ** normal database file) then record the fact that the database
3296 ** has changed. If the transaction counter is modified, record that
3297 ** fact too.
3298 */
dan08da86a2009-08-21 17:18:03 +00003299 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003300 pFile->dbUpdate = 1; /* The database has been modified */
3301 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003302 int rc;
drh8f941bc2009-01-14 23:03:40 +00003303 char oldCntr[4];
3304 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003305 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003306 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003307 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003308 pFile->transCntrChng = 1; /* The transaction counter has changed */
3309 }
3310 }
3311 }
3312#endif
3313
drh9b4c59f2013-04-15 17:03:42 +00003314#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003315 /* Deal with as much of this write request as possible by transfering
3316 ** data from the memory mapping using memcpy(). */
3317 if( offset<pFile->mmapSize ){
3318 if( offset+amt <= pFile->mmapSize ){
3319 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3320 return SQLITE_OK;
3321 }else{
3322 int nCopy = pFile->mmapSize - offset;
3323 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3324 pBuf = &((u8 *)pBuf)[nCopy];
3325 amt -= nCopy;
3326 offset += nCopy;
3327 }
3328 }
drh6e0b6d52013-04-09 16:19:20 +00003329#endif
danf23da962013-03-23 21:00:41 +00003330
dan08da86a2009-08-21 17:18:03 +00003331 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003332 amt -= wrote;
3333 offset += wrote;
3334 pBuf = &((char*)pBuf)[wrote];
3335 }
3336 SimulateIOError(( wrote=(-1), amt=1 ));
3337 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003338
drh734c9862008-11-28 15:37:20 +00003339 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003340 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003341 /* lastErrno set by seekAndWrite */
3342 return SQLITE_IOERR_WRITE;
3343 }else{
dan08da86a2009-08-21 17:18:03 +00003344 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003345 return SQLITE_FULL;
3346 }
3347 }
dan6e09d692010-07-27 18:34:15 +00003348
drh734c9862008-11-28 15:37:20 +00003349 return SQLITE_OK;
3350}
3351
3352#ifdef SQLITE_TEST
3353/*
3354** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003355** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003356*/
3357int sqlite3_sync_count = 0;
3358int sqlite3_fullsync_count = 0;
3359#endif
3360
3361/*
drh89240432009-03-25 01:06:01 +00003362** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003363** Others do no. To be safe, we will stick with the (slightly slower)
3364** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003365** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003366*/
drh20f8e132011-08-31 21:01:55 +00003367#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003368# define fdatasync fsync
3369#endif
3370
3371/*
3372** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3373** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3374** only available on Mac OS X. But that could change.
3375*/
3376#ifdef F_FULLFSYNC
3377# define HAVE_FULLFSYNC 1
3378#else
3379# define HAVE_FULLFSYNC 0
3380#endif
3381
3382
3383/*
3384** The fsync() system call does not work as advertised on many
3385** unix systems. The following procedure is an attempt to make
3386** it work better.
3387**
3388** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3389** for testing when we want to run through the test suite quickly.
3390** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3391** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3392** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003393**
3394** SQLite sets the dataOnly flag if the size of the file is unchanged.
3395** The idea behind dataOnly is that it should only write the file content
3396** to disk, not the inode. We only set dataOnly if the file size is
3397** unchanged since the file size is part of the inode. However,
3398** Ted Ts'o tells us that fdatasync() will also write the inode if the
3399** file size has changed. The only real difference between fdatasync()
3400** and fsync(), Ted tells us, is that fdatasync() will not flush the
3401** inode if the mtime or owner or other inode attributes have changed.
3402** We only care about the file size, not the other file attributes, so
3403** as far as SQLite is concerned, an fdatasync() is always adequate.
3404** So, we always use fdatasync() if it is available, regardless of
3405** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003406*/
3407static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003408 int rc;
drh734c9862008-11-28 15:37:20 +00003409
3410 /* The following "ifdef/elif/else/" block has the same structure as
3411 ** the one below. It is replicated here solely to avoid cluttering
3412 ** up the real code with the UNUSED_PARAMETER() macros.
3413 */
3414#ifdef SQLITE_NO_SYNC
3415 UNUSED_PARAMETER(fd);
3416 UNUSED_PARAMETER(fullSync);
3417 UNUSED_PARAMETER(dataOnly);
3418#elif HAVE_FULLFSYNC
3419 UNUSED_PARAMETER(dataOnly);
3420#else
3421 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003422 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003423#endif
3424
3425 /* Record the number of times that we do a normal fsync() and
3426 ** FULLSYNC. This is used during testing to verify that this procedure
3427 ** gets called with the correct arguments.
3428 */
3429#ifdef SQLITE_TEST
3430 if( fullSync ) sqlite3_fullsync_count++;
3431 sqlite3_sync_count++;
3432#endif
3433
3434 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3435 ** no-op
3436 */
3437#ifdef SQLITE_NO_SYNC
3438 rc = SQLITE_OK;
3439#elif HAVE_FULLFSYNC
3440 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003441 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003442 }else{
3443 rc = 1;
3444 }
3445 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003446 ** It shouldn't be possible for fullfsync to fail on the local
3447 ** file system (on OSX), so failure indicates that FULLFSYNC
3448 ** isn't supported for this file system. So, attempt an fsync
3449 ** and (for now) ignore the overhead of a superfluous fcntl call.
3450 ** It'd be better to detect fullfsync support once and avoid
3451 ** the fcntl call every time sync is called.
3452 */
drh734c9862008-11-28 15:37:20 +00003453 if( rc ) rc = fsync(fd);
3454
drh7ed97b92010-01-20 13:07:21 +00003455#elif defined(__APPLE__)
3456 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3457 ** so currently we default to the macro that redefines fdatasync to fsync
3458 */
3459 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003460#else
drh0b647ff2009-03-21 14:41:04 +00003461 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003462#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003463 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003464 rc = fsync(fd);
3465 }
drh0b647ff2009-03-21 14:41:04 +00003466#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003467#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3468
3469 if( OS_VXWORKS && rc!= -1 ){
3470 rc = 0;
3471 }
chw97185482008-11-17 08:05:31 +00003472 return rc;
drhbfe66312006-10-03 17:40:40 +00003473}
3474
drh734c9862008-11-28 15:37:20 +00003475/*
drh0059eae2011-08-08 23:48:40 +00003476** Open a file descriptor to the directory containing file zFilename.
3477** If successful, *pFd is set to the opened file descriptor and
3478** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3479** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3480** value.
3481**
drh90315a22011-08-10 01:52:12 +00003482** The directory file descriptor is used for only one thing - to
3483** fsync() a directory to make sure file creation and deletion events
3484** are flushed to disk. Such fsyncs are not needed on newer
3485** journaling filesystems, but are required on older filesystems.
3486**
3487** This routine can be overridden using the xSetSysCall interface.
3488** The ability to override this routine was added in support of the
3489** chromium sandbox. Opening a directory is a security risk (we are
3490** told) so making it overrideable allows the chromium sandbox to
3491** replace this routine with a harmless no-op. To make this routine
3492** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3493** *pFd set to a negative number.
3494**
drh0059eae2011-08-08 23:48:40 +00003495** If SQLITE_OK is returned, the caller is responsible for closing
3496** the file descriptor *pFd using close().
3497*/
3498static int openDirectory(const char *zFilename, int *pFd){
3499 int ii;
3500 int fd = -1;
3501 char zDirname[MAX_PATHNAME+1];
3502
3503 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3504 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3505 if( ii>0 ){
3506 zDirname[ii] = '\0';
3507 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3508 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003509 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3510 }
3511 }
3512 *pFd = fd;
3513 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3514}
3515
3516/*
drh734c9862008-11-28 15:37:20 +00003517** Make sure all writes to a particular file are committed to disk.
3518**
3519** If dataOnly==0 then both the file itself and its metadata (file
3520** size, access time, etc) are synced. If dataOnly!=0 then only the
3521** file data is synced.
3522**
3523** Under Unix, also make sure that the directory entry for the file
3524** has been created by fsync-ing the directory that contains the file.
3525** If we do not do this and we encounter a power failure, the directory
3526** entry for the journal might not exist after we reboot. The next
3527** SQLite to access the file will not know that the journal exists (because
3528** the directory entry for the journal was never created) and the transaction
3529** will not roll back - possibly leading to database corruption.
3530*/
3531static int unixSync(sqlite3_file *id, int flags){
3532 int rc;
3533 unixFile *pFile = (unixFile*)id;
3534
3535 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3536 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3537
3538 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3539 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3540 || (flags&0x0F)==SQLITE_SYNC_FULL
3541 );
3542
3543 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3544 ** line is to test that doing so does not cause any problems.
3545 */
3546 SimulateDiskfullError( return SQLITE_FULL );
3547
3548 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003549 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003550 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3551 SimulateIOError( rc=1 );
3552 if( rc ){
3553 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003554 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003555 }
drh0059eae2011-08-08 23:48:40 +00003556
3557 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003558 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003559 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003560 */
3561 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3562 int dirfd;
3563 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003564 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003565 rc = osOpenDirectory(pFile->zPath, &dirfd);
3566 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003567 full_fsync(dirfd, 0, 0);
3568 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003569 }else if( rc==SQLITE_CANTOPEN ){
3570 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003571 }
drh0059eae2011-08-08 23:48:40 +00003572 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003573 }
3574 return rc;
3575}
3576
3577/*
3578** Truncate an open file to a specified size
3579*/
3580static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003581 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003582 int rc;
dan6e09d692010-07-27 18:34:15 +00003583 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003584 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003585
3586 /* If the user has configured a chunk-size for this file, truncate the
3587 ** file so that it consists of an integer number of chunks (i.e. the
3588 ** actual file size after the operation may be larger than the requested
3589 ** size).
3590 */
drhb8af4b72012-04-05 20:04:39 +00003591 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003592 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3593 }
3594
drhff812312011-02-23 13:33:46 +00003595 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003596 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003597 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003598 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003599 }else{
drhd3d8c042012-05-29 17:02:40 +00003600#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003601 /* If we are doing a normal write to a database file (as opposed to
3602 ** doing a hot-journal rollback or a write to some file other than a
3603 ** normal database file) and we truncate the file to zero length,
3604 ** that effectively updates the change counter. This might happen
3605 ** when restoring a database using the backup API from a zero-length
3606 ** source.
3607 */
dan6e09d692010-07-27 18:34:15 +00003608 if( pFile->inNormalWrite && nByte==0 ){
3609 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003610 }
danf23da962013-03-23 21:00:41 +00003611#endif
danc0003312013-03-22 17:46:11 +00003612
mistachkine98844f2013-08-24 00:59:24 +00003613#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003614 /* If the file was just truncated to a size smaller than the currently
3615 ** mapped region, reduce the effective mapping size as well. SQLite will
3616 ** use read() and write() to access data beyond this point from now on.
3617 */
3618 if( nByte<pFile->mmapSize ){
3619 pFile->mmapSize = nByte;
3620 }
mistachkine98844f2013-08-24 00:59:24 +00003621#endif
drh3313b142009-11-06 04:13:18 +00003622
drh734c9862008-11-28 15:37:20 +00003623 return SQLITE_OK;
3624 }
3625}
3626
3627/*
3628** Determine the current size of a file in bytes
3629*/
3630static int unixFileSize(sqlite3_file *id, i64 *pSize){
3631 int rc;
3632 struct stat buf;
3633 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003634 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003635 SimulateIOError( rc=1 );
3636 if( rc!=0 ){
3637 ((unixFile*)id)->lastErrno = errno;
3638 return SQLITE_IOERR_FSTAT;
3639 }
3640 *pSize = buf.st_size;
3641
drh8af6c222010-05-14 12:43:01 +00003642 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003643 ** writes a single byte into that file in order to work around a bug
3644 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3645 ** layers, we need to report this file size as zero even though it is
3646 ** really 1. Ticket #3260.
3647 */
3648 if( *pSize==1 ) *pSize = 0;
3649
3650
3651 return SQLITE_OK;
3652}
3653
drhd2cb50b2009-01-09 21:41:17 +00003654#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003655/*
3656** Handler for proxy-locking file-control verbs. Defined below in the
3657** proxying locking division.
3658*/
3659static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003660#endif
drh715ff302008-12-03 22:32:44 +00003661
dan502019c2010-07-28 14:26:17 +00003662/*
3663** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003664** file-control operation. Enlarge the database to nBytes in size
3665** (rounded up to the next chunk-size). If the database is already
3666** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003667*/
3668static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003669 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003670 i64 nSize; /* Required file size */
3671 struct stat buf; /* Used to hold return values of fstat() */
3672
drh99ab3b12011-03-02 15:09:07 +00003673 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003674
3675 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3676 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003677
dan502019c2010-07-28 14:26:17 +00003678#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003679 /* The code below is handling the return value of osFallocate()
3680 ** correctly. posix_fallocate() is defined to "returns zero on success,
3681 ** or an error number on failure". See the manpage for details. */
3682 int err;
drhff812312011-02-23 13:33:46 +00003683 do{
dan661d71a2011-03-30 19:08:03 +00003684 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3685 }while( err==EINTR );
3686 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003687#else
3688 /* If the OS does not have posix_fallocate(), fake it. First use
3689 ** ftruncate() to set the file size, then write a single byte to
3690 ** the last byte in each block within the extended region. This
3691 ** is the same technique used by glibc to implement posix_fallocate()
3692 ** on systems that do not have a real fallocate() system call.
3693 */
3694 int nBlk = buf.st_blksize; /* File-system block size */
3695 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003696
drhff812312011-02-23 13:33:46 +00003697 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003698 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003699 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003700 }
3701 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003702 while( iWrite<nSize ){
3703 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3704 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003705 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003706 }
dan502019c2010-07-28 14:26:17 +00003707#endif
3708 }
3709 }
3710
mistachkine98844f2013-08-24 00:59:24 +00003711#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003712 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003713 int rc;
3714 if( pFile->szChunk<=0 ){
3715 if( robust_ftruncate(pFile->h, nByte) ){
3716 pFile->lastErrno = errno;
3717 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3718 }
3719 }
3720
3721 rc = unixMapfile(pFile, nByte);
3722 return rc;
3723 }
mistachkine98844f2013-08-24 00:59:24 +00003724#endif
danf23da962013-03-23 21:00:41 +00003725
dan502019c2010-07-28 14:26:17 +00003726 return SQLITE_OK;
3727}
danielk1977ad94b582007-08-20 06:44:22 +00003728
danielk1977e3026632004-06-22 11:29:02 +00003729/*
drhf12b3f62011-12-21 14:42:29 +00003730** If *pArg is inititially negative then this is a query. Set *pArg to
3731** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3732**
3733** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3734*/
3735static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3736 if( *pArg<0 ){
3737 *pArg = (pFile->ctrlFlags & mask)!=0;
3738 }else if( (*pArg)==0 ){
3739 pFile->ctrlFlags &= ~mask;
3740 }else{
3741 pFile->ctrlFlags |= mask;
3742 }
3743}
3744
drh696b33e2012-12-06 19:01:42 +00003745/* Forward declaration */
3746static int unixGetTempname(int nBuf, char *zBuf);
3747
drhf12b3f62011-12-21 14:42:29 +00003748/*
drh9e33c2c2007-08-31 18:34:59 +00003749** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003750*/
drhcc6bb3e2007-08-31 16:11:35 +00003751static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003752 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003753 switch( op ){
3754 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003755 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003756 return SQLITE_OK;
3757 }
drh7708e972008-11-29 00:56:52 +00003758 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003759 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003760 return SQLITE_OK;
3761 }
dan6e09d692010-07-27 18:34:15 +00003762 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003763 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003764 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003765 }
drh9ff27ec2010-05-19 19:26:05 +00003766 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003767 int rc;
3768 SimulateIOErrorBenign(1);
3769 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3770 SimulateIOErrorBenign(0);
3771 return rc;
drhf0b190d2011-07-26 16:03:07 +00003772 }
3773 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003774 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3775 return SQLITE_OK;
3776 }
drhcb15f352011-12-23 01:04:17 +00003777 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3778 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003779 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003780 }
drhde60fc22011-12-14 17:53:36 +00003781 case SQLITE_FCNTL_VFSNAME: {
3782 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3783 return SQLITE_OK;
3784 }
drh696b33e2012-12-06 19:01:42 +00003785 case SQLITE_FCNTL_TEMPFILENAME: {
3786 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3787 if( zTFile ){
3788 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3789 *(char**)pArg = zTFile;
3790 }
3791 return SQLITE_OK;
3792 }
mistachkine98844f2013-08-24 00:59:24 +00003793#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003794 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003795 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003796 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003797 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3798 newLimit = sqlite3GlobalConfig.mxMmap;
3799 }
3800 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003801 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003802 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003803 if( pFile->mmapSize>0 ){
3804 unixUnmapfile(pFile);
3805 rc = unixMapfile(pFile, -1);
3806 }
danbcb8a862013-04-08 15:30:41 +00003807 }
drh34e258c2013-05-23 01:40:53 +00003808 return rc;
danb2d3de32013-03-14 18:34:37 +00003809 }
mistachkine98844f2013-08-24 00:59:24 +00003810#endif
drhd3d8c042012-05-29 17:02:40 +00003811#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003812 /* The pager calls this method to signal that it has done
3813 ** a rollback and that the database is therefore unchanged and
3814 ** it hence it is OK for the transaction change counter to be
3815 ** unchanged.
3816 */
3817 case SQLITE_FCNTL_DB_UNCHANGED: {
3818 ((unixFile*)id)->dbUpdate = 0;
3819 return SQLITE_OK;
3820 }
3821#endif
drhd2cb50b2009-01-09 21:41:17 +00003822#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003823 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003824 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003825 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003826 }
drhd2cb50b2009-01-09 21:41:17 +00003827#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003828 }
drh0b52b7d2011-01-26 19:46:22 +00003829 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003830}
3831
3832/*
danielk1977a3d4c882007-03-23 10:08:38 +00003833** Return the sector size in bytes of the underlying block device for
3834** the specified file. This is almost always 512 bytes, but may be
3835** larger for some devices.
3836**
3837** SQLite code assumes this function cannot fail. It also assumes that
3838** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003839** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003840** same for both.
3841*/
drh537dddf2012-10-26 13:46:24 +00003842#ifndef __QNXNTO__
3843static int unixSectorSize(sqlite3_file *NotUsed){
3844 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003845 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003846}
drh537dddf2012-10-26 13:46:24 +00003847#endif
3848
3849/*
3850** The following version of unixSectorSize() is optimized for QNX.
3851*/
3852#ifdef __QNXNTO__
3853#include <sys/dcmd_blk.h>
3854#include <sys/statvfs.h>
3855static int unixSectorSize(sqlite3_file *id){
3856 unixFile *pFile = (unixFile*)id;
3857 if( pFile->sectorSize == 0 ){
3858 struct statvfs fsInfo;
3859
3860 /* Set defaults for non-supported filesystems */
3861 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3862 pFile->deviceCharacteristics = 0;
3863 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3864 return pFile->sectorSize;
3865 }
3866
3867 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3868 pFile->sectorSize = fsInfo.f_bsize;
3869 pFile->deviceCharacteristics =
3870 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3871 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3872 ** the write succeeds */
3873 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3874 ** so it is ordered */
3875 0;
3876 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3877 pFile->sectorSize = fsInfo.f_bsize;
3878 pFile->deviceCharacteristics =
3879 /* etfs cluster size writes are atomic */
3880 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3881 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3882 ** the write succeeds */
3883 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3884 ** so it is ordered */
3885 0;
3886 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3887 pFile->sectorSize = fsInfo.f_bsize;
3888 pFile->deviceCharacteristics =
3889 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3890 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3891 ** the write succeeds */
3892 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3893 ** so it is ordered */
3894 0;
3895 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3896 pFile->sectorSize = fsInfo.f_bsize;
3897 pFile->deviceCharacteristics =
3898 /* full bitset of atomics from max sector size and smaller */
3899 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3900 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3901 ** so it is ordered */
3902 0;
3903 }else if( strstr(fsInfo.f_basetype, "dos") ){
3904 pFile->sectorSize = fsInfo.f_bsize;
3905 pFile->deviceCharacteristics =
3906 /* full bitset of atomics from max sector size and smaller */
3907 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3908 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3909 ** so it is ordered */
3910 0;
3911 }else{
3912 pFile->deviceCharacteristics =
3913 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3914 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3915 ** the write succeeds */
3916 0;
3917 }
3918 }
3919 /* Last chance verification. If the sector size isn't a multiple of 512
3920 ** then it isn't valid.*/
3921 if( pFile->sectorSize % 512 != 0 ){
3922 pFile->deviceCharacteristics = 0;
3923 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3924 }
3925 return pFile->sectorSize;
3926}
3927#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003928
danielk197790949c22007-08-17 16:50:38 +00003929/*
drhf12b3f62011-12-21 14:42:29 +00003930** Return the device characteristics for the file.
3931**
drhcb15f352011-12-23 01:04:17 +00003932** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3933** However, that choice is contraversial since technically the underlying
3934** file system does not always provide powersafe overwrites. (In other
3935** words, after a power-loss event, parts of the file that were never
3936** written might end up being altered.) However, non-PSOW behavior is very,
3937** very rare. And asserting PSOW makes a large reduction in the amount
3938** of required I/O for journaling, since a lot of padding is eliminated.
3939** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3940** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003941*/
drhf12b3f62011-12-21 14:42:29 +00003942static int unixDeviceCharacteristics(sqlite3_file *id){
3943 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003944 int rc = 0;
3945#ifdef __QNXNTO__
3946 if( p->sectorSize==0 ) unixSectorSize(id);
3947 rc = p->deviceCharacteristics;
3948#endif
drhcb15f352011-12-23 01:04:17 +00003949 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003950 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003951 }
drh537dddf2012-10-26 13:46:24 +00003952 return rc;
danielk197762079062007-08-15 17:08:46 +00003953}
3954
drhd9e5c4f2010-05-12 18:01:39 +00003955#ifndef SQLITE_OMIT_WAL
3956
3957
3958/*
drhd91c68f2010-05-14 14:52:25 +00003959** Object used to represent an shared memory buffer.
3960**
3961** When multiple threads all reference the same wal-index, each thread
3962** has its own unixShm object, but they all point to a single instance
3963** of this unixShmNode object. In other words, each wal-index is opened
3964** only once per process.
3965**
3966** Each unixShmNode object is connected to a single unixInodeInfo object.
3967** We could coalesce this object into unixInodeInfo, but that would mean
3968** every open file that does not use shared memory (in other words, most
3969** open files) would have to carry around this extra information. So
3970** the unixInodeInfo object contains a pointer to this unixShmNode object
3971** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003972**
3973** unixMutexHeld() must be true when creating or destroying
3974** this object or while reading or writing the following fields:
3975**
3976** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003977**
3978** The following fields are read-only after the object is created:
3979**
3980** fid
3981** zFilename
3982**
drhd91c68f2010-05-14 14:52:25 +00003983** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003984** unixMutexHeld() is true when reading or writing any other field
3985** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003986*/
drhd91c68f2010-05-14 14:52:25 +00003987struct unixShmNode {
3988 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003989 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003990 char *zFilename; /* Name of the mmapped file */
3991 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003992 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003993 u16 nRegion; /* Size of array apRegion */
3994 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003995 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003996 int nRef; /* Number of unixShm objects pointing to this */
3997 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003998#ifdef SQLITE_DEBUG
3999 u8 exclMask; /* Mask of exclusive locks held */
4000 u8 sharedMask; /* Mask of shared locks held */
4001 u8 nextShmId; /* Next available unixShm.id value */
4002#endif
4003};
4004
4005/*
drhd9e5c4f2010-05-12 18:01:39 +00004006** Structure used internally by this VFS to record the state of an
4007** open shared memory connection.
4008**
drhd91c68f2010-05-14 14:52:25 +00004009** The following fields are initialized when this object is created and
4010** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004011**
drhd91c68f2010-05-14 14:52:25 +00004012** unixShm.pFile
4013** unixShm.id
4014**
4015** All other fields are read/write. The unixShm.pFile->mutex must be held
4016** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004017*/
4018struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004019 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4020 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004021 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004022 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004023 u16 sharedMask; /* Mask of shared locks held */
4024 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004025};
4026
4027/*
drhd9e5c4f2010-05-12 18:01:39 +00004028** Constants used for locking
4029*/
drhbd9676c2010-06-23 17:58:38 +00004030#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004031#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004032
drhd9e5c4f2010-05-12 18:01:39 +00004033/*
drh73b64e42010-05-30 19:55:15 +00004034** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004035**
4036** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4037** otherwise.
4038*/
4039static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004040 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4041 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004042 int ofst, /* First byte of the locking range */
4043 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004044){
4045 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004046 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004047
drhd91c68f2010-05-14 14:52:25 +00004048 /* Access to the unixShmNode object is serialized by the caller */
4049 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004050
drh73b64e42010-05-30 19:55:15 +00004051 /* Shared locks never span more than one byte */
4052 assert( n==1 || lockType!=F_RDLCK );
4053
4054 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004055 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004056
drh3cb93392011-03-12 18:10:44 +00004057 if( pShmNode->h>=0 ){
4058 /* Initialize the locking parameters */
4059 memset(&f, 0, sizeof(f));
4060 f.l_type = lockType;
4061 f.l_whence = SEEK_SET;
4062 f.l_start = ofst;
4063 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004064
drh3cb93392011-03-12 18:10:44 +00004065 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4066 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4067 }
drhd9e5c4f2010-05-12 18:01:39 +00004068
4069 /* Update the global lock state and do debug tracing */
4070#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004071 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004072 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00004073 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004074 if( rc==SQLITE_OK ){
4075 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004076 OSTRACE(("unlock %d ok", ofst));
4077 pShmNode->exclMask &= ~mask;
4078 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004079 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004080 OSTRACE(("read-lock %d ok", ofst));
4081 pShmNode->exclMask &= ~mask;
4082 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004083 }else{
4084 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004085 OSTRACE(("write-lock %d ok", ofst));
4086 pShmNode->exclMask |= mask;
4087 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004088 }
4089 }else{
4090 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004091 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004092 }else if( lockType==F_RDLCK ){
4093 OSTRACE(("read-lock failed"));
4094 }else{
4095 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004096 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004097 }
4098 }
drh20e1f082010-05-31 16:10:12 +00004099 OSTRACE((" - afterwards %03x,%03x\n",
4100 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004101 }
drhd9e5c4f2010-05-12 18:01:39 +00004102#endif
4103
4104 return rc;
4105}
4106
drhd9e5c4f2010-05-12 18:01:39 +00004107
4108/*
drhd91c68f2010-05-14 14:52:25 +00004109** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004110**
4111** This is not a VFS shared-memory method; it is a utility function called
4112** by VFS shared-memory methods.
4113*/
drhd91c68f2010-05-14 14:52:25 +00004114static void unixShmPurge(unixFile *pFd){
4115 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004116 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004117 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00004118 int i;
drhd91c68f2010-05-14 14:52:25 +00004119 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004120 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00004121 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00004122 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004123 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004124 }else{
4125 sqlite3_free(p->apRegion[i]);
4126 }
dan13a3cb82010-06-11 19:04:21 +00004127 }
dan18801912010-06-14 14:07:50 +00004128 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004129 if( p->h>=0 ){
4130 robust_close(pFd, p->h, __LINE__);
4131 p->h = -1;
4132 }
drhd91c68f2010-05-14 14:52:25 +00004133 p->pInode->pShmNode = 0;
4134 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004135 }
4136}
4137
4138/*
danda9fe0c2010-07-13 18:44:03 +00004139** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004140** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004141**
drh7234c6d2010-06-19 15:10:09 +00004142** The file used to implement shared-memory is in the same directory
4143** as the open database file and has the same name as the open database
4144** file with the "-shm" suffix added. For example, if the database file
4145** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004146** for shared memory will be called "/home/user1/config.db-shm".
4147**
4148** Another approach to is to use files in /dev/shm or /dev/tmp or an
4149** some other tmpfs mount. But if a file in a different directory
4150** from the database file is used, then differing access permissions
4151** or a chroot() might cause two different processes on the same
4152** database to end up using different files for shared memory -
4153** meaning that their memory would not really be shared - resulting
4154** in database corruption. Nevertheless, this tmpfs file usage
4155** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4156** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4157** option results in an incompatible build of SQLite; builds of SQLite
4158** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4159** same database file at the same time, database corruption will likely
4160** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4161** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004162**
4163** When opening a new shared-memory file, if no other instances of that
4164** file are currently open, in this process or in other processes, then
4165** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004166**
4167** If the original database file (pDbFd) is using the "unix-excl" VFS
4168** that means that an exclusive lock is held on the database file and
4169** that no other processes are able to read or write the database. In
4170** that case, we do not really need shared memory. No shared memory
4171** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004172*/
danda9fe0c2010-07-13 18:44:03 +00004173static int unixOpenSharedMemory(unixFile *pDbFd){
4174 struct unixShm *p = 0; /* The connection to be opened */
4175 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4176 int rc; /* Result code */
4177 unixInodeInfo *pInode; /* The inode of fd */
4178 char *zShmFilename; /* Name of the file used for SHM */
4179 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004180
danda9fe0c2010-07-13 18:44:03 +00004181 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004182 p = sqlite3_malloc( sizeof(*p) );
4183 if( p==0 ) return SQLITE_NOMEM;
4184 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004185 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004186
danda9fe0c2010-07-13 18:44:03 +00004187 /* Check to see if a unixShmNode object already exists. Reuse an existing
4188 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004189 */
4190 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004191 pInode = pDbFd->pInode;
4192 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004193 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004194 struct stat sStat; /* fstat() info for database file */
4195
4196 /* Call fstat() to figure out the permissions on the database file. If
4197 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004198 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004199 */
drh3cb93392011-03-12 18:10:44 +00004200 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004201 rc = SQLITE_IOERR_FSTAT;
4202 goto shm_open_err;
4203 }
4204
drha4ced192010-07-15 18:32:40 +00004205#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004206 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004207#else
drh52bcde02012-01-03 14:50:45 +00004208 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004209#endif
drh7234c6d2010-06-19 15:10:09 +00004210 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004211 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004212 rc = SQLITE_NOMEM;
4213 goto shm_open_err;
4214 }
drh9cb5a0d2012-01-05 21:19:54 +00004215 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004216 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004217#ifdef SQLITE_SHM_DIRECTORY
4218 sqlite3_snprintf(nShmFilename, zShmFilename,
4219 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4220 (u32)sStat.st_ino, (u32)sStat.st_dev);
4221#else
drh7234c6d2010-06-19 15:10:09 +00004222 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004223 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004224#endif
drhd91c68f2010-05-14 14:52:25 +00004225 pShmNode->h = -1;
4226 pDbFd->pInode->pShmNode = pShmNode;
4227 pShmNode->pInode = pDbFd->pInode;
4228 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4229 if( pShmNode->mutex==0 ){
4230 rc = SQLITE_NOMEM;
4231 goto shm_open_err;
4232 }
drhd9e5c4f2010-05-12 18:01:39 +00004233
drh3cb93392011-03-12 18:10:44 +00004234 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004235 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004236 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004237 openFlags = O_RDONLY;
4238 pShmNode->isReadonly = 1;
4239 }
4240 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004241 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004242 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4243 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004244 }
drhac7c3ac2012-02-11 19:23:48 +00004245
4246 /* If this process is running as root, make sure that the SHM file
4247 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004248 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004249 */
drhed466822012-05-31 13:10:49 +00004250 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004251
4252 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004253 ** If not, truncate the file to zero length.
4254 */
4255 rc = SQLITE_OK;
4256 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4257 if( robust_ftruncate(pShmNode->h, 0) ){
4258 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004259 }
4260 }
drh66dfec8b2011-06-01 20:01:49 +00004261 if( rc==SQLITE_OK ){
4262 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4263 }
4264 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004265 }
drhd9e5c4f2010-05-12 18:01:39 +00004266 }
4267
drhd91c68f2010-05-14 14:52:25 +00004268 /* Make the new connection a child of the unixShmNode */
4269 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004270#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004271 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004272#endif
drhd91c68f2010-05-14 14:52:25 +00004273 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004274 pDbFd->pShm = p;
4275 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004276
4277 /* The reference count on pShmNode has already been incremented under
4278 ** the cover of the unixEnterMutex() mutex and the pointer from the
4279 ** new (struct unixShm) object to the pShmNode has been set. All that is
4280 ** left to do is to link the new object into the linked list starting
4281 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4282 ** mutex.
4283 */
4284 sqlite3_mutex_enter(pShmNode->mutex);
4285 p->pNext = pShmNode->pFirst;
4286 pShmNode->pFirst = p;
4287 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004288 return SQLITE_OK;
4289
4290 /* Jump here on any error */
4291shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004292 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004293 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004294 unixLeaveMutex();
4295 return rc;
4296}
4297
4298/*
danda9fe0c2010-07-13 18:44:03 +00004299** This function is called to obtain a pointer to region iRegion of the
4300** shared-memory associated with the database file fd. Shared-memory regions
4301** are numbered starting from zero. Each shared-memory region is szRegion
4302** bytes in size.
4303**
4304** If an error occurs, an error code is returned and *pp is set to NULL.
4305**
4306** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4307** region has not been allocated (by any client, including one running in a
4308** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4309** bExtend is non-zero and the requested shared-memory region has not yet
4310** been allocated, it is allocated by this function.
4311**
4312** If the shared-memory region has already been allocated or is allocated by
4313** this call as described above, then it is mapped into this processes
4314** address space (if it is not already), *pp is set to point to the mapped
4315** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004316*/
danda9fe0c2010-07-13 18:44:03 +00004317static int unixShmMap(
4318 sqlite3_file *fd, /* Handle open on database file */
4319 int iRegion, /* Region to retrieve */
4320 int szRegion, /* Size of regions */
4321 int bExtend, /* True to extend file if necessary */
4322 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004323){
danda9fe0c2010-07-13 18:44:03 +00004324 unixFile *pDbFd = (unixFile*)fd;
4325 unixShm *p;
4326 unixShmNode *pShmNode;
4327 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004328
danda9fe0c2010-07-13 18:44:03 +00004329 /* If the shared-memory file has not yet been opened, open it now. */
4330 if( pDbFd->pShm==0 ){
4331 rc = unixOpenSharedMemory(pDbFd);
4332 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004333 }
drhd9e5c4f2010-05-12 18:01:39 +00004334
danda9fe0c2010-07-13 18:44:03 +00004335 p = pDbFd->pShm;
4336 pShmNode = p->pShmNode;
4337 sqlite3_mutex_enter(pShmNode->mutex);
4338 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004339 assert( pShmNode->pInode==pDbFd->pInode );
4340 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4341 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004342
4343 if( pShmNode->nRegion<=iRegion ){
4344 char **apNew; /* New apRegion[] array */
4345 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4346 struct stat sStat; /* Used by fstat() */
4347
4348 pShmNode->szRegion = szRegion;
4349
drh3cb93392011-03-12 18:10:44 +00004350 if( pShmNode->h>=0 ){
4351 /* The requested region is not mapped into this processes address space.
4352 ** Check to see if it has been allocated (i.e. if the wal-index file is
4353 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004354 */
drh3cb93392011-03-12 18:10:44 +00004355 if( osFstat(pShmNode->h, &sStat) ){
4356 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004357 goto shmpage_out;
4358 }
drh3cb93392011-03-12 18:10:44 +00004359
4360 if( sStat.st_size<nByte ){
4361 /* The requested memory region does not exist. If bExtend is set to
4362 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004363 */
dan47a2b4a2013-04-26 16:09:29 +00004364 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004365 goto shmpage_out;
4366 }
dan47a2b4a2013-04-26 16:09:29 +00004367
4368 /* Alternatively, if bExtend is true, extend the file. Do this by
4369 ** writing a single byte to the end of each (OS) page being
4370 ** allocated or extended. Technically, we need only write to the
4371 ** last page in order to extend the file. But writing to all new
4372 ** pages forces the OS to allocate them immediately, which reduces
4373 ** the chances of SIGBUS while accessing the mapped region later on.
4374 */
4375 else{
4376 static const int pgsz = 4096;
4377 int iPg;
4378
4379 /* Write to the last byte of each newly allocated or extended page */
4380 assert( (nByte % pgsz)==0 );
4381 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4382 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4383 const char *zFile = pShmNode->zFilename;
4384 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4385 goto shmpage_out;
4386 }
4387 }
drh3cb93392011-03-12 18:10:44 +00004388 }
4389 }
danda9fe0c2010-07-13 18:44:03 +00004390 }
4391
4392 /* Map the requested memory region into this processes address space. */
4393 apNew = (char **)sqlite3_realloc(
4394 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4395 );
4396 if( !apNew ){
4397 rc = SQLITE_IOERR_NOMEM;
4398 goto shmpage_out;
4399 }
4400 pShmNode->apRegion = apNew;
4401 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004402 void *pMem;
4403 if( pShmNode->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004404 pMem = osMmap(0, szRegion,
drh66dfec8b2011-06-01 20:01:49 +00004405 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004406 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004407 );
4408 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004409 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004410 goto shmpage_out;
4411 }
4412 }else{
4413 pMem = sqlite3_malloc(szRegion);
4414 if( pMem==0 ){
4415 rc = SQLITE_NOMEM;
4416 goto shmpage_out;
4417 }
4418 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004419 }
4420 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4421 pShmNode->nRegion++;
4422 }
4423 }
4424
4425shmpage_out:
4426 if( pShmNode->nRegion>iRegion ){
4427 *pp = pShmNode->apRegion[iRegion];
4428 }else{
4429 *pp = 0;
4430 }
drh66dfec8b2011-06-01 20:01:49 +00004431 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004432 sqlite3_mutex_leave(pShmNode->mutex);
4433 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004434}
4435
4436/*
drhd9e5c4f2010-05-12 18:01:39 +00004437** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004438**
4439** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4440** different here than in posix. In xShmLock(), one can go from unlocked
4441** to shared and back or from unlocked to exclusive and back. But one may
4442** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004443*/
4444static int unixShmLock(
4445 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004446 int ofst, /* First lock to acquire or release */
4447 int n, /* Number of locks to acquire or release */
4448 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004449){
drh73b64e42010-05-30 19:55:15 +00004450 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4451 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4452 unixShm *pX; /* For looping over all siblings */
4453 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4454 int rc = SQLITE_OK; /* Result code */
4455 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004456
drhd91c68f2010-05-14 14:52:25 +00004457 assert( pShmNode==pDbFd->pInode->pShmNode );
4458 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004459 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004460 assert( n>=1 );
4461 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4462 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4463 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4464 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4465 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004466 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4467 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004468
drhc99597c2010-05-31 01:41:15 +00004469 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004470 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004471 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004472 if( flags & SQLITE_SHM_UNLOCK ){
4473 u16 allMask = 0; /* Mask of locks held by siblings */
4474
4475 /* See if any siblings hold this same lock */
4476 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4477 if( pX==p ) continue;
4478 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4479 allMask |= pX->sharedMask;
4480 }
4481
4482 /* Unlock the system-level locks */
4483 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004484 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004485 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004486 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004487 }
drh73b64e42010-05-30 19:55:15 +00004488
4489 /* Undo the local locks */
4490 if( rc==SQLITE_OK ){
4491 p->exclMask &= ~mask;
4492 p->sharedMask &= ~mask;
4493 }
4494 }else if( flags & SQLITE_SHM_SHARED ){
4495 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4496
4497 /* Find out which shared locks are already held by sibling connections.
4498 ** If any sibling already holds an exclusive lock, go ahead and return
4499 ** SQLITE_BUSY.
4500 */
4501 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004502 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004503 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004504 break;
4505 }
4506 allShared |= pX->sharedMask;
4507 }
4508
4509 /* Get shared locks at the system level, if necessary */
4510 if( rc==SQLITE_OK ){
4511 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004512 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004513 }else{
drh73b64e42010-05-30 19:55:15 +00004514 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004515 }
drhd9e5c4f2010-05-12 18:01:39 +00004516 }
drh73b64e42010-05-30 19:55:15 +00004517
4518 /* Get the local shared locks */
4519 if( rc==SQLITE_OK ){
4520 p->sharedMask |= mask;
4521 }
4522 }else{
4523 /* Make sure no sibling connections hold locks that will block this
4524 ** lock. If any do, return SQLITE_BUSY right away.
4525 */
4526 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004527 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4528 rc = SQLITE_BUSY;
4529 break;
4530 }
4531 }
4532
4533 /* Get the exclusive locks at the system level. Then if successful
4534 ** also mark the local connection as being locked.
4535 */
4536 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004537 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004538 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004539 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004540 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004541 }
drhd9e5c4f2010-05-12 18:01:39 +00004542 }
4543 }
drhd91c68f2010-05-14 14:52:25 +00004544 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004545 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4546 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004547 return rc;
4548}
4549
drh286a2882010-05-20 23:51:06 +00004550/*
4551** Implement a memory barrier or memory fence on shared memory.
4552**
4553** All loads and stores begun before the barrier must complete before
4554** any load or store begun after the barrier.
4555*/
4556static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004557 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004558){
drhff828942010-06-26 21:34:06 +00004559 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004560 unixEnterMutex();
4561 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004562}
4563
dan18801912010-06-14 14:07:50 +00004564/*
danda9fe0c2010-07-13 18:44:03 +00004565** Close a connection to shared-memory. Delete the underlying
4566** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004567**
4568** If there is no shared memory associated with the connection then this
4569** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004570*/
danda9fe0c2010-07-13 18:44:03 +00004571static int unixShmUnmap(
4572 sqlite3_file *fd, /* The underlying database file */
4573 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004574){
danda9fe0c2010-07-13 18:44:03 +00004575 unixShm *p; /* The connection to be closed */
4576 unixShmNode *pShmNode; /* The underlying shared-memory file */
4577 unixShm **pp; /* For looping over sibling connections */
4578 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004579
danda9fe0c2010-07-13 18:44:03 +00004580 pDbFd = (unixFile*)fd;
4581 p = pDbFd->pShm;
4582 if( p==0 ) return SQLITE_OK;
4583 pShmNode = p->pShmNode;
4584
4585 assert( pShmNode==pDbFd->pInode->pShmNode );
4586 assert( pShmNode->pInode==pDbFd->pInode );
4587
4588 /* Remove connection p from the set of connections associated
4589 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004590 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004591 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4592 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004593
danda9fe0c2010-07-13 18:44:03 +00004594 /* Free the connection p */
4595 sqlite3_free(p);
4596 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004597 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004598
4599 /* If pShmNode->nRef has reached 0, then close the underlying
4600 ** shared-memory file, too */
4601 unixEnterMutex();
4602 assert( pShmNode->nRef>0 );
4603 pShmNode->nRef--;
4604 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004605 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004606 unixShmPurge(pDbFd);
4607 }
4608 unixLeaveMutex();
4609
4610 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004611}
drh286a2882010-05-20 23:51:06 +00004612
danda9fe0c2010-07-13 18:44:03 +00004613
drhd9e5c4f2010-05-12 18:01:39 +00004614#else
drh6b017cc2010-06-14 18:01:46 +00004615# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004616# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004617# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004618# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004619#endif /* #ifndef SQLITE_OMIT_WAL */
4620
mistachkine98844f2013-08-24 00:59:24 +00004621#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004622/*
danaef49d72013-03-25 16:28:54 +00004623** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004624*/
danf23da962013-03-23 21:00:41 +00004625static void unixUnmapfile(unixFile *pFd){
4626 assert( pFd->nFetchOut==0 );
4627 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004628 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004629 pFd->pMapRegion = 0;
4630 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004631 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004632 }
4633}
dan5d8a1372013-03-19 19:28:06 +00004634
danaef49d72013-03-25 16:28:54 +00004635/*
dane6ecd662013-04-01 17:56:59 +00004636** Return the system page size.
4637*/
4638static int unixGetPagesize(void){
4639#if HAVE_MREMAP
4640 return 512;
drh85830a72013-04-03 00:42:01 +00004641#elif defined(_BSD_SOURCE)
dane6ecd662013-04-01 17:56:59 +00004642 return getpagesize();
4643#else
4644 return (int)sysconf(_SC_PAGESIZE);
4645#endif
4646}
4647
4648/*
4649** Attempt to set the size of the memory mapping maintained by file
4650** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4651**
4652** If successful, this function sets the following variables:
4653**
4654** unixFile.pMapRegion
4655** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004656** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004657**
4658** If unsuccessful, an error message is logged via sqlite3_log() and
4659** the three variables above are zeroed. In this case SQLite should
4660** continue accessing the database using the xRead() and xWrite()
4661** methods.
4662*/
4663static void unixRemapfile(
4664 unixFile *pFd, /* File descriptor object */
4665 i64 nNew /* Required mapping size */
4666){
dan4ff7bc42013-04-02 12:04:09 +00004667 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004668 int h = pFd->h; /* File descriptor open on db file */
4669 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004670 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004671 u8 *pNew = 0; /* Location of new mapping */
4672 int flags = PROT_READ; /* Flags to pass to mmap() */
4673
4674 assert( pFd->nFetchOut==0 );
4675 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004676 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004677 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004678 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004679 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004680
4681 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4682
4683 if( pOrig ){
4684 const int szSyspage = unixGetPagesize();
4685 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
4686 u8 *pReq = &pOrig[nReuse];
4687
4688 /* Unmap any pages of the existing mapping that cannot be reused. */
4689 if( nReuse!=nOrig ){
4690 osMunmap(pReq, nOrig-nReuse);
4691 }
4692
4693#if HAVE_MREMAP
4694 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004695 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004696#else
4697 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4698 if( pNew!=MAP_FAILED ){
4699 if( pNew!=pReq ){
4700 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004701 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004702 }else{
4703 pNew = pOrig;
4704 }
4705 }
4706#endif
4707
dan48ccef82013-04-02 20:55:01 +00004708 /* The attempt to extend the existing mapping failed. Free it. */
4709 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004710 osMunmap(pOrig, nReuse);
4711 }
4712 }
4713
4714 /* If pNew is still NULL, try to create an entirely new mapping. */
4715 if( pNew==0 ){
4716 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004717 }
4718
dan4ff7bc42013-04-02 12:04:09 +00004719 if( pNew==MAP_FAILED ){
4720 pNew = 0;
4721 nNew = 0;
4722 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4723
4724 /* If the mmap() above failed, assume that all subsequent mmap() calls
4725 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4726 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004727 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004728 }
dane6ecd662013-04-01 17:56:59 +00004729 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004730 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004731}
4732
4733/*
danaef49d72013-03-25 16:28:54 +00004734** Memory map or remap the file opened by file-descriptor pFd (if the file
4735** is already mapped, the existing mapping is replaced by the new). Or, if
4736** there already exists a mapping for this file, and there are still
4737** outstanding xFetch() references to it, this function is a no-op.
4738**
4739** If parameter nByte is non-negative, then it is the requested size of
4740** the mapping to create. Otherwise, if nByte is less than zero, then the
4741** requested size is the size of the file on disk. The actual size of the
4742** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004743** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004744**
4745** SQLITE_OK is returned if no error occurs (even if the mapping is not
4746** recreated as a result of outstanding references) or an SQLite error
4747** code otherwise.
4748*/
danf23da962013-03-23 21:00:41 +00004749static int unixMapfile(unixFile *pFd, i64 nByte){
4750 i64 nMap = nByte;
4751 int rc;
daneb97b292013-03-20 14:26:59 +00004752
danf23da962013-03-23 21:00:41 +00004753 assert( nMap>=0 || pFd->nFetchOut==0 );
4754 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4755
4756 if( nMap<0 ){
daneb97b292013-03-20 14:26:59 +00004757 struct stat statbuf; /* Low-level file information */
danf23da962013-03-23 21:00:41 +00004758 rc = osFstat(pFd->h, &statbuf);
4759 if( rc!=SQLITE_OK ){
4760 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004761 }
danf23da962013-03-23 21:00:41 +00004762 nMap = statbuf.st_size;
4763 }
drh9b4c59f2013-04-15 17:03:42 +00004764 if( nMap>pFd->mmapSizeMax ){
4765 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004766 }
4767
danf23da962013-03-23 21:00:41 +00004768 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004769 if( nMap>0 ){
4770 unixRemapfile(pFd, nMap);
4771 }else{
danb7e3a322013-03-25 20:30:13 +00004772 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004773 }
4774 }
4775
danf23da962013-03-23 21:00:41 +00004776 return SQLITE_OK;
4777}
mistachkine98844f2013-08-24 00:59:24 +00004778#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004779
danaef49d72013-03-25 16:28:54 +00004780/*
4781** If possible, return a pointer to a mapping of file fd starting at offset
4782** iOff. The mapping must be valid for at least nAmt bytes.
4783**
4784** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4785** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4786** Finally, if an error does occur, return an SQLite error code. The final
4787** value of *pp is undefined in this case.
4788**
4789** If this function does return a pointer, the caller must eventually
4790** release the reference by calling unixUnfetch().
4791*/
danf23da962013-03-23 21:00:41 +00004792static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004793#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004794 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004795#endif
danf23da962013-03-23 21:00:41 +00004796 *pp = 0;
4797
drh9b4c59f2013-04-15 17:03:42 +00004798#if SQLITE_MAX_MMAP_SIZE>0
4799 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004800 if( pFd->pMapRegion==0 ){
4801 int rc = unixMapfile(pFd, -1);
4802 if( rc!=SQLITE_OK ) return rc;
4803 }
4804 if( pFd->mmapSize >= iOff+nAmt ){
4805 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4806 pFd->nFetchOut++;
4807 }
4808 }
drh6e0b6d52013-04-09 16:19:20 +00004809#endif
danf23da962013-03-23 21:00:41 +00004810 return SQLITE_OK;
4811}
4812
danaef49d72013-03-25 16:28:54 +00004813/*
dandf737fe2013-03-25 17:00:24 +00004814** If the third argument is non-NULL, then this function releases a
4815** reference obtained by an earlier call to unixFetch(). The second
4816** argument passed to this function must be the same as the corresponding
4817** argument that was passed to the unixFetch() invocation.
4818**
4819** Or, if the third argument is NULL, then this function is being called
4820** to inform the VFS layer that, according to POSIX, any existing mapping
4821** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004822*/
dandf737fe2013-03-25 17:00:24 +00004823static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
danf23da962013-03-23 21:00:41 +00004824 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhda8caa02013-04-22 23:38:50 +00004825 UNUSED_PARAMETER(iOff);
danf23da962013-03-23 21:00:41 +00004826
mistachkinb5ca3cb2013-08-24 01:12:03 +00004827#if SQLITE_MAX_MMAP_SIZE>0
danaef49d72013-03-25 16:28:54 +00004828 /* If p==0 (unmap the entire file) then there must be no outstanding
4829 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4830 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004831 assert( (p==0)==(pFd->nFetchOut==0) );
4832
dandf737fe2013-03-25 17:00:24 +00004833 /* If p!=0, it must match the iOff value. */
4834 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4835
danf23da962013-03-23 21:00:41 +00004836 if( p ){
4837 pFd->nFetchOut--;
4838 }else{
4839 unixUnmapfile(pFd);
4840 }
4841
4842 assert( pFd->nFetchOut>=0 );
mistachkinb5ca3cb2013-08-24 01:12:03 +00004843#endif
danf23da962013-03-23 21:00:41 +00004844 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004845}
4846
4847/*
drh734c9862008-11-28 15:37:20 +00004848** Here ends the implementation of all sqlite3_file methods.
4849**
4850********************** End sqlite3_file Methods *******************************
4851******************************************************************************/
4852
4853/*
drh6b9d6dd2008-12-03 19:34:47 +00004854** This division contains definitions of sqlite3_io_methods objects that
4855** implement various file locking strategies. It also contains definitions
4856** of "finder" functions. A finder-function is used to locate the appropriate
4857** sqlite3_io_methods object for a particular database file. The pAppData
4858** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4859** the correct finder-function for that VFS.
4860**
4861** Most finder functions return a pointer to a fixed sqlite3_io_methods
4862** object. The only interesting finder-function is autolockIoFinder, which
4863** looks at the filesystem type and tries to guess the best locking
4864** strategy from that.
4865**
drh1875f7a2008-12-08 18:19:17 +00004866** For finder-funtion F, two objects are created:
4867**
4868** (1) The real finder-function named "FImpt()".
4869**
dane946c392009-08-22 11:39:46 +00004870** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004871**
4872**
4873** A pointer to the F pointer is used as the pAppData value for VFS
4874** objects. We have to do this instead of letting pAppData point
4875** directly at the finder-function since C90 rules prevent a void*
4876** from be cast into a function pointer.
4877**
drh6b9d6dd2008-12-03 19:34:47 +00004878**
drh7708e972008-11-29 00:56:52 +00004879** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004880**
drh7708e972008-11-29 00:56:52 +00004881** * A constant sqlite3_io_methods object call METHOD that has locking
4882** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4883**
4884** * An I/O method finder function called FINDER that returns a pointer
4885** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004886*/
drhd9e5c4f2010-05-12 18:01:39 +00004887#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004888static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004889 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004890 CLOSE, /* xClose */ \
4891 unixRead, /* xRead */ \
4892 unixWrite, /* xWrite */ \
4893 unixTruncate, /* xTruncate */ \
4894 unixSync, /* xSync */ \
4895 unixFileSize, /* xFileSize */ \
4896 LOCK, /* xLock */ \
4897 UNLOCK, /* xUnlock */ \
4898 CKLOCK, /* xCheckReservedLock */ \
4899 unixFileControl, /* xFileControl */ \
4900 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004901 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004902 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004903 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004904 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004905 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004906 unixFetch, /* xFetch */ \
4907 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004908}; \
drh0c2694b2009-09-03 16:23:44 +00004909static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4910 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004911 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004912} \
drh0c2694b2009-09-03 16:23:44 +00004913static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004914 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004915
4916/*
4917** Here are all of the sqlite3_io_methods objects for each of the
4918** locking strategies. Functions that return pointers to these methods
4919** are also created.
4920*/
4921IOMETHODS(
4922 posixIoFinder, /* Finder function name */
4923 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004924 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004925 unixClose, /* xClose method */
4926 unixLock, /* xLock method */
4927 unixUnlock, /* xUnlock method */
4928 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004929)
drh7708e972008-11-29 00:56:52 +00004930IOMETHODS(
4931 nolockIoFinder, /* Finder function name */
4932 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004933 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004934 nolockClose, /* xClose method */
4935 nolockLock, /* xLock method */
4936 nolockUnlock, /* xUnlock method */
4937 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004938)
drh7708e972008-11-29 00:56:52 +00004939IOMETHODS(
4940 dotlockIoFinder, /* Finder function name */
4941 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004942 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004943 dotlockClose, /* xClose method */
4944 dotlockLock, /* xLock method */
4945 dotlockUnlock, /* xUnlock method */
4946 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004947)
drh7708e972008-11-29 00:56:52 +00004948
chw78a13182009-04-07 05:35:03 +00004949#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004950IOMETHODS(
4951 flockIoFinder, /* Finder function name */
4952 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004953 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004954 flockClose, /* xClose method */
4955 flockLock, /* xLock method */
4956 flockUnlock, /* xUnlock method */
4957 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004958)
drh7708e972008-11-29 00:56:52 +00004959#endif
4960
drh6c7d5c52008-11-21 20:32:33 +00004961#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004962IOMETHODS(
4963 semIoFinder, /* Finder function name */
4964 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004965 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004966 semClose, /* xClose method */
4967 semLock, /* xLock method */
4968 semUnlock, /* xUnlock method */
4969 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004970)
aswiftaebf4132008-11-21 00:10:35 +00004971#endif
drh7708e972008-11-29 00:56:52 +00004972
drhd2cb50b2009-01-09 21:41:17 +00004973#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004974IOMETHODS(
4975 afpIoFinder, /* Finder function name */
4976 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004977 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004978 afpClose, /* xClose method */
4979 afpLock, /* xLock method */
4980 afpUnlock, /* xUnlock method */
4981 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004982)
drh715ff302008-12-03 22:32:44 +00004983#endif
4984
4985/*
4986** The proxy locking method is a "super-method" in the sense that it
4987** opens secondary file descriptors for the conch and lock files and
4988** it uses proxy, dot-file, AFP, and flock() locking methods on those
4989** secondary files. For this reason, the division that implements
4990** proxy locking is located much further down in the file. But we need
4991** to go ahead and define the sqlite3_io_methods and finder function
4992** for proxy locking here. So we forward declare the I/O methods.
4993*/
drhd2cb50b2009-01-09 21:41:17 +00004994#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004995static int proxyClose(sqlite3_file*);
4996static int proxyLock(sqlite3_file*, int);
4997static int proxyUnlock(sqlite3_file*, int);
4998static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004999IOMETHODS(
5000 proxyIoFinder, /* Finder function name */
5001 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005002 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005003 proxyClose, /* xClose method */
5004 proxyLock, /* xLock method */
5005 proxyUnlock, /* xUnlock method */
5006 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005007)
aswiftaebf4132008-11-21 00:10:35 +00005008#endif
drh7708e972008-11-29 00:56:52 +00005009
drh7ed97b92010-01-20 13:07:21 +00005010/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5011#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5012IOMETHODS(
5013 nfsIoFinder, /* Finder function name */
5014 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005015 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005016 unixClose, /* xClose method */
5017 unixLock, /* xLock method */
5018 nfsUnlock, /* xUnlock method */
5019 unixCheckReservedLock /* xCheckReservedLock method */
5020)
5021#endif
drh7708e972008-11-29 00:56:52 +00005022
drhd2cb50b2009-01-09 21:41:17 +00005023#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005024/*
drh6b9d6dd2008-12-03 19:34:47 +00005025** This "finder" function attempts to determine the best locking strategy
5026** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005027** object that implements that strategy.
5028**
5029** This is for MacOSX only.
5030*/
drh1875f7a2008-12-08 18:19:17 +00005031static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005032 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005033 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005034){
5035 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005036 const char *zFilesystem; /* Filesystem type name */
5037 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005038 } aMap[] = {
5039 { "hfs", &posixIoMethods },
5040 { "ufs", &posixIoMethods },
5041 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005042 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005043 { "webdav", &nolockIoMethods },
5044 { 0, 0 }
5045 };
5046 int i;
5047 struct statfs fsInfo;
5048 struct flock lockInfo;
5049
5050 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005051 /* If filePath==NULL that means we are dealing with a transient file
5052 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005053 return &nolockIoMethods;
5054 }
5055 if( statfs(filePath, &fsInfo) != -1 ){
5056 if( fsInfo.f_flags & MNT_RDONLY ){
5057 return &nolockIoMethods;
5058 }
5059 for(i=0; aMap[i].zFilesystem; i++){
5060 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5061 return aMap[i].pMethods;
5062 }
5063 }
5064 }
5065
5066 /* Default case. Handles, amongst others, "nfs".
5067 ** Test byte-range lock using fcntl(). If the call succeeds,
5068 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005069 */
drh7708e972008-11-29 00:56:52 +00005070 lockInfo.l_len = 1;
5071 lockInfo.l_start = 0;
5072 lockInfo.l_whence = SEEK_SET;
5073 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005074 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005075 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5076 return &nfsIoMethods;
5077 } else {
5078 return &posixIoMethods;
5079 }
drh7708e972008-11-29 00:56:52 +00005080 }else{
5081 return &dotlockIoMethods;
5082 }
5083}
drh0c2694b2009-09-03 16:23:44 +00005084static const sqlite3_io_methods
5085 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005086
drhd2cb50b2009-01-09 21:41:17 +00005087#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005088
chw78a13182009-04-07 05:35:03 +00005089#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5090/*
5091** This "finder" function attempts to determine the best locking strategy
5092** for the database file "filePath". It then returns the sqlite3_io_methods
5093** object that implements that strategy.
5094**
5095** This is for VXWorks only.
5096*/
5097static const sqlite3_io_methods *autolockIoFinderImpl(
5098 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005099 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005100){
5101 struct flock lockInfo;
5102
5103 if( !filePath ){
5104 /* If filePath==NULL that means we are dealing with a transient file
5105 ** that does not need to be locked. */
5106 return &nolockIoMethods;
5107 }
5108
5109 /* Test if fcntl() is supported and use POSIX style locks.
5110 ** Otherwise fall back to the named semaphore method.
5111 */
5112 lockInfo.l_len = 1;
5113 lockInfo.l_start = 0;
5114 lockInfo.l_whence = SEEK_SET;
5115 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005116 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005117 return &posixIoMethods;
5118 }else{
5119 return &semIoMethods;
5120 }
5121}
drh0c2694b2009-09-03 16:23:44 +00005122static const sqlite3_io_methods
5123 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005124
5125#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5126
drh7708e972008-11-29 00:56:52 +00005127/*
5128** An abstract type for a pointer to a IO method finder function:
5129*/
drh0c2694b2009-09-03 16:23:44 +00005130typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005131
aswiftaebf4132008-11-21 00:10:35 +00005132
drh734c9862008-11-28 15:37:20 +00005133/****************************************************************************
5134**************************** sqlite3_vfs methods ****************************
5135**
5136** This division contains the implementation of methods on the
5137** sqlite3_vfs object.
5138*/
5139
danielk1977a3d4c882007-03-23 10:08:38 +00005140/*
danielk1977e339d652008-06-28 11:23:00 +00005141** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005142*/
5143static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005144 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005145 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005146 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005147 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005148 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005149){
drh7708e972008-11-29 00:56:52 +00005150 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005151 unixFile *pNew = (unixFile *)pId;
5152 int rc = SQLITE_OK;
5153
drh8af6c222010-05-14 12:43:01 +00005154 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005155
dan00157392010-10-05 11:33:15 +00005156 /* Usually the path zFilename should not be a relative pathname. The
5157 ** exception is when opening the proxy "conch" file in builds that
5158 ** include the special Apple locking styles.
5159 */
dan00157392010-10-05 11:33:15 +00005160#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005161 assert( zFilename==0 || zFilename[0]=='/'
5162 || pVfs->pAppData==(void*)&autolockIoFinder );
5163#else
5164 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005165#endif
dan00157392010-10-05 11:33:15 +00005166
drhb07028f2011-10-14 21:49:18 +00005167 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005168 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005169
drh308c2a52010-05-14 11:30:18 +00005170 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005171 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005172 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005173 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005174 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005175#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005176 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005177#endif
drhc02a43a2012-01-10 23:18:38 +00005178 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5179 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005180 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005181 }
drh503a6862013-03-01 01:07:17 +00005182 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005183 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005184 }
drh339eb0b2008-03-07 15:34:11 +00005185
drh6c7d5c52008-11-21 20:32:33 +00005186#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005187 pNew->pId = vxworksFindFileId(zFilename);
5188 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005189 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005190 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005191 }
5192#endif
5193
drhc02a43a2012-01-10 23:18:38 +00005194 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005195 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005196 }else{
drh0c2694b2009-09-03 16:23:44 +00005197 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005198#if SQLITE_ENABLE_LOCKING_STYLE
5199 /* Cache zFilename in the locking context (AFP and dotlock override) for
5200 ** proxyLock activation is possible (remote proxy is based on db name)
5201 ** zFilename remains valid until file is closed, to support */
5202 pNew->lockingContext = (void*)zFilename;
5203#endif
drhda0e7682008-07-30 15:27:54 +00005204 }
danielk1977e339d652008-06-28 11:23:00 +00005205
drh7ed97b92010-01-20 13:07:21 +00005206 if( pLockingStyle == &posixIoMethods
5207#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5208 || pLockingStyle == &nfsIoMethods
5209#endif
5210 ){
drh7708e972008-11-29 00:56:52 +00005211 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005212 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005213 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005214 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005215 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005216 ** in two scenarios:
5217 **
5218 ** (a) A call to fstat() failed.
5219 ** (b) A malloc failed.
5220 **
5221 ** Scenario (b) may only occur if the process is holding no other
5222 ** file descriptors open on the same file. If there were other file
5223 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005224 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005225 ** handle h - as it is guaranteed that no posix locks will be released
5226 ** by doing so.
5227 **
5228 ** If scenario (a) caused the error then things are not so safe. The
5229 ** implicit assumption here is that if fstat() fails, things are in
5230 ** such bad shape that dropping a lock or two doesn't matter much.
5231 */
drh0e9365c2011-03-02 02:08:13 +00005232 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005233 h = -1;
5234 }
drh7708e972008-11-29 00:56:52 +00005235 unixLeaveMutex();
5236 }
danielk1977e339d652008-06-28 11:23:00 +00005237
drhd2cb50b2009-01-09 21:41:17 +00005238#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005239 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005240 /* AFP locking uses the file path so it needs to be included in
5241 ** the afpLockingContext.
5242 */
5243 afpLockingContext *pCtx;
5244 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5245 if( pCtx==0 ){
5246 rc = SQLITE_NOMEM;
5247 }else{
5248 /* NB: zFilename exists and remains valid until the file is closed
5249 ** according to requirement F11141. So we do not need to make a
5250 ** copy of the filename. */
5251 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005252 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005253 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005254 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005255 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005256 if( rc!=SQLITE_OK ){
5257 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005258 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005259 h = -1;
5260 }
drh7708e972008-11-29 00:56:52 +00005261 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005262 }
drh7708e972008-11-29 00:56:52 +00005263 }
5264#endif
danielk1977e339d652008-06-28 11:23:00 +00005265
drh7708e972008-11-29 00:56:52 +00005266 else if( pLockingStyle == &dotlockIoMethods ){
5267 /* Dotfile locking uses the file path so it needs to be included in
5268 ** the dotlockLockingContext
5269 */
5270 char *zLockFile;
5271 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005272 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005273 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005274 zLockFile = (char *)sqlite3_malloc(nFilename);
5275 if( zLockFile==0 ){
5276 rc = SQLITE_NOMEM;
5277 }else{
5278 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005279 }
drh7708e972008-11-29 00:56:52 +00005280 pNew->lockingContext = zLockFile;
5281 }
danielk1977e339d652008-06-28 11:23:00 +00005282
drh6c7d5c52008-11-21 20:32:33 +00005283#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005284 else if( pLockingStyle == &semIoMethods ){
5285 /* Named semaphore locking uses the file path so it needs to be
5286 ** included in the semLockingContext
5287 */
5288 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005289 rc = findInodeInfo(pNew, &pNew->pInode);
5290 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5291 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005292 int n;
drh2238dcc2009-08-27 17:56:20 +00005293 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005294 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005295 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005296 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005297 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5298 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005299 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005300 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005301 }
chw97185482008-11-17 08:05:31 +00005302 }
drh7708e972008-11-29 00:56:52 +00005303 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005304 }
drh7708e972008-11-29 00:56:52 +00005305#endif
aswift5b1a2562008-08-22 00:22:35 +00005306
5307 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005308#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005309 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005310 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005311 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005312 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005313 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005314 }
chw97185482008-11-17 08:05:31 +00005315#endif
danielk1977e339d652008-06-28 11:23:00 +00005316 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005317 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005318 }else{
drh7708e972008-11-29 00:56:52 +00005319 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005320 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005321 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005322 }
danielk1977e339d652008-06-28 11:23:00 +00005323 return rc;
drh054889e2005-11-30 03:20:31 +00005324}
drh9c06c952005-11-26 00:25:00 +00005325
danielk1977ad94b582007-08-20 06:44:22 +00005326/*
drh8b3cf822010-06-01 21:02:51 +00005327** Return the name of a directory in which to put temporary files.
5328** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005329*/
drh7234c6d2010-06-19 15:10:09 +00005330static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005331 static const char *azDirs[] = {
5332 0,
aswiftaebf4132008-11-21 00:10:35 +00005333 0,
danielk197717b90b52008-06-06 11:11:25 +00005334 "/var/tmp",
5335 "/usr/tmp",
5336 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005337 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005338 };
drh8b3cf822010-06-01 21:02:51 +00005339 unsigned int i;
5340 struct stat buf;
5341 const char *zDir = 0;
5342
5343 azDirs[0] = sqlite3_temp_directory;
5344 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005345 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005346 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005347 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005348 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005349 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005350 break;
5351 }
5352 return zDir;
5353}
5354
5355/*
5356** Create a temporary file name in zBuf. zBuf must be allocated
5357** by the calling process and must be big enough to hold at least
5358** pVfs->mxPathname bytes.
5359*/
5360static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005361 static const unsigned char zChars[] =
5362 "abcdefghijklmnopqrstuvwxyz"
5363 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5364 "0123456789";
drh41022642008-11-21 00:24:42 +00005365 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005366 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005367
5368 /* It's odd to simulate an io-error here, but really this is just
5369 ** using the io-error infrastructure to test that SQLite handles this
5370 ** function failing.
5371 */
5372 SimulateIOError( return SQLITE_IOERR );
5373
drh7234c6d2010-06-19 15:10:09 +00005374 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005375 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005376
5377 /* Check that the output buffer is large enough for the temporary file
5378 ** name. If it is not, return SQLITE_ERROR.
5379 */
drhc02a43a2012-01-10 23:18:38 +00005380 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005381 return SQLITE_ERROR;
5382 }
5383
5384 do{
drhc02a43a2012-01-10 23:18:38 +00005385 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005386 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005387 sqlite3_randomness(15, &zBuf[j]);
5388 for(i=0; i<15; i++, j++){
5389 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5390 }
5391 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005392 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005393 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005394 return SQLITE_OK;
5395}
5396
drhd2cb50b2009-01-09 21:41:17 +00005397#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005398/*
5399** Routine to transform a unixFile into a proxy-locking unixFile.
5400** Implementation in the proxy-lock division, but used by unixOpen()
5401** if SQLITE_PREFER_PROXY_LOCKING is defined.
5402*/
5403static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005404#endif
drhc66d5b62008-12-03 22:48:32 +00005405
dan08da86a2009-08-21 17:18:03 +00005406/*
5407** Search for an unused file descriptor that was opened on the database
5408** file (not a journal or master-journal file) identified by pathname
5409** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5410** argument to this function.
5411**
5412** Such a file descriptor may exist if a database connection was closed
5413** but the associated file descriptor could not be closed because some
5414** other file descriptor open on the same file is holding a file-lock.
5415** Refer to comments in the unixClose() function and the lengthy comment
5416** describing "Posix Advisory Locking" at the start of this file for
5417** further details. Also, ticket #4018.
5418**
5419** If a suitable file descriptor is found, then it is returned. If no
5420** such file descriptor is located, -1 is returned.
5421*/
dane946c392009-08-22 11:39:46 +00005422static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5423 UnixUnusedFd *pUnused = 0;
5424
5425 /* Do not search for an unused file descriptor on vxworks. Not because
5426 ** vxworks would not benefit from the change (it might, we're not sure),
5427 ** but because no way to test it is currently available. It is better
5428 ** not to risk breaking vxworks support for the sake of such an obscure
5429 ** feature. */
5430#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005431 struct stat sStat; /* Results of stat() call */
5432
5433 /* A stat() call may fail for various reasons. If this happens, it is
5434 ** almost certain that an open() call on the same path will also fail.
5435 ** For this reason, if an error occurs in the stat() call here, it is
5436 ** ignored and -1 is returned. The caller will try to open a new file
5437 ** descriptor on the same path, fail, and return an error to SQLite.
5438 **
5439 ** Even if a subsequent open() call does succeed, the consequences of
5440 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005441 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005442 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005443
5444 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005445 pInode = inodeList;
5446 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5447 || pInode->fileId.ino!=sStat.st_ino) ){
5448 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005449 }
drh8af6c222010-05-14 12:43:01 +00005450 if( pInode ){
dane946c392009-08-22 11:39:46 +00005451 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005452 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005453 pUnused = *pp;
5454 if( pUnused ){
5455 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005456 }
5457 }
5458 unixLeaveMutex();
5459 }
dane946c392009-08-22 11:39:46 +00005460#endif /* if !OS_VXWORKS */
5461 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005462}
danielk197717b90b52008-06-06 11:11:25 +00005463
5464/*
danddb0ac42010-07-14 14:48:58 +00005465** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005466** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005467** and a value suitable for passing as the third argument to open(2) is
5468** written to *pMode. If an IO error occurs, an SQLite error code is
5469** returned and the value of *pMode is not modified.
5470**
drh8c815d12012-02-13 20:16:37 +00005471** In most cases cases, this routine sets *pMode to 0, which will become
5472** an indication to robust_open() to create the file using
5473** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5474** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005475** this function queries the file-system for the permissions on the
5476** corresponding database file and sets *pMode to this value. Whenever
5477** possible, WAL and journal files are created using the same permissions
5478** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005479**
5480** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5481** original filename is unavailable. But 8_3_NAMES is only used for
5482** FAT filesystems and permissions do not matter there, so just use
5483** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005484*/
5485static int findCreateFileMode(
5486 const char *zPath, /* Path of file (possibly) being created */
5487 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005488 mode_t *pMode, /* OUT: Permissions to open file with */
5489 uid_t *pUid, /* OUT: uid to set on the file */
5490 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005491){
5492 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005493 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005494 *pUid = 0;
5495 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005496 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005497 char zDb[MAX_PATHNAME+1]; /* Database file path */
5498 int nDb; /* Number of valid bytes in zDb */
5499 struct stat sStat; /* Output of stat() on database file */
5500
dana0c989d2010-11-05 18:07:37 +00005501 /* zPath is a path to a WAL or journal file. The following block derives
5502 ** the path to the associated database file from zPath. This block handles
5503 ** the following naming conventions:
5504 **
5505 ** "<path to db>-journal"
5506 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005507 ** "<path to db>-journalNN"
5508 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005509 **
drhd337c5b2011-10-20 18:23:35 +00005510 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005511 ** used by the test_multiplex.c module.
5512 */
5513 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005514#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005515 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005516 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005517#else
5518 while( zPath[nDb]!='-' ){
5519 assert( nDb>0 );
5520 assert( zPath[nDb]!='\n' );
5521 nDb--;
5522 }
5523#endif
danddb0ac42010-07-14 14:48:58 +00005524 memcpy(zDb, zPath, nDb);
5525 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005526
drh58384f12011-07-28 00:14:45 +00005527 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005528 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005529 *pUid = sStat.st_uid;
5530 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005531 }else{
5532 rc = SQLITE_IOERR_FSTAT;
5533 }
5534 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5535 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005536 }
5537 return rc;
5538}
5539
5540/*
danielk1977ad94b582007-08-20 06:44:22 +00005541** Open the file zPath.
5542**
danielk1977b4b47412007-08-17 15:53:36 +00005543** Previously, the SQLite OS layer used three functions in place of this
5544** one:
5545**
5546** sqlite3OsOpenReadWrite();
5547** sqlite3OsOpenReadOnly();
5548** sqlite3OsOpenExclusive();
5549**
5550** These calls correspond to the following combinations of flags:
5551**
5552** ReadWrite() -> (READWRITE | CREATE)
5553** ReadOnly() -> (READONLY)
5554** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5555**
5556** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5557** true, the file was configured to be automatically deleted when the
5558** file handle closed. To achieve the same effect using this new
5559** interface, add the DELETEONCLOSE flag to those specified above for
5560** OpenExclusive().
5561*/
5562static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005563 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5564 const char *zPath, /* Pathname of file to be opened */
5565 sqlite3_file *pFile, /* The file descriptor to be filled in */
5566 int flags, /* Input flags to control the opening */
5567 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005568){
dan08da86a2009-08-21 17:18:03 +00005569 unixFile *p = (unixFile *)pFile;
5570 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005571 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005572 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005573 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005574 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005575 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005576
5577 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5578 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5579 int isCreate = (flags & SQLITE_OPEN_CREATE);
5580 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5581 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005582#if SQLITE_ENABLE_LOCKING_STYLE
5583 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5584#endif
drh3d4435b2011-08-26 20:55:50 +00005585#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5586 struct statfs fsInfo;
5587#endif
danielk1977b4b47412007-08-17 15:53:36 +00005588
danielk1977fee2d252007-08-18 10:59:19 +00005589 /* If creating a master or main-file journal, this function will open
5590 ** a file-descriptor on the directory too. The first time unixSync()
5591 ** is called the directory file descriptor will be fsync()ed and close()d.
5592 */
drh0059eae2011-08-08 23:48:40 +00005593 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005594 eType==SQLITE_OPEN_MASTER_JOURNAL
5595 || eType==SQLITE_OPEN_MAIN_JOURNAL
5596 || eType==SQLITE_OPEN_WAL
5597 ));
danielk1977fee2d252007-08-18 10:59:19 +00005598
danielk197717b90b52008-06-06 11:11:25 +00005599 /* If argument zPath is a NULL pointer, this function is required to open
5600 ** a temporary file. Use this buffer to store the file name in.
5601 */
drhc02a43a2012-01-10 23:18:38 +00005602 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005603 const char *zName = zPath;
5604
danielk1977fee2d252007-08-18 10:59:19 +00005605 /* Check the following statements are true:
5606 **
5607 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5608 ** (b) if CREATE is set, then READWRITE must also be set, and
5609 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005610 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005611 */
danielk1977b4b47412007-08-17 15:53:36 +00005612 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005613 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005614 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005615 assert(isDelete==0 || isCreate);
5616
danddb0ac42010-07-14 14:48:58 +00005617 /* The main DB, main journal, WAL file and master journal are never
5618 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005619 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5620 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5621 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005622 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005623
danielk1977fee2d252007-08-18 10:59:19 +00005624 /* Assert that the upper layer has set one of the "file-type" flags. */
5625 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5626 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5627 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005628 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005629 );
5630
dan08da86a2009-08-21 17:18:03 +00005631 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005632
dan08da86a2009-08-21 17:18:03 +00005633 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005634 UnixUnusedFd *pUnused;
5635 pUnused = findReusableFd(zName, flags);
5636 if( pUnused ){
5637 fd = pUnused->fd;
5638 }else{
dan6aa657f2009-08-24 18:57:58 +00005639 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005640 if( !pUnused ){
5641 return SQLITE_NOMEM;
5642 }
5643 }
5644 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005645
5646 /* Database filenames are double-zero terminated if they are not
5647 ** URIs with parameters. Hence, they can always be passed into
5648 ** sqlite3_uri_parameter(). */
5649 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5650
dan08da86a2009-08-21 17:18:03 +00005651 }else if( !zName ){
5652 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005653 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005654 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005655 if( rc!=SQLITE_OK ){
5656 return rc;
5657 }
5658 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005659
5660 /* Generated temporary filenames are always double-zero terminated
5661 ** for use by sqlite3_uri_parameter(). */
5662 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005663 }
5664
dan08da86a2009-08-21 17:18:03 +00005665 /* Determine the value of the flags parameter passed to POSIX function
5666 ** open(). These must be calculated even if open() is not called, as
5667 ** they may be stored as part of the file handle and used by the
5668 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005669 if( isReadonly ) openFlags |= O_RDONLY;
5670 if( isReadWrite ) openFlags |= O_RDWR;
5671 if( isCreate ) openFlags |= O_CREAT;
5672 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5673 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005674
danielk1977b4b47412007-08-17 15:53:36 +00005675 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005676 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005677 uid_t uid; /* Userid for the file */
5678 gid_t gid; /* Groupid for the file */
5679 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005680 if( rc!=SQLITE_OK ){
5681 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005682 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005683 return rc;
5684 }
drhad4f1e52011-03-04 15:43:57 +00005685 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005686 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005687 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5688 /* Failed to open the file for read/write access. Try read-only. */
5689 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005690 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005691 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005692 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005693 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005694 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005695 }
5696 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005697 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005698 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005699 }
drhac7c3ac2012-02-11 19:23:48 +00005700
5701 /* If this process is running as root and if creating a new rollback
5702 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005703 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005704 */
5705 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005706 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005707 }
danielk1977b4b47412007-08-17 15:53:36 +00005708 }
dan08da86a2009-08-21 17:18:03 +00005709 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005710 if( pOutFlags ){
5711 *pOutFlags = flags;
5712 }
5713
dane946c392009-08-22 11:39:46 +00005714 if( p->pUnused ){
5715 p->pUnused->fd = fd;
5716 p->pUnused->flags = flags;
5717 }
5718
danielk1977b4b47412007-08-17 15:53:36 +00005719 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005720#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005721 zPath = zName;
5722#else
drh036ac7f2011-08-08 23:18:05 +00005723 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005724#endif
danielk1977b4b47412007-08-17 15:53:36 +00005725 }
drh41022642008-11-21 00:24:42 +00005726#if SQLITE_ENABLE_LOCKING_STYLE
5727 else{
dan08da86a2009-08-21 17:18:03 +00005728 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005729 }
5730#endif
5731
drhda0e7682008-07-30 15:27:54 +00005732 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005733
drh7ed97b92010-01-20 13:07:21 +00005734
5735#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005736 if( fstatfs(fd, &fsInfo) == -1 ){
5737 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005738 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005739 return SQLITE_IOERR_ACCESS;
5740 }
5741 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5742 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5743 }
5744#endif
drhc02a43a2012-01-10 23:18:38 +00005745
5746 /* Set up appropriate ctrlFlags */
5747 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5748 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5749 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5750 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5751 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5752
drh7ed97b92010-01-20 13:07:21 +00005753#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005754#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005755 isAutoProxy = 1;
5756#endif
5757 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005758 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5759 int useProxy = 0;
5760
dan08da86a2009-08-21 17:18:03 +00005761 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5762 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005763 if( envforce!=NULL ){
5764 useProxy = atoi(envforce)>0;
5765 }else{
aswiftaebf4132008-11-21 00:10:35 +00005766 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005767 /* In theory, the close(fd) call is sub-optimal. If the file opened
5768 ** with fd is a database file, and there are other connections open
5769 ** on that file that are currently holding advisory locks on it,
5770 ** then the call to close() will cancel those locks. In practice,
5771 ** we're assuming that statfs() doesn't fail very often. At least
5772 ** not while other file descriptors opened by the same process on
5773 ** the same file are working. */
5774 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005775 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005776 rc = SQLITE_IOERR_ACCESS;
5777 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005778 }
5779 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5780 }
5781 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005782 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005783 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005784 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005785 if( rc!=SQLITE_OK ){
5786 /* Use unixClose to clean up the resources added in fillInUnixFile
5787 ** and clear all the structure's references. Specifically,
5788 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5789 */
5790 unixClose(pFile);
5791 return rc;
5792 }
aswiftaebf4132008-11-21 00:10:35 +00005793 }
dane946c392009-08-22 11:39:46 +00005794 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005795 }
5796 }
5797#endif
5798
drhc02a43a2012-01-10 23:18:38 +00005799 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5800
dane946c392009-08-22 11:39:46 +00005801open_finished:
5802 if( rc!=SQLITE_OK ){
5803 sqlite3_free(p->pUnused);
5804 }
5805 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005806}
5807
dane946c392009-08-22 11:39:46 +00005808
danielk1977b4b47412007-08-17 15:53:36 +00005809/*
danielk1977fee2d252007-08-18 10:59:19 +00005810** Delete the file at zPath. If the dirSync argument is true, fsync()
5811** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005812*/
drh6b9d6dd2008-12-03 19:34:47 +00005813static int unixDelete(
5814 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5815 const char *zPath, /* Name of file to be deleted */
5816 int dirSync /* If true, fsync() directory after deleting file */
5817){
danielk1977fee2d252007-08-18 10:59:19 +00005818 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005819 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005820 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005821 if( osUnlink(zPath)==(-1) ){
5822 if( errno==ENOENT ){
5823 rc = SQLITE_IOERR_DELETE_NOENT;
5824 }else{
drhb4308162012-11-09 21:40:02 +00005825 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005826 }
drhb4308162012-11-09 21:40:02 +00005827 return rc;
drh5d4feff2010-07-14 01:45:22 +00005828 }
danielk1977d39fa702008-10-16 13:27:40 +00005829#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005830 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005831 int fd;
drh90315a22011-08-10 01:52:12 +00005832 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005833 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005834#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005835 if( fsync(fd)==-1 )
5836#else
5837 if( fsync(fd) )
5838#endif
5839 {
dane18d4952011-02-21 11:46:24 +00005840 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005841 }
drh0e9365c2011-03-02 02:08:13 +00005842 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005843 }else if( rc==SQLITE_CANTOPEN ){
5844 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005845 }
5846 }
danielk1977d138dd82008-10-15 16:02:48 +00005847#endif
danielk1977fee2d252007-08-18 10:59:19 +00005848 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005849}
5850
danielk197790949c22007-08-17 16:50:38 +00005851/*
mistachkin48864df2013-03-21 21:20:32 +00005852** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005853** test performed depends on the value of flags:
5854**
5855** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5856** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5857** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5858**
5859** Otherwise return 0.
5860*/
danielk1977861f7452008-06-05 11:39:11 +00005861static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005862 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5863 const char *zPath, /* Path of the file to examine */
5864 int flags, /* What do we want to learn about the zPath file? */
5865 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005866){
rse25c0d1a2007-09-20 08:38:14 +00005867 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005868 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005869 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005870 switch( flags ){
5871 case SQLITE_ACCESS_EXISTS:
5872 amode = F_OK;
5873 break;
5874 case SQLITE_ACCESS_READWRITE:
5875 amode = W_OK|R_OK;
5876 break;
drh50d3f902007-08-27 21:10:36 +00005877 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005878 amode = R_OK;
5879 break;
5880
5881 default:
5882 assert(!"Invalid flags argument");
5883 }
drh99ab3b12011-03-02 15:09:07 +00005884 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005885 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5886 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005887 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005888 *pResOut = 0;
5889 }
5890 }
danielk1977861f7452008-06-05 11:39:11 +00005891 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005892}
5893
danielk1977b4b47412007-08-17 15:53:36 +00005894
5895/*
5896** Turn a relative pathname into a full pathname. The relative path
5897** is stored as a nul-terminated string in the buffer pointed to by
5898** zPath.
5899**
5900** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5901** (in this case, MAX_PATHNAME bytes). The full-path is written to
5902** this buffer before returning.
5903*/
danielk1977adfb9b02007-09-17 07:02:56 +00005904static int unixFullPathname(
5905 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5906 const char *zPath, /* Possibly relative input path */
5907 int nOut, /* Size of output buffer in bytes */
5908 char *zOut /* Output buffer */
5909){
danielk1977843e65f2007-09-01 16:16:15 +00005910
5911 /* It's odd to simulate an io-error here, but really this is just
5912 ** using the io-error infrastructure to test that SQLite handles this
5913 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005914 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005915 */
5916 SimulateIOError( return SQLITE_ERROR );
5917
drh153c62c2007-08-24 03:51:33 +00005918 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005919 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005920
drh3c7f2dc2007-12-06 13:26:20 +00005921 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005922 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005923 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005924 }else{
5925 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005926 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005927 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005928 }
drhea678832008-12-10 19:26:22 +00005929 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005930 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005931 }
5932 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005933}
5934
drh0ccebe72005-06-07 22:22:50 +00005935
drh761df872006-12-21 01:29:22 +00005936#ifndef SQLITE_OMIT_LOAD_EXTENSION
5937/*
5938** Interfaces for opening a shared library, finding entry points
5939** within the shared library, and closing the shared library.
5940*/
5941#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005942static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5943 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005944 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5945}
danielk197795c8a542007-09-01 06:51:27 +00005946
5947/*
5948** SQLite calls this function immediately after a call to unixDlSym() or
5949** unixDlOpen() fails (returns a null pointer). If a more detailed error
5950** message is available, it is written to zBufOut. If no error message
5951** is available, zBufOut is left unmodified and SQLite uses a default
5952** error message.
5953*/
danielk1977397d65f2008-11-19 11:35:39 +00005954static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005955 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005956 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005957 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005958 zErr = dlerror();
5959 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005960 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005961 }
drh6c7d5c52008-11-21 20:32:33 +00005962 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005963}
drh1875f7a2008-12-08 18:19:17 +00005964static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5965 /*
5966 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5967 ** cast into a pointer to a function. And yet the library dlsym() routine
5968 ** returns a void* which is really a pointer to a function. So how do we
5969 ** use dlsym() with -pedantic-errors?
5970 **
5971 ** Variable x below is defined to be a pointer to a function taking
5972 ** parameters void* and const char* and returning a pointer to a function.
5973 ** We initialize x by assigning it a pointer to the dlsym() function.
5974 ** (That assignment requires a cast.) Then we call the function that
5975 ** x points to.
5976 **
5977 ** This work-around is unlikely to work correctly on any system where
5978 ** you really cannot cast a function pointer into void*. But then, on the
5979 ** other hand, dlsym() will not work on such a system either, so we have
5980 ** not really lost anything.
5981 */
5982 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005983 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005984 x = (void(*(*)(void*,const char*))(void))dlsym;
5985 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005986}
danielk1977397d65f2008-11-19 11:35:39 +00005987static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5988 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005989 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005990}
danielk1977b4b47412007-08-17 15:53:36 +00005991#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5992 #define unixDlOpen 0
5993 #define unixDlError 0
5994 #define unixDlSym 0
5995 #define unixDlClose 0
5996#endif
5997
5998/*
danielk197790949c22007-08-17 16:50:38 +00005999** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006000*/
danielk1977397d65f2008-11-19 11:35:39 +00006001static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6002 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006003 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006004
drhbbd42a62004-05-22 17:41:58 +00006005 /* We have to initialize zBuf to prevent valgrind from reporting
6006 ** errors. The reports issued by valgrind are incorrect - we would
6007 ** prefer that the randomness be increased by making use of the
6008 ** uninitialized space in zBuf - but valgrind errors tend to worry
6009 ** some users. Rather than argue, it seems easier just to initialize
6010 ** the whole array and silence valgrind, even if that means less randomness
6011 ** in the random seed.
6012 **
6013 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006014 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006015 ** tests repeatable.
6016 */
danielk1977b4b47412007-08-17 15:53:36 +00006017 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00006018#if !defined(SQLITE_TEST)
6019 {
drhc18b4042012-02-10 03:10:27 +00006020 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00006021 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006022 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006023 time_t t;
6024 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006025 memcpy(zBuf, &t, sizeof(t));
6026 pid = getpid();
6027 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00006028 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00006029 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00006030 }else{
drhc18b4042012-02-10 03:10:27 +00006031 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006032 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006033 }
drhbbd42a62004-05-22 17:41:58 +00006034 }
6035#endif
drh72cbd072008-10-14 17:58:38 +00006036 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006037}
6038
danielk1977b4b47412007-08-17 15:53:36 +00006039
drhbbd42a62004-05-22 17:41:58 +00006040/*
6041** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006042** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006043** The return value is the number of microseconds of sleep actually
6044** requested from the underlying operating system, a number which
6045** might be greater than or equal to the argument, but not less
6046** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006047*/
danielk1977397d65f2008-11-19 11:35:39 +00006048static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006049#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006050 struct timespec sp;
6051
6052 sp.tv_sec = microseconds / 1000000;
6053 sp.tv_nsec = (microseconds % 1000000) * 1000;
6054 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006055 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006056 return microseconds;
6057#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006058 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006059 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006060 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006061#else
danielk1977b4b47412007-08-17 15:53:36 +00006062 int seconds = (microseconds+999999)/1000000;
6063 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006064 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006065 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006066#endif
drh88f474a2006-01-02 20:00:12 +00006067}
6068
6069/*
drh6b9d6dd2008-12-03 19:34:47 +00006070** The following variable, if set to a non-zero value, is interpreted as
6071** the number of seconds since 1970 and is used to set the result of
6072** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006073*/
6074#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006075int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006076#endif
6077
6078/*
drhb7e8ea22010-05-03 14:32:30 +00006079** Find the current time (in Universal Coordinated Time). Write into *piNow
6080** the current time and date as a Julian Day number times 86_400_000. In
6081** other words, write into *piNow the number of milliseconds since the Julian
6082** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6083** proleptic Gregorian calendar.
6084**
drh31702252011-10-12 23:13:43 +00006085** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6086** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006087*/
6088static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6089 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006090 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006091#if defined(NO_GETTOD)
6092 time_t t;
6093 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006094 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006095#elif OS_VXWORKS
6096 struct timespec sNow;
6097 clock_gettime(CLOCK_REALTIME, &sNow);
6098 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6099#else
6100 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006101 if( gettimeofday(&sNow, 0)==0 ){
6102 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6103 }else{
6104 rc = SQLITE_ERROR;
6105 }
drhb7e8ea22010-05-03 14:32:30 +00006106#endif
6107
6108#ifdef SQLITE_TEST
6109 if( sqlite3_current_time ){
6110 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6111 }
6112#endif
6113 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006114 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006115}
6116
6117/*
drhbbd42a62004-05-22 17:41:58 +00006118** Find the current time (in Universal Coordinated Time). Write the
6119** current time and date as a Julian Day number into *prNow and
6120** return 0. Return 1 if the time and date cannot be found.
6121*/
danielk1977397d65f2008-11-19 11:35:39 +00006122static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006123 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006124 int rc;
drhff828942010-06-26 21:34:06 +00006125 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006126 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006127 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006128 return rc;
drhbbd42a62004-05-22 17:41:58 +00006129}
danielk1977b4b47412007-08-17 15:53:36 +00006130
drh6b9d6dd2008-12-03 19:34:47 +00006131/*
6132** We added the xGetLastError() method with the intention of providing
6133** better low-level error messages when operating-system problems come up
6134** during SQLite operation. But so far, none of that has been implemented
6135** in the core. So this routine is never called. For now, it is merely
6136** a place-holder.
6137*/
danielk1977397d65f2008-11-19 11:35:39 +00006138static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6139 UNUSED_PARAMETER(NotUsed);
6140 UNUSED_PARAMETER(NotUsed2);
6141 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006142 return 0;
6143}
6144
drhf2424c52010-04-26 00:04:55 +00006145
6146/*
drh734c9862008-11-28 15:37:20 +00006147************************ End of sqlite3_vfs methods ***************************
6148******************************************************************************/
6149
drh715ff302008-12-03 22:32:44 +00006150/******************************************************************************
6151************************** Begin Proxy Locking ********************************
6152**
6153** Proxy locking is a "uber-locking-method" in this sense: It uses the
6154** other locking methods on secondary lock files. Proxy locking is a
6155** meta-layer over top of the primitive locking implemented above. For
6156** this reason, the division that implements of proxy locking is deferred
6157** until late in the file (here) after all of the other I/O methods have
6158** been defined - so that the primitive locking methods are available
6159** as services to help with the implementation of proxy locking.
6160**
6161****
6162**
6163** The default locking schemes in SQLite use byte-range locks on the
6164** database file to coordinate safe, concurrent access by multiple readers
6165** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6166** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6167** as POSIX read & write locks over fixed set of locations (via fsctl),
6168** on AFP and SMB only exclusive byte-range locks are available via fsctl
6169** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6170** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6171** address in the shared range is taken for a SHARED lock, the entire
6172** shared range is taken for an EXCLUSIVE lock):
6173**
drhf2f105d2012-08-20 15:53:54 +00006174** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006175** RESERVED_BYTE 0x40000001
6176** SHARED_RANGE 0x40000002 -> 0x40000200
6177**
6178** This works well on the local file system, but shows a nearly 100x
6179** slowdown in read performance on AFP because the AFP client disables
6180** the read cache when byte-range locks are present. Enabling the read
6181** cache exposes a cache coherency problem that is present on all OS X
6182** supported network file systems. NFS and AFP both observe the
6183** close-to-open semantics for ensuring cache coherency
6184** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6185** address the requirements for concurrent database access by multiple
6186** readers and writers
6187** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6188**
6189** To address the performance and cache coherency issues, proxy file locking
6190** changes the way database access is controlled by limiting access to a
6191** single host at a time and moving file locks off of the database file
6192** and onto a proxy file on the local file system.
6193**
6194**
6195** Using proxy locks
6196** -----------------
6197**
6198** C APIs
6199**
6200** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6201** <proxy_path> | ":auto:");
6202** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6203**
6204**
6205** SQL pragmas
6206**
6207** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6208** PRAGMA [database.]lock_proxy_file
6209**
6210** Specifying ":auto:" means that if there is a conch file with a matching
6211** host ID in it, the proxy path in the conch file will be used, otherwise
6212** a proxy path based on the user's temp dir
6213** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6214** actual proxy file name is generated from the name and path of the
6215** database file. For example:
6216**
6217** For database path "/Users/me/foo.db"
6218** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6219**
6220** Once a lock proxy is configured for a database connection, it can not
6221** be removed, however it may be switched to a different proxy path via
6222** the above APIs (assuming the conch file is not being held by another
6223** connection or process).
6224**
6225**
6226** How proxy locking works
6227** -----------------------
6228**
6229** Proxy file locking relies primarily on two new supporting files:
6230**
6231** * conch file to limit access to the database file to a single host
6232** at a time
6233**
6234** * proxy file to act as a proxy for the advisory locks normally
6235** taken on the database
6236**
6237** The conch file - to use a proxy file, sqlite must first "hold the conch"
6238** by taking an sqlite-style shared lock on the conch file, reading the
6239** contents and comparing the host's unique host ID (see below) and lock
6240** proxy path against the values stored in the conch. The conch file is
6241** stored in the same directory as the database file and the file name
6242** is patterned after the database file name as ".<databasename>-conch".
6243** If the conch file does not exist, or it's contents do not match the
6244** host ID and/or proxy path, then the lock is escalated to an exclusive
6245** lock and the conch file contents is updated with the host ID and proxy
6246** path and the lock is downgraded to a shared lock again. If the conch
6247** is held by another process (with a shared lock), the exclusive lock
6248** will fail and SQLITE_BUSY is returned.
6249**
6250** The proxy file - a single-byte file used for all advisory file locks
6251** normally taken on the database file. This allows for safe sharing
6252** of the database file for multiple readers and writers on the same
6253** host (the conch ensures that they all use the same local lock file).
6254**
drh715ff302008-12-03 22:32:44 +00006255** Requesting the lock proxy does not immediately take the conch, it is
6256** only taken when the first request to lock database file is made.
6257** This matches the semantics of the traditional locking behavior, where
6258** opening a connection to a database file does not take a lock on it.
6259** The shared lock and an open file descriptor are maintained until
6260** the connection to the database is closed.
6261**
6262** The proxy file and the lock file are never deleted so they only need
6263** to be created the first time they are used.
6264**
6265** Configuration options
6266** ---------------------
6267**
6268** SQLITE_PREFER_PROXY_LOCKING
6269**
6270** Database files accessed on non-local file systems are
6271** automatically configured for proxy locking, lock files are
6272** named automatically using the same logic as
6273** PRAGMA lock_proxy_file=":auto:"
6274**
6275** SQLITE_PROXY_DEBUG
6276**
6277** Enables the logging of error messages during host id file
6278** retrieval and creation
6279**
drh715ff302008-12-03 22:32:44 +00006280** LOCKPROXYDIR
6281**
6282** Overrides the default directory used for lock proxy files that
6283** are named automatically via the ":auto:" setting
6284**
6285** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6286**
6287** Permissions to use when creating a directory for storing the
6288** lock proxy files, only used when LOCKPROXYDIR is not set.
6289**
6290**
6291** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6292** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6293** force proxy locking to be used for every database file opened, and 0
6294** will force automatic proxy locking to be disabled for all database
6295** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6296** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6297*/
6298
6299/*
6300** Proxy locking is only available on MacOSX
6301*/
drhd2cb50b2009-01-09 21:41:17 +00006302#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006303
drh715ff302008-12-03 22:32:44 +00006304/*
6305** The proxyLockingContext has the path and file structures for the remote
6306** and local proxy files in it
6307*/
6308typedef struct proxyLockingContext proxyLockingContext;
6309struct proxyLockingContext {
6310 unixFile *conchFile; /* Open conch file */
6311 char *conchFilePath; /* Name of the conch file */
6312 unixFile *lockProxy; /* Open proxy lock file */
6313 char *lockProxyPath; /* Name of the proxy lock file */
6314 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006315 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006316 void *oldLockingContext; /* Original lockingcontext to restore on close */
6317 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6318};
6319
drh7ed97b92010-01-20 13:07:21 +00006320/*
6321** The proxy lock file path for the database at dbPath is written into lPath,
6322** which must point to valid, writable memory large enough for a maxLen length
6323** file path.
drh715ff302008-12-03 22:32:44 +00006324*/
drh715ff302008-12-03 22:32:44 +00006325static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6326 int len;
6327 int dbLen;
6328 int i;
6329
6330#ifdef LOCKPROXYDIR
6331 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6332#else
6333# ifdef _CS_DARWIN_USER_TEMP_DIR
6334 {
drh7ed97b92010-01-20 13:07:21 +00006335 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006336 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6337 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006338 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006339 }
drh7ed97b92010-01-20 13:07:21 +00006340 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006341 }
6342# else
6343 len = strlcpy(lPath, "/tmp/", maxLen);
6344# endif
6345#endif
6346
6347 if( lPath[len-1]!='/' ){
6348 len = strlcat(lPath, "/", maxLen);
6349 }
6350
6351 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006352 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006353 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006354 char c = dbPath[i];
6355 lPath[i+len] = (c=='/')?'_':c;
6356 }
6357 lPath[i+len]='\0';
6358 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006359 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006360 return SQLITE_OK;
6361}
6362
drh7ed97b92010-01-20 13:07:21 +00006363/*
6364 ** Creates the lock file and any missing directories in lockPath
6365 */
6366static int proxyCreateLockPath(const char *lockPath){
6367 int i, len;
6368 char buf[MAXPATHLEN];
6369 int start = 0;
6370
6371 assert(lockPath!=NULL);
6372 /* try to create all the intermediate directories */
6373 len = (int)strlen(lockPath);
6374 buf[0] = lockPath[0];
6375 for( i=1; i<len; i++ ){
6376 if( lockPath[i] == '/' && (i - start > 0) ){
6377 /* only mkdir if leaf dir != "." or "/" or ".." */
6378 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6379 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6380 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006381 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006382 int err=errno;
6383 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006384 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006385 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006386 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006387 return err;
6388 }
6389 }
6390 }
6391 start=i+1;
6392 }
6393 buf[i] = lockPath[i];
6394 }
drh308c2a52010-05-14 11:30:18 +00006395 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006396 return 0;
6397}
6398
drh715ff302008-12-03 22:32:44 +00006399/*
6400** Create a new VFS file descriptor (stored in memory obtained from
6401** sqlite3_malloc) and open the file named "path" in the file descriptor.
6402**
6403** The caller is responsible not only for closing the file descriptor
6404** but also for freeing the memory associated with the file descriptor.
6405*/
drh7ed97b92010-01-20 13:07:21 +00006406static int proxyCreateUnixFile(
6407 const char *path, /* path for the new unixFile */
6408 unixFile **ppFile, /* unixFile created and returned by ref */
6409 int islockfile /* if non zero missing dirs will be created */
6410) {
6411 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006412 unixFile *pNew;
6413 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006414 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006415 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006416 int terrno = 0;
6417 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006418
drh7ed97b92010-01-20 13:07:21 +00006419 /* 1. first try to open/create the file
6420 ** 2. if that fails, and this is a lock file (not-conch), try creating
6421 ** the parent directories and then try again.
6422 ** 3. if that fails, try to open the file read-only
6423 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6424 */
6425 pUnused = findReusableFd(path, openFlags);
6426 if( pUnused ){
6427 fd = pUnused->fd;
6428 }else{
6429 pUnused = sqlite3_malloc(sizeof(*pUnused));
6430 if( !pUnused ){
6431 return SQLITE_NOMEM;
6432 }
6433 }
6434 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006435 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006436 terrno = errno;
6437 if( fd<0 && errno==ENOENT && islockfile ){
6438 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006439 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006440 }
6441 }
6442 }
6443 if( fd<0 ){
6444 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006445 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006446 terrno = errno;
6447 }
6448 if( fd<0 ){
6449 if( islockfile ){
6450 return SQLITE_BUSY;
6451 }
6452 switch (terrno) {
6453 case EACCES:
6454 return SQLITE_PERM;
6455 case EIO:
6456 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6457 default:
drh9978c972010-02-23 17:36:32 +00006458 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006459 }
6460 }
6461
6462 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6463 if( pNew==NULL ){
6464 rc = SQLITE_NOMEM;
6465 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006466 }
6467 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006468 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006469 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006470 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006471 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006472 pUnused->fd = fd;
6473 pUnused->flags = openFlags;
6474 pNew->pUnused = pUnused;
6475
drhc02a43a2012-01-10 23:18:38 +00006476 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006477 if( rc==SQLITE_OK ){
6478 *ppFile = pNew;
6479 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006480 }
drh7ed97b92010-01-20 13:07:21 +00006481end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006482 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006483 sqlite3_free(pNew);
6484 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006485 return rc;
6486}
6487
drh7ed97b92010-01-20 13:07:21 +00006488#ifdef SQLITE_TEST
6489/* simulate multiple hosts by creating unique hostid file paths */
6490int sqlite3_hostid_num = 0;
6491#endif
6492
6493#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6494
drh0ab216a2010-07-02 17:10:40 +00006495/* Not always defined in the headers as it ought to be */
6496extern int gethostuuid(uuid_t id, const struct timespec *wait);
6497
drh7ed97b92010-01-20 13:07:21 +00006498/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6499** bytes of writable memory.
6500*/
6501static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006502 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6503 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006504#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6505 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006506 {
6507 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6508 if( gethostuuid(pHostID, &timeout) ){
6509 int err = errno;
6510 if( pError ){
6511 *pError = err;
6512 }
6513 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006514 }
drh7ed97b92010-01-20 13:07:21 +00006515 }
drh3d4435b2011-08-26 20:55:50 +00006516#else
6517 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006518#endif
drh7ed97b92010-01-20 13:07:21 +00006519#ifdef SQLITE_TEST
6520 /* simulate multiple hosts by creating unique hostid file paths */
6521 if( sqlite3_hostid_num != 0){
6522 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6523 }
6524#endif
6525
6526 return SQLITE_OK;
6527}
6528
6529/* The conch file contains the header, host id and lock file path
6530 */
6531#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6532#define PROXY_HEADERLEN 1 /* conch file header length */
6533#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6534#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6535
6536/*
6537** Takes an open conch file, copies the contents to a new path and then moves
6538** it back. The newly created file's file descriptor is assigned to the
6539** conch file structure and finally the original conch file descriptor is
6540** closed. Returns zero if successful.
6541*/
6542static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6543 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6544 unixFile *conchFile = pCtx->conchFile;
6545 char tPath[MAXPATHLEN];
6546 char buf[PROXY_MAXCONCHLEN];
6547 char *cPath = pCtx->conchFilePath;
6548 size_t readLen = 0;
6549 size_t pathLen = 0;
6550 char errmsg[64] = "";
6551 int fd = -1;
6552 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006553 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006554
6555 /* create a new path by replace the trailing '-conch' with '-break' */
6556 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6557 if( pathLen>MAXPATHLEN || pathLen<6 ||
6558 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006559 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006560 goto end_breaklock;
6561 }
6562 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006563 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006564 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006565 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006566 goto end_breaklock;
6567 }
6568 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006569 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006570 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006571 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006572 goto end_breaklock;
6573 }
drhe562be52011-03-02 18:01:10 +00006574 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006575 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006576 goto end_breaklock;
6577 }
6578 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006579 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006580 goto end_breaklock;
6581 }
6582 rc = 0;
6583 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006584 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006585 conchFile->h = fd;
6586 conchFile->openFlags = O_RDWR | O_CREAT;
6587
6588end_breaklock:
6589 if( rc ){
6590 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006591 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006592 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006593 }
6594 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6595 }
6596 return rc;
6597}
6598
6599/* Take the requested lock on the conch file and break a stale lock if the
6600** host id matches.
6601*/
6602static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6603 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6604 unixFile *conchFile = pCtx->conchFile;
6605 int rc = SQLITE_OK;
6606 int nTries = 0;
6607 struct timespec conchModTime;
6608
drh3d4435b2011-08-26 20:55:50 +00006609 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006610 do {
6611 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6612 nTries ++;
6613 if( rc==SQLITE_BUSY ){
6614 /* If the lock failed (busy):
6615 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6616 * 2nd try: fail if the mod time changed or host id is different, wait
6617 * 10 sec and try again
6618 * 3rd try: break the lock unless the mod time has changed.
6619 */
6620 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006621 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006622 pFile->lastErrno = errno;
6623 return SQLITE_IOERR_LOCK;
6624 }
6625
6626 if( nTries==1 ){
6627 conchModTime = buf.st_mtimespec;
6628 usleep(500000); /* wait 0.5 sec and try the lock again*/
6629 continue;
6630 }
6631
6632 assert( nTries>1 );
6633 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6634 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6635 return SQLITE_BUSY;
6636 }
6637
6638 if( nTries==2 ){
6639 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006640 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006641 if( len<0 ){
6642 pFile->lastErrno = errno;
6643 return SQLITE_IOERR_LOCK;
6644 }
6645 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6646 /* don't break the lock if the host id doesn't match */
6647 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6648 return SQLITE_BUSY;
6649 }
6650 }else{
6651 /* don't break the lock on short read or a version mismatch */
6652 return SQLITE_BUSY;
6653 }
6654 usleep(10000000); /* wait 10 sec and try the lock again */
6655 continue;
6656 }
6657
6658 assert( nTries==3 );
6659 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6660 rc = SQLITE_OK;
6661 if( lockType==EXCLUSIVE_LOCK ){
6662 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6663 }
6664 if( !rc ){
6665 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6666 }
6667 }
6668 }
6669 } while( rc==SQLITE_BUSY && nTries<3 );
6670
6671 return rc;
6672}
6673
6674/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006675** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6676** lockPath means that the lockPath in the conch file will be used if the
6677** host IDs match, or a new lock path will be generated automatically
6678** and written to the conch file.
6679*/
6680static int proxyTakeConch(unixFile *pFile){
6681 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6682
drh7ed97b92010-01-20 13:07:21 +00006683 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006684 return SQLITE_OK;
6685 }else{
6686 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006687 uuid_t myHostID;
6688 int pError = 0;
6689 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006690 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006691 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006692 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006693 int createConch = 0;
6694 int hostIdMatch = 0;
6695 int readLen = 0;
6696 int tryOldLockPath = 0;
6697 int forceNewLockPath = 0;
6698
drh308c2a52010-05-14 11:30:18 +00006699 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6700 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006701
drh7ed97b92010-01-20 13:07:21 +00006702 rc = proxyGetHostID(myHostID, &pError);
6703 if( (rc&0xff)==SQLITE_IOERR ){
6704 pFile->lastErrno = pError;
6705 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006706 }
drh7ed97b92010-01-20 13:07:21 +00006707 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006708 if( rc!=SQLITE_OK ){
6709 goto end_takeconch;
6710 }
drh7ed97b92010-01-20 13:07:21 +00006711 /* read the existing conch file */
6712 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6713 if( readLen<0 ){
6714 /* I/O error: lastErrno set by seekAndRead */
6715 pFile->lastErrno = conchFile->lastErrno;
6716 rc = SQLITE_IOERR_READ;
6717 goto end_takeconch;
6718 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6719 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6720 /* a short read or version format mismatch means we need to create a new
6721 ** conch file.
6722 */
6723 createConch = 1;
6724 }
6725 /* if the host id matches and the lock path already exists in the conch
6726 ** we'll try to use the path there, if we can't open that path, we'll
6727 ** retry with a new auto-generated path
6728 */
6729 do { /* in case we need to try again for an :auto: named lock file */
6730
6731 if( !createConch && !forceNewLockPath ){
6732 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6733 PROXY_HOSTIDLEN);
6734 /* if the conch has data compare the contents */
6735 if( !pCtx->lockProxyPath ){
6736 /* for auto-named local lock file, just check the host ID and we'll
6737 ** use the local lock file path that's already in there
6738 */
6739 if( hostIdMatch ){
6740 size_t pathLen = (readLen - PROXY_PATHINDEX);
6741
6742 if( pathLen>=MAXPATHLEN ){
6743 pathLen=MAXPATHLEN-1;
6744 }
6745 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6746 lockPath[pathLen] = 0;
6747 tempLockPath = lockPath;
6748 tryOldLockPath = 1;
6749 /* create a copy of the lock path if the conch is taken */
6750 goto end_takeconch;
6751 }
6752 }else if( hostIdMatch
6753 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6754 readLen-PROXY_PATHINDEX)
6755 ){
6756 /* conch host and lock path match */
6757 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006758 }
drh7ed97b92010-01-20 13:07:21 +00006759 }
6760
6761 /* if the conch isn't writable and doesn't match, we can't take it */
6762 if( (conchFile->openFlags&O_RDWR) == 0 ){
6763 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006764 goto end_takeconch;
6765 }
drh7ed97b92010-01-20 13:07:21 +00006766
6767 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006768 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006769 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6770 tempLockPath = lockPath;
6771 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006772 }
drh7ed97b92010-01-20 13:07:21 +00006773
6774 /* update conch with host and path (this will fail if other process
6775 ** has a shared lock already), if the host id matches, use the big
6776 ** stick.
drh715ff302008-12-03 22:32:44 +00006777 */
drh7ed97b92010-01-20 13:07:21 +00006778 futimes(conchFile->h, NULL);
6779 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006780 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006781 /* We are trying for an exclusive lock but another thread in this
6782 ** same process is still holding a shared lock. */
6783 rc = SQLITE_BUSY;
6784 } else {
6785 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006786 }
drh715ff302008-12-03 22:32:44 +00006787 }else{
drh7ed97b92010-01-20 13:07:21 +00006788 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006789 }
drh7ed97b92010-01-20 13:07:21 +00006790 if( rc==SQLITE_OK ){
6791 char writeBuffer[PROXY_MAXCONCHLEN];
6792 int writeSize = 0;
6793
6794 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6795 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6796 if( pCtx->lockProxyPath!=NULL ){
6797 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6798 }else{
6799 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6800 }
6801 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006802 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006803 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6804 fsync(conchFile->h);
6805 /* If we created a new conch file (not just updated the contents of a
6806 ** valid conch file), try to match the permissions of the database
6807 */
6808 if( rc==SQLITE_OK && createConch ){
6809 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006810 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006811 if( err==0 ){
6812 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6813 S_IROTH|S_IWOTH);
6814 /* try to match the database file R/W permissions, ignore failure */
6815#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006816 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006817#else
drhff812312011-02-23 13:33:46 +00006818 do{
drhe562be52011-03-02 18:01:10 +00006819 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006820 }while( rc==(-1) && errno==EINTR );
6821 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006822 int code = errno;
6823 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6824 cmode, code, strerror(code));
6825 } else {
6826 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6827 }
6828 }else{
6829 int code = errno;
6830 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6831 err, code, strerror(code));
6832#endif
6833 }
drh715ff302008-12-03 22:32:44 +00006834 }
6835 }
drh7ed97b92010-01-20 13:07:21 +00006836 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6837
6838 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006839 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006840 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006841 int fd;
drh7ed97b92010-01-20 13:07:21 +00006842 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006843 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006844 }
6845 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006846 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006847 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006848 if( fd>=0 ){
6849 pFile->h = fd;
6850 }else{
drh9978c972010-02-23 17:36:32 +00006851 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006852 during locking */
6853 }
6854 }
6855 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6856 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6857 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6858 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6859 /* we couldn't create the proxy lock file with the old lock file path
6860 ** so try again via auto-naming
6861 */
6862 forceNewLockPath = 1;
6863 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006864 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006865 }
6866 }
6867 if( rc==SQLITE_OK ){
6868 /* Need to make a copy of path if we extracted the value
6869 ** from the conch file or the path was allocated on the stack
6870 */
6871 if( tempLockPath ){
6872 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6873 if( !pCtx->lockProxyPath ){
6874 rc = SQLITE_NOMEM;
6875 }
6876 }
6877 }
6878 if( rc==SQLITE_OK ){
6879 pCtx->conchHeld = 1;
6880
6881 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6882 afpLockingContext *afpCtx;
6883 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6884 afpCtx->dbPath = pCtx->lockProxyPath;
6885 }
6886 } else {
6887 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6888 }
drh308c2a52010-05-14 11:30:18 +00006889 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6890 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006891 return rc;
drh308c2a52010-05-14 11:30:18 +00006892 } while (1); /* in case we need to retry the :auto: lock file -
6893 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006894 }
6895}
6896
6897/*
6898** If pFile holds a lock on a conch file, then release that lock.
6899*/
6900static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006901 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006902 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6903 unixFile *conchFile; /* Name of the conch file */
6904
6905 pCtx = (proxyLockingContext *)pFile->lockingContext;
6906 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006907 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006908 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006909 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006910 if( pCtx->conchHeld>0 ){
6911 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6912 }
drh715ff302008-12-03 22:32:44 +00006913 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006914 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6915 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006916 return rc;
6917}
6918
6919/*
6920** Given the name of a database file, compute the name of its conch file.
6921** Store the conch filename in memory obtained from sqlite3_malloc().
6922** Make *pConchPath point to the new name. Return SQLITE_OK on success
6923** or SQLITE_NOMEM if unable to obtain memory.
6924**
6925** The caller is responsible for ensuring that the allocated memory
6926** space is eventually freed.
6927**
6928** *pConchPath is set to NULL if a memory allocation error occurs.
6929*/
6930static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6931 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006932 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006933 char *conchPath; /* buffer in which to construct conch name */
6934
6935 /* Allocate space for the conch filename and initialize the name to
6936 ** the name of the original database file. */
6937 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6938 if( conchPath==0 ){
6939 return SQLITE_NOMEM;
6940 }
6941 memcpy(conchPath, dbPath, len+1);
6942
6943 /* now insert a "." before the last / character */
6944 for( i=(len-1); i>=0; i-- ){
6945 if( conchPath[i]=='/' ){
6946 i++;
6947 break;
6948 }
6949 }
6950 conchPath[i]='.';
6951 while ( i<len ){
6952 conchPath[i+1]=dbPath[i];
6953 i++;
6954 }
6955
6956 /* append the "-conch" suffix to the file */
6957 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006958 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006959
6960 return SQLITE_OK;
6961}
6962
6963
6964/* Takes a fully configured proxy locking-style unix file and switches
6965** the local lock file path
6966*/
6967static int switchLockProxyPath(unixFile *pFile, const char *path) {
6968 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6969 char *oldPath = pCtx->lockProxyPath;
6970 int rc = SQLITE_OK;
6971
drh308c2a52010-05-14 11:30:18 +00006972 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006973 return SQLITE_BUSY;
6974 }
6975
6976 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6977 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6978 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6979 return SQLITE_OK;
6980 }else{
6981 unixFile *lockProxy = pCtx->lockProxy;
6982 pCtx->lockProxy=NULL;
6983 pCtx->conchHeld = 0;
6984 if( lockProxy!=NULL ){
6985 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6986 if( rc ) return rc;
6987 sqlite3_free(lockProxy);
6988 }
6989 sqlite3_free(oldPath);
6990 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6991 }
6992
6993 return rc;
6994}
6995
6996/*
6997** pFile is a file that has been opened by a prior xOpen call. dbPath
6998** is a string buffer at least MAXPATHLEN+1 characters in size.
6999**
7000** This routine find the filename associated with pFile and writes it
7001** int dbPath.
7002*/
7003static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007004#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007005 if( pFile->pMethod == &afpIoMethods ){
7006 /* afp style keeps a reference to the db path in the filePath field
7007 ** of the struct */
drhea678832008-12-10 19:26:22 +00007008 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007009 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
7010 } else
drh715ff302008-12-03 22:32:44 +00007011#endif
7012 if( pFile->pMethod == &dotlockIoMethods ){
7013 /* dot lock style uses the locking context to store the dot lock
7014 ** file path */
7015 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7016 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7017 }else{
7018 /* all other styles use the locking context to store the db file path */
7019 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007020 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007021 }
7022 return SQLITE_OK;
7023}
7024
7025/*
7026** Takes an already filled in unix file and alters it so all file locking
7027** will be performed on the local proxy lock file. The following fields
7028** are preserved in the locking context so that they can be restored and
7029** the unix structure properly cleaned up at close time:
7030** ->lockingContext
7031** ->pMethod
7032*/
7033static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7034 proxyLockingContext *pCtx;
7035 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7036 char *lockPath=NULL;
7037 int rc = SQLITE_OK;
7038
drh308c2a52010-05-14 11:30:18 +00007039 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007040 return SQLITE_BUSY;
7041 }
7042 proxyGetDbPathForUnixFile(pFile, dbPath);
7043 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7044 lockPath=NULL;
7045 }else{
7046 lockPath=(char *)path;
7047 }
7048
drh308c2a52010-05-14 11:30:18 +00007049 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7050 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007051
7052 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7053 if( pCtx==0 ){
7054 return SQLITE_NOMEM;
7055 }
7056 memset(pCtx, 0, sizeof(*pCtx));
7057
7058 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7059 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007060 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7061 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7062 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7063 ** (c) the file system is read-only, then enable no-locking access.
7064 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7065 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7066 */
7067 struct statfs fsInfo;
7068 struct stat conchInfo;
7069 int goLockless = 0;
7070
drh99ab3b12011-03-02 15:09:07 +00007071 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007072 int err = errno;
7073 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7074 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7075 }
7076 }
7077 if( goLockless ){
7078 pCtx->conchHeld = -1; /* read only FS/ lockless */
7079 rc = SQLITE_OK;
7080 }
7081 }
drh715ff302008-12-03 22:32:44 +00007082 }
7083 if( rc==SQLITE_OK && lockPath ){
7084 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7085 }
7086
7087 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007088 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7089 if( pCtx->dbPath==NULL ){
7090 rc = SQLITE_NOMEM;
7091 }
7092 }
7093 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007094 /* all memory is allocated, proxys are created and assigned,
7095 ** switch the locking context and pMethod then return.
7096 */
drh715ff302008-12-03 22:32:44 +00007097 pCtx->oldLockingContext = pFile->lockingContext;
7098 pFile->lockingContext = pCtx;
7099 pCtx->pOldMethod = pFile->pMethod;
7100 pFile->pMethod = &proxyIoMethods;
7101 }else{
7102 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007103 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007104 sqlite3_free(pCtx->conchFile);
7105 }
drhd56b1212010-08-11 06:14:15 +00007106 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007107 sqlite3_free(pCtx->conchFilePath);
7108 sqlite3_free(pCtx);
7109 }
drh308c2a52010-05-14 11:30:18 +00007110 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7111 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007112 return rc;
7113}
7114
7115
7116/*
7117** This routine handles sqlite3_file_control() calls that are specific
7118** to proxy locking.
7119*/
7120static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7121 switch( op ){
7122 case SQLITE_GET_LOCKPROXYFILE: {
7123 unixFile *pFile = (unixFile*)id;
7124 if( pFile->pMethod == &proxyIoMethods ){
7125 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7126 proxyTakeConch(pFile);
7127 if( pCtx->lockProxyPath ){
7128 *(const char **)pArg = pCtx->lockProxyPath;
7129 }else{
7130 *(const char **)pArg = ":auto: (not held)";
7131 }
7132 } else {
7133 *(const char **)pArg = NULL;
7134 }
7135 return SQLITE_OK;
7136 }
7137 case SQLITE_SET_LOCKPROXYFILE: {
7138 unixFile *pFile = (unixFile*)id;
7139 int rc = SQLITE_OK;
7140 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7141 if( pArg==NULL || (const char *)pArg==0 ){
7142 if( isProxyStyle ){
7143 /* turn off proxy locking - not supported */
7144 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7145 }else{
7146 /* turn off proxy locking - already off - NOOP */
7147 rc = SQLITE_OK;
7148 }
7149 }else{
7150 const char *proxyPath = (const char *)pArg;
7151 if( isProxyStyle ){
7152 proxyLockingContext *pCtx =
7153 (proxyLockingContext*)pFile->lockingContext;
7154 if( !strcmp(pArg, ":auto:")
7155 || (pCtx->lockProxyPath &&
7156 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7157 ){
7158 rc = SQLITE_OK;
7159 }else{
7160 rc = switchLockProxyPath(pFile, proxyPath);
7161 }
7162 }else{
7163 /* turn on proxy file locking */
7164 rc = proxyTransformUnixFile(pFile, proxyPath);
7165 }
7166 }
7167 return rc;
7168 }
7169 default: {
7170 assert( 0 ); /* The call assures that only valid opcodes are sent */
7171 }
7172 }
7173 /*NOTREACHED*/
7174 return SQLITE_ERROR;
7175}
7176
7177/*
7178** Within this division (the proxying locking implementation) the procedures
7179** above this point are all utilities. The lock-related methods of the
7180** proxy-locking sqlite3_io_method object follow.
7181*/
7182
7183
7184/*
7185** This routine checks if there is a RESERVED lock held on the specified
7186** file by this or any other process. If such a lock is held, set *pResOut
7187** to a non-zero value otherwise *pResOut is set to zero. The return value
7188** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7189*/
7190static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7191 unixFile *pFile = (unixFile*)id;
7192 int rc = proxyTakeConch(pFile);
7193 if( rc==SQLITE_OK ){
7194 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007195 if( pCtx->conchHeld>0 ){
7196 unixFile *proxy = pCtx->lockProxy;
7197 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7198 }else{ /* conchHeld < 0 is lockless */
7199 pResOut=0;
7200 }
drh715ff302008-12-03 22:32:44 +00007201 }
7202 return rc;
7203}
7204
7205/*
drh308c2a52010-05-14 11:30:18 +00007206** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007207** of the following:
7208**
7209** (1) SHARED_LOCK
7210** (2) RESERVED_LOCK
7211** (3) PENDING_LOCK
7212** (4) EXCLUSIVE_LOCK
7213**
7214** Sometimes when requesting one lock state, additional lock states
7215** are inserted in between. The locking might fail on one of the later
7216** transitions leaving the lock state different from what it started but
7217** still short of its goal. The following chart shows the allowed
7218** transitions and the inserted intermediate states:
7219**
7220** UNLOCKED -> SHARED
7221** SHARED -> RESERVED
7222** SHARED -> (PENDING) -> EXCLUSIVE
7223** RESERVED -> (PENDING) -> EXCLUSIVE
7224** PENDING -> EXCLUSIVE
7225**
7226** This routine will only increase a lock. Use the sqlite3OsUnlock()
7227** routine to lower a locking level.
7228*/
drh308c2a52010-05-14 11:30:18 +00007229static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007230 unixFile *pFile = (unixFile*)id;
7231 int rc = proxyTakeConch(pFile);
7232 if( rc==SQLITE_OK ){
7233 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007234 if( pCtx->conchHeld>0 ){
7235 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007236 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7237 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007238 }else{
7239 /* conchHeld < 0 is lockless */
7240 }
drh715ff302008-12-03 22:32:44 +00007241 }
7242 return rc;
7243}
7244
7245
7246/*
drh308c2a52010-05-14 11:30:18 +00007247** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007248** must be either NO_LOCK or SHARED_LOCK.
7249**
7250** If the locking level of the file descriptor is already at or below
7251** the requested locking level, this routine is a no-op.
7252*/
drh308c2a52010-05-14 11:30:18 +00007253static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007254 unixFile *pFile = (unixFile*)id;
7255 int rc = proxyTakeConch(pFile);
7256 if( rc==SQLITE_OK ){
7257 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007258 if( pCtx->conchHeld>0 ){
7259 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007260 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7261 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007262 }else{
7263 /* conchHeld < 0 is lockless */
7264 }
drh715ff302008-12-03 22:32:44 +00007265 }
7266 return rc;
7267}
7268
7269/*
7270** Close a file that uses proxy locks.
7271*/
7272static int proxyClose(sqlite3_file *id) {
7273 if( id ){
7274 unixFile *pFile = (unixFile*)id;
7275 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7276 unixFile *lockProxy = pCtx->lockProxy;
7277 unixFile *conchFile = pCtx->conchFile;
7278 int rc = SQLITE_OK;
7279
7280 if( lockProxy ){
7281 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7282 if( rc ) return rc;
7283 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7284 if( rc ) return rc;
7285 sqlite3_free(lockProxy);
7286 pCtx->lockProxy = 0;
7287 }
7288 if( conchFile ){
7289 if( pCtx->conchHeld ){
7290 rc = proxyReleaseConch(pFile);
7291 if( rc ) return rc;
7292 }
7293 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7294 if( rc ) return rc;
7295 sqlite3_free(conchFile);
7296 }
drhd56b1212010-08-11 06:14:15 +00007297 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007298 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007299 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007300 /* restore the original locking context and pMethod then close it */
7301 pFile->lockingContext = pCtx->oldLockingContext;
7302 pFile->pMethod = pCtx->pOldMethod;
7303 sqlite3_free(pCtx);
7304 return pFile->pMethod->xClose(id);
7305 }
7306 return SQLITE_OK;
7307}
7308
7309
7310
drhd2cb50b2009-01-09 21:41:17 +00007311#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007312/*
7313** The proxy locking style is intended for use with AFP filesystems.
7314** And since AFP is only supported on MacOSX, the proxy locking is also
7315** restricted to MacOSX.
7316**
7317**
7318******************* End of the proxy lock implementation **********************
7319******************************************************************************/
7320
drh734c9862008-11-28 15:37:20 +00007321/*
danielk1977e339d652008-06-28 11:23:00 +00007322** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007323**
7324** This routine registers all VFS implementations for unix-like operating
7325** systems. This routine, and the sqlite3_os_end() routine that follows,
7326** should be the only routines in this file that are visible from other
7327** files.
drh6b9d6dd2008-12-03 19:34:47 +00007328**
7329** This routine is called once during SQLite initialization and by a
7330** single thread. The memory allocation and mutex subsystems have not
7331** necessarily been initialized when this routine is called, and so they
7332** should not be used.
drh153c62c2007-08-24 03:51:33 +00007333*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007334int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007335 /*
7336 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007337 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7338 ** to the "finder" function. (pAppData is a pointer to a pointer because
7339 ** silly C90 rules prohibit a void* from being cast to a function pointer
7340 ** and so we have to go through the intermediate pointer to avoid problems
7341 ** when compiling with -pedantic-errors on GCC.)
7342 **
7343 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007344 ** finder-function. The finder-function returns a pointer to the
7345 ** sqlite_io_methods object that implements the desired locking
7346 ** behaviors. See the division above that contains the IOMETHODS
7347 ** macro for addition information on finder-functions.
7348 **
7349 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7350 ** object. But the "autolockIoFinder" available on MacOSX does a little
7351 ** more than that; it looks at the filesystem type that hosts the
7352 ** database file and tries to choose an locking method appropriate for
7353 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007354 */
drh7708e972008-11-29 00:56:52 +00007355 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007356 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007357 sizeof(unixFile), /* szOsFile */ \
7358 MAX_PATHNAME, /* mxPathname */ \
7359 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007360 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007361 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007362 unixOpen, /* xOpen */ \
7363 unixDelete, /* xDelete */ \
7364 unixAccess, /* xAccess */ \
7365 unixFullPathname, /* xFullPathname */ \
7366 unixDlOpen, /* xDlOpen */ \
7367 unixDlError, /* xDlError */ \
7368 unixDlSym, /* xDlSym */ \
7369 unixDlClose, /* xDlClose */ \
7370 unixRandomness, /* xRandomness */ \
7371 unixSleep, /* xSleep */ \
7372 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007373 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007374 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007375 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007376 unixGetSystemCall, /* xGetSystemCall */ \
7377 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007378 }
7379
drh6b9d6dd2008-12-03 19:34:47 +00007380 /*
7381 ** All default VFSes for unix are contained in the following array.
7382 **
7383 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7384 ** by the SQLite core when the VFS is registered. So the following
7385 ** array cannot be const.
7386 */
danielk1977e339d652008-06-28 11:23:00 +00007387 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007388#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007389 UNIXVFS("unix", autolockIoFinder ),
7390#else
7391 UNIXVFS("unix", posixIoFinder ),
7392#endif
7393 UNIXVFS("unix-none", nolockIoFinder ),
7394 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007395 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007396#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007397 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007398#endif
7399#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007400 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007401#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007402 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007403#endif
chw78a13182009-04-07 05:35:03 +00007404#endif
drhd2cb50b2009-01-09 21:41:17 +00007405#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007406 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007407 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007408 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007409#endif
drh153c62c2007-08-24 03:51:33 +00007410 };
drh6b9d6dd2008-12-03 19:34:47 +00007411 unsigned int i; /* Loop counter */
7412
drh2aa5a002011-04-13 13:42:25 +00007413 /* Double-check that the aSyscall[] array has been constructed
7414 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhd1ab8062013-03-25 20:50:25 +00007415 assert( ArraySize(aSyscall)==24 );
drh2aa5a002011-04-13 13:42:25 +00007416
drh6b9d6dd2008-12-03 19:34:47 +00007417 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007418 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007419 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007420 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007421 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007422}
danielk1977e339d652008-06-28 11:23:00 +00007423
7424/*
drh6b9d6dd2008-12-03 19:34:47 +00007425** Shutdown the operating system interface.
7426**
7427** Some operating systems might need to do some cleanup in this routine,
7428** to release dynamically allocated objects. But not on unix.
7429** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007430*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007431int sqlite3_os_end(void){
7432 return SQLITE_OK;
7433}
drhdce8bdb2007-08-16 13:01:44 +00007434
danielk197729bafea2008-06-26 10:41:19 +00007435#endif /* SQLITE_OS_UNIX */