blob: a45aaa1d73be2953534e531bbe3fe0d586364c02 [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>
danielk1977e339d652008-06-28 11:23:00 +0000122
drh40bbb0a2008-09-23 10:23:26 +0000123#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000124# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000125# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000126# include <semaphore.h>
127# include <limits.h>
128# else
drh9b35ea62008-11-29 02:20:26 +0000129# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <sys/param.h>
131# include <sys/mount.h>
132# endif
drhbfe66312006-10-03 17:40:40 +0000133#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000134
135/*
drhf1a221e2006-01-15 17:27:17 +0000136** If we are to be thread-safe, include the pthreads header and define
137** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000138*/
drhd677b3d2007-08-20 22:48:41 +0000139#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000140# include <pthread.h>
141# define SQLITE_UNIX_THREADS 1
142#endif
143
144/*
145** Default permissions when creating a new file
146*/
147#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
148# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
149#endif
150
danielk1977b4b47412007-08-17 15:53:36 +0000151/*
aswiftaebf4132008-11-21 00:10:35 +0000152 ** Default permissions when creating auto proxy dir
153 */
154#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
155# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
156#endif
157
158/*
danielk1977b4b47412007-08-17 15:53:36 +0000159** Maximum supported path-length.
160*/
161#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000162
drh734c9862008-11-28 15:37:20 +0000163/*
drh734c9862008-11-28 15:37:20 +0000164** Only set the lastErrno if the error code is a real error and not
165** a normal expected return code of SQLITE_BUSY or SQLITE_OK
166*/
167#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
168
drh9cbe6352005-11-29 03:13:21 +0000169
170/*
dane946c392009-08-22 11:39:46 +0000171** Sometimes, after a file handle is closed by SQLite, the file descriptor
172** cannot be closed immediately. In these cases, instances of the following
173** structure are used to store the file descriptor while waiting for an
174** opportunity to either close or reuse it.
175*/
176typedef struct UnixUnusedFd UnixUnusedFd;
177struct UnixUnusedFd {
178 int fd; /* File descriptor to close */
179 int flags; /* Flags this file descriptor was opened with */
180 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
181};
182
183/*
drh9b35ea62008-11-29 02:20:26 +0000184** The unixFile structure is subclass of sqlite3_file specific to the unix
185** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000186*/
drh054889e2005-11-30 03:20:31 +0000187typedef struct unixFile unixFile;
188struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000189 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh6c7d5c52008-11-21 20:32:33 +0000190 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
191 struct unixLockInfo *pLock; /* Info about locks on this inode */
192 int h; /* The file descriptor */
193 int dirfd; /* File descriptor for the directory */
194 unsigned char locktype; /* The type of lock held on this fd */
195 int lastErrno; /* The unix errno from the last I/O error */
drh6c7d5c52008-11-21 20:32:33 +0000196 void *lockingContext; /* Locking style specific state */
dane946c392009-08-22 11:39:46 +0000197 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh0c2694b2009-09-03 16:23:44 +0000198 int fileFlags; /* Miscellanous flags */
drh08c6d442009-02-09 17:34:07 +0000199#if SQLITE_ENABLE_LOCKING_STYLE
200 int openFlags; /* The flags specified at open() */
201#endif
drh734c9862008-11-28 15:37:20 +0000202#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000203 pthread_t tid; /* The thread that "owns" this unixFile */
204#endif
205#if OS_VXWORKS
206 int isDelete; /* Delete on close if true */
drh107886a2008-11-21 22:21:50 +0000207 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000208#endif
drh8f941bc2009-01-14 23:03:40 +0000209#ifndef NDEBUG
210 /* The next group of variables are used to track whether or not the
211 ** transaction counter in bytes 24-27 of database files are updated
212 ** whenever any part of the database changes. An assertion fault will
213 ** occur if a file is updated without also updating the transaction
214 ** counter. This test is made to avoid new problems similar to the
215 ** one described by ticket #3584.
216 */
217 unsigned char transCntrChng; /* True if the transaction counter changed */
218 unsigned char dbUpdate; /* True if any part of database file changed */
219 unsigned char inNormalWrite; /* True if in a normal write operation */
220#endif
danielk1977967a4a12007-08-20 14:23:44 +0000221#ifdef SQLITE_TEST
222 /* In test mode, increase the size of this structure a bit so that
223 ** it is larger than the struct CrashFile defined in test6.c.
224 */
225 char aPadding[32];
226#endif
drh9cbe6352005-11-29 03:13:21 +0000227};
228
drh0ccebe72005-06-07 22:22:50 +0000229/*
drh0c2694b2009-09-03 16:23:44 +0000230** The following macros define bits in unixFile.fileFlags
231*/
232#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
233
234/*
drh198bf392006-01-06 21:52:49 +0000235** Include code that is common to all os_*.c files
236*/
237#include "os_common.h"
238
239/*
drh0ccebe72005-06-07 22:22:50 +0000240** Define various macros that are missing from some systems.
241*/
drhbbd42a62004-05-22 17:41:58 +0000242#ifndef O_LARGEFILE
243# define O_LARGEFILE 0
244#endif
245#ifdef SQLITE_DISABLE_LFS
246# undef O_LARGEFILE
247# define O_LARGEFILE 0
248#endif
249#ifndef O_NOFOLLOW
250# define O_NOFOLLOW 0
251#endif
252#ifndef O_BINARY
253# define O_BINARY 0
254#endif
255
256/*
257** The DJGPP compiler environment looks mostly like Unix, but it
258** lacks the fcntl() system call. So redefine fcntl() to be something
259** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000260** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000261*/
262#ifdef __DJGPP__
263# define fcntl(A,B,C) 0
264#endif
265
266/*
drh2b4b5962005-06-15 17:47:55 +0000267** The threadid macro resolves to the thread-id or to 0. Used for
268** testing and debugging only.
269*/
drhd677b3d2007-08-20 22:48:41 +0000270#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000271#define threadid pthread_self()
272#else
273#define threadid 0
274#endif
275
danielk197713adf8a2004-06-03 16:08:41 +0000276
drh107886a2008-11-21 22:21:50 +0000277/*
dan9359c7b2009-08-21 08:29:10 +0000278** Helper functions to obtain and relinquish the global mutex. The
279** global mutex is used to protect the unixOpenCnt, unixLockInfo and
280** vxworksFileId objects used by this file, all of which may be
281** shared by multiple threads.
282**
283** Function unixMutexHeld() is used to assert() that the global mutex
284** is held when required. This function is only used as part of assert()
285** statements. e.g.
286**
287** unixEnterMutex()
288** assert( unixMutexHeld() );
289** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000290*/
291static void unixEnterMutex(void){
292 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
293}
294static void unixLeaveMutex(void){
295 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
296}
dan9359c7b2009-08-21 08:29:10 +0000297#ifdef SQLITE_DEBUG
298static int unixMutexHeld(void) {
299 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
300}
301#endif
drh107886a2008-11-21 22:21:50 +0000302
drh734c9862008-11-28 15:37:20 +0000303
304#ifdef SQLITE_DEBUG
305/*
306** Helper function for printing out trace information from debugging
307** binaries. This returns the string represetation of the supplied
308** integer lock-type.
309*/
310static const char *locktypeName(int locktype){
311 switch( locktype ){
dan9359c7b2009-08-21 08:29:10 +0000312 case NO_LOCK: return "NONE";
313 case SHARED_LOCK: return "SHARED";
314 case RESERVED_LOCK: return "RESERVED";
315 case PENDING_LOCK: return "PENDING";
316 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000317 }
318 return "ERROR";
319}
320#endif
321
322#ifdef SQLITE_LOCK_TRACE
323/*
324** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000325**
drh734c9862008-11-28 15:37:20 +0000326** This routine is used for troubleshooting locks on multithreaded
327** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
328** command-line option on the compiler. This code is normally
329** turned off.
330*/
331static int lockTrace(int fd, int op, struct flock *p){
332 char *zOpName, *zType;
333 int s;
334 int savedErrno;
335 if( op==F_GETLK ){
336 zOpName = "GETLK";
337 }else if( op==F_SETLK ){
338 zOpName = "SETLK";
339 }else{
340 s = fcntl(fd, op, p);
341 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
342 return s;
343 }
344 if( p->l_type==F_RDLCK ){
345 zType = "RDLCK";
346 }else if( p->l_type==F_WRLCK ){
347 zType = "WRLCK";
348 }else if( p->l_type==F_UNLCK ){
349 zType = "UNLCK";
350 }else{
351 assert( 0 );
352 }
353 assert( p->l_whence==SEEK_SET );
354 s = fcntl(fd, op, p);
355 savedErrno = errno;
356 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
357 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
358 (int)p->l_pid, s);
359 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
360 struct flock l2;
361 l2 = *p;
362 fcntl(fd, F_GETLK, &l2);
363 if( l2.l_type==F_RDLCK ){
364 zType = "RDLCK";
365 }else if( l2.l_type==F_WRLCK ){
366 zType = "WRLCK";
367 }else if( l2.l_type==F_UNLCK ){
368 zType = "UNLCK";
369 }else{
370 assert( 0 );
371 }
372 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
373 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
374 }
375 errno = savedErrno;
376 return s;
377}
378#define fcntl lockTrace
379#endif /* SQLITE_LOCK_TRACE */
380
381
382
383/*
384** This routine translates a standard POSIX errno code into something
385** useful to the clients of the sqlite3 functions. Specifically, it is
386** intended to translate a variety of "try again" errors into SQLITE_BUSY
387** and a variety of "please close the file descriptor NOW" errors into
388** SQLITE_IOERR
389**
390** Errors during initialization of locks, or file system support for locks,
391** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
392*/
393static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
394 switch (posixError) {
395 case 0:
396 return SQLITE_OK;
397
398 case EAGAIN:
399 case ETIMEDOUT:
400 case EBUSY:
401 case EINTR:
402 case ENOLCK:
403 /* random NFS retry error, unless during file system support
404 * introspection, in which it actually means what it says */
405 return SQLITE_BUSY;
406
407 case EACCES:
408 /* EACCES is like EAGAIN during locking operations, but not any other time*/
409 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
410 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
411 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
412 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
413 return SQLITE_BUSY;
414 }
415 /* else fall through */
416 case EPERM:
417 return SQLITE_PERM;
418
419 case EDEADLK:
420 return SQLITE_IOERR_BLOCKED;
421
422#if EOPNOTSUPP!=ENOTSUP
423 case EOPNOTSUPP:
424 /* something went terribly awry, unless during file system support
425 * introspection, in which it actually means what it says */
426#endif
427#ifdef ENOTSUP
428 case ENOTSUP:
429 /* invalid fd, unless during file system support introspection, in which
430 * it actually means what it says */
431#endif
432 case EIO:
433 case EBADF:
434 case EINVAL:
435 case ENOTCONN:
436 case ENODEV:
437 case ENXIO:
438 case ENOENT:
439 case ESTALE:
440 case ENOSYS:
441 /* these should force the client to close the file and reconnect */
442
443 default:
444 return sqliteIOErr;
445 }
446}
447
448
449
450/******************************************************************************
451****************** Begin Unique File ID Utility Used By VxWorks ***************
452**
453** On most versions of unix, we can get a unique ID for a file by concatenating
454** the device number and the inode number. But this does not work on VxWorks.
455** On VxWorks, a unique file id must be based on the canonical filename.
456**
457** A pointer to an instance of the following structure can be used as a
458** unique file ID in VxWorks. Each instance of this structure contains
459** a copy of the canonical filename. There is also a reference count.
460** The structure is reclaimed when the number of pointers to it drops to
461** zero.
462**
463** There are never very many files open at one time and lookups are not
464** a performance-critical path, so it is sufficient to put these
465** structures on a linked list.
466*/
467struct vxworksFileId {
468 struct vxworksFileId *pNext; /* Next in a list of them all */
469 int nRef; /* Number of references to this one */
470 int nName; /* Length of the zCanonicalName[] string */
471 char *zCanonicalName; /* Canonical filename */
472};
473
474#if OS_VXWORKS
475/*
drh9b35ea62008-11-29 02:20:26 +0000476** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000477** variable:
478*/
479static struct vxworksFileId *vxworksFileList = 0;
480
481/*
482** Simplify a filename into its canonical form
483** by making the following changes:
484**
485** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000486** * convert /./ into just /
487** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000488**
489** Changes are made in-place. Return the new name length.
490**
491** The original filename is in z[0..n-1]. Return the number of
492** characters in the simplified name.
493*/
494static int vxworksSimplifyName(char *z, int n){
495 int i, j;
496 while( n>1 && z[n-1]=='/' ){ n--; }
497 for(i=j=0; i<n; i++){
498 if( z[i]=='/' ){
499 if( z[i+1]=='/' ) continue;
500 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
501 i += 1;
502 continue;
503 }
504 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
505 while( j>0 && z[j-1]!='/' ){ j--; }
506 if( j>0 ){ j--; }
507 i += 2;
508 continue;
509 }
510 }
511 z[j++] = z[i];
512 }
513 z[j] = 0;
514 return j;
515}
516
517/*
518** Find a unique file ID for the given absolute pathname. Return
519** a pointer to the vxworksFileId object. This pointer is the unique
520** file ID.
521**
522** The nRef field of the vxworksFileId object is incremented before
523** the object is returned. A new vxworksFileId object is created
524** and added to the global list if necessary.
525**
526** If a memory allocation error occurs, return NULL.
527*/
528static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
529 struct vxworksFileId *pNew; /* search key and new file ID */
530 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
531 int n; /* Length of zAbsoluteName string */
532
533 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000534 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000535 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
536 if( pNew==0 ) return 0;
537 pNew->zCanonicalName = (char*)&pNew[1];
538 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
539 n = vxworksSimplifyName(pNew->zCanonicalName, n);
540
541 /* Search for an existing entry that matching the canonical name.
542 ** If found, increment the reference count and return a pointer to
543 ** the existing file ID.
544 */
545 unixEnterMutex();
546 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
547 if( pCandidate->nName==n
548 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
549 ){
550 sqlite3_free(pNew);
551 pCandidate->nRef++;
552 unixLeaveMutex();
553 return pCandidate;
554 }
555 }
556
557 /* No match was found. We will make a new file ID */
558 pNew->nRef = 1;
559 pNew->nName = n;
560 pNew->pNext = vxworksFileList;
561 vxworksFileList = pNew;
562 unixLeaveMutex();
563 return pNew;
564}
565
566/*
567** Decrement the reference count on a vxworksFileId object. Free
568** the object when the reference count reaches zero.
569*/
570static void vxworksReleaseFileId(struct vxworksFileId *pId){
571 unixEnterMutex();
572 assert( pId->nRef>0 );
573 pId->nRef--;
574 if( pId->nRef==0 ){
575 struct vxworksFileId **pp;
576 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
577 assert( *pp==pId );
578 *pp = pId->pNext;
579 sqlite3_free(pId);
580 }
581 unixLeaveMutex();
582}
583#endif /* OS_VXWORKS */
584/*************** End of Unique File ID Utility Used By VxWorks ****************
585******************************************************************************/
586
587
588/******************************************************************************
589*************************** Posix Advisory Locking ****************************
590**
drh9b35ea62008-11-29 02:20:26 +0000591** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000592** section 6.5.2.2 lines 483 through 490 specify that when a process
593** sets or clears a lock, that operation overrides any prior locks set
594** by the same process. It does not explicitly say so, but this implies
595** that it overrides locks set by the same process using a different
596** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000597**
598** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000599** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
600**
601** Suppose ./file1 and ./file2 are really the same file (because
602** one is a hard or symbolic link to the other) then if you set
603** an exclusive lock on fd1, then try to get an exclusive lock
604** on fd2, it works. I would have expected the second lock to
605** fail since there was already a lock on the file due to fd1.
606** But not so. Since both locks came from the same process, the
607** second overrides the first, even though they were on different
608** file descriptors opened on different file names.
609**
drh734c9862008-11-28 15:37:20 +0000610** This means that we cannot use POSIX locks to synchronize file access
611** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000612** to synchronize access for threads in separate processes, but not
613** threads within the same process.
614**
615** To work around the problem, SQLite has to manage file locks internally
616** on its own. Whenever a new database is opened, we have to find the
617** specific inode of the database file (the inode is determined by the
618** st_dev and st_ino fields of the stat structure that fstat() fills in)
619** and check for locks already existing on that inode. When locks are
620** created or removed, we have to look at our own internal record of the
621** locks to see if another thread has previously set a lock on that same
622** inode.
623**
drh9b35ea62008-11-29 02:20:26 +0000624** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
625** For VxWorks, we have to use the alternative unique ID system based on
626** canonical filename and implemented in the previous division.)
627**
danielk1977ad94b582007-08-20 06:44:22 +0000628** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000629** descriptor. It is now a structure that holds the integer file
630** descriptor and a pointer to a structure that describes the internal
631** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000632** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000633** point to the same locking structure. The locking structure keeps
634** a reference count (so we will know when to delete it) and a "cnt"
635** field that tells us its internal lock status. cnt==0 means the
636** file is unlocked. cnt==-1 means the file has an exclusive lock.
637** cnt>0 means there are cnt shared locks on the file.
638**
639** Any attempt to lock or unlock a file first checks the locking
640** structure. The fcntl() system call is only invoked to set a
641** POSIX lock if the internal lock structure transitions between
642** a locked and an unlocked state.
643**
drh734c9862008-11-28 15:37:20 +0000644** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000645**
646** If you close a file descriptor that points to a file that has locks,
647** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000648** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000649** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000650** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000651** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000652** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000653** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000654** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000655** be closed and that list is walked (and cleared) when the last lock
656** clears.
657**
drh9b35ea62008-11-29 02:20:26 +0000658** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000659**
drh9b35ea62008-11-29 02:20:26 +0000660** Many older versions of linux use the LinuxThreads library which is
661** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000662** A cannot be modified or overridden by a different thread B.
663** Only thread A can modify the lock. Locking behavior is correct
664** if the appliation uses the newer Native Posix Thread Library (NPTL)
665** on linux - with NPTL a lock created by thread A can override locks
666** in thread B. But there is no way to know at compile-time which
667** threading library is being used. So there is no way to know at
668** compile-time whether or not thread A can override locks on thread B.
669** We have to do a run-time check to discover the behavior of the
670** current process.
drh5fdae772004-06-29 03:29:00 +0000671**
drh734c9862008-11-28 15:37:20 +0000672** On systems where thread A is unable to modify locks created by
673** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000674** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000675** structure to record this information. And on those systems it
676** is illegal to begin a transaction in one thread and finish it
677** in another. For this latter restriction, there is no work-around.
678** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000679*/
680
681/*
drh6c7d5c52008-11-21 20:32:33 +0000682** Set or check the unixFile.tid field. This field is set when an unixFile
683** is first opened. All subsequent uses of the unixFile verify that the
684** same thread is operating on the unixFile. Some operating systems do
685** not allow locks to be overridden by other threads and that restriction
686** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000687** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000688**
689** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
690** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000691** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000692** or if no locks are held. But the unixFile.pLock field needs to be
693** recomputed because its key includes the thread-id. See the
694** transferOwnership() function below for additional information
695*/
drh734c9862008-11-28 15:37:20 +0000696#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000697# define SET_THREADID(X) (X)->tid = pthread_self()
698# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
699 !pthread_equal((X)->tid, pthread_self()))
700#else
701# define SET_THREADID(X)
702# define CHECK_THREADID(X) 0
703#endif
704
705/*
drhbbd42a62004-05-22 17:41:58 +0000706** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000707** to locate a particular unixOpenCnt structure given its inode. This
708** is the same as the unixLockKey except that the thread ID is omitted.
709*/
710struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000711 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000712#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000713 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000714#else
drh107886a2008-11-21 22:21:50 +0000715 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000716#endif
717};
718
719/*
720** An instance of the following structure serves as the key used
721** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000722**
drh734c9862008-11-28 15:37:20 +0000723** If threads cannot override each others locks (LinuxThreads), then we
724** set the unixLockKey.tid field to the thread ID. If threads can override
725** each others locks (Posix and NPTL) then tid is always set to zero.
726** tid is omitted if we compile without threading support or on an OS
727** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000728*/
drh6c7d5c52008-11-21 20:32:33 +0000729struct unixLockKey {
730 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000731#if SQLITE_THREADSAFE && defined(__linux__)
732 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000733#endif
drhbbd42a62004-05-22 17:41:58 +0000734};
735
736/*
737** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000738** inode. Or, on LinuxThreads, there is one of these structures for
739** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000740**
danielk1977ad94b582007-08-20 06:44:22 +0000741** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000742** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000743** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000744*/
drh6c7d5c52008-11-21 20:32:33 +0000745struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000746 struct unixLockKey lockKey; /* The lookup key */
747 int cnt; /* Number of SHARED locks held */
748 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
749 int nRef; /* Number of pointers to this structure */
750 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
751 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000752};
753
754/*
755** An instance of the following structure is allocated for each open
756** inode. This structure keeps track of the number of locks on that
757** inode. If a close is attempted against an inode that is holding
758** locks, the close is deferred until all locks clear by adding the
759** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000760**
761** TODO: Consider changing this so that there is only a single file
762** descriptor for each open file, even when it is opened multiple times.
763** The close() system call would only occur when the last database
764** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000765*/
drh6c7d5c52008-11-21 20:32:33 +0000766struct unixOpenCnt {
767 struct unixFileId fileId; /* The lookup key */
768 int nRef; /* Number of pointers to this structure */
769 int nLock; /* Number of outstanding locks */
dane946c392009-08-22 11:39:46 +0000770 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh6c7d5c52008-11-21 20:32:33 +0000771#if OS_VXWORKS
772 sem_t *pSem; /* Named POSIX semaphore */
drh2238dcc2009-08-27 17:56:20 +0000773 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000774#endif
drh6c7d5c52008-11-21 20:32:33 +0000775 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000776};
777
drhda0e7682008-07-30 15:27:54 +0000778/*
drh9b35ea62008-11-29 02:20:26 +0000779** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
780** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000781** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000782** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000783*/
drh6c7d5c52008-11-21 20:32:33 +0000784static struct unixLockInfo *lockList = 0;
785static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000786
drh5fdae772004-06-29 03:29:00 +0000787/*
drh9b35ea62008-11-29 02:20:26 +0000788** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000789** locks.
790**
drh9b35ea62008-11-29 02:20:26 +0000791** 0: No. Threads cannot override each others locks. (LinuxThreads)
792** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000793** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000794**
drh5062d3a2006-01-31 23:03:35 +0000795** On some systems, we know at compile-time if threads can override each
796** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
797** will be set appropriately. On other systems, we have to check at
798** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
799** undefined.
800**
drhf1a221e2006-01-15 17:27:17 +0000801** This variable normally has file scope only. But during testing, we make
802** it a global so that the test code can change its value in order to verify
803** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000804*/
drh715ff302008-12-03 22:32:44 +0000805#if SQLITE_THREADSAFE && defined(__linux__)
806# ifndef SQLITE_THREAD_OVERRIDE_LOCK
807# define SQLITE_THREAD_OVERRIDE_LOCK -1
808# endif
809# ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000810int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000811# else
drh5062d3a2006-01-31 23:03:35 +0000812static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000813# endif
drh029b44b2006-01-15 00:13:15 +0000814#endif
drh5fdae772004-06-29 03:29:00 +0000815
816/*
817** This structure holds information passed into individual test
818** threads by the testThreadLockingBehavior() routine.
819*/
820struct threadTestData {
821 int fd; /* File to be locked */
822 struct flock lock; /* The locking operation */
823 int result; /* Result of the locking operation */
824};
825
drh6c7d5c52008-11-21 20:32:33 +0000826#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000827/*
danielk197741a6a612008-11-11 18:34:35 +0000828** This function is used as the main routine for a thread launched by
829** testThreadLockingBehavior(). It tests whether the shared-lock obtained
830** by the main thread in testThreadLockingBehavior() conflicts with a
831** hypothetical write-lock obtained by this thread on the same file.
832**
833** The write-lock is not actually acquired, as this is not possible if
834** the file is open in read-only mode (see ticket #3472).
835*/
drh5fdae772004-06-29 03:29:00 +0000836static void *threadLockingTest(void *pArg){
837 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000838 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000839 return pArg;
840}
drh6c7d5c52008-11-21 20:32:33 +0000841#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000842
drh6c7d5c52008-11-21 20:32:33 +0000843
844#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000845/*
846** This procedure attempts to determine whether or not threads
847** can override each others locks then sets the
848** threadsOverrideEachOthersLocks variable appropriately.
849*/
danielk19774d5238f2006-01-27 06:32:00 +0000850static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000851 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000852 int rc;
853 struct threadTestData d;
854 struct flock l;
855 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000856
857 fd = dup(fd_orig);
858 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000859 memset(&l, 0, sizeof(l));
860 l.l_type = F_RDLCK;
861 l.l_len = 1;
862 l.l_start = 0;
863 l.l_whence = SEEK_SET;
864 rc = fcntl(fd_orig, F_SETLK, &l);
865 if( rc!=0 ) return;
866 memset(&d, 0, sizeof(d));
867 d.fd = fd;
868 d.lock = l;
869 d.lock.l_type = F_WRLCK;
drh06150f92009-07-03 12:57:58 +0000870 if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
871 pthread_join(t, 0);
872 }
drh5fdae772004-06-29 03:29:00 +0000873 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000874 if( d.result!=0 ) return;
875 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000876}
drh06150f92009-07-03 12:57:58 +0000877#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000878
drhbbd42a62004-05-22 17:41:58 +0000879/*
drh6c7d5c52008-11-21 20:32:33 +0000880** Release a unixLockInfo structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000881**
882** The mutex entered using the unixEnterMutex() function must be held
883** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000884*/
885static void releaseLockInfo(struct unixLockInfo *pLock){
dan9359c7b2009-08-21 08:29:10 +0000886 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000887 if( pLock ){
888 pLock->nRef--;
889 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000890 if( pLock->pPrev ){
891 assert( pLock->pPrev->pNext==pLock );
892 pLock->pPrev->pNext = pLock->pNext;
893 }else{
894 assert( lockList==pLock );
895 lockList = pLock->pNext;
896 }
897 if( pLock->pNext ){
898 assert( pLock->pNext->pPrev==pLock );
899 pLock->pNext->pPrev = pLock->pPrev;
900 }
danielk1977e339d652008-06-28 11:23:00 +0000901 sqlite3_free(pLock);
902 }
drhbbd42a62004-05-22 17:41:58 +0000903 }
904}
905
906/*
drh6c7d5c52008-11-21 20:32:33 +0000907** Release a unixOpenCnt structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000908**
909** The mutex entered using the unixEnterMutex() function must be held
910** when this function is called.
drhbbd42a62004-05-22 17:41:58 +0000911*/
drh6c7d5c52008-11-21 20:32:33 +0000912static void releaseOpenCnt(struct unixOpenCnt *pOpen){
dan9359c7b2009-08-21 08:29:10 +0000913 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000914 if( pOpen ){
915 pOpen->nRef--;
916 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000917 if( pOpen->pPrev ){
918 assert( pOpen->pPrev->pNext==pOpen );
919 pOpen->pPrev->pNext = pOpen->pNext;
920 }else{
921 assert( openList==pOpen );
922 openList = pOpen->pNext;
923 }
924 if( pOpen->pNext ){
925 assert( pOpen->pNext->pPrev==pOpen );
926 pOpen->pNext->pPrev = pOpen->pPrev;
927 }
dan11b38792009-09-09 18:46:52 +0000928 assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
929
930 /* If pOpen->pUnused is not null, then memory and file-descriptors
931 ** are leaked.
932 **
933 ** This will only happen if, under Linuxthreads, the user has opened
934 ** a transaction in one thread, then attempts to close the database
935 ** handle from another thread (without first unlocking the db file).
936 ** This is a misuse. */
danielk1977e339d652008-06-28 11:23:00 +0000937 sqlite3_free(pOpen);
938 }
drhbbd42a62004-05-22 17:41:58 +0000939 }
940}
941
drh6c7d5c52008-11-21 20:32:33 +0000942/*
943** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
944** describes that file descriptor. Create new ones if necessary. The
945** return values might be uninitialized if an error occurs.
946**
dan9359c7b2009-08-21 08:29:10 +0000947** The mutex entered using the unixEnterMutex() function must be held
948** when this function is called.
949**
drh6c7d5c52008-11-21 20:32:33 +0000950** Return an appropriate error code.
951*/
952static int findLockInfo(
953 unixFile *pFile, /* Unix file with file desc used in the key */
954 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
955 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
956){
957 int rc; /* System call return code */
958 int fd; /* The file descriptor for pFile */
959 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
960 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
961 struct stat statbuf; /* Low-level file information */
drh0d588bb2009-06-17 13:09:38 +0000962 struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000963 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
964
dan9359c7b2009-08-21 08:29:10 +0000965 assert( unixMutexHeld() );
966
drh6c7d5c52008-11-21 20:32:33 +0000967 /* Get low-level information about the file that we can used to
968 ** create a unique name for the file.
969 */
970 fd = pFile->h;
971 rc = fstat(fd, &statbuf);
972 if( rc!=0 ){
973 pFile->lastErrno = errno;
974#ifdef EOVERFLOW
975 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
976#endif
977 return SQLITE_IOERR;
978 }
979
drheb0d74f2009-02-03 15:27:02 +0000980#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000981 /* On OS X on an msdos filesystem, the inode number is reported
982 ** incorrectly for zero-size files. See ticket #3260. To work
983 ** around this problem (we consider it a bug in OS X, not SQLite)
984 ** we always increase the file size to 1 by writing a single byte
985 ** prior to accessing the inode number. The one byte written is
986 ** an ASCII 'S' character which also happens to be the first byte
987 ** in the header of every SQLite database. In this way, if there
988 ** is a race condition such that another thread has already populated
989 ** the first page of the database, no damage is done.
990 */
991 if( statbuf.st_size==0 ){
drheb0d74f2009-02-03 15:27:02 +0000992 rc = write(fd, "S", 1);
993 if( rc!=1 ){
994 return SQLITE_IOERR;
995 }
drh6c7d5c52008-11-21 20:32:33 +0000996 rc = fstat(fd, &statbuf);
997 if( rc!=0 ){
998 pFile->lastErrno = errno;
999 return SQLITE_IOERR;
1000 }
1001 }
drheb0d74f2009-02-03 15:27:02 +00001002#endif
drh6c7d5c52008-11-21 20:32:33 +00001003
1004 memset(&lockKey, 0, sizeof(lockKey));
1005 lockKey.fid.dev = statbuf.st_dev;
1006#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001007 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001008#else
1009 lockKey.fid.ino = statbuf.st_ino;
1010#endif
drh734c9862008-11-28 15:37:20 +00001011#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +00001012 if( threadsOverrideEachOthersLocks<0 ){
1013 testThreadLockingBehavior(fd);
1014 }
1015 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
1016#endif
1017 fileId = lockKey.fid;
1018 if( ppLock!=0 ){
1019 pLock = lockList;
1020 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
1021 pLock = pLock->pNext;
1022 }
1023 if( pLock==0 ){
1024 pLock = sqlite3_malloc( sizeof(*pLock) );
1025 if( pLock==0 ){
1026 rc = SQLITE_NOMEM;
1027 goto exit_findlockinfo;
1028 }
1029 pLock->lockKey = lockKey;
1030 pLock->nRef = 1;
1031 pLock->cnt = 0;
1032 pLock->locktype = 0;
1033 pLock->pNext = lockList;
1034 pLock->pPrev = 0;
1035 if( lockList ) lockList->pPrev = pLock;
1036 lockList = pLock;
1037 }else{
1038 pLock->nRef++;
1039 }
1040 *ppLock = pLock;
1041 }
1042 if( ppOpen!=0 ){
1043 pOpen = openList;
1044 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
1045 pOpen = pOpen->pNext;
1046 }
1047 if( pOpen==0 ){
1048 pOpen = sqlite3_malloc( sizeof(*pOpen) );
1049 if( pOpen==0 ){
1050 releaseLockInfo(pLock);
1051 rc = SQLITE_NOMEM;
1052 goto exit_findlockinfo;
1053 }
dane946c392009-08-22 11:39:46 +00001054 memset(pOpen, 0, sizeof(*pOpen));
drh6c7d5c52008-11-21 20:32:33 +00001055 pOpen->fileId = fileId;
1056 pOpen->nRef = 1;
drh6c7d5c52008-11-21 20:32:33 +00001057 pOpen->pNext = openList;
drh6c7d5c52008-11-21 20:32:33 +00001058 if( openList ) openList->pPrev = pOpen;
1059 openList = pOpen;
drh6c7d5c52008-11-21 20:32:33 +00001060 }else{
1061 pOpen->nRef++;
1062 }
1063 *ppOpen = pOpen;
1064 }
1065
1066exit_findlockinfo:
1067 return rc;
1068}
drh6c7d5c52008-11-21 20:32:33 +00001069
drh7708e972008-11-29 00:56:52 +00001070/*
1071** If we are currently in a different thread than the thread that the
1072** unixFile argument belongs to, then transfer ownership of the unixFile
1073** over to the current thread.
1074**
1075** A unixFile is only owned by a thread on systems that use LinuxThreads.
1076**
1077** Ownership transfer is only allowed if the unixFile is currently unlocked.
1078** If the unixFile is locked and an ownership is wrong, then return
1079** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1080*/
1081#if SQLITE_THREADSAFE && defined(__linux__)
1082static int transferOwnership(unixFile *pFile){
1083 int rc;
1084 pthread_t hSelf;
1085 if( threadsOverrideEachOthersLocks ){
1086 /* Ownership transfers not needed on this system */
1087 return SQLITE_OK;
1088 }
1089 hSelf = pthread_self();
1090 if( pthread_equal(pFile->tid, hSelf) ){
1091 /* We are still in the same thread */
1092 OSTRACE1("No-transfer, same thread\n");
1093 return SQLITE_OK;
1094 }
1095 if( pFile->locktype!=NO_LOCK ){
1096 /* We cannot change ownership while we are holding a lock! */
1097 return SQLITE_MISUSE;
1098 }
1099 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1100 pFile->h, pFile->tid, hSelf);
1101 pFile->tid = hSelf;
1102 if (pFile->pLock != NULL) {
1103 releaseLockInfo(pFile->pLock);
1104 rc = findLockInfo(pFile, &pFile->pLock, 0);
1105 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1106 locktypeName(pFile->locktype),
1107 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1108 return rc;
1109 } else {
1110 return SQLITE_OK;
1111 }
1112}
1113#else /* if not SQLITE_THREADSAFE */
1114 /* On single-threaded builds, ownership transfer is a no-op */
1115# define transferOwnership(X) SQLITE_OK
1116#endif /* SQLITE_THREADSAFE */
1117
aswift5b1a2562008-08-22 00:22:35 +00001118
1119/*
danielk197713adf8a2004-06-03 16:08:41 +00001120** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001121** file by this or any other process. If such a lock is held, set *pResOut
1122** to a non-zero value otherwise *pResOut is set to zero. The return value
1123** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001124*/
danielk1977861f7452008-06-05 11:39:11 +00001125static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001126 int rc = SQLITE_OK;
1127 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001128 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001129
danielk1977861f7452008-06-05 11:39:11 +00001130 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1131
drh054889e2005-11-30 03:20:31 +00001132 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001133 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001134
1135 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001136 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001137 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001138 }
1139
drh2ac3ee92004-06-07 16:27:46 +00001140 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001141 */
danielk197709480a92009-02-09 05:32:32 +00001142#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001143 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001144 struct flock lock;
1145 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001146 lock.l_start = RESERVED_BYTE;
1147 lock.l_len = 1;
1148 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001149 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1150 int tErrno = errno;
1151 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1152 pFile->lastErrno = tErrno;
1153 } else if( lock.l_type!=F_UNLCK ){
1154 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001155 }
1156 }
danielk197709480a92009-02-09 05:32:32 +00001157#endif
danielk197713adf8a2004-06-03 16:08:41 +00001158
drh6c7d5c52008-11-21 20:32:33 +00001159 unixLeaveMutex();
aswift5b1a2562008-08-22 00:22:35 +00001160 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001161
aswift5b1a2562008-08-22 00:22:35 +00001162 *pResOut = reserved;
1163 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001164}
1165
1166/*
drh0c2694b2009-09-03 16:23:44 +00001167** Perform a file locking operation on a range of bytes in a file.
1168** The "op" parameter should be one of F_RDLCK, F_WRLCK, or F_UNLCK.
1169** Return 0 on success or -1 for failure. On failure, write the error
1170** code into *pErrcode.
1171**
1172** If the SQLITE_WHOLE_FILE_LOCKING bit is clear, then only lock
1173** the range of bytes on the locking page between SHARED_FIRST and
1174** SHARED_SIZE. If SQLITE_WHOLE_FILE_LOCKING is set, then lock all
1175** bytes from 0 up to but not including PENDING_BYTE, and all bytes
1176** that follow SHARED_FIRST.
1177**
1178** In other words, of SQLITE_WHOLE_FILE_LOCKING if false (the historical
1179** default case) then only lock a small range of bytes from SHARED_FIRST
1180** through SHARED_FIRST+SHARED_SIZE-1. But if SQLITE_WHOLE_FILE_LOCKING is
1181** true then lock every byte in the file except for PENDING_BYTE and
1182** RESERVED_BYTE.
1183**
1184** SQLITE_WHOLE_FILE_LOCKING=true overlaps SQLITE_WHOLE_FILE_LOCKING=false
1185** and so the locking schemes are compatible. One type of lock will
1186** effectively exclude the other type. The reason for using the
1187** SQLITE_WHOLE_FILE_LOCKING=true is that by indicating the full range
1188** of bytes to be read or written, we give hints to NFS to help it
1189** maintain cache coherency. On the other hand, whole file locking
1190** is slower, so we don't want to use it except for NFS.
1191*/
1192static int rangeLock(unixFile *pFile, int op, int *pErrcode){
1193 struct flock lock;
1194 int rc;
1195 lock.l_type = op;
1196 lock.l_start = SHARED_FIRST;
1197 lock.l_whence = SEEK_SET;
1198 if( (pFile->fileFlags & SQLITE_WHOLE_FILE_LOCKING)==0 ){
1199 lock.l_len = SHARED_SIZE;
1200 rc = fcntl(pFile->h, F_SETLK, &lock);
1201 *pErrcode = errno;
1202 }else{
1203 lock.l_len = 0;
1204 rc = fcntl(pFile->h, F_SETLK, &lock);
1205 *pErrcode = errno;
1206 if( NEVER(op==F_UNLCK) || rc!=(-1) ){
1207 lock.l_start = 0;
1208 lock.l_len = PENDING_BYTE;
1209 rc = fcntl(pFile->h, F_SETLK, &lock);
1210 if( ALWAYS(op!=F_UNLCK) && rc==(-1) ){
1211 *pErrcode = errno;
1212 lock.l_type = F_UNLCK;
1213 lock.l_start = SHARED_FIRST;
1214 lock.l_len = 0;
1215 fcntl(pFile->h, F_SETLK, &lock);
1216 }
1217 }
1218 }
1219 return rc;
1220}
1221
1222/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001223** Lock the file with the lock specified by parameter locktype - one
1224** of the following:
1225**
drh2ac3ee92004-06-07 16:27:46 +00001226** (1) SHARED_LOCK
1227** (2) RESERVED_LOCK
1228** (3) PENDING_LOCK
1229** (4) EXCLUSIVE_LOCK
1230**
drhb3e04342004-06-08 00:47:47 +00001231** Sometimes when requesting one lock state, additional lock states
1232** are inserted in between. The locking might fail on one of the later
1233** transitions leaving the lock state different from what it started but
1234** still short of its goal. The following chart shows the allowed
1235** transitions and the inserted intermediate states:
1236**
1237** UNLOCKED -> SHARED
1238** SHARED -> RESERVED
1239** SHARED -> (PENDING) -> EXCLUSIVE
1240** RESERVED -> (PENDING) -> EXCLUSIVE
1241** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001242**
drha6abd042004-06-09 17:37:22 +00001243** This routine will only increase a lock. Use the sqlite3OsUnlock()
1244** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001245*/
danielk197762079062007-08-15 17:08:46 +00001246static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001247 /* The following describes the implementation of the various locks and
1248 ** lock transitions in terms of the POSIX advisory shared and exclusive
1249 ** lock primitives (called read-locks and write-locks below, to avoid
1250 ** confusion with SQLite lock names). The algorithms are complicated
1251 ** slightly in order to be compatible with windows systems simultaneously
1252 ** accessing the same database file, in case that is ever required.
1253 **
1254 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1255 ** byte', each single bytes at well known offsets, and the 'shared byte
1256 ** range', a range of 510 bytes at a well known offset.
1257 **
1258 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1259 ** byte'. If this is successful, a random byte from the 'shared byte
1260 ** range' is read-locked and the lock on the 'pending byte' released.
1261 **
danielk197790ba3bd2004-06-25 08:32:25 +00001262 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1263 ** A RESERVED lock is implemented by grabbing a write-lock on the
1264 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001265 **
1266 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001267 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1268 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1269 ** obtained, but existing SHARED locks are allowed to persist. A process
1270 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1271 ** This property is used by the algorithm for rolling back a journal file
1272 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001273 **
danielk197790ba3bd2004-06-25 08:32:25 +00001274 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1275 ** implemented by obtaining a write-lock on the entire 'shared byte
1276 ** range'. Since all other locks require a read-lock on one of the bytes
1277 ** within this range, this ensures that no other locks are held on the
1278 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001279 **
1280 ** The reason a single byte cannot be used instead of the 'shared byte
1281 ** range' is that some versions of windows do not support read-locks. By
1282 ** locking a random byte from a range, concurrent SHARED locks may exist
1283 ** even if the locking primitive used is always a write-lock.
1284 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001285 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001286 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001287 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001288 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001289 int s = 0;
drh0c2694b2009-09-03 16:23:44 +00001290 int tErrno;
danielk19779a1d0ab2004-06-01 14:09:28 +00001291
drh054889e2005-11-30 03:20:31 +00001292 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001293 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001294 locktypeName(locktype), locktypeName(pFile->locktype),
1295 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001296
1297 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001298 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001299 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001300 */
drh054889e2005-11-30 03:20:31 +00001301 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001302 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001303 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001304 return SQLITE_OK;
1305 }
1306
drh0c2694b2009-09-03 16:23:44 +00001307 /* Make sure the locking sequence is correct.
1308 ** (1) We never move from unlocked to anything higher than shared lock.
1309 ** (2) SQLite never explicitly requests a pendig lock.
1310 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001311 */
drh054889e2005-11-30 03:20:31 +00001312 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001313 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001314 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001315
drh054889e2005-11-30 03:20:31 +00001316 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001317 */
drh6c7d5c52008-11-21 20:32:33 +00001318 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001319
drh029b44b2006-01-15 00:13:15 +00001320 /* Make sure the current thread owns the pFile.
1321 */
1322 rc = transferOwnership(pFile);
1323 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001324 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001325 return rc;
1326 }
drh64b1bea2006-01-15 02:30:57 +00001327 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001328
danielk1977ad94b582007-08-20 06:44:22 +00001329 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001330 ** handle that precludes the requested lock, return BUSY.
1331 */
drh054889e2005-11-30 03:20:31 +00001332 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001333 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001334 ){
1335 rc = SQLITE_BUSY;
1336 goto end_lock;
1337 }
1338
1339 /* If a SHARED lock is requested, and some thread using this PID already
1340 ** has a SHARED or RESERVED lock, then increment reference counts and
1341 ** return SQLITE_OK.
1342 */
1343 if( locktype==SHARED_LOCK &&
1344 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1345 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001346 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001347 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001348 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001349 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001350 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001351 goto end_lock;
1352 }
1353
danielk19779a1d0ab2004-06-01 14:09:28 +00001354
drh3cde3bb2004-06-12 02:17:14 +00001355 /* A PENDING lock is needed before acquiring a SHARED lock and before
1356 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1357 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001358 */
drh0c2694b2009-09-03 16:23:44 +00001359 lock.l_len = 1L;
1360 lock.l_whence = SEEK_SET;
drh3cde3bb2004-06-12 02:17:14 +00001361 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001362 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001363 ){
danielk1977489468c2004-06-28 08:25:47 +00001364 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001365 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001366 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001367 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001368 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001369 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1370 if( IS_LOCK_ERROR(rc) ){
1371 pFile->lastErrno = tErrno;
1372 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001373 goto end_lock;
1374 }
drh3cde3bb2004-06-12 02:17:14 +00001375 }
1376
1377
1378 /* If control gets to this point, then actually go ahead and make
1379 ** operating system calls for the specified lock.
1380 */
1381 if( locktype==SHARED_LOCK ){
1382 assert( pLock->cnt==0 );
1383 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001384
drh2ac3ee92004-06-07 16:27:46 +00001385 /* Now get the read-lock */
drh0c2694b2009-09-03 16:23:44 +00001386 s = rangeLock(pFile, F_RDLCK, &tErrno);
1387
drh2ac3ee92004-06-07 16:27:46 +00001388 /* Drop the temporary PENDING lock */
1389 lock.l_start = PENDING_BYTE;
1390 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001391 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001392 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001393 if( s != -1 ){
1394 /* This could happen with a network mount */
1395 tErrno = errno;
1396 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1397 if( IS_LOCK_ERROR(rc) ){
1398 pFile->lastErrno = tErrno;
1399 }
1400 goto end_lock;
1401 }
drh2b4b5962005-06-15 17:47:55 +00001402 }
drhe2396a12007-03-29 20:19:58 +00001403 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001404 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1405 if( IS_LOCK_ERROR(rc) ){
1406 pFile->lastErrno = tErrno;
1407 }
drhbbd42a62004-05-22 17:41:58 +00001408 }else{
drh054889e2005-11-30 03:20:31 +00001409 pFile->locktype = SHARED_LOCK;
1410 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001411 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001412 }
drh3cde3bb2004-06-12 02:17:14 +00001413 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1414 /* We are trying for an exclusive lock but another thread in this
1415 ** same process is still holding a shared lock. */
1416 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001417 }else{
drh3cde3bb2004-06-12 02:17:14 +00001418 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001419 ** assumed that there is a SHARED or greater lock on the file
1420 ** already.
1421 */
drh054889e2005-11-30 03:20:31 +00001422 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001423 lock.l_type = F_WRLCK;
1424 switch( locktype ){
1425 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001426 lock.l_start = RESERVED_BYTE;
drh0c2694b2009-09-03 16:23:44 +00001427 s = fcntl(pFile->h, F_SETLK, &lock);
1428 tErrno = errno;
danielk19779a1d0ab2004-06-01 14:09:28 +00001429 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001430 case EXCLUSIVE_LOCK:
drh0c2694b2009-09-03 16:23:44 +00001431 s = rangeLock(pFile, F_WRLCK, &tErrno);
danielk19779a1d0ab2004-06-01 14:09:28 +00001432 break;
1433 default:
1434 assert(0);
1435 }
drhe2396a12007-03-29 20:19:58 +00001436 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001437 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1438 if( IS_LOCK_ERROR(rc) ){
1439 pFile->lastErrno = tErrno;
1440 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001441 }
drhbbd42a62004-05-22 17:41:58 +00001442 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001443
drh8f941bc2009-01-14 23:03:40 +00001444
1445#ifndef NDEBUG
1446 /* Set up the transaction-counter change checking flags when
1447 ** transitioning from a SHARED to a RESERVED lock. The change
1448 ** from SHARED to RESERVED marks the beginning of a normal
1449 ** write operation (not a hot journal rollback).
1450 */
1451 if( rc==SQLITE_OK
1452 && pFile->locktype<=SHARED_LOCK
1453 && locktype==RESERVED_LOCK
1454 ){
1455 pFile->transCntrChng = 0;
1456 pFile->dbUpdate = 0;
1457 pFile->inNormalWrite = 1;
1458 }
1459#endif
1460
1461
danielk1977ecb2a962004-06-02 06:30:16 +00001462 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001463 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001464 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001465 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001466 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001467 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001468 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001469
1470end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001471 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001472 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001473 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001474 return rc;
1475}
1476
1477/*
dane946c392009-08-22 11:39:46 +00001478** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
1479** If all such file descriptors are closed without error, the list is
1480** cleared and SQLITE_OK returned.
dan08da86a2009-08-21 17:18:03 +00001481**
1482** Otherwise, if an error occurs, then successfully closed file descriptor
dane946c392009-08-22 11:39:46 +00001483** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
dan08da86a2009-08-21 17:18:03 +00001484** not deleted and SQLITE_IOERR_CLOSE returned.
1485*/
1486static int closePendingFds(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001487 int rc = SQLITE_OK;
dane946c392009-08-22 11:39:46 +00001488 struct unixOpenCnt *pOpen = pFile->pOpen;
1489 UnixUnusedFd *pError = 0;
1490 UnixUnusedFd *p;
1491 UnixUnusedFd *pNext;
1492 for(p=pOpen->pUnused; p; p=pNext){
1493 pNext = p->pNext;
1494 if( close(p->fd) ){
1495 pFile->lastErrno = errno;
1496 rc = SQLITE_IOERR_CLOSE;
1497 p->pNext = pError;
1498 pError = p;
dane946c392009-08-22 11:39:46 +00001499 }else{
1500 sqlite3_free(p);
dan08da86a2009-08-21 17:18:03 +00001501 }
1502 }
dane946c392009-08-22 11:39:46 +00001503 pOpen->pUnused = pError;
dan08da86a2009-08-21 17:18:03 +00001504 return rc;
1505}
1506
1507/*
1508** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001509** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001510*/
1511static void setPendingFd(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001512 struct unixOpenCnt *pOpen = pFile->pOpen;
dane946c392009-08-22 11:39:46 +00001513 UnixUnusedFd *p = pFile->pUnused;
1514 p->pNext = pOpen->pUnused;
1515 pOpen->pUnused = p;
1516 pFile->h = -1;
1517 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001518}
1519
1520/*
drh054889e2005-11-30 03:20:31 +00001521** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001522** must be either NO_LOCK or SHARED_LOCK.
1523**
1524** If the locking level of the file descriptor is already at or below
1525** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001526*/
danielk197762079062007-08-15 17:08:46 +00001527static int unixUnlock(sqlite3_file *id, int locktype){
drh0c2694b2009-09-03 16:23:44 +00001528 unixFile *pFile = (unixFile*)id; /* The open file */
1529 struct unixLockInfo *pLock; /* Structure describing current lock state */
1530 struct flock lock; /* Information passed into fcntl() */
1531 int rc = SQLITE_OK; /* Return code from this interface */
1532 int h; /* The underlying file descriptor */
1533 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001534
drh054889e2005-11-30 03:20:31 +00001535 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001536 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001537 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001538
1539 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001540 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001541 return SQLITE_OK;
1542 }
drhf1a221e2006-01-15 17:27:17 +00001543 if( CHECK_THREADID(pFile) ){
1544 return SQLITE_MISUSE;
1545 }
drh6c7d5c52008-11-21 20:32:33 +00001546 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001547 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001548 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001549 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001550 if( pFile->locktype>SHARED_LOCK ){
1551 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001552 SimulateIOErrorBenign(1);
1553 SimulateIOError( h=(-1) )
1554 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001555
1556#ifndef NDEBUG
1557 /* When reducing a lock such that other processes can start
1558 ** reading the database file again, make sure that the
1559 ** transaction counter was updated if any part of the database
1560 ** file changed. If the transaction counter is not updated,
1561 ** other connections to the same file might not realize that
1562 ** the file has changed and hence might not know to flush their
1563 ** cache. The use of a stale cache can lead to database corruption.
1564 */
1565 assert( pFile->inNormalWrite==0
1566 || pFile->dbUpdate==0
1567 || pFile->transCntrChng==1 );
1568 pFile->inNormalWrite = 0;
1569#endif
1570
1571
drh9c105bb2004-10-02 20:38:28 +00001572 if( locktype==SHARED_LOCK ){
drh0c2694b2009-09-03 16:23:44 +00001573 if( rangeLock(pFile, F_RDLCK, &tErrno)==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001574 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1575 if( IS_LOCK_ERROR(rc) ){
1576 pFile->lastErrno = tErrno;
1577 }
danielk197709480a92009-02-09 05:32:32 +00001578 goto end_unlock;
drh9c105bb2004-10-02 20:38:28 +00001579 }
1580 }
drhbbd42a62004-05-22 17:41:58 +00001581 lock.l_type = F_UNLCK;
1582 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001583 lock.l_start = PENDING_BYTE;
1584 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001585 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001586 pLock->locktype = SHARED_LOCK;
1587 }else{
drh0c2694b2009-09-03 16:23:44 +00001588 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001589 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1590 if( IS_LOCK_ERROR(rc) ){
1591 pFile->lastErrno = tErrno;
1592 }
drhcd731cf2009-03-28 23:23:02 +00001593 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001594 }
drhbbd42a62004-05-22 17:41:58 +00001595 }
drha6abd042004-06-09 17:37:22 +00001596 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001597 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001598
drha6abd042004-06-09 17:37:22 +00001599 /* Decrement the shared lock counter. Release the lock using an
1600 ** OS call only when all threads in this same process have released
1601 ** the lock.
1602 */
1603 pLock->cnt--;
1604 if( pLock->cnt==0 ){
1605 lock.l_type = F_UNLCK;
1606 lock.l_whence = SEEK_SET;
1607 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001608 SimulateIOErrorBenign(1);
1609 SimulateIOError( h=(-1) )
1610 SimulateIOErrorBenign(0);
1611 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001612 pLock->locktype = NO_LOCK;
1613 }else{
drh0c2694b2009-09-03 16:23:44 +00001614 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001615 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001616 if( IS_LOCK_ERROR(rc) ){
1617 pFile->lastErrno = tErrno;
1618 }
drhf48f9ca2009-03-28 23:47:10 +00001619 pLock->locktype = NO_LOCK;
1620 pFile->locktype = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001621 }
drha6abd042004-06-09 17:37:22 +00001622 }
1623
drhbbd42a62004-05-22 17:41:58 +00001624 /* Decrement the count of locks against this same file. When the
1625 ** count reaches zero, close any other file descriptors whose close
1626 ** was deferred because of outstanding locks.
1627 */
danielk197764a54c52009-03-30 07:39:35 +00001628 pOpen = pFile->pOpen;
1629 pOpen->nLock--;
1630 assert( pOpen->nLock>=0 );
dane946c392009-08-22 11:39:46 +00001631 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001632 int rc2 = closePendingFds(pFile);
1633 if( rc==SQLITE_OK ){
1634 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001635 }
drhbbd42a62004-05-22 17:41:58 +00001636 }
1637 }
aswift5b1a2562008-08-22 00:22:35 +00001638
1639end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001640 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001641 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001642 return rc;
drhbbd42a62004-05-22 17:41:58 +00001643}
1644
1645/*
danielk1977e339d652008-06-28 11:23:00 +00001646** This function performs the parts of the "close file" operation
1647** common to all locking schemes. It closes the directory and file
1648** handles, if they are valid, and sets all fields of the unixFile
1649** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001650**
1651** It is *not* necessary to hold the mutex when this routine is called,
1652** even on VxWorks. A mutex will be acquired on VxWorks by the
1653** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001654*/
1655static int closeUnixFile(sqlite3_file *id){
1656 unixFile *pFile = (unixFile*)id;
1657 if( pFile ){
1658 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001659 int err = close(pFile->dirfd);
1660 if( err ){
1661 pFile->lastErrno = errno;
1662 return SQLITE_IOERR_DIR_CLOSE;
1663 }else{
1664 pFile->dirfd=-1;
1665 }
danielk1977e339d652008-06-28 11:23:00 +00001666 }
1667 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001668 int err = close(pFile->h);
1669 if( err ){
1670 pFile->lastErrno = errno;
1671 return SQLITE_IOERR_CLOSE;
1672 }
danielk1977e339d652008-06-28 11:23:00 +00001673 }
drh6c7d5c52008-11-21 20:32:33 +00001674#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001675 if( pFile->pId ){
1676 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001677 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001678 }
drh107886a2008-11-21 22:21:50 +00001679 vxworksReleaseFileId(pFile->pId);
1680 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001681 }
1682#endif
danielk1977e339d652008-06-28 11:23:00 +00001683 OSTRACE2("CLOSE %-3d\n", pFile->h);
1684 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001685 sqlite3_free(pFile->pUnused);
danielk1977e339d652008-06-28 11:23:00 +00001686 memset(pFile, 0, sizeof(unixFile));
1687 }
1688 return SQLITE_OK;
1689}
1690
1691/*
danielk1977e3026632004-06-22 11:29:02 +00001692** Close a file.
1693*/
danielk197762079062007-08-15 17:08:46 +00001694static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001695 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001696 if( id ){
1697 unixFile *pFile = (unixFile *)id;
1698 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001699 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001700 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001701 /* If there are outstanding locks, do not actually close the file just
1702 ** yet because that would clear those locks. Instead, add the file
dane946c392009-08-22 11:39:46 +00001703 ** descriptor to pOpen->pUnused list. It will be automatically closed
1704 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001705 */
dan08da86a2009-08-21 17:18:03 +00001706 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001707 }
danielk1977e339d652008-06-28 11:23:00 +00001708 releaseLockInfo(pFile->pLock);
1709 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001710 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001711 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001712 }
aswiftaebf4132008-11-21 00:10:35 +00001713 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001714}
1715
drh734c9862008-11-28 15:37:20 +00001716/************** End of the posix advisory lock implementation *****************
1717******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001718
drh734c9862008-11-28 15:37:20 +00001719/******************************************************************************
1720****************************** No-op Locking **********************************
1721**
1722** Of the various locking implementations available, this is by far the
1723** simplest: locking is ignored. No attempt is made to lock the database
1724** file for reading or writing.
1725**
1726** This locking mode is appropriate for use on read-only databases
1727** (ex: databases that are burned into CD-ROM, for example.) It can
1728** also be used if the application employs some external mechanism to
1729** prevent simultaneous access of the same database by two or more
1730** database connections. But there is a serious risk of database
1731** corruption if this locking mode is used in situations where multiple
1732** database connections are accessing the same database file at the same
1733** time and one or more of those connections are writing.
1734*/
drhbfe66312006-10-03 17:40:40 +00001735
drh734c9862008-11-28 15:37:20 +00001736static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1737 UNUSED_PARAMETER(NotUsed);
1738 *pResOut = 0;
1739 return SQLITE_OK;
1740}
drh734c9862008-11-28 15:37:20 +00001741static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1742 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1743 return SQLITE_OK;
1744}
drh734c9862008-11-28 15:37:20 +00001745static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1746 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1747 return SQLITE_OK;
1748}
1749
1750/*
drh9b35ea62008-11-29 02:20:26 +00001751** Close the file.
drh734c9862008-11-28 15:37:20 +00001752*/
1753static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001754 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001755}
1756
1757/******************* End of the no-op lock implementation *********************
1758******************************************************************************/
1759
1760/******************************************************************************
1761************************* Begin dot-file Locking ******************************
1762**
drh0c2694b2009-09-03 16:23:44 +00001763** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001764** files in order to control access to the database. This works on just
1765** about every filesystem imaginable. But there are serious downsides:
1766**
1767** (1) There is zero concurrency. A single reader blocks all other
1768** connections from reading or writing the database.
1769**
1770** (2) An application crash or power loss can leave stale lock files
1771** sitting around that need to be cleared manually.
1772**
1773** Nevertheless, a dotlock is an appropriate locking mode for use if no
1774** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001775**
1776** Dotfile locking works by creating a file in the same directory as the
1777** database and with the same name but with a ".lock" extension added.
1778** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1779** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001780*/
1781
1782/*
1783** The file suffix added to the data base filename in order to create the
1784** lock file.
1785*/
1786#define DOTLOCK_SUFFIX ".lock"
1787
drh7708e972008-11-29 00:56:52 +00001788/*
1789** This routine checks if there is a RESERVED lock held on the specified
1790** file by this or any other process. If such a lock is held, set *pResOut
1791** to a non-zero value otherwise *pResOut is set to zero. The return value
1792** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1793**
1794** In dotfile locking, either a lock exists or it does not. So in this
1795** variation of CheckReservedLock(), *pResOut is set to true if any lock
1796** is held on the file and false if the file is unlocked.
1797*/
drh734c9862008-11-28 15:37:20 +00001798static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1799 int rc = SQLITE_OK;
1800 int reserved = 0;
1801 unixFile *pFile = (unixFile*)id;
1802
1803 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1804
1805 assert( pFile );
1806
1807 /* Check if a thread in this process holds such a lock */
1808 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001809 /* Either this connection or some other connection in the same process
1810 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001811 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001812 }else{
1813 /* The lock is held if and only if the lockfile exists */
1814 const char *zLockFile = (const char*)pFile->lockingContext;
1815 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001816 }
1817 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001818 *pResOut = reserved;
1819 return rc;
1820}
1821
drh7708e972008-11-29 00:56:52 +00001822/*
1823** Lock the file with the lock specified by parameter locktype - one
1824** of the following:
1825**
1826** (1) SHARED_LOCK
1827** (2) RESERVED_LOCK
1828** (3) PENDING_LOCK
1829** (4) EXCLUSIVE_LOCK
1830**
1831** Sometimes when requesting one lock state, additional lock states
1832** are inserted in between. The locking might fail on one of the later
1833** transitions leaving the lock state different from what it started but
1834** still short of its goal. The following chart shows the allowed
1835** transitions and the inserted intermediate states:
1836**
1837** UNLOCKED -> SHARED
1838** SHARED -> RESERVED
1839** SHARED -> (PENDING) -> EXCLUSIVE
1840** RESERVED -> (PENDING) -> EXCLUSIVE
1841** PENDING -> EXCLUSIVE
1842**
1843** This routine will only increase a lock. Use the sqlite3OsUnlock()
1844** routine to lower a locking level.
1845**
1846** With dotfile locking, we really only support state (4): EXCLUSIVE.
1847** But we track the other locking levels internally.
1848*/
drh734c9862008-11-28 15:37:20 +00001849static int dotlockLock(sqlite3_file *id, int locktype) {
1850 unixFile *pFile = (unixFile*)id;
1851 int fd;
1852 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001853 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001854
drh7708e972008-11-29 00:56:52 +00001855
1856 /* If we have any lock, then the lock file already exists. All we have
1857 ** to do is adjust our internal record of the lock level.
1858 */
1859 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001860 pFile->locktype = locktype;
1861#if !OS_VXWORKS
1862 /* Always update the timestamp on the old file */
1863 utimes(zLockFile, NULL);
1864#endif
drh7708e972008-11-29 00:56:52 +00001865 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001866 }
1867
1868 /* grab an exclusive lock */
1869 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1870 if( fd<0 ){
1871 /* failed to open/create the file, someone else may have stolen the lock */
1872 int tErrno = errno;
1873 if( EEXIST == tErrno ){
1874 rc = SQLITE_BUSY;
1875 } else {
1876 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1877 if( IS_LOCK_ERROR(rc) ){
1878 pFile->lastErrno = tErrno;
1879 }
1880 }
drh7708e972008-11-29 00:56:52 +00001881 return rc;
drh734c9862008-11-28 15:37:20 +00001882 }
1883 if( close(fd) ){
1884 pFile->lastErrno = errno;
1885 rc = SQLITE_IOERR_CLOSE;
1886 }
1887
1888 /* got it, set the type and return ok */
1889 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001890 return rc;
1891}
1892
drh7708e972008-11-29 00:56:52 +00001893/*
1894** Lower the locking level on file descriptor pFile to locktype. locktype
1895** must be either NO_LOCK or SHARED_LOCK.
1896**
1897** If the locking level of the file descriptor is already at or below
1898** the requested locking level, this routine is a no-op.
1899**
1900** When the locking level reaches NO_LOCK, delete the lock file.
1901*/
drh734c9862008-11-28 15:37:20 +00001902static int dotlockUnlock(sqlite3_file *id, int locktype) {
1903 unixFile *pFile = (unixFile*)id;
1904 char *zLockFile = (char *)pFile->lockingContext;
1905
1906 assert( pFile );
1907 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1908 pFile->locktype, getpid());
1909 assert( locktype<=SHARED_LOCK );
1910
1911 /* no-op if possible */
1912 if( pFile->locktype==locktype ){
1913 return SQLITE_OK;
1914 }
drh7708e972008-11-29 00:56:52 +00001915
1916 /* To downgrade to shared, simply update our internal notion of the
1917 ** lock state. No need to mess with the file on disk.
1918 */
1919 if( locktype==SHARED_LOCK ){
1920 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001921 return SQLITE_OK;
1922 }
1923
drh7708e972008-11-29 00:56:52 +00001924 /* To fully unlock the database, delete the lock file */
1925 assert( locktype==NO_LOCK );
1926 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001927 int rc = 0;
1928 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001929 if( ENOENT != tErrno ){
1930 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1931 }
1932 if( IS_LOCK_ERROR(rc) ){
1933 pFile->lastErrno = tErrno;
1934 }
1935 return rc;
1936 }
1937 pFile->locktype = NO_LOCK;
1938 return SQLITE_OK;
1939}
1940
1941/*
drh9b35ea62008-11-29 02:20:26 +00001942** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001943*/
1944static int dotlockClose(sqlite3_file *id) {
1945 int rc;
1946 if( id ){
1947 unixFile *pFile = (unixFile*)id;
1948 dotlockUnlock(id, NO_LOCK);
1949 sqlite3_free(pFile->lockingContext);
1950 }
drh734c9862008-11-28 15:37:20 +00001951 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001952 return rc;
1953}
1954/****************** End of the dot-file lock implementation *******************
1955******************************************************************************/
1956
1957/******************************************************************************
1958************************** Begin flock Locking ********************************
1959**
1960** Use the flock() system call to do file locking.
1961**
drh6b9d6dd2008-12-03 19:34:47 +00001962** flock() locking is like dot-file locking in that the various
1963** fine-grain locking levels supported by SQLite are collapsed into
1964** a single exclusive lock. In other words, SHARED, RESERVED, and
1965** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1966** still works when you do this, but concurrency is reduced since
1967** only a single process can be reading the database at a time.
1968**
drh734c9862008-11-28 15:37:20 +00001969** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1970** compiling for VXWORKS.
1971*/
1972#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001973
drh6b9d6dd2008-12-03 19:34:47 +00001974/*
1975** This routine checks if there is a RESERVED lock held on the specified
1976** file by this or any other process. If such a lock is held, set *pResOut
1977** to a non-zero value otherwise *pResOut is set to zero. The return value
1978** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1979*/
drh734c9862008-11-28 15:37:20 +00001980static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1981 int rc = SQLITE_OK;
1982 int reserved = 0;
1983 unixFile *pFile = (unixFile*)id;
1984
1985 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1986
1987 assert( pFile );
1988
1989 /* Check if a thread in this process holds such a lock */
1990 if( pFile->locktype>SHARED_LOCK ){
1991 reserved = 1;
1992 }
1993
1994 /* Otherwise see if some other process holds it. */
1995 if( !reserved ){
1996 /* attempt to get the lock */
1997 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1998 if( !lrc ){
1999 /* got the lock, unlock it */
2000 lrc = flock(pFile->h, LOCK_UN);
2001 if ( lrc ) {
2002 int tErrno = errno;
2003 /* unlock failed with an error */
2004 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2005 if( IS_LOCK_ERROR(lrc) ){
2006 pFile->lastErrno = tErrno;
2007 rc = lrc;
2008 }
2009 }
2010 } else {
2011 int tErrno = errno;
2012 reserved = 1;
2013 /* someone else might have it reserved */
2014 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2015 if( IS_LOCK_ERROR(lrc) ){
2016 pFile->lastErrno = tErrno;
2017 rc = lrc;
2018 }
2019 }
2020 }
2021 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2022
2023#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2024 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2025 rc = SQLITE_OK;
2026 reserved=1;
2027 }
2028#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2029 *pResOut = reserved;
2030 return rc;
2031}
2032
drh6b9d6dd2008-12-03 19:34:47 +00002033/*
2034** Lock the file with the lock specified by parameter locktype - one
2035** of the following:
2036**
2037** (1) SHARED_LOCK
2038** (2) RESERVED_LOCK
2039** (3) PENDING_LOCK
2040** (4) EXCLUSIVE_LOCK
2041**
2042** Sometimes when requesting one lock state, additional lock states
2043** are inserted in between. The locking might fail on one of the later
2044** transitions leaving the lock state different from what it started but
2045** still short of its goal. The following chart shows the allowed
2046** transitions and the inserted intermediate states:
2047**
2048** UNLOCKED -> SHARED
2049** SHARED -> RESERVED
2050** SHARED -> (PENDING) -> EXCLUSIVE
2051** RESERVED -> (PENDING) -> EXCLUSIVE
2052** PENDING -> EXCLUSIVE
2053**
2054** flock() only really support EXCLUSIVE locks. We track intermediate
2055** lock states in the sqlite3_file structure, but all locks SHARED or
2056** above are really EXCLUSIVE locks and exclude all other processes from
2057** access the file.
2058**
2059** This routine will only increase a lock. Use the sqlite3OsUnlock()
2060** routine to lower a locking level.
2061*/
drh734c9862008-11-28 15:37:20 +00002062static int flockLock(sqlite3_file *id, int locktype) {
2063 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002064 unixFile *pFile = (unixFile*)id;
2065
2066 assert( pFile );
2067
2068 /* if we already have a lock, it is exclusive.
2069 ** Just adjust level and punt on outta here. */
2070 if (pFile->locktype > NO_LOCK) {
2071 pFile->locktype = locktype;
2072 return SQLITE_OK;
2073 }
2074
2075 /* grab an exclusive lock */
2076
2077 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
2078 int tErrno = errno;
2079 /* didn't get, must be busy */
2080 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2081 if( IS_LOCK_ERROR(rc) ){
2082 pFile->lastErrno = tErrno;
2083 }
2084 } else {
2085 /* got it, set the type and return ok */
2086 pFile->locktype = locktype;
2087 }
2088 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
2089 rc==SQLITE_OK ? "ok" : "failed");
2090#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2091 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2092 rc = SQLITE_BUSY;
2093 }
2094#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2095 return rc;
2096}
2097
drh6b9d6dd2008-12-03 19:34:47 +00002098
2099/*
2100** Lower the locking level on file descriptor pFile to locktype. locktype
2101** must be either NO_LOCK or SHARED_LOCK.
2102**
2103** If the locking level of the file descriptor is already at or below
2104** the requested locking level, this routine is a no-op.
2105*/
drh734c9862008-11-28 15:37:20 +00002106static int flockUnlock(sqlite3_file *id, int locktype) {
2107 unixFile *pFile = (unixFile*)id;
2108
2109 assert( pFile );
2110 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2111 pFile->locktype, getpid());
2112 assert( locktype<=SHARED_LOCK );
2113
2114 /* no-op if possible */
2115 if( pFile->locktype==locktype ){
2116 return SQLITE_OK;
2117 }
2118
2119 /* shared can just be set because we always have an exclusive */
2120 if (locktype==SHARED_LOCK) {
2121 pFile->locktype = locktype;
2122 return SQLITE_OK;
2123 }
2124
2125 /* no, really, unlock. */
2126 int rc = flock(pFile->h, LOCK_UN);
2127 if (rc) {
2128 int r, tErrno = errno;
2129 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2130 if( IS_LOCK_ERROR(r) ){
2131 pFile->lastErrno = tErrno;
2132 }
2133#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2134 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2135 r = SQLITE_BUSY;
2136 }
2137#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2138
2139 return r;
2140 } else {
2141 pFile->locktype = NO_LOCK;
2142 return SQLITE_OK;
2143 }
2144}
2145
2146/*
2147** Close a file.
2148*/
2149static int flockClose(sqlite3_file *id) {
2150 if( id ){
2151 flockUnlock(id, NO_LOCK);
2152 }
2153 return closeUnixFile(id);
2154}
2155
2156#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2157
2158/******************* End of the flock lock implementation *********************
2159******************************************************************************/
2160
2161/******************************************************************************
2162************************ Begin Named Semaphore Locking ************************
2163**
2164** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002165**
2166** Semaphore locking is like dot-lock and flock in that it really only
2167** supports EXCLUSIVE locking. Only a single process can read or write
2168** the database file at a time. This reduces potential concurrency, but
2169** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002170*/
2171#if OS_VXWORKS
2172
drh6b9d6dd2008-12-03 19:34:47 +00002173/*
2174** This routine checks if there is a RESERVED lock held on the specified
2175** file by this or any other process. If such a lock is held, set *pResOut
2176** to a non-zero value otherwise *pResOut is set to zero. The return value
2177** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2178*/
drh734c9862008-11-28 15:37:20 +00002179static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2180 int rc = SQLITE_OK;
2181 int reserved = 0;
2182 unixFile *pFile = (unixFile*)id;
2183
2184 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2185
2186 assert( pFile );
2187
2188 /* Check if a thread in this process holds such a lock */
2189 if( pFile->locktype>SHARED_LOCK ){
2190 reserved = 1;
2191 }
2192
2193 /* Otherwise see if some other process holds it. */
2194 if( !reserved ){
2195 sem_t *pSem = pFile->pOpen->pSem;
2196 struct stat statBuf;
2197
2198 if( sem_trywait(pSem)==-1 ){
2199 int tErrno = errno;
2200 if( EAGAIN != tErrno ){
2201 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2202 pFile->lastErrno = tErrno;
2203 } else {
2204 /* someone else has the lock when we are in NO_LOCK */
2205 reserved = (pFile->locktype < SHARED_LOCK);
2206 }
2207 }else{
2208 /* we could have it if we want it */
2209 sem_post(pSem);
2210 }
2211 }
2212 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2213
2214 *pResOut = reserved;
2215 return rc;
2216}
2217
drh6b9d6dd2008-12-03 19:34:47 +00002218/*
2219** Lock the file with the lock specified by parameter locktype - one
2220** of the following:
2221**
2222** (1) SHARED_LOCK
2223** (2) RESERVED_LOCK
2224** (3) PENDING_LOCK
2225** (4) EXCLUSIVE_LOCK
2226**
2227** Sometimes when requesting one lock state, additional lock states
2228** are inserted in between. The locking might fail on one of the later
2229** transitions leaving the lock state different from what it started but
2230** still short of its goal. The following chart shows the allowed
2231** transitions and the inserted intermediate states:
2232**
2233** UNLOCKED -> SHARED
2234** SHARED -> RESERVED
2235** SHARED -> (PENDING) -> EXCLUSIVE
2236** RESERVED -> (PENDING) -> EXCLUSIVE
2237** PENDING -> EXCLUSIVE
2238**
2239** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2240** lock states in the sqlite3_file structure, but all locks SHARED or
2241** above are really EXCLUSIVE locks and exclude all other processes from
2242** access the file.
2243**
2244** This routine will only increase a lock. Use the sqlite3OsUnlock()
2245** routine to lower a locking level.
2246*/
drh734c9862008-11-28 15:37:20 +00002247static int semLock(sqlite3_file *id, int locktype) {
2248 unixFile *pFile = (unixFile*)id;
2249 int fd;
2250 sem_t *pSem = pFile->pOpen->pSem;
2251 int rc = SQLITE_OK;
2252
2253 /* if we already have a lock, it is exclusive.
2254 ** Just adjust level and punt on outta here. */
2255 if (pFile->locktype > NO_LOCK) {
2256 pFile->locktype = locktype;
2257 rc = SQLITE_OK;
2258 goto sem_end_lock;
2259 }
2260
2261 /* lock semaphore now but bail out when already locked. */
2262 if( sem_trywait(pSem)==-1 ){
2263 rc = SQLITE_BUSY;
2264 goto sem_end_lock;
2265 }
2266
2267 /* got it, set the type and return ok */
2268 pFile->locktype = locktype;
2269
2270 sem_end_lock:
2271 return rc;
2272}
2273
drh6b9d6dd2008-12-03 19:34:47 +00002274/*
2275** Lower the locking level on file descriptor pFile to locktype. locktype
2276** must be either NO_LOCK or SHARED_LOCK.
2277**
2278** If the locking level of the file descriptor is already at or below
2279** the requested locking level, this routine is a no-op.
2280*/
drh734c9862008-11-28 15:37:20 +00002281static int semUnlock(sqlite3_file *id, int locktype) {
2282 unixFile *pFile = (unixFile*)id;
2283 sem_t *pSem = pFile->pOpen->pSem;
2284
2285 assert( pFile );
2286 assert( pSem );
2287 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2288 pFile->locktype, getpid());
2289 assert( locktype<=SHARED_LOCK );
2290
2291 /* no-op if possible */
2292 if( pFile->locktype==locktype ){
2293 return SQLITE_OK;
2294 }
2295
2296 /* shared can just be set because we always have an exclusive */
2297 if (locktype==SHARED_LOCK) {
2298 pFile->locktype = locktype;
2299 return SQLITE_OK;
2300 }
2301
2302 /* no, really unlock. */
2303 if ( sem_post(pSem)==-1 ) {
2304 int rc, tErrno = errno;
2305 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2306 if( IS_LOCK_ERROR(rc) ){
2307 pFile->lastErrno = tErrno;
2308 }
2309 return rc;
2310 }
2311 pFile->locktype = NO_LOCK;
2312 return SQLITE_OK;
2313}
2314
2315/*
2316 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002317 */
drh734c9862008-11-28 15:37:20 +00002318static int semClose(sqlite3_file *id) {
2319 if( id ){
2320 unixFile *pFile = (unixFile*)id;
2321 semUnlock(id, NO_LOCK);
2322 assert( pFile );
2323 unixEnterMutex();
2324 releaseLockInfo(pFile->pLock);
2325 releaseOpenCnt(pFile->pOpen);
drh734c9862008-11-28 15:37:20 +00002326 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002327 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002328 }
2329 return SQLITE_OK;
2330}
2331
2332#endif /* OS_VXWORKS */
2333/*
2334** Named semaphore locking is only available on VxWorks.
2335**
2336*************** End of the named semaphore lock implementation ****************
2337******************************************************************************/
2338
2339
2340/******************************************************************************
2341*************************** Begin AFP Locking *********************************
2342**
2343** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2344** on Apple Macintosh computers - both OS9 and OSX.
2345**
2346** Third-party implementations of AFP are available. But this code here
2347** only works on OSX.
2348*/
2349
drhd2cb50b2009-01-09 21:41:17 +00002350#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002351/*
2352** The afpLockingContext structure contains all afp lock specific state
2353*/
drhbfe66312006-10-03 17:40:40 +00002354typedef struct afpLockingContext afpLockingContext;
2355struct afpLockingContext {
aswiftaebf4132008-11-21 00:10:35 +00002356 unsigned long long sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002357 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002358};
2359
2360struct ByteRangeLockPB2
2361{
2362 unsigned long long offset; /* offset to first byte to lock */
2363 unsigned long long length; /* nbr of bytes to lock */
2364 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2365 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2366 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2367 int fd; /* file desc to assoc this lock with */
2368};
2369
drhfd131da2007-08-07 17:13:03 +00002370#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002371
drh6b9d6dd2008-12-03 19:34:47 +00002372/*
2373** This is a utility for setting or clearing a bit-range lock on an
2374** AFP filesystem.
2375**
2376** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2377*/
2378static int afpSetLock(
2379 const char *path, /* Name of the file to be locked or unlocked */
2380 unixFile *pFile, /* Open file descriptor on path */
2381 unsigned long long offset, /* First byte to be locked */
2382 unsigned long long length, /* Number of bytes to lock */
2383 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002384){
drh6b9d6dd2008-12-03 19:34:47 +00002385 struct ByteRangeLockPB2 pb;
2386 int err;
drhbfe66312006-10-03 17:40:40 +00002387
2388 pb.unLockFlag = setLockFlag ? 0 : 1;
2389 pb.startEndFlag = 0;
2390 pb.offset = offset;
2391 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002392 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002393
2394 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002395 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2396 offset, length);
drhbfe66312006-10-03 17:40:40 +00002397 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2398 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002399 int rc;
2400 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002401 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2402 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002403#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2404 rc = SQLITE_BUSY;
2405#else
drh734c9862008-11-28 15:37:20 +00002406 rc = sqliteErrorFromPosixError(tErrno,
2407 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002408#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002409 if( IS_LOCK_ERROR(rc) ){
2410 pFile->lastErrno = tErrno;
2411 }
2412 return rc;
drhbfe66312006-10-03 17:40:40 +00002413 } else {
aswift5b1a2562008-08-22 00:22:35 +00002414 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002415 }
2416}
2417
drh6b9d6dd2008-12-03 19:34:47 +00002418/*
2419** This routine checks if there is a RESERVED lock held on the specified
2420** file by this or any other process. If such a lock is held, set *pResOut
2421** to a non-zero value otherwise *pResOut is set to zero. The return value
2422** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2423*/
danielk1977e339d652008-06-28 11:23:00 +00002424static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002425 int rc = SQLITE_OK;
2426 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002427 unixFile *pFile = (unixFile*)id;
2428
aswift5b1a2562008-08-22 00:22:35 +00002429 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2430
2431 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002432 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2433
2434 /* Check if a thread in this process holds such a lock */
2435 if( pFile->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002436 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002437 }
2438
2439 /* Otherwise see if some other process holds it.
2440 */
aswift5b1a2562008-08-22 00:22:35 +00002441 if( !reserved ){
2442 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002443 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002444 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002445 /* if we succeeded in taking the reserved lock, unlock it to restore
2446 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002447 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002448 } else {
2449 /* if we failed to get the lock then someone else must have it */
2450 reserved = 1;
2451 }
2452 if( IS_LOCK_ERROR(lrc) ){
2453 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002454 }
2455 }
drhbfe66312006-10-03 17:40:40 +00002456
aswift5b1a2562008-08-22 00:22:35 +00002457 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2458
2459 *pResOut = reserved;
2460 return rc;
drhbfe66312006-10-03 17:40:40 +00002461}
2462
drh6b9d6dd2008-12-03 19:34:47 +00002463/*
2464** Lock the file with the lock specified by parameter locktype - one
2465** of the following:
2466**
2467** (1) SHARED_LOCK
2468** (2) RESERVED_LOCK
2469** (3) PENDING_LOCK
2470** (4) EXCLUSIVE_LOCK
2471**
2472** Sometimes when requesting one lock state, additional lock states
2473** are inserted in between. The locking might fail on one of the later
2474** transitions leaving the lock state different from what it started but
2475** still short of its goal. The following chart shows the allowed
2476** transitions and the inserted intermediate states:
2477**
2478** UNLOCKED -> SHARED
2479** SHARED -> RESERVED
2480** SHARED -> (PENDING) -> EXCLUSIVE
2481** RESERVED -> (PENDING) -> EXCLUSIVE
2482** PENDING -> EXCLUSIVE
2483**
2484** This routine will only increase a lock. Use the sqlite3OsUnlock()
2485** routine to lower a locking level.
2486*/
danielk1977e339d652008-06-28 11:23:00 +00002487static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002488 int rc = SQLITE_OK;
2489 unixFile *pFile = (unixFile*)id;
2490 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002491
2492 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002493 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00002494 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
2495
drhbfe66312006-10-03 17:40:40 +00002496 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002497 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002498 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002499 */
drhbfe66312006-10-03 17:40:40 +00002500 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00002501 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002502 locktypeName(locktype));
2503 return SQLITE_OK;
2504 }
2505
2506 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00002507 */
drhbfe66312006-10-03 17:40:40 +00002508 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2509 assert( locktype!=PENDING_LOCK );
2510 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2511
2512 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002513 */
drh6c7d5c52008-11-21 20:32:33 +00002514 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002515
2516 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002517 */
drhbfe66312006-10-03 17:40:40 +00002518 rc = transferOwnership(pFile);
2519 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002520 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002521 return rc;
2522 }
2523
2524 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002525 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2526 ** be released.
2527 */
drhbfe66312006-10-03 17:40:40 +00002528 if( locktype==SHARED_LOCK
2529 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002530 ){
2531 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002532 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002533 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002534 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002535 goto afp_end_lock;
2536 }
2537 }
2538
2539 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002540 ** operating system calls for the specified lock.
2541 */
drhbfe66312006-10-03 17:40:40 +00002542 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002543 int lk, lrc1, lrc2, lrc1Errno;
drhbfe66312006-10-03 17:40:40 +00002544
aswift5b1a2562008-08-22 00:22:35 +00002545 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002546 /* note that the quality of the randomness doesn't matter that much */
2547 lk = random();
aswiftaebf4132008-11-21 00:10:35 +00002548 context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002549 lrc1 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002550 SHARED_FIRST+context->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002551 if( IS_LOCK_ERROR(lrc1) ){
2552 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002553 }
aswift5b1a2562008-08-22 00:22:35 +00002554 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002555 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002556
aswift5b1a2562008-08-22 00:22:35 +00002557 if( IS_LOCK_ERROR(lrc1) ) {
2558 pFile->lastErrno = lrc1Errno;
2559 rc = lrc1;
2560 goto afp_end_lock;
2561 } else if( IS_LOCK_ERROR(lrc2) ){
2562 rc = lrc2;
2563 goto afp_end_lock;
2564 } else if( lrc1 != SQLITE_OK ) {
2565 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002566 } else {
2567 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002568 pFile->pOpen->nLock++;
drhbfe66312006-10-03 17:40:40 +00002569 }
2570 }else{
2571 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2572 ** assumed that there is a SHARED or greater lock on the file
2573 ** already.
2574 */
2575 int failed = 0;
2576 assert( 0!=pFile->locktype );
2577 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2578 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002579 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drhbfe66312006-10-03 17:40:40 +00002580 }
2581 if (!failed && locktype == EXCLUSIVE_LOCK) {
2582 /* Acquire an EXCLUSIVE lock */
2583
2584 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002585 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002586 */
drh6b9d6dd2008-12-03 19:34:47 +00002587 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
aswiftaebf4132008-11-21 00:10:35 +00002588 context->sharedByte, 1, 0)) ){
2589 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002590 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002591 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002592 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002593 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002594 SHARED_FIRST + context->sharedByte, 1, 1)) ){
2595 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2596 ** a critical I/O error
2597 */
2598 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2599 SQLITE_IOERR_LOCK;
2600 goto afp_end_lock;
2601 }
2602 }else{
aswift5b1a2562008-08-22 00:22:35 +00002603 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002604 }
2605 }
aswift5b1a2562008-08-22 00:22:35 +00002606 if( failed ){
2607 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002608 }
2609 }
2610
2611 if( rc==SQLITE_OK ){
2612 pFile->locktype = locktype;
2613 }else if( locktype==EXCLUSIVE_LOCK ){
2614 pFile->locktype = PENDING_LOCK;
2615 }
2616
2617afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002618 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00002619 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002620 rc==SQLITE_OK ? "ok" : "failed");
2621 return rc;
2622}
2623
2624/*
drh339eb0b2008-03-07 15:34:11 +00002625** Lower the locking level on file descriptor pFile to locktype. locktype
2626** must be either NO_LOCK or SHARED_LOCK.
2627**
2628** If the locking level of the file descriptor is already at or below
2629** the requested locking level, this routine is a no-op.
2630*/
danielk1977e339d652008-06-28 11:23:00 +00002631static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002632 int rc = SQLITE_OK;
2633 unixFile *pFile = (unixFile*)id;
aswiftaebf4132008-11-21 00:10:35 +00002634 afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002635
2636 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002637 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00002638 pFile->locktype, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002639
drhbfe66312006-10-03 17:40:40 +00002640 assert( locktype<=SHARED_LOCK );
2641 if( pFile->locktype<=locktype ){
2642 return SQLITE_OK;
2643 }
2644 if( CHECK_THREADID(pFile) ){
2645 return SQLITE_MISUSE;
2646 }
drh6c7d5c52008-11-21 20:32:33 +00002647 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002648 if( pFile->locktype>SHARED_LOCK ){
aswiftaebf4132008-11-21 00:10:35 +00002649
2650 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002651 rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
aswiftaebf4132008-11-21 00:10:35 +00002652 if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
2653 /* only re-establish the shared lock if necessary */
2654 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002655 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
aswiftaebf4132008-11-21 00:10:35 +00002656 }
2657 }
2658 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002659 rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002660 }
2661 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002662 rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002663 }
2664 }else if( locktype==NO_LOCK ){
2665 /* clear the shared lock */
2666 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002667 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002668 }
drhbfe66312006-10-03 17:40:40 +00002669
aswiftaebf4132008-11-21 00:10:35 +00002670 if( rc==SQLITE_OK ){
2671 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00002672 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002673 pOpen->nLock--;
2674 assert( pOpen->nLock>=0 );
dan6aa657f2009-08-24 18:57:58 +00002675 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002676 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002677 }
2678 }
drhbfe66312006-10-03 17:40:40 +00002679 }
drh6c7d5c52008-11-21 20:32:33 +00002680 unixLeaveMutex();
dan08da86a2009-08-21 17:18:03 +00002681 if( rc==SQLITE_OK ){
2682 pFile->locktype = locktype;
2683 }
drhbfe66312006-10-03 17:40:40 +00002684 return rc;
2685}
2686
2687/*
drh339eb0b2008-03-07 15:34:11 +00002688** Close a file & cleanup AFP specific locking context
2689*/
danielk1977e339d652008-06-28 11:23:00 +00002690static int afpClose(sqlite3_file *id) {
2691 if( id ){
2692 unixFile *pFile = (unixFile*)id;
2693 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002694 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002695 if( pFile->pOpen && pFile->pOpen->nLock ){
2696 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002697 ** yet because that would clear those locks. Instead, add the file
2698 ** descriptor to pOpen->aPending. It will be automatically closed when
2699 ** the last lock is cleared.
2700 */
dan08da86a2009-08-21 17:18:03 +00002701 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002702 }
2703 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002704 sqlite3_free(pFile->lockingContext);
aswiftaebf4132008-11-21 00:10:35 +00002705 closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002706 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002707 }
aswiftaebf4132008-11-21 00:10:35 +00002708 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002709}
2710
drhd2cb50b2009-01-09 21:41:17 +00002711#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002712/*
2713** The code above is the AFP lock implementation. The code is specific
2714** to MacOSX and does not work on other unix platforms. No alternative
2715** is available. If you don't compile for a mac, then the "unix-afp"
2716** VFS is not available.
2717**
2718********************* End of the AFP lock implementation **********************
2719******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002720
drh734c9862008-11-28 15:37:20 +00002721
2722/******************************************************************************
2723**************** Non-locking sqlite3_file methods *****************************
2724**
2725** The next division contains implementations for all methods of the
2726** sqlite3_file object other than the locking methods. The locking
2727** methods were defined in divisions above (one locking method per
2728** division). Those methods that are common to all locking modes
2729** are gather together into this division.
2730*/
drhbfe66312006-10-03 17:40:40 +00002731
2732/*
drh734c9862008-11-28 15:37:20 +00002733** Seek to the offset passed as the second argument, then read cnt
2734** bytes into pBuf. Return the number of bytes actually read.
2735**
2736** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2737** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2738** one system to another. Since SQLite does not define USE_PREAD
2739** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2740** See tickets #2741 and #2681.
2741**
2742** To avoid stomping the errno value on a failed read the lastErrno value
2743** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002744*/
drh734c9862008-11-28 15:37:20 +00002745static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2746 int got;
2747 i64 newOffset;
2748 TIMER_START;
2749#if defined(USE_PREAD)
2750 got = pread(id->h, pBuf, cnt, offset);
2751 SimulateIOError( got = -1 );
2752#elif defined(USE_PREAD64)
2753 got = pread64(id->h, pBuf, cnt, offset);
2754 SimulateIOError( got = -1 );
2755#else
2756 newOffset = lseek(id->h, offset, SEEK_SET);
2757 SimulateIOError( newOffset-- );
2758 if( newOffset!=offset ){
2759 if( newOffset == -1 ){
2760 ((unixFile*)id)->lastErrno = errno;
2761 }else{
2762 ((unixFile*)id)->lastErrno = 0;
2763 }
2764 return -1;
2765 }
2766 got = read(id->h, pBuf, cnt);
2767#endif
2768 TIMER_END;
2769 if( got<0 ){
2770 ((unixFile*)id)->lastErrno = errno;
2771 }
2772 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2773 return got;
drhbfe66312006-10-03 17:40:40 +00002774}
2775
2776/*
drh734c9862008-11-28 15:37:20 +00002777** Read data from a file into a buffer. Return SQLITE_OK if all
2778** bytes were read successfully and SQLITE_IOERR if anything goes
2779** wrong.
drh339eb0b2008-03-07 15:34:11 +00002780*/
drh734c9862008-11-28 15:37:20 +00002781static int unixRead(
2782 sqlite3_file *id,
2783 void *pBuf,
2784 int amt,
2785 sqlite3_int64 offset
2786){
dan08da86a2009-08-21 17:18:03 +00002787 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002788 int got;
2789 assert( id );
drh08c6d442009-02-09 17:34:07 +00002790
dan08da86a2009-08-21 17:18:03 +00002791 /* If this is a database file (not a journal, master-journal or temp
2792 ** file), the bytes in the locking range should never be read or written. */
dane946c392009-08-22 11:39:46 +00002793 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002794 || offset>=PENDING_BYTE+512
2795 || offset+amt<=PENDING_BYTE
2796 );
drh08c6d442009-02-09 17:34:07 +00002797
dan08da86a2009-08-21 17:18:03 +00002798 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002799 if( got==amt ){
2800 return SQLITE_OK;
2801 }else if( got<0 ){
2802 /* lastErrno set by seekAndRead */
2803 return SQLITE_IOERR_READ;
2804 }else{
dan08da86a2009-08-21 17:18:03 +00002805 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002806 /* Unread parts of the buffer must be zero-filled */
2807 memset(&((char*)pBuf)[got], 0, amt-got);
2808 return SQLITE_IOERR_SHORT_READ;
2809 }
2810}
2811
2812/*
2813** Seek to the offset in id->offset then read cnt bytes into pBuf.
2814** Return the number of bytes actually read. Update the offset.
2815**
2816** To avoid stomping the errno value on a failed write the lastErrno value
2817** is set before returning.
2818*/
2819static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2820 int got;
2821 i64 newOffset;
2822 TIMER_START;
2823#if defined(USE_PREAD)
2824 got = pwrite(id->h, pBuf, cnt, offset);
2825#elif defined(USE_PREAD64)
2826 got = pwrite64(id->h, pBuf, cnt, offset);
2827#else
2828 newOffset = lseek(id->h, offset, SEEK_SET);
2829 if( newOffset!=offset ){
2830 if( newOffset == -1 ){
2831 ((unixFile*)id)->lastErrno = errno;
2832 }else{
2833 ((unixFile*)id)->lastErrno = 0;
2834 }
2835 return -1;
2836 }
2837 got = write(id->h, pBuf, cnt);
2838#endif
2839 TIMER_END;
2840 if( got<0 ){
2841 ((unixFile*)id)->lastErrno = errno;
2842 }
2843
2844 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2845 return got;
2846}
2847
2848
2849/*
2850** Write data from a buffer into a file. Return SQLITE_OK on success
2851** or some other error code on failure.
2852*/
2853static int unixWrite(
2854 sqlite3_file *id,
2855 const void *pBuf,
2856 int amt,
2857 sqlite3_int64 offset
2858){
dan08da86a2009-08-21 17:18:03 +00002859 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002860 int wrote = 0;
2861 assert( id );
2862 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002863
dan08da86a2009-08-21 17:18:03 +00002864 /* If this is a database file (not a journal, master-journal or temp
2865 ** file), the bytes in the locking range should never be read or written. */
dane946c392009-08-22 11:39:46 +00002866 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002867 || offset>=PENDING_BYTE+512
2868 || offset+amt<=PENDING_BYTE
2869 );
drh08c6d442009-02-09 17:34:07 +00002870
drh8f941bc2009-01-14 23:03:40 +00002871#ifndef NDEBUG
2872 /* If we are doing a normal write to a database file (as opposed to
2873 ** doing a hot-journal rollback or a write to some file other than a
2874 ** normal database file) then record the fact that the database
2875 ** has changed. If the transaction counter is modified, record that
2876 ** fact too.
2877 */
dan08da86a2009-08-21 17:18:03 +00002878 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002879 pFile->dbUpdate = 1; /* The database has been modified */
2880 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002881 int rc;
drh8f941bc2009-01-14 23:03:40 +00002882 char oldCntr[4];
2883 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002884 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002885 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002886 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002887 pFile->transCntrChng = 1; /* The transaction counter has changed */
2888 }
2889 }
2890 }
2891#endif
2892
dan08da86a2009-08-21 17:18:03 +00002893 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002894 amt -= wrote;
2895 offset += wrote;
2896 pBuf = &((char*)pBuf)[wrote];
2897 }
2898 SimulateIOError(( wrote=(-1), amt=1 ));
2899 SimulateDiskfullError(( wrote=0, amt=1 ));
2900 if( amt>0 ){
2901 if( wrote<0 ){
2902 /* lastErrno set by seekAndWrite */
2903 return SQLITE_IOERR_WRITE;
2904 }else{
dan08da86a2009-08-21 17:18:03 +00002905 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002906 return SQLITE_FULL;
2907 }
2908 }
2909 return SQLITE_OK;
2910}
2911
2912#ifdef SQLITE_TEST
2913/*
2914** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002915** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002916*/
2917int sqlite3_sync_count = 0;
2918int sqlite3_fullsync_count = 0;
2919#endif
2920
2921/*
drh89240432009-03-25 01:06:01 +00002922** We do not trust systems to provide a working fdatasync(). Some do.
2923** Others do no. To be safe, we will stick with the (slower) fsync().
2924** If you know that your system does support fdatasync() correctly,
2925** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002926*/
drh89240432009-03-25 01:06:01 +00002927#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002928# define fdatasync fsync
2929#endif
2930
2931/*
2932** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2933** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2934** only available on Mac OS X. But that could change.
2935*/
2936#ifdef F_FULLFSYNC
2937# define HAVE_FULLFSYNC 1
2938#else
2939# define HAVE_FULLFSYNC 0
2940#endif
2941
2942
2943/*
2944** The fsync() system call does not work as advertised on many
2945** unix systems. The following procedure is an attempt to make
2946** it work better.
2947**
2948** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2949** for testing when we want to run through the test suite quickly.
2950** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2951** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2952** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002953**
2954** SQLite sets the dataOnly flag if the size of the file is unchanged.
2955** The idea behind dataOnly is that it should only write the file content
2956** to disk, not the inode. We only set dataOnly if the file size is
2957** unchanged since the file size is part of the inode. However,
2958** Ted Ts'o tells us that fdatasync() will also write the inode if the
2959** file size has changed. The only real difference between fdatasync()
2960** and fsync(), Ted tells us, is that fdatasync() will not flush the
2961** inode if the mtime or owner or other inode attributes have changed.
2962** We only care about the file size, not the other file attributes, so
2963** as far as SQLite is concerned, an fdatasync() is always adequate.
2964** So, we always use fdatasync() if it is available, regardless of
2965** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002966*/
2967static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002968 int rc;
drh734c9862008-11-28 15:37:20 +00002969
2970 /* The following "ifdef/elif/else/" block has the same structure as
2971 ** the one below. It is replicated here solely to avoid cluttering
2972 ** up the real code with the UNUSED_PARAMETER() macros.
2973 */
2974#ifdef SQLITE_NO_SYNC
2975 UNUSED_PARAMETER(fd);
2976 UNUSED_PARAMETER(fullSync);
2977 UNUSED_PARAMETER(dataOnly);
2978#elif HAVE_FULLFSYNC
2979 UNUSED_PARAMETER(dataOnly);
2980#else
2981 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002982 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002983#endif
2984
2985 /* Record the number of times that we do a normal fsync() and
2986 ** FULLSYNC. This is used during testing to verify that this procedure
2987 ** gets called with the correct arguments.
2988 */
2989#ifdef SQLITE_TEST
2990 if( fullSync ) sqlite3_fullsync_count++;
2991 sqlite3_sync_count++;
2992#endif
2993
2994 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2995 ** no-op
2996 */
2997#ifdef SQLITE_NO_SYNC
2998 rc = SQLITE_OK;
2999#elif HAVE_FULLFSYNC
3000 if( fullSync ){
3001 rc = fcntl(fd, F_FULLFSYNC, 0);
3002 }else{
3003 rc = 1;
3004 }
3005 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003006 ** It shouldn't be possible for fullfsync to fail on the local
3007 ** file system (on OSX), so failure indicates that FULLFSYNC
3008 ** isn't supported for this file system. So, attempt an fsync
3009 ** and (for now) ignore the overhead of a superfluous fcntl call.
3010 ** It'd be better to detect fullfsync support once and avoid
3011 ** the fcntl call every time sync is called.
3012 */
drh734c9862008-11-28 15:37:20 +00003013 if( rc ) rc = fsync(fd);
3014
3015#else
drh0b647ff2009-03-21 14:41:04 +00003016 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003017#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003018 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003019 rc = fsync(fd);
3020 }
drh0b647ff2009-03-21 14:41:04 +00003021#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003022#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3023
3024 if( OS_VXWORKS && rc!= -1 ){
3025 rc = 0;
3026 }
chw97185482008-11-17 08:05:31 +00003027 return rc;
drhbfe66312006-10-03 17:40:40 +00003028}
3029
drh734c9862008-11-28 15:37:20 +00003030/*
3031** Make sure all writes to a particular file are committed to disk.
3032**
3033** If dataOnly==0 then both the file itself and its metadata (file
3034** size, access time, etc) are synced. If dataOnly!=0 then only the
3035** file data is synced.
3036**
3037** Under Unix, also make sure that the directory entry for the file
3038** has been created by fsync-ing the directory that contains the file.
3039** If we do not do this and we encounter a power failure, the directory
3040** entry for the journal might not exist after we reboot. The next
3041** SQLite to access the file will not know that the journal exists (because
3042** the directory entry for the journal was never created) and the transaction
3043** will not roll back - possibly leading to database corruption.
3044*/
3045static int unixSync(sqlite3_file *id, int flags){
3046 int rc;
3047 unixFile *pFile = (unixFile*)id;
3048
3049 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3050 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3051
3052 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3053 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3054 || (flags&0x0F)==SQLITE_SYNC_FULL
3055 );
3056
3057 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3058 ** line is to test that doing so does not cause any problems.
3059 */
3060 SimulateDiskfullError( return SQLITE_FULL );
3061
3062 assert( pFile );
3063 OSTRACE2("SYNC %-3d\n", pFile->h);
3064 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3065 SimulateIOError( rc=1 );
3066 if( rc ){
3067 pFile->lastErrno = errno;
3068 return SQLITE_IOERR_FSYNC;
3069 }
3070 if( pFile->dirfd>=0 ){
3071 int err;
3072 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3073 HAVE_FULLFSYNC, isFullsync);
3074#ifndef SQLITE_DISABLE_DIRSYNC
3075 /* The directory sync is only attempted if full_fsync is
3076 ** turned off or unavailable. If a full_fsync occurred above,
3077 ** then the directory sync is superfluous.
3078 */
3079 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3080 /*
3081 ** We have received multiple reports of fsync() returning
3082 ** errors when applied to directories on certain file systems.
3083 ** A failed directory sync is not a big deal. So it seems
3084 ** better to ignore the error. Ticket #1657
3085 */
3086 /* pFile->lastErrno = errno; */
3087 /* return SQLITE_IOERR; */
3088 }
3089#endif
3090 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3091 if( err==0 ){ /* directory when we are done */
3092 pFile->dirfd = -1;
3093 }else{
3094 pFile->lastErrno = errno;
3095 rc = SQLITE_IOERR_DIR_CLOSE;
3096 }
3097 }
3098 return rc;
3099}
3100
3101/*
3102** Truncate an open file to a specified size
3103*/
3104static int unixTruncate(sqlite3_file *id, i64 nByte){
3105 int rc;
3106 assert( id );
3107 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3108 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3109 if( rc ){
3110 ((unixFile*)id)->lastErrno = errno;
3111 return SQLITE_IOERR_TRUNCATE;
3112 }else{
3113 return SQLITE_OK;
3114 }
3115}
3116
3117/*
3118** Determine the current size of a file in bytes
3119*/
3120static int unixFileSize(sqlite3_file *id, i64 *pSize){
3121 int rc;
3122 struct stat buf;
3123 assert( id );
3124 rc = fstat(((unixFile*)id)->h, &buf);
3125 SimulateIOError( rc=1 );
3126 if( rc!=0 ){
3127 ((unixFile*)id)->lastErrno = errno;
3128 return SQLITE_IOERR_FSTAT;
3129 }
3130 *pSize = buf.st_size;
3131
3132 /* When opening a zero-size database, the findLockInfo() procedure
3133 ** writes a single byte into that file in order to work around a bug
3134 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3135 ** layers, we need to report this file size as zero even though it is
3136 ** really 1. Ticket #3260.
3137 */
3138 if( *pSize==1 ) *pSize = 0;
3139
3140
3141 return SQLITE_OK;
3142}
3143
drhd2cb50b2009-01-09 21:41:17 +00003144#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003145/*
3146** Handler for proxy-locking file-control verbs. Defined below in the
3147** proxying locking division.
3148*/
3149static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003150#endif
drh715ff302008-12-03 22:32:44 +00003151
danielk1977ad94b582007-08-20 06:44:22 +00003152
danielk1977e3026632004-06-22 11:29:02 +00003153/*
drh9e33c2c2007-08-31 18:34:59 +00003154** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003155*/
drhcc6bb3e2007-08-31 16:11:35 +00003156static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003157 switch( op ){
3158 case SQLITE_FCNTL_LOCKSTATE: {
3159 *(int*)pArg = ((unixFile*)id)->locktype;
3160 return SQLITE_OK;
3161 }
drh7708e972008-11-29 00:56:52 +00003162 case SQLITE_LAST_ERRNO: {
3163 *(int*)pArg = ((unixFile*)id)->lastErrno;
3164 return SQLITE_OK;
3165 }
drh8f941bc2009-01-14 23:03:40 +00003166#ifndef NDEBUG
3167 /* The pager calls this method to signal that it has done
3168 ** a rollback and that the database is therefore unchanged and
3169 ** it hence it is OK for the transaction change counter to be
3170 ** unchanged.
3171 */
3172 case SQLITE_FCNTL_DB_UNCHANGED: {
3173 ((unixFile*)id)->dbUpdate = 0;
3174 return SQLITE_OK;
3175 }
3176#endif
drhd2cb50b2009-01-09 21:41:17 +00003177#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003178 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003179 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003180 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003181 }
drhd2cb50b2009-01-09 21:41:17 +00003182#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003183 }
drhcc6bb3e2007-08-31 16:11:35 +00003184 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003185}
3186
3187/*
danielk1977a3d4c882007-03-23 10:08:38 +00003188** Return the sector size in bytes of the underlying block device for
3189** the specified file. This is almost always 512 bytes, but may be
3190** larger for some devices.
3191**
3192** SQLite code assumes this function cannot fail. It also assumes that
3193** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003194** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003195** same for both.
3196*/
danielk1977397d65f2008-11-19 11:35:39 +00003197static int unixSectorSize(sqlite3_file *NotUsed){
3198 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003199 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003200}
3201
danielk197790949c22007-08-17 16:50:38 +00003202/*
danielk1977397d65f2008-11-19 11:35:39 +00003203** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003204*/
danielk1977397d65f2008-11-19 11:35:39 +00003205static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3206 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003207 return 0;
3208}
3209
drh734c9862008-11-28 15:37:20 +00003210/*
3211** Here ends the implementation of all sqlite3_file methods.
3212**
3213********************** End sqlite3_file Methods *******************************
3214******************************************************************************/
3215
3216/*
drh6b9d6dd2008-12-03 19:34:47 +00003217** This division contains definitions of sqlite3_io_methods objects that
3218** implement various file locking strategies. It also contains definitions
3219** of "finder" functions. A finder-function is used to locate the appropriate
3220** sqlite3_io_methods object for a particular database file. The pAppData
3221** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3222** the correct finder-function for that VFS.
3223**
3224** Most finder functions return a pointer to a fixed sqlite3_io_methods
3225** object. The only interesting finder-function is autolockIoFinder, which
3226** looks at the filesystem type and tries to guess the best locking
3227** strategy from that.
3228**
drh1875f7a2008-12-08 18:19:17 +00003229** For finder-funtion F, two objects are created:
3230**
3231** (1) The real finder-function named "FImpt()".
3232**
dane946c392009-08-22 11:39:46 +00003233** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003234**
3235**
3236** A pointer to the F pointer is used as the pAppData value for VFS
3237** objects. We have to do this instead of letting pAppData point
3238** directly at the finder-function since C90 rules prevent a void*
3239** from be cast into a function pointer.
3240**
drh6b9d6dd2008-12-03 19:34:47 +00003241**
drh7708e972008-11-29 00:56:52 +00003242** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003243**
drh7708e972008-11-29 00:56:52 +00003244** * A constant sqlite3_io_methods object call METHOD that has locking
3245** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3246**
3247** * An I/O method finder function called FINDER that returns a pointer
3248** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003249*/
drh7708e972008-11-29 00:56:52 +00003250#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3251static const sqlite3_io_methods METHOD = { \
3252 1, /* iVersion */ \
3253 CLOSE, /* xClose */ \
3254 unixRead, /* xRead */ \
3255 unixWrite, /* xWrite */ \
3256 unixTruncate, /* xTruncate */ \
3257 unixSync, /* xSync */ \
3258 unixFileSize, /* xFileSize */ \
3259 LOCK, /* xLock */ \
3260 UNLOCK, /* xUnlock */ \
3261 CKLOCK, /* xCheckReservedLock */ \
3262 unixFileControl, /* xFileControl */ \
3263 unixSectorSize, /* xSectorSize */ \
3264 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3265}; \
drh0c2694b2009-09-03 16:23:44 +00003266static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3267 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003268 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003269} \
drh0c2694b2009-09-03 16:23:44 +00003270static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003271 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003272
3273/*
3274** Here are all of the sqlite3_io_methods objects for each of the
3275** locking strategies. Functions that return pointers to these methods
3276** are also created.
3277*/
3278IOMETHODS(
3279 posixIoFinder, /* Finder function name */
3280 posixIoMethods, /* sqlite3_io_methods object name */
3281 unixClose, /* xClose method */
3282 unixLock, /* xLock method */
3283 unixUnlock, /* xUnlock method */
3284 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003285)
drh7708e972008-11-29 00:56:52 +00003286IOMETHODS(
3287 nolockIoFinder, /* Finder function name */
3288 nolockIoMethods, /* sqlite3_io_methods object name */
3289 nolockClose, /* xClose method */
3290 nolockLock, /* xLock method */
3291 nolockUnlock, /* xUnlock method */
3292 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003293)
drh7708e972008-11-29 00:56:52 +00003294IOMETHODS(
3295 dotlockIoFinder, /* Finder function name */
3296 dotlockIoMethods, /* sqlite3_io_methods object name */
3297 dotlockClose, /* xClose method */
3298 dotlockLock, /* xLock method */
3299 dotlockUnlock, /* xUnlock method */
3300 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003301)
drh7708e972008-11-29 00:56:52 +00003302
chw78a13182009-04-07 05:35:03 +00003303#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003304IOMETHODS(
3305 flockIoFinder, /* Finder function name */
3306 flockIoMethods, /* sqlite3_io_methods object name */
3307 flockClose, /* xClose method */
3308 flockLock, /* xLock method */
3309 flockUnlock, /* xUnlock method */
3310 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003311)
drh7708e972008-11-29 00:56:52 +00003312#endif
3313
drh6c7d5c52008-11-21 20:32:33 +00003314#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003315IOMETHODS(
3316 semIoFinder, /* Finder function name */
3317 semIoMethods, /* sqlite3_io_methods object name */
3318 semClose, /* xClose method */
3319 semLock, /* xLock method */
3320 semUnlock, /* xUnlock method */
3321 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003322)
aswiftaebf4132008-11-21 00:10:35 +00003323#endif
drh7708e972008-11-29 00:56:52 +00003324
drhd2cb50b2009-01-09 21:41:17 +00003325#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003326IOMETHODS(
3327 afpIoFinder, /* Finder function name */
3328 afpIoMethods, /* sqlite3_io_methods object name */
3329 afpClose, /* xClose method */
3330 afpLock, /* xLock method */
3331 afpUnlock, /* xUnlock method */
3332 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003333)
drh715ff302008-12-03 22:32:44 +00003334#endif
3335
3336/*
drh0c2694b2009-09-03 16:23:44 +00003337** The "Whole File Locking" finder returns the same set of methods as
3338** the posix locking finder. But it also sets the SQLITE_WHOLE_FILE_LOCKING
3339** flag to force the posix advisory locks to cover the whole file instead
3340** of just a small span of bytes near the 1GiB boundary. Whole File Locking
3341** is useful on NFS-mounted files since it helps NFS to maintain cache
3342** coherency. But it is a detriment to other filesystems since it runs
3343** slower.
3344*/
3345static const sqlite3_io_methods *posixWflIoFinderImpl(const char*z, unixFile*p){
3346 UNUSED_PARAMETER(z);
3347 p->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
3348 return &posixIoMethods;
3349}
3350static const sqlite3_io_methods
3351 *(*const posixWflIoFinder)(const char*,unixFile *p) = posixWflIoFinderImpl;
3352
3353/*
drh715ff302008-12-03 22:32:44 +00003354** The proxy locking method is a "super-method" in the sense that it
3355** opens secondary file descriptors for the conch and lock files and
3356** it uses proxy, dot-file, AFP, and flock() locking methods on those
3357** secondary files. For this reason, the division that implements
3358** proxy locking is located much further down in the file. But we need
3359** to go ahead and define the sqlite3_io_methods and finder function
3360** for proxy locking here. So we forward declare the I/O methods.
3361*/
drhd2cb50b2009-01-09 21:41:17 +00003362#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003363static int proxyClose(sqlite3_file*);
3364static int proxyLock(sqlite3_file*, int);
3365static int proxyUnlock(sqlite3_file*, int);
3366static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003367IOMETHODS(
3368 proxyIoFinder, /* Finder function name */
3369 proxyIoMethods, /* sqlite3_io_methods object name */
3370 proxyClose, /* xClose method */
3371 proxyLock, /* xLock method */
3372 proxyUnlock, /* xUnlock method */
3373 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003374)
aswiftaebf4132008-11-21 00:10:35 +00003375#endif
drh7708e972008-11-29 00:56:52 +00003376
3377
drhd2cb50b2009-01-09 21:41:17 +00003378#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003379/*
drh6b9d6dd2008-12-03 19:34:47 +00003380** This "finder" function attempts to determine the best locking strategy
3381** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003382** object that implements that strategy.
3383**
3384** This is for MacOSX only.
3385*/
drh1875f7a2008-12-08 18:19:17 +00003386static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003387 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003388 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00003389){
3390 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003391 const char *zFilesystem; /* Filesystem type name */
3392 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003393 } aMap[] = {
3394 { "hfs", &posixIoMethods },
3395 { "ufs", &posixIoMethods },
3396 { "afpfs", &afpIoMethods },
3397#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
3398 { "smbfs", &afpIoMethods },
3399#else
3400 { "smbfs", &flockIoMethods },
3401#endif
3402 { "webdav", &nolockIoMethods },
3403 { 0, 0 }
3404 };
3405 int i;
3406 struct statfs fsInfo;
3407 struct flock lockInfo;
3408
3409 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003410 /* If filePath==NULL that means we are dealing with a transient file
3411 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003412 return &nolockIoMethods;
3413 }
3414 if( statfs(filePath, &fsInfo) != -1 ){
3415 if( fsInfo.f_flags & MNT_RDONLY ){
3416 return &nolockIoMethods;
3417 }
3418 for(i=0; aMap[i].zFilesystem; i++){
3419 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3420 return aMap[i].pMethods;
3421 }
3422 }
3423 }
3424
3425 /* Default case. Handles, amongst others, "nfs".
3426 ** Test byte-range lock using fcntl(). If the call succeeds,
3427 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003428 */
drh7708e972008-11-29 00:56:52 +00003429 lockInfo.l_len = 1;
3430 lockInfo.l_start = 0;
3431 lockInfo.l_whence = SEEK_SET;
3432 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003433 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
3434 pNew->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
drh7708e972008-11-29 00:56:52 +00003435 return &posixIoMethods;
3436 }else{
3437 return &dotlockIoMethods;
3438 }
3439}
drh0c2694b2009-09-03 16:23:44 +00003440static const sqlite3_io_methods
3441 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00003442
drhd2cb50b2009-01-09 21:41:17 +00003443#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003444
chw78a13182009-04-07 05:35:03 +00003445#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
3446/*
3447** This "finder" function attempts to determine the best locking strategy
3448** for the database file "filePath". It then returns the sqlite3_io_methods
3449** object that implements that strategy.
3450**
3451** This is for VXWorks only.
3452*/
3453static const sqlite3_io_methods *autolockIoFinderImpl(
3454 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003455 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00003456){
3457 struct flock lockInfo;
3458
3459 if( !filePath ){
3460 /* If filePath==NULL that means we are dealing with a transient file
3461 ** that does not need to be locked. */
3462 return &nolockIoMethods;
3463 }
3464
3465 /* Test if fcntl() is supported and use POSIX style locks.
3466 ** Otherwise fall back to the named semaphore method.
3467 */
3468 lockInfo.l_len = 1;
3469 lockInfo.l_start = 0;
3470 lockInfo.l_whence = SEEK_SET;
3471 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003472 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00003473 return &posixIoMethods;
3474 }else{
3475 return &semIoMethods;
3476 }
3477}
drh0c2694b2009-09-03 16:23:44 +00003478static const sqlite3_io_methods
3479 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00003480
3481#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
3482
drh7708e972008-11-29 00:56:52 +00003483/*
3484** An abstract type for a pointer to a IO method finder function:
3485*/
drh0c2694b2009-09-03 16:23:44 +00003486typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00003487
aswiftaebf4132008-11-21 00:10:35 +00003488
drh734c9862008-11-28 15:37:20 +00003489/****************************************************************************
3490**************************** sqlite3_vfs methods ****************************
3491**
3492** This division contains the implementation of methods on the
3493** sqlite3_vfs object.
3494*/
3495
danielk1977a3d4c882007-03-23 10:08:38 +00003496/*
danielk1977e339d652008-06-28 11:23:00 +00003497** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003498*/
3499static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003500 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003501 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003502 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003503 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003504 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003505 int noLock, /* Omit locking if true */
3506 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003507){
drh7708e972008-11-29 00:56:52 +00003508 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003509 unixFile *pNew = (unixFile *)pId;
3510 int rc = SQLITE_OK;
3511
danielk197717b90b52008-06-06 11:11:25 +00003512 assert( pNew->pLock==NULL );
3513 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003514
dane946c392009-08-22 11:39:46 +00003515 /* Parameter isDelete is only used on vxworks. Express this explicitly
3516 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003517 */
drh7708e972008-11-29 00:56:52 +00003518 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00003519
drh218c5082008-03-07 00:27:10 +00003520 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003521 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003522 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003523 SET_THREADID(pNew);
drh0c2694b2009-09-03 16:23:44 +00003524 pNew->fileFlags = 0;
drh339eb0b2008-03-07 15:34:11 +00003525
drh6c7d5c52008-11-21 20:32:33 +00003526#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003527 pNew->pId = vxworksFindFileId(zFilename);
3528 if( pNew->pId==0 ){
3529 noLock = 1;
3530 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003531 }
3532#endif
3533
drhda0e7682008-07-30 15:27:54 +00003534 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003535 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003536 }else{
drh0c2694b2009-09-03 16:23:44 +00003537 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00003538#if SQLITE_ENABLE_LOCKING_STYLE
3539 /* Cache zFilename in the locking context (AFP and dotlock override) for
3540 ** proxyLock activation is possible (remote proxy is based on db name)
3541 ** zFilename remains valid until file is closed, to support */
3542 pNew->lockingContext = (void*)zFilename;
3543#endif
drhda0e7682008-07-30 15:27:54 +00003544 }
danielk1977e339d652008-06-28 11:23:00 +00003545
drh7708e972008-11-29 00:56:52 +00003546 if( pLockingStyle == &posixIoMethods ){
3547 unixEnterMutex();
3548 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
dane946c392009-08-22 11:39:46 +00003549 if( rc!=SQLITE_OK ){
3550 /* If an error occured in findLockInfo(), close the file descriptor
3551 ** immediately, before releasing the mutex. findLockInfo() may fail
3552 ** in two scenarios:
3553 **
3554 ** (a) A call to fstat() failed.
3555 ** (b) A malloc failed.
3556 **
3557 ** Scenario (b) may only occur if the process is holding no other
3558 ** file descriptors open on the same file. If there were other file
3559 ** descriptors on this file, then no malloc would be required by
3560 ** findLockInfo(). If this is the case, it is quite safe to close
3561 ** handle h - as it is guaranteed that no posix locks will be released
3562 ** by doing so.
3563 **
3564 ** If scenario (a) caused the error then things are not so safe. The
3565 ** implicit assumption here is that if fstat() fails, things are in
3566 ** such bad shape that dropping a lock or two doesn't matter much.
3567 */
3568 close(h);
3569 h = -1;
3570 }
drh7708e972008-11-29 00:56:52 +00003571 unixLeaveMutex();
3572 }
danielk1977e339d652008-06-28 11:23:00 +00003573
drhd2cb50b2009-01-09 21:41:17 +00003574#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003575 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003576 /* AFP locking uses the file path so it needs to be included in
3577 ** the afpLockingContext.
3578 */
3579 afpLockingContext *pCtx;
3580 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3581 if( pCtx==0 ){
3582 rc = SQLITE_NOMEM;
3583 }else{
3584 /* NB: zFilename exists and remains valid until the file is closed
3585 ** according to requirement F11141. So we do not need to make a
3586 ** copy of the filename. */
3587 pCtx->dbPath = zFilename;
3588 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003589 unixEnterMutex();
drh7708e972008-11-29 00:56:52 +00003590 rc = findLockInfo(pNew, NULL, &pNew->pOpen);
3591 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003592 }
drh7708e972008-11-29 00:56:52 +00003593 }
3594#endif
danielk1977e339d652008-06-28 11:23:00 +00003595
drh7708e972008-11-29 00:56:52 +00003596 else if( pLockingStyle == &dotlockIoMethods ){
3597 /* Dotfile locking uses the file path so it needs to be included in
3598 ** the dotlockLockingContext
3599 */
3600 char *zLockFile;
3601 int nFilename;
drhea678832008-12-10 19:26:22 +00003602 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003603 zLockFile = (char *)sqlite3_malloc(nFilename);
3604 if( zLockFile==0 ){
3605 rc = SQLITE_NOMEM;
3606 }else{
3607 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003608 }
drh7708e972008-11-29 00:56:52 +00003609 pNew->lockingContext = zLockFile;
3610 }
danielk1977e339d652008-06-28 11:23:00 +00003611
drh6c7d5c52008-11-21 20:32:33 +00003612#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003613 else if( pLockingStyle == &semIoMethods ){
3614 /* Named semaphore locking uses the file path so it needs to be
3615 ** included in the semLockingContext
3616 */
3617 unixEnterMutex();
3618 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3619 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3620 char *zSemName = pNew->pOpen->aSemName;
3621 int n;
drh2238dcc2009-08-27 17:56:20 +00003622 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00003623 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00003624 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00003625 if( zSemName[n]=='/' ) zSemName[n] = '_';
3626 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3627 if( pNew->pOpen->pSem == SEM_FAILED ){
3628 rc = SQLITE_NOMEM;
3629 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003630 }
chw97185482008-11-17 08:05:31 +00003631 }
drh7708e972008-11-29 00:56:52 +00003632 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003633 }
drh7708e972008-11-29 00:56:52 +00003634#endif
aswift5b1a2562008-08-22 00:22:35 +00003635
3636 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003637#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003638 if( rc!=SQLITE_OK ){
3639 unlink(zFilename);
3640 isDelete = 0;
3641 }
3642 pNew->isDelete = isDelete;
3643#endif
danielk1977e339d652008-06-28 11:23:00 +00003644 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003645 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00003646 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00003647 }else{
drh7708e972008-11-29 00:56:52 +00003648 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003649 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003650 }
danielk1977e339d652008-06-28 11:23:00 +00003651 return rc;
drh054889e2005-11-30 03:20:31 +00003652}
drh9c06c952005-11-26 00:25:00 +00003653
danielk1977ad94b582007-08-20 06:44:22 +00003654/*
3655** Open a file descriptor to the directory containing file zFilename.
3656** If successful, *pFd is set to the opened file descriptor and
3657** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3658** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3659** value.
3660**
3661** If SQLITE_OK is returned, the caller is responsible for closing
3662** the file descriptor *pFd using close().
3663*/
danielk1977fee2d252007-08-18 10:59:19 +00003664static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003665 int ii;
drh777b17a2007-09-20 10:02:54 +00003666 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003667 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003668
drh153c62c2007-08-24 03:51:33 +00003669 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003670 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003671 if( ii>0 ){
3672 zDirname[ii] = '\0';
3673 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003674 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003675#ifdef FD_CLOEXEC
3676 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3677#endif
3678 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3679 }
3680 }
danielk1977fee2d252007-08-18 10:59:19 +00003681 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00003682 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00003683}
3684
danielk1977b4b47412007-08-17 15:53:36 +00003685/*
danielk197717b90b52008-06-06 11:11:25 +00003686** Create a temporary file name in zBuf. zBuf must be allocated
3687** by the calling process and must be big enough to hold at least
3688** pVfs->mxPathname bytes.
3689*/
3690static int getTempname(int nBuf, char *zBuf){
3691 static const char *azDirs[] = {
3692 0,
aswiftaebf4132008-11-21 00:10:35 +00003693 0,
danielk197717b90b52008-06-06 11:11:25 +00003694 "/var/tmp",
3695 "/usr/tmp",
3696 "/tmp",
3697 ".",
3698 };
3699 static const unsigned char zChars[] =
3700 "abcdefghijklmnopqrstuvwxyz"
3701 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3702 "0123456789";
drh41022642008-11-21 00:24:42 +00003703 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003704 struct stat buf;
3705 const char *zDir = ".";
3706
3707 /* It's odd to simulate an io-error here, but really this is just
3708 ** using the io-error infrastructure to test that SQLite handles this
3709 ** function failing.
3710 */
3711 SimulateIOError( return SQLITE_IOERR );
3712
3713 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003714 if (NULL == azDirs[1]) {
3715 azDirs[1] = getenv("TMPDIR");
3716 }
3717
3718 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003719 if( azDirs[i]==0 ) continue;
3720 if( stat(azDirs[i], &buf) ) continue;
3721 if( !S_ISDIR(buf.st_mode) ) continue;
3722 if( access(azDirs[i], 07) ) continue;
3723 zDir = azDirs[i];
3724 break;
3725 }
3726
3727 /* Check that the output buffer is large enough for the temporary file
3728 ** name. If it is not, return SQLITE_ERROR.
3729 */
danielk197700e13612008-11-17 19:18:54 +00003730 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003731 return SQLITE_ERROR;
3732 }
3733
3734 do{
3735 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003736 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003737 sqlite3_randomness(15, &zBuf[j]);
3738 for(i=0; i<15; i++, j++){
3739 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3740 }
3741 zBuf[j] = 0;
3742 }while( access(zBuf,0)==0 );
3743 return SQLITE_OK;
3744}
3745
drhd2cb50b2009-01-09 21:41:17 +00003746#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003747/*
3748** Routine to transform a unixFile into a proxy-locking unixFile.
3749** Implementation in the proxy-lock division, but used by unixOpen()
3750** if SQLITE_PREFER_PROXY_LOCKING is defined.
3751*/
3752static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003753#endif
drhc66d5b62008-12-03 22:48:32 +00003754
dan08da86a2009-08-21 17:18:03 +00003755/*
3756** Search for an unused file descriptor that was opened on the database
3757** file (not a journal or master-journal file) identified by pathname
3758** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
3759** argument to this function.
3760**
3761** Such a file descriptor may exist if a database connection was closed
3762** but the associated file descriptor could not be closed because some
3763** other file descriptor open on the same file is holding a file-lock.
3764** Refer to comments in the unixClose() function and the lengthy comment
3765** describing "Posix Advisory Locking" at the start of this file for
3766** further details. Also, ticket #4018.
3767**
3768** If a suitable file descriptor is found, then it is returned. If no
3769** such file descriptor is located, -1 is returned.
3770*/
dane946c392009-08-22 11:39:46 +00003771static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
3772 UnixUnusedFd *pUnused = 0;
3773
3774 /* Do not search for an unused file descriptor on vxworks. Not because
3775 ** vxworks would not benefit from the change (it might, we're not sure),
3776 ** but because no way to test it is currently available. It is better
3777 ** not to risk breaking vxworks support for the sake of such an obscure
3778 ** feature. */
3779#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00003780 struct stat sStat; /* Results of stat() call */
3781
3782 /* A stat() call may fail for various reasons. If this happens, it is
3783 ** almost certain that an open() call on the same path will also fail.
3784 ** For this reason, if an error occurs in the stat() call here, it is
3785 ** ignored and -1 is returned. The caller will try to open a new file
3786 ** descriptor on the same path, fail, and return an error to SQLite.
3787 **
3788 ** Even if a subsequent open() call does succeed, the consequences of
3789 ** not searching for a resusable file descriptor are not dire. */
3790 if( 0==stat(zPath, &sStat) ){
dane946c392009-08-22 11:39:46 +00003791 struct unixOpenCnt *pO;
dan08da86a2009-08-21 17:18:03 +00003792 struct unixFileId id;
3793 id.dev = sStat.st_dev;
3794 id.ino = sStat.st_ino;
3795
3796 unixEnterMutex();
dane946c392009-08-22 11:39:46 +00003797 for(pO=openList; pO && memcmp(&id, &pO->fileId, sizeof(id)); pO=pO->pNext);
3798 if( pO ){
3799 UnixUnusedFd **pp;
3800 for(pp=&pO->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
3801 pUnused = *pp;
3802 if( pUnused ){
3803 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00003804 }
3805 }
3806 unixLeaveMutex();
3807 }
dane946c392009-08-22 11:39:46 +00003808#endif /* if !OS_VXWORKS */
3809 return pUnused;
dan08da86a2009-08-21 17:18:03 +00003810}
danielk197717b90b52008-06-06 11:11:25 +00003811
3812/*
danielk1977ad94b582007-08-20 06:44:22 +00003813** Open the file zPath.
3814**
danielk1977b4b47412007-08-17 15:53:36 +00003815** Previously, the SQLite OS layer used three functions in place of this
3816** one:
3817**
3818** sqlite3OsOpenReadWrite();
3819** sqlite3OsOpenReadOnly();
3820** sqlite3OsOpenExclusive();
3821**
3822** These calls correspond to the following combinations of flags:
3823**
3824** ReadWrite() -> (READWRITE | CREATE)
3825** ReadOnly() -> (READONLY)
3826** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
3827**
3828** The old OpenExclusive() accepted a boolean argument - "delFlag". If
3829** true, the file was configured to be automatically deleted when the
3830** file handle closed. To achieve the same effect using this new
3831** interface, add the DELETEONCLOSE flag to those specified above for
3832** OpenExclusive().
3833*/
3834static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00003835 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
3836 const char *zPath, /* Pathname of file to be opened */
3837 sqlite3_file *pFile, /* The file descriptor to be filled in */
3838 int flags, /* Input flags to control the opening */
3839 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00003840){
dan08da86a2009-08-21 17:18:03 +00003841 unixFile *p = (unixFile *)pFile;
3842 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00003843 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00003844 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00003845 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00003846 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00003847 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00003848
3849 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
3850 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
3851 int isCreate = (flags & SQLITE_OPEN_CREATE);
3852 int isReadonly = (flags & SQLITE_OPEN_READONLY);
3853 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
3854
danielk1977fee2d252007-08-18 10:59:19 +00003855 /* If creating a master or main-file journal, this function will open
3856 ** a file-descriptor on the directory too. The first time unixSync()
3857 ** is called the directory file descriptor will be fsync()ed and close()d.
3858 */
3859 int isOpenDirectory = (isCreate &&
3860 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
3861 );
3862
danielk197717b90b52008-06-06 11:11:25 +00003863 /* If argument zPath is a NULL pointer, this function is required to open
3864 ** a temporary file. Use this buffer to store the file name in.
3865 */
3866 char zTmpname[MAX_PATHNAME+1];
3867 const char *zName = zPath;
3868
danielk1977fee2d252007-08-18 10:59:19 +00003869 /* Check the following statements are true:
3870 **
3871 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
3872 ** (b) if CREATE is set, then READWRITE must also be set, and
3873 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00003874 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00003875 */
danielk1977b4b47412007-08-17 15:53:36 +00003876 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00003877 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00003878 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00003879 assert(isDelete==0 || isCreate);
3880
drh33f4e022007-09-03 15:19:34 +00003881 /* The main DB, main journal, and master journal are never automatically
dan08da86a2009-08-21 17:18:03 +00003882 ** deleted. Nor are they ever temporary files. */
3883 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
3884 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
3885 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danielk1977b4b47412007-08-17 15:53:36 +00003886
danielk1977fee2d252007-08-18 10:59:19 +00003887 /* Assert that the upper layer has set one of the "file-type" flags. */
3888 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
3889 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3890 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00003891 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00003892 );
3893
dan08da86a2009-08-21 17:18:03 +00003894 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00003895
dan08da86a2009-08-21 17:18:03 +00003896 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00003897 UnixUnusedFd *pUnused;
3898 pUnused = findReusableFd(zName, flags);
3899 if( pUnused ){
3900 fd = pUnused->fd;
3901 }else{
dan6aa657f2009-08-24 18:57:58 +00003902 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00003903 if( !pUnused ){
3904 return SQLITE_NOMEM;
3905 }
3906 }
3907 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00003908 }else if( !zName ){
3909 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00003910 assert(isDelete && !isOpenDirectory);
3911 rc = getTempname(MAX_PATHNAME+1, zTmpname);
3912 if( rc!=SQLITE_OK ){
3913 return rc;
3914 }
3915 zName = zTmpname;
3916 }
3917
dan08da86a2009-08-21 17:18:03 +00003918 /* Determine the value of the flags parameter passed to POSIX function
3919 ** open(). These must be calculated even if open() is not called, as
3920 ** they may be stored as part of the file handle and used by the
3921 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00003922 if( isReadonly ) openFlags |= O_RDONLY;
3923 if( isReadWrite ) openFlags |= O_RDWR;
3924 if( isCreate ) openFlags |= O_CREAT;
3925 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
3926 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00003927
danielk1977b4b47412007-08-17 15:53:36 +00003928 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00003929 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
3930 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00003931 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
3932 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
3933 /* Failed to open the file for read/write access. Try read-only. */
3934 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00003935 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00003936 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00003937 openFlags |= O_RDONLY;
3938 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00003939 }
3940 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00003941 rc = SQLITE_CANTOPEN;
3942 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00003943 }
danielk1977b4b47412007-08-17 15:53:36 +00003944 }
dan08da86a2009-08-21 17:18:03 +00003945 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00003946 if( pOutFlags ){
3947 *pOutFlags = flags;
3948 }
3949
dane946c392009-08-22 11:39:46 +00003950 if( p->pUnused ){
3951 p->pUnused->fd = fd;
3952 p->pUnused->flags = flags;
3953 }
3954
danielk1977b4b47412007-08-17 15:53:36 +00003955 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00003956#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003957 zPath = zName;
3958#else
danielk197717b90b52008-06-06 11:11:25 +00003959 unlink(zName);
chw97185482008-11-17 08:05:31 +00003960#endif
danielk1977b4b47412007-08-17 15:53:36 +00003961 }
drh41022642008-11-21 00:24:42 +00003962#if SQLITE_ENABLE_LOCKING_STYLE
3963 else{
dan08da86a2009-08-21 17:18:03 +00003964 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00003965 }
3966#endif
3967
danielk1977fee2d252007-08-18 10:59:19 +00003968 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00003969 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00003970 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00003971 /* It is safe to close fd at this point, because it is guaranteed not
3972 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00003973 ** it would not be safe to close as this would release any locks held
3974 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00003975 assert( eType!=SQLITE_OPEN_MAIN_DB );
3976 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00003977 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00003978 }
3979 }
danielk1977e339d652008-06-28 11:23:00 +00003980
3981#ifdef FD_CLOEXEC
3982 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3983#endif
3984
drhda0e7682008-07-30 15:27:54 +00003985 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00003986
3987#if SQLITE_PREFER_PROXY_LOCKING
dan15edd582009-08-25 05:57:47 +00003988 if( zPath!=NULL && !noLock && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00003989 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
3990 int useProxy = 0;
3991
dan08da86a2009-08-21 17:18:03 +00003992 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
3993 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00003994 if( envforce!=NULL ){
3995 useProxy = atoi(envforce)>0;
3996 }else{
3997 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00003998 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00003999 /* In theory, the close(fd) call is sub-optimal. If the file opened
4000 ** with fd is a database file, and there are other connections open
4001 ** on that file that are currently holding advisory locks on it,
4002 ** then the call to close() will cancel those locks. In practice,
4003 ** we're assuming that statfs() doesn't fail very often. At least
4004 ** not while other file descriptors opened by the same process on
4005 ** the same file are working. */
4006 p->lastErrno = errno;
4007 if( dirfd>=0 ){
4008 close(dirfd); /* silently leak if fail, in error */
4009 }
aswiftaebf4132008-11-21 00:10:35 +00004010 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004011 rc = SQLITE_IOERR_ACCESS;
4012 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004013 }
4014 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4015 }
4016 if( useProxy ){
4017 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4018 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004019 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
aswiftaebf4132008-11-21 00:10:35 +00004020 }
dane946c392009-08-22 11:39:46 +00004021 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004022 }
4023 }
4024#endif
4025
dane946c392009-08-22 11:39:46 +00004026 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4027open_finished:
4028 if( rc!=SQLITE_OK ){
4029 sqlite3_free(p->pUnused);
4030 }
4031 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004032}
4033
dane946c392009-08-22 11:39:46 +00004034
danielk1977b4b47412007-08-17 15:53:36 +00004035/*
danielk1977fee2d252007-08-18 10:59:19 +00004036** Delete the file at zPath. If the dirSync argument is true, fsync()
4037** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004038*/
drh6b9d6dd2008-12-03 19:34:47 +00004039static int unixDelete(
4040 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4041 const char *zPath, /* Name of file to be deleted */
4042 int dirSync /* If true, fsync() directory after deleting file */
4043){
danielk1977fee2d252007-08-18 10:59:19 +00004044 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004045 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004046 SimulateIOError(return SQLITE_IOERR_DELETE);
4047 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00004048#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004049 if( dirSync ){
4050 int fd;
4051 rc = openDirectory(zPath, &fd);
4052 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004053#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004054 if( fsync(fd)==-1 )
4055#else
4056 if( fsync(fd) )
4057#endif
4058 {
danielk1977fee2d252007-08-18 10:59:19 +00004059 rc = SQLITE_IOERR_DIR_FSYNC;
4060 }
aswiftaebf4132008-11-21 00:10:35 +00004061 if( close(fd)&&!rc ){
4062 rc = SQLITE_IOERR_DIR_CLOSE;
4063 }
danielk1977fee2d252007-08-18 10:59:19 +00004064 }
4065 }
danielk1977d138dd82008-10-15 16:02:48 +00004066#endif
danielk1977fee2d252007-08-18 10:59:19 +00004067 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004068}
4069
danielk197790949c22007-08-17 16:50:38 +00004070/*
4071** Test the existance of or access permissions of file zPath. The
4072** test performed depends on the value of flags:
4073**
4074** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4075** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4076** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4077**
4078** Otherwise return 0.
4079*/
danielk1977861f7452008-06-05 11:39:11 +00004080static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004081 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4082 const char *zPath, /* Path of the file to examine */
4083 int flags, /* What do we want to learn about the zPath file? */
4084 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004085){
rse25c0d1a2007-09-20 08:38:14 +00004086 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004087 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004088 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004089 switch( flags ){
4090 case SQLITE_ACCESS_EXISTS:
4091 amode = F_OK;
4092 break;
4093 case SQLITE_ACCESS_READWRITE:
4094 amode = W_OK|R_OK;
4095 break;
drh50d3f902007-08-27 21:10:36 +00004096 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004097 amode = R_OK;
4098 break;
4099
4100 default:
4101 assert(!"Invalid flags argument");
4102 }
danielk1977861f7452008-06-05 11:39:11 +00004103 *pResOut = (access(zPath, amode)==0);
4104 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004105}
4106
danielk1977b4b47412007-08-17 15:53:36 +00004107
4108/*
4109** Turn a relative pathname into a full pathname. The relative path
4110** is stored as a nul-terminated string in the buffer pointed to by
4111** zPath.
4112**
4113** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4114** (in this case, MAX_PATHNAME bytes). The full-path is written to
4115** this buffer before returning.
4116*/
danielk1977adfb9b02007-09-17 07:02:56 +00004117static int unixFullPathname(
4118 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4119 const char *zPath, /* Possibly relative input path */
4120 int nOut, /* Size of output buffer in bytes */
4121 char *zOut /* Output buffer */
4122){
danielk1977843e65f2007-09-01 16:16:15 +00004123
4124 /* It's odd to simulate an io-error here, but really this is just
4125 ** using the io-error infrastructure to test that SQLite handles this
4126 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004127 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004128 */
4129 SimulateIOError( return SQLITE_ERROR );
4130
drh153c62c2007-08-24 03:51:33 +00004131 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004132 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004133
drh3c7f2dc2007-12-06 13:26:20 +00004134 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004135 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004136 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004137 }else{
4138 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004139 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00004140 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00004141 }
drhea678832008-12-10 19:26:22 +00004142 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004143 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004144 }
4145 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004146}
4147
drh0ccebe72005-06-07 22:22:50 +00004148
drh761df872006-12-21 01:29:22 +00004149#ifndef SQLITE_OMIT_LOAD_EXTENSION
4150/*
4151** Interfaces for opening a shared library, finding entry points
4152** within the shared library, and closing the shared library.
4153*/
4154#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004155static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4156 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004157 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4158}
danielk197795c8a542007-09-01 06:51:27 +00004159
4160/*
4161** SQLite calls this function immediately after a call to unixDlSym() or
4162** unixDlOpen() fails (returns a null pointer). If a more detailed error
4163** message is available, it is written to zBufOut. If no error message
4164** is available, zBufOut is left unmodified and SQLite uses a default
4165** error message.
4166*/
danielk1977397d65f2008-11-19 11:35:39 +00004167static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004168 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004169 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004170 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004171 zErr = dlerror();
4172 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004173 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004174 }
drh6c7d5c52008-11-21 20:32:33 +00004175 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004176}
drh1875f7a2008-12-08 18:19:17 +00004177static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4178 /*
4179 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4180 ** cast into a pointer to a function. And yet the library dlsym() routine
4181 ** returns a void* which is really a pointer to a function. So how do we
4182 ** use dlsym() with -pedantic-errors?
4183 **
4184 ** Variable x below is defined to be a pointer to a function taking
4185 ** parameters void* and const char* and returning a pointer to a function.
4186 ** We initialize x by assigning it a pointer to the dlsym() function.
4187 ** (That assignment requires a cast.) Then we call the function that
4188 ** x points to.
4189 **
4190 ** This work-around is unlikely to work correctly on any system where
4191 ** you really cannot cast a function pointer into void*. But then, on the
4192 ** other hand, dlsym() will not work on such a system either, so we have
4193 ** not really lost anything.
4194 */
4195 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004196 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004197 x = (void(*(*)(void*,const char*))(void))dlsym;
4198 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004199}
danielk1977397d65f2008-11-19 11:35:39 +00004200static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4201 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004202 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004203}
danielk1977b4b47412007-08-17 15:53:36 +00004204#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4205 #define unixDlOpen 0
4206 #define unixDlError 0
4207 #define unixDlSym 0
4208 #define unixDlClose 0
4209#endif
4210
4211/*
danielk197790949c22007-08-17 16:50:38 +00004212** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004213*/
danielk1977397d65f2008-11-19 11:35:39 +00004214static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4215 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004216 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004217
drhbbd42a62004-05-22 17:41:58 +00004218 /* We have to initialize zBuf to prevent valgrind from reporting
4219 ** errors. The reports issued by valgrind are incorrect - we would
4220 ** prefer that the randomness be increased by making use of the
4221 ** uninitialized space in zBuf - but valgrind errors tend to worry
4222 ** some users. Rather than argue, it seems easier just to initialize
4223 ** the whole array and silence valgrind, even if that means less randomness
4224 ** in the random seed.
4225 **
4226 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004227 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004228 ** tests repeatable.
4229 */
danielk1977b4b47412007-08-17 15:53:36 +00004230 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004231#if !defined(SQLITE_TEST)
4232 {
drh842b8642005-01-21 17:53:17 +00004233 int pid, fd;
4234 fd = open("/dev/urandom", O_RDONLY);
4235 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004236 time_t t;
4237 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004238 memcpy(zBuf, &t, sizeof(t));
4239 pid = getpid();
4240 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004241 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004242 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004243 }else{
drh72cbd072008-10-14 17:58:38 +00004244 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004245 close(fd);
4246 }
drhbbd42a62004-05-22 17:41:58 +00004247 }
4248#endif
drh72cbd072008-10-14 17:58:38 +00004249 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004250}
4251
danielk1977b4b47412007-08-17 15:53:36 +00004252
drhbbd42a62004-05-22 17:41:58 +00004253/*
4254** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004255** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004256** The return value is the number of microseconds of sleep actually
4257** requested from the underlying operating system, a number which
4258** might be greater than or equal to the argument, but not less
4259** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004260*/
danielk1977397d65f2008-11-19 11:35:39 +00004261static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004262#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004263 struct timespec sp;
4264
4265 sp.tv_sec = microseconds / 1000000;
4266 sp.tv_nsec = (microseconds % 1000000) * 1000;
4267 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004268 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004269 return microseconds;
4270#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004271 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004272 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004273 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004274#else
danielk1977b4b47412007-08-17 15:53:36 +00004275 int seconds = (microseconds+999999)/1000000;
4276 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004277 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004278 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004279#endif
drh88f474a2006-01-02 20:00:12 +00004280}
4281
4282/*
drh6b9d6dd2008-12-03 19:34:47 +00004283** The following variable, if set to a non-zero value, is interpreted as
4284** the number of seconds since 1970 and is used to set the result of
4285** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004286*/
4287#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004288int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004289#endif
4290
4291/*
4292** Find the current time (in Universal Coordinated Time). Write the
4293** current time and date as a Julian Day number into *prNow and
4294** return 0. Return 1 if the time and date cannot be found.
4295*/
danielk1977397d65f2008-11-19 11:35:39 +00004296static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh0b3bf922009-06-15 20:45:34 +00004297#if defined(SQLITE_OMIT_FLOATING_POINT)
4298 time_t t;
4299 time(&t);
4300 *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
4301#elif defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00004302 time_t t;
4303 time(&t);
4304 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00004305#elif OS_VXWORKS
4306 struct timespec sNow;
4307 clock_gettime(CLOCK_REALTIME, &sNow);
4308 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00004309#else
4310 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00004311 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00004312 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
4313#endif
danielk1977397d65f2008-11-19 11:35:39 +00004314
drhbbd42a62004-05-22 17:41:58 +00004315#ifdef SQLITE_TEST
4316 if( sqlite3_current_time ){
4317 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4318 }
4319#endif
danielk1977397d65f2008-11-19 11:35:39 +00004320 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004321 return 0;
4322}
danielk1977b4b47412007-08-17 15:53:36 +00004323
drh6b9d6dd2008-12-03 19:34:47 +00004324/*
4325** We added the xGetLastError() method with the intention of providing
4326** better low-level error messages when operating-system problems come up
4327** during SQLite operation. But so far, none of that has been implemented
4328** in the core. So this routine is never called. For now, it is merely
4329** a place-holder.
4330*/
danielk1977397d65f2008-11-19 11:35:39 +00004331static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4332 UNUSED_PARAMETER(NotUsed);
4333 UNUSED_PARAMETER(NotUsed2);
4334 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004335 return 0;
4336}
4337
drh153c62c2007-08-24 03:51:33 +00004338/*
drh734c9862008-11-28 15:37:20 +00004339************************ End of sqlite3_vfs methods ***************************
4340******************************************************************************/
4341
drh715ff302008-12-03 22:32:44 +00004342/******************************************************************************
4343************************** Begin Proxy Locking ********************************
4344**
4345** Proxy locking is a "uber-locking-method" in this sense: It uses the
4346** other locking methods on secondary lock files. Proxy locking is a
4347** meta-layer over top of the primitive locking implemented above. For
4348** this reason, the division that implements of proxy locking is deferred
4349** until late in the file (here) after all of the other I/O methods have
4350** been defined - so that the primitive locking methods are available
4351** as services to help with the implementation of proxy locking.
4352**
4353****
4354**
4355** The default locking schemes in SQLite use byte-range locks on the
4356** database file to coordinate safe, concurrent access by multiple readers
4357** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4358** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4359** as POSIX read & write locks over fixed set of locations (via fsctl),
4360** on AFP and SMB only exclusive byte-range locks are available via fsctl
4361** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4362** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4363** address in the shared range is taken for a SHARED lock, the entire
4364** shared range is taken for an EXCLUSIVE lock):
4365**
4366** PENDING_BYTE 0x40000000
4367** RESERVED_BYTE 0x40000001
4368** SHARED_RANGE 0x40000002 -> 0x40000200
4369**
4370** This works well on the local file system, but shows a nearly 100x
4371** slowdown in read performance on AFP because the AFP client disables
4372** the read cache when byte-range locks are present. Enabling the read
4373** cache exposes a cache coherency problem that is present on all OS X
4374** supported network file systems. NFS and AFP both observe the
4375** close-to-open semantics for ensuring cache coherency
4376** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4377** address the requirements for concurrent database access by multiple
4378** readers and writers
4379** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4380**
4381** To address the performance and cache coherency issues, proxy file locking
4382** changes the way database access is controlled by limiting access to a
4383** single host at a time and moving file locks off of the database file
4384** and onto a proxy file on the local file system.
4385**
4386**
4387** Using proxy locks
4388** -----------------
4389**
4390** C APIs
4391**
4392** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4393** <proxy_path> | ":auto:");
4394** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4395**
4396**
4397** SQL pragmas
4398**
4399** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4400** PRAGMA [database.]lock_proxy_file
4401**
4402** Specifying ":auto:" means that if there is a conch file with a matching
4403** host ID in it, the proxy path in the conch file will be used, otherwise
4404** a proxy path based on the user's temp dir
4405** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4406** actual proxy file name is generated from the name and path of the
4407** database file. For example:
4408**
4409** For database path "/Users/me/foo.db"
4410** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4411**
4412** Once a lock proxy is configured for a database connection, it can not
4413** be removed, however it may be switched to a different proxy path via
4414** the above APIs (assuming the conch file is not being held by another
4415** connection or process).
4416**
4417**
4418** How proxy locking works
4419** -----------------------
4420**
4421** Proxy file locking relies primarily on two new supporting files:
4422**
4423** * conch file to limit access to the database file to a single host
4424** at a time
4425**
4426** * proxy file to act as a proxy for the advisory locks normally
4427** taken on the database
4428**
4429** The conch file - to use a proxy file, sqlite must first "hold the conch"
4430** by taking an sqlite-style shared lock on the conch file, reading the
4431** contents and comparing the host's unique host ID (see below) and lock
4432** proxy path against the values stored in the conch. The conch file is
4433** stored in the same directory as the database file and the file name
4434** is patterned after the database file name as ".<databasename>-conch".
4435** If the conch file does not exist, or it's contents do not match the
4436** host ID and/or proxy path, then the lock is escalated to an exclusive
4437** lock and the conch file contents is updated with the host ID and proxy
4438** path and the lock is downgraded to a shared lock again. If the conch
4439** is held by another process (with a shared lock), the exclusive lock
4440** will fail and SQLITE_BUSY is returned.
4441**
4442** The proxy file - a single-byte file used for all advisory file locks
4443** normally taken on the database file. This allows for safe sharing
4444** of the database file for multiple readers and writers on the same
4445** host (the conch ensures that they all use the same local lock file).
4446**
4447** There is a third file - the host ID file - used as a persistent record
4448** of a unique identifier for the host, a 128-byte unique host id file
4449** in the path defined by the HOSTIDPATH macro (default value is
4450** /Library/Caches/.com.apple.sqliteConchHostId).
4451**
4452** Requesting the lock proxy does not immediately take the conch, it is
4453** only taken when the first request to lock database file is made.
4454** This matches the semantics of the traditional locking behavior, where
4455** opening a connection to a database file does not take a lock on it.
4456** The shared lock and an open file descriptor are maintained until
4457** the connection to the database is closed.
4458**
4459** The proxy file and the lock file are never deleted so they only need
4460** to be created the first time they are used.
4461**
4462** Configuration options
4463** ---------------------
4464**
4465** SQLITE_PREFER_PROXY_LOCKING
4466**
4467** Database files accessed on non-local file systems are
4468** automatically configured for proxy locking, lock files are
4469** named automatically using the same logic as
4470** PRAGMA lock_proxy_file=":auto:"
4471**
4472** SQLITE_PROXY_DEBUG
4473**
4474** Enables the logging of error messages during host id file
4475** retrieval and creation
4476**
4477** HOSTIDPATH
4478**
4479** Overrides the default host ID file path location
4480**
4481** LOCKPROXYDIR
4482**
4483** Overrides the default directory used for lock proxy files that
4484** are named automatically via the ":auto:" setting
4485**
4486** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4487**
4488** Permissions to use when creating a directory for storing the
4489** lock proxy files, only used when LOCKPROXYDIR is not set.
4490**
4491**
4492** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4493** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4494** force proxy locking to be used for every database file opened, and 0
4495** will force automatic proxy locking to be disabled for all database
4496** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4497** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4498*/
4499
4500/*
4501** Proxy locking is only available on MacOSX
4502*/
drhd2cb50b2009-01-09 21:41:17 +00004503#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004504
4505#ifdef SQLITE_TEST
4506/* simulate multiple hosts by creating unique hostid file paths */
4507int sqlite3_hostid_num = 0;
4508#endif
4509
4510/*
4511** The proxyLockingContext has the path and file structures for the remote
4512** and local proxy files in it
4513*/
4514typedef struct proxyLockingContext proxyLockingContext;
4515struct proxyLockingContext {
4516 unixFile *conchFile; /* Open conch file */
4517 char *conchFilePath; /* Name of the conch file */
4518 unixFile *lockProxy; /* Open proxy lock file */
4519 char *lockProxyPath; /* Name of the proxy lock file */
4520 char *dbPath; /* Name of the open file */
4521 int conchHeld; /* True if the conch is currently held */
4522 void *oldLockingContext; /* Original lockingcontext to restore on close */
4523 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4524};
4525
4526/* HOSTIDLEN and CONCHLEN both include space for the string
4527** terminating nul
4528*/
4529#define HOSTIDLEN 128
4530#define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
4531#ifndef HOSTIDPATH
4532# define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
4533#endif
4534
4535/* basically a copy of unixRandomness with different
4536** test behavior built in */
4537static int proxyGenerateHostID(char *pHostID){
4538 int pid, fd, len;
4539 unsigned char *key = (unsigned char *)pHostID;
4540
4541 memset(key, 0, HOSTIDLEN);
4542 len = 0;
4543 fd = open("/dev/urandom", O_RDONLY);
4544 if( fd>=0 ){
4545 len = read(fd, key, HOSTIDLEN);
4546 close(fd); /* silently leak the fd if it fails */
4547 }
4548 if( len < HOSTIDLEN ){
4549 time_t t;
4550 time(&t);
4551 memcpy(key, &t, sizeof(t));
4552 pid = getpid();
4553 memcpy(&key[sizeof(t)], &pid, sizeof(pid));
4554 }
4555
4556#ifdef MAKE_PRETTY_HOSTID
4557 {
4558 int i;
4559 /* filter the bytes into printable ascii characters and NUL terminate */
4560 key[(HOSTIDLEN-1)] = 0x00;
4561 for( i=0; i<(HOSTIDLEN-1); i++ ){
4562 unsigned char pa = key[i]&0x7F;
4563 if( pa<0x20 ){
4564 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
4565 }else if( pa==0x7F ){
4566 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
4567 }
4568 }
4569 }
4570#endif
4571 return SQLITE_OK;
4572}
4573
4574/* writes the host id path to path, path should be an pre-allocated buffer
4575** with enough space for a path
4576*/
4577static void proxyGetHostIDPath(char *path, size_t len){
4578 strlcpy(path, HOSTIDPATH, len);
4579#ifdef SQLITE_TEST
4580 if( sqlite3_hostid_num>0 ){
4581 char suffix[2] = "1";
4582 suffix[0] = suffix[0] + sqlite3_hostid_num;
4583 strlcat(path, suffix, len);
4584 }
4585#endif
4586 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
4587}
4588
4589/* get the host ID from a sqlite hostid file stored in the
4590** user-specific tmp directory, create the ID if it's not there already
4591*/
4592static int proxyGetHostID(char *pHostID, int *pError){
4593 int fd;
4594 char path[MAXPATHLEN];
4595 size_t len;
4596 int rc=SQLITE_OK;
4597
4598 proxyGetHostIDPath(path, MAXPATHLEN);
4599 /* try to create the host ID file, if it already exists read the contents */
4600 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
4601 if( fd<0 ){
4602 int err=errno;
4603
4604 if( err!=EEXIST ){
4605#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4606 fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
4607 path, strerror(err));
4608#endif
4609 return SQLITE_PERM;
4610 }
4611 /* couldn't create the file, read it instead */
4612 fd = open(path, O_RDONLY|O_EXCL);
4613 if( fd<0 ){
4614#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4615 int err = errno;
4616 fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
4617 path, strerror(err));
4618#endif
4619 return SQLITE_PERM;
4620 }
4621 len = pread(fd, pHostID, HOSTIDLEN, 0);
4622 if( len<0 ){
4623 *pError = errno;
4624 rc = SQLITE_IOERR_READ;
4625 }else if( len<HOSTIDLEN ){
4626 *pError = 0;
4627 rc = SQLITE_IOERR_SHORT_READ;
4628 }
4629 close(fd); /* silently leak the fd if it fails */
4630 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
4631 return rc;
4632 }else{
4633 /* we're creating the host ID file (use a random string of bytes) */
4634 proxyGenerateHostID(pHostID);
4635 len = pwrite(fd, pHostID, HOSTIDLEN, 0);
4636 if( len<0 ){
4637 *pError = errno;
4638 rc = SQLITE_IOERR_WRITE;
4639 }else if( len<HOSTIDLEN ){
4640 *pError = 0;
4641 rc = SQLITE_IOERR_WRITE;
4642 }
4643 close(fd); /* silently leak the fd if it fails */
4644 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
4645 return rc;
4646 }
4647}
4648
4649static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4650 int len;
4651 int dbLen;
4652 int i;
4653
4654#ifdef LOCKPROXYDIR
4655 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4656#else
4657# ifdef _CS_DARWIN_USER_TEMP_DIR
4658 {
4659 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
4660 len = strlcat(lPath, "sqliteplocks", maxLen);
4661 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4662 /* if mkdir fails, handle as lock file creation failure */
drh715ff302008-12-03 22:32:44 +00004663# ifdef SQLITE_DEBUG
danielk197750c55a92009-05-08 11:34:37 +00004664 int err = errno;
drh715ff302008-12-03 22:32:44 +00004665 if( err!=EEXIST ){
4666 fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
4667 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
4668 }
4669# endif
4670 }else{
4671 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
4672 }
4673
4674 }
4675# else
4676 len = strlcpy(lPath, "/tmp/", maxLen);
4677# endif
4678#endif
4679
4680 if( lPath[len-1]!='/' ){
4681 len = strlcat(lPath, "/", maxLen);
4682 }
4683
4684 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004685 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004686 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4687 char c = dbPath[i];
4688 lPath[i+len] = (c=='/')?'_':c;
4689 }
4690 lPath[i+len]='\0';
4691 strlcat(lPath, ":auto:", maxLen);
4692 return SQLITE_OK;
4693}
4694
4695/*
4696** Create a new VFS file descriptor (stored in memory obtained from
4697** sqlite3_malloc) and open the file named "path" in the file descriptor.
4698**
4699** The caller is responsible not only for closing the file descriptor
4700** but also for freeing the memory associated with the file descriptor.
4701*/
4702static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
drh715ff302008-12-03 22:32:44 +00004703 unixFile *pNew;
dan15edd582009-08-25 05:57:47 +00004704 int flags = SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
drh715ff302008-12-03 22:32:44 +00004705 int rc = SQLITE_OK;
4706 sqlite3_vfs dummyVfs;
4707
drh715ff302008-12-03 22:32:44 +00004708 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
dan15edd582009-08-25 05:57:47 +00004709 if( !pNew ){
4710 return SQLITE_NOMEM;
drh715ff302008-12-03 22:32:44 +00004711 }
4712 memset(pNew, 0, sizeof(unixFile));
4713
dan15edd582009-08-25 05:57:47 +00004714 /* Call unixOpen() to open the proxy file. The flags passed to unixOpen()
4715 ** suggest that the file being opened is a "main database". This is
4716 ** necessary as other file types do not necessarily support locking. It
4717 ** is better to use unixOpen() instead of opening the file directly with
4718 ** open(), as unixOpen() sets up the various mechanisms required to
4719 ** make sure a call to close() does not cause the system to discard
4720 ** POSIX locks prematurely.
4721 **
4722 ** It is important that the xOpen member of the VFS object passed to
4723 ** unixOpen() is NULL. This tells unixOpen() may try to open a proxy-file
4724 ** for the proxy-file (creating a potential infinite loop).
4725 */
drh1875f7a2008-12-08 18:19:17 +00004726 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan15edd582009-08-25 05:57:47 +00004727 dummyVfs.xOpen = 0;
4728 rc = unixOpen(&dummyVfs, path, (sqlite3_file *)pNew, flags, &flags);
4729 if( rc==SQLITE_OK && (flags&SQLITE_OPEN_READONLY) ){
4730 pNew->pMethod->xClose((sqlite3_file *)pNew);
4731 rc = SQLITE_CANTOPEN;
drh715ff302008-12-03 22:32:44 +00004732 }
dan15edd582009-08-25 05:57:47 +00004733
4734 if( rc!=SQLITE_OK ){
4735 sqlite3_free(pNew);
4736 pNew = 0;
4737 }
4738
4739 *ppFile = pNew;
drh715ff302008-12-03 22:32:44 +00004740 return rc;
4741}
4742
4743/* takes the conch by taking a shared lock and read the contents conch, if
4744** lockPath is non-NULL, the host ID and lock file path must match. A NULL
4745** lockPath means that the lockPath in the conch file will be used if the
4746** host IDs match, or a new lock path will be generated automatically
4747** and written to the conch file.
4748*/
4749static int proxyTakeConch(unixFile *pFile){
4750 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4751
4752 if( pCtx->conchHeld>0 ){
4753 return SQLITE_OK;
4754 }else{
4755 unixFile *conchFile = pCtx->conchFile;
4756 char testValue[CONCHLEN];
4757 char conchValue[CONCHLEN];
4758 char lockPath[MAXPATHLEN];
4759 char *tLockPath = NULL;
4760 int rc = SQLITE_OK;
4761 int readRc = SQLITE_OK;
4762 int syncPerms = 0;
4763
4764 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
4765 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
4766
4767 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
4768 if( rc==SQLITE_OK ){
4769 int pError = 0;
drh1875f7a2008-12-08 18:19:17 +00004770 memset(testValue, 0, CONCHLEN); /* conch is fixed size */
drh715ff302008-12-03 22:32:44 +00004771 rc = proxyGetHostID(testValue, &pError);
4772 if( (rc&0xff)==SQLITE_IOERR ){
4773 pFile->lastErrno = pError;
4774 }
4775 if( pCtx->lockProxyPath ){
4776 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
4777 }
4778 }
4779 if( rc!=SQLITE_OK ){
4780 goto end_takeconch;
4781 }
4782
4783 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
4784 if( readRc!=SQLITE_IOERR_SHORT_READ ){
4785 if( readRc!=SQLITE_OK ){
4786 if( (rc&0xff)==SQLITE_IOERR ){
4787 pFile->lastErrno = conchFile->lastErrno;
4788 }
4789 rc = readRc;
4790 goto end_takeconch;
4791 }
4792 /* if the conch has data compare the contents */
4793 if( !pCtx->lockProxyPath ){
4794 /* for auto-named local lock file, just check the host ID and we'll
4795 ** use the local lock file path that's already in there */
4796 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
4797 tLockPath = (char *)&conchValue[HOSTIDLEN];
4798 goto end_takeconch;
4799 }
4800 }else{
4801 /* we've got the conch if conchValue matches our path and host ID */
4802 if( !memcmp(testValue, conchValue, CONCHLEN) ){
4803 goto end_takeconch;
4804 }
4805 }
4806 }else{
4807 /* a short read means we're "creating" the conch (even though it could
4808 ** have been user-intervention), if we acquire the exclusive lock,
4809 ** we'll try to match the current on-disk permissions of the database
4810 */
4811 syncPerms = 1;
4812 }
4813
4814 /* either conch was emtpy or didn't match */
4815 if( !pCtx->lockProxyPath ){
4816 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
4817 tLockPath = lockPath;
4818 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
4819 }
4820
4821 /* update conch with host and path (this will fail if other process
4822 ** has a shared lock already) */
4823 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
4824 if( rc==SQLITE_OK ){
4825 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
4826 if( rc==SQLITE_OK && syncPerms ){
4827 struct stat buf;
4828 int err = fstat(pFile->h, &buf);
4829 if( err==0 ){
4830 /* try to match the database file permissions, ignore failure */
4831#ifndef SQLITE_PROXY_DEBUG
4832 fchmod(conchFile->h, buf.st_mode);
4833#else
4834 if( fchmod(conchFile->h, buf.st_mode)!=0 ){
4835 int code = errno;
4836 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
4837 buf.st_mode, code, strerror(code));
4838 } else {
4839 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
4840 }
4841 }else{
4842 int code = errno;
4843 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
4844 err, code, strerror(code));
4845#endif
4846 }
4847 }
4848 }
4849 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
4850
4851end_takeconch:
4852 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
4853 if( rc==SQLITE_OK && pFile->openFlags ){
4854 if( pFile->h>=0 ){
4855#ifdef STRICT_CLOSE_ERROR
4856 if( close(pFile->h) ){
4857 pFile->lastErrno = errno;
4858 return SQLITE_IOERR_CLOSE;
4859 }
4860#else
4861 close(pFile->h); /* silently leak fd if fail */
4862#endif
4863 }
4864 pFile->h = -1;
4865 int fd = open(pCtx->dbPath, pFile->openFlags,
4866 SQLITE_DEFAULT_FILE_PERMISSIONS);
4867 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
4868 if( fd>=0 ){
4869 pFile->h = fd;
4870 }else{
drh1875f7a2008-12-08 18:19:17 +00004871 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
4872 during locking */
drh715ff302008-12-03 22:32:44 +00004873 }
4874 }
4875 if( rc==SQLITE_OK && !pCtx->lockProxy ){
4876 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
drh1875f7a2008-12-08 18:19:17 +00004877 /* ACS: Need to make a copy of path sometimes */
drh715ff302008-12-03 22:32:44 +00004878 rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
4879 }
4880 if( rc==SQLITE_OK ){
4881 pCtx->conchHeld = 1;
4882
4883 if( tLockPath ){
4884 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
4885 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
4886 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
4887 pCtx->lockProxyPath;
4888 }
4889 }
4890 } else {
4891 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4892 }
4893 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
4894 return rc;
4895 }
4896}
4897
4898/*
4899** If pFile holds a lock on a conch file, then release that lock.
4900*/
4901static int proxyReleaseConch(unixFile *pFile){
4902 int rc; /* Subroutine return code */
4903 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
4904 unixFile *conchFile; /* Name of the conch file */
4905
4906 pCtx = (proxyLockingContext *)pFile->lockingContext;
4907 conchFile = pCtx->conchFile;
4908 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
4909 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
4910 getpid());
4911 pCtx->conchHeld = 0;
4912 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4913 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
4914 (rc==SQLITE_OK ? "ok" : "failed"));
4915 return rc;
4916}
4917
4918/*
4919** Given the name of a database file, compute the name of its conch file.
4920** Store the conch filename in memory obtained from sqlite3_malloc().
4921** Make *pConchPath point to the new name. Return SQLITE_OK on success
4922** or SQLITE_NOMEM if unable to obtain memory.
4923**
4924** The caller is responsible for ensuring that the allocated memory
4925** space is eventually freed.
4926**
4927** *pConchPath is set to NULL if a memory allocation error occurs.
4928*/
4929static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
4930 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00004931 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00004932 char *conchPath; /* buffer in which to construct conch name */
4933
4934 /* Allocate space for the conch filename and initialize the name to
4935 ** the name of the original database file. */
4936 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
4937 if( conchPath==0 ){
4938 return SQLITE_NOMEM;
4939 }
4940 memcpy(conchPath, dbPath, len+1);
4941
4942 /* now insert a "." before the last / character */
4943 for( i=(len-1); i>=0; i-- ){
4944 if( conchPath[i]=='/' ){
4945 i++;
4946 break;
4947 }
4948 }
4949 conchPath[i]='.';
4950 while ( i<len ){
4951 conchPath[i+1]=dbPath[i];
4952 i++;
4953 }
4954
4955 /* append the "-conch" suffix to the file */
4956 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00004957 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00004958
4959 return SQLITE_OK;
4960}
4961
4962
4963/* Takes a fully configured proxy locking-style unix file and switches
4964** the local lock file path
4965*/
4966static int switchLockProxyPath(unixFile *pFile, const char *path) {
4967 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4968 char *oldPath = pCtx->lockProxyPath;
4969 int rc = SQLITE_OK;
4970
4971 if( pFile->locktype!=NO_LOCK ){
4972 return SQLITE_BUSY;
4973 }
4974
4975 /* nothing to do if the path is NULL, :auto: or matches the existing path */
4976 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
4977 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
4978 return SQLITE_OK;
4979 }else{
4980 unixFile *lockProxy = pCtx->lockProxy;
4981 pCtx->lockProxy=NULL;
4982 pCtx->conchHeld = 0;
4983 if( lockProxy!=NULL ){
4984 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
4985 if( rc ) return rc;
4986 sqlite3_free(lockProxy);
4987 }
4988 sqlite3_free(oldPath);
4989 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
4990 }
4991
4992 return rc;
4993}
4994
4995/*
4996** pFile is a file that has been opened by a prior xOpen call. dbPath
4997** is a string buffer at least MAXPATHLEN+1 characters in size.
4998**
4999** This routine find the filename associated with pFile and writes it
5000** int dbPath.
5001*/
5002static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00005003#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00005004 if( pFile->pMethod == &afpIoMethods ){
5005 /* afp style keeps a reference to the db path in the filePath field
5006 ** of the struct */
drhea678832008-12-10 19:26:22 +00005007 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh715ff302008-12-03 22:32:44 +00005008 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
5009 }else
5010#endif
5011 if( pFile->pMethod == &dotlockIoMethods ){
5012 /* dot lock style uses the locking context to store the dot lock
5013 ** file path */
5014 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5015 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5016 }else{
5017 /* all other styles use the locking context to store the db file path */
5018 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
5019 strcpy(dbPath, (char *)pFile->lockingContext);
5020 }
5021 return SQLITE_OK;
5022}
5023
5024/*
5025** Takes an already filled in unix file and alters it so all file locking
5026** will be performed on the local proxy lock file. The following fields
5027** are preserved in the locking context so that they can be restored and
5028** the unix structure properly cleaned up at close time:
5029** ->lockingContext
5030** ->pMethod
5031*/
5032static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
5033 proxyLockingContext *pCtx;
5034 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
5035 char *lockPath=NULL;
5036 int rc = SQLITE_OK;
5037
5038 if( pFile->locktype!=NO_LOCK ){
5039 return SQLITE_BUSY;
5040 }
5041 proxyGetDbPathForUnixFile(pFile, dbPath);
5042 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
5043 lockPath=NULL;
5044 }else{
5045 lockPath=(char *)path;
5046 }
5047
5048 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
5049 (lockPath ? lockPath : ":auto:"), getpid());
5050
5051 pCtx = sqlite3_malloc( sizeof(*pCtx) );
5052 if( pCtx==0 ){
5053 return SQLITE_NOMEM;
5054 }
5055 memset(pCtx, 0, sizeof(*pCtx));
5056
5057 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
5058 if( rc==SQLITE_OK ){
5059 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
5060 }
5061 if( rc==SQLITE_OK && lockPath ){
5062 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
5063 }
5064
5065 if( rc==SQLITE_OK ){
5066 /* all memory is allocated, proxys are created and assigned,
5067 ** switch the locking context and pMethod then return.
5068 */
5069 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
5070 pCtx->oldLockingContext = pFile->lockingContext;
5071 pFile->lockingContext = pCtx;
5072 pCtx->pOldMethod = pFile->pMethod;
5073 pFile->pMethod = &proxyIoMethods;
5074 }else{
5075 if( pCtx->conchFile ){
5076 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
5077 if( rc ) return rc;
5078 sqlite3_free(pCtx->conchFile);
5079 }
5080 sqlite3_free(pCtx->conchFilePath);
5081 sqlite3_free(pCtx);
5082 }
5083 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
5084 (rc==SQLITE_OK ? "ok" : "failed"));
5085 return rc;
5086}
5087
5088
5089/*
5090** This routine handles sqlite3_file_control() calls that are specific
5091** to proxy locking.
5092*/
5093static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
5094 switch( op ){
5095 case SQLITE_GET_LOCKPROXYFILE: {
5096 unixFile *pFile = (unixFile*)id;
5097 if( pFile->pMethod == &proxyIoMethods ){
5098 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5099 proxyTakeConch(pFile);
5100 if( pCtx->lockProxyPath ){
5101 *(const char **)pArg = pCtx->lockProxyPath;
5102 }else{
5103 *(const char **)pArg = ":auto: (not held)";
5104 }
5105 } else {
5106 *(const char **)pArg = NULL;
5107 }
5108 return SQLITE_OK;
5109 }
5110 case SQLITE_SET_LOCKPROXYFILE: {
5111 unixFile *pFile = (unixFile*)id;
5112 int rc = SQLITE_OK;
5113 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
5114 if( pArg==NULL || (const char *)pArg==0 ){
5115 if( isProxyStyle ){
5116 /* turn off proxy locking - not supported */
5117 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
5118 }else{
5119 /* turn off proxy locking - already off - NOOP */
5120 rc = SQLITE_OK;
5121 }
5122 }else{
5123 const char *proxyPath = (const char *)pArg;
5124 if( isProxyStyle ){
5125 proxyLockingContext *pCtx =
5126 (proxyLockingContext*)pFile->lockingContext;
5127 if( !strcmp(pArg, ":auto:")
5128 || (pCtx->lockProxyPath &&
5129 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
5130 ){
5131 rc = SQLITE_OK;
5132 }else{
5133 rc = switchLockProxyPath(pFile, proxyPath);
5134 }
5135 }else{
5136 /* turn on proxy file locking */
5137 rc = proxyTransformUnixFile(pFile, proxyPath);
5138 }
5139 }
5140 return rc;
5141 }
5142 default: {
5143 assert( 0 ); /* The call assures that only valid opcodes are sent */
5144 }
5145 }
5146 /*NOTREACHED*/
5147 return SQLITE_ERROR;
5148}
5149
5150/*
5151** Within this division (the proxying locking implementation) the procedures
5152** above this point are all utilities. The lock-related methods of the
5153** proxy-locking sqlite3_io_method object follow.
5154*/
5155
5156
5157/*
5158** This routine checks if there is a RESERVED lock held on the specified
5159** file by this or any other process. If such a lock is held, set *pResOut
5160** to a non-zero value otherwise *pResOut is set to zero. The return value
5161** is set to SQLITE_OK unless an I/O error occurs during lock checking.
5162*/
5163static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
5164 unixFile *pFile = (unixFile*)id;
5165 int rc = proxyTakeConch(pFile);
5166 if( rc==SQLITE_OK ){
5167 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5168 unixFile *proxy = pCtx->lockProxy;
5169 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
5170 }
5171 return rc;
5172}
5173
5174/*
5175** Lock the file with the lock specified by parameter locktype - one
5176** of the following:
5177**
5178** (1) SHARED_LOCK
5179** (2) RESERVED_LOCK
5180** (3) PENDING_LOCK
5181** (4) EXCLUSIVE_LOCK
5182**
5183** Sometimes when requesting one lock state, additional lock states
5184** are inserted in between. The locking might fail on one of the later
5185** transitions leaving the lock state different from what it started but
5186** still short of its goal. The following chart shows the allowed
5187** transitions and the inserted intermediate states:
5188**
5189** UNLOCKED -> SHARED
5190** SHARED -> RESERVED
5191** SHARED -> (PENDING) -> EXCLUSIVE
5192** RESERVED -> (PENDING) -> EXCLUSIVE
5193** PENDING -> EXCLUSIVE
5194**
5195** This routine will only increase a lock. Use the sqlite3OsUnlock()
5196** routine to lower a locking level.
5197*/
5198static int proxyLock(sqlite3_file *id, int locktype) {
5199 unixFile *pFile = (unixFile*)id;
5200 int rc = proxyTakeConch(pFile);
5201 if( rc==SQLITE_OK ){
5202 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5203 unixFile *proxy = pCtx->lockProxy;
5204 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
5205 pFile->locktype = proxy->locktype;
5206 }
5207 return rc;
5208}
5209
5210
5211/*
5212** Lower the locking level on file descriptor pFile to locktype. locktype
5213** must be either NO_LOCK or SHARED_LOCK.
5214**
5215** If the locking level of the file descriptor is already at or below
5216** the requested locking level, this routine is a no-op.
5217*/
5218static int proxyUnlock(sqlite3_file *id, int locktype) {
5219 unixFile *pFile = (unixFile*)id;
5220 int rc = proxyTakeConch(pFile);
5221 if( rc==SQLITE_OK ){
5222 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5223 unixFile *proxy = pCtx->lockProxy;
5224 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
5225 pFile->locktype = proxy->locktype;
5226 }
5227 return rc;
5228}
5229
5230/*
5231** Close a file that uses proxy locks.
5232*/
5233static int proxyClose(sqlite3_file *id) {
5234 if( id ){
5235 unixFile *pFile = (unixFile*)id;
5236 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5237 unixFile *lockProxy = pCtx->lockProxy;
5238 unixFile *conchFile = pCtx->conchFile;
5239 int rc = SQLITE_OK;
5240
5241 if( lockProxy ){
5242 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
5243 if( rc ) return rc;
5244 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
5245 if( rc ) return rc;
5246 sqlite3_free(lockProxy);
5247 pCtx->lockProxy = 0;
5248 }
5249 if( conchFile ){
5250 if( pCtx->conchHeld ){
5251 rc = proxyReleaseConch(pFile);
5252 if( rc ) return rc;
5253 }
5254 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
5255 if( rc ) return rc;
5256 sqlite3_free(conchFile);
5257 }
5258 sqlite3_free(pCtx->lockProxyPath);
5259 sqlite3_free(pCtx->conchFilePath);
5260 sqlite3_free(pCtx->dbPath);
5261 /* restore the original locking context and pMethod then close it */
5262 pFile->lockingContext = pCtx->oldLockingContext;
5263 pFile->pMethod = pCtx->pOldMethod;
5264 sqlite3_free(pCtx);
5265 return pFile->pMethod->xClose(id);
5266 }
5267 return SQLITE_OK;
5268}
5269
5270
5271
drhd2cb50b2009-01-09 21:41:17 +00005272#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00005273/*
5274** The proxy locking style is intended for use with AFP filesystems.
5275** And since AFP is only supported on MacOSX, the proxy locking is also
5276** restricted to MacOSX.
5277**
5278**
5279******************* End of the proxy lock implementation **********************
5280******************************************************************************/
5281
drh734c9862008-11-28 15:37:20 +00005282/*
danielk1977e339d652008-06-28 11:23:00 +00005283** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00005284**
5285** This routine registers all VFS implementations for unix-like operating
5286** systems. This routine, and the sqlite3_os_end() routine that follows,
5287** should be the only routines in this file that are visible from other
5288** files.
drh6b9d6dd2008-12-03 19:34:47 +00005289**
5290** This routine is called once during SQLite initialization and by a
5291** single thread. The memory allocation and mutex subsystems have not
5292** necessarily been initialized when this routine is called, and so they
5293** should not be used.
drh153c62c2007-08-24 03:51:33 +00005294*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005295int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00005296 /*
5297 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00005298 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
5299 ** to the "finder" function. (pAppData is a pointer to a pointer because
5300 ** silly C90 rules prohibit a void* from being cast to a function pointer
5301 ** and so we have to go through the intermediate pointer to avoid problems
5302 ** when compiling with -pedantic-errors on GCC.)
5303 **
5304 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00005305 ** finder-function. The finder-function returns a pointer to the
5306 ** sqlite_io_methods object that implements the desired locking
5307 ** behaviors. See the division above that contains the IOMETHODS
5308 ** macro for addition information on finder-functions.
5309 **
5310 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
5311 ** object. But the "autolockIoFinder" available on MacOSX does a little
5312 ** more than that; it looks at the filesystem type that hosts the
5313 ** database file and tries to choose an locking method appropriate for
5314 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00005315 */
drh7708e972008-11-29 00:56:52 +00005316 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00005317 1, /* iVersion */ \
5318 sizeof(unixFile), /* szOsFile */ \
5319 MAX_PATHNAME, /* mxPathname */ \
5320 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00005321 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00005322 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00005323 unixOpen, /* xOpen */ \
5324 unixDelete, /* xDelete */ \
5325 unixAccess, /* xAccess */ \
5326 unixFullPathname, /* xFullPathname */ \
5327 unixDlOpen, /* xDlOpen */ \
5328 unixDlError, /* xDlError */ \
5329 unixDlSym, /* xDlSym */ \
5330 unixDlClose, /* xDlClose */ \
5331 unixRandomness, /* xRandomness */ \
5332 unixSleep, /* xSleep */ \
5333 unixCurrentTime, /* xCurrentTime */ \
5334 unixGetLastError /* xGetLastError */ \
5335 }
5336
drh6b9d6dd2008-12-03 19:34:47 +00005337 /*
5338 ** All default VFSes for unix are contained in the following array.
5339 **
5340 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5341 ** by the SQLite core when the VFS is registered. So the following
5342 ** array cannot be const.
5343 */
danielk1977e339d652008-06-28 11:23:00 +00005344 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00005345#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00005346 UNIXVFS("unix", autolockIoFinder ),
5347#else
5348 UNIXVFS("unix", posixIoFinder ),
5349#endif
5350 UNIXVFS("unix-none", nolockIoFinder ),
5351 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh0c2694b2009-09-03 16:23:44 +00005352 UNIXVFS("unix-wfl", posixWflIoFinder ),
drh734c9862008-11-28 15:37:20 +00005353#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005354 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005355#endif
5356#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005357 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00005358#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005359 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005360#endif
chw78a13182009-04-07 05:35:03 +00005361#endif
drhd2cb50b2009-01-09 21:41:17 +00005362#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005363 UNIXVFS("unix-afp", afpIoFinder ),
5364 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005365#endif
drh153c62c2007-08-24 03:51:33 +00005366 };
drh6b9d6dd2008-12-03 19:34:47 +00005367 unsigned int i; /* Loop counter */
5368
5369 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005370 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005371 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005372 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005373 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005374}
danielk1977e339d652008-06-28 11:23:00 +00005375
5376/*
drh6b9d6dd2008-12-03 19:34:47 +00005377** Shutdown the operating system interface.
5378**
5379** Some operating systems might need to do some cleanup in this routine,
5380** to release dynamically allocated objects. But not on unix.
5381** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005382*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005383int sqlite3_os_end(void){
5384 return SQLITE_OK;
5385}
drhdce8bdb2007-08-16 13:01:44 +00005386
danielk197729bafea2008-06-26 10:41:19 +00005387#endif /* SQLITE_OS_UNIX */