blob: 016415149fd35f2b7ba7c13df2b3e50393d9aa3a [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>
drhf2424c52010-04-26 00:04:55 +0000122#include <sys/mman.h>
danielk1977e339d652008-06-28 11:23:00 +0000123
drh40bbb0a2008-09-23 10:23:26 +0000124#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000125# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000126# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <semaphore.h>
128# include <limits.h>
129# else
drh9b35ea62008-11-29 02:20:26 +0000130# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000131# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000132# endif
drhbfe66312006-10-03 17:40:40 +0000133#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000134
drhf8b4d8c2010-03-05 13:53:22 +0000135#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000136# include <sys/mount.h>
137#endif
138
drh9cbe6352005-11-29 03:13:21 +0000139/*
drh7ed97b92010-01-20 13:07:21 +0000140** Allowed values of unixFile.fsFlags
141*/
142#define SQLITE_FSFLAGS_IS_MSDOS 0x1
143
144/*
drhf1a221e2006-01-15 17:27:17 +0000145** If we are to be thread-safe, include the pthreads header and define
146** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000147*/
drhd677b3d2007-08-20 22:48:41 +0000148#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000149# include <pthread.h>
150# define SQLITE_UNIX_THREADS 1
151#endif
152
153/*
154** Default permissions when creating a new file
155*/
156#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
157# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
158#endif
159
danielk1977b4b47412007-08-17 15:53:36 +0000160/*
aswiftaebf4132008-11-21 00:10:35 +0000161 ** Default permissions when creating auto proxy dir
162 */
163#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
164# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
165#endif
166
167/*
danielk1977b4b47412007-08-17 15:53:36 +0000168** Maximum supported path-length.
169*/
170#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000171
drh734c9862008-11-28 15:37:20 +0000172/*
drh734c9862008-11-28 15:37:20 +0000173** Only set the lastErrno if the error code is a real error and not
174** a normal expected return code of SQLITE_BUSY or SQLITE_OK
175*/
176#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
177
drhd9e5c4f2010-05-12 18:01:39 +0000178/* Forward reference */
179typedef struct unixShm unixShm;
180typedef struct unixShmFile unixShmFile;
drh9cbe6352005-11-29 03:13:21 +0000181
182/*
dane946c392009-08-22 11:39:46 +0000183** Sometimes, after a file handle is closed by SQLite, the file descriptor
184** cannot be closed immediately. In these cases, instances of the following
185** structure are used to store the file descriptor while waiting for an
186** opportunity to either close or reuse it.
187*/
188typedef struct UnixUnusedFd UnixUnusedFd;
189struct UnixUnusedFd {
190 int fd; /* File descriptor to close */
191 int flags; /* Flags this file descriptor was opened with */
192 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
193};
194
195/*
drh9b35ea62008-11-29 02:20:26 +0000196** The unixFile structure is subclass of sqlite3_file specific to the unix
197** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000198*/
drh054889e2005-11-30 03:20:31 +0000199typedef struct unixFile unixFile;
200struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000201 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh8af6c222010-05-14 12:43:01 +0000202 struct unixInodeInfo *pInode; /* Info about locks on this inode */
203 int h; /* The file descriptor */
204 int dirfd; /* File descriptor for the directory */
205 unsigned char eFileLock; /* The type of lock held on this fd */
206 int lastErrno; /* The unix errno from last I/O error */
207 void *lockingContext; /* Locking style specific state */
208 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
209 int fileFlags; /* Miscellanous flags */
210 const char *zPath; /* Name of the file */
211 unixShm *pShm; /* Shared memory segment information */
drh08c6d442009-02-09 17:34:07 +0000212#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000213 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000214#endif
drh7ed97b92010-01-20 13:07:21 +0000215#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000216 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000217#endif
218#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000219 int isDelete; /* Delete on close if true */
220 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000221#endif
drh8f941bc2009-01-14 23:03:40 +0000222#ifndef NDEBUG
223 /* The next group of variables are used to track whether or not the
224 ** transaction counter in bytes 24-27 of database files are updated
225 ** whenever any part of the database changes. An assertion fault will
226 ** occur if a file is updated without also updating the transaction
227 ** counter. This test is made to avoid new problems similar to the
228 ** one described by ticket #3584.
229 */
230 unsigned char transCntrChng; /* True if the transaction counter changed */
231 unsigned char dbUpdate; /* True if any part of database file changed */
232 unsigned char inNormalWrite; /* True if in a normal write operation */
233#endif
danielk1977967a4a12007-08-20 14:23:44 +0000234#ifdef SQLITE_TEST
235 /* In test mode, increase the size of this structure a bit so that
236 ** it is larger than the struct CrashFile defined in test6.c.
237 */
238 char aPadding[32];
239#endif
drh9cbe6352005-11-29 03:13:21 +0000240};
241
drh0ccebe72005-06-07 22:22:50 +0000242/*
drh0c2694b2009-09-03 16:23:44 +0000243** The following macros define bits in unixFile.fileFlags
244*/
245#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
246
247/*
drh198bf392006-01-06 21:52:49 +0000248** Include code that is common to all os_*.c files
249*/
250#include "os_common.h"
251
252/*
drh0ccebe72005-06-07 22:22:50 +0000253** Define various macros that are missing from some systems.
254*/
drhbbd42a62004-05-22 17:41:58 +0000255#ifndef O_LARGEFILE
256# define O_LARGEFILE 0
257#endif
258#ifdef SQLITE_DISABLE_LFS
259# undef O_LARGEFILE
260# define O_LARGEFILE 0
261#endif
262#ifndef O_NOFOLLOW
263# define O_NOFOLLOW 0
264#endif
265#ifndef O_BINARY
266# define O_BINARY 0
267#endif
268
269/*
270** The DJGPP compiler environment looks mostly like Unix, but it
271** lacks the fcntl() system call. So redefine fcntl() to be something
272** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000273** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000274*/
275#ifdef __DJGPP__
276# define fcntl(A,B,C) 0
277#endif
278
279/*
drh2b4b5962005-06-15 17:47:55 +0000280** The threadid macro resolves to the thread-id or to 0. Used for
281** testing and debugging only.
282*/
drhd677b3d2007-08-20 22:48:41 +0000283#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000284#define threadid pthread_self()
285#else
286#define threadid 0
287#endif
288
danielk197713adf8a2004-06-03 16:08:41 +0000289
drh107886a2008-11-21 22:21:50 +0000290/*
dan9359c7b2009-08-21 08:29:10 +0000291** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000292** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000293** vxworksFileId objects used by this file, all of which may be
294** shared by multiple threads.
295**
296** Function unixMutexHeld() is used to assert() that the global mutex
297** is held when required. This function is only used as part of assert()
298** statements. e.g.
299**
300** unixEnterMutex()
301** assert( unixMutexHeld() );
302** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000303*/
304static void unixEnterMutex(void){
305 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
306}
307static void unixLeaveMutex(void){
308 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
309}
dan9359c7b2009-08-21 08:29:10 +0000310#ifdef SQLITE_DEBUG
311static int unixMutexHeld(void) {
312 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
313}
314#endif
drh107886a2008-11-21 22:21:50 +0000315
drh734c9862008-11-28 15:37:20 +0000316
317#ifdef SQLITE_DEBUG
318/*
319** Helper function for printing out trace information from debugging
320** binaries. This returns the string represetation of the supplied
321** integer lock-type.
322*/
drh308c2a52010-05-14 11:30:18 +0000323static const char *azFileLock(int eFileLock){
324 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000325 case NO_LOCK: return "NONE";
326 case SHARED_LOCK: return "SHARED";
327 case RESERVED_LOCK: return "RESERVED";
328 case PENDING_LOCK: return "PENDING";
329 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000330 }
331 return "ERROR";
332}
333#endif
334
335#ifdef SQLITE_LOCK_TRACE
336/*
337** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000338**
drh734c9862008-11-28 15:37:20 +0000339** This routine is used for troubleshooting locks on multithreaded
340** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
341** command-line option on the compiler. This code is normally
342** turned off.
343*/
344static int lockTrace(int fd, int op, struct flock *p){
345 char *zOpName, *zType;
346 int s;
347 int savedErrno;
348 if( op==F_GETLK ){
349 zOpName = "GETLK";
350 }else if( op==F_SETLK ){
351 zOpName = "SETLK";
352 }else{
353 s = fcntl(fd, op, p);
354 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
355 return s;
356 }
357 if( p->l_type==F_RDLCK ){
358 zType = "RDLCK";
359 }else if( p->l_type==F_WRLCK ){
360 zType = "WRLCK";
361 }else if( p->l_type==F_UNLCK ){
362 zType = "UNLCK";
363 }else{
364 assert( 0 );
365 }
366 assert( p->l_whence==SEEK_SET );
367 s = fcntl(fd, op, p);
368 savedErrno = errno;
369 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
370 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
371 (int)p->l_pid, s);
372 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
373 struct flock l2;
374 l2 = *p;
375 fcntl(fd, F_GETLK, &l2);
376 if( l2.l_type==F_RDLCK ){
377 zType = "RDLCK";
378 }else if( l2.l_type==F_WRLCK ){
379 zType = "WRLCK";
380 }else if( l2.l_type==F_UNLCK ){
381 zType = "UNLCK";
382 }else{
383 assert( 0 );
384 }
385 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
386 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
387 }
388 errno = savedErrno;
389 return s;
390}
391#define fcntl lockTrace
392#endif /* SQLITE_LOCK_TRACE */
393
394
395
396/*
397** This routine translates a standard POSIX errno code into something
398** useful to the clients of the sqlite3 functions. Specifically, it is
399** intended to translate a variety of "try again" errors into SQLITE_BUSY
400** and a variety of "please close the file descriptor NOW" errors into
401** SQLITE_IOERR
402**
403** Errors during initialization of locks, or file system support for locks,
404** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
405*/
406static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
407 switch (posixError) {
408 case 0:
409 return SQLITE_OK;
410
411 case EAGAIN:
412 case ETIMEDOUT:
413 case EBUSY:
414 case EINTR:
415 case ENOLCK:
416 /* random NFS retry error, unless during file system support
417 * introspection, in which it actually means what it says */
418 return SQLITE_BUSY;
419
420 case EACCES:
421 /* EACCES is like EAGAIN during locking operations, but not any other time*/
422 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
423 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
424 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
425 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
426 return SQLITE_BUSY;
427 }
428 /* else fall through */
429 case EPERM:
430 return SQLITE_PERM;
431
432 case EDEADLK:
433 return SQLITE_IOERR_BLOCKED;
434
435#if EOPNOTSUPP!=ENOTSUP
436 case EOPNOTSUPP:
437 /* something went terribly awry, unless during file system support
438 * introspection, in which it actually means what it says */
439#endif
440#ifdef ENOTSUP
441 case ENOTSUP:
442 /* invalid fd, unless during file system support introspection, in which
443 * it actually means what it says */
444#endif
445 case EIO:
446 case EBADF:
447 case EINVAL:
448 case ENOTCONN:
449 case ENODEV:
450 case ENXIO:
451 case ENOENT:
452 case ESTALE:
453 case ENOSYS:
454 /* these should force the client to close the file and reconnect */
455
456 default:
457 return sqliteIOErr;
458 }
459}
460
461
462
463/******************************************************************************
464****************** Begin Unique File ID Utility Used By VxWorks ***************
465**
466** On most versions of unix, we can get a unique ID for a file by concatenating
467** the device number and the inode number. But this does not work on VxWorks.
468** On VxWorks, a unique file id must be based on the canonical filename.
469**
470** A pointer to an instance of the following structure can be used as a
471** unique file ID in VxWorks. Each instance of this structure contains
472** a copy of the canonical filename. There is also a reference count.
473** The structure is reclaimed when the number of pointers to it drops to
474** zero.
475**
476** There are never very many files open at one time and lookups are not
477** a performance-critical path, so it is sufficient to put these
478** structures on a linked list.
479*/
480struct vxworksFileId {
481 struct vxworksFileId *pNext; /* Next in a list of them all */
482 int nRef; /* Number of references to this one */
483 int nName; /* Length of the zCanonicalName[] string */
484 char *zCanonicalName; /* Canonical filename */
485};
486
487#if OS_VXWORKS
488/*
drh9b35ea62008-11-29 02:20:26 +0000489** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000490** variable:
491*/
492static struct vxworksFileId *vxworksFileList = 0;
493
494/*
495** Simplify a filename into its canonical form
496** by making the following changes:
497**
498** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000499** * convert /./ into just /
500** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000501**
502** Changes are made in-place. Return the new name length.
503**
504** The original filename is in z[0..n-1]. Return the number of
505** characters in the simplified name.
506*/
507static int vxworksSimplifyName(char *z, int n){
508 int i, j;
509 while( n>1 && z[n-1]=='/' ){ n--; }
510 for(i=j=0; i<n; i++){
511 if( z[i]=='/' ){
512 if( z[i+1]=='/' ) continue;
513 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
514 i += 1;
515 continue;
516 }
517 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
518 while( j>0 && z[j-1]!='/' ){ j--; }
519 if( j>0 ){ j--; }
520 i += 2;
521 continue;
522 }
523 }
524 z[j++] = z[i];
525 }
526 z[j] = 0;
527 return j;
528}
529
530/*
531** Find a unique file ID for the given absolute pathname. Return
532** a pointer to the vxworksFileId object. This pointer is the unique
533** file ID.
534**
535** The nRef field of the vxworksFileId object is incremented before
536** the object is returned. A new vxworksFileId object is created
537** and added to the global list if necessary.
538**
539** If a memory allocation error occurs, return NULL.
540*/
541static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
542 struct vxworksFileId *pNew; /* search key and new file ID */
543 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
544 int n; /* Length of zAbsoluteName string */
545
546 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000547 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000548 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
549 if( pNew==0 ) return 0;
550 pNew->zCanonicalName = (char*)&pNew[1];
551 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
552 n = vxworksSimplifyName(pNew->zCanonicalName, n);
553
554 /* Search for an existing entry that matching the canonical name.
555 ** If found, increment the reference count and return a pointer to
556 ** the existing file ID.
557 */
558 unixEnterMutex();
559 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
560 if( pCandidate->nName==n
561 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
562 ){
563 sqlite3_free(pNew);
564 pCandidate->nRef++;
565 unixLeaveMutex();
566 return pCandidate;
567 }
568 }
569
570 /* No match was found. We will make a new file ID */
571 pNew->nRef = 1;
572 pNew->nName = n;
573 pNew->pNext = vxworksFileList;
574 vxworksFileList = pNew;
575 unixLeaveMutex();
576 return pNew;
577}
578
579/*
580** Decrement the reference count on a vxworksFileId object. Free
581** the object when the reference count reaches zero.
582*/
583static void vxworksReleaseFileId(struct vxworksFileId *pId){
584 unixEnterMutex();
585 assert( pId->nRef>0 );
586 pId->nRef--;
587 if( pId->nRef==0 ){
588 struct vxworksFileId **pp;
589 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
590 assert( *pp==pId );
591 *pp = pId->pNext;
592 sqlite3_free(pId);
593 }
594 unixLeaveMutex();
595}
596#endif /* OS_VXWORKS */
597/*************** End of Unique File ID Utility Used By VxWorks ****************
598******************************************************************************/
599
600
601/******************************************************************************
602*************************** Posix Advisory Locking ****************************
603**
drh9b35ea62008-11-29 02:20:26 +0000604** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000605** section 6.5.2.2 lines 483 through 490 specify that when a process
606** sets or clears a lock, that operation overrides any prior locks set
607** by the same process. It does not explicitly say so, but this implies
608** that it overrides locks set by the same process using a different
609** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000610**
611** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000612** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
613**
614** Suppose ./file1 and ./file2 are really the same file (because
615** one is a hard or symbolic link to the other) then if you set
616** an exclusive lock on fd1, then try to get an exclusive lock
617** on fd2, it works. I would have expected the second lock to
618** fail since there was already a lock on the file due to fd1.
619** But not so. Since both locks came from the same process, the
620** second overrides the first, even though they were on different
621** file descriptors opened on different file names.
622**
drh734c9862008-11-28 15:37:20 +0000623** This means that we cannot use POSIX locks to synchronize file access
624** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000625** to synchronize access for threads in separate processes, but not
626** threads within the same process.
627**
628** To work around the problem, SQLite has to manage file locks internally
629** on its own. Whenever a new database is opened, we have to find the
630** specific inode of the database file (the inode is determined by the
631** st_dev and st_ino fields of the stat structure that fstat() fills in)
632** and check for locks already existing on that inode. When locks are
633** created or removed, we have to look at our own internal record of the
634** locks to see if another thread has previously set a lock on that same
635** inode.
636**
drh9b35ea62008-11-29 02:20:26 +0000637** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
638** For VxWorks, we have to use the alternative unique ID system based on
639** canonical filename and implemented in the previous division.)
640**
danielk1977ad94b582007-08-20 06:44:22 +0000641** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000642** descriptor. It is now a structure that holds the integer file
643** descriptor and a pointer to a structure that describes the internal
644** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000645** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000646** point to the same locking structure. The locking structure keeps
647** a reference count (so we will know when to delete it) and a "cnt"
648** field that tells us its internal lock status. cnt==0 means the
649** file is unlocked. cnt==-1 means the file has an exclusive lock.
650** cnt>0 means there are cnt shared locks on the file.
651**
652** Any attempt to lock or unlock a file first checks the locking
653** structure. The fcntl() system call is only invoked to set a
654** POSIX lock if the internal lock structure transitions between
655** a locked and an unlocked state.
656**
drh734c9862008-11-28 15:37:20 +0000657** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000658**
659** If you close a file descriptor that points to a file that has locks,
660** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000661** released. To work around this problem, each unixInodeInfo object
662** maintains a count of the number of pending locks on tha inode.
663** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000664** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000665** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000666** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000667** be closed and that list is walked (and cleared) when the last lock
668** clears.
669**
drh9b35ea62008-11-29 02:20:26 +0000670** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000671**
drh9b35ea62008-11-29 02:20:26 +0000672** Many older versions of linux use the LinuxThreads library which is
673** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000674** A cannot be modified or overridden by a different thread B.
675** Only thread A can modify the lock. Locking behavior is correct
676** if the appliation uses the newer Native Posix Thread Library (NPTL)
677** on linux - with NPTL a lock created by thread A can override locks
678** in thread B. But there is no way to know at compile-time which
679** threading library is being used. So there is no way to know at
680** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000681** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000682** current process.
drh5fdae772004-06-29 03:29:00 +0000683**
drh8af6c222010-05-14 12:43:01 +0000684** SQLite used to support LinuxThreads. But support for LinuxThreads
685** was dropped beginning with version 3.7.0. SQLite will still work with
686** LinuxThreads provided that (1) there is no more than one connection
687** per database file in the same process and (2) database connections
688** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000689*/
690
691/*
692** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000693** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000694*/
695struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000696 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000697#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000698 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000699#else
drh107886a2008-11-21 22:21:50 +0000700 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000701#endif
702};
703
704/*
drhbbd42a62004-05-22 17:41:58 +0000705** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000706** inode. Or, on LinuxThreads, there is one of these structures for
707** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000708**
danielk1977ad94b582007-08-20 06:44:22 +0000709** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000710** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000711** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000712*/
drh8af6c222010-05-14 12:43:01 +0000713struct unixInodeInfo {
714 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000715 int nShared; /* Number of SHARED locks held */
drh8af6c222010-05-14 12:43:01 +0000716 int eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drh734c9862008-11-28 15:37:20 +0000717 int nRef; /* Number of pointers to this structure */
drh7ed97b92010-01-20 13:07:21 +0000718#if defined(SQLITE_ENABLE_LOCKING_STYLE)
719 unsigned long long sharedByte; /* for AFP simulated shared lock */
720#endif
drh8af6c222010-05-14 12:43:01 +0000721 int nLock; /* Number of outstanding file locks */
722 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh6c7d5c52008-11-21 20:32:33 +0000723#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000724 sem_t *pSem; /* Named POSIX semaphore */
725 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000726#endif
drh8af6c222010-05-14 12:43:01 +0000727 struct unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
728 struct unixInodeInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000729};
730
drhda0e7682008-07-30 15:27:54 +0000731/*
drh8af6c222010-05-14 12:43:01 +0000732** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000733*/
drh8af6c222010-05-14 12:43:01 +0000734static struct unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000735
drh5fdae772004-06-29 03:29:00 +0000736/*
drh8af6c222010-05-14 12:43:01 +0000737** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +0000738**
739** The mutex entered using the unixEnterMutex() function must be held
740** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000741*/
drh8af6c222010-05-14 12:43:01 +0000742static void releaseInodeInfo(struct unixInodeInfo *pInode){
dan9359c7b2009-08-21 08:29:10 +0000743 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +0000744 if( pInode ){
745 pInode->nRef--;
746 if( pInode->nRef==0 ){
747 if( pInode->pPrev ){
748 assert( pInode->pPrev->pNext==pInode );
749 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000750 }else{
drh8af6c222010-05-14 12:43:01 +0000751 assert( inodeList==pInode );
752 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +0000753 }
drh8af6c222010-05-14 12:43:01 +0000754 if( pInode->pNext ){
755 assert( pInode->pNext->pPrev==pInode );
756 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +0000757 }
drh8af6c222010-05-14 12:43:01 +0000758 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +0000759 }
drhbbd42a62004-05-22 17:41:58 +0000760 }
761}
762
763/*
drh8af6c222010-05-14 12:43:01 +0000764** Given a file descriptor, locate the unixInodeInfo object that
765** describes that file descriptor. Create a new one if necessary. The
766** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +0000767**
dan9359c7b2009-08-21 08:29:10 +0000768** The mutex entered using the unixEnterMutex() function must be held
769** when this function is called.
770**
drh6c7d5c52008-11-21 20:32:33 +0000771** Return an appropriate error code.
772*/
drh8af6c222010-05-14 12:43:01 +0000773static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +0000774 unixFile *pFile, /* Unix file with file desc used in the key */
drh8af6c222010-05-14 12:43:01 +0000775 struct unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +0000776){
777 int rc; /* System call return code */
778 int fd; /* The file descriptor for pFile */
drh8af6c222010-05-14 12:43:01 +0000779 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
780 struct stat statbuf; /* Low-level file information */
781 struct unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000782
dan9359c7b2009-08-21 08:29:10 +0000783 assert( unixMutexHeld() );
784
drh6c7d5c52008-11-21 20:32:33 +0000785 /* Get low-level information about the file that we can used to
786 ** create a unique name for the file.
787 */
788 fd = pFile->h;
789 rc = fstat(fd, &statbuf);
790 if( rc!=0 ){
791 pFile->lastErrno = errno;
792#ifdef EOVERFLOW
793 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
794#endif
795 return SQLITE_IOERR;
796 }
797
drheb0d74f2009-02-03 15:27:02 +0000798#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000799 /* On OS X on an msdos filesystem, the inode number is reported
800 ** incorrectly for zero-size files. See ticket #3260. To work
801 ** around this problem (we consider it a bug in OS X, not SQLite)
802 ** we always increase the file size to 1 by writing a single byte
803 ** prior to accessing the inode number. The one byte written is
804 ** an ASCII 'S' character which also happens to be the first byte
805 ** in the header of every SQLite database. In this way, if there
806 ** is a race condition such that another thread has already populated
807 ** the first page of the database, no damage is done.
808 */
drh7ed97b92010-01-20 13:07:21 +0000809 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drheb0d74f2009-02-03 15:27:02 +0000810 rc = write(fd, "S", 1);
811 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +0000812 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +0000813 return SQLITE_IOERR;
814 }
drh6c7d5c52008-11-21 20:32:33 +0000815 rc = fstat(fd, &statbuf);
816 if( rc!=0 ){
817 pFile->lastErrno = errno;
818 return SQLITE_IOERR;
819 }
820 }
drheb0d74f2009-02-03 15:27:02 +0000821#endif
drh6c7d5c52008-11-21 20:32:33 +0000822
drh8af6c222010-05-14 12:43:01 +0000823 memset(&fileId, 0, sizeof(fileId));
824 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +0000825#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000826 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000827#else
drh8af6c222010-05-14 12:43:01 +0000828 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +0000829#endif
drh8af6c222010-05-14 12:43:01 +0000830 pInode = inodeList;
831 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
832 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +0000833 }
drh8af6c222010-05-14 12:43:01 +0000834 if( pInode==0 ){
835 pInode = sqlite3_malloc( sizeof(*pInode) );
836 if( pInode==0 ){
837 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +0000838 }
drh8af6c222010-05-14 12:43:01 +0000839 memset(pInode, 0, sizeof(*pInode));
840 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
841 pInode->nRef = 1;
842 pInode->pNext = inodeList;
843 pInode->pPrev = 0;
844 if( inodeList ) inodeList->pPrev = pInode;
845 inodeList = pInode;
846 }else{
847 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +0000848 }
drh8af6c222010-05-14 12:43:01 +0000849 *ppInode = pInode;
850 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +0000851}
drh6c7d5c52008-11-21 20:32:33 +0000852
aswift5b1a2562008-08-22 00:22:35 +0000853
854/*
danielk197713adf8a2004-06-03 16:08:41 +0000855** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +0000856** file by this or any other process. If such a lock is held, set *pResOut
857** to a non-zero value otherwise *pResOut is set to zero. The return value
858** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +0000859*/
danielk1977861f7452008-06-05 11:39:11 +0000860static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +0000861 int rc = SQLITE_OK;
862 int reserved = 0;
drh054889e2005-11-30 03:20:31 +0000863 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +0000864
danielk1977861f7452008-06-05 11:39:11 +0000865 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
866
drh054889e2005-11-30 03:20:31 +0000867 assert( pFile );
drh8af6c222010-05-14 12:43:01 +0000868 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000869
870 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +0000871 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +0000872 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000873 }
874
drh2ac3ee92004-06-07 16:27:46 +0000875 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000876 */
danielk197709480a92009-02-09 05:32:32 +0000877#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +0000878 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +0000879 struct flock lock;
880 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000881 lock.l_start = RESERVED_BYTE;
882 lock.l_len = 1;
883 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +0000884 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
885 int tErrno = errno;
886 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
887 pFile->lastErrno = tErrno;
888 } else if( lock.l_type!=F_UNLCK ){
889 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +0000890 }
891 }
danielk197709480a92009-02-09 05:32:32 +0000892#endif
danielk197713adf8a2004-06-03 16:08:41 +0000893
drh6c7d5c52008-11-21 20:32:33 +0000894 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +0000895 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +0000896
aswift5b1a2562008-08-22 00:22:35 +0000897 *pResOut = reserved;
898 return rc;
danielk197713adf8a2004-06-03 16:08:41 +0000899}
900
901/*
drh308c2a52010-05-14 11:30:18 +0000902** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +0000903** of the following:
904**
drh2ac3ee92004-06-07 16:27:46 +0000905** (1) SHARED_LOCK
906** (2) RESERVED_LOCK
907** (3) PENDING_LOCK
908** (4) EXCLUSIVE_LOCK
909**
drhb3e04342004-06-08 00:47:47 +0000910** Sometimes when requesting one lock state, additional lock states
911** are inserted in between. The locking might fail on one of the later
912** transitions leaving the lock state different from what it started but
913** still short of its goal. The following chart shows the allowed
914** transitions and the inserted intermediate states:
915**
916** UNLOCKED -> SHARED
917** SHARED -> RESERVED
918** SHARED -> (PENDING) -> EXCLUSIVE
919** RESERVED -> (PENDING) -> EXCLUSIVE
920** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +0000921**
drha6abd042004-06-09 17:37:22 +0000922** This routine will only increase a lock. Use the sqlite3OsUnlock()
923** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +0000924*/
drh308c2a52010-05-14 11:30:18 +0000925static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +0000926 /* The following describes the implementation of the various locks and
927 ** lock transitions in terms of the POSIX advisory shared and exclusive
928 ** lock primitives (called read-locks and write-locks below, to avoid
929 ** confusion with SQLite lock names). The algorithms are complicated
930 ** slightly in order to be compatible with windows systems simultaneously
931 ** accessing the same database file, in case that is ever required.
932 **
933 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
934 ** byte', each single bytes at well known offsets, and the 'shared byte
935 ** range', a range of 510 bytes at a well known offset.
936 **
937 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
938 ** byte'. If this is successful, a random byte from the 'shared byte
939 ** range' is read-locked and the lock on the 'pending byte' released.
940 **
danielk197790ba3bd2004-06-25 08:32:25 +0000941 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
942 ** A RESERVED lock is implemented by grabbing a write-lock on the
943 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +0000944 **
945 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +0000946 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
947 ** on the 'pending byte'. This ensures that no new SHARED locks can be
948 ** obtained, but existing SHARED locks are allowed to persist. A process
949 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
950 ** This property is used by the algorithm for rolling back a journal file
951 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +0000952 **
danielk197790ba3bd2004-06-25 08:32:25 +0000953 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
954 ** implemented by obtaining a write-lock on the entire 'shared byte
955 ** range'. Since all other locks require a read-lock on one of the bytes
956 ** within this range, this ensures that no other locks are held on the
957 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +0000958 **
959 ** The reason a single byte cannot be used instead of the 'shared byte
960 ** range' is that some versions of windows do not support read-locks. By
961 ** locking a random byte from a range, concurrent SHARED locks may exist
962 ** even if the locking primitive used is always a write-lock.
963 */
danielk19779a1d0ab2004-06-01 14:09:28 +0000964 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +0000965 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +0000966 struct unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +0000967 struct flock lock;
drh3f022182009-09-09 16:10:50 +0000968 int s = 0;
drh383d30f2010-02-26 13:07:37 +0000969 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000970
drh054889e2005-11-30 03:20:31 +0000971 assert( pFile );
drh308c2a52010-05-14 11:30:18 +0000972 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
973 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +0000974 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +0000975
976 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +0000977 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +0000978 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +0000979 */
drh308c2a52010-05-14 11:30:18 +0000980 if( pFile->eFileLock>=eFileLock ){
981 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
982 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +0000983 return SQLITE_OK;
984 }
985
drh0c2694b2009-09-03 16:23:44 +0000986 /* Make sure the locking sequence is correct.
987 ** (1) We never move from unlocked to anything higher than shared lock.
988 ** (2) SQLite never explicitly requests a pendig lock.
989 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +0000990 */
drh308c2a52010-05-14 11:30:18 +0000991 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
992 assert( eFileLock!=PENDING_LOCK );
993 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +0000994
drh8af6c222010-05-14 12:43:01 +0000995 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +0000996 */
drh6c7d5c52008-11-21 20:32:33 +0000997 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +0000998 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +0000999
danielk1977ad94b582007-08-20 06:44:22 +00001000 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001001 ** handle that precludes the requested lock, return BUSY.
1002 */
drh8af6c222010-05-14 12:43:01 +00001003 if( (pFile->eFileLock!=pInode->eFileLock &&
1004 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001005 ){
1006 rc = SQLITE_BUSY;
1007 goto end_lock;
1008 }
1009
1010 /* If a SHARED lock is requested, and some thread using this PID already
1011 ** has a SHARED or RESERVED lock, then increment reference counts and
1012 ** return SQLITE_OK.
1013 */
drh308c2a52010-05-14 11:30:18 +00001014 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001015 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001016 assert( eFileLock==SHARED_LOCK );
1017 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001018 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001019 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001020 pInode->nShared++;
1021 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001022 goto end_lock;
1023 }
1024
danielk19779a1d0ab2004-06-01 14:09:28 +00001025
drh3cde3bb2004-06-12 02:17:14 +00001026 /* A PENDING lock is needed before acquiring a SHARED lock and before
1027 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1028 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001029 */
drh0c2694b2009-09-03 16:23:44 +00001030 lock.l_len = 1L;
1031 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001032 if( eFileLock==SHARED_LOCK
1033 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001034 ){
drh308c2a52010-05-14 11:30:18 +00001035 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001036 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001037 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001038 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001039 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001040 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1041 if( IS_LOCK_ERROR(rc) ){
1042 pFile->lastErrno = tErrno;
1043 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001044 goto end_lock;
1045 }
drh3cde3bb2004-06-12 02:17:14 +00001046 }
1047
1048
1049 /* If control gets to this point, then actually go ahead and make
1050 ** operating system calls for the specified lock.
1051 */
drh308c2a52010-05-14 11:30:18 +00001052 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001053 assert( pInode->nShared==0 );
1054 assert( pInode->eFileLock==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001055
drh2ac3ee92004-06-07 16:27:46 +00001056 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001057 lock.l_start = SHARED_FIRST;
1058 lock.l_len = SHARED_SIZE;
1059 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1060 tErrno = errno;
1061 }
drh2ac3ee92004-06-07 16:27:46 +00001062 /* Drop the temporary PENDING lock */
1063 lock.l_start = PENDING_BYTE;
1064 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001065 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001066 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001067 if( s != -1 ){
1068 /* This could happen with a network mount */
1069 tErrno = errno;
1070 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1071 if( IS_LOCK_ERROR(rc) ){
1072 pFile->lastErrno = tErrno;
1073 }
1074 goto end_lock;
1075 }
drh2b4b5962005-06-15 17:47:55 +00001076 }
drhe2396a12007-03-29 20:19:58 +00001077 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001078 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1079 if( IS_LOCK_ERROR(rc) ){
1080 pFile->lastErrno = tErrno;
1081 }
drhbbd42a62004-05-22 17:41:58 +00001082 }else{
drh308c2a52010-05-14 11:30:18 +00001083 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001084 pInode->nLock++;
1085 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001086 }
drh8af6c222010-05-14 12:43:01 +00001087 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001088 /* We are trying for an exclusive lock but another thread in this
1089 ** same process is still holding a shared lock. */
1090 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001091 }else{
drh3cde3bb2004-06-12 02:17:14 +00001092 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001093 ** assumed that there is a SHARED or greater lock on the file
1094 ** already.
1095 */
drh308c2a52010-05-14 11:30:18 +00001096 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001097 lock.l_type = F_WRLCK;
drh308c2a52010-05-14 11:30:18 +00001098 switch( eFileLock ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001099 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001100 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001101 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001102 case EXCLUSIVE_LOCK:
drh7ed97b92010-01-20 13:07:21 +00001103 lock.l_start = SHARED_FIRST;
1104 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001105 break;
1106 default:
1107 assert(0);
1108 }
drh7ed97b92010-01-20 13:07:21 +00001109 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001110 if( s==(-1) ){
drh7ed97b92010-01-20 13:07:21 +00001111 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001112 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1113 if( IS_LOCK_ERROR(rc) ){
1114 pFile->lastErrno = tErrno;
1115 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001116 }
drhbbd42a62004-05-22 17:41:58 +00001117 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001118
drh8f941bc2009-01-14 23:03:40 +00001119
1120#ifndef NDEBUG
1121 /* Set up the transaction-counter change checking flags when
1122 ** transitioning from a SHARED to a RESERVED lock. The change
1123 ** from SHARED to RESERVED marks the beginning of a normal
1124 ** write operation (not a hot journal rollback).
1125 */
1126 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001127 && pFile->eFileLock<=SHARED_LOCK
1128 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001129 ){
1130 pFile->transCntrChng = 0;
1131 pFile->dbUpdate = 0;
1132 pFile->inNormalWrite = 1;
1133 }
1134#endif
1135
1136
danielk1977ecb2a962004-06-02 06:30:16 +00001137 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001138 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001139 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001140 }else if( eFileLock==EXCLUSIVE_LOCK ){
1141 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001142 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001143 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001144
1145end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001146 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001147 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1148 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001149 return rc;
1150}
1151
1152/*
drh8af6c222010-05-14 12:43:01 +00001153** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
dane946c392009-08-22 11:39:46 +00001154** If all such file descriptors are closed without error, the list is
1155** cleared and SQLITE_OK returned.
dan08da86a2009-08-21 17:18:03 +00001156**
1157** Otherwise, if an error occurs, then successfully closed file descriptor
dane946c392009-08-22 11:39:46 +00001158** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
dan08da86a2009-08-21 17:18:03 +00001159** not deleted and SQLITE_IOERR_CLOSE returned.
1160*/
1161static int closePendingFds(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001162 int rc = SQLITE_OK;
drh8af6c222010-05-14 12:43:01 +00001163 struct unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001164 UnixUnusedFd *pError = 0;
1165 UnixUnusedFd *p;
1166 UnixUnusedFd *pNext;
drh8af6c222010-05-14 12:43:01 +00001167 for(p=pInode->pUnused; p; p=pNext){
dane946c392009-08-22 11:39:46 +00001168 pNext = p->pNext;
1169 if( close(p->fd) ){
1170 pFile->lastErrno = errno;
1171 rc = SQLITE_IOERR_CLOSE;
1172 p->pNext = pError;
1173 pError = p;
dane946c392009-08-22 11:39:46 +00001174 }else{
1175 sqlite3_free(p);
dan08da86a2009-08-21 17:18:03 +00001176 }
1177 }
drh8af6c222010-05-14 12:43:01 +00001178 pInode->pUnused = pError;
dan08da86a2009-08-21 17:18:03 +00001179 return rc;
1180}
1181
1182/*
1183** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001184** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001185*/
1186static void setPendingFd(unixFile *pFile){
drh8af6c222010-05-14 12:43:01 +00001187 struct unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001188 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001189 p->pNext = pInode->pUnused;
1190 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001191 pFile->h = -1;
1192 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001193}
1194
1195/*
drh308c2a52010-05-14 11:30:18 +00001196** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001197** must be either NO_LOCK or SHARED_LOCK.
1198**
1199** If the locking level of the file descriptor is already at or below
1200** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001201**
1202** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1203** the byte range is divided into 2 parts and the first part is unlocked then
1204** set to a read lock, then the other part is simply unlocked. This works
1205** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1206** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001207*/
drh308c2a52010-05-14 11:30:18 +00001208static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001209 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00001210 struct unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001211 struct flock lock;
1212 int rc = SQLITE_OK;
1213 int h;
drh0c2694b2009-09-03 16:23:44 +00001214 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001215
drh054889e2005-11-30 03:20:31 +00001216 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001217 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001218 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001219 getpid()));
drha6abd042004-06-09 17:37:22 +00001220
drh308c2a52010-05-14 11:30:18 +00001221 assert( eFileLock<=SHARED_LOCK );
1222 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001223 return SQLITE_OK;
1224 }
drh6c7d5c52008-11-21 20:32:33 +00001225 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001226 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001227 pInode = pFile->pInode;
1228 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001229 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001230 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001231 SimulateIOErrorBenign(1);
1232 SimulateIOError( h=(-1) )
1233 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001234
1235#ifndef NDEBUG
1236 /* When reducing a lock such that other processes can start
1237 ** reading the database file again, make sure that the
1238 ** transaction counter was updated if any part of the database
1239 ** file changed. If the transaction counter is not updated,
1240 ** other connections to the same file might not realize that
1241 ** the file has changed and hence might not know to flush their
1242 ** cache. The use of a stale cache can lead to database corruption.
1243 */
dan7c246102010-04-12 19:00:29 +00001244#if 0
drh8f941bc2009-01-14 23:03:40 +00001245 assert( pFile->inNormalWrite==0
1246 || pFile->dbUpdate==0
1247 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001248#endif
drh8f941bc2009-01-14 23:03:40 +00001249 pFile->inNormalWrite = 0;
1250#endif
1251
drh7ed97b92010-01-20 13:07:21 +00001252 /* downgrading to a shared lock on NFS involves clearing the write lock
1253 ** before establishing the readlock - to avoid a race condition we downgrade
1254 ** the lock in 2 blocks, so that part of the range will be covered by a
1255 ** write lock until the rest is covered by a read lock:
1256 ** 1: [WWWWW]
1257 ** 2: [....W]
1258 ** 3: [RRRRW]
1259 ** 4: [RRRR.]
1260 */
drh308c2a52010-05-14 11:30:18 +00001261 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00001262 if( handleNFSUnlock ){
1263 off_t divSize = SHARED_SIZE - 1;
1264
1265 lock.l_type = F_UNLCK;
1266 lock.l_whence = SEEK_SET;
1267 lock.l_start = SHARED_FIRST;
1268 lock.l_len = divSize;
1269 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001270 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001271 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1272 if( IS_LOCK_ERROR(rc) ){
1273 pFile->lastErrno = tErrno;
1274 }
1275 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001276 }
drh7ed97b92010-01-20 13:07:21 +00001277 lock.l_type = F_RDLCK;
1278 lock.l_whence = SEEK_SET;
1279 lock.l_start = SHARED_FIRST;
1280 lock.l_len = divSize;
1281 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001282 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001283 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1284 if( IS_LOCK_ERROR(rc) ){
1285 pFile->lastErrno = tErrno;
1286 }
1287 goto end_unlock;
1288 }
1289 lock.l_type = F_UNLCK;
1290 lock.l_whence = SEEK_SET;
1291 lock.l_start = SHARED_FIRST+divSize;
1292 lock.l_len = SHARED_SIZE-divSize;
1293 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001294 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001295 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1296 if( IS_LOCK_ERROR(rc) ){
1297 pFile->lastErrno = tErrno;
1298 }
1299 goto end_unlock;
1300 }
1301 }else{
1302 lock.l_type = F_RDLCK;
1303 lock.l_whence = SEEK_SET;
1304 lock.l_start = SHARED_FIRST;
1305 lock.l_len = SHARED_SIZE;
1306 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001307 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001308 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1309 if( IS_LOCK_ERROR(rc) ){
1310 pFile->lastErrno = tErrno;
1311 }
1312 goto end_unlock;
1313 }
drh9c105bb2004-10-02 20:38:28 +00001314 }
1315 }
drhbbd42a62004-05-22 17:41:58 +00001316 lock.l_type = F_UNLCK;
1317 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001318 lock.l_start = PENDING_BYTE;
1319 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001320 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001321 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001322 }else{
drh0c2694b2009-09-03 16:23:44 +00001323 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001324 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1325 if( IS_LOCK_ERROR(rc) ){
1326 pFile->lastErrno = tErrno;
1327 }
drhcd731cf2009-03-28 23:23:02 +00001328 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001329 }
drhbbd42a62004-05-22 17:41:58 +00001330 }
drh308c2a52010-05-14 11:30:18 +00001331 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001332 /* Decrement the shared lock counter. Release the lock using an
1333 ** OS call only when all threads in this same process have released
1334 ** the lock.
1335 */
drh8af6c222010-05-14 12:43:01 +00001336 pInode->nShared--;
1337 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001338 lock.l_type = F_UNLCK;
1339 lock.l_whence = SEEK_SET;
1340 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001341 SimulateIOErrorBenign(1);
1342 SimulateIOError( h=(-1) )
1343 SimulateIOErrorBenign(0);
1344 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh8af6c222010-05-14 12:43:01 +00001345 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001346 }else{
drh0c2694b2009-09-03 16:23:44 +00001347 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001348 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001349 if( IS_LOCK_ERROR(rc) ){
1350 pFile->lastErrno = tErrno;
1351 }
drh8af6c222010-05-14 12:43:01 +00001352 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001353 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001354 }
drha6abd042004-06-09 17:37:22 +00001355 }
1356
drhbbd42a62004-05-22 17:41:58 +00001357 /* Decrement the count of locks against this same file. When the
1358 ** count reaches zero, close any other file descriptors whose close
1359 ** was deferred because of outstanding locks.
1360 */
drh8af6c222010-05-14 12:43:01 +00001361 pInode->nLock--;
1362 assert( pInode->nLock>=0 );
1363 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001364 int rc2 = closePendingFds(pFile);
1365 if( rc==SQLITE_OK ){
1366 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001367 }
drhbbd42a62004-05-22 17:41:58 +00001368 }
1369 }
aswift5b1a2562008-08-22 00:22:35 +00001370
1371end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001372 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001373 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001374 return rc;
drhbbd42a62004-05-22 17:41:58 +00001375}
1376
1377/*
drh308c2a52010-05-14 11:30:18 +00001378** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001379** must be either NO_LOCK or SHARED_LOCK.
1380**
1381** If the locking level of the file descriptor is already at or below
1382** the requested locking level, this routine is a no-op.
1383*/
drh308c2a52010-05-14 11:30:18 +00001384static int unixUnlock(sqlite3_file *id, int eFileLock){
1385 return _posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001386}
1387
1388/*
danielk1977e339d652008-06-28 11:23:00 +00001389** This function performs the parts of the "close file" operation
1390** common to all locking schemes. It closes the directory and file
1391** handles, if they are valid, and sets all fields of the unixFile
1392** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001393**
1394** It is *not* necessary to hold the mutex when this routine is called,
1395** even on VxWorks. A mutex will be acquired on VxWorks by the
1396** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001397*/
1398static int closeUnixFile(sqlite3_file *id){
1399 unixFile *pFile = (unixFile*)id;
1400 if( pFile ){
1401 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001402 int err = close(pFile->dirfd);
1403 if( err ){
1404 pFile->lastErrno = errno;
1405 return SQLITE_IOERR_DIR_CLOSE;
1406 }else{
1407 pFile->dirfd=-1;
1408 }
danielk1977e339d652008-06-28 11:23:00 +00001409 }
1410 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001411 int err = close(pFile->h);
1412 if( err ){
1413 pFile->lastErrno = errno;
1414 return SQLITE_IOERR_CLOSE;
1415 }
danielk1977e339d652008-06-28 11:23:00 +00001416 }
drh6c7d5c52008-11-21 20:32:33 +00001417#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001418 if( pFile->pId ){
1419 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001420 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001421 }
drh107886a2008-11-21 22:21:50 +00001422 vxworksReleaseFileId(pFile->pId);
1423 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001424 }
1425#endif
drh308c2a52010-05-14 11:30:18 +00001426 OSTRACE(("CLOSE %-3d\n", pFile->h);
danielk1977e339d652008-06-28 11:23:00 +00001427 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001428 sqlite3_free(pFile->pUnused);
drh308c2a52010-05-14 11:30:18 +00001429 memset(pFile, 0, sizeof(unixFile)));
danielk1977e339d652008-06-28 11:23:00 +00001430 }
1431 return SQLITE_OK;
1432}
1433
1434/*
danielk1977e3026632004-06-22 11:29:02 +00001435** Close a file.
1436*/
danielk197762079062007-08-15 17:08:46 +00001437static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001438 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001439 if( id ){
1440 unixFile *pFile = (unixFile *)id;
1441 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001442 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001443 if( pFile->pInode && pFile->pInode->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001444 /* If there are outstanding locks, do not actually close the file just
1445 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00001446 ** descriptor to pInode->pUnused list. It will be automatically closed
dane946c392009-08-22 11:39:46 +00001447 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001448 */
dan08da86a2009-08-21 17:18:03 +00001449 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001450 }
drh8af6c222010-05-14 12:43:01 +00001451 releaseInodeInfo(pFile->pInode);
aswiftaebf4132008-11-21 00:10:35 +00001452 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001453 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001454 }
aswiftaebf4132008-11-21 00:10:35 +00001455 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001456}
1457
drh734c9862008-11-28 15:37:20 +00001458/************** End of the posix advisory lock implementation *****************
1459******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001460
drh734c9862008-11-28 15:37:20 +00001461/******************************************************************************
1462****************************** No-op Locking **********************************
1463**
1464** Of the various locking implementations available, this is by far the
1465** simplest: locking is ignored. No attempt is made to lock the database
1466** file for reading or writing.
1467**
1468** This locking mode is appropriate for use on read-only databases
1469** (ex: databases that are burned into CD-ROM, for example.) It can
1470** also be used if the application employs some external mechanism to
1471** prevent simultaneous access of the same database by two or more
1472** database connections. But there is a serious risk of database
1473** corruption if this locking mode is used in situations where multiple
1474** database connections are accessing the same database file at the same
1475** time and one or more of those connections are writing.
1476*/
drhbfe66312006-10-03 17:40:40 +00001477
drh734c9862008-11-28 15:37:20 +00001478static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1479 UNUSED_PARAMETER(NotUsed);
1480 *pResOut = 0;
1481 return SQLITE_OK;
1482}
drh734c9862008-11-28 15:37:20 +00001483static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1484 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1485 return SQLITE_OK;
1486}
drh734c9862008-11-28 15:37:20 +00001487static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1488 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1489 return SQLITE_OK;
1490}
1491
1492/*
drh9b35ea62008-11-29 02:20:26 +00001493** Close the file.
drh734c9862008-11-28 15:37:20 +00001494*/
1495static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001496 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001497}
1498
1499/******************* End of the no-op lock implementation *********************
1500******************************************************************************/
1501
1502/******************************************************************************
1503************************* Begin dot-file Locking ******************************
1504**
drh0c2694b2009-09-03 16:23:44 +00001505** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001506** files in order to control access to the database. This works on just
1507** about every filesystem imaginable. But there are serious downsides:
1508**
1509** (1) There is zero concurrency. A single reader blocks all other
1510** connections from reading or writing the database.
1511**
1512** (2) An application crash or power loss can leave stale lock files
1513** sitting around that need to be cleared manually.
1514**
1515** Nevertheless, a dotlock is an appropriate locking mode for use if no
1516** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001517**
1518** Dotfile locking works by creating a file in the same directory as the
1519** database and with the same name but with a ".lock" extension added.
1520** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1521** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001522*/
1523
1524/*
1525** The file suffix added to the data base filename in order to create the
1526** lock file.
1527*/
1528#define DOTLOCK_SUFFIX ".lock"
1529
drh7708e972008-11-29 00:56:52 +00001530/*
1531** This routine checks if there is a RESERVED lock held on the specified
1532** file by this or any other process. If such a lock is held, set *pResOut
1533** to a non-zero value otherwise *pResOut is set to zero. The return value
1534** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1535**
1536** In dotfile locking, either a lock exists or it does not. So in this
1537** variation of CheckReservedLock(), *pResOut is set to true if any lock
1538** is held on the file and false if the file is unlocked.
1539*/
drh734c9862008-11-28 15:37:20 +00001540static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1541 int rc = SQLITE_OK;
1542 int reserved = 0;
1543 unixFile *pFile = (unixFile*)id;
1544
1545 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1546
1547 assert( pFile );
1548
1549 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001550 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001551 /* Either this connection or some other connection in the same process
1552 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001553 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001554 }else{
1555 /* The lock is held if and only if the lockfile exists */
1556 const char *zLockFile = (const char*)pFile->lockingContext;
1557 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001558 }
drh308c2a52010-05-14 11:30:18 +00001559 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001560 *pResOut = reserved;
1561 return rc;
1562}
1563
drh7708e972008-11-29 00:56:52 +00001564/*
drh308c2a52010-05-14 11:30:18 +00001565** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001566** of the following:
1567**
1568** (1) SHARED_LOCK
1569** (2) RESERVED_LOCK
1570** (3) PENDING_LOCK
1571** (4) EXCLUSIVE_LOCK
1572**
1573** Sometimes when requesting one lock state, additional lock states
1574** are inserted in between. The locking might fail on one of the later
1575** transitions leaving the lock state different from what it started but
1576** still short of its goal. The following chart shows the allowed
1577** transitions and the inserted intermediate states:
1578**
1579** UNLOCKED -> SHARED
1580** SHARED -> RESERVED
1581** SHARED -> (PENDING) -> EXCLUSIVE
1582** RESERVED -> (PENDING) -> EXCLUSIVE
1583** PENDING -> EXCLUSIVE
1584**
1585** This routine will only increase a lock. Use the sqlite3OsUnlock()
1586** routine to lower a locking level.
1587**
1588** With dotfile locking, we really only support state (4): EXCLUSIVE.
1589** But we track the other locking levels internally.
1590*/
drh308c2a52010-05-14 11:30:18 +00001591static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001592 unixFile *pFile = (unixFile*)id;
1593 int fd;
1594 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001595 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001596
drh7708e972008-11-29 00:56:52 +00001597
1598 /* If we have any lock, then the lock file already exists. All we have
1599 ** to do is adjust our internal record of the lock level.
1600 */
drh308c2a52010-05-14 11:30:18 +00001601 if( pFile->eFileLock > NO_LOCK ){
1602 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001603#if !OS_VXWORKS
1604 /* Always update the timestamp on the old file */
1605 utimes(zLockFile, NULL);
1606#endif
drh7708e972008-11-29 00:56:52 +00001607 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001608 }
1609
1610 /* grab an exclusive lock */
1611 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1612 if( fd<0 ){
1613 /* failed to open/create the file, someone else may have stolen the lock */
1614 int tErrno = errno;
1615 if( EEXIST == tErrno ){
1616 rc = SQLITE_BUSY;
1617 } else {
1618 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1619 if( IS_LOCK_ERROR(rc) ){
1620 pFile->lastErrno = tErrno;
1621 }
1622 }
drh7708e972008-11-29 00:56:52 +00001623 return rc;
drh734c9862008-11-28 15:37:20 +00001624 }
1625 if( close(fd) ){
1626 pFile->lastErrno = errno;
1627 rc = SQLITE_IOERR_CLOSE;
1628 }
1629
1630 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001631 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001632 return rc;
1633}
1634
drh7708e972008-11-29 00:56:52 +00001635/*
drh308c2a52010-05-14 11:30:18 +00001636** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001637** must be either NO_LOCK or SHARED_LOCK.
1638**
1639** If the locking level of the file descriptor is already at or below
1640** the requested locking level, this routine is a no-op.
1641**
1642** When the locking level reaches NO_LOCK, delete the lock file.
1643*/
drh308c2a52010-05-14 11:30:18 +00001644static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001645 unixFile *pFile = (unixFile*)id;
1646 char *zLockFile = (char *)pFile->lockingContext;
1647
1648 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001649 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1650 pFile->eFileLock, getpid()));
1651 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001652
1653 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001654 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001655 return SQLITE_OK;
1656 }
drh7708e972008-11-29 00:56:52 +00001657
1658 /* To downgrade to shared, simply update our internal notion of the
1659 ** lock state. No need to mess with the file on disk.
1660 */
drh308c2a52010-05-14 11:30:18 +00001661 if( eFileLock==SHARED_LOCK ){
1662 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001663 return SQLITE_OK;
1664 }
1665
drh7708e972008-11-29 00:56:52 +00001666 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00001667 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00001668 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001669 int rc = 0;
1670 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001671 if( ENOENT != tErrno ){
1672 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1673 }
1674 if( IS_LOCK_ERROR(rc) ){
1675 pFile->lastErrno = tErrno;
1676 }
1677 return rc;
1678 }
drh308c2a52010-05-14 11:30:18 +00001679 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001680 return SQLITE_OK;
1681}
1682
1683/*
drh9b35ea62008-11-29 02:20:26 +00001684** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001685*/
1686static int dotlockClose(sqlite3_file *id) {
1687 int rc;
1688 if( id ){
1689 unixFile *pFile = (unixFile*)id;
1690 dotlockUnlock(id, NO_LOCK);
1691 sqlite3_free(pFile->lockingContext);
1692 }
drh734c9862008-11-28 15:37:20 +00001693 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001694 return rc;
1695}
1696/****************** End of the dot-file lock implementation *******************
1697******************************************************************************/
1698
1699/******************************************************************************
1700************************** Begin flock Locking ********************************
1701**
1702** Use the flock() system call to do file locking.
1703**
drh6b9d6dd2008-12-03 19:34:47 +00001704** flock() locking is like dot-file locking in that the various
1705** fine-grain locking levels supported by SQLite are collapsed into
1706** a single exclusive lock. In other words, SHARED, RESERVED, and
1707** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1708** still works when you do this, but concurrency is reduced since
1709** only a single process can be reading the database at a time.
1710**
drh734c9862008-11-28 15:37:20 +00001711** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1712** compiling for VXWORKS.
1713*/
1714#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001715
drh6b9d6dd2008-12-03 19:34:47 +00001716/*
1717** This routine checks if there is a RESERVED lock held on the specified
1718** file by this or any other process. If such a lock is held, set *pResOut
1719** to a non-zero value otherwise *pResOut is set to zero. The return value
1720** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1721*/
drh734c9862008-11-28 15:37:20 +00001722static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1723 int rc = SQLITE_OK;
1724 int reserved = 0;
1725 unixFile *pFile = (unixFile*)id;
1726
1727 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1728
1729 assert( pFile );
1730
1731 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001732 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001733 reserved = 1;
1734 }
1735
1736 /* Otherwise see if some other process holds it. */
1737 if( !reserved ){
1738 /* attempt to get the lock */
1739 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1740 if( !lrc ){
1741 /* got the lock, unlock it */
1742 lrc = flock(pFile->h, LOCK_UN);
1743 if ( lrc ) {
1744 int tErrno = errno;
1745 /* unlock failed with an error */
1746 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1747 if( IS_LOCK_ERROR(lrc) ){
1748 pFile->lastErrno = tErrno;
1749 rc = lrc;
1750 }
1751 }
1752 } else {
1753 int tErrno = errno;
1754 reserved = 1;
1755 /* someone else might have it reserved */
1756 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1757 if( IS_LOCK_ERROR(lrc) ){
1758 pFile->lastErrno = tErrno;
1759 rc = lrc;
1760 }
1761 }
1762 }
drh308c2a52010-05-14 11:30:18 +00001763 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001764
1765#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1766 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1767 rc = SQLITE_OK;
1768 reserved=1;
1769 }
1770#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1771 *pResOut = reserved;
1772 return rc;
1773}
1774
drh6b9d6dd2008-12-03 19:34:47 +00001775/*
drh308c2a52010-05-14 11:30:18 +00001776** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001777** of the following:
1778**
1779** (1) SHARED_LOCK
1780** (2) RESERVED_LOCK
1781** (3) PENDING_LOCK
1782** (4) EXCLUSIVE_LOCK
1783**
1784** Sometimes when requesting one lock state, additional lock states
1785** are inserted in between. The locking might fail on one of the later
1786** transitions leaving the lock state different from what it started but
1787** still short of its goal. The following chart shows the allowed
1788** transitions and the inserted intermediate states:
1789**
1790** UNLOCKED -> SHARED
1791** SHARED -> RESERVED
1792** SHARED -> (PENDING) -> EXCLUSIVE
1793** RESERVED -> (PENDING) -> EXCLUSIVE
1794** PENDING -> EXCLUSIVE
1795**
1796** flock() only really support EXCLUSIVE locks. We track intermediate
1797** lock states in the sqlite3_file structure, but all locks SHARED or
1798** above are really EXCLUSIVE locks and exclude all other processes from
1799** access the file.
1800**
1801** This routine will only increase a lock. Use the sqlite3OsUnlock()
1802** routine to lower a locking level.
1803*/
drh308c2a52010-05-14 11:30:18 +00001804static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001805 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001806 unixFile *pFile = (unixFile*)id;
1807
1808 assert( pFile );
1809
1810 /* if we already have a lock, it is exclusive.
1811 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00001812 if (pFile->eFileLock > NO_LOCK) {
1813 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001814 return SQLITE_OK;
1815 }
1816
1817 /* grab an exclusive lock */
1818
1819 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1820 int tErrno = errno;
1821 /* didn't get, must be busy */
1822 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1823 if( IS_LOCK_ERROR(rc) ){
1824 pFile->lastErrno = tErrno;
1825 }
1826 } else {
1827 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001828 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001829 }
drh308c2a52010-05-14 11:30:18 +00001830 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
1831 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00001832#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1833 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1834 rc = SQLITE_BUSY;
1835 }
1836#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1837 return rc;
1838}
1839
drh6b9d6dd2008-12-03 19:34:47 +00001840
1841/*
drh308c2a52010-05-14 11:30:18 +00001842** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00001843** must be either NO_LOCK or SHARED_LOCK.
1844**
1845** If the locking level of the file descriptor is already at or below
1846** the requested locking level, this routine is a no-op.
1847*/
drh308c2a52010-05-14 11:30:18 +00001848static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001849 unixFile *pFile = (unixFile*)id;
1850
1851 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001852 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
1853 pFile->eFileLock, getpid()));
1854 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001855
1856 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001857 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001858 return SQLITE_OK;
1859 }
1860
1861 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00001862 if (eFileLock==SHARED_LOCK) {
1863 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001864 return SQLITE_OK;
1865 }
1866
1867 /* no, really, unlock. */
1868 int rc = flock(pFile->h, LOCK_UN);
1869 if (rc) {
1870 int r, tErrno = errno;
1871 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1872 if( IS_LOCK_ERROR(r) ){
1873 pFile->lastErrno = tErrno;
1874 }
1875#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1876 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
1877 r = SQLITE_BUSY;
1878 }
1879#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1880
1881 return r;
1882 } else {
drh308c2a52010-05-14 11:30:18 +00001883 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00001884 return SQLITE_OK;
1885 }
1886}
1887
1888/*
1889** Close a file.
1890*/
1891static int flockClose(sqlite3_file *id) {
1892 if( id ){
1893 flockUnlock(id, NO_LOCK);
1894 }
1895 return closeUnixFile(id);
1896}
1897
1898#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
1899
1900/******************* End of the flock lock implementation *********************
1901******************************************************************************/
1902
1903/******************************************************************************
1904************************ Begin Named Semaphore Locking ************************
1905**
1906** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00001907**
1908** Semaphore locking is like dot-lock and flock in that it really only
1909** supports EXCLUSIVE locking. Only a single process can read or write
1910** the database file at a time. This reduces potential concurrency, but
1911** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00001912*/
1913#if OS_VXWORKS
1914
drh6b9d6dd2008-12-03 19:34:47 +00001915/*
1916** This routine checks if there is a RESERVED lock held on the specified
1917** file by this or any other process. If such a lock is held, set *pResOut
1918** to a non-zero value otherwise *pResOut is set to zero. The return value
1919** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1920*/
drh734c9862008-11-28 15:37:20 +00001921static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
1922 int rc = SQLITE_OK;
1923 int reserved = 0;
1924 unixFile *pFile = (unixFile*)id;
1925
1926 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1927
1928 assert( pFile );
1929
1930 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001931 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00001932 reserved = 1;
1933 }
1934
1935 /* Otherwise see if some other process holds it. */
1936 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00001937 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00001938 struct stat statBuf;
1939
1940 if( sem_trywait(pSem)==-1 ){
1941 int tErrno = errno;
1942 if( EAGAIN != tErrno ){
1943 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1944 pFile->lastErrno = tErrno;
1945 } else {
1946 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00001947 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00001948 }
1949 }else{
1950 /* we could have it if we want it */
1951 sem_post(pSem);
1952 }
1953 }
drh308c2a52010-05-14 11:30:18 +00001954 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001955
1956 *pResOut = reserved;
1957 return rc;
1958}
1959
drh6b9d6dd2008-12-03 19:34:47 +00001960/*
drh308c2a52010-05-14 11:30:18 +00001961** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00001962** of the following:
1963**
1964** (1) SHARED_LOCK
1965** (2) RESERVED_LOCK
1966** (3) PENDING_LOCK
1967** (4) EXCLUSIVE_LOCK
1968**
1969** Sometimes when requesting one lock state, additional lock states
1970** are inserted in between. The locking might fail on one of the later
1971** transitions leaving the lock state different from what it started but
1972** still short of its goal. The following chart shows the allowed
1973** transitions and the inserted intermediate states:
1974**
1975** UNLOCKED -> SHARED
1976** SHARED -> RESERVED
1977** SHARED -> (PENDING) -> EXCLUSIVE
1978** RESERVED -> (PENDING) -> EXCLUSIVE
1979** PENDING -> EXCLUSIVE
1980**
1981** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
1982** lock states in the sqlite3_file structure, but all locks SHARED or
1983** above are really EXCLUSIVE locks and exclude all other processes from
1984** access the file.
1985**
1986** This routine will only increase a lock. Use the sqlite3OsUnlock()
1987** routine to lower a locking level.
1988*/
drh308c2a52010-05-14 11:30:18 +00001989static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001990 unixFile *pFile = (unixFile*)id;
1991 int fd;
drh8af6c222010-05-14 12:43:01 +00001992 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00001993 int rc = SQLITE_OK;
1994
1995 /* if we already have a lock, it is exclusive.
1996 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00001997 if (pFile->eFileLock > NO_LOCK) {
1998 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001999 rc = SQLITE_OK;
2000 goto sem_end_lock;
2001 }
2002
2003 /* lock semaphore now but bail out when already locked. */
2004 if( sem_trywait(pSem)==-1 ){
2005 rc = SQLITE_BUSY;
2006 goto sem_end_lock;
2007 }
2008
2009 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002010 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002011
2012 sem_end_lock:
2013 return rc;
2014}
2015
drh6b9d6dd2008-12-03 19:34:47 +00002016/*
drh308c2a52010-05-14 11:30:18 +00002017** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002018** must be either NO_LOCK or SHARED_LOCK.
2019**
2020** If the locking level of the file descriptor is already at or below
2021** the requested locking level, this routine is a no-op.
2022*/
drh308c2a52010-05-14 11:30:18 +00002023static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002024 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002025 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002026
2027 assert( pFile );
2028 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002029 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2030 pFile->eFileLock, getpid()));
2031 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002032
2033 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002034 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002035 return SQLITE_OK;
2036 }
2037
2038 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002039 if (eFileLock==SHARED_LOCK) {
2040 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002041 return SQLITE_OK;
2042 }
2043
2044 /* no, really unlock. */
2045 if ( sem_post(pSem)==-1 ) {
2046 int rc, tErrno = errno;
2047 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2048 if( IS_LOCK_ERROR(rc) ){
2049 pFile->lastErrno = tErrno;
2050 }
2051 return rc;
2052 }
drh308c2a52010-05-14 11:30:18 +00002053 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002054 return SQLITE_OK;
2055}
2056
2057/*
2058 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002059 */
drh734c9862008-11-28 15:37:20 +00002060static int semClose(sqlite3_file *id) {
2061 if( id ){
2062 unixFile *pFile = (unixFile*)id;
2063 semUnlock(id, NO_LOCK);
2064 assert( pFile );
2065 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002066 releaseLockInfo(pFile->pInode);
drh734c9862008-11-28 15:37:20 +00002067 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002068 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002069 }
2070 return SQLITE_OK;
2071}
2072
2073#endif /* OS_VXWORKS */
2074/*
2075** Named semaphore locking is only available on VxWorks.
2076**
2077*************** End of the named semaphore lock implementation ****************
2078******************************************************************************/
2079
2080
2081/******************************************************************************
2082*************************** Begin AFP Locking *********************************
2083**
2084** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2085** on Apple Macintosh computers - both OS9 and OSX.
2086**
2087** Third-party implementations of AFP are available. But this code here
2088** only works on OSX.
2089*/
2090
drhd2cb50b2009-01-09 21:41:17 +00002091#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002092/*
2093** The afpLockingContext structure contains all afp lock specific state
2094*/
drhbfe66312006-10-03 17:40:40 +00002095typedef struct afpLockingContext afpLockingContext;
2096struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002097 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002098 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002099};
2100
2101struct ByteRangeLockPB2
2102{
2103 unsigned long long offset; /* offset to first byte to lock */
2104 unsigned long long length; /* nbr of bytes to lock */
2105 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2106 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2107 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2108 int fd; /* file desc to assoc this lock with */
2109};
2110
drhfd131da2007-08-07 17:13:03 +00002111#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002112
drh6b9d6dd2008-12-03 19:34:47 +00002113/*
2114** This is a utility for setting or clearing a bit-range lock on an
2115** AFP filesystem.
2116**
2117** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2118*/
2119static int afpSetLock(
2120 const char *path, /* Name of the file to be locked or unlocked */
2121 unixFile *pFile, /* Open file descriptor on path */
2122 unsigned long long offset, /* First byte to be locked */
2123 unsigned long long length, /* Number of bytes to lock */
2124 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002125){
drh6b9d6dd2008-12-03 19:34:47 +00002126 struct ByteRangeLockPB2 pb;
2127 int err;
drhbfe66312006-10-03 17:40:40 +00002128
2129 pb.unLockFlag = setLockFlag ? 0 : 1;
2130 pb.startEndFlag = 0;
2131 pb.offset = offset;
2132 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002133 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002134
drh308c2a52010-05-14 11:30:18 +00002135 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002136 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002137 offset, length));
drhbfe66312006-10-03 17:40:40 +00002138 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2139 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002140 int rc;
2141 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002142 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2143 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002144#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2145 rc = SQLITE_BUSY;
2146#else
drh734c9862008-11-28 15:37:20 +00002147 rc = sqliteErrorFromPosixError(tErrno,
2148 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002149#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002150 if( IS_LOCK_ERROR(rc) ){
2151 pFile->lastErrno = tErrno;
2152 }
2153 return rc;
drhbfe66312006-10-03 17:40:40 +00002154 } else {
aswift5b1a2562008-08-22 00:22:35 +00002155 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002156 }
2157}
2158
drh6b9d6dd2008-12-03 19:34:47 +00002159/*
2160** This routine checks if there is a RESERVED lock held on the specified
2161** file by this or any other process. If such a lock is held, set *pResOut
2162** to a non-zero value otherwise *pResOut is set to zero. The return value
2163** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2164*/
danielk1977e339d652008-06-28 11:23:00 +00002165static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002166 int rc = SQLITE_OK;
2167 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002168 unixFile *pFile = (unixFile*)id;
2169
aswift5b1a2562008-08-22 00:22:35 +00002170 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2171
2172 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002173 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002174 if( context->reserved ){
2175 *pResOut = 1;
2176 return SQLITE_OK;
2177 }
drh8af6c222010-05-14 12:43:01 +00002178 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002179
2180 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002181 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002182 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002183 }
2184
2185 /* Otherwise see if some other process holds it.
2186 */
aswift5b1a2562008-08-22 00:22:35 +00002187 if( !reserved ){
2188 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002189 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002190 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002191 /* if we succeeded in taking the reserved lock, unlock it to restore
2192 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002193 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002194 } else {
2195 /* if we failed to get the lock then someone else must have it */
2196 reserved = 1;
2197 }
2198 if( IS_LOCK_ERROR(lrc) ){
2199 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002200 }
2201 }
drhbfe66312006-10-03 17:40:40 +00002202
drh7ed97b92010-01-20 13:07:21 +00002203 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002204 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002205
2206 *pResOut = reserved;
2207 return rc;
drhbfe66312006-10-03 17:40:40 +00002208}
2209
drh6b9d6dd2008-12-03 19:34:47 +00002210/*
drh308c2a52010-05-14 11:30:18 +00002211** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002212** of the following:
2213**
2214** (1) SHARED_LOCK
2215** (2) RESERVED_LOCK
2216** (3) PENDING_LOCK
2217** (4) EXCLUSIVE_LOCK
2218**
2219** Sometimes when requesting one lock state, additional lock states
2220** are inserted in between. The locking might fail on one of the later
2221** transitions leaving the lock state different from what it started but
2222** still short of its goal. The following chart shows the allowed
2223** transitions and the inserted intermediate states:
2224**
2225** UNLOCKED -> SHARED
2226** SHARED -> RESERVED
2227** SHARED -> (PENDING) -> EXCLUSIVE
2228** RESERVED -> (PENDING) -> EXCLUSIVE
2229** PENDING -> EXCLUSIVE
2230**
2231** This routine will only increase a lock. Use the sqlite3OsUnlock()
2232** routine to lower a locking level.
2233*/
drh308c2a52010-05-14 11:30:18 +00002234static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002235 int rc = SQLITE_OK;
2236 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002237 struct unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002238 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002239
2240 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002241 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2242 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002243 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002244
drhbfe66312006-10-03 17:40:40 +00002245 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002246 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002247 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002248 */
drh308c2a52010-05-14 11:30:18 +00002249 if( pFile->eFileLock>=eFileLock ){
2250 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2251 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002252 return SQLITE_OK;
2253 }
2254
2255 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002256 ** (1) We never move from unlocked to anything higher than shared lock.
2257 ** (2) SQLite never explicitly requests a pendig lock.
2258 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002259 */
drh308c2a52010-05-14 11:30:18 +00002260 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2261 assert( eFileLock!=PENDING_LOCK );
2262 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002263
drh8af6c222010-05-14 12:43:01 +00002264 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002265 */
drh6c7d5c52008-11-21 20:32:33 +00002266 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002267 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002268
2269 /* If some thread using this PID has a lock via a different unixFile*
2270 ** handle that precludes the requested lock, return BUSY.
2271 */
drh8af6c222010-05-14 12:43:01 +00002272 if( (pFile->eFileLock!=pInode->eFileLock &&
2273 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002274 ){
2275 rc = SQLITE_BUSY;
2276 goto afp_end_lock;
2277 }
2278
2279 /* If a SHARED lock is requested, and some thread using this PID already
2280 ** has a SHARED or RESERVED lock, then increment reference counts and
2281 ** return SQLITE_OK.
2282 */
drh308c2a52010-05-14 11:30:18 +00002283 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002284 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002285 assert( eFileLock==SHARED_LOCK );
2286 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002287 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002288 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002289 pInode->nShared++;
2290 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002291 goto afp_end_lock;
2292 }
drhbfe66312006-10-03 17:40:40 +00002293
2294 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002295 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2296 ** be released.
2297 */
drh308c2a52010-05-14 11:30:18 +00002298 if( eFileLock==SHARED_LOCK
2299 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002300 ){
2301 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002302 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002303 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002304 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002305 goto afp_end_lock;
2306 }
2307 }
2308
2309 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002310 ** operating system calls for the specified lock.
2311 */
drh308c2a52010-05-14 11:30:18 +00002312 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002313 int lrc1, lrc2, lrc1Errno;
2314 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002315
drh8af6c222010-05-14 12:43:01 +00002316 assert( pInode->nShared==0 );
2317 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002318
2319 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002320 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002321 /* note that the quality of the randomness doesn't matter that much */
2322 lk = random();
drh8af6c222010-05-14 12:43:01 +00002323 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002324 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002325 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002326 if( IS_LOCK_ERROR(lrc1) ){
2327 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002328 }
aswift5b1a2562008-08-22 00:22:35 +00002329 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002330 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002331
aswift5b1a2562008-08-22 00:22:35 +00002332 if( IS_LOCK_ERROR(lrc1) ) {
2333 pFile->lastErrno = lrc1Errno;
2334 rc = lrc1;
2335 goto afp_end_lock;
2336 } else if( IS_LOCK_ERROR(lrc2) ){
2337 rc = lrc2;
2338 goto afp_end_lock;
2339 } else if( lrc1 != SQLITE_OK ) {
2340 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002341 } else {
drh308c2a52010-05-14 11:30:18 +00002342 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002343 pInode->nLock++;
2344 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002345 }
drh8af6c222010-05-14 12:43:01 +00002346 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002347 /* We are trying for an exclusive lock but another thread in this
2348 ** same process is still holding a shared lock. */
2349 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002350 }else{
2351 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2352 ** assumed that there is a SHARED or greater lock on the file
2353 ** already.
2354 */
2355 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002356 assert( 0!=pFile->eFileLock );
2357 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002358 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002359 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002360 if( !failed ){
2361 context->reserved = 1;
2362 }
drhbfe66312006-10-03 17:40:40 +00002363 }
drh308c2a52010-05-14 11:30:18 +00002364 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002365 /* Acquire an EXCLUSIVE lock */
2366
2367 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002368 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002369 */
drh6b9d6dd2008-12-03 19:34:47 +00002370 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002371 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002372 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002373 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002374 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002375 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002376 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002377 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002378 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2379 ** a critical I/O error
2380 */
2381 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2382 SQLITE_IOERR_LOCK;
2383 goto afp_end_lock;
2384 }
2385 }else{
aswift5b1a2562008-08-22 00:22:35 +00002386 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002387 }
2388 }
aswift5b1a2562008-08-22 00:22:35 +00002389 if( failed ){
2390 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002391 }
2392 }
2393
2394 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002395 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002396 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002397 }else if( eFileLock==EXCLUSIVE_LOCK ){
2398 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002399 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002400 }
2401
2402afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002403 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002404 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2405 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002406 return rc;
2407}
2408
2409/*
drh308c2a52010-05-14 11:30:18 +00002410** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002411** must be either NO_LOCK or SHARED_LOCK.
2412**
2413** If the locking level of the file descriptor is already at or below
2414** the requested locking level, this routine is a no-op.
2415*/
drh308c2a52010-05-14 11:30:18 +00002416static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002417 int rc = SQLITE_OK;
2418 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002419 struct unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002420 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2421 int skipShared = 0;
2422#ifdef SQLITE_TEST
2423 int h = pFile->h;
2424#endif
drhbfe66312006-10-03 17:40:40 +00002425
2426 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002427 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002428 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002429 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002430
drh308c2a52010-05-14 11:30:18 +00002431 assert( eFileLock<=SHARED_LOCK );
2432 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002433 return SQLITE_OK;
2434 }
drh6c7d5c52008-11-21 20:32:33 +00002435 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002436 pInode = pFile->pInode;
2437 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002438 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002439 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002440 SimulateIOErrorBenign(1);
2441 SimulateIOError( h=(-1) )
2442 SimulateIOErrorBenign(0);
2443
2444#ifndef NDEBUG
2445 /* When reducing a lock such that other processes can start
2446 ** reading the database file again, make sure that the
2447 ** transaction counter was updated if any part of the database
2448 ** file changed. If the transaction counter is not updated,
2449 ** other connections to the same file might not realize that
2450 ** the file has changed and hence might not know to flush their
2451 ** cache. The use of a stale cache can lead to database corruption.
2452 */
2453 assert( pFile->inNormalWrite==0
2454 || pFile->dbUpdate==0
2455 || pFile->transCntrChng==1 );
2456 pFile->inNormalWrite = 0;
2457#endif
aswiftaebf4132008-11-21 00:10:35 +00002458
drh308c2a52010-05-14 11:30:18 +00002459 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002460 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002461 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002462 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002463 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002464 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2465 } else {
2466 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002467 }
2468 }
drh308c2a52010-05-14 11:30:18 +00002469 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002470 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002471 }
drh308c2a52010-05-14 11:30:18 +00002472 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002473 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2474 if( !rc ){
2475 context->reserved = 0;
2476 }
aswiftaebf4132008-11-21 00:10:35 +00002477 }
drh8af6c222010-05-14 12:43:01 +00002478 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2479 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002480 }
aswiftaebf4132008-11-21 00:10:35 +00002481 }
drh308c2a52010-05-14 11:30:18 +00002482 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002483
drh7ed97b92010-01-20 13:07:21 +00002484 /* Decrement the shared lock counter. Release the lock using an
2485 ** OS call only when all threads in this same process have released
2486 ** the lock.
2487 */
drh8af6c222010-05-14 12:43:01 +00002488 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2489 pInode->nShared--;
2490 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002491 SimulateIOErrorBenign(1);
2492 SimulateIOError( h=(-1) )
2493 SimulateIOErrorBenign(0);
2494 if( !skipShared ){
2495 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2496 }
2497 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002498 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002499 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002500 }
2501 }
2502 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002503 pInode->nLock--;
2504 assert( pInode->nLock>=0 );
2505 if( pInode->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002506 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002507 }
2508 }
drhbfe66312006-10-03 17:40:40 +00002509 }
drh7ed97b92010-01-20 13:07:21 +00002510
drh6c7d5c52008-11-21 20:32:33 +00002511 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002512 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002513 return rc;
2514}
2515
2516/*
drh339eb0b2008-03-07 15:34:11 +00002517** Close a file & cleanup AFP specific locking context
2518*/
danielk1977e339d652008-06-28 11:23:00 +00002519static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002520 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002521 if( id ){
2522 unixFile *pFile = (unixFile*)id;
2523 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002524 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002525 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002526 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002527 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002528 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002529 ** the last lock is cleared.
2530 */
dan08da86a2009-08-21 17:18:03 +00002531 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002532 }
drh8af6c222010-05-14 12:43:01 +00002533 releaseLockInfo(pFile->pInode);
danielk1977e339d652008-06-28 11:23:00 +00002534 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002535 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002536 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002537 }
drh7ed97b92010-01-20 13:07:21 +00002538 return rc;
drhbfe66312006-10-03 17:40:40 +00002539}
2540
drhd2cb50b2009-01-09 21:41:17 +00002541#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002542/*
2543** The code above is the AFP lock implementation. The code is specific
2544** to MacOSX and does not work on other unix platforms. No alternative
2545** is available. If you don't compile for a mac, then the "unix-afp"
2546** VFS is not available.
2547**
2548********************* End of the AFP lock implementation **********************
2549******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002550
drh7ed97b92010-01-20 13:07:21 +00002551/******************************************************************************
2552*************************** Begin NFS Locking ********************************/
2553
2554#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2555/*
drh308c2a52010-05-14 11:30:18 +00002556 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002557 ** must be either NO_LOCK or SHARED_LOCK.
2558 **
2559 ** If the locking level of the file descriptor is already at or below
2560 ** the requested locking level, this routine is a no-op.
2561 */
drh308c2a52010-05-14 11:30:18 +00002562static int nfsUnlock(sqlite3_file *id, int eFileLock){
2563 return _posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002564}
2565
2566#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2567/*
2568** The code above is the NFS lock implementation. The code is specific
2569** to MacOSX and does not work on other unix platforms. No alternative
2570** is available.
2571**
2572********************* End of the NFS lock implementation **********************
2573******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002574
2575/******************************************************************************
2576**************** Non-locking sqlite3_file methods *****************************
2577**
2578** The next division contains implementations for all methods of the
2579** sqlite3_file object other than the locking methods. The locking
2580** methods were defined in divisions above (one locking method per
2581** division). Those methods that are common to all locking modes
2582** are gather together into this division.
2583*/
drhbfe66312006-10-03 17:40:40 +00002584
2585/*
drh734c9862008-11-28 15:37:20 +00002586** Seek to the offset passed as the second argument, then read cnt
2587** bytes into pBuf. Return the number of bytes actually read.
2588**
2589** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2590** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2591** one system to another. Since SQLite does not define USE_PREAD
2592** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2593** See tickets #2741 and #2681.
2594**
2595** To avoid stomping the errno value on a failed read the lastErrno value
2596** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002597*/
drh734c9862008-11-28 15:37:20 +00002598static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2599 int got;
drh7ed97b92010-01-20 13:07:21 +00002600#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002601 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002602#endif
drh734c9862008-11-28 15:37:20 +00002603 TIMER_START;
2604#if defined(USE_PREAD)
2605 got = pread(id->h, pBuf, cnt, offset);
2606 SimulateIOError( got = -1 );
2607#elif defined(USE_PREAD64)
2608 got = pread64(id->h, pBuf, cnt, offset);
2609 SimulateIOError( got = -1 );
2610#else
2611 newOffset = lseek(id->h, offset, SEEK_SET);
2612 SimulateIOError( newOffset-- );
2613 if( newOffset!=offset ){
2614 if( newOffset == -1 ){
2615 ((unixFile*)id)->lastErrno = errno;
2616 }else{
2617 ((unixFile*)id)->lastErrno = 0;
2618 }
2619 return -1;
2620 }
2621 got = read(id->h, pBuf, cnt);
2622#endif
2623 TIMER_END;
2624 if( got<0 ){
2625 ((unixFile*)id)->lastErrno = errno;
2626 }
drh308c2a52010-05-14 11:30:18 +00002627 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002628 return got;
drhbfe66312006-10-03 17:40:40 +00002629}
2630
2631/*
drh734c9862008-11-28 15:37:20 +00002632** Read data from a file into a buffer. Return SQLITE_OK if all
2633** bytes were read successfully and SQLITE_IOERR if anything goes
2634** wrong.
drh339eb0b2008-03-07 15:34:11 +00002635*/
drh734c9862008-11-28 15:37:20 +00002636static int unixRead(
2637 sqlite3_file *id,
2638 void *pBuf,
2639 int amt,
2640 sqlite3_int64 offset
2641){
dan08da86a2009-08-21 17:18:03 +00002642 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002643 int got;
2644 assert( id );
drh08c6d442009-02-09 17:34:07 +00002645
dan08da86a2009-08-21 17:18:03 +00002646 /* If this is a database file (not a journal, master-journal or temp
2647 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002648#if 0
dane946c392009-08-22 11:39:46 +00002649 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002650 || offset>=PENDING_BYTE+512
2651 || offset+amt<=PENDING_BYTE
2652 );
dan7c246102010-04-12 19:00:29 +00002653#endif
drh08c6d442009-02-09 17:34:07 +00002654
dan08da86a2009-08-21 17:18:03 +00002655 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002656 if( got==amt ){
2657 return SQLITE_OK;
2658 }else if( got<0 ){
2659 /* lastErrno set by seekAndRead */
2660 return SQLITE_IOERR_READ;
2661 }else{
dan08da86a2009-08-21 17:18:03 +00002662 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002663 /* Unread parts of the buffer must be zero-filled */
2664 memset(&((char*)pBuf)[got], 0, amt-got);
2665 return SQLITE_IOERR_SHORT_READ;
2666 }
2667}
2668
2669/*
2670** Seek to the offset in id->offset then read cnt bytes into pBuf.
2671** Return the number of bytes actually read. Update the offset.
2672**
2673** To avoid stomping the errno value on a failed write the lastErrno value
2674** is set before returning.
2675*/
2676static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2677 int got;
drh7ed97b92010-01-20 13:07:21 +00002678#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002679 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002680#endif
drh734c9862008-11-28 15:37:20 +00002681 TIMER_START;
2682#if defined(USE_PREAD)
2683 got = pwrite(id->h, pBuf, cnt, offset);
2684#elif defined(USE_PREAD64)
2685 got = pwrite64(id->h, pBuf, cnt, offset);
2686#else
2687 newOffset = lseek(id->h, offset, SEEK_SET);
2688 if( newOffset!=offset ){
2689 if( newOffset == -1 ){
2690 ((unixFile*)id)->lastErrno = errno;
2691 }else{
2692 ((unixFile*)id)->lastErrno = 0;
2693 }
2694 return -1;
2695 }
2696 got = write(id->h, pBuf, cnt);
2697#endif
2698 TIMER_END;
2699 if( got<0 ){
2700 ((unixFile*)id)->lastErrno = errno;
2701 }
2702
drh308c2a52010-05-14 11:30:18 +00002703 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002704 return got;
2705}
2706
2707
2708/*
2709** Write data from a buffer into a file. Return SQLITE_OK on success
2710** or some other error code on failure.
2711*/
2712static int unixWrite(
2713 sqlite3_file *id,
2714 const void *pBuf,
2715 int amt,
2716 sqlite3_int64 offset
2717){
dan08da86a2009-08-21 17:18:03 +00002718 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002719 int wrote = 0;
2720 assert( id );
2721 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002722
dan08da86a2009-08-21 17:18:03 +00002723 /* If this is a database file (not a journal, master-journal or temp
2724 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002725#if 0
dane946c392009-08-22 11:39:46 +00002726 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002727 || offset>=PENDING_BYTE+512
2728 || offset+amt<=PENDING_BYTE
2729 );
dan7c246102010-04-12 19:00:29 +00002730#endif
drh08c6d442009-02-09 17:34:07 +00002731
drh8f941bc2009-01-14 23:03:40 +00002732#ifndef NDEBUG
2733 /* If we are doing a normal write to a database file (as opposed to
2734 ** doing a hot-journal rollback or a write to some file other than a
2735 ** normal database file) then record the fact that the database
2736 ** has changed. If the transaction counter is modified, record that
2737 ** fact too.
2738 */
dan08da86a2009-08-21 17:18:03 +00002739 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002740 pFile->dbUpdate = 1; /* The database has been modified */
2741 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002742 int rc;
drh8f941bc2009-01-14 23:03:40 +00002743 char oldCntr[4];
2744 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002745 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002746 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002747 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002748 pFile->transCntrChng = 1; /* The transaction counter has changed */
2749 }
2750 }
2751 }
2752#endif
2753
dan08da86a2009-08-21 17:18:03 +00002754 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002755 amt -= wrote;
2756 offset += wrote;
2757 pBuf = &((char*)pBuf)[wrote];
2758 }
2759 SimulateIOError(( wrote=(-1), amt=1 ));
2760 SimulateDiskfullError(( wrote=0, amt=1 ));
2761 if( amt>0 ){
2762 if( wrote<0 ){
2763 /* lastErrno set by seekAndWrite */
2764 return SQLITE_IOERR_WRITE;
2765 }else{
dan08da86a2009-08-21 17:18:03 +00002766 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002767 return SQLITE_FULL;
2768 }
2769 }
2770 return SQLITE_OK;
2771}
2772
2773#ifdef SQLITE_TEST
2774/*
2775** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002776** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002777*/
2778int sqlite3_sync_count = 0;
2779int sqlite3_fullsync_count = 0;
2780#endif
2781
2782/*
drh89240432009-03-25 01:06:01 +00002783** We do not trust systems to provide a working fdatasync(). Some do.
2784** Others do no. To be safe, we will stick with the (slower) fsync().
2785** If you know that your system does support fdatasync() correctly,
2786** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002787*/
drh89240432009-03-25 01:06:01 +00002788#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002789# define fdatasync fsync
2790#endif
2791
2792/*
2793** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2794** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2795** only available on Mac OS X. But that could change.
2796*/
2797#ifdef F_FULLFSYNC
2798# define HAVE_FULLFSYNC 1
2799#else
2800# define HAVE_FULLFSYNC 0
2801#endif
2802
2803
2804/*
2805** The fsync() system call does not work as advertised on many
2806** unix systems. The following procedure is an attempt to make
2807** it work better.
2808**
2809** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2810** for testing when we want to run through the test suite quickly.
2811** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2812** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2813** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002814**
2815** SQLite sets the dataOnly flag if the size of the file is unchanged.
2816** The idea behind dataOnly is that it should only write the file content
2817** to disk, not the inode. We only set dataOnly if the file size is
2818** unchanged since the file size is part of the inode. However,
2819** Ted Ts'o tells us that fdatasync() will also write the inode if the
2820** file size has changed. The only real difference between fdatasync()
2821** and fsync(), Ted tells us, is that fdatasync() will not flush the
2822** inode if the mtime or owner or other inode attributes have changed.
2823** We only care about the file size, not the other file attributes, so
2824** as far as SQLite is concerned, an fdatasync() is always adequate.
2825** So, we always use fdatasync() if it is available, regardless of
2826** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002827*/
2828static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002829 int rc;
drh734c9862008-11-28 15:37:20 +00002830
2831 /* The following "ifdef/elif/else/" block has the same structure as
2832 ** the one below. It is replicated here solely to avoid cluttering
2833 ** up the real code with the UNUSED_PARAMETER() macros.
2834 */
2835#ifdef SQLITE_NO_SYNC
2836 UNUSED_PARAMETER(fd);
2837 UNUSED_PARAMETER(fullSync);
2838 UNUSED_PARAMETER(dataOnly);
2839#elif HAVE_FULLFSYNC
2840 UNUSED_PARAMETER(dataOnly);
2841#else
2842 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002843 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002844#endif
2845
2846 /* Record the number of times that we do a normal fsync() and
2847 ** FULLSYNC. This is used during testing to verify that this procedure
2848 ** gets called with the correct arguments.
2849 */
2850#ifdef SQLITE_TEST
2851 if( fullSync ) sqlite3_fullsync_count++;
2852 sqlite3_sync_count++;
2853#endif
2854
2855 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2856 ** no-op
2857 */
2858#ifdef SQLITE_NO_SYNC
2859 rc = SQLITE_OK;
2860#elif HAVE_FULLFSYNC
2861 if( fullSync ){
2862 rc = fcntl(fd, F_FULLFSYNC, 0);
2863 }else{
2864 rc = 1;
2865 }
2866 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002867 ** It shouldn't be possible for fullfsync to fail on the local
2868 ** file system (on OSX), so failure indicates that FULLFSYNC
2869 ** isn't supported for this file system. So, attempt an fsync
2870 ** and (for now) ignore the overhead of a superfluous fcntl call.
2871 ** It'd be better to detect fullfsync support once and avoid
2872 ** the fcntl call every time sync is called.
2873 */
drh734c9862008-11-28 15:37:20 +00002874 if( rc ) rc = fsync(fd);
2875
drh7ed97b92010-01-20 13:07:21 +00002876#elif defined(__APPLE__)
2877 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
2878 ** so currently we default to the macro that redefines fdatasync to fsync
2879 */
2880 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00002881#else
drh0b647ff2009-03-21 14:41:04 +00002882 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002883#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002884 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002885 rc = fsync(fd);
2886 }
drh0b647ff2009-03-21 14:41:04 +00002887#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00002888#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2889
2890 if( OS_VXWORKS && rc!= -1 ){
2891 rc = 0;
2892 }
chw97185482008-11-17 08:05:31 +00002893 return rc;
drhbfe66312006-10-03 17:40:40 +00002894}
2895
drh734c9862008-11-28 15:37:20 +00002896/*
2897** Make sure all writes to a particular file are committed to disk.
2898**
2899** If dataOnly==0 then both the file itself and its metadata (file
2900** size, access time, etc) are synced. If dataOnly!=0 then only the
2901** file data is synced.
2902**
2903** Under Unix, also make sure that the directory entry for the file
2904** has been created by fsync-ing the directory that contains the file.
2905** If we do not do this and we encounter a power failure, the directory
2906** entry for the journal might not exist after we reboot. The next
2907** SQLite to access the file will not know that the journal exists (because
2908** the directory entry for the journal was never created) and the transaction
2909** will not roll back - possibly leading to database corruption.
2910*/
2911static int unixSync(sqlite3_file *id, int flags){
2912 int rc;
2913 unixFile *pFile = (unixFile*)id;
2914
2915 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2916 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2917
2918 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2919 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2920 || (flags&0x0F)==SQLITE_SYNC_FULL
2921 );
2922
2923 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2924 ** line is to test that doing so does not cause any problems.
2925 */
2926 SimulateDiskfullError( return SQLITE_FULL );
2927
2928 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002929 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00002930 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
2931 SimulateIOError( rc=1 );
2932 if( rc ){
2933 pFile->lastErrno = errno;
2934 return SQLITE_IOERR_FSYNC;
2935 }
2936 if( pFile->dirfd>=0 ){
2937 int err;
drh308c2a52010-05-14 11:30:18 +00002938 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
2939 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00002940#ifndef SQLITE_DISABLE_DIRSYNC
2941 /* The directory sync is only attempted if full_fsync is
2942 ** turned off or unavailable. If a full_fsync occurred above,
2943 ** then the directory sync is superfluous.
2944 */
2945 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
2946 /*
2947 ** We have received multiple reports of fsync() returning
2948 ** errors when applied to directories on certain file systems.
2949 ** A failed directory sync is not a big deal. So it seems
2950 ** better to ignore the error. Ticket #1657
2951 */
2952 /* pFile->lastErrno = errno; */
2953 /* return SQLITE_IOERR; */
2954 }
2955#endif
2956 err = close(pFile->dirfd); /* Only need to sync once, so close the */
2957 if( err==0 ){ /* directory when we are done */
2958 pFile->dirfd = -1;
2959 }else{
2960 pFile->lastErrno = errno;
2961 rc = SQLITE_IOERR_DIR_CLOSE;
2962 }
2963 }
2964 return rc;
2965}
2966
2967/*
2968** Truncate an open file to a specified size
2969*/
2970static int unixTruncate(sqlite3_file *id, i64 nByte){
2971 int rc;
2972 assert( id );
2973 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
2974 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
2975 if( rc ){
2976 ((unixFile*)id)->lastErrno = errno;
2977 return SQLITE_IOERR_TRUNCATE;
2978 }else{
drh3313b142009-11-06 04:13:18 +00002979#ifndef NDEBUG
2980 /* If we are doing a normal write to a database file (as opposed to
2981 ** doing a hot-journal rollback or a write to some file other than a
2982 ** normal database file) and we truncate the file to zero length,
2983 ** that effectively updates the change counter. This might happen
2984 ** when restoring a database using the backup API from a zero-length
2985 ** source.
2986 */
2987 if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
2988 ((unixFile*)id)->transCntrChng = 1;
2989 }
2990#endif
2991
drh734c9862008-11-28 15:37:20 +00002992 return SQLITE_OK;
2993 }
2994}
2995
2996/*
2997** Determine the current size of a file in bytes
2998*/
2999static int unixFileSize(sqlite3_file *id, i64 *pSize){
3000 int rc;
3001 struct stat buf;
3002 assert( id );
3003 rc = fstat(((unixFile*)id)->h, &buf);
3004 SimulateIOError( rc=1 );
3005 if( rc!=0 ){
3006 ((unixFile*)id)->lastErrno = errno;
3007 return SQLITE_IOERR_FSTAT;
3008 }
3009 *pSize = buf.st_size;
3010
drh8af6c222010-05-14 12:43:01 +00003011 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003012 ** writes a single byte into that file in order to work around a bug
3013 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3014 ** layers, we need to report this file size as zero even though it is
3015 ** really 1. Ticket #3260.
3016 */
3017 if( *pSize==1 ) *pSize = 0;
3018
3019
3020 return SQLITE_OK;
3021}
3022
drhd2cb50b2009-01-09 21:41:17 +00003023#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003024/*
3025** Handler for proxy-locking file-control verbs. Defined below in the
3026** proxying locking division.
3027*/
3028static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003029#endif
drh715ff302008-12-03 22:32:44 +00003030
danielk1977ad94b582007-08-20 06:44:22 +00003031
danielk1977e3026632004-06-22 11:29:02 +00003032/*
drh9e33c2c2007-08-31 18:34:59 +00003033** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003034*/
drhcc6bb3e2007-08-31 16:11:35 +00003035static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003036 switch( op ){
3037 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003038 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003039 return SQLITE_OK;
3040 }
drh7708e972008-11-29 00:56:52 +00003041 case SQLITE_LAST_ERRNO: {
3042 *(int*)pArg = ((unixFile*)id)->lastErrno;
3043 return SQLITE_OK;
3044 }
drh8f941bc2009-01-14 23:03:40 +00003045#ifndef NDEBUG
3046 /* The pager calls this method to signal that it has done
3047 ** a rollback and that the database is therefore unchanged and
3048 ** it hence it is OK for the transaction change counter to be
3049 ** unchanged.
3050 */
3051 case SQLITE_FCNTL_DB_UNCHANGED: {
3052 ((unixFile*)id)->dbUpdate = 0;
3053 return SQLITE_OK;
3054 }
3055#endif
drhd2cb50b2009-01-09 21:41:17 +00003056#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003057 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003058 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003059 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003060 }
drhd2cb50b2009-01-09 21:41:17 +00003061#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003062 }
drhcc6bb3e2007-08-31 16:11:35 +00003063 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003064}
3065
3066/*
danielk1977a3d4c882007-03-23 10:08:38 +00003067** Return the sector size in bytes of the underlying block device for
3068** the specified file. This is almost always 512 bytes, but may be
3069** larger for some devices.
3070**
3071** SQLite code assumes this function cannot fail. It also assumes that
3072** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003073** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003074** same for both.
3075*/
danielk1977397d65f2008-11-19 11:35:39 +00003076static int unixSectorSize(sqlite3_file *NotUsed){
3077 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003078 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003079}
3080
danielk197790949c22007-08-17 16:50:38 +00003081/*
danielk1977397d65f2008-11-19 11:35:39 +00003082** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003083*/
danielk1977397d65f2008-11-19 11:35:39 +00003084static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3085 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003086 return 0;
3087}
3088
drhd9e5c4f2010-05-12 18:01:39 +00003089#ifndef SQLITE_OMIT_WAL
3090
3091
3092/*
3093** Object used to represent a single file opened and mmapped to provide
3094** shared memory. When multiple threads all reference the same
3095** log-summary, each thread has its own unixFile object, but they all
3096** point to a single instance of this object. In other words, each
3097** log-summary is opened only once per process.
3098**
3099** unixMutexHeld() must be true when creating or destroying
3100** this object or while reading or writing the following fields:
3101**
3102** nRef
3103** pNext
3104**
3105** The following fields are read-only after the object is created:
3106**
3107** fid
3108** zFilename
3109**
3110** Either unixShmFile.mutex must be held or unixShmFile.nRef==0 and
3111** unixMutexHeld() is true when reading or writing any other field
3112** in this structure.
3113**
3114** To avoid deadlocks, mutex and mutexBuf are always released in the
3115** reverse order that they are acquired. mutexBuf is always acquired
3116** first and released last. This invariant is check by asserting
3117** sqlite3_mutex_notheld() on mutex whenever mutexBuf is acquired or
3118** released.
3119*/
3120struct unixShmFile {
3121 struct unixFileId fid; /* Unique file identifier */
3122 sqlite3_mutex *mutex; /* Mutex to access this object */
3123 sqlite3_mutex *mutexBuf; /* Mutex to access zBuf[] */
3124 char *zFilename; /* Name of the mmapped file */
3125 int h; /* Open file descriptor */
3126 int szMap; /* Size of the mapping of file into memory */
3127 char *pMMapBuf; /* Where currently mmapped(). NULL if unmapped */
3128 int nRef; /* Number of unixShm objects pointing to this */
3129 unixShm *pFirst; /* All unixShm objects pointing to this */
3130 unixShmFile *pNext; /* Next in list of all unixShmFile objects */
3131#ifdef SQLITE_DEBUG
3132 u8 exclMask; /* Mask of exclusive locks held */
3133 u8 sharedMask; /* Mask of shared locks held */
3134 u8 nextShmId; /* Next available unixShm.id value */
3135#endif
3136};
3137
3138/*
3139** A global array of all unixShmFile objects.
3140**
3141** The unixMutexHeld() must be true while reading or writing this list.
3142*/
3143static unixShmFile *unixShmFileList = 0;
3144
3145/*
3146** Structure used internally by this VFS to record the state of an
3147** open shared memory connection.
3148**
3149** unixShm.pFile->mutex must be held while reading or writing the
3150** unixShm.pNext and unixShm.locks[] elements.
3151**
3152** The unixShm.pFile element is initialized when the object is created
3153** and is read-only thereafter.
3154*/
3155struct unixShm {
3156 unixShmFile *pFile; /* The underlying unixShmFile object */
3157 unixShm *pNext; /* Next unixShm with the same unixShmFile */
3158 u8 lockState; /* Current lock state */
3159 u8 hasMutex; /* True if holding the unixShmFile mutex */
3160 u8 hasMutexBuf; /* True if holding pFile->mutexBuf */
3161 u8 sharedMask; /* Mask of shared locks held */
3162 u8 exclMask; /* Mask of exclusive locks held */
3163#ifdef SQLITE_DEBUG
3164 u8 id; /* Id of this connection with its unixShmFile */
3165#endif
3166};
3167
3168/*
3169** Size increment by which shared memory grows
3170*/
3171#define SQLITE_UNIX_SHM_INCR 4096
3172
3173/*
3174** Constants used for locking
3175*/
3176#define UNIX_SHM_BASE 32 /* Byte offset of the first lock byte */
3177#define UNIX_SHM_DMS 0x01 /* Mask for Dead-Man-Switch lock */
3178#define UNIX_SHM_A 0x10 /* Mask for region locks... */
3179#define UNIX_SHM_B 0x20
3180#define UNIX_SHM_C 0x40
3181#define UNIX_SHM_D 0x80
3182
3183#ifdef SQLITE_DEBUG
3184/*
3185** Return a pointer to a nul-terminated string in static memory that
3186** describes a locking mask. The string is of the form "MSABCD" with
3187** each character representing a lock. "M" for MUTEX, "S" for DMS,
3188** and "A" through "D" for the region locks. If a lock is held, the
3189** letter is shown. If the lock is not held, the letter is converted
3190** to ".".
3191**
3192** This routine is for debugging purposes only and does not appear
3193** in a production build.
3194*/
3195static const char *unixShmLockString(u8 mask){
3196 static char zBuf[48];
3197 static int iBuf = 0;
3198 char *z;
3199
3200 z = &zBuf[iBuf];
3201 iBuf += 8;
3202 if( iBuf>=sizeof(zBuf) ) iBuf = 0;
3203
3204 z[0] = (mask & UNIX_SHM_DMS) ? 'S' : '.';
3205 z[1] = (mask & UNIX_SHM_A) ? 'A' : '.';
3206 z[2] = (mask & UNIX_SHM_B) ? 'B' : '.';
3207 z[3] = (mask & UNIX_SHM_C) ? 'C' : '.';
3208 z[4] = (mask & UNIX_SHM_D) ? 'D' : '.';
3209 z[5] = 0;
3210 return z;
3211}
3212#endif /* SQLITE_DEBUG */
3213
3214/*
3215** Apply posix advisory locks for all bytes identified in lockMask.
3216**
3217** lockMask might contain multiple bits but all bits are guaranteed
3218** to be contiguous.
3219**
3220** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3221** otherwise.
3222*/
3223static int unixShmSystemLock(
3224 unixShmFile *pFile, /* Apply locks to this open shared-memory segment */
3225 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
3226 u8 lockMask /* Which bytes to lock or unlock */
3227){
3228 struct flock f; /* The posix advisory locking structure */
3229 int lockOp; /* The opcode for fcntl() */
3230 int i; /* Offset into the locking byte range */
3231 int rc; /* Result code form fcntl() */
3232 u8 mask; /* Mask of bits in lockMask */
3233
3234 /* Access to the unixShmFile object is serialized by the caller */
3235 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
3236
3237 /* Initialize the locking parameters */
3238 memset(&f, 0, sizeof(f));
3239 f.l_type = lockType;
3240 f.l_whence = SEEK_SET;
3241 if( lockMask==UNIX_SHM_C && lockType!=F_UNLCK ){
3242 lockOp = F_SETLKW;
3243 OSTRACE(("SHM-LOCK requesting blocking lock\n"));
3244 }else{
3245 lockOp = F_SETLK;
3246 }
3247
3248 /* Find the first bit in lockMask that is set */
3249 for(i=0, mask=0x01; mask!=0 && (lockMask&mask)==0; mask <<= 1, i++){}
3250 assert( mask!=0 );
3251 f.l_start = i+UNIX_SHM_BASE;
3252 f.l_len = 1;
3253
3254 /* Extend the locking range for each additional bit that is set */
3255 mask <<= 1;
3256 while( mask!=0 && (lockMask & mask)!=0 ){
3257 f.l_len++;
3258 mask <<= 1;
3259 }
3260
3261 /* Verify that all bits set in lockMask are contiguous */
3262 assert( mask==0 || (lockMask & ~(mask | (mask-1)))==0 );
3263
3264 /* Acquire the system-level lock */
3265 rc = fcntl(pFile->h, lockOp, &f);
3266 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3267
3268 /* Update the global lock state and do debug tracing */
3269#ifdef SQLITE_DEBUG
3270 OSTRACE(("SHM-LOCK "));
3271 if( rc==SQLITE_OK ){
3272 if( lockType==F_UNLCK ){
3273 OSTRACE(("unlock ok"));
3274 pFile->exclMask &= ~lockMask;
3275 pFile->sharedMask &= ~lockMask;
3276 }else if( lockType==F_RDLCK ){
3277 OSTRACE(("read-lock ok"));
3278 pFile->exclMask &= ~lockMask;
3279 pFile->sharedMask |= lockMask;
3280 }else{
3281 assert( lockType==F_WRLCK );
3282 OSTRACE(("write-lock ok"));
3283 pFile->exclMask |= lockMask;
3284 pFile->sharedMask &= ~lockMask;
3285 }
3286 }else{
3287 if( lockType==F_UNLCK ){
3288 OSTRACE(("unlock failed"));
3289 }else if( lockType==F_RDLCK ){
3290 OSTRACE(("read-lock failed"));
3291 }else{
3292 assert( lockType==F_WRLCK );
3293 OSTRACE(("write-lock failed"));
3294 }
3295 }
3296 OSTRACE((" - change requested %s - afterwards %s:%s\n",
3297 unixShmLockString(lockMask),
3298 unixShmLockString(pFile->sharedMask),
3299 unixShmLockString(pFile->exclMask)));
3300#endif
3301
3302 return rc;
3303}
3304
3305/*
3306** For connection p, unlock all of the locks identified by the unlockMask
3307** parameter.
3308*/
3309static int unixShmUnlock(
3310 unixShmFile *pFile, /* The underlying shared-memory file */
3311 unixShm *p, /* The connection to be unlocked */
3312 u8 unlockMask /* Mask of locks to be unlocked */
3313){
3314 int rc; /* Result code */
3315 unixShm *pX; /* For looping over all sibling connections */
3316 u8 allMask; /* Union of locks held by connections other than "p" */
3317
3318 /* Access to the unixShmFile object is serialized by the caller */
3319 assert( sqlite3_mutex_held(pFile->mutex) );
3320
3321 /* Compute locks held by sibling connections */
3322 allMask = 0;
3323 for(pX=pFile->pFirst; pX; pX=pX->pNext){
3324 if( pX==p ) continue;
3325 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3326 allMask |= pX->sharedMask;
3327 }
3328
3329 /* Unlock the system-level locks */
3330 if( (unlockMask & allMask)!=unlockMask ){
3331 rc = unixShmSystemLock(pFile, F_UNLCK, unlockMask & ~allMask);
3332 }else{
3333 rc = SQLITE_OK;
3334 }
3335
3336 /* Undo the local locks */
3337 if( rc==SQLITE_OK ){
3338 p->exclMask &= ~unlockMask;
3339 p->sharedMask &= ~unlockMask;
3340 }
3341 return rc;
3342}
3343
3344/*
3345** Get reader locks for connection p on all locks in the readMask parameter.
3346*/
3347static int unixShmSharedLock(
3348 unixShmFile *pFile, /* The underlying shared-memory file */
3349 unixShm *p, /* The connection to get the shared locks */
3350 u8 readMask /* Mask of shared locks to be acquired */
3351){
3352 int rc; /* Result code */
3353 unixShm *pX; /* For looping over all sibling connections */
3354 u8 allShared; /* Union of locks held by connections other than "p" */
3355
3356 /* Access to the unixShmFile object is serialized by the caller */
3357 assert( sqlite3_mutex_held(pFile->mutex) );
3358
3359 /* Find out which shared locks are already held by sibling connections.
3360 ** If any sibling already holds an exclusive lock, go ahead and return
3361 ** SQLITE_BUSY.
3362 */
3363 allShared = 0;
3364 for(pX=pFile->pFirst; pX; pX=pX->pNext){
3365 if( pX==p ) continue;
3366 if( (pX->exclMask & readMask)!=0 ) return SQLITE_BUSY;
3367 allShared |= pX->sharedMask;
3368 }
3369
3370 /* Get shared locks at the system level, if necessary */
3371 if( (~allShared) & readMask ){
3372 rc = unixShmSystemLock(pFile, F_RDLCK, readMask);
3373 }else{
3374 rc = SQLITE_OK;
3375 }
3376
3377 /* Get the local shared locks */
3378 if( rc==SQLITE_OK ){
3379 p->sharedMask |= readMask;
3380 }
3381 return rc;
3382}
3383
3384/*
3385** For connection p, get an exclusive lock on all locks identified in
3386** the writeMask parameter.
3387*/
3388static int unixShmExclusiveLock(
3389 unixShmFile *pFile, /* The underlying shared-memory file */
3390 unixShm *p, /* The connection to get the exclusive locks */
3391 u8 writeMask /* Mask of exclusive locks to be acquired */
3392){
3393 int rc; /* Result code */
3394 unixShm *pX; /* For looping over all sibling connections */
3395
3396 /* Access to the unixShmFile object is serialized by the caller */
3397 assert( sqlite3_mutex_held(pFile->mutex) );
3398
3399 /* Make sure no sibling connections hold locks that will block this
3400 ** lock. If any do, return SQLITE_BUSY right away.
3401 */
3402 for(pX=pFile->pFirst; pX; pX=pX->pNext){
3403 if( pX==p ) continue;
3404 if( (pX->exclMask & writeMask)!=0 ) return SQLITE_BUSY;
3405 if( (pX->sharedMask & writeMask)!=0 ) return SQLITE_BUSY;
3406 }
3407
3408 /* Get the exclusive locks at the system level. Then if successful
3409 ** also mark the local connection as being locked.
3410 */
3411 rc = unixShmSystemLock(pFile, F_WRLCK, writeMask);
3412 if( rc==SQLITE_OK ){
3413 p->sharedMask &= ~writeMask;
3414 p->exclMask |= writeMask;
3415 }
3416 return rc;
3417}
3418
3419/*
3420** Purge the unixShmFileList list of all entries with unixShmFile.nRef==0.
3421**
3422** This is not a VFS shared-memory method; it is a utility function called
3423** by VFS shared-memory methods.
3424*/
3425static void unixShmPurge(void){
3426 unixShmFile **pp;
3427 unixShmFile *p;
3428 assert( unixMutexHeld() );
3429 pp = &unixShmFileList;
3430 while( (p = *pp)!=0 ){
3431 if( p->nRef==0 ){
3432 if( p->mutex ) sqlite3_mutex_free(p->mutex);
3433 if( p->mutexBuf ) sqlite3_mutex_free(p->mutexBuf);
3434 if( p->h>=0 ) close(p->h);
3435 *pp = p->pNext;
3436 sqlite3_free(p);
3437 }else{
3438 pp = &p->pNext;
3439 }
3440 }
3441}
3442
3443/*
3444** Open a shared-memory area. This particular implementation uses
3445** mmapped files.
3446**
3447** zName is a filename used to identify the shared-memory area. The
3448** implementation does not (and perhaps should not) use this name
3449** directly, but rather use it as a template for finding an appropriate
3450** name for the shared-memory storage. In this implementation, the
3451** string "-index" is appended to zName and used as the name of the
3452** mmapped file.
3453**
3454** When opening a new shared-memory file, if no other instances of that
3455** file are currently open, in this process or in other processes, then
3456** the file must be truncated to zero length or have its header cleared.
3457*/
3458static int unixShmOpen(
3459 sqlite3_file *fd /* The file descriptor of the associated database */
3460){
3461 struct unixShm *p = 0; /* The connection to be opened */
3462 struct unixShmFile *pFile = 0; /* The underlying mmapped file */
3463 int rc; /* Result code */
3464 struct unixFileId fid; /* Unix file identifier */
3465 struct unixShmFile *pNew; /* Newly allocated pFile */
3466 struct stat sStat; /* Result from stat() an fstat() */
3467 struct unixFile *pDbFd; /* Underlying database file */
3468 int nPath; /* Size of pDbFd->zPath in bytes */
3469
3470 /* Allocate space for the new sqlite3_shm object. Also speculatively
3471 ** allocate space for a new unixShmFile and filename.
3472 */
3473 p = sqlite3_malloc( sizeof(*p) );
3474 if( p==0 ) return SQLITE_NOMEM;
3475 memset(p, 0, sizeof(*p));
3476 pDbFd = (struct unixFile*)fd;
3477 assert( pDbFd->pShm==0 );
3478 nPath = strlen(pDbFd->zPath);
3479 pNew = sqlite3_malloc( sizeof(*pFile) + nPath + 15 );
3480 if( pNew==0 ){
3481 sqlite3_free(p);
3482 return SQLITE_NOMEM;
3483 }
3484 memset(pNew, 0, sizeof(*pNew));
3485 pNew->zFilename = (char*)&pNew[1];
3486 sqlite3_snprintf(nPath+15, pNew->zFilename, "%s-wal-index", pDbFd->zPath);
3487
3488 /* Look to see if there is an existing unixShmFile that can be used.
3489 ** If no matching unixShmFile currently exists, create a new one.
3490 */
3491 unixEnterMutex();
3492 rc = stat(pNew->zFilename, &sStat);
3493 if( rc==0 ){
3494 memset(&fid, 0, sizeof(fid));
3495 fid.dev = sStat.st_dev;
3496 fid.ino = sStat.st_ino;
3497 for(pFile = unixShmFileList; pFile; pFile=pFile->pNext){
3498 if( memcmp(&pFile->fid, &fid, sizeof(fid))==0 ) break;
3499 }
3500 }
3501 if( pFile ){
3502 sqlite3_free(pNew);
3503 }else{
3504 pFile = pNew;
3505 pNew = 0;
3506 pFile->h = -1;
3507 pFile->pNext = unixShmFileList;
3508 unixShmFileList = pFile;
3509
3510 pFile->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3511 if( pFile->mutex==0 ){
3512 rc = SQLITE_NOMEM;
3513 goto shm_open_err;
3514 }
3515 pFile->mutexBuf = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3516 if( pFile->mutexBuf==0 ){
3517 rc = SQLITE_NOMEM;
3518 goto shm_open_err;
3519 }
3520
3521 pFile->h = open(pFile->zFilename, O_RDWR|O_CREAT, 0664);
3522 if( pFile->h<0 ){
3523 rc = SQLITE_CANTOPEN_BKPT;
3524 goto shm_open_err;
3525 }
3526
3527 rc = fstat(pFile->h, &sStat);
3528 if( rc ){
3529 rc = SQLITE_CANTOPEN_BKPT;
3530 goto shm_open_err;
3531 }
3532 pFile->fid.dev = sStat.st_dev;
3533 pFile->fid.ino = sStat.st_ino;
3534
3535 /* Check to see if another process is holding the dead-man switch.
3536 ** If not, truncate the file to zero length.
3537 */
3538 if( unixShmSystemLock(pFile, F_WRLCK, UNIX_SHM_DMS)==SQLITE_OK ){
3539 if( ftruncate(pFile->h, 0) ){
3540 rc = SQLITE_IOERR;
3541 }
3542 }
3543 if( rc==SQLITE_OK ){
3544 rc = unixShmSystemLock(pFile, F_RDLCK, UNIX_SHM_DMS);
3545 }
3546 if( rc ) goto shm_open_err;
3547 }
3548
3549 /* Make the new connection a child of the unixShmFile */
3550 p->pFile = pFile;
3551 p->pNext = pFile->pFirst;
3552#ifdef SQLITE_DEBUG
3553 p->id = pFile->nextShmId++;
3554#endif
3555 pFile->pFirst = p;
3556 pFile->nRef++;
3557 pDbFd->pShm = p;
3558 unixLeaveMutex();
3559 return SQLITE_OK;
3560
3561 /* Jump here on any error */
3562shm_open_err:
3563 unixShmPurge(); /* This call frees pFile if required */
3564 sqlite3_free(p);
3565 sqlite3_free(pNew);
3566 unixLeaveMutex();
3567 return rc;
3568}
3569
3570/*
3571** Close a connection to shared-memory. Delete the underlying
3572** storage if deleteFlag is true.
3573*/
3574static int unixShmClose(
3575 sqlite3_file *fd, /* The underlying database file */
3576 int deleteFlag /* Delete shared-memory if true */
3577){
3578 unixShm *p; /* The connection to be closed */
3579 unixShmFile *pFile; /* The underlying shared-memory file */
3580 unixShm **pp; /* For looping over sibling connections */
3581 unixFile *pDbFd; /* The underlying database file */
3582
3583 pDbFd = (unixFile*)fd;
3584 p = pDbFd->pShm;
3585 if( p==0 ) return SQLITE_OK;
3586 pFile = p->pFile;
3587
3588 /* Verify that the connection being closed holds no locks */
3589 assert( p->exclMask==0 );
3590 assert( p->sharedMask==0 );
3591
3592 /* Remove connection p from the set of connections associated with pFile */
3593 sqlite3_mutex_enter(pFile->mutex);
3594 for(pp=&pFile->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3595 *pp = p->pNext;
3596
3597 /* Free the connection p */
3598 sqlite3_free(p);
3599 pDbFd->pShm = 0;
3600 sqlite3_mutex_leave(pFile->mutex);
3601
3602 /* If pFile->nRef has reached 0, then close the underlying
3603 ** shared-memory file, too */
3604 unixEnterMutex();
3605 assert( pFile->nRef>0 );
3606 pFile->nRef--;
3607 if( pFile->nRef==0 ){
3608 if( deleteFlag ) unlink(pFile->zFilename);
3609 unixShmPurge();
3610 }
3611 unixLeaveMutex();
3612
3613 return SQLITE_OK;
3614}
3615
3616/*
3617** Query and/or changes the size of the underlying storage for
3618** a shared-memory segment. The reqSize parameter is the new size
3619** of the underlying storage, or -1 to do just a query. The size
3620** of the underlying storage (after resizing if resizing occurs) is
3621** written into pNewSize.
3622**
3623** This routine does not (necessarily) change the size of the mapping
3624** of the underlying storage into memory. Use xShmGet() to change
3625** the mapping size.
3626**
3627** The reqSize parameter is the minimum size requested. The implementation
3628** is free to expand the storage to some larger amount if it chooses.
3629*/
3630static int unixShmSize(
3631 sqlite3_file *fd, /* The open database file holding SHM */
3632 int reqSize, /* Requested size. -1 for query only */
3633 int *pNewSize /* Write new size here */
3634){
3635 unixFile *pDbFd = (unixFile*)fd;
3636 unixShm *p = pDbFd->pShm;
3637 unixShmFile *pFile = p->pFile;
3638 int rc = SQLITE_OK;
3639 struct stat sStat;
3640
drha925fd22010-05-13 08:33:35 +00003641 /* On a query, this loop runs once. When reqSize>=0, the loop potentially
3642 ** runs twice, except if the actual size is already greater than or equal
3643 ** to the requested size, reqSize is set to -1 on the first iteration and
3644 ** the loop only runs once.
3645 */
3646 while( 1 ){
3647 if( fstat(pFile->h, &sStat)==0 ){
3648 *pNewSize = (int)sStat.st_size;
3649 if( reqSize>=0 && reqSize<=(int)sStat.st_size ) break;
3650 }else{
3651 *pNewSize = 0;
3652 rc = SQLITE_IOERR;
3653 break;
3654 }
3655 if( reqSize<0 ) break;
drhd9e5c4f2010-05-12 18:01:39 +00003656 reqSize = (reqSize + SQLITE_UNIX_SHM_INCR - 1)/SQLITE_UNIX_SHM_INCR;
3657 reqSize *= SQLITE_UNIX_SHM_INCR;
3658 rc = ftruncate(pFile->h, reqSize);
drha925fd22010-05-13 08:33:35 +00003659 reqSize = -1;
drhd9e5c4f2010-05-12 18:01:39 +00003660 }
3661 return rc;
3662}
3663
3664
3665/*
3666** Map the shared storage into memory. The minimum size of the
3667** mapping should be reqMapSize if reqMapSize is positive. If
3668** reqMapSize is zero or negative, the implementation can choose
3669** whatever mapping size is convenient.
3670**
3671** *ppBuf is made to point to the memory which is a mapping of the
3672** underlying storage. A mutex is acquired to prevent other threads
3673** from running while *ppBuf is in use in order to prevent other threads
3674** remapping *ppBuf out from under this thread. The unixShmRelease()
3675** call will release the mutex. However, if the lock state is CHECKPOINT,
3676** the mutex is not acquired because CHECKPOINT will never remap the
3677** buffer. RECOVER might remap, though, so CHECKPOINT will acquire
3678** the mutex if and when it promotes to RECOVER.
3679**
3680** RECOVER needs to be atomic. The same mutex that prevents *ppBuf from
3681** being remapped also prevents more than one thread from being in
3682** RECOVER at a time. But, RECOVER sometimes wants to remap itself.
3683** To prevent RECOVER from losing its lock while remapping, the
3684** mutex is not released by unixShmRelease() when in RECOVER.
3685**
3686** *pNewMapSize is set to the size of the mapping.
3687**
3688** *ppBuf and *pNewMapSize might be NULL and zero if no space has
3689** yet been allocated to the underlying storage.
3690*/
3691static int unixShmGet(
3692 sqlite3_file *fd, /* Database file holding shared memory */
3693 int reqMapSize, /* Requested size of mapping. -1 means don't care */
3694 int *pNewMapSize, /* Write new size of mapping here */
3695 void **ppBuf /* Write mapping buffer origin here */
3696){
3697 unixFile *pDbFd = (unixFile*)fd;
3698 unixShm *p = pDbFd->pShm;
3699 unixShmFile *pFile = p->pFile;
3700 int rc = SQLITE_OK;
3701
3702 if( p->lockState!=SQLITE_SHM_CHECKPOINT && p->hasMutexBuf==0 ){
3703 assert( sqlite3_mutex_notheld(pFile->mutex) );
3704 sqlite3_mutex_enter(pFile->mutexBuf);
3705 p->hasMutexBuf = 1;
3706 }
3707 sqlite3_mutex_enter(pFile->mutex);
3708 if( pFile->szMap==0 || reqMapSize>pFile->szMap ){
3709 int actualSize;
3710 if( unixShmSize(fd, -1, &actualSize)==SQLITE_OK
3711 && reqMapSize<actualSize
3712 ){
3713 reqMapSize = actualSize;
3714 }
3715 if( pFile->pMMapBuf ){
3716 munmap(pFile->pMMapBuf, pFile->szMap);
3717 }
3718 pFile->pMMapBuf = mmap(0, reqMapSize, PROT_READ|PROT_WRITE, MAP_SHARED,
3719 pFile->h, 0);
3720 pFile->szMap = pFile->pMMapBuf ? reqMapSize : 0;
3721 }
3722 *pNewMapSize = pFile->szMap;
3723 *ppBuf = pFile->pMMapBuf;
3724 sqlite3_mutex_leave(pFile->mutex);
3725 return rc;
3726}
3727
3728/*
3729** Release the lock held on the shared memory segment to that other
3730** threads are free to resize it if necessary.
3731**
3732** If the lock is not currently held, this routine is a harmless no-op.
3733**
3734** If the shared-memory object is in lock state RECOVER, then we do not
3735** really want to release the lock, so in that case too, this routine
3736** is a no-op.
3737*/
3738static int unixShmRelease(sqlite3_file *fd){
3739 unixFile *pDbFd = (unixFile*)fd;
3740 unixShm *p = pDbFd->pShm;
3741
3742 if( p->hasMutexBuf && p->lockState!=SQLITE_SHM_RECOVER ){
3743 assert( sqlite3_mutex_notheld(p->pFile->mutex) );
3744 sqlite3_mutex_leave(p->pFile->mutexBuf);
3745 p->hasMutexBuf = 0;
3746 }
3747 return SQLITE_OK;
3748}
3749
3750/*
3751** Symbolic names for LOCK states used for debugging.
3752*/
3753#ifdef SQLITE_DEBUG
3754static const char *azLkName[] = {
3755 "UNLOCK",
3756 "READ",
3757 "READ_FULL",
3758 "WRITE",
3759 "PENDING",
3760 "CHECKPOINT",
3761 "RECOVER"
3762};
3763#endif
3764
3765
3766/*
3767** Change the lock state for a shared-memory segment.
3768*/
3769static int unixShmLock(
3770 sqlite3_file *fd, /* Database file holding the shared memory */
3771 int desiredLock, /* One of SQLITE_SHM_xxxxx locking states */
3772 int *pGotLock /* The lock you actually got */
3773){
3774 unixFile *pDbFd = (unixFile*)fd;
3775 unixShm *p = pDbFd->pShm;
3776 unixShmFile *pFile = p->pFile;
3777 int rc = SQLITE_PROTOCOL;
3778
3779 /* Note that SQLITE_SHM_READ_FULL and SQLITE_SHM_PENDING are never
3780 ** directly requested; they are side effects from requesting
3781 ** SQLITE_SHM_READ and SQLITE_SHM_CHECKPOINT, respectively.
3782 */
3783 assert( desiredLock==SQLITE_SHM_UNLOCK
3784 || desiredLock==SQLITE_SHM_READ
3785 || desiredLock==SQLITE_SHM_WRITE
3786 || desiredLock==SQLITE_SHM_CHECKPOINT
3787 || desiredLock==SQLITE_SHM_RECOVER );
3788
3789 /* Return directly if this is just a lock state query, or if
3790 ** the connection is already in the desired locking state.
3791 */
3792 if( desiredLock==p->lockState
3793 || (desiredLock==SQLITE_SHM_READ && p->lockState==SQLITE_SHM_READ_FULL)
3794 ){
3795 OSTRACE(("SHM-LOCK shmid-%d, pid-%d request %s and got %s\n",
3796 p->id, getpid(), azLkName[desiredLock], azLkName[p->lockState]));
3797 if( pGotLock ) *pGotLock = p->lockState;
3798 return SQLITE_OK;
3799 }
3800
3801 OSTRACE(("SHM-LOCK shmid-%d, pid-%d request %s->%s\n",
3802 p->id, getpid(), azLkName[p->lockState], azLkName[desiredLock]));
3803
3804 if( desiredLock==SQLITE_SHM_RECOVER && !p->hasMutexBuf ){
3805 assert( sqlite3_mutex_notheld(pFile->mutex) );
3806 sqlite3_mutex_enter(pFile->mutexBuf);
3807 p->hasMutexBuf = 1;
3808 }
3809 sqlite3_mutex_enter(pFile->mutex);
3810 switch( desiredLock ){
3811 case SQLITE_SHM_UNLOCK: {
3812 assert( p->lockState!=SQLITE_SHM_RECOVER );
3813 unixShmUnlock(pFile, p, UNIX_SHM_A|UNIX_SHM_B|UNIX_SHM_C|UNIX_SHM_D);
3814 rc = SQLITE_OK;
3815 p->lockState = SQLITE_SHM_UNLOCK;
3816 break;
3817 }
3818 case SQLITE_SHM_READ: {
3819 if( p->lockState==SQLITE_SHM_UNLOCK ){
3820 int nAttempt;
3821 rc = SQLITE_BUSY;
3822 assert( p->lockState==SQLITE_SHM_UNLOCK );
3823 for(nAttempt=0; nAttempt<5 && rc==SQLITE_BUSY; nAttempt++){
3824 rc = unixShmSharedLock(pFile, p, UNIX_SHM_A|UNIX_SHM_B);
3825 if( rc==SQLITE_BUSY ){
3826 rc = unixShmSharedLock(pFile, p, UNIX_SHM_D);
3827 if( rc==SQLITE_OK ){
3828 p->lockState = SQLITE_SHM_READ_FULL;
3829 }
3830 }else{
3831 unixShmUnlock(pFile, p, UNIX_SHM_B);
3832 p->lockState = SQLITE_SHM_READ;
3833 }
3834 }
3835 }else{
3836 assert( p->lockState==SQLITE_SHM_WRITE
3837 || p->lockState==SQLITE_SHM_RECOVER );
3838 rc = unixShmSharedLock(pFile, p, UNIX_SHM_A);
3839 unixShmUnlock(pFile, p, UNIX_SHM_C|UNIX_SHM_D);
3840 p->lockState = SQLITE_SHM_READ;
3841 }
3842 break;
3843 }
3844 case SQLITE_SHM_WRITE: {
3845 assert( p->lockState==SQLITE_SHM_READ
3846 || p->lockState==SQLITE_SHM_READ_FULL );
3847 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_C|UNIX_SHM_D);
3848 if( rc==SQLITE_OK ){
3849 p->lockState = SQLITE_SHM_WRITE;
3850 }
3851 break;
3852 }
3853 case SQLITE_SHM_CHECKPOINT: {
3854 assert( p->lockState==SQLITE_SHM_UNLOCK
3855 || p->lockState==SQLITE_SHM_PENDING
3856 );
3857 if( p->lockState==SQLITE_SHM_UNLOCK ){
3858 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_B|UNIX_SHM_C);
3859 if( rc==SQLITE_OK ){
3860 p->lockState = SQLITE_SHM_PENDING;
3861 }
3862 }
3863 if( p->lockState==SQLITE_SHM_PENDING ){
3864 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_A);
3865 if( rc==SQLITE_OK ){
3866 p->lockState = SQLITE_SHM_CHECKPOINT;
3867 }
3868 }
3869 break;
3870 }
3871 default: {
3872 assert( desiredLock==SQLITE_SHM_RECOVER );
3873 assert( p->lockState==SQLITE_SHM_READ
3874 || p->lockState==SQLITE_SHM_READ_FULL
3875 );
3876 assert( sqlite3_mutex_held(pFile->mutexBuf) );
3877 rc = unixShmExclusiveLock(pFile, p, UNIX_SHM_C);
3878 if( rc==SQLITE_OK ){
3879 p->lockState = SQLITE_SHM_RECOVER;
3880 }
3881 break;
3882 }
3883 }
3884 sqlite3_mutex_leave(pFile->mutex);
3885 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %s\n",
3886 p->id, getpid(), azLkName[p->lockState]));
3887 if( pGotLock ) *pGotLock = p->lockState;
3888 return rc;
3889}
3890
3891#else
3892# define unixShmOpen 0
3893# define unixShmSize 0
3894# define unixShmGet 0
3895# define unixShmRelease 0
3896# define unixShmLock 0
3897# define unixShmClose 0
3898#endif /* #ifndef SQLITE_OMIT_WAL */
3899
drh734c9862008-11-28 15:37:20 +00003900/*
3901** Here ends the implementation of all sqlite3_file methods.
3902**
3903********************** End sqlite3_file Methods *******************************
3904******************************************************************************/
3905
3906/*
drh6b9d6dd2008-12-03 19:34:47 +00003907** This division contains definitions of sqlite3_io_methods objects that
3908** implement various file locking strategies. It also contains definitions
3909** of "finder" functions. A finder-function is used to locate the appropriate
3910** sqlite3_io_methods object for a particular database file. The pAppData
3911** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3912** the correct finder-function for that VFS.
3913**
3914** Most finder functions return a pointer to a fixed sqlite3_io_methods
3915** object. The only interesting finder-function is autolockIoFinder, which
3916** looks at the filesystem type and tries to guess the best locking
3917** strategy from that.
3918**
drh1875f7a2008-12-08 18:19:17 +00003919** For finder-funtion F, two objects are created:
3920**
3921** (1) The real finder-function named "FImpt()".
3922**
dane946c392009-08-22 11:39:46 +00003923** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003924**
3925**
3926** A pointer to the F pointer is used as the pAppData value for VFS
3927** objects. We have to do this instead of letting pAppData point
3928** directly at the finder-function since C90 rules prevent a void*
3929** from be cast into a function pointer.
3930**
drh6b9d6dd2008-12-03 19:34:47 +00003931**
drh7708e972008-11-29 00:56:52 +00003932** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003933**
drh7708e972008-11-29 00:56:52 +00003934** * A constant sqlite3_io_methods object call METHOD that has locking
3935** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3936**
3937** * An I/O method finder function called FINDER that returns a pointer
3938** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003939*/
drhd9e5c4f2010-05-12 18:01:39 +00003940#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00003941static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00003942 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00003943 CLOSE, /* xClose */ \
3944 unixRead, /* xRead */ \
3945 unixWrite, /* xWrite */ \
3946 unixTruncate, /* xTruncate */ \
3947 unixSync, /* xSync */ \
3948 unixFileSize, /* xFileSize */ \
3949 LOCK, /* xLock */ \
3950 UNLOCK, /* xUnlock */ \
3951 CKLOCK, /* xCheckReservedLock */ \
3952 unixFileControl, /* xFileControl */ \
3953 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00003954 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
3955 unixShmOpen, /* xShmOpen */ \
3956 unixShmSize, /* xShmSize */ \
3957 unixShmGet, /* xShmGet */ \
3958 unixShmRelease, /* xShmRelease */ \
3959 unixShmLock, /* xShmLock */ \
3960 unixShmClose /* xShmClose */ \
drh7708e972008-11-29 00:56:52 +00003961}; \
drh0c2694b2009-09-03 16:23:44 +00003962static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3963 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003964 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003965} \
drh0c2694b2009-09-03 16:23:44 +00003966static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003967 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003968
3969/*
3970** Here are all of the sqlite3_io_methods objects for each of the
3971** locking strategies. Functions that return pointers to these methods
3972** are also created.
3973*/
3974IOMETHODS(
3975 posixIoFinder, /* Finder function name */
3976 posixIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00003977 2, /* ShmOpen is enabled */
drh7708e972008-11-29 00:56:52 +00003978 unixClose, /* xClose method */
3979 unixLock, /* xLock method */
3980 unixUnlock, /* xUnlock method */
3981 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003982)
drh7708e972008-11-29 00:56:52 +00003983IOMETHODS(
3984 nolockIoFinder, /* Finder function name */
3985 nolockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00003986 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00003987 nolockClose, /* xClose method */
3988 nolockLock, /* xLock method */
3989 nolockUnlock, /* xUnlock method */
3990 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003991)
drh7708e972008-11-29 00:56:52 +00003992IOMETHODS(
3993 dotlockIoFinder, /* Finder function name */
3994 dotlockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00003995 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00003996 dotlockClose, /* xClose method */
3997 dotlockLock, /* xLock method */
3998 dotlockUnlock, /* xUnlock method */
3999 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004000)
drh7708e972008-11-29 00:56:52 +00004001
chw78a13182009-04-07 05:35:03 +00004002#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004003IOMETHODS(
4004 flockIoFinder, /* Finder function name */
4005 flockIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004006 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004007 flockClose, /* xClose method */
4008 flockLock, /* xLock method */
4009 flockUnlock, /* xUnlock method */
4010 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004011)
drh7708e972008-11-29 00:56:52 +00004012#endif
4013
drh6c7d5c52008-11-21 20:32:33 +00004014#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004015IOMETHODS(
4016 semIoFinder, /* Finder function name */
4017 semIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004018 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004019 semClose, /* xClose method */
4020 semLock, /* xLock method */
4021 semUnlock, /* xUnlock method */
4022 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004023)
aswiftaebf4132008-11-21 00:10:35 +00004024#endif
drh7708e972008-11-29 00:56:52 +00004025
drhd2cb50b2009-01-09 21:41:17 +00004026#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004027IOMETHODS(
4028 afpIoFinder, /* Finder function name */
4029 afpIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004030 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004031 afpClose, /* xClose method */
4032 afpLock, /* xLock method */
4033 afpUnlock, /* xUnlock method */
4034 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004035)
drh715ff302008-12-03 22:32:44 +00004036#endif
4037
4038/*
4039** The proxy locking method is a "super-method" in the sense that it
4040** opens secondary file descriptors for the conch and lock files and
4041** it uses proxy, dot-file, AFP, and flock() locking methods on those
4042** secondary files. For this reason, the division that implements
4043** proxy locking is located much further down in the file. But we need
4044** to go ahead and define the sqlite3_io_methods and finder function
4045** for proxy locking here. So we forward declare the I/O methods.
4046*/
drhd2cb50b2009-01-09 21:41:17 +00004047#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004048static int proxyClose(sqlite3_file*);
4049static int proxyLock(sqlite3_file*, int);
4050static int proxyUnlock(sqlite3_file*, int);
4051static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004052IOMETHODS(
4053 proxyIoFinder, /* Finder function name */
4054 proxyIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004055 1, /* ShmOpen is disabled */
drh7708e972008-11-29 00:56:52 +00004056 proxyClose, /* xClose method */
4057 proxyLock, /* xLock method */
4058 proxyUnlock, /* xUnlock method */
4059 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004060)
aswiftaebf4132008-11-21 00:10:35 +00004061#endif
drh7708e972008-11-29 00:56:52 +00004062
drh7ed97b92010-01-20 13:07:21 +00004063/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4064#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4065IOMETHODS(
4066 nfsIoFinder, /* Finder function name */
4067 nfsIoMethods, /* sqlite3_io_methods object name */
drhd9e5c4f2010-05-12 18:01:39 +00004068 1, /* ShmOpen is disabled */
drh7ed97b92010-01-20 13:07:21 +00004069 unixClose, /* xClose method */
4070 unixLock, /* xLock method */
4071 nfsUnlock, /* xUnlock method */
4072 unixCheckReservedLock /* xCheckReservedLock method */
4073)
4074#endif
drh7708e972008-11-29 00:56:52 +00004075
drhd2cb50b2009-01-09 21:41:17 +00004076#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004077/*
drh6b9d6dd2008-12-03 19:34:47 +00004078** This "finder" function attempts to determine the best locking strategy
4079** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004080** object that implements that strategy.
4081**
4082** This is for MacOSX only.
4083*/
drh1875f7a2008-12-08 18:19:17 +00004084static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004085 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004086 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004087){
4088 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004089 const char *zFilesystem; /* Filesystem type name */
4090 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004091 } aMap[] = {
4092 { "hfs", &posixIoMethods },
4093 { "ufs", &posixIoMethods },
4094 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004095 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004096 { "webdav", &nolockIoMethods },
4097 { 0, 0 }
4098 };
4099 int i;
4100 struct statfs fsInfo;
4101 struct flock lockInfo;
4102
4103 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004104 /* If filePath==NULL that means we are dealing with a transient file
4105 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004106 return &nolockIoMethods;
4107 }
4108 if( statfs(filePath, &fsInfo) != -1 ){
4109 if( fsInfo.f_flags & MNT_RDONLY ){
4110 return &nolockIoMethods;
4111 }
4112 for(i=0; aMap[i].zFilesystem; i++){
4113 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4114 return aMap[i].pMethods;
4115 }
4116 }
4117 }
4118
4119 /* Default case. Handles, amongst others, "nfs".
4120 ** Test byte-range lock using fcntl(). If the call succeeds,
4121 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004122 */
drh7708e972008-11-29 00:56:52 +00004123 lockInfo.l_len = 1;
4124 lockInfo.l_start = 0;
4125 lockInfo.l_whence = SEEK_SET;
4126 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004127 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004128 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4129 return &nfsIoMethods;
4130 } else {
4131 return &posixIoMethods;
4132 }
drh7708e972008-11-29 00:56:52 +00004133 }else{
4134 return &dotlockIoMethods;
4135 }
4136}
drh0c2694b2009-09-03 16:23:44 +00004137static const sqlite3_io_methods
4138 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004139
drhd2cb50b2009-01-09 21:41:17 +00004140#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004141
chw78a13182009-04-07 05:35:03 +00004142#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4143/*
4144** This "finder" function attempts to determine the best locking strategy
4145** for the database file "filePath". It then returns the sqlite3_io_methods
4146** object that implements that strategy.
4147**
4148** This is for VXWorks only.
4149*/
4150static const sqlite3_io_methods *autolockIoFinderImpl(
4151 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004152 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004153){
4154 struct flock lockInfo;
4155
4156 if( !filePath ){
4157 /* If filePath==NULL that means we are dealing with a transient file
4158 ** that does not need to be locked. */
4159 return &nolockIoMethods;
4160 }
4161
4162 /* Test if fcntl() is supported and use POSIX style locks.
4163 ** Otherwise fall back to the named semaphore method.
4164 */
4165 lockInfo.l_len = 1;
4166 lockInfo.l_start = 0;
4167 lockInfo.l_whence = SEEK_SET;
4168 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00004169 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004170 return &posixIoMethods;
4171 }else{
4172 return &semIoMethods;
4173 }
4174}
drh0c2694b2009-09-03 16:23:44 +00004175static const sqlite3_io_methods
4176 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004177
4178#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4179
drh7708e972008-11-29 00:56:52 +00004180/*
4181** An abstract type for a pointer to a IO method finder function:
4182*/
drh0c2694b2009-09-03 16:23:44 +00004183typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004184
aswiftaebf4132008-11-21 00:10:35 +00004185
drh734c9862008-11-28 15:37:20 +00004186/****************************************************************************
4187**************************** sqlite3_vfs methods ****************************
4188**
4189** This division contains the implementation of methods on the
4190** sqlite3_vfs object.
4191*/
4192
danielk1977a3d4c882007-03-23 10:08:38 +00004193/*
danielk1977e339d652008-06-28 11:23:00 +00004194** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004195*/
4196static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004197 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004198 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004199 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004200 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004201 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004202 int noLock, /* Omit locking if true */
4203 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00004204){
drh7708e972008-11-29 00:56:52 +00004205 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004206 unixFile *pNew = (unixFile *)pId;
4207 int rc = SQLITE_OK;
4208
drh8af6c222010-05-14 12:43:01 +00004209 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004210
dane946c392009-08-22 11:39:46 +00004211 /* Parameter isDelete is only used on vxworks. Express this explicitly
4212 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004213 */
drh7708e972008-11-29 00:56:52 +00004214 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004215
drh308c2a52010-05-14 11:30:18 +00004216 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004217 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004218 pNew->dirfd = dirfd;
drh0c2694b2009-09-03 16:23:44 +00004219 pNew->fileFlags = 0;
drhd9e5c4f2010-05-12 18:01:39 +00004220 assert( zFilename==0 || zFilename[0]=='/' ); /* Never a relative pathname */
4221 pNew->zPath = zFilename;
drh339eb0b2008-03-07 15:34:11 +00004222
drh6c7d5c52008-11-21 20:32:33 +00004223#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004224 pNew->pId = vxworksFindFileId(zFilename);
4225 if( pNew->pId==0 ){
4226 noLock = 1;
4227 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004228 }
4229#endif
4230
drhda0e7682008-07-30 15:27:54 +00004231 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004232 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004233 }else{
drh0c2694b2009-09-03 16:23:44 +00004234 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004235#if SQLITE_ENABLE_LOCKING_STYLE
4236 /* Cache zFilename in the locking context (AFP and dotlock override) for
4237 ** proxyLock activation is possible (remote proxy is based on db name)
4238 ** zFilename remains valid until file is closed, to support */
4239 pNew->lockingContext = (void*)zFilename;
4240#endif
drhda0e7682008-07-30 15:27:54 +00004241 }
danielk1977e339d652008-06-28 11:23:00 +00004242
drh7ed97b92010-01-20 13:07:21 +00004243 if( pLockingStyle == &posixIoMethods
4244#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4245 || pLockingStyle == &nfsIoMethods
4246#endif
4247 ){
drh7708e972008-11-29 00:56:52 +00004248 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004249 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004250 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004251 /* If an error occured in findInodeInfo(), close the file descriptor
4252 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004253 ** in two scenarios:
4254 **
4255 ** (a) A call to fstat() failed.
4256 ** (b) A malloc failed.
4257 **
4258 ** Scenario (b) may only occur if the process is holding no other
4259 ** file descriptors open on the same file. If there were other file
4260 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004261 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004262 ** handle h - as it is guaranteed that no posix locks will be released
4263 ** by doing so.
4264 **
4265 ** If scenario (a) caused the error then things are not so safe. The
4266 ** implicit assumption here is that if fstat() fails, things are in
4267 ** such bad shape that dropping a lock or two doesn't matter much.
4268 */
4269 close(h);
4270 h = -1;
4271 }
drh7708e972008-11-29 00:56:52 +00004272 unixLeaveMutex();
4273 }
danielk1977e339d652008-06-28 11:23:00 +00004274
drhd2cb50b2009-01-09 21:41:17 +00004275#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004276 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004277 /* AFP locking uses the file path so it needs to be included in
4278 ** the afpLockingContext.
4279 */
4280 afpLockingContext *pCtx;
4281 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4282 if( pCtx==0 ){
4283 rc = SQLITE_NOMEM;
4284 }else{
4285 /* NB: zFilename exists and remains valid until the file is closed
4286 ** according to requirement F11141. So we do not need to make a
4287 ** copy of the filename. */
4288 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004289 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004290 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004291 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004292 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004293 if( rc!=SQLITE_OK ){
4294 sqlite3_free(pNew->lockingContext);
4295 close(h);
4296 h = -1;
4297 }
drh7708e972008-11-29 00:56:52 +00004298 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004299 }
drh7708e972008-11-29 00:56:52 +00004300 }
4301#endif
danielk1977e339d652008-06-28 11:23:00 +00004302
drh7708e972008-11-29 00:56:52 +00004303 else if( pLockingStyle == &dotlockIoMethods ){
4304 /* Dotfile locking uses the file path so it needs to be included in
4305 ** the dotlockLockingContext
4306 */
4307 char *zLockFile;
4308 int nFilename;
drhea678832008-12-10 19:26:22 +00004309 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004310 zLockFile = (char *)sqlite3_malloc(nFilename);
4311 if( zLockFile==0 ){
4312 rc = SQLITE_NOMEM;
4313 }else{
4314 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004315 }
drh7708e972008-11-29 00:56:52 +00004316 pNew->lockingContext = zLockFile;
4317 }
danielk1977e339d652008-06-28 11:23:00 +00004318
drh6c7d5c52008-11-21 20:32:33 +00004319#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004320 else if( pLockingStyle == &semIoMethods ){
4321 /* Named semaphore locking uses the file path so it needs to be
4322 ** included in the semLockingContext
4323 */
4324 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004325 rc = findInodeInfo(pNew, &pNew->pInode);
4326 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4327 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004328 int n;
drh2238dcc2009-08-27 17:56:20 +00004329 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004330 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004331 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004332 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004333 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4334 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004335 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004336 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004337 }
chw97185482008-11-17 08:05:31 +00004338 }
drh7708e972008-11-29 00:56:52 +00004339 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004340 }
drh7708e972008-11-29 00:56:52 +00004341#endif
aswift5b1a2562008-08-22 00:22:35 +00004342
4343 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004344#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004345 if( rc!=SQLITE_OK ){
drh309e6552010-02-05 18:00:26 +00004346 if( h>=0 ) close(h);
4347 h = -1;
chw97185482008-11-17 08:05:31 +00004348 unlink(zFilename);
4349 isDelete = 0;
4350 }
4351 pNew->isDelete = isDelete;
4352#endif
danielk1977e339d652008-06-28 11:23:00 +00004353 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00004354 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004355 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00004356 }else{
drh7708e972008-11-29 00:56:52 +00004357 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004358 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004359 }
danielk1977e339d652008-06-28 11:23:00 +00004360 return rc;
drh054889e2005-11-30 03:20:31 +00004361}
drh9c06c952005-11-26 00:25:00 +00004362
danielk1977ad94b582007-08-20 06:44:22 +00004363/*
4364** Open a file descriptor to the directory containing file zFilename.
4365** If successful, *pFd is set to the opened file descriptor and
4366** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4367** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4368** value.
4369**
4370** If SQLITE_OK is returned, the caller is responsible for closing
4371** the file descriptor *pFd using close().
4372*/
danielk1977fee2d252007-08-18 10:59:19 +00004373static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004374 int ii;
drh777b17a2007-09-20 10:02:54 +00004375 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004376 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004377
drh153c62c2007-08-24 03:51:33 +00004378 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004379 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004380 if( ii>0 ){
4381 zDirname[ii] = '\0';
4382 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004383 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004384#ifdef FD_CLOEXEC
4385 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4386#endif
drh308c2a52010-05-14 11:30:18 +00004387 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004388 }
4389 }
danielk1977fee2d252007-08-18 10:59:19 +00004390 *pFd = fd;
drh9978c972010-02-23 17:36:32 +00004391 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
danielk1977fee2d252007-08-18 10:59:19 +00004392}
4393
danielk1977b4b47412007-08-17 15:53:36 +00004394/*
danielk197717b90b52008-06-06 11:11:25 +00004395** Create a temporary file name in zBuf. zBuf must be allocated
4396** by the calling process and must be big enough to hold at least
4397** pVfs->mxPathname bytes.
4398*/
4399static int getTempname(int nBuf, char *zBuf){
4400 static const char *azDirs[] = {
4401 0,
aswiftaebf4132008-11-21 00:10:35 +00004402 0,
danielk197717b90b52008-06-06 11:11:25 +00004403 "/var/tmp",
4404 "/usr/tmp",
4405 "/tmp",
4406 ".",
4407 };
4408 static const unsigned char zChars[] =
4409 "abcdefghijklmnopqrstuvwxyz"
4410 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4411 "0123456789";
drh41022642008-11-21 00:24:42 +00004412 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00004413 struct stat buf;
4414 const char *zDir = ".";
4415
4416 /* It's odd to simulate an io-error here, but really this is just
4417 ** using the io-error infrastructure to test that SQLite handles this
4418 ** function failing.
4419 */
4420 SimulateIOError( return SQLITE_IOERR );
4421
4422 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00004423 if (NULL == azDirs[1]) {
4424 azDirs[1] = getenv("TMPDIR");
4425 }
4426
4427 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00004428 if( azDirs[i]==0 ) continue;
4429 if( stat(azDirs[i], &buf) ) continue;
4430 if( !S_ISDIR(buf.st_mode) ) continue;
4431 if( access(azDirs[i], 07) ) continue;
4432 zDir = azDirs[i];
4433 break;
4434 }
4435
4436 /* Check that the output buffer is large enough for the temporary file
4437 ** name. If it is not, return SQLITE_ERROR.
4438 */
danielk197700e13612008-11-17 19:18:54 +00004439 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004440 return SQLITE_ERROR;
4441 }
4442
4443 do{
4444 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004445 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004446 sqlite3_randomness(15, &zBuf[j]);
4447 for(i=0; i<15; i++, j++){
4448 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4449 }
4450 zBuf[j] = 0;
4451 }while( access(zBuf,0)==0 );
4452 return SQLITE_OK;
4453}
4454
drhd2cb50b2009-01-09 21:41:17 +00004455#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004456/*
4457** Routine to transform a unixFile into a proxy-locking unixFile.
4458** Implementation in the proxy-lock division, but used by unixOpen()
4459** if SQLITE_PREFER_PROXY_LOCKING is defined.
4460*/
4461static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004462#endif
drhc66d5b62008-12-03 22:48:32 +00004463
dan08da86a2009-08-21 17:18:03 +00004464/*
4465** Search for an unused file descriptor that was opened on the database
4466** file (not a journal or master-journal file) identified by pathname
4467** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4468** argument to this function.
4469**
4470** Such a file descriptor may exist if a database connection was closed
4471** but the associated file descriptor could not be closed because some
4472** other file descriptor open on the same file is holding a file-lock.
4473** Refer to comments in the unixClose() function and the lengthy comment
4474** describing "Posix Advisory Locking" at the start of this file for
4475** further details. Also, ticket #4018.
4476**
4477** If a suitable file descriptor is found, then it is returned. If no
4478** such file descriptor is located, -1 is returned.
4479*/
dane946c392009-08-22 11:39:46 +00004480static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4481 UnixUnusedFd *pUnused = 0;
4482
4483 /* Do not search for an unused file descriptor on vxworks. Not because
4484 ** vxworks would not benefit from the change (it might, we're not sure),
4485 ** but because no way to test it is currently available. It is better
4486 ** not to risk breaking vxworks support for the sake of such an obscure
4487 ** feature. */
4488#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004489 struct stat sStat; /* Results of stat() call */
4490
4491 /* A stat() call may fail for various reasons. If this happens, it is
4492 ** almost certain that an open() call on the same path will also fail.
4493 ** For this reason, if an error occurs in the stat() call here, it is
4494 ** ignored and -1 is returned. The caller will try to open a new file
4495 ** descriptor on the same path, fail, and return an error to SQLite.
4496 **
4497 ** Even if a subsequent open() call does succeed, the consequences of
4498 ** not searching for a resusable file descriptor are not dire. */
4499 if( 0==stat(zPath, &sStat) ){
drh8af6c222010-05-14 12:43:01 +00004500 struct unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004501
4502 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004503 pInode = inodeList;
4504 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4505 || pInode->fileId.ino!=sStat.st_ino) ){
4506 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004507 }
drh8af6c222010-05-14 12:43:01 +00004508 if( pInode ){
dane946c392009-08-22 11:39:46 +00004509 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004510 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004511 pUnused = *pp;
4512 if( pUnused ){
4513 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004514 }
4515 }
4516 unixLeaveMutex();
4517 }
dane946c392009-08-22 11:39:46 +00004518#endif /* if !OS_VXWORKS */
4519 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004520}
danielk197717b90b52008-06-06 11:11:25 +00004521
4522/*
danielk1977ad94b582007-08-20 06:44:22 +00004523** Open the file zPath.
4524**
danielk1977b4b47412007-08-17 15:53:36 +00004525** Previously, the SQLite OS layer used three functions in place of this
4526** one:
4527**
4528** sqlite3OsOpenReadWrite();
4529** sqlite3OsOpenReadOnly();
4530** sqlite3OsOpenExclusive();
4531**
4532** These calls correspond to the following combinations of flags:
4533**
4534** ReadWrite() -> (READWRITE | CREATE)
4535** ReadOnly() -> (READONLY)
4536** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4537**
4538** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4539** true, the file was configured to be automatically deleted when the
4540** file handle closed. To achieve the same effect using this new
4541** interface, add the DELETEONCLOSE flag to those specified above for
4542** OpenExclusive().
4543*/
4544static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004545 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4546 const char *zPath, /* Pathname of file to be opened */
4547 sqlite3_file *pFile, /* The file descriptor to be filled in */
4548 int flags, /* Input flags to control the opening */
4549 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004550){
dan08da86a2009-08-21 17:18:03 +00004551 unixFile *p = (unixFile *)pFile;
4552 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004553 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004554 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004555 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004556 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004557 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004558
4559 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4560 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4561 int isCreate = (flags & SQLITE_OPEN_CREATE);
4562 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4563 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004564#if SQLITE_ENABLE_LOCKING_STYLE
4565 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4566#endif
danielk1977b4b47412007-08-17 15:53:36 +00004567
danielk1977fee2d252007-08-18 10:59:19 +00004568 /* If creating a master or main-file journal, this function will open
4569 ** a file-descriptor on the directory too. The first time unixSync()
4570 ** is called the directory file descriptor will be fsync()ed and close()d.
4571 */
4572 int isOpenDirectory = (isCreate &&
4573 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
4574 );
4575
danielk197717b90b52008-06-06 11:11:25 +00004576 /* If argument zPath is a NULL pointer, this function is required to open
4577 ** a temporary file. Use this buffer to store the file name in.
4578 */
4579 char zTmpname[MAX_PATHNAME+1];
4580 const char *zName = zPath;
4581
danielk1977fee2d252007-08-18 10:59:19 +00004582 /* Check the following statements are true:
4583 **
4584 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4585 ** (b) if CREATE is set, then READWRITE must also be set, and
4586 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004587 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004588 */
danielk1977b4b47412007-08-17 15:53:36 +00004589 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004590 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004591 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004592 assert(isDelete==0 || isCreate);
4593
drh33f4e022007-09-03 15:19:34 +00004594 /* The main DB, main journal, and master journal are never automatically
dan08da86a2009-08-21 17:18:03 +00004595 ** deleted. Nor are they ever temporary files. */
4596 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4597 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4598 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danielk1977b4b47412007-08-17 15:53:36 +00004599
danielk1977fee2d252007-08-18 10:59:19 +00004600 /* Assert that the upper layer has set one of the "file-type" flags. */
4601 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4602 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4603 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00004604 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00004605 );
4606
dan08da86a2009-08-21 17:18:03 +00004607 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004608
dan08da86a2009-08-21 17:18:03 +00004609 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004610 UnixUnusedFd *pUnused;
4611 pUnused = findReusableFd(zName, flags);
4612 if( pUnused ){
4613 fd = pUnused->fd;
4614 }else{
dan6aa657f2009-08-24 18:57:58 +00004615 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004616 if( !pUnused ){
4617 return SQLITE_NOMEM;
4618 }
4619 }
4620 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004621 }else if( !zName ){
4622 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004623 assert(isDelete && !isOpenDirectory);
4624 rc = getTempname(MAX_PATHNAME+1, zTmpname);
4625 if( rc!=SQLITE_OK ){
4626 return rc;
4627 }
4628 zName = zTmpname;
4629 }
4630
dan08da86a2009-08-21 17:18:03 +00004631 /* Determine the value of the flags parameter passed to POSIX function
4632 ** open(). These must be calculated even if open() is not called, as
4633 ** they may be stored as part of the file handle and used by the
4634 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004635 if( isReadonly ) openFlags |= O_RDONLY;
4636 if( isReadWrite ) openFlags |= O_RDWR;
4637 if( isCreate ) openFlags |= O_CREAT;
4638 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4639 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004640
danielk1977b4b47412007-08-17 15:53:36 +00004641 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00004642 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
4643 fd = open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00004644 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00004645 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
4646 /* Failed to open the file for read/write access. Try read-only. */
4647 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00004648 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00004649 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00004650 openFlags |= O_RDONLY;
4651 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00004652 }
4653 if( fd<0 ){
drh9978c972010-02-23 17:36:32 +00004654 rc = SQLITE_CANTOPEN_BKPT;
dane946c392009-08-22 11:39:46 +00004655 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00004656 }
danielk1977b4b47412007-08-17 15:53:36 +00004657 }
dan08da86a2009-08-21 17:18:03 +00004658 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00004659 if( pOutFlags ){
4660 *pOutFlags = flags;
4661 }
4662
dane946c392009-08-22 11:39:46 +00004663 if( p->pUnused ){
4664 p->pUnused->fd = fd;
4665 p->pUnused->flags = flags;
4666 }
4667
danielk1977b4b47412007-08-17 15:53:36 +00004668 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004669#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004670 zPath = zName;
4671#else
danielk197717b90b52008-06-06 11:11:25 +00004672 unlink(zName);
chw97185482008-11-17 08:05:31 +00004673#endif
danielk1977b4b47412007-08-17 15:53:36 +00004674 }
drh41022642008-11-21 00:24:42 +00004675#if SQLITE_ENABLE_LOCKING_STYLE
4676 else{
dan08da86a2009-08-21 17:18:03 +00004677 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00004678 }
4679#endif
4680
danielk1977fee2d252007-08-18 10:59:19 +00004681 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004682 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004683 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00004684 /* It is safe to close fd at this point, because it is guaranteed not
4685 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00004686 ** it would not be safe to close as this would release any locks held
4687 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00004688 assert( eType!=SQLITE_OPEN_MAIN_DB );
4689 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00004690 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00004691 }
4692 }
danielk1977e339d652008-06-28 11:23:00 +00004693
4694#ifdef FD_CLOEXEC
4695 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4696#endif
4697
drhda0e7682008-07-30 15:27:54 +00004698 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004699
drh7ed97b92010-01-20 13:07:21 +00004700
4701#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4702 struct statfs fsInfo;
4703 if( fstatfs(fd, &fsInfo) == -1 ){
4704 ((unixFile*)pFile)->lastErrno = errno;
4705 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4706 close(fd); /* silently leak if fail, in error */
4707 return SQLITE_IOERR_ACCESS;
4708 }
4709 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4710 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4711 }
4712#endif
4713
4714#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004715#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00004716 isAutoProxy = 1;
4717#endif
4718 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004719 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4720 int useProxy = 0;
4721
dan08da86a2009-08-21 17:18:03 +00004722 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4723 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004724 if( envforce!=NULL ){
4725 useProxy = atoi(envforce)>0;
4726 }else{
4727 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004728 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004729 /* In theory, the close(fd) call is sub-optimal. If the file opened
4730 ** with fd is a database file, and there are other connections open
4731 ** on that file that are currently holding advisory locks on it,
4732 ** then the call to close() will cancel those locks. In practice,
4733 ** we're assuming that statfs() doesn't fail very often. At least
4734 ** not while other file descriptors opened by the same process on
4735 ** the same file are working. */
4736 p->lastErrno = errno;
4737 if( dirfd>=0 ){
4738 close(dirfd); /* silently leak if fail, in error */
4739 }
aswiftaebf4132008-11-21 00:10:35 +00004740 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004741 rc = SQLITE_IOERR_ACCESS;
4742 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004743 }
4744 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4745 }
4746 if( useProxy ){
4747 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4748 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004749 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00004750 if( rc!=SQLITE_OK ){
4751 /* Use unixClose to clean up the resources added in fillInUnixFile
4752 ** and clear all the structure's references. Specifically,
4753 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4754 */
4755 unixClose(pFile);
4756 return rc;
4757 }
aswiftaebf4132008-11-21 00:10:35 +00004758 }
dane946c392009-08-22 11:39:46 +00004759 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004760 }
4761 }
4762#endif
4763
dane946c392009-08-22 11:39:46 +00004764 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4765open_finished:
4766 if( rc!=SQLITE_OK ){
4767 sqlite3_free(p->pUnused);
4768 }
4769 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004770}
4771
dane946c392009-08-22 11:39:46 +00004772
danielk1977b4b47412007-08-17 15:53:36 +00004773/*
danielk1977fee2d252007-08-18 10:59:19 +00004774** Delete the file at zPath. If the dirSync argument is true, fsync()
4775** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004776*/
drh6b9d6dd2008-12-03 19:34:47 +00004777static int unixDelete(
4778 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4779 const char *zPath, /* Name of file to be deleted */
4780 int dirSync /* If true, fsync() directory after deleting file */
4781){
danielk1977fee2d252007-08-18 10:59:19 +00004782 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004783 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004784 SimulateIOError(return SQLITE_IOERR_DELETE);
4785 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00004786#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004787 if( dirSync ){
4788 int fd;
4789 rc = openDirectory(zPath, &fd);
4790 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004791#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004792 if( fsync(fd)==-1 )
4793#else
4794 if( fsync(fd) )
4795#endif
4796 {
danielk1977fee2d252007-08-18 10:59:19 +00004797 rc = SQLITE_IOERR_DIR_FSYNC;
4798 }
aswiftaebf4132008-11-21 00:10:35 +00004799 if( close(fd)&&!rc ){
4800 rc = SQLITE_IOERR_DIR_CLOSE;
4801 }
danielk1977fee2d252007-08-18 10:59:19 +00004802 }
4803 }
danielk1977d138dd82008-10-15 16:02:48 +00004804#endif
danielk1977fee2d252007-08-18 10:59:19 +00004805 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004806}
4807
danielk197790949c22007-08-17 16:50:38 +00004808/*
4809** Test the existance of or access permissions of file zPath. The
4810** test performed depends on the value of flags:
4811**
4812** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4813** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4814** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4815**
4816** Otherwise return 0.
4817*/
danielk1977861f7452008-06-05 11:39:11 +00004818static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004819 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4820 const char *zPath, /* Path of the file to examine */
4821 int flags, /* What do we want to learn about the zPath file? */
4822 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004823){
rse25c0d1a2007-09-20 08:38:14 +00004824 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004825 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004826 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004827 switch( flags ){
4828 case SQLITE_ACCESS_EXISTS:
4829 amode = F_OK;
4830 break;
4831 case SQLITE_ACCESS_READWRITE:
4832 amode = W_OK|R_OK;
4833 break;
drh50d3f902007-08-27 21:10:36 +00004834 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004835 amode = R_OK;
4836 break;
4837
4838 default:
4839 assert(!"Invalid flags argument");
4840 }
danielk1977861f7452008-06-05 11:39:11 +00004841 *pResOut = (access(zPath, amode)==0);
4842 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004843}
4844
danielk1977b4b47412007-08-17 15:53:36 +00004845
4846/*
4847** Turn a relative pathname into a full pathname. The relative path
4848** is stored as a nul-terminated string in the buffer pointed to by
4849** zPath.
4850**
4851** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4852** (in this case, MAX_PATHNAME bytes). The full-path is written to
4853** this buffer before returning.
4854*/
danielk1977adfb9b02007-09-17 07:02:56 +00004855static int unixFullPathname(
4856 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4857 const char *zPath, /* Possibly relative input path */
4858 int nOut, /* Size of output buffer in bytes */
4859 char *zOut /* Output buffer */
4860){
danielk1977843e65f2007-09-01 16:16:15 +00004861
4862 /* It's odd to simulate an io-error here, but really this is just
4863 ** using the io-error infrastructure to test that SQLite handles this
4864 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004865 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004866 */
4867 SimulateIOError( return SQLITE_ERROR );
4868
drh153c62c2007-08-24 03:51:33 +00004869 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004870 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004871
drh3c7f2dc2007-12-06 13:26:20 +00004872 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004873 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004874 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004875 }else{
4876 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004877 if( getcwd(zOut, nOut-1)==0 ){
drh9978c972010-02-23 17:36:32 +00004878 return SQLITE_CANTOPEN_BKPT;
danielk1977b4b47412007-08-17 15:53:36 +00004879 }
drhea678832008-12-10 19:26:22 +00004880 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004881 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004882 }
4883 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004884}
4885
drh0ccebe72005-06-07 22:22:50 +00004886
drh761df872006-12-21 01:29:22 +00004887#ifndef SQLITE_OMIT_LOAD_EXTENSION
4888/*
4889** Interfaces for opening a shared library, finding entry points
4890** within the shared library, and closing the shared library.
4891*/
4892#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004893static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4894 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004895 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4896}
danielk197795c8a542007-09-01 06:51:27 +00004897
4898/*
4899** SQLite calls this function immediately after a call to unixDlSym() or
4900** unixDlOpen() fails (returns a null pointer). If a more detailed error
4901** message is available, it is written to zBufOut. If no error message
4902** is available, zBufOut is left unmodified and SQLite uses a default
4903** error message.
4904*/
danielk1977397d65f2008-11-19 11:35:39 +00004905static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004906 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004907 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004908 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004909 zErr = dlerror();
4910 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004911 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004912 }
drh6c7d5c52008-11-21 20:32:33 +00004913 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004914}
drh1875f7a2008-12-08 18:19:17 +00004915static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4916 /*
4917 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4918 ** cast into a pointer to a function. And yet the library dlsym() routine
4919 ** returns a void* which is really a pointer to a function. So how do we
4920 ** use dlsym() with -pedantic-errors?
4921 **
4922 ** Variable x below is defined to be a pointer to a function taking
4923 ** parameters void* and const char* and returning a pointer to a function.
4924 ** We initialize x by assigning it a pointer to the dlsym() function.
4925 ** (That assignment requires a cast.) Then we call the function that
4926 ** x points to.
4927 **
4928 ** This work-around is unlikely to work correctly on any system where
4929 ** you really cannot cast a function pointer into void*. But then, on the
4930 ** other hand, dlsym() will not work on such a system either, so we have
4931 ** not really lost anything.
4932 */
4933 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004934 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004935 x = (void(*(*)(void*,const char*))(void))dlsym;
4936 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004937}
danielk1977397d65f2008-11-19 11:35:39 +00004938static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4939 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004940 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004941}
danielk1977b4b47412007-08-17 15:53:36 +00004942#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4943 #define unixDlOpen 0
4944 #define unixDlError 0
4945 #define unixDlSym 0
4946 #define unixDlClose 0
4947#endif
4948
4949/*
danielk197790949c22007-08-17 16:50:38 +00004950** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004951*/
danielk1977397d65f2008-11-19 11:35:39 +00004952static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4953 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004954 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004955
drhbbd42a62004-05-22 17:41:58 +00004956 /* We have to initialize zBuf to prevent valgrind from reporting
4957 ** errors. The reports issued by valgrind are incorrect - we would
4958 ** prefer that the randomness be increased by making use of the
4959 ** uninitialized space in zBuf - but valgrind errors tend to worry
4960 ** some users. Rather than argue, it seems easier just to initialize
4961 ** the whole array and silence valgrind, even if that means less randomness
4962 ** in the random seed.
4963 **
4964 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004965 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004966 ** tests repeatable.
4967 */
danielk1977b4b47412007-08-17 15:53:36 +00004968 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004969#if !defined(SQLITE_TEST)
4970 {
drh842b8642005-01-21 17:53:17 +00004971 int pid, fd;
4972 fd = open("/dev/urandom", O_RDONLY);
4973 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004974 time_t t;
4975 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004976 memcpy(zBuf, &t, sizeof(t));
4977 pid = getpid();
4978 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004979 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004980 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004981 }else{
drh72cbd072008-10-14 17:58:38 +00004982 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004983 close(fd);
4984 }
drhbbd42a62004-05-22 17:41:58 +00004985 }
4986#endif
drh72cbd072008-10-14 17:58:38 +00004987 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004988}
4989
danielk1977b4b47412007-08-17 15:53:36 +00004990
drhbbd42a62004-05-22 17:41:58 +00004991/*
4992** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004993** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004994** The return value is the number of microseconds of sleep actually
4995** requested from the underlying operating system, a number which
4996** might be greater than or equal to the argument, but not less
4997** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004998*/
danielk1977397d65f2008-11-19 11:35:39 +00004999static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005000#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005001 struct timespec sp;
5002
5003 sp.tv_sec = microseconds / 1000000;
5004 sp.tv_nsec = (microseconds % 1000000) * 1000;
5005 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005006 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005007 return microseconds;
5008#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005009 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005010 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005011 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005012#else
danielk1977b4b47412007-08-17 15:53:36 +00005013 int seconds = (microseconds+999999)/1000000;
5014 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005015 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005016 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005017#endif
drh88f474a2006-01-02 20:00:12 +00005018}
5019
5020/*
drh6b9d6dd2008-12-03 19:34:47 +00005021** The following variable, if set to a non-zero value, is interpreted as
5022** the number of seconds since 1970 and is used to set the result of
5023** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005024*/
5025#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005026int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005027#endif
5028
5029/*
drhb7e8ea22010-05-03 14:32:30 +00005030** Find the current time (in Universal Coordinated Time). Write into *piNow
5031** the current time and date as a Julian Day number times 86_400_000. In
5032** other words, write into *piNow the number of milliseconds since the Julian
5033** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5034** proleptic Gregorian calendar.
5035**
5036** On success, return 0. Return 1 if the time and date cannot be found.
5037*/
5038static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5039 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5040#if defined(NO_GETTOD)
5041 time_t t;
5042 time(&t);
5043 *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
5044#elif OS_VXWORKS
5045 struct timespec sNow;
5046 clock_gettime(CLOCK_REALTIME, &sNow);
5047 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5048#else
5049 struct timeval sNow;
5050 gettimeofday(&sNow, 0);
5051 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5052#endif
5053
5054#ifdef SQLITE_TEST
5055 if( sqlite3_current_time ){
5056 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5057 }
5058#endif
5059 UNUSED_PARAMETER(NotUsed);
5060 return 0;
5061}
5062
5063/*
drhbbd42a62004-05-22 17:41:58 +00005064** Find the current time (in Universal Coordinated Time). Write the
5065** current time and date as a Julian Day number into *prNow and
5066** return 0. Return 1 if the time and date cannot be found.
5067*/
danielk1977397d65f2008-11-19 11:35:39 +00005068static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005069 sqlite3_int64 i;
5070 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005071 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005072 return 0;
5073}
danielk1977b4b47412007-08-17 15:53:36 +00005074
drh6b9d6dd2008-12-03 19:34:47 +00005075/*
5076** We added the xGetLastError() method with the intention of providing
5077** better low-level error messages when operating-system problems come up
5078** during SQLite operation. But so far, none of that has been implemented
5079** in the core. So this routine is never called. For now, it is merely
5080** a place-holder.
5081*/
danielk1977397d65f2008-11-19 11:35:39 +00005082static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5083 UNUSED_PARAMETER(NotUsed);
5084 UNUSED_PARAMETER(NotUsed2);
5085 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005086 return 0;
5087}
5088
drhf2424c52010-04-26 00:04:55 +00005089
5090/*
drh734c9862008-11-28 15:37:20 +00005091************************ End of sqlite3_vfs methods ***************************
5092******************************************************************************/
5093
drh715ff302008-12-03 22:32:44 +00005094/******************************************************************************
5095************************** Begin Proxy Locking ********************************
5096**
5097** Proxy locking is a "uber-locking-method" in this sense: It uses the
5098** other locking methods on secondary lock files. Proxy locking is a
5099** meta-layer over top of the primitive locking implemented above. For
5100** this reason, the division that implements of proxy locking is deferred
5101** until late in the file (here) after all of the other I/O methods have
5102** been defined - so that the primitive locking methods are available
5103** as services to help with the implementation of proxy locking.
5104**
5105****
5106**
5107** The default locking schemes in SQLite use byte-range locks on the
5108** database file to coordinate safe, concurrent access by multiple readers
5109** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5110** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5111** as POSIX read & write locks over fixed set of locations (via fsctl),
5112** on AFP and SMB only exclusive byte-range locks are available via fsctl
5113** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5114** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5115** address in the shared range is taken for a SHARED lock, the entire
5116** shared range is taken for an EXCLUSIVE lock):
5117**
5118** PENDING_BYTE 0x40000000
5119** RESERVED_BYTE 0x40000001
5120** SHARED_RANGE 0x40000002 -> 0x40000200
5121**
5122** This works well on the local file system, but shows a nearly 100x
5123** slowdown in read performance on AFP because the AFP client disables
5124** the read cache when byte-range locks are present. Enabling the read
5125** cache exposes a cache coherency problem that is present on all OS X
5126** supported network file systems. NFS and AFP both observe the
5127** close-to-open semantics for ensuring cache coherency
5128** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5129** address the requirements for concurrent database access by multiple
5130** readers and writers
5131** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5132**
5133** To address the performance and cache coherency issues, proxy file locking
5134** changes the way database access is controlled by limiting access to a
5135** single host at a time and moving file locks off of the database file
5136** and onto a proxy file on the local file system.
5137**
5138**
5139** Using proxy locks
5140** -----------------
5141**
5142** C APIs
5143**
5144** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5145** <proxy_path> | ":auto:");
5146** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5147**
5148**
5149** SQL pragmas
5150**
5151** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5152** PRAGMA [database.]lock_proxy_file
5153**
5154** Specifying ":auto:" means that if there is a conch file with a matching
5155** host ID in it, the proxy path in the conch file will be used, otherwise
5156** a proxy path based on the user's temp dir
5157** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5158** actual proxy file name is generated from the name and path of the
5159** database file. For example:
5160**
5161** For database path "/Users/me/foo.db"
5162** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5163**
5164** Once a lock proxy is configured for a database connection, it can not
5165** be removed, however it may be switched to a different proxy path via
5166** the above APIs (assuming the conch file is not being held by another
5167** connection or process).
5168**
5169**
5170** How proxy locking works
5171** -----------------------
5172**
5173** Proxy file locking relies primarily on two new supporting files:
5174**
5175** * conch file to limit access to the database file to a single host
5176** at a time
5177**
5178** * proxy file to act as a proxy for the advisory locks normally
5179** taken on the database
5180**
5181** The conch file - to use a proxy file, sqlite must first "hold the conch"
5182** by taking an sqlite-style shared lock on the conch file, reading the
5183** contents and comparing the host's unique host ID (see below) and lock
5184** proxy path against the values stored in the conch. The conch file is
5185** stored in the same directory as the database file and the file name
5186** is patterned after the database file name as ".<databasename>-conch".
5187** If the conch file does not exist, or it's contents do not match the
5188** host ID and/or proxy path, then the lock is escalated to an exclusive
5189** lock and the conch file contents is updated with the host ID and proxy
5190** path and the lock is downgraded to a shared lock again. If the conch
5191** is held by another process (with a shared lock), the exclusive lock
5192** will fail and SQLITE_BUSY is returned.
5193**
5194** The proxy file - a single-byte file used for all advisory file locks
5195** normally taken on the database file. This allows for safe sharing
5196** of the database file for multiple readers and writers on the same
5197** host (the conch ensures that they all use the same local lock file).
5198**
drh715ff302008-12-03 22:32:44 +00005199** Requesting the lock proxy does not immediately take the conch, it is
5200** only taken when the first request to lock database file is made.
5201** This matches the semantics of the traditional locking behavior, where
5202** opening a connection to a database file does not take a lock on it.
5203** The shared lock and an open file descriptor are maintained until
5204** the connection to the database is closed.
5205**
5206** The proxy file and the lock file are never deleted so they only need
5207** to be created the first time they are used.
5208**
5209** Configuration options
5210** ---------------------
5211**
5212** SQLITE_PREFER_PROXY_LOCKING
5213**
5214** Database files accessed on non-local file systems are
5215** automatically configured for proxy locking, lock files are
5216** named automatically using the same logic as
5217** PRAGMA lock_proxy_file=":auto:"
5218**
5219** SQLITE_PROXY_DEBUG
5220**
5221** Enables the logging of error messages during host id file
5222** retrieval and creation
5223**
drh715ff302008-12-03 22:32:44 +00005224** LOCKPROXYDIR
5225**
5226** Overrides the default directory used for lock proxy files that
5227** are named automatically via the ":auto:" setting
5228**
5229** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5230**
5231** Permissions to use when creating a directory for storing the
5232** lock proxy files, only used when LOCKPROXYDIR is not set.
5233**
5234**
5235** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5236** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5237** force proxy locking to be used for every database file opened, and 0
5238** will force automatic proxy locking to be disabled for all database
5239** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5240** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5241*/
5242
5243/*
5244** Proxy locking is only available on MacOSX
5245*/
drhd2cb50b2009-01-09 21:41:17 +00005246#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005247
drh715ff302008-12-03 22:32:44 +00005248/*
5249** The proxyLockingContext has the path and file structures for the remote
5250** and local proxy files in it
5251*/
5252typedef struct proxyLockingContext proxyLockingContext;
5253struct proxyLockingContext {
5254 unixFile *conchFile; /* Open conch file */
5255 char *conchFilePath; /* Name of the conch file */
5256 unixFile *lockProxy; /* Open proxy lock file */
5257 char *lockProxyPath; /* Name of the proxy lock file */
5258 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005259 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005260 void *oldLockingContext; /* Original lockingcontext to restore on close */
5261 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5262};
5263
drh7ed97b92010-01-20 13:07:21 +00005264/*
5265** The proxy lock file path for the database at dbPath is written into lPath,
5266** which must point to valid, writable memory large enough for a maxLen length
5267** file path.
drh715ff302008-12-03 22:32:44 +00005268*/
drh715ff302008-12-03 22:32:44 +00005269static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5270 int len;
5271 int dbLen;
5272 int i;
5273
5274#ifdef LOCKPROXYDIR
5275 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5276#else
5277# ifdef _CS_DARWIN_USER_TEMP_DIR
5278 {
drh7ed97b92010-01-20 13:07:21 +00005279 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005280 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5281 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005282 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005283 }
drh7ed97b92010-01-20 13:07:21 +00005284 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005285 }
5286# else
5287 len = strlcpy(lPath, "/tmp/", maxLen);
5288# endif
5289#endif
5290
5291 if( lPath[len-1]!='/' ){
5292 len = strlcat(lPath, "/", maxLen);
5293 }
5294
5295 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005296 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00005297 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
5298 char c = dbPath[i];
5299 lPath[i+len] = (c=='/')?'_':c;
5300 }
5301 lPath[i+len]='\0';
5302 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005303 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005304 return SQLITE_OK;
5305}
5306
drh7ed97b92010-01-20 13:07:21 +00005307/*
5308 ** Creates the lock file and any missing directories in lockPath
5309 */
5310static int proxyCreateLockPath(const char *lockPath){
5311 int i, len;
5312 char buf[MAXPATHLEN];
5313 int start = 0;
5314
5315 assert(lockPath!=NULL);
5316 /* try to create all the intermediate directories */
5317 len = (int)strlen(lockPath);
5318 buf[0] = lockPath[0];
5319 for( i=1; i<len; i++ ){
5320 if( lockPath[i] == '/' && (i - start > 0) ){
5321 /* only mkdir if leaf dir != "." or "/" or ".." */
5322 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5323 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5324 buf[i]='\0';
5325 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5326 int err=errno;
5327 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005328 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005329 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005330 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005331 return err;
5332 }
5333 }
5334 }
5335 start=i+1;
5336 }
5337 buf[i] = lockPath[i];
5338 }
drh308c2a52010-05-14 11:30:18 +00005339 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005340 return 0;
5341}
5342
drh715ff302008-12-03 22:32:44 +00005343/*
5344** Create a new VFS file descriptor (stored in memory obtained from
5345** sqlite3_malloc) and open the file named "path" in the file descriptor.
5346**
5347** The caller is responsible not only for closing the file descriptor
5348** but also for freeing the memory associated with the file descriptor.
5349*/
drh7ed97b92010-01-20 13:07:21 +00005350static int proxyCreateUnixFile(
5351 const char *path, /* path for the new unixFile */
5352 unixFile **ppFile, /* unixFile created and returned by ref */
5353 int islockfile /* if non zero missing dirs will be created */
5354) {
5355 int fd = -1;
5356 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005357 unixFile *pNew;
5358 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005359 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005360 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005361 int terrno = 0;
5362 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005363
drh7ed97b92010-01-20 13:07:21 +00005364 /* 1. first try to open/create the file
5365 ** 2. if that fails, and this is a lock file (not-conch), try creating
5366 ** the parent directories and then try again.
5367 ** 3. if that fails, try to open the file read-only
5368 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5369 */
5370 pUnused = findReusableFd(path, openFlags);
5371 if( pUnused ){
5372 fd = pUnused->fd;
5373 }else{
5374 pUnused = sqlite3_malloc(sizeof(*pUnused));
5375 if( !pUnused ){
5376 return SQLITE_NOMEM;
5377 }
5378 }
5379 if( fd<0 ){
5380 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5381 terrno = errno;
5382 if( fd<0 && errno==ENOENT && islockfile ){
5383 if( proxyCreateLockPath(path) == SQLITE_OK ){
5384 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5385 }
5386 }
5387 }
5388 if( fd<0 ){
5389 openFlags = O_RDONLY;
5390 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5391 terrno = errno;
5392 }
5393 if( fd<0 ){
5394 if( islockfile ){
5395 return SQLITE_BUSY;
5396 }
5397 switch (terrno) {
5398 case EACCES:
5399 return SQLITE_PERM;
5400 case EIO:
5401 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5402 default:
drh9978c972010-02-23 17:36:32 +00005403 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005404 }
5405 }
5406
5407 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5408 if( pNew==NULL ){
5409 rc = SQLITE_NOMEM;
5410 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005411 }
5412 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005413 pNew->openFlags = openFlags;
drh1875f7a2008-12-08 18:19:17 +00005414 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh7ed97b92010-01-20 13:07:21 +00005415 pUnused->fd = fd;
5416 pUnused->flags = openFlags;
5417 pNew->pUnused = pUnused;
5418
5419 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
5420 if( rc==SQLITE_OK ){
5421 *ppFile = pNew;
5422 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005423 }
drh7ed97b92010-01-20 13:07:21 +00005424end_create_proxy:
5425 close(fd); /* silently leak fd if error, we're already in error */
5426 sqlite3_free(pNew);
5427 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005428 return rc;
5429}
5430
drh7ed97b92010-01-20 13:07:21 +00005431#ifdef SQLITE_TEST
5432/* simulate multiple hosts by creating unique hostid file paths */
5433int sqlite3_hostid_num = 0;
5434#endif
5435
5436#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5437
5438/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5439** bytes of writable memory.
5440*/
5441static int proxyGetHostID(unsigned char *pHostID, int *pError){
5442 struct timespec timeout = {1, 0}; /* 1 sec timeout */
5443
5444 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5445 memset(pHostID, 0, PROXY_HOSTIDLEN);
5446 if( gethostuuid(pHostID, &timeout) ){
5447 int err = errno;
5448 if( pError ){
5449 *pError = err;
5450 }
5451 return SQLITE_IOERR;
5452 }
5453#ifdef SQLITE_TEST
5454 /* simulate multiple hosts by creating unique hostid file paths */
5455 if( sqlite3_hostid_num != 0){
5456 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5457 }
5458#endif
5459
5460 return SQLITE_OK;
5461}
5462
5463/* The conch file contains the header, host id and lock file path
5464 */
5465#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5466#define PROXY_HEADERLEN 1 /* conch file header length */
5467#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5468#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5469
5470/*
5471** Takes an open conch file, copies the contents to a new path and then moves
5472** it back. The newly created file's file descriptor is assigned to the
5473** conch file structure and finally the original conch file descriptor is
5474** closed. Returns zero if successful.
5475*/
5476static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5477 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5478 unixFile *conchFile = pCtx->conchFile;
5479 char tPath[MAXPATHLEN];
5480 char buf[PROXY_MAXCONCHLEN];
5481 char *cPath = pCtx->conchFilePath;
5482 size_t readLen = 0;
5483 size_t pathLen = 0;
5484 char errmsg[64] = "";
5485 int fd = -1;
5486 int rc = -1;
5487
5488 /* create a new path by replace the trailing '-conch' with '-break' */
5489 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5490 if( pathLen>MAXPATHLEN || pathLen<6 ||
5491 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
5492 sprintf(errmsg, "path error (len %d)", (int)pathLen);
5493 goto end_breaklock;
5494 }
5495 /* read the conch content */
5496 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5497 if( readLen<PROXY_PATHINDEX ){
5498 sprintf(errmsg, "read error (len %d)", (int)readLen);
5499 goto end_breaklock;
5500 }
5501 /* write it out to the temporary break file */
5502 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5503 if( fd<0 ){
5504 sprintf(errmsg, "create failed (%d)", errno);
5505 goto end_breaklock;
5506 }
5507 if( pwrite(fd, buf, readLen, 0) != readLen ){
5508 sprintf(errmsg, "write failed (%d)", errno);
5509 goto end_breaklock;
5510 }
5511 if( rename(tPath, cPath) ){
5512 sprintf(errmsg, "rename failed (%d)", errno);
5513 goto end_breaklock;
5514 }
5515 rc = 0;
5516 fprintf(stderr, "broke stale lock on %s\n", cPath);
5517 close(conchFile->h);
5518 conchFile->h = fd;
5519 conchFile->openFlags = O_RDWR | O_CREAT;
5520
5521end_breaklock:
5522 if( rc ){
5523 if( fd>=0 ){
5524 unlink(tPath);
5525 close(fd);
5526 }
5527 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5528 }
5529 return rc;
5530}
5531
5532/* Take the requested lock on the conch file and break a stale lock if the
5533** host id matches.
5534*/
5535static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5536 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5537 unixFile *conchFile = pCtx->conchFile;
5538 int rc = SQLITE_OK;
5539 int nTries = 0;
5540 struct timespec conchModTime;
5541
5542 do {
5543 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5544 nTries ++;
5545 if( rc==SQLITE_BUSY ){
5546 /* If the lock failed (busy):
5547 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5548 * 2nd try: fail if the mod time changed or host id is different, wait
5549 * 10 sec and try again
5550 * 3rd try: break the lock unless the mod time has changed.
5551 */
5552 struct stat buf;
5553 if( fstat(conchFile->h, &buf) ){
5554 pFile->lastErrno = errno;
5555 return SQLITE_IOERR_LOCK;
5556 }
5557
5558 if( nTries==1 ){
5559 conchModTime = buf.st_mtimespec;
5560 usleep(500000); /* wait 0.5 sec and try the lock again*/
5561 continue;
5562 }
5563
5564 assert( nTries>1 );
5565 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5566 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5567 return SQLITE_BUSY;
5568 }
5569
5570 if( nTries==2 ){
5571 char tBuf[PROXY_MAXCONCHLEN];
5572 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5573 if( len<0 ){
5574 pFile->lastErrno = errno;
5575 return SQLITE_IOERR_LOCK;
5576 }
5577 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5578 /* don't break the lock if the host id doesn't match */
5579 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5580 return SQLITE_BUSY;
5581 }
5582 }else{
5583 /* don't break the lock on short read or a version mismatch */
5584 return SQLITE_BUSY;
5585 }
5586 usleep(10000000); /* wait 10 sec and try the lock again */
5587 continue;
5588 }
5589
5590 assert( nTries==3 );
5591 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5592 rc = SQLITE_OK;
5593 if( lockType==EXCLUSIVE_LOCK ){
5594 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5595 }
5596 if( !rc ){
5597 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5598 }
5599 }
5600 }
5601 } while( rc==SQLITE_BUSY && nTries<3 );
5602
5603 return rc;
5604}
5605
5606/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005607** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5608** lockPath means that the lockPath in the conch file will be used if the
5609** host IDs match, or a new lock path will be generated automatically
5610** and written to the conch file.
5611*/
5612static int proxyTakeConch(unixFile *pFile){
5613 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5614
drh7ed97b92010-01-20 13:07:21 +00005615 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005616 return SQLITE_OK;
5617 }else{
5618 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005619 uuid_t myHostID;
5620 int pError = 0;
5621 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00005622 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00005623 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00005624 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005625 int createConch = 0;
5626 int hostIdMatch = 0;
5627 int readLen = 0;
5628 int tryOldLockPath = 0;
5629 int forceNewLockPath = 0;
5630
drh308c2a52010-05-14 11:30:18 +00005631 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5632 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005633
drh7ed97b92010-01-20 13:07:21 +00005634 rc = proxyGetHostID(myHostID, &pError);
5635 if( (rc&0xff)==SQLITE_IOERR ){
5636 pFile->lastErrno = pError;
5637 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005638 }
drh7ed97b92010-01-20 13:07:21 +00005639 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00005640 if( rc!=SQLITE_OK ){
5641 goto end_takeconch;
5642 }
drh7ed97b92010-01-20 13:07:21 +00005643 /* read the existing conch file */
5644 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
5645 if( readLen<0 ){
5646 /* I/O error: lastErrno set by seekAndRead */
5647 pFile->lastErrno = conchFile->lastErrno;
5648 rc = SQLITE_IOERR_READ;
5649 goto end_takeconch;
5650 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5651 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5652 /* a short read or version format mismatch means we need to create a new
5653 ** conch file.
5654 */
5655 createConch = 1;
5656 }
5657 /* if the host id matches and the lock path already exists in the conch
5658 ** we'll try to use the path there, if we can't open that path, we'll
5659 ** retry with a new auto-generated path
5660 */
5661 do { /* in case we need to try again for an :auto: named lock file */
5662
5663 if( !createConch && !forceNewLockPath ){
5664 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5665 PROXY_HOSTIDLEN);
5666 /* if the conch has data compare the contents */
5667 if( !pCtx->lockProxyPath ){
5668 /* for auto-named local lock file, just check the host ID and we'll
5669 ** use the local lock file path that's already in there
5670 */
5671 if( hostIdMatch ){
5672 size_t pathLen = (readLen - PROXY_PATHINDEX);
5673
5674 if( pathLen>=MAXPATHLEN ){
5675 pathLen=MAXPATHLEN-1;
5676 }
5677 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5678 lockPath[pathLen] = 0;
5679 tempLockPath = lockPath;
5680 tryOldLockPath = 1;
5681 /* create a copy of the lock path if the conch is taken */
5682 goto end_takeconch;
5683 }
5684 }else if( hostIdMatch
5685 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5686 readLen-PROXY_PATHINDEX)
5687 ){
5688 /* conch host and lock path match */
5689 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00005690 }
drh7ed97b92010-01-20 13:07:21 +00005691 }
5692
5693 /* if the conch isn't writable and doesn't match, we can't take it */
5694 if( (conchFile->openFlags&O_RDWR) == 0 ){
5695 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00005696 goto end_takeconch;
5697 }
drh7ed97b92010-01-20 13:07:21 +00005698
5699 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00005700 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00005701 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
5702 tempLockPath = lockPath;
5703 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00005704 }
drh7ed97b92010-01-20 13:07:21 +00005705
5706 /* update conch with host and path (this will fail if other process
5707 ** has a shared lock already), if the host id matches, use the big
5708 ** stick.
drh715ff302008-12-03 22:32:44 +00005709 */
drh7ed97b92010-01-20 13:07:21 +00005710 futimes(conchFile->h, NULL);
5711 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00005712 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00005713 /* We are trying for an exclusive lock but another thread in this
5714 ** same process is still holding a shared lock. */
5715 rc = SQLITE_BUSY;
5716 } else {
5717 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005718 }
drh715ff302008-12-03 22:32:44 +00005719 }else{
drh7ed97b92010-01-20 13:07:21 +00005720 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00005721 }
drh7ed97b92010-01-20 13:07:21 +00005722 if( rc==SQLITE_OK ){
5723 char writeBuffer[PROXY_MAXCONCHLEN];
5724 int writeSize = 0;
5725
5726 writeBuffer[0] = (char)PROXY_CONCHVERSION;
5727 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
5728 if( pCtx->lockProxyPath!=NULL ){
5729 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
5730 }else{
5731 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
5732 }
5733 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
5734 ftruncate(conchFile->h, writeSize);
5735 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
5736 fsync(conchFile->h);
5737 /* If we created a new conch file (not just updated the contents of a
5738 ** valid conch file), try to match the permissions of the database
5739 */
5740 if( rc==SQLITE_OK && createConch ){
5741 struct stat buf;
5742 int err = fstat(pFile->h, &buf);
5743 if( err==0 ){
5744 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
5745 S_IROTH|S_IWOTH);
5746 /* try to match the database file R/W permissions, ignore failure */
5747#ifndef SQLITE_PROXY_DEBUG
5748 fchmod(conchFile->h, cmode);
5749#else
5750 if( fchmod(conchFile->h, cmode)!=0 ){
5751 int code = errno;
5752 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5753 cmode, code, strerror(code));
5754 } else {
5755 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5756 }
5757 }else{
5758 int code = errno;
5759 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
5760 err, code, strerror(code));
5761#endif
5762 }
drh715ff302008-12-03 22:32:44 +00005763 }
5764 }
drh7ed97b92010-01-20 13:07:21 +00005765 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5766
5767 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00005768 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00005769 if( rc==SQLITE_OK && pFile->openFlags ){
5770 if( pFile->h>=0 ){
5771#ifdef STRICT_CLOSE_ERROR
5772 if( close(pFile->h) ){
5773 pFile->lastErrno = errno;
5774 return SQLITE_IOERR_CLOSE;
5775 }
5776#else
5777 close(pFile->h); /* silently leak fd if fail */
5778#endif
5779 }
5780 pFile->h = -1;
5781 int fd = open(pCtx->dbPath, pFile->openFlags,
5782 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00005783 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00005784 if( fd>=0 ){
5785 pFile->h = fd;
5786 }else{
drh9978c972010-02-23 17:36:32 +00005787 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00005788 during locking */
5789 }
5790 }
5791 if( rc==SQLITE_OK && !pCtx->lockProxy ){
5792 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
5793 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
5794 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
5795 /* we couldn't create the proxy lock file with the old lock file path
5796 ** so try again via auto-naming
5797 */
5798 forceNewLockPath = 1;
5799 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00005800 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00005801 }
5802 }
5803 if( rc==SQLITE_OK ){
5804 /* Need to make a copy of path if we extracted the value
5805 ** from the conch file or the path was allocated on the stack
5806 */
5807 if( tempLockPath ){
5808 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
5809 if( !pCtx->lockProxyPath ){
5810 rc = SQLITE_NOMEM;
5811 }
5812 }
5813 }
5814 if( rc==SQLITE_OK ){
5815 pCtx->conchHeld = 1;
5816
5817 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
5818 afpLockingContext *afpCtx;
5819 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
5820 afpCtx->dbPath = pCtx->lockProxyPath;
5821 }
5822 } else {
5823 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5824 }
drh308c2a52010-05-14 11:30:18 +00005825 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
5826 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00005827 return rc;
drh308c2a52010-05-14 11:30:18 +00005828 } while (1); /* in case we need to retry the :auto: lock file -
5829 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00005830 }
5831}
5832
5833/*
5834** If pFile holds a lock on a conch file, then release that lock.
5835*/
5836static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00005837 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00005838 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
5839 unixFile *conchFile; /* Name of the conch file */
5840
5841 pCtx = (proxyLockingContext *)pFile->lockingContext;
5842 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00005843 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00005844 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00005845 getpid()));
drh7ed97b92010-01-20 13:07:21 +00005846 if( pCtx->conchHeld>0 ){
5847 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5848 }
drh715ff302008-12-03 22:32:44 +00005849 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00005850 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
5851 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00005852 return rc;
5853}
5854
5855/*
5856** Given the name of a database file, compute the name of its conch file.
5857** Store the conch filename in memory obtained from sqlite3_malloc().
5858** Make *pConchPath point to the new name. Return SQLITE_OK on success
5859** or SQLITE_NOMEM if unable to obtain memory.
5860**
5861** The caller is responsible for ensuring that the allocated memory
5862** space is eventually freed.
5863**
5864** *pConchPath is set to NULL if a memory allocation error occurs.
5865*/
5866static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
5867 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00005868 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00005869 char *conchPath; /* buffer in which to construct conch name */
5870
5871 /* Allocate space for the conch filename and initialize the name to
5872 ** the name of the original database file. */
5873 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
5874 if( conchPath==0 ){
5875 return SQLITE_NOMEM;
5876 }
5877 memcpy(conchPath, dbPath, len+1);
5878
5879 /* now insert a "." before the last / character */
5880 for( i=(len-1); i>=0; i-- ){
5881 if( conchPath[i]=='/' ){
5882 i++;
5883 break;
5884 }
5885 }
5886 conchPath[i]='.';
5887 while ( i<len ){
5888 conchPath[i+1]=dbPath[i];
5889 i++;
5890 }
5891
5892 /* append the "-conch" suffix to the file */
5893 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00005894 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00005895
5896 return SQLITE_OK;
5897}
5898
5899
5900/* Takes a fully configured proxy locking-style unix file and switches
5901** the local lock file path
5902*/
5903static int switchLockProxyPath(unixFile *pFile, const char *path) {
5904 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5905 char *oldPath = pCtx->lockProxyPath;
5906 int rc = SQLITE_OK;
5907
drh308c2a52010-05-14 11:30:18 +00005908 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005909 return SQLITE_BUSY;
5910 }
5911
5912 /* nothing to do if the path is NULL, :auto: or matches the existing path */
5913 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
5914 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
5915 return SQLITE_OK;
5916 }else{
5917 unixFile *lockProxy = pCtx->lockProxy;
5918 pCtx->lockProxy=NULL;
5919 pCtx->conchHeld = 0;
5920 if( lockProxy!=NULL ){
5921 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
5922 if( rc ) return rc;
5923 sqlite3_free(lockProxy);
5924 }
5925 sqlite3_free(oldPath);
5926 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
5927 }
5928
5929 return rc;
5930}
5931
5932/*
5933** pFile is a file that has been opened by a prior xOpen call. dbPath
5934** is a string buffer at least MAXPATHLEN+1 characters in size.
5935**
5936** This routine find the filename associated with pFile and writes it
5937** int dbPath.
5938*/
5939static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00005940#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00005941 if( pFile->pMethod == &afpIoMethods ){
5942 /* afp style keeps a reference to the db path in the filePath field
5943 ** of the struct */
drhea678832008-12-10 19:26:22 +00005944 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005945 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
5946 } else
drh715ff302008-12-03 22:32:44 +00005947#endif
5948 if( pFile->pMethod == &dotlockIoMethods ){
5949 /* dot lock style uses the locking context to store the dot lock
5950 ** file path */
5951 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5952 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5953 }else{
5954 /* all other styles use the locking context to store the db file path */
5955 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00005956 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00005957 }
5958 return SQLITE_OK;
5959}
5960
5961/*
5962** Takes an already filled in unix file and alters it so all file locking
5963** will be performed on the local proxy lock file. The following fields
5964** are preserved in the locking context so that they can be restored and
5965** the unix structure properly cleaned up at close time:
5966** ->lockingContext
5967** ->pMethod
5968*/
5969static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
5970 proxyLockingContext *pCtx;
5971 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
5972 char *lockPath=NULL;
5973 int rc = SQLITE_OK;
5974
drh308c2a52010-05-14 11:30:18 +00005975 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00005976 return SQLITE_BUSY;
5977 }
5978 proxyGetDbPathForUnixFile(pFile, dbPath);
5979 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
5980 lockPath=NULL;
5981 }else{
5982 lockPath=(char *)path;
5983 }
5984
drh308c2a52010-05-14 11:30:18 +00005985 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
5986 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00005987
5988 pCtx = sqlite3_malloc( sizeof(*pCtx) );
5989 if( pCtx==0 ){
5990 return SQLITE_NOMEM;
5991 }
5992 memset(pCtx, 0, sizeof(*pCtx));
5993
5994 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
5995 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00005996 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
5997 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
5998 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
5999 ** (c) the file system is read-only, then enable no-locking access.
6000 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6001 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6002 */
6003 struct statfs fsInfo;
6004 struct stat conchInfo;
6005 int goLockless = 0;
6006
6007 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
6008 int err = errno;
6009 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6010 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6011 }
6012 }
6013 if( goLockless ){
6014 pCtx->conchHeld = -1; /* read only FS/ lockless */
6015 rc = SQLITE_OK;
6016 }
6017 }
drh715ff302008-12-03 22:32:44 +00006018 }
6019 if( rc==SQLITE_OK && lockPath ){
6020 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6021 }
6022
6023 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006024 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6025 if( pCtx->dbPath==NULL ){
6026 rc = SQLITE_NOMEM;
6027 }
6028 }
6029 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006030 /* all memory is allocated, proxys are created and assigned,
6031 ** switch the locking context and pMethod then return.
6032 */
drh715ff302008-12-03 22:32:44 +00006033 pCtx->oldLockingContext = pFile->lockingContext;
6034 pFile->lockingContext = pCtx;
6035 pCtx->pOldMethod = pFile->pMethod;
6036 pFile->pMethod = &proxyIoMethods;
6037 }else{
6038 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006039 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006040 sqlite3_free(pCtx->conchFile);
6041 }
drh7ed97b92010-01-20 13:07:21 +00006042 sqlite3_free(pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006043 sqlite3_free(pCtx->conchFilePath);
6044 sqlite3_free(pCtx);
6045 }
drh308c2a52010-05-14 11:30:18 +00006046 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6047 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006048 return rc;
6049}
6050
6051
6052/*
6053** This routine handles sqlite3_file_control() calls that are specific
6054** to proxy locking.
6055*/
6056static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6057 switch( op ){
6058 case SQLITE_GET_LOCKPROXYFILE: {
6059 unixFile *pFile = (unixFile*)id;
6060 if( pFile->pMethod == &proxyIoMethods ){
6061 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6062 proxyTakeConch(pFile);
6063 if( pCtx->lockProxyPath ){
6064 *(const char **)pArg = pCtx->lockProxyPath;
6065 }else{
6066 *(const char **)pArg = ":auto: (not held)";
6067 }
6068 } else {
6069 *(const char **)pArg = NULL;
6070 }
6071 return SQLITE_OK;
6072 }
6073 case SQLITE_SET_LOCKPROXYFILE: {
6074 unixFile *pFile = (unixFile*)id;
6075 int rc = SQLITE_OK;
6076 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6077 if( pArg==NULL || (const char *)pArg==0 ){
6078 if( isProxyStyle ){
6079 /* turn off proxy locking - not supported */
6080 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6081 }else{
6082 /* turn off proxy locking - already off - NOOP */
6083 rc = SQLITE_OK;
6084 }
6085 }else{
6086 const char *proxyPath = (const char *)pArg;
6087 if( isProxyStyle ){
6088 proxyLockingContext *pCtx =
6089 (proxyLockingContext*)pFile->lockingContext;
6090 if( !strcmp(pArg, ":auto:")
6091 || (pCtx->lockProxyPath &&
6092 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6093 ){
6094 rc = SQLITE_OK;
6095 }else{
6096 rc = switchLockProxyPath(pFile, proxyPath);
6097 }
6098 }else{
6099 /* turn on proxy file locking */
6100 rc = proxyTransformUnixFile(pFile, proxyPath);
6101 }
6102 }
6103 return rc;
6104 }
6105 default: {
6106 assert( 0 ); /* The call assures that only valid opcodes are sent */
6107 }
6108 }
6109 /*NOTREACHED*/
6110 return SQLITE_ERROR;
6111}
6112
6113/*
6114** Within this division (the proxying locking implementation) the procedures
6115** above this point are all utilities. The lock-related methods of the
6116** proxy-locking sqlite3_io_method object follow.
6117*/
6118
6119
6120/*
6121** This routine checks if there is a RESERVED lock held on the specified
6122** file by this or any other process. If such a lock is held, set *pResOut
6123** to a non-zero value otherwise *pResOut is set to zero. The return value
6124** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6125*/
6126static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6127 unixFile *pFile = (unixFile*)id;
6128 int rc = proxyTakeConch(pFile);
6129 if( rc==SQLITE_OK ){
6130 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006131 if( pCtx->conchHeld>0 ){
6132 unixFile *proxy = pCtx->lockProxy;
6133 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6134 }else{ /* conchHeld < 0 is lockless */
6135 pResOut=0;
6136 }
drh715ff302008-12-03 22:32:44 +00006137 }
6138 return rc;
6139}
6140
6141/*
drh308c2a52010-05-14 11:30:18 +00006142** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006143** of the following:
6144**
6145** (1) SHARED_LOCK
6146** (2) RESERVED_LOCK
6147** (3) PENDING_LOCK
6148** (4) EXCLUSIVE_LOCK
6149**
6150** Sometimes when requesting one lock state, additional lock states
6151** are inserted in between. The locking might fail on one of the later
6152** transitions leaving the lock state different from what it started but
6153** still short of its goal. The following chart shows the allowed
6154** transitions and the inserted intermediate states:
6155**
6156** UNLOCKED -> SHARED
6157** SHARED -> RESERVED
6158** SHARED -> (PENDING) -> EXCLUSIVE
6159** RESERVED -> (PENDING) -> EXCLUSIVE
6160** PENDING -> EXCLUSIVE
6161**
6162** This routine will only increase a lock. Use the sqlite3OsUnlock()
6163** routine to lower a locking level.
6164*/
drh308c2a52010-05-14 11:30:18 +00006165static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006166 unixFile *pFile = (unixFile*)id;
6167 int rc = proxyTakeConch(pFile);
6168 if( rc==SQLITE_OK ){
6169 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006170 if( pCtx->conchHeld>0 ){
6171 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006172 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6173 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006174 }else{
6175 /* conchHeld < 0 is lockless */
6176 }
drh715ff302008-12-03 22:32:44 +00006177 }
6178 return rc;
6179}
6180
6181
6182/*
drh308c2a52010-05-14 11:30:18 +00006183** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006184** must be either NO_LOCK or SHARED_LOCK.
6185**
6186** If the locking level of the file descriptor is already at or below
6187** the requested locking level, this routine is a no-op.
6188*/
drh308c2a52010-05-14 11:30:18 +00006189static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006190 unixFile *pFile = (unixFile*)id;
6191 int rc = proxyTakeConch(pFile);
6192 if( rc==SQLITE_OK ){
6193 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006194 if( pCtx->conchHeld>0 ){
6195 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006196 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6197 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006198 }else{
6199 /* conchHeld < 0 is lockless */
6200 }
drh715ff302008-12-03 22:32:44 +00006201 }
6202 return rc;
6203}
6204
6205/*
6206** Close a file that uses proxy locks.
6207*/
6208static int proxyClose(sqlite3_file *id) {
6209 if( id ){
6210 unixFile *pFile = (unixFile*)id;
6211 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6212 unixFile *lockProxy = pCtx->lockProxy;
6213 unixFile *conchFile = pCtx->conchFile;
6214 int rc = SQLITE_OK;
6215
6216 if( lockProxy ){
6217 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6218 if( rc ) return rc;
6219 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6220 if( rc ) return rc;
6221 sqlite3_free(lockProxy);
6222 pCtx->lockProxy = 0;
6223 }
6224 if( conchFile ){
6225 if( pCtx->conchHeld ){
6226 rc = proxyReleaseConch(pFile);
6227 if( rc ) return rc;
6228 }
6229 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6230 if( rc ) return rc;
6231 sqlite3_free(conchFile);
6232 }
6233 sqlite3_free(pCtx->lockProxyPath);
6234 sqlite3_free(pCtx->conchFilePath);
6235 sqlite3_free(pCtx->dbPath);
6236 /* restore the original locking context and pMethod then close it */
6237 pFile->lockingContext = pCtx->oldLockingContext;
6238 pFile->pMethod = pCtx->pOldMethod;
6239 sqlite3_free(pCtx);
6240 return pFile->pMethod->xClose(id);
6241 }
6242 return SQLITE_OK;
6243}
6244
6245
6246
drhd2cb50b2009-01-09 21:41:17 +00006247#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006248/*
6249** The proxy locking style is intended for use with AFP filesystems.
6250** And since AFP is only supported on MacOSX, the proxy locking is also
6251** restricted to MacOSX.
6252**
6253**
6254******************* End of the proxy lock implementation **********************
6255******************************************************************************/
6256
drh734c9862008-11-28 15:37:20 +00006257/*
danielk1977e339d652008-06-28 11:23:00 +00006258** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006259**
6260** This routine registers all VFS implementations for unix-like operating
6261** systems. This routine, and the sqlite3_os_end() routine that follows,
6262** should be the only routines in this file that are visible from other
6263** files.
drh6b9d6dd2008-12-03 19:34:47 +00006264**
6265** This routine is called once during SQLite initialization and by a
6266** single thread. The memory allocation and mutex subsystems have not
6267** necessarily been initialized when this routine is called, and so they
6268** should not be used.
drh153c62c2007-08-24 03:51:33 +00006269*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006270int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006271 /*
6272 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006273 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6274 ** to the "finder" function. (pAppData is a pointer to a pointer because
6275 ** silly C90 rules prohibit a void* from being cast to a function pointer
6276 ** and so we have to go through the intermediate pointer to avoid problems
6277 ** when compiling with -pedantic-errors on GCC.)
6278 **
6279 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006280 ** finder-function. The finder-function returns a pointer to the
6281 ** sqlite_io_methods object that implements the desired locking
6282 ** behaviors. See the division above that contains the IOMETHODS
6283 ** macro for addition information on finder-functions.
6284 **
6285 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6286 ** object. But the "autolockIoFinder" available on MacOSX does a little
6287 ** more than that; it looks at the filesystem type that hosts the
6288 ** database file and tries to choose an locking method appropriate for
6289 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006290 */
drh7708e972008-11-29 00:56:52 +00006291 #define UNIXVFS(VFSNAME, FINDER) { \
drhf2424c52010-04-26 00:04:55 +00006292 2, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006293 sizeof(unixFile), /* szOsFile */ \
6294 MAX_PATHNAME, /* mxPathname */ \
6295 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006296 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006297 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006298 unixOpen, /* xOpen */ \
6299 unixDelete, /* xDelete */ \
6300 unixAccess, /* xAccess */ \
6301 unixFullPathname, /* xFullPathname */ \
6302 unixDlOpen, /* xDlOpen */ \
6303 unixDlError, /* xDlError */ \
6304 unixDlSym, /* xDlSym */ \
6305 unixDlClose, /* xDlClose */ \
6306 unixRandomness, /* xRandomness */ \
6307 unixSleep, /* xSleep */ \
6308 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006309 unixGetLastError, /* xGetLastError */ \
drhf2424c52010-04-26 00:04:55 +00006310 0, /* xRename */ \
drhb7e8ea22010-05-03 14:32:30 +00006311 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
danielk1977e339d652008-06-28 11:23:00 +00006312 }
6313
drh6b9d6dd2008-12-03 19:34:47 +00006314 /*
6315 ** All default VFSes for unix are contained in the following array.
6316 **
6317 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6318 ** by the SQLite core when the VFS is registered. So the following
6319 ** array cannot be const.
6320 */
danielk1977e339d652008-06-28 11:23:00 +00006321 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006322#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006323 UNIXVFS("unix", autolockIoFinder ),
6324#else
6325 UNIXVFS("unix", posixIoFinder ),
6326#endif
6327 UNIXVFS("unix-none", nolockIoFinder ),
6328 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006329#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006330 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006331#endif
6332#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006333 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006334#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006335 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006336#endif
chw78a13182009-04-07 05:35:03 +00006337#endif
drhd2cb50b2009-01-09 21:41:17 +00006338#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006339 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006340 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006341 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006342#endif
drh153c62c2007-08-24 03:51:33 +00006343 };
drh6b9d6dd2008-12-03 19:34:47 +00006344 unsigned int i; /* Loop counter */
6345
6346 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006347 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006348 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006349 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006350 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006351}
danielk1977e339d652008-06-28 11:23:00 +00006352
6353/*
drh6b9d6dd2008-12-03 19:34:47 +00006354** Shutdown the operating system interface.
6355**
6356** Some operating systems might need to do some cleanup in this routine,
6357** to release dynamically allocated objects. But not on unix.
6358** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006359*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006360int sqlite3_os_end(void){
6361 return SQLITE_OK;
6362}
drhdce8bdb2007-08-16 13:01:44 +00006363
danielk197729bafea2008-06-26 10:41:19 +00006364#endif /* SQLITE_OS_UNIX */