blob: 15bd8cc638d2eb6b74d070133e30bde01b9e2c4a [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 */
drh08c6d442009-02-09 17:34:07 +0000198#if SQLITE_ENABLE_LOCKING_STYLE
199 int openFlags; /* The flags specified at open() */
200#endif
drh734c9862008-11-28 15:37:20 +0000201#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000202 pthread_t tid; /* The thread that "owns" this unixFile */
203#endif
204#if OS_VXWORKS
205 int isDelete; /* Delete on close if true */
drh107886a2008-11-21 22:21:50 +0000206 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000207#endif
drh8f941bc2009-01-14 23:03:40 +0000208#ifndef NDEBUG
209 /* The next group of variables are used to track whether or not the
210 ** transaction counter in bytes 24-27 of database files are updated
211 ** whenever any part of the database changes. An assertion fault will
212 ** occur if a file is updated without also updating the transaction
213 ** counter. This test is made to avoid new problems similar to the
214 ** one described by ticket #3584.
215 */
216 unsigned char transCntrChng; /* True if the transaction counter changed */
217 unsigned char dbUpdate; /* True if any part of database file changed */
218 unsigned char inNormalWrite; /* True if in a normal write operation */
219#endif
danielk1977967a4a12007-08-20 14:23:44 +0000220#ifdef SQLITE_TEST
221 /* In test mode, increase the size of this structure a bit so that
222 ** it is larger than the struct CrashFile defined in test6.c.
223 */
224 char aPadding[32];
225#endif
drh9cbe6352005-11-29 03:13:21 +0000226};
227
drh0ccebe72005-06-07 22:22:50 +0000228/*
drh198bf392006-01-06 21:52:49 +0000229** Include code that is common to all os_*.c files
230*/
231#include "os_common.h"
232
233/*
drh0ccebe72005-06-07 22:22:50 +0000234** Define various macros that are missing from some systems.
235*/
drhbbd42a62004-05-22 17:41:58 +0000236#ifndef O_LARGEFILE
237# define O_LARGEFILE 0
238#endif
239#ifdef SQLITE_DISABLE_LFS
240# undef O_LARGEFILE
241# define O_LARGEFILE 0
242#endif
243#ifndef O_NOFOLLOW
244# define O_NOFOLLOW 0
245#endif
246#ifndef O_BINARY
247# define O_BINARY 0
248#endif
249
250/*
251** The DJGPP compiler environment looks mostly like Unix, but it
252** lacks the fcntl() system call. So redefine fcntl() to be something
253** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000254** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000255*/
256#ifdef __DJGPP__
257# define fcntl(A,B,C) 0
258#endif
259
260/*
drh2b4b5962005-06-15 17:47:55 +0000261** The threadid macro resolves to the thread-id or to 0. Used for
262** testing and debugging only.
263*/
drhd677b3d2007-08-20 22:48:41 +0000264#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000265#define threadid pthread_self()
266#else
267#define threadid 0
268#endif
269
danielk197713adf8a2004-06-03 16:08:41 +0000270
drh107886a2008-11-21 22:21:50 +0000271/*
dan9359c7b2009-08-21 08:29:10 +0000272** Helper functions to obtain and relinquish the global mutex. The
273** global mutex is used to protect the unixOpenCnt, unixLockInfo and
274** vxworksFileId objects used by this file, all of which may be
275** shared by multiple threads.
276**
277** Function unixMutexHeld() is used to assert() that the global mutex
278** is held when required. This function is only used as part of assert()
279** statements. e.g.
280**
281** unixEnterMutex()
282** assert( unixMutexHeld() );
283** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000284*/
285static void unixEnterMutex(void){
286 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
287}
288static void unixLeaveMutex(void){
289 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
290}
dan9359c7b2009-08-21 08:29:10 +0000291#ifdef SQLITE_DEBUG
292static int unixMutexHeld(void) {
293 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
294}
295#endif
drh107886a2008-11-21 22:21:50 +0000296
drh734c9862008-11-28 15:37:20 +0000297
298#ifdef SQLITE_DEBUG
299/*
300** Helper function for printing out trace information from debugging
301** binaries. This returns the string represetation of the supplied
302** integer lock-type.
303*/
304static const char *locktypeName(int locktype){
305 switch( locktype ){
dan9359c7b2009-08-21 08:29:10 +0000306 case NO_LOCK: return "NONE";
307 case SHARED_LOCK: return "SHARED";
308 case RESERVED_LOCK: return "RESERVED";
309 case PENDING_LOCK: return "PENDING";
310 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000311 }
312 return "ERROR";
313}
314#endif
315
316#ifdef SQLITE_LOCK_TRACE
317/*
318** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000319**
drh734c9862008-11-28 15:37:20 +0000320** This routine is used for troubleshooting locks on multithreaded
321** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
322** command-line option on the compiler. This code is normally
323** turned off.
324*/
325static int lockTrace(int fd, int op, struct flock *p){
326 char *zOpName, *zType;
327 int s;
328 int savedErrno;
329 if( op==F_GETLK ){
330 zOpName = "GETLK";
331 }else if( op==F_SETLK ){
332 zOpName = "SETLK";
333 }else{
334 s = fcntl(fd, op, p);
335 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
336 return s;
337 }
338 if( p->l_type==F_RDLCK ){
339 zType = "RDLCK";
340 }else if( p->l_type==F_WRLCK ){
341 zType = "WRLCK";
342 }else if( p->l_type==F_UNLCK ){
343 zType = "UNLCK";
344 }else{
345 assert( 0 );
346 }
347 assert( p->l_whence==SEEK_SET );
348 s = fcntl(fd, op, p);
349 savedErrno = errno;
350 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
351 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
352 (int)p->l_pid, s);
353 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
354 struct flock l2;
355 l2 = *p;
356 fcntl(fd, F_GETLK, &l2);
357 if( l2.l_type==F_RDLCK ){
358 zType = "RDLCK";
359 }else if( l2.l_type==F_WRLCK ){
360 zType = "WRLCK";
361 }else if( l2.l_type==F_UNLCK ){
362 zType = "UNLCK";
363 }else{
364 assert( 0 );
365 }
366 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
367 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
368 }
369 errno = savedErrno;
370 return s;
371}
372#define fcntl lockTrace
373#endif /* SQLITE_LOCK_TRACE */
374
375
376
377/*
378** This routine translates a standard POSIX errno code into something
379** useful to the clients of the sqlite3 functions. Specifically, it is
380** intended to translate a variety of "try again" errors into SQLITE_BUSY
381** and a variety of "please close the file descriptor NOW" errors into
382** SQLITE_IOERR
383**
384** Errors during initialization of locks, or file system support for locks,
385** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
386*/
387static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
388 switch (posixError) {
389 case 0:
390 return SQLITE_OK;
391
392 case EAGAIN:
393 case ETIMEDOUT:
394 case EBUSY:
395 case EINTR:
396 case ENOLCK:
397 /* random NFS retry error, unless during file system support
398 * introspection, in which it actually means what it says */
399 return SQLITE_BUSY;
400
401 case EACCES:
402 /* EACCES is like EAGAIN during locking operations, but not any other time*/
403 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
404 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
405 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
406 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
407 return SQLITE_BUSY;
408 }
409 /* else fall through */
410 case EPERM:
411 return SQLITE_PERM;
412
413 case EDEADLK:
414 return SQLITE_IOERR_BLOCKED;
415
416#if EOPNOTSUPP!=ENOTSUP
417 case EOPNOTSUPP:
418 /* something went terribly awry, unless during file system support
419 * introspection, in which it actually means what it says */
420#endif
421#ifdef ENOTSUP
422 case ENOTSUP:
423 /* invalid fd, unless during file system support introspection, in which
424 * it actually means what it says */
425#endif
426 case EIO:
427 case EBADF:
428 case EINVAL:
429 case ENOTCONN:
430 case ENODEV:
431 case ENXIO:
432 case ENOENT:
433 case ESTALE:
434 case ENOSYS:
435 /* these should force the client to close the file and reconnect */
436
437 default:
438 return sqliteIOErr;
439 }
440}
441
442
443
444/******************************************************************************
445****************** Begin Unique File ID Utility Used By VxWorks ***************
446**
447** On most versions of unix, we can get a unique ID for a file by concatenating
448** the device number and the inode number. But this does not work on VxWorks.
449** On VxWorks, a unique file id must be based on the canonical filename.
450**
451** A pointer to an instance of the following structure can be used as a
452** unique file ID in VxWorks. Each instance of this structure contains
453** a copy of the canonical filename. There is also a reference count.
454** The structure is reclaimed when the number of pointers to it drops to
455** zero.
456**
457** There are never very many files open at one time and lookups are not
458** a performance-critical path, so it is sufficient to put these
459** structures on a linked list.
460*/
461struct vxworksFileId {
462 struct vxworksFileId *pNext; /* Next in a list of them all */
463 int nRef; /* Number of references to this one */
464 int nName; /* Length of the zCanonicalName[] string */
465 char *zCanonicalName; /* Canonical filename */
466};
467
468#if OS_VXWORKS
469/*
drh9b35ea62008-11-29 02:20:26 +0000470** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000471** variable:
472*/
473static struct vxworksFileId *vxworksFileList = 0;
474
475/*
476** Simplify a filename into its canonical form
477** by making the following changes:
478**
479** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000480** * convert /./ into just /
481** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000482**
483** Changes are made in-place. Return the new name length.
484**
485** The original filename is in z[0..n-1]. Return the number of
486** characters in the simplified name.
487*/
488static int vxworksSimplifyName(char *z, int n){
489 int i, j;
490 while( n>1 && z[n-1]=='/' ){ n--; }
491 for(i=j=0; i<n; i++){
492 if( z[i]=='/' ){
493 if( z[i+1]=='/' ) continue;
494 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
495 i += 1;
496 continue;
497 }
498 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
499 while( j>0 && z[j-1]!='/' ){ j--; }
500 if( j>0 ){ j--; }
501 i += 2;
502 continue;
503 }
504 }
505 z[j++] = z[i];
506 }
507 z[j] = 0;
508 return j;
509}
510
511/*
512** Find a unique file ID for the given absolute pathname. Return
513** a pointer to the vxworksFileId object. This pointer is the unique
514** file ID.
515**
516** The nRef field of the vxworksFileId object is incremented before
517** the object is returned. A new vxworksFileId object is created
518** and added to the global list if necessary.
519**
520** If a memory allocation error occurs, return NULL.
521*/
522static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
523 struct vxworksFileId *pNew; /* search key and new file ID */
524 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
525 int n; /* Length of zAbsoluteName string */
526
527 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000528 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000529 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
530 if( pNew==0 ) return 0;
531 pNew->zCanonicalName = (char*)&pNew[1];
532 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
533 n = vxworksSimplifyName(pNew->zCanonicalName, n);
534
535 /* Search for an existing entry that matching the canonical name.
536 ** If found, increment the reference count and return a pointer to
537 ** the existing file ID.
538 */
539 unixEnterMutex();
540 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
541 if( pCandidate->nName==n
542 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
543 ){
544 sqlite3_free(pNew);
545 pCandidate->nRef++;
546 unixLeaveMutex();
547 return pCandidate;
548 }
549 }
550
551 /* No match was found. We will make a new file ID */
552 pNew->nRef = 1;
553 pNew->nName = n;
554 pNew->pNext = vxworksFileList;
555 vxworksFileList = pNew;
556 unixLeaveMutex();
557 return pNew;
558}
559
560/*
561** Decrement the reference count on a vxworksFileId object. Free
562** the object when the reference count reaches zero.
563*/
564static void vxworksReleaseFileId(struct vxworksFileId *pId){
565 unixEnterMutex();
566 assert( pId->nRef>0 );
567 pId->nRef--;
568 if( pId->nRef==0 ){
569 struct vxworksFileId **pp;
570 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
571 assert( *pp==pId );
572 *pp = pId->pNext;
573 sqlite3_free(pId);
574 }
575 unixLeaveMutex();
576}
577#endif /* OS_VXWORKS */
578/*************** End of Unique File ID Utility Used By VxWorks ****************
579******************************************************************************/
580
581
582/******************************************************************************
583*************************** Posix Advisory Locking ****************************
584**
drh9b35ea62008-11-29 02:20:26 +0000585** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000586** section 6.5.2.2 lines 483 through 490 specify that when a process
587** sets or clears a lock, that operation overrides any prior locks set
588** by the same process. It does not explicitly say so, but this implies
589** that it overrides locks set by the same process using a different
590** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000591**
592** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000593** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
594**
595** Suppose ./file1 and ./file2 are really the same file (because
596** one is a hard or symbolic link to the other) then if you set
597** an exclusive lock on fd1, then try to get an exclusive lock
598** on fd2, it works. I would have expected the second lock to
599** fail since there was already a lock on the file due to fd1.
600** But not so. Since both locks came from the same process, the
601** second overrides the first, even though they were on different
602** file descriptors opened on different file names.
603**
drh734c9862008-11-28 15:37:20 +0000604** This means that we cannot use POSIX locks to synchronize file access
605** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000606** to synchronize access for threads in separate processes, but not
607** threads within the same process.
608**
609** To work around the problem, SQLite has to manage file locks internally
610** on its own. Whenever a new database is opened, we have to find the
611** specific inode of the database file (the inode is determined by the
612** st_dev and st_ino fields of the stat structure that fstat() fills in)
613** and check for locks already existing on that inode. When locks are
614** created or removed, we have to look at our own internal record of the
615** locks to see if another thread has previously set a lock on that same
616** inode.
617**
drh9b35ea62008-11-29 02:20:26 +0000618** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
619** For VxWorks, we have to use the alternative unique ID system based on
620** canonical filename and implemented in the previous division.)
621**
danielk1977ad94b582007-08-20 06:44:22 +0000622** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000623** descriptor. It is now a structure that holds the integer file
624** descriptor and a pointer to a structure that describes the internal
625** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000626** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000627** point to the same locking structure. The locking structure keeps
628** a reference count (so we will know when to delete it) and a "cnt"
629** field that tells us its internal lock status. cnt==0 means the
630** file is unlocked. cnt==-1 means the file has an exclusive lock.
631** cnt>0 means there are cnt shared locks on the file.
632**
633** Any attempt to lock or unlock a file first checks the locking
634** structure. The fcntl() system call is only invoked to set a
635** POSIX lock if the internal lock structure transitions between
636** a locked and an unlocked state.
637**
drh734c9862008-11-28 15:37:20 +0000638** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000639**
640** If you close a file descriptor that points to a file that has locks,
641** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000642** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000643** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000644** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000645** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000646** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000647** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000648** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000649** be closed and that list is walked (and cleared) when the last lock
650** clears.
651**
drh9b35ea62008-11-29 02:20:26 +0000652** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000653**
drh9b35ea62008-11-29 02:20:26 +0000654** Many older versions of linux use the LinuxThreads library which is
655** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000656** A cannot be modified or overridden by a different thread B.
657** Only thread A can modify the lock. Locking behavior is correct
658** if the appliation uses the newer Native Posix Thread Library (NPTL)
659** on linux - with NPTL a lock created by thread A can override locks
660** in thread B. But there is no way to know at compile-time which
661** threading library is being used. So there is no way to know at
662** compile-time whether or not thread A can override locks on thread B.
663** We have to do a run-time check to discover the behavior of the
664** current process.
drh5fdae772004-06-29 03:29:00 +0000665**
drh734c9862008-11-28 15:37:20 +0000666** On systems where thread A is unable to modify locks created by
667** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000668** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000669** structure to record this information. And on those systems it
670** is illegal to begin a transaction in one thread and finish it
671** in another. For this latter restriction, there is no work-around.
672** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000673*/
674
675/*
drh6c7d5c52008-11-21 20:32:33 +0000676** Set or check the unixFile.tid field. This field is set when an unixFile
677** is first opened. All subsequent uses of the unixFile verify that the
678** same thread is operating on the unixFile. Some operating systems do
679** not allow locks to be overridden by other threads and that restriction
680** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000681** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000682**
683** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
684** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000685** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000686** or if no locks are held. But the unixFile.pLock field needs to be
687** recomputed because its key includes the thread-id. See the
688** transferOwnership() function below for additional information
689*/
drh734c9862008-11-28 15:37:20 +0000690#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000691# define SET_THREADID(X) (X)->tid = pthread_self()
692# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
693 !pthread_equal((X)->tid, pthread_self()))
694#else
695# define SET_THREADID(X)
696# define CHECK_THREADID(X) 0
697#endif
698
699/*
drhbbd42a62004-05-22 17:41:58 +0000700** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000701** to locate a particular unixOpenCnt structure given its inode. This
702** is the same as the unixLockKey except that the thread ID is omitted.
703*/
704struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000705 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000706#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000707 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000708#else
drh107886a2008-11-21 22:21:50 +0000709 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000710#endif
711};
712
713/*
714** An instance of the following structure serves as the key used
715** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000716**
drh734c9862008-11-28 15:37:20 +0000717** If threads cannot override each others locks (LinuxThreads), then we
718** set the unixLockKey.tid field to the thread ID. If threads can override
719** each others locks (Posix and NPTL) then tid is always set to zero.
720** tid is omitted if we compile without threading support or on an OS
721** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000722*/
drh6c7d5c52008-11-21 20:32:33 +0000723struct unixLockKey {
724 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000725#if SQLITE_THREADSAFE && defined(__linux__)
726 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000727#endif
drhbbd42a62004-05-22 17:41:58 +0000728};
729
730/*
731** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000732** inode. Or, on LinuxThreads, there is one of these structures for
733** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000734**
danielk1977ad94b582007-08-20 06:44:22 +0000735** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000736** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000737** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000738*/
drh6c7d5c52008-11-21 20:32:33 +0000739struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000740 struct unixLockKey lockKey; /* The lookup key */
741 int cnt; /* Number of SHARED locks held */
742 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
743 int nRef; /* Number of pointers to this structure */
744 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
745 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000746};
747
748/*
749** An instance of the following structure is allocated for each open
750** inode. This structure keeps track of the number of locks on that
751** inode. If a close is attempted against an inode that is holding
752** locks, the close is deferred until all locks clear by adding the
753** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000754**
755** TODO: Consider changing this so that there is only a single file
756** descriptor for each open file, even when it is opened multiple times.
757** The close() system call would only occur when the last database
758** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000759*/
drh6c7d5c52008-11-21 20:32:33 +0000760struct unixOpenCnt {
761 struct unixFileId fileId; /* The lookup key */
762 int nRef; /* Number of pointers to this structure */
763 int nLock; /* Number of outstanding locks */
dane946c392009-08-22 11:39:46 +0000764 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh6c7d5c52008-11-21 20:32:33 +0000765#if OS_VXWORKS
766 sem_t *pSem; /* Named POSIX semaphore */
drh2238dcc2009-08-27 17:56:20 +0000767 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000768#endif
drh6c7d5c52008-11-21 20:32:33 +0000769 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000770};
771
drhda0e7682008-07-30 15:27:54 +0000772/*
drh9b35ea62008-11-29 02:20:26 +0000773** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
774** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000775** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000776** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000777*/
drh6c7d5c52008-11-21 20:32:33 +0000778static struct unixLockInfo *lockList = 0;
779static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000780
drh5fdae772004-06-29 03:29:00 +0000781/*
drh9b35ea62008-11-29 02:20:26 +0000782** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000783** locks.
784**
drh9b35ea62008-11-29 02:20:26 +0000785** 0: No. Threads cannot override each others locks. (LinuxThreads)
786** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000787** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000788**
drh5062d3a2006-01-31 23:03:35 +0000789** On some systems, we know at compile-time if threads can override each
790** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
791** will be set appropriately. On other systems, we have to check at
792** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
793** undefined.
794**
drhf1a221e2006-01-15 17:27:17 +0000795** This variable normally has file scope only. But during testing, we make
796** it a global so that the test code can change its value in order to verify
797** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000798*/
drh715ff302008-12-03 22:32:44 +0000799#if SQLITE_THREADSAFE && defined(__linux__)
800# ifndef SQLITE_THREAD_OVERRIDE_LOCK
801# define SQLITE_THREAD_OVERRIDE_LOCK -1
802# endif
803# ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000804int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000805# else
drh5062d3a2006-01-31 23:03:35 +0000806static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000807# endif
drh029b44b2006-01-15 00:13:15 +0000808#endif
drh5fdae772004-06-29 03:29:00 +0000809
810/*
811** This structure holds information passed into individual test
812** threads by the testThreadLockingBehavior() routine.
813*/
814struct threadTestData {
815 int fd; /* File to be locked */
816 struct flock lock; /* The locking operation */
817 int result; /* Result of the locking operation */
818};
819
drh6c7d5c52008-11-21 20:32:33 +0000820#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000821/*
danielk197741a6a612008-11-11 18:34:35 +0000822** This function is used as the main routine for a thread launched by
823** testThreadLockingBehavior(). It tests whether the shared-lock obtained
824** by the main thread in testThreadLockingBehavior() conflicts with a
825** hypothetical write-lock obtained by this thread on the same file.
826**
827** The write-lock is not actually acquired, as this is not possible if
828** the file is open in read-only mode (see ticket #3472).
829*/
drh5fdae772004-06-29 03:29:00 +0000830static void *threadLockingTest(void *pArg){
831 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000832 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000833 return pArg;
834}
drh6c7d5c52008-11-21 20:32:33 +0000835#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000836
drh6c7d5c52008-11-21 20:32:33 +0000837
838#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000839/*
840** This procedure attempts to determine whether or not threads
841** can override each others locks then sets the
842** threadsOverrideEachOthersLocks variable appropriately.
843*/
danielk19774d5238f2006-01-27 06:32:00 +0000844static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000845 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000846 int rc;
847 struct threadTestData d;
848 struct flock l;
849 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000850
851 fd = dup(fd_orig);
852 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000853 memset(&l, 0, sizeof(l));
854 l.l_type = F_RDLCK;
855 l.l_len = 1;
856 l.l_start = 0;
857 l.l_whence = SEEK_SET;
858 rc = fcntl(fd_orig, F_SETLK, &l);
859 if( rc!=0 ) return;
860 memset(&d, 0, sizeof(d));
861 d.fd = fd;
862 d.lock = l;
863 d.lock.l_type = F_WRLCK;
drh06150f92009-07-03 12:57:58 +0000864 if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
865 pthread_join(t, 0);
866 }
drh5fdae772004-06-29 03:29:00 +0000867 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000868 if( d.result!=0 ) return;
869 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000870}
drh06150f92009-07-03 12:57:58 +0000871#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000872
drhbbd42a62004-05-22 17:41:58 +0000873/*
drh6c7d5c52008-11-21 20:32:33 +0000874** Release a unixLockInfo structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000875**
876** The mutex entered using the unixEnterMutex() function must be held
877** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000878*/
879static void releaseLockInfo(struct unixLockInfo *pLock){
dan9359c7b2009-08-21 08:29:10 +0000880 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000881 if( pLock ){
882 pLock->nRef--;
883 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000884 if( pLock->pPrev ){
885 assert( pLock->pPrev->pNext==pLock );
886 pLock->pPrev->pNext = pLock->pNext;
887 }else{
888 assert( lockList==pLock );
889 lockList = pLock->pNext;
890 }
891 if( pLock->pNext ){
892 assert( pLock->pNext->pPrev==pLock );
893 pLock->pNext->pPrev = pLock->pPrev;
894 }
danielk1977e339d652008-06-28 11:23:00 +0000895 sqlite3_free(pLock);
896 }
drhbbd42a62004-05-22 17:41:58 +0000897 }
898}
899
900/*
drh6c7d5c52008-11-21 20:32:33 +0000901** Release a unixOpenCnt structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000902**
903** The mutex entered using the unixEnterMutex() function must be held
904** when this function is called.
drhbbd42a62004-05-22 17:41:58 +0000905*/
drh6c7d5c52008-11-21 20:32:33 +0000906static void releaseOpenCnt(struct unixOpenCnt *pOpen){
dan9359c7b2009-08-21 08:29:10 +0000907 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000908 if( pOpen ){
909 pOpen->nRef--;
910 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000911 if( pOpen->pPrev ){
912 assert( pOpen->pPrev->pNext==pOpen );
913 pOpen->pPrev->pNext = pOpen->pNext;
914 }else{
915 assert( openList==pOpen );
916 openList = pOpen->pNext;
917 }
918 if( pOpen->pNext ){
919 assert( pOpen->pNext->pPrev==pOpen );
920 pOpen->pNext->pPrev = pOpen->pPrev;
921 }
dane946c392009-08-22 11:39:46 +0000922 assert( !pOpen->pUnused );
danielk1977e339d652008-06-28 11:23:00 +0000923 sqlite3_free(pOpen);
924 }
drhbbd42a62004-05-22 17:41:58 +0000925 }
926}
927
drh6c7d5c52008-11-21 20:32:33 +0000928/*
929** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
930** describes that file descriptor. Create new ones if necessary. The
931** return values might be uninitialized if an error occurs.
932**
dan9359c7b2009-08-21 08:29:10 +0000933** The mutex entered using the unixEnterMutex() function must be held
934** when this function is called.
935**
drh6c7d5c52008-11-21 20:32:33 +0000936** Return an appropriate error code.
937*/
938static int findLockInfo(
939 unixFile *pFile, /* Unix file with file desc used in the key */
940 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
941 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
942){
943 int rc; /* System call return code */
944 int fd; /* The file descriptor for pFile */
945 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
946 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
947 struct stat statbuf; /* Low-level file information */
drh0d588bb2009-06-17 13:09:38 +0000948 struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000949 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
950
dan9359c7b2009-08-21 08:29:10 +0000951 assert( unixMutexHeld() );
952
drh6c7d5c52008-11-21 20:32:33 +0000953 /* Get low-level information about the file that we can used to
954 ** create a unique name for the file.
955 */
956 fd = pFile->h;
957 rc = fstat(fd, &statbuf);
958 if( rc!=0 ){
959 pFile->lastErrno = errno;
960#ifdef EOVERFLOW
961 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
962#endif
963 return SQLITE_IOERR;
964 }
965
drheb0d74f2009-02-03 15:27:02 +0000966#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000967 /* On OS X on an msdos filesystem, the inode number is reported
968 ** incorrectly for zero-size files. See ticket #3260. To work
969 ** around this problem (we consider it a bug in OS X, not SQLite)
970 ** we always increase the file size to 1 by writing a single byte
971 ** prior to accessing the inode number. The one byte written is
972 ** an ASCII 'S' character which also happens to be the first byte
973 ** in the header of every SQLite database. In this way, if there
974 ** is a race condition such that another thread has already populated
975 ** the first page of the database, no damage is done.
976 */
977 if( statbuf.st_size==0 ){
drheb0d74f2009-02-03 15:27:02 +0000978 rc = write(fd, "S", 1);
979 if( rc!=1 ){
980 return SQLITE_IOERR;
981 }
drh6c7d5c52008-11-21 20:32:33 +0000982 rc = fstat(fd, &statbuf);
983 if( rc!=0 ){
984 pFile->lastErrno = errno;
985 return SQLITE_IOERR;
986 }
987 }
drheb0d74f2009-02-03 15:27:02 +0000988#endif
drh6c7d5c52008-11-21 20:32:33 +0000989
990 memset(&lockKey, 0, sizeof(lockKey));
991 lockKey.fid.dev = statbuf.st_dev;
992#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000993 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000994#else
995 lockKey.fid.ino = statbuf.st_ino;
996#endif
drh734c9862008-11-28 15:37:20 +0000997#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000998 if( threadsOverrideEachOthersLocks<0 ){
999 testThreadLockingBehavior(fd);
1000 }
1001 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
1002#endif
1003 fileId = lockKey.fid;
1004 if( ppLock!=0 ){
1005 pLock = lockList;
1006 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
1007 pLock = pLock->pNext;
1008 }
1009 if( pLock==0 ){
1010 pLock = sqlite3_malloc( sizeof(*pLock) );
1011 if( pLock==0 ){
1012 rc = SQLITE_NOMEM;
1013 goto exit_findlockinfo;
1014 }
1015 pLock->lockKey = lockKey;
1016 pLock->nRef = 1;
1017 pLock->cnt = 0;
1018 pLock->locktype = 0;
1019 pLock->pNext = lockList;
1020 pLock->pPrev = 0;
1021 if( lockList ) lockList->pPrev = pLock;
1022 lockList = pLock;
1023 }else{
1024 pLock->nRef++;
1025 }
1026 *ppLock = pLock;
1027 }
1028 if( ppOpen!=0 ){
1029 pOpen = openList;
1030 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
1031 pOpen = pOpen->pNext;
1032 }
1033 if( pOpen==0 ){
1034 pOpen = sqlite3_malloc( sizeof(*pOpen) );
1035 if( pOpen==0 ){
1036 releaseLockInfo(pLock);
1037 rc = SQLITE_NOMEM;
1038 goto exit_findlockinfo;
1039 }
dane946c392009-08-22 11:39:46 +00001040 memset(pOpen, 0, sizeof(*pOpen));
drh6c7d5c52008-11-21 20:32:33 +00001041 pOpen->fileId = fileId;
1042 pOpen->nRef = 1;
drh6c7d5c52008-11-21 20:32:33 +00001043 pOpen->pNext = openList;
drh6c7d5c52008-11-21 20:32:33 +00001044 if( openList ) openList->pPrev = pOpen;
1045 openList = pOpen;
drh6c7d5c52008-11-21 20:32:33 +00001046 }else{
1047 pOpen->nRef++;
1048 }
1049 *ppOpen = pOpen;
1050 }
1051
1052exit_findlockinfo:
1053 return rc;
1054}
drh6c7d5c52008-11-21 20:32:33 +00001055
drh7708e972008-11-29 00:56:52 +00001056/*
1057** If we are currently in a different thread than the thread that the
1058** unixFile argument belongs to, then transfer ownership of the unixFile
1059** over to the current thread.
1060**
1061** A unixFile is only owned by a thread on systems that use LinuxThreads.
1062**
1063** Ownership transfer is only allowed if the unixFile is currently unlocked.
1064** If the unixFile is locked and an ownership is wrong, then return
1065** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1066*/
1067#if SQLITE_THREADSAFE && defined(__linux__)
1068static int transferOwnership(unixFile *pFile){
1069 int rc;
1070 pthread_t hSelf;
1071 if( threadsOverrideEachOthersLocks ){
1072 /* Ownership transfers not needed on this system */
1073 return SQLITE_OK;
1074 }
1075 hSelf = pthread_self();
1076 if( pthread_equal(pFile->tid, hSelf) ){
1077 /* We are still in the same thread */
1078 OSTRACE1("No-transfer, same thread\n");
1079 return SQLITE_OK;
1080 }
1081 if( pFile->locktype!=NO_LOCK ){
1082 /* We cannot change ownership while we are holding a lock! */
1083 return SQLITE_MISUSE;
1084 }
1085 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1086 pFile->h, pFile->tid, hSelf);
1087 pFile->tid = hSelf;
1088 if (pFile->pLock != NULL) {
1089 releaseLockInfo(pFile->pLock);
1090 rc = findLockInfo(pFile, &pFile->pLock, 0);
1091 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1092 locktypeName(pFile->locktype),
1093 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1094 return rc;
1095 } else {
1096 return SQLITE_OK;
1097 }
1098}
1099#else /* if not SQLITE_THREADSAFE */
1100 /* On single-threaded builds, ownership transfer is a no-op */
1101# define transferOwnership(X) SQLITE_OK
1102#endif /* SQLITE_THREADSAFE */
1103
aswift5b1a2562008-08-22 00:22:35 +00001104
1105/*
danielk197713adf8a2004-06-03 16:08:41 +00001106** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001107** file by this or any other process. If such a lock is held, set *pResOut
1108** to a non-zero value otherwise *pResOut is set to zero. The return value
1109** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001110*/
danielk1977861f7452008-06-05 11:39:11 +00001111static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001112 int rc = SQLITE_OK;
1113 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001114 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001115
danielk1977861f7452008-06-05 11:39:11 +00001116 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1117
drh054889e2005-11-30 03:20:31 +00001118 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001119 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001120
1121 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001122 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001123 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001124 }
1125
drh2ac3ee92004-06-07 16:27:46 +00001126 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001127 */
danielk197709480a92009-02-09 05:32:32 +00001128#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001129 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001130 struct flock lock;
1131 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001132 lock.l_start = RESERVED_BYTE;
1133 lock.l_len = 1;
1134 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001135 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1136 int tErrno = errno;
1137 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1138 pFile->lastErrno = tErrno;
1139 } else if( lock.l_type!=F_UNLCK ){
1140 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001141 }
1142 }
danielk197709480a92009-02-09 05:32:32 +00001143#endif
danielk197713adf8a2004-06-03 16:08:41 +00001144
drh6c7d5c52008-11-21 20:32:33 +00001145 unixLeaveMutex();
aswift5b1a2562008-08-22 00:22:35 +00001146 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001147
aswift5b1a2562008-08-22 00:22:35 +00001148 *pResOut = reserved;
1149 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001150}
1151
1152/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001153** Lock the file with the lock specified by parameter locktype - one
1154** of the following:
1155**
drh2ac3ee92004-06-07 16:27:46 +00001156** (1) SHARED_LOCK
1157** (2) RESERVED_LOCK
1158** (3) PENDING_LOCK
1159** (4) EXCLUSIVE_LOCK
1160**
drhb3e04342004-06-08 00:47:47 +00001161** Sometimes when requesting one lock state, additional lock states
1162** are inserted in between. The locking might fail on one of the later
1163** transitions leaving the lock state different from what it started but
1164** still short of its goal. The following chart shows the allowed
1165** transitions and the inserted intermediate states:
1166**
1167** UNLOCKED -> SHARED
1168** SHARED -> RESERVED
1169** SHARED -> (PENDING) -> EXCLUSIVE
1170** RESERVED -> (PENDING) -> EXCLUSIVE
1171** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001172**
drha6abd042004-06-09 17:37:22 +00001173** This routine will only increase a lock. Use the sqlite3OsUnlock()
1174** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001175*/
danielk197762079062007-08-15 17:08:46 +00001176static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001177 /* The following describes the implementation of the various locks and
1178 ** lock transitions in terms of the POSIX advisory shared and exclusive
1179 ** lock primitives (called read-locks and write-locks below, to avoid
1180 ** confusion with SQLite lock names). The algorithms are complicated
1181 ** slightly in order to be compatible with windows systems simultaneously
1182 ** accessing the same database file, in case that is ever required.
1183 **
1184 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1185 ** byte', each single bytes at well known offsets, and the 'shared byte
1186 ** range', a range of 510 bytes at a well known offset.
1187 **
1188 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1189 ** byte'. If this is successful, a random byte from the 'shared byte
1190 ** range' is read-locked and the lock on the 'pending byte' released.
1191 **
danielk197790ba3bd2004-06-25 08:32:25 +00001192 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1193 ** A RESERVED lock is implemented by grabbing a write-lock on the
1194 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001195 **
1196 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001197 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1198 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1199 ** obtained, but existing SHARED locks are allowed to persist. A process
1200 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1201 ** This property is used by the algorithm for rolling back a journal file
1202 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001203 **
danielk197790ba3bd2004-06-25 08:32:25 +00001204 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1205 ** implemented by obtaining a write-lock on the entire 'shared byte
1206 ** range'. Since all other locks require a read-lock on one of the bytes
1207 ** within this range, this ensures that no other locks are held on the
1208 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001209 **
1210 ** The reason a single byte cannot be used instead of the 'shared byte
1211 ** range' is that some versions of windows do not support read-locks. By
1212 ** locking a random byte from a range, concurrent SHARED locks may exist
1213 ** even if the locking primitive used is always a write-lock.
1214 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001215 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001216 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001217 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001218 struct flock lock;
1219 int s;
1220
drh054889e2005-11-30 03:20:31 +00001221 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001222 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001223 locktypeName(locktype), locktypeName(pFile->locktype),
1224 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001225
1226 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001227 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001228 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001229 */
drh054889e2005-11-30 03:20:31 +00001230 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001231 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001232 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001233 return SQLITE_OK;
1234 }
1235
drhb3e04342004-06-08 00:47:47 +00001236 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001237 */
drh054889e2005-11-30 03:20:31 +00001238 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001239 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001240 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001241
drh054889e2005-11-30 03:20:31 +00001242 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001243 */
drh6c7d5c52008-11-21 20:32:33 +00001244 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001245
drh029b44b2006-01-15 00:13:15 +00001246 /* Make sure the current thread owns the pFile.
1247 */
1248 rc = transferOwnership(pFile);
1249 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001250 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001251 return rc;
1252 }
drh64b1bea2006-01-15 02:30:57 +00001253 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001254
danielk1977ad94b582007-08-20 06:44:22 +00001255 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001256 ** handle that precludes the requested lock, return BUSY.
1257 */
drh054889e2005-11-30 03:20:31 +00001258 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001259 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001260 ){
1261 rc = SQLITE_BUSY;
1262 goto end_lock;
1263 }
1264
1265 /* If a SHARED lock is requested, and some thread using this PID already
1266 ** has a SHARED or RESERVED lock, then increment reference counts and
1267 ** return SQLITE_OK.
1268 */
1269 if( locktype==SHARED_LOCK &&
1270 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1271 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001272 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001273 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001274 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001275 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001276 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001277 goto end_lock;
1278 }
1279
danielk197713adf8a2004-06-03 16:08:41 +00001280 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001281
danielk19779a1d0ab2004-06-01 14:09:28 +00001282 lock.l_whence = SEEK_SET;
1283
drh3cde3bb2004-06-12 02:17:14 +00001284 /* A PENDING lock is needed before acquiring a SHARED lock and before
1285 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1286 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001287 */
drh3cde3bb2004-06-12 02:17:14 +00001288 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001289 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001290 ){
danielk1977489468c2004-06-28 08:25:47 +00001291 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001292 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001293 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001294 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001295 int tErrno = errno;
1296 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1297 if( IS_LOCK_ERROR(rc) ){
1298 pFile->lastErrno = tErrno;
1299 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001300 goto end_lock;
1301 }
drh3cde3bb2004-06-12 02:17:14 +00001302 }
1303
1304
1305 /* If control gets to this point, then actually go ahead and make
1306 ** operating system calls for the specified lock.
1307 */
1308 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001309 int tErrno = 0;
drh3cde3bb2004-06-12 02:17:14 +00001310 assert( pLock->cnt==0 );
1311 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001312
drh2ac3ee92004-06-07 16:27:46 +00001313 /* Now get the read-lock */
1314 lock.l_start = SHARED_FIRST;
1315 lock.l_len = SHARED_SIZE;
aswift5b1a2562008-08-22 00:22:35 +00001316 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1317 tErrno = errno;
1318 }
drh2ac3ee92004-06-07 16:27:46 +00001319 /* Drop the temporary PENDING lock */
1320 lock.l_start = PENDING_BYTE;
1321 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001322 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001323 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001324 if( s != -1 ){
1325 /* This could happen with a network mount */
1326 tErrno = errno;
1327 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1328 if( IS_LOCK_ERROR(rc) ){
1329 pFile->lastErrno = tErrno;
1330 }
1331 goto end_lock;
1332 }
drh2b4b5962005-06-15 17:47:55 +00001333 }
drhe2396a12007-03-29 20:19:58 +00001334 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001335 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1336 if( IS_LOCK_ERROR(rc) ){
1337 pFile->lastErrno = tErrno;
1338 }
drhbbd42a62004-05-22 17:41:58 +00001339 }else{
drh054889e2005-11-30 03:20:31 +00001340 pFile->locktype = SHARED_LOCK;
1341 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001342 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001343 }
drh3cde3bb2004-06-12 02:17:14 +00001344 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1345 /* We are trying for an exclusive lock but another thread in this
1346 ** same process is still holding a shared lock. */
1347 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001348 }else{
drh3cde3bb2004-06-12 02:17:14 +00001349 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001350 ** assumed that there is a SHARED or greater lock on the file
1351 ** already.
1352 */
drh054889e2005-11-30 03:20:31 +00001353 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001354 lock.l_type = F_WRLCK;
1355 switch( locktype ){
1356 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001357 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001358 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001359 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001360 lock.l_start = SHARED_FIRST;
1361 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001362 break;
1363 default:
1364 assert(0);
1365 }
drh054889e2005-11-30 03:20:31 +00001366 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001367 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001368 int tErrno = errno;
1369 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1370 if( IS_LOCK_ERROR(rc) ){
1371 pFile->lastErrno = tErrno;
1372 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001373 }
drhbbd42a62004-05-22 17:41:58 +00001374 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001375
drh8f941bc2009-01-14 23:03:40 +00001376
1377#ifndef NDEBUG
1378 /* Set up the transaction-counter change checking flags when
1379 ** transitioning from a SHARED to a RESERVED lock. The change
1380 ** from SHARED to RESERVED marks the beginning of a normal
1381 ** write operation (not a hot journal rollback).
1382 */
1383 if( rc==SQLITE_OK
1384 && pFile->locktype<=SHARED_LOCK
1385 && locktype==RESERVED_LOCK
1386 ){
1387 pFile->transCntrChng = 0;
1388 pFile->dbUpdate = 0;
1389 pFile->inNormalWrite = 1;
1390 }
1391#endif
1392
1393
danielk1977ecb2a962004-06-02 06:30:16 +00001394 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001395 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001396 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001397 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001398 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001399 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001400 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001401
1402end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001403 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001404 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001405 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001406 return rc;
1407}
1408
1409/*
dane946c392009-08-22 11:39:46 +00001410** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
1411** If all such file descriptors are closed without error, the list is
1412** cleared and SQLITE_OK returned.
dan08da86a2009-08-21 17:18:03 +00001413**
1414** Otherwise, if an error occurs, then successfully closed file descriptor
dane946c392009-08-22 11:39:46 +00001415** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
dan08da86a2009-08-21 17:18:03 +00001416** not deleted and SQLITE_IOERR_CLOSE returned.
1417*/
1418static int closePendingFds(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001419 int rc = SQLITE_OK;
dane946c392009-08-22 11:39:46 +00001420 struct unixOpenCnt *pOpen = pFile->pOpen;
1421 UnixUnusedFd *pError = 0;
1422 UnixUnusedFd *p;
1423 UnixUnusedFd *pNext;
1424 for(p=pOpen->pUnused; p; p=pNext){
1425 pNext = p->pNext;
1426 if( close(p->fd) ){
1427 pFile->lastErrno = errno;
1428 rc = SQLITE_IOERR_CLOSE;
1429 p->pNext = pError;
1430 pError = p;
dane946c392009-08-22 11:39:46 +00001431 }else{
1432 sqlite3_free(p);
dan08da86a2009-08-21 17:18:03 +00001433 }
1434 }
dane946c392009-08-22 11:39:46 +00001435 pOpen->pUnused = pError;
dan08da86a2009-08-21 17:18:03 +00001436 return rc;
1437}
1438
1439/*
1440** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001441** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001442*/
1443static void setPendingFd(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001444 struct unixOpenCnt *pOpen = pFile->pOpen;
dane946c392009-08-22 11:39:46 +00001445 UnixUnusedFd *p = pFile->pUnused;
1446 p->pNext = pOpen->pUnused;
1447 pOpen->pUnused = p;
1448 pFile->h = -1;
1449 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001450}
1451
1452/*
drh054889e2005-11-30 03:20:31 +00001453** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001454** must be either NO_LOCK or SHARED_LOCK.
1455**
1456** If the locking level of the file descriptor is already at or below
1457** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001458*/
danielk197762079062007-08-15 17:08:46 +00001459static int unixUnlock(sqlite3_file *id, int locktype){
drh6c7d5c52008-11-21 20:32:33 +00001460 struct unixLockInfo *pLock;
drha6abd042004-06-09 17:37:22 +00001461 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001462 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001463 unixFile *pFile = (unixFile*)id;
drh1aa5af12008-03-07 19:51:14 +00001464 int h;
drha6abd042004-06-09 17:37:22 +00001465
drh054889e2005-11-30 03:20:31 +00001466 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001467 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001468 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001469
1470 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001471 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001472 return SQLITE_OK;
1473 }
drhf1a221e2006-01-15 17:27:17 +00001474 if( CHECK_THREADID(pFile) ){
1475 return SQLITE_MISUSE;
1476 }
drh6c7d5c52008-11-21 20:32:33 +00001477 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001478 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001479 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001480 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001481 if( pFile->locktype>SHARED_LOCK ){
1482 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001483 SimulateIOErrorBenign(1);
1484 SimulateIOError( h=(-1) )
1485 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001486
1487#ifndef NDEBUG
1488 /* When reducing a lock such that other processes can start
1489 ** reading the database file again, make sure that the
1490 ** transaction counter was updated if any part of the database
1491 ** file changed. If the transaction counter is not updated,
1492 ** other connections to the same file might not realize that
1493 ** the file has changed and hence might not know to flush their
1494 ** cache. The use of a stale cache can lead to database corruption.
1495 */
1496 assert( pFile->inNormalWrite==0
1497 || pFile->dbUpdate==0
1498 || pFile->transCntrChng==1 );
1499 pFile->inNormalWrite = 0;
1500#endif
1501
1502
drh9c105bb2004-10-02 20:38:28 +00001503 if( locktype==SHARED_LOCK ){
1504 lock.l_type = F_RDLCK;
1505 lock.l_whence = SEEK_SET;
1506 lock.l_start = SHARED_FIRST;
1507 lock.l_len = SHARED_SIZE;
drh1aa5af12008-03-07 19:51:14 +00001508 if( fcntl(h, F_SETLK, &lock)==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001509 int tErrno = errno;
1510 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1511 if( IS_LOCK_ERROR(rc) ){
1512 pFile->lastErrno = tErrno;
1513 }
danielk197709480a92009-02-09 05:32:32 +00001514 goto end_unlock;
drh9c105bb2004-10-02 20:38:28 +00001515 }
1516 }
drhbbd42a62004-05-22 17:41:58 +00001517 lock.l_type = F_UNLCK;
1518 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001519 lock.l_start = PENDING_BYTE;
1520 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001521 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001522 pLock->locktype = SHARED_LOCK;
1523 }else{
aswift5b1a2562008-08-22 00:22:35 +00001524 int tErrno = errno;
1525 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1526 if( IS_LOCK_ERROR(rc) ){
1527 pFile->lastErrno = tErrno;
1528 }
drhcd731cf2009-03-28 23:23:02 +00001529 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001530 }
drhbbd42a62004-05-22 17:41:58 +00001531 }
drha6abd042004-06-09 17:37:22 +00001532 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001533 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001534
drha6abd042004-06-09 17:37:22 +00001535 /* Decrement the shared lock counter. Release the lock using an
1536 ** OS call only when all threads in this same process have released
1537 ** the lock.
1538 */
1539 pLock->cnt--;
1540 if( pLock->cnt==0 ){
1541 lock.l_type = F_UNLCK;
1542 lock.l_whence = SEEK_SET;
1543 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001544 SimulateIOErrorBenign(1);
1545 SimulateIOError( h=(-1) )
1546 SimulateIOErrorBenign(0);
1547 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001548 pLock->locktype = NO_LOCK;
1549 }else{
aswift5b1a2562008-08-22 00:22:35 +00001550 int tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001551 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001552 if( IS_LOCK_ERROR(rc) ){
1553 pFile->lastErrno = tErrno;
1554 }
drhf48f9ca2009-03-28 23:47:10 +00001555 pLock->locktype = NO_LOCK;
1556 pFile->locktype = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001557 }
drha6abd042004-06-09 17:37:22 +00001558 }
1559
drhbbd42a62004-05-22 17:41:58 +00001560 /* Decrement the count of locks against this same file. When the
1561 ** count reaches zero, close any other file descriptors whose close
1562 ** was deferred because of outstanding locks.
1563 */
danielk197764a54c52009-03-30 07:39:35 +00001564 pOpen = pFile->pOpen;
1565 pOpen->nLock--;
1566 assert( pOpen->nLock>=0 );
dane946c392009-08-22 11:39:46 +00001567 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001568 int rc2 = closePendingFds(pFile);
1569 if( rc==SQLITE_OK ){
1570 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001571 }
drhbbd42a62004-05-22 17:41:58 +00001572 }
1573 }
aswift5b1a2562008-08-22 00:22:35 +00001574
1575end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001576 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001577 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001578 return rc;
drhbbd42a62004-05-22 17:41:58 +00001579}
1580
1581/*
danielk1977e339d652008-06-28 11:23:00 +00001582** This function performs the parts of the "close file" operation
1583** common to all locking schemes. It closes the directory and file
1584** handles, if they are valid, and sets all fields of the unixFile
1585** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001586**
1587** It is *not* necessary to hold the mutex when this routine is called,
1588** even on VxWorks. A mutex will be acquired on VxWorks by the
1589** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001590*/
1591static int closeUnixFile(sqlite3_file *id){
1592 unixFile *pFile = (unixFile*)id;
1593 if( pFile ){
1594 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001595 int err = close(pFile->dirfd);
1596 if( err ){
1597 pFile->lastErrno = errno;
1598 return SQLITE_IOERR_DIR_CLOSE;
1599 }else{
1600 pFile->dirfd=-1;
1601 }
danielk1977e339d652008-06-28 11:23:00 +00001602 }
1603 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001604 int err = close(pFile->h);
1605 if( err ){
1606 pFile->lastErrno = errno;
1607 return SQLITE_IOERR_CLOSE;
1608 }
danielk1977e339d652008-06-28 11:23:00 +00001609 }
drh6c7d5c52008-11-21 20:32:33 +00001610#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001611 if( pFile->pId ){
1612 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001613 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001614 }
drh107886a2008-11-21 22:21:50 +00001615 vxworksReleaseFileId(pFile->pId);
1616 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001617 }
1618#endif
danielk1977e339d652008-06-28 11:23:00 +00001619 OSTRACE2("CLOSE %-3d\n", pFile->h);
1620 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001621 sqlite3_free(pFile->pUnused);
danielk1977e339d652008-06-28 11:23:00 +00001622 memset(pFile, 0, sizeof(unixFile));
1623 }
1624 return SQLITE_OK;
1625}
1626
1627/*
danielk1977e3026632004-06-22 11:29:02 +00001628** Close a file.
1629*/
danielk197762079062007-08-15 17:08:46 +00001630static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001631 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001632 if( id ){
1633 unixFile *pFile = (unixFile *)id;
1634 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001635 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001636 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001637 /* If there are outstanding locks, do not actually close the file just
1638 ** yet because that would clear those locks. Instead, add the file
dane946c392009-08-22 11:39:46 +00001639 ** descriptor to pOpen->pUnused list. It will be automatically closed
1640 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001641 */
dan08da86a2009-08-21 17:18:03 +00001642 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001643 }
danielk1977e339d652008-06-28 11:23:00 +00001644 releaseLockInfo(pFile->pLock);
1645 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001646 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001647 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001648 }
aswiftaebf4132008-11-21 00:10:35 +00001649 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001650}
1651
drh734c9862008-11-28 15:37:20 +00001652/************** End of the posix advisory lock implementation *****************
1653******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001654
drh734c9862008-11-28 15:37:20 +00001655/******************************************************************************
1656****************************** No-op Locking **********************************
1657**
1658** Of the various locking implementations available, this is by far the
1659** simplest: locking is ignored. No attempt is made to lock the database
1660** file for reading or writing.
1661**
1662** This locking mode is appropriate for use on read-only databases
1663** (ex: databases that are burned into CD-ROM, for example.) It can
1664** also be used if the application employs some external mechanism to
1665** prevent simultaneous access of the same database by two or more
1666** database connections. But there is a serious risk of database
1667** corruption if this locking mode is used in situations where multiple
1668** database connections are accessing the same database file at the same
1669** time and one or more of those connections are writing.
1670*/
drhbfe66312006-10-03 17:40:40 +00001671
drh734c9862008-11-28 15:37:20 +00001672static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1673 UNUSED_PARAMETER(NotUsed);
1674 *pResOut = 0;
1675 return SQLITE_OK;
1676}
drh734c9862008-11-28 15:37:20 +00001677static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1678 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1679 return SQLITE_OK;
1680}
drh734c9862008-11-28 15:37:20 +00001681static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1682 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1683 return SQLITE_OK;
1684}
1685
1686/*
drh9b35ea62008-11-29 02:20:26 +00001687** Close the file.
drh734c9862008-11-28 15:37:20 +00001688*/
1689static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001690 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001691}
1692
1693/******************* End of the no-op lock implementation *********************
1694******************************************************************************/
1695
1696/******************************************************************************
1697************************* Begin dot-file Locking ******************************
1698**
1699** The dotfile locking implementation uses the existing of separate lock
1700** files in order to control access to the database. This works on just
1701** about every filesystem imaginable. But there are serious downsides:
1702**
1703** (1) There is zero concurrency. A single reader blocks all other
1704** connections from reading or writing the database.
1705**
1706** (2) An application crash or power loss can leave stale lock files
1707** sitting around that need to be cleared manually.
1708**
1709** Nevertheless, a dotlock is an appropriate locking mode for use if no
1710** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001711**
1712** Dotfile locking works by creating a file in the same directory as the
1713** database and with the same name but with a ".lock" extension added.
1714** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1715** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001716*/
1717
1718/*
1719** The file suffix added to the data base filename in order to create the
1720** lock file.
1721*/
1722#define DOTLOCK_SUFFIX ".lock"
1723
drh7708e972008-11-29 00:56:52 +00001724/*
1725** This routine checks if there is a RESERVED lock held on the specified
1726** file by this or any other process. If such a lock is held, set *pResOut
1727** to a non-zero value otherwise *pResOut is set to zero. The return value
1728** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1729**
1730** In dotfile locking, either a lock exists or it does not. So in this
1731** variation of CheckReservedLock(), *pResOut is set to true if any lock
1732** is held on the file and false if the file is unlocked.
1733*/
drh734c9862008-11-28 15:37:20 +00001734static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1735 int rc = SQLITE_OK;
1736 int reserved = 0;
1737 unixFile *pFile = (unixFile*)id;
1738
1739 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1740
1741 assert( pFile );
1742
1743 /* Check if a thread in this process holds such a lock */
1744 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001745 /* Either this connection or some other connection in the same process
1746 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001747 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001748 }else{
1749 /* The lock is held if and only if the lockfile exists */
1750 const char *zLockFile = (const char*)pFile->lockingContext;
1751 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001752 }
1753 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001754 *pResOut = reserved;
1755 return rc;
1756}
1757
drh7708e972008-11-29 00:56:52 +00001758/*
1759** Lock the file with the lock specified by parameter locktype - one
1760** of the following:
1761**
1762** (1) SHARED_LOCK
1763** (2) RESERVED_LOCK
1764** (3) PENDING_LOCK
1765** (4) EXCLUSIVE_LOCK
1766**
1767** Sometimes when requesting one lock state, additional lock states
1768** are inserted in between. The locking might fail on one of the later
1769** transitions leaving the lock state different from what it started but
1770** still short of its goal. The following chart shows the allowed
1771** transitions and the inserted intermediate states:
1772**
1773** UNLOCKED -> SHARED
1774** SHARED -> RESERVED
1775** SHARED -> (PENDING) -> EXCLUSIVE
1776** RESERVED -> (PENDING) -> EXCLUSIVE
1777** PENDING -> EXCLUSIVE
1778**
1779** This routine will only increase a lock. Use the sqlite3OsUnlock()
1780** routine to lower a locking level.
1781**
1782** With dotfile locking, we really only support state (4): EXCLUSIVE.
1783** But we track the other locking levels internally.
1784*/
drh734c9862008-11-28 15:37:20 +00001785static int dotlockLock(sqlite3_file *id, int locktype) {
1786 unixFile *pFile = (unixFile*)id;
1787 int fd;
1788 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001789 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001790
drh7708e972008-11-29 00:56:52 +00001791
1792 /* If we have any lock, then the lock file already exists. All we have
1793 ** to do is adjust our internal record of the lock level.
1794 */
1795 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001796 pFile->locktype = locktype;
1797#if !OS_VXWORKS
1798 /* Always update the timestamp on the old file */
1799 utimes(zLockFile, NULL);
1800#endif
drh7708e972008-11-29 00:56:52 +00001801 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001802 }
1803
1804 /* grab an exclusive lock */
1805 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1806 if( fd<0 ){
1807 /* failed to open/create the file, someone else may have stolen the lock */
1808 int tErrno = errno;
1809 if( EEXIST == tErrno ){
1810 rc = SQLITE_BUSY;
1811 } else {
1812 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1813 if( IS_LOCK_ERROR(rc) ){
1814 pFile->lastErrno = tErrno;
1815 }
1816 }
drh7708e972008-11-29 00:56:52 +00001817 return rc;
drh734c9862008-11-28 15:37:20 +00001818 }
1819 if( close(fd) ){
1820 pFile->lastErrno = errno;
1821 rc = SQLITE_IOERR_CLOSE;
1822 }
1823
1824 /* got it, set the type and return ok */
1825 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001826 return rc;
1827}
1828
drh7708e972008-11-29 00:56:52 +00001829/*
1830** Lower the locking level on file descriptor pFile to locktype. locktype
1831** must be either NO_LOCK or SHARED_LOCK.
1832**
1833** If the locking level of the file descriptor is already at or below
1834** the requested locking level, this routine is a no-op.
1835**
1836** When the locking level reaches NO_LOCK, delete the lock file.
1837*/
drh734c9862008-11-28 15:37:20 +00001838static int dotlockUnlock(sqlite3_file *id, int locktype) {
1839 unixFile *pFile = (unixFile*)id;
1840 char *zLockFile = (char *)pFile->lockingContext;
1841
1842 assert( pFile );
1843 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1844 pFile->locktype, getpid());
1845 assert( locktype<=SHARED_LOCK );
1846
1847 /* no-op if possible */
1848 if( pFile->locktype==locktype ){
1849 return SQLITE_OK;
1850 }
drh7708e972008-11-29 00:56:52 +00001851
1852 /* To downgrade to shared, simply update our internal notion of the
1853 ** lock state. No need to mess with the file on disk.
1854 */
1855 if( locktype==SHARED_LOCK ){
1856 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001857 return SQLITE_OK;
1858 }
1859
drh7708e972008-11-29 00:56:52 +00001860 /* To fully unlock the database, delete the lock file */
1861 assert( locktype==NO_LOCK );
1862 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001863 int rc = 0;
1864 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001865 if( ENOENT != tErrno ){
1866 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1867 }
1868 if( IS_LOCK_ERROR(rc) ){
1869 pFile->lastErrno = tErrno;
1870 }
1871 return rc;
1872 }
1873 pFile->locktype = NO_LOCK;
1874 return SQLITE_OK;
1875}
1876
1877/*
drh9b35ea62008-11-29 02:20:26 +00001878** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001879*/
1880static int dotlockClose(sqlite3_file *id) {
1881 int rc;
1882 if( id ){
1883 unixFile *pFile = (unixFile*)id;
1884 dotlockUnlock(id, NO_LOCK);
1885 sqlite3_free(pFile->lockingContext);
1886 }
drh734c9862008-11-28 15:37:20 +00001887 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001888 return rc;
1889}
1890/****************** End of the dot-file lock implementation *******************
1891******************************************************************************/
1892
1893/******************************************************************************
1894************************** Begin flock Locking ********************************
1895**
1896** Use the flock() system call to do file locking.
1897**
drh6b9d6dd2008-12-03 19:34:47 +00001898** flock() locking is like dot-file locking in that the various
1899** fine-grain locking levels supported by SQLite are collapsed into
1900** a single exclusive lock. In other words, SHARED, RESERVED, and
1901** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1902** still works when you do this, but concurrency is reduced since
1903** only a single process can be reading the database at a time.
1904**
drh734c9862008-11-28 15:37:20 +00001905** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1906** compiling for VXWORKS.
1907*/
1908#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001909
drh6b9d6dd2008-12-03 19:34:47 +00001910/*
1911** This routine checks if there is a RESERVED lock held on the specified
1912** file by this or any other process. If such a lock is held, set *pResOut
1913** to a non-zero value otherwise *pResOut is set to zero. The return value
1914** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1915*/
drh734c9862008-11-28 15:37:20 +00001916static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1917 int rc = SQLITE_OK;
1918 int reserved = 0;
1919 unixFile *pFile = (unixFile*)id;
1920
1921 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1922
1923 assert( pFile );
1924
1925 /* Check if a thread in this process holds such a lock */
1926 if( pFile->locktype>SHARED_LOCK ){
1927 reserved = 1;
1928 }
1929
1930 /* Otherwise see if some other process holds it. */
1931 if( !reserved ){
1932 /* attempt to get the lock */
1933 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1934 if( !lrc ){
1935 /* got the lock, unlock it */
1936 lrc = flock(pFile->h, LOCK_UN);
1937 if ( lrc ) {
1938 int tErrno = errno;
1939 /* unlock failed with an error */
1940 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1941 if( IS_LOCK_ERROR(lrc) ){
1942 pFile->lastErrno = tErrno;
1943 rc = lrc;
1944 }
1945 }
1946 } else {
1947 int tErrno = errno;
1948 reserved = 1;
1949 /* someone else might have it reserved */
1950 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1951 if( IS_LOCK_ERROR(lrc) ){
1952 pFile->lastErrno = tErrno;
1953 rc = lrc;
1954 }
1955 }
1956 }
1957 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
1958
1959#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1960 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1961 rc = SQLITE_OK;
1962 reserved=1;
1963 }
1964#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1965 *pResOut = reserved;
1966 return rc;
1967}
1968
drh6b9d6dd2008-12-03 19:34:47 +00001969/*
1970** Lock the file with the lock specified by parameter locktype - one
1971** of the following:
1972**
1973** (1) SHARED_LOCK
1974** (2) RESERVED_LOCK
1975** (3) PENDING_LOCK
1976** (4) EXCLUSIVE_LOCK
1977**
1978** Sometimes when requesting one lock state, additional lock states
1979** are inserted in between. The locking might fail on one of the later
1980** transitions leaving the lock state different from what it started but
1981** still short of its goal. The following chart shows the allowed
1982** transitions and the inserted intermediate states:
1983**
1984** UNLOCKED -> SHARED
1985** SHARED -> RESERVED
1986** SHARED -> (PENDING) -> EXCLUSIVE
1987** RESERVED -> (PENDING) -> EXCLUSIVE
1988** PENDING -> EXCLUSIVE
1989**
1990** flock() only really support EXCLUSIVE locks. We track intermediate
1991** lock states in the sqlite3_file structure, but all locks SHARED or
1992** above are really EXCLUSIVE locks and exclude all other processes from
1993** access the file.
1994**
1995** This routine will only increase a lock. Use the sqlite3OsUnlock()
1996** routine to lower a locking level.
1997*/
drh734c9862008-11-28 15:37:20 +00001998static int flockLock(sqlite3_file *id, int locktype) {
1999 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002000 unixFile *pFile = (unixFile*)id;
2001
2002 assert( pFile );
2003
2004 /* if we already have a lock, it is exclusive.
2005 ** Just adjust level and punt on outta here. */
2006 if (pFile->locktype > NO_LOCK) {
2007 pFile->locktype = locktype;
2008 return SQLITE_OK;
2009 }
2010
2011 /* grab an exclusive lock */
2012
2013 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
2014 int tErrno = errno;
2015 /* didn't get, must be busy */
2016 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2017 if( IS_LOCK_ERROR(rc) ){
2018 pFile->lastErrno = tErrno;
2019 }
2020 } else {
2021 /* got it, set the type and return ok */
2022 pFile->locktype = locktype;
2023 }
2024 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
2025 rc==SQLITE_OK ? "ok" : "failed");
2026#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2027 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2028 rc = SQLITE_BUSY;
2029 }
2030#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2031 return rc;
2032}
2033
drh6b9d6dd2008-12-03 19:34:47 +00002034
2035/*
2036** Lower the locking level on file descriptor pFile to locktype. locktype
2037** must be either NO_LOCK or SHARED_LOCK.
2038**
2039** If the locking level of the file descriptor is already at or below
2040** the requested locking level, this routine is a no-op.
2041*/
drh734c9862008-11-28 15:37:20 +00002042static int flockUnlock(sqlite3_file *id, int locktype) {
2043 unixFile *pFile = (unixFile*)id;
2044
2045 assert( pFile );
2046 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2047 pFile->locktype, getpid());
2048 assert( locktype<=SHARED_LOCK );
2049
2050 /* no-op if possible */
2051 if( pFile->locktype==locktype ){
2052 return SQLITE_OK;
2053 }
2054
2055 /* shared can just be set because we always have an exclusive */
2056 if (locktype==SHARED_LOCK) {
2057 pFile->locktype = locktype;
2058 return SQLITE_OK;
2059 }
2060
2061 /* no, really, unlock. */
2062 int rc = flock(pFile->h, LOCK_UN);
2063 if (rc) {
2064 int r, tErrno = errno;
2065 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2066 if( IS_LOCK_ERROR(r) ){
2067 pFile->lastErrno = tErrno;
2068 }
2069#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2070 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2071 r = SQLITE_BUSY;
2072 }
2073#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2074
2075 return r;
2076 } else {
2077 pFile->locktype = NO_LOCK;
2078 return SQLITE_OK;
2079 }
2080}
2081
2082/*
2083** Close a file.
2084*/
2085static int flockClose(sqlite3_file *id) {
2086 if( id ){
2087 flockUnlock(id, NO_LOCK);
2088 }
2089 return closeUnixFile(id);
2090}
2091
2092#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2093
2094/******************* End of the flock lock implementation *********************
2095******************************************************************************/
2096
2097/******************************************************************************
2098************************ Begin Named Semaphore Locking ************************
2099**
2100** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002101**
2102** Semaphore locking is like dot-lock and flock in that it really only
2103** supports EXCLUSIVE locking. Only a single process can read or write
2104** the database file at a time. This reduces potential concurrency, but
2105** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002106*/
2107#if OS_VXWORKS
2108
drh6b9d6dd2008-12-03 19:34:47 +00002109/*
2110** This routine checks if there is a RESERVED lock held on the specified
2111** file by this or any other process. If such a lock is held, set *pResOut
2112** to a non-zero value otherwise *pResOut is set to zero. The return value
2113** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2114*/
drh734c9862008-11-28 15:37:20 +00002115static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2116 int rc = SQLITE_OK;
2117 int reserved = 0;
2118 unixFile *pFile = (unixFile*)id;
2119
2120 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2121
2122 assert( pFile );
2123
2124 /* Check if a thread in this process holds such a lock */
2125 if( pFile->locktype>SHARED_LOCK ){
2126 reserved = 1;
2127 }
2128
2129 /* Otherwise see if some other process holds it. */
2130 if( !reserved ){
2131 sem_t *pSem = pFile->pOpen->pSem;
2132 struct stat statBuf;
2133
2134 if( sem_trywait(pSem)==-1 ){
2135 int tErrno = errno;
2136 if( EAGAIN != tErrno ){
2137 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2138 pFile->lastErrno = tErrno;
2139 } else {
2140 /* someone else has the lock when we are in NO_LOCK */
2141 reserved = (pFile->locktype < SHARED_LOCK);
2142 }
2143 }else{
2144 /* we could have it if we want it */
2145 sem_post(pSem);
2146 }
2147 }
2148 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2149
2150 *pResOut = reserved;
2151 return rc;
2152}
2153
drh6b9d6dd2008-12-03 19:34:47 +00002154/*
2155** Lock the file with the lock specified by parameter locktype - one
2156** of the following:
2157**
2158** (1) SHARED_LOCK
2159** (2) RESERVED_LOCK
2160** (3) PENDING_LOCK
2161** (4) EXCLUSIVE_LOCK
2162**
2163** Sometimes when requesting one lock state, additional lock states
2164** are inserted in between. The locking might fail on one of the later
2165** transitions leaving the lock state different from what it started but
2166** still short of its goal. The following chart shows the allowed
2167** transitions and the inserted intermediate states:
2168**
2169** UNLOCKED -> SHARED
2170** SHARED -> RESERVED
2171** SHARED -> (PENDING) -> EXCLUSIVE
2172** RESERVED -> (PENDING) -> EXCLUSIVE
2173** PENDING -> EXCLUSIVE
2174**
2175** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2176** lock states in the sqlite3_file structure, but all locks SHARED or
2177** above are really EXCLUSIVE locks and exclude all other processes from
2178** access the file.
2179**
2180** This routine will only increase a lock. Use the sqlite3OsUnlock()
2181** routine to lower a locking level.
2182*/
drh734c9862008-11-28 15:37:20 +00002183static int semLock(sqlite3_file *id, int locktype) {
2184 unixFile *pFile = (unixFile*)id;
2185 int fd;
2186 sem_t *pSem = pFile->pOpen->pSem;
2187 int rc = SQLITE_OK;
2188
2189 /* if we already have a lock, it is exclusive.
2190 ** Just adjust level and punt on outta here. */
2191 if (pFile->locktype > NO_LOCK) {
2192 pFile->locktype = locktype;
2193 rc = SQLITE_OK;
2194 goto sem_end_lock;
2195 }
2196
2197 /* lock semaphore now but bail out when already locked. */
2198 if( sem_trywait(pSem)==-1 ){
2199 rc = SQLITE_BUSY;
2200 goto sem_end_lock;
2201 }
2202
2203 /* got it, set the type and return ok */
2204 pFile->locktype = locktype;
2205
2206 sem_end_lock:
2207 return rc;
2208}
2209
drh6b9d6dd2008-12-03 19:34:47 +00002210/*
2211** Lower the locking level on file descriptor pFile to locktype. locktype
2212** must be either NO_LOCK or SHARED_LOCK.
2213**
2214** If the locking level of the file descriptor is already at or below
2215** the requested locking level, this routine is a no-op.
2216*/
drh734c9862008-11-28 15:37:20 +00002217static int semUnlock(sqlite3_file *id, int locktype) {
2218 unixFile *pFile = (unixFile*)id;
2219 sem_t *pSem = pFile->pOpen->pSem;
2220
2221 assert( pFile );
2222 assert( pSem );
2223 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2224 pFile->locktype, getpid());
2225 assert( locktype<=SHARED_LOCK );
2226
2227 /* no-op if possible */
2228 if( pFile->locktype==locktype ){
2229 return SQLITE_OK;
2230 }
2231
2232 /* shared can just be set because we always have an exclusive */
2233 if (locktype==SHARED_LOCK) {
2234 pFile->locktype = locktype;
2235 return SQLITE_OK;
2236 }
2237
2238 /* no, really unlock. */
2239 if ( sem_post(pSem)==-1 ) {
2240 int rc, tErrno = errno;
2241 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2242 if( IS_LOCK_ERROR(rc) ){
2243 pFile->lastErrno = tErrno;
2244 }
2245 return rc;
2246 }
2247 pFile->locktype = NO_LOCK;
2248 return SQLITE_OK;
2249}
2250
2251/*
2252 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002253 */
drh734c9862008-11-28 15:37:20 +00002254static int semClose(sqlite3_file *id) {
2255 if( id ){
2256 unixFile *pFile = (unixFile*)id;
2257 semUnlock(id, NO_LOCK);
2258 assert( pFile );
2259 unixEnterMutex();
2260 releaseLockInfo(pFile->pLock);
2261 releaseOpenCnt(pFile->pOpen);
drh734c9862008-11-28 15:37:20 +00002262 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002263 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002264 }
2265 return SQLITE_OK;
2266}
2267
2268#endif /* OS_VXWORKS */
2269/*
2270** Named semaphore locking is only available on VxWorks.
2271**
2272*************** End of the named semaphore lock implementation ****************
2273******************************************************************************/
2274
2275
2276/******************************************************************************
2277*************************** Begin AFP Locking *********************************
2278**
2279** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2280** on Apple Macintosh computers - both OS9 and OSX.
2281**
2282** Third-party implementations of AFP are available. But this code here
2283** only works on OSX.
2284*/
2285
drhd2cb50b2009-01-09 21:41:17 +00002286#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002287/*
2288** The afpLockingContext structure contains all afp lock specific state
2289*/
drhbfe66312006-10-03 17:40:40 +00002290typedef struct afpLockingContext afpLockingContext;
2291struct afpLockingContext {
aswiftaebf4132008-11-21 00:10:35 +00002292 unsigned long long sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002293 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002294};
2295
2296struct ByteRangeLockPB2
2297{
2298 unsigned long long offset; /* offset to first byte to lock */
2299 unsigned long long length; /* nbr of bytes to lock */
2300 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2301 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2302 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2303 int fd; /* file desc to assoc this lock with */
2304};
2305
drhfd131da2007-08-07 17:13:03 +00002306#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002307
drh6b9d6dd2008-12-03 19:34:47 +00002308/*
2309** This is a utility for setting or clearing a bit-range lock on an
2310** AFP filesystem.
2311**
2312** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2313*/
2314static int afpSetLock(
2315 const char *path, /* Name of the file to be locked or unlocked */
2316 unixFile *pFile, /* Open file descriptor on path */
2317 unsigned long long offset, /* First byte to be locked */
2318 unsigned long long length, /* Number of bytes to lock */
2319 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002320){
drh6b9d6dd2008-12-03 19:34:47 +00002321 struct ByteRangeLockPB2 pb;
2322 int err;
drhbfe66312006-10-03 17:40:40 +00002323
2324 pb.unLockFlag = setLockFlag ? 0 : 1;
2325 pb.startEndFlag = 0;
2326 pb.offset = offset;
2327 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002328 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002329
2330 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002331 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2332 offset, length);
drhbfe66312006-10-03 17:40:40 +00002333 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2334 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002335 int rc;
2336 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002337 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2338 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002339#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2340 rc = SQLITE_BUSY;
2341#else
drh734c9862008-11-28 15:37:20 +00002342 rc = sqliteErrorFromPosixError(tErrno,
2343 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002344#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002345 if( IS_LOCK_ERROR(rc) ){
2346 pFile->lastErrno = tErrno;
2347 }
2348 return rc;
drhbfe66312006-10-03 17:40:40 +00002349 } else {
aswift5b1a2562008-08-22 00:22:35 +00002350 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002351 }
2352}
2353
drh6b9d6dd2008-12-03 19:34:47 +00002354/*
2355** This routine checks if there is a RESERVED lock held on the specified
2356** file by this or any other process. If such a lock is held, set *pResOut
2357** to a non-zero value otherwise *pResOut is set to zero. The return value
2358** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2359*/
danielk1977e339d652008-06-28 11:23:00 +00002360static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002361 int rc = SQLITE_OK;
2362 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002363 unixFile *pFile = (unixFile*)id;
2364
aswift5b1a2562008-08-22 00:22:35 +00002365 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2366
2367 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002368 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2369
2370 /* Check if a thread in this process holds such a lock */
2371 if( pFile->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002372 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002373 }
2374
2375 /* Otherwise see if some other process holds it.
2376 */
aswift5b1a2562008-08-22 00:22:35 +00002377 if( !reserved ){
2378 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002379 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002380 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002381 /* if we succeeded in taking the reserved lock, unlock it to restore
2382 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002383 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002384 } else {
2385 /* if we failed to get the lock then someone else must have it */
2386 reserved = 1;
2387 }
2388 if( IS_LOCK_ERROR(lrc) ){
2389 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002390 }
2391 }
drhbfe66312006-10-03 17:40:40 +00002392
aswift5b1a2562008-08-22 00:22:35 +00002393 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2394
2395 *pResOut = reserved;
2396 return rc;
drhbfe66312006-10-03 17:40:40 +00002397}
2398
drh6b9d6dd2008-12-03 19:34:47 +00002399/*
2400** Lock the file with the lock specified by parameter locktype - one
2401** of the following:
2402**
2403** (1) SHARED_LOCK
2404** (2) RESERVED_LOCK
2405** (3) PENDING_LOCK
2406** (4) EXCLUSIVE_LOCK
2407**
2408** Sometimes when requesting one lock state, additional lock states
2409** are inserted in between. The locking might fail on one of the later
2410** transitions leaving the lock state different from what it started but
2411** still short of its goal. The following chart shows the allowed
2412** transitions and the inserted intermediate states:
2413**
2414** UNLOCKED -> SHARED
2415** SHARED -> RESERVED
2416** SHARED -> (PENDING) -> EXCLUSIVE
2417** RESERVED -> (PENDING) -> EXCLUSIVE
2418** PENDING -> EXCLUSIVE
2419**
2420** This routine will only increase a lock. Use the sqlite3OsUnlock()
2421** routine to lower a locking level.
2422*/
danielk1977e339d652008-06-28 11:23:00 +00002423static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002424 int rc = SQLITE_OK;
2425 unixFile *pFile = (unixFile*)id;
2426 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002427
2428 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002429 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00002430 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
2431
drhbfe66312006-10-03 17:40:40 +00002432 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002433 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002434 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002435 */
drhbfe66312006-10-03 17:40:40 +00002436 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00002437 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002438 locktypeName(locktype));
2439 return SQLITE_OK;
2440 }
2441
2442 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00002443 */
drhbfe66312006-10-03 17:40:40 +00002444 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2445 assert( locktype!=PENDING_LOCK );
2446 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2447
2448 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002449 */
drh6c7d5c52008-11-21 20:32:33 +00002450 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002451
2452 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002453 */
drhbfe66312006-10-03 17:40:40 +00002454 rc = transferOwnership(pFile);
2455 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002456 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002457 return rc;
2458 }
2459
2460 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002461 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2462 ** be released.
2463 */
drhbfe66312006-10-03 17:40:40 +00002464 if( locktype==SHARED_LOCK
2465 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002466 ){
2467 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002468 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002469 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002470 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002471 goto afp_end_lock;
2472 }
2473 }
2474
2475 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002476 ** operating system calls for the specified lock.
2477 */
drhbfe66312006-10-03 17:40:40 +00002478 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002479 int lk, lrc1, lrc2, lrc1Errno;
drhbfe66312006-10-03 17:40:40 +00002480
aswift5b1a2562008-08-22 00:22:35 +00002481 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002482 /* note that the quality of the randomness doesn't matter that much */
2483 lk = random();
aswiftaebf4132008-11-21 00:10:35 +00002484 context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002485 lrc1 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002486 SHARED_FIRST+context->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002487 if( IS_LOCK_ERROR(lrc1) ){
2488 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002489 }
aswift5b1a2562008-08-22 00:22:35 +00002490 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002491 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002492
aswift5b1a2562008-08-22 00:22:35 +00002493 if( IS_LOCK_ERROR(lrc1) ) {
2494 pFile->lastErrno = lrc1Errno;
2495 rc = lrc1;
2496 goto afp_end_lock;
2497 } else if( IS_LOCK_ERROR(lrc2) ){
2498 rc = lrc2;
2499 goto afp_end_lock;
2500 } else if( lrc1 != SQLITE_OK ) {
2501 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002502 } else {
2503 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002504 pFile->pOpen->nLock++;
drhbfe66312006-10-03 17:40:40 +00002505 }
2506 }else{
2507 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2508 ** assumed that there is a SHARED or greater lock on the file
2509 ** already.
2510 */
2511 int failed = 0;
2512 assert( 0!=pFile->locktype );
2513 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2514 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002515 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drhbfe66312006-10-03 17:40:40 +00002516 }
2517 if (!failed && locktype == EXCLUSIVE_LOCK) {
2518 /* Acquire an EXCLUSIVE lock */
2519
2520 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002521 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002522 */
drh6b9d6dd2008-12-03 19:34:47 +00002523 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
aswiftaebf4132008-11-21 00:10:35 +00002524 context->sharedByte, 1, 0)) ){
2525 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002526 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002527 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002528 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002529 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002530 SHARED_FIRST + context->sharedByte, 1, 1)) ){
2531 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2532 ** a critical I/O error
2533 */
2534 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2535 SQLITE_IOERR_LOCK;
2536 goto afp_end_lock;
2537 }
2538 }else{
aswift5b1a2562008-08-22 00:22:35 +00002539 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002540 }
2541 }
aswift5b1a2562008-08-22 00:22:35 +00002542 if( failed ){
2543 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002544 }
2545 }
2546
2547 if( rc==SQLITE_OK ){
2548 pFile->locktype = locktype;
2549 }else if( locktype==EXCLUSIVE_LOCK ){
2550 pFile->locktype = PENDING_LOCK;
2551 }
2552
2553afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002554 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00002555 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002556 rc==SQLITE_OK ? "ok" : "failed");
2557 return rc;
2558}
2559
2560/*
drh339eb0b2008-03-07 15:34:11 +00002561** Lower the locking level on file descriptor pFile to locktype. locktype
2562** must be either NO_LOCK or SHARED_LOCK.
2563**
2564** If the locking level of the file descriptor is already at or below
2565** the requested locking level, this routine is a no-op.
2566*/
danielk1977e339d652008-06-28 11:23:00 +00002567static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002568 int rc = SQLITE_OK;
2569 unixFile *pFile = (unixFile*)id;
aswiftaebf4132008-11-21 00:10:35 +00002570 afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002571
2572 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002573 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00002574 pFile->locktype, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002575
drhbfe66312006-10-03 17:40:40 +00002576 assert( locktype<=SHARED_LOCK );
2577 if( pFile->locktype<=locktype ){
2578 return SQLITE_OK;
2579 }
2580 if( CHECK_THREADID(pFile) ){
2581 return SQLITE_MISUSE;
2582 }
drh6c7d5c52008-11-21 20:32:33 +00002583 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002584 if( pFile->locktype>SHARED_LOCK ){
aswiftaebf4132008-11-21 00:10:35 +00002585
2586 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002587 rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
aswiftaebf4132008-11-21 00:10:35 +00002588 if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
2589 /* only re-establish the shared lock if necessary */
2590 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002591 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
aswiftaebf4132008-11-21 00:10:35 +00002592 }
2593 }
2594 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002595 rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002596 }
2597 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002598 rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002599 }
2600 }else if( locktype==NO_LOCK ){
2601 /* clear the shared lock */
2602 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002603 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002604 }
drhbfe66312006-10-03 17:40:40 +00002605
aswiftaebf4132008-11-21 00:10:35 +00002606 if( rc==SQLITE_OK ){
2607 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00002608 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002609 pOpen->nLock--;
2610 assert( pOpen->nLock>=0 );
dan6aa657f2009-08-24 18:57:58 +00002611 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002612 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002613 }
2614 }
drhbfe66312006-10-03 17:40:40 +00002615 }
drh6c7d5c52008-11-21 20:32:33 +00002616 unixLeaveMutex();
dan08da86a2009-08-21 17:18:03 +00002617 if( rc==SQLITE_OK ){
2618 pFile->locktype = locktype;
2619 }
drhbfe66312006-10-03 17:40:40 +00002620 return rc;
2621}
2622
2623/*
drh339eb0b2008-03-07 15:34:11 +00002624** Close a file & cleanup AFP specific locking context
2625*/
danielk1977e339d652008-06-28 11:23:00 +00002626static int afpClose(sqlite3_file *id) {
2627 if( id ){
2628 unixFile *pFile = (unixFile*)id;
2629 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002630 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002631 if( pFile->pOpen && pFile->pOpen->nLock ){
2632 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002633 ** yet because that would clear those locks. Instead, add the file
2634 ** descriptor to pOpen->aPending. It will be automatically closed when
2635 ** the last lock is cleared.
2636 */
dan08da86a2009-08-21 17:18:03 +00002637 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002638 }
2639 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002640 sqlite3_free(pFile->lockingContext);
aswiftaebf4132008-11-21 00:10:35 +00002641 closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002642 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002643 }
aswiftaebf4132008-11-21 00:10:35 +00002644 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002645}
2646
drhd2cb50b2009-01-09 21:41:17 +00002647#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002648/*
2649** The code above is the AFP lock implementation. The code is specific
2650** to MacOSX and does not work on other unix platforms. No alternative
2651** is available. If you don't compile for a mac, then the "unix-afp"
2652** VFS is not available.
2653**
2654********************* End of the AFP lock implementation **********************
2655******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002656
drh734c9862008-11-28 15:37:20 +00002657
2658/******************************************************************************
2659**************** Non-locking sqlite3_file methods *****************************
2660**
2661** The next division contains implementations for all methods of the
2662** sqlite3_file object other than the locking methods. The locking
2663** methods were defined in divisions above (one locking method per
2664** division). Those methods that are common to all locking modes
2665** are gather together into this division.
2666*/
drhbfe66312006-10-03 17:40:40 +00002667
2668/*
drh734c9862008-11-28 15:37:20 +00002669** Seek to the offset passed as the second argument, then read cnt
2670** bytes into pBuf. Return the number of bytes actually read.
2671**
2672** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2673** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2674** one system to another. Since SQLite does not define USE_PREAD
2675** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2676** See tickets #2741 and #2681.
2677**
2678** To avoid stomping the errno value on a failed read the lastErrno value
2679** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002680*/
drh734c9862008-11-28 15:37:20 +00002681static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2682 int got;
2683 i64 newOffset;
2684 TIMER_START;
2685#if defined(USE_PREAD)
2686 got = pread(id->h, pBuf, cnt, offset);
2687 SimulateIOError( got = -1 );
2688#elif defined(USE_PREAD64)
2689 got = pread64(id->h, pBuf, cnt, offset);
2690 SimulateIOError( got = -1 );
2691#else
2692 newOffset = lseek(id->h, offset, SEEK_SET);
2693 SimulateIOError( newOffset-- );
2694 if( newOffset!=offset ){
2695 if( newOffset == -1 ){
2696 ((unixFile*)id)->lastErrno = errno;
2697 }else{
2698 ((unixFile*)id)->lastErrno = 0;
2699 }
2700 return -1;
2701 }
2702 got = read(id->h, pBuf, cnt);
2703#endif
2704 TIMER_END;
2705 if( got<0 ){
2706 ((unixFile*)id)->lastErrno = errno;
2707 }
2708 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2709 return got;
drhbfe66312006-10-03 17:40:40 +00002710}
2711
2712/*
drh734c9862008-11-28 15:37:20 +00002713** Read data from a file into a buffer. Return SQLITE_OK if all
2714** bytes were read successfully and SQLITE_IOERR if anything goes
2715** wrong.
drh339eb0b2008-03-07 15:34:11 +00002716*/
drh734c9862008-11-28 15:37:20 +00002717static int unixRead(
2718 sqlite3_file *id,
2719 void *pBuf,
2720 int amt,
2721 sqlite3_int64 offset
2722){
dan08da86a2009-08-21 17:18:03 +00002723 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002724 int got;
2725 assert( id );
drh08c6d442009-02-09 17:34:07 +00002726
dan08da86a2009-08-21 17:18:03 +00002727 /* If this is a database file (not a journal, master-journal or temp
2728 ** file), the bytes in the locking range should never be read or written. */
dane946c392009-08-22 11:39:46 +00002729 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002730 || offset>=PENDING_BYTE+512
2731 || offset+amt<=PENDING_BYTE
2732 );
drh08c6d442009-02-09 17:34:07 +00002733
dan08da86a2009-08-21 17:18:03 +00002734 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002735 if( got==amt ){
2736 return SQLITE_OK;
2737 }else if( got<0 ){
2738 /* lastErrno set by seekAndRead */
2739 return SQLITE_IOERR_READ;
2740 }else{
dan08da86a2009-08-21 17:18:03 +00002741 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002742 /* Unread parts of the buffer must be zero-filled */
2743 memset(&((char*)pBuf)[got], 0, amt-got);
2744 return SQLITE_IOERR_SHORT_READ;
2745 }
2746}
2747
2748/*
2749** Seek to the offset in id->offset then read cnt bytes into pBuf.
2750** Return the number of bytes actually read. Update the offset.
2751**
2752** To avoid stomping the errno value on a failed write the lastErrno value
2753** is set before returning.
2754*/
2755static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2756 int got;
2757 i64 newOffset;
2758 TIMER_START;
2759#if defined(USE_PREAD)
2760 got = pwrite(id->h, pBuf, cnt, offset);
2761#elif defined(USE_PREAD64)
2762 got = pwrite64(id->h, pBuf, cnt, offset);
2763#else
2764 newOffset = lseek(id->h, offset, SEEK_SET);
2765 if( newOffset!=offset ){
2766 if( newOffset == -1 ){
2767 ((unixFile*)id)->lastErrno = errno;
2768 }else{
2769 ((unixFile*)id)->lastErrno = 0;
2770 }
2771 return -1;
2772 }
2773 got = write(id->h, pBuf, cnt);
2774#endif
2775 TIMER_END;
2776 if( got<0 ){
2777 ((unixFile*)id)->lastErrno = errno;
2778 }
2779
2780 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2781 return got;
2782}
2783
2784
2785/*
2786** Write data from a buffer into a file. Return SQLITE_OK on success
2787** or some other error code on failure.
2788*/
2789static int unixWrite(
2790 sqlite3_file *id,
2791 const void *pBuf,
2792 int amt,
2793 sqlite3_int64 offset
2794){
dan08da86a2009-08-21 17:18:03 +00002795 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002796 int wrote = 0;
2797 assert( id );
2798 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002799
dan08da86a2009-08-21 17:18:03 +00002800 /* If this is a database file (not a journal, master-journal or temp
2801 ** file), the bytes in the locking range should never be read or written. */
dane946c392009-08-22 11:39:46 +00002802 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002803 || offset>=PENDING_BYTE+512
2804 || offset+amt<=PENDING_BYTE
2805 );
drh08c6d442009-02-09 17:34:07 +00002806
drh8f941bc2009-01-14 23:03:40 +00002807#ifndef NDEBUG
2808 /* If we are doing a normal write to a database file (as opposed to
2809 ** doing a hot-journal rollback or a write to some file other than a
2810 ** normal database file) then record the fact that the database
2811 ** has changed. If the transaction counter is modified, record that
2812 ** fact too.
2813 */
dan08da86a2009-08-21 17:18:03 +00002814 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002815 pFile->dbUpdate = 1; /* The database has been modified */
2816 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002817 int rc;
drh8f941bc2009-01-14 23:03:40 +00002818 char oldCntr[4];
2819 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002820 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002821 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002822 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002823 pFile->transCntrChng = 1; /* The transaction counter has changed */
2824 }
2825 }
2826 }
2827#endif
2828
dan08da86a2009-08-21 17:18:03 +00002829 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002830 amt -= wrote;
2831 offset += wrote;
2832 pBuf = &((char*)pBuf)[wrote];
2833 }
2834 SimulateIOError(( wrote=(-1), amt=1 ));
2835 SimulateDiskfullError(( wrote=0, amt=1 ));
2836 if( amt>0 ){
2837 if( wrote<0 ){
2838 /* lastErrno set by seekAndWrite */
2839 return SQLITE_IOERR_WRITE;
2840 }else{
dan08da86a2009-08-21 17:18:03 +00002841 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002842 return SQLITE_FULL;
2843 }
2844 }
2845 return SQLITE_OK;
2846}
2847
2848#ifdef SQLITE_TEST
2849/*
2850** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002851** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002852*/
2853int sqlite3_sync_count = 0;
2854int sqlite3_fullsync_count = 0;
2855#endif
2856
2857/*
drh89240432009-03-25 01:06:01 +00002858** We do not trust systems to provide a working fdatasync(). Some do.
2859** Others do no. To be safe, we will stick with the (slower) fsync().
2860** If you know that your system does support fdatasync() correctly,
2861** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002862*/
drh89240432009-03-25 01:06:01 +00002863#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002864# define fdatasync fsync
2865#endif
2866
2867/*
2868** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2869** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2870** only available on Mac OS X. But that could change.
2871*/
2872#ifdef F_FULLFSYNC
2873# define HAVE_FULLFSYNC 1
2874#else
2875# define HAVE_FULLFSYNC 0
2876#endif
2877
2878
2879/*
2880** The fsync() system call does not work as advertised on many
2881** unix systems. The following procedure is an attempt to make
2882** it work better.
2883**
2884** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2885** for testing when we want to run through the test suite quickly.
2886** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2887** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2888** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002889**
2890** SQLite sets the dataOnly flag if the size of the file is unchanged.
2891** The idea behind dataOnly is that it should only write the file content
2892** to disk, not the inode. We only set dataOnly if the file size is
2893** unchanged since the file size is part of the inode. However,
2894** Ted Ts'o tells us that fdatasync() will also write the inode if the
2895** file size has changed. The only real difference between fdatasync()
2896** and fsync(), Ted tells us, is that fdatasync() will not flush the
2897** inode if the mtime or owner or other inode attributes have changed.
2898** We only care about the file size, not the other file attributes, so
2899** as far as SQLite is concerned, an fdatasync() is always adequate.
2900** So, we always use fdatasync() if it is available, regardless of
2901** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002902*/
2903static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002904 int rc;
drh734c9862008-11-28 15:37:20 +00002905
2906 /* The following "ifdef/elif/else/" block has the same structure as
2907 ** the one below. It is replicated here solely to avoid cluttering
2908 ** up the real code with the UNUSED_PARAMETER() macros.
2909 */
2910#ifdef SQLITE_NO_SYNC
2911 UNUSED_PARAMETER(fd);
2912 UNUSED_PARAMETER(fullSync);
2913 UNUSED_PARAMETER(dataOnly);
2914#elif HAVE_FULLFSYNC
2915 UNUSED_PARAMETER(dataOnly);
2916#else
2917 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002918 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002919#endif
2920
2921 /* Record the number of times that we do a normal fsync() and
2922 ** FULLSYNC. This is used during testing to verify that this procedure
2923 ** gets called with the correct arguments.
2924 */
2925#ifdef SQLITE_TEST
2926 if( fullSync ) sqlite3_fullsync_count++;
2927 sqlite3_sync_count++;
2928#endif
2929
2930 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2931 ** no-op
2932 */
2933#ifdef SQLITE_NO_SYNC
2934 rc = SQLITE_OK;
2935#elif HAVE_FULLFSYNC
2936 if( fullSync ){
2937 rc = fcntl(fd, F_FULLFSYNC, 0);
2938 }else{
2939 rc = 1;
2940 }
2941 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002942 ** It shouldn't be possible for fullfsync to fail on the local
2943 ** file system (on OSX), so failure indicates that FULLFSYNC
2944 ** isn't supported for this file system. So, attempt an fsync
2945 ** and (for now) ignore the overhead of a superfluous fcntl call.
2946 ** It'd be better to detect fullfsync support once and avoid
2947 ** the fcntl call every time sync is called.
2948 */
drh734c9862008-11-28 15:37:20 +00002949 if( rc ) rc = fsync(fd);
2950
2951#else
drh0b647ff2009-03-21 14:41:04 +00002952 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002953#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002954 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002955 rc = fsync(fd);
2956 }
drh0b647ff2009-03-21 14:41:04 +00002957#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00002958#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2959
2960 if( OS_VXWORKS && rc!= -1 ){
2961 rc = 0;
2962 }
chw97185482008-11-17 08:05:31 +00002963 return rc;
drhbfe66312006-10-03 17:40:40 +00002964}
2965
drh734c9862008-11-28 15:37:20 +00002966/*
2967** Make sure all writes to a particular file are committed to disk.
2968**
2969** If dataOnly==0 then both the file itself and its metadata (file
2970** size, access time, etc) are synced. If dataOnly!=0 then only the
2971** file data is synced.
2972**
2973** Under Unix, also make sure that the directory entry for the file
2974** has been created by fsync-ing the directory that contains the file.
2975** If we do not do this and we encounter a power failure, the directory
2976** entry for the journal might not exist after we reboot. The next
2977** SQLite to access the file will not know that the journal exists (because
2978** the directory entry for the journal was never created) and the transaction
2979** will not roll back - possibly leading to database corruption.
2980*/
2981static int unixSync(sqlite3_file *id, int flags){
2982 int rc;
2983 unixFile *pFile = (unixFile*)id;
2984
2985 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2986 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2987
2988 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2989 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2990 || (flags&0x0F)==SQLITE_SYNC_FULL
2991 );
2992
2993 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2994 ** line is to test that doing so does not cause any problems.
2995 */
2996 SimulateDiskfullError( return SQLITE_FULL );
2997
2998 assert( pFile );
2999 OSTRACE2("SYNC %-3d\n", pFile->h);
3000 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3001 SimulateIOError( rc=1 );
3002 if( rc ){
3003 pFile->lastErrno = errno;
3004 return SQLITE_IOERR_FSYNC;
3005 }
3006 if( pFile->dirfd>=0 ){
3007 int err;
3008 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3009 HAVE_FULLFSYNC, isFullsync);
3010#ifndef SQLITE_DISABLE_DIRSYNC
3011 /* The directory sync is only attempted if full_fsync is
3012 ** turned off or unavailable. If a full_fsync occurred above,
3013 ** then the directory sync is superfluous.
3014 */
3015 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3016 /*
3017 ** We have received multiple reports of fsync() returning
3018 ** errors when applied to directories on certain file systems.
3019 ** A failed directory sync is not a big deal. So it seems
3020 ** better to ignore the error. Ticket #1657
3021 */
3022 /* pFile->lastErrno = errno; */
3023 /* return SQLITE_IOERR; */
3024 }
3025#endif
3026 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3027 if( err==0 ){ /* directory when we are done */
3028 pFile->dirfd = -1;
3029 }else{
3030 pFile->lastErrno = errno;
3031 rc = SQLITE_IOERR_DIR_CLOSE;
3032 }
3033 }
3034 return rc;
3035}
3036
3037/*
3038** Truncate an open file to a specified size
3039*/
3040static int unixTruncate(sqlite3_file *id, i64 nByte){
3041 int rc;
3042 assert( id );
3043 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3044 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3045 if( rc ){
3046 ((unixFile*)id)->lastErrno = errno;
3047 return SQLITE_IOERR_TRUNCATE;
3048 }else{
3049 return SQLITE_OK;
3050 }
3051}
3052
3053/*
3054** Determine the current size of a file in bytes
3055*/
3056static int unixFileSize(sqlite3_file *id, i64 *pSize){
3057 int rc;
3058 struct stat buf;
3059 assert( id );
3060 rc = fstat(((unixFile*)id)->h, &buf);
3061 SimulateIOError( rc=1 );
3062 if( rc!=0 ){
3063 ((unixFile*)id)->lastErrno = errno;
3064 return SQLITE_IOERR_FSTAT;
3065 }
3066 *pSize = buf.st_size;
3067
3068 /* When opening a zero-size database, the findLockInfo() procedure
3069 ** writes a single byte into that file in order to work around a bug
3070 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3071 ** layers, we need to report this file size as zero even though it is
3072 ** really 1. Ticket #3260.
3073 */
3074 if( *pSize==1 ) *pSize = 0;
3075
3076
3077 return SQLITE_OK;
3078}
3079
drhd2cb50b2009-01-09 21:41:17 +00003080#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003081/*
3082** Handler for proxy-locking file-control verbs. Defined below in the
3083** proxying locking division.
3084*/
3085static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003086#endif
drh715ff302008-12-03 22:32:44 +00003087
danielk1977ad94b582007-08-20 06:44:22 +00003088
danielk1977e3026632004-06-22 11:29:02 +00003089/*
drh9e33c2c2007-08-31 18:34:59 +00003090** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003091*/
drhcc6bb3e2007-08-31 16:11:35 +00003092static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003093 switch( op ){
3094 case SQLITE_FCNTL_LOCKSTATE: {
3095 *(int*)pArg = ((unixFile*)id)->locktype;
3096 return SQLITE_OK;
3097 }
drh7708e972008-11-29 00:56:52 +00003098 case SQLITE_LAST_ERRNO: {
3099 *(int*)pArg = ((unixFile*)id)->lastErrno;
3100 return SQLITE_OK;
3101 }
drh8f941bc2009-01-14 23:03:40 +00003102#ifndef NDEBUG
3103 /* The pager calls this method to signal that it has done
3104 ** a rollback and that the database is therefore unchanged and
3105 ** it hence it is OK for the transaction change counter to be
3106 ** unchanged.
3107 */
3108 case SQLITE_FCNTL_DB_UNCHANGED: {
3109 ((unixFile*)id)->dbUpdate = 0;
3110 return SQLITE_OK;
3111 }
3112#endif
drhd2cb50b2009-01-09 21:41:17 +00003113#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003114 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003115 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003116 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003117 }
drhd2cb50b2009-01-09 21:41:17 +00003118#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003119 }
drhcc6bb3e2007-08-31 16:11:35 +00003120 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003121}
3122
3123/*
danielk1977a3d4c882007-03-23 10:08:38 +00003124** Return the sector size in bytes of the underlying block device for
3125** the specified file. This is almost always 512 bytes, but may be
3126** larger for some devices.
3127**
3128** SQLite code assumes this function cannot fail. It also assumes that
3129** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003130** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003131** same for both.
3132*/
danielk1977397d65f2008-11-19 11:35:39 +00003133static int unixSectorSize(sqlite3_file *NotUsed){
3134 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003135 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003136}
3137
danielk197790949c22007-08-17 16:50:38 +00003138/*
danielk1977397d65f2008-11-19 11:35:39 +00003139** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003140*/
danielk1977397d65f2008-11-19 11:35:39 +00003141static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3142 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003143 return 0;
3144}
3145
drh734c9862008-11-28 15:37:20 +00003146/*
3147** Here ends the implementation of all sqlite3_file methods.
3148**
3149********************** End sqlite3_file Methods *******************************
3150******************************************************************************/
3151
3152/*
drh6b9d6dd2008-12-03 19:34:47 +00003153** This division contains definitions of sqlite3_io_methods objects that
3154** implement various file locking strategies. It also contains definitions
3155** of "finder" functions. A finder-function is used to locate the appropriate
3156** sqlite3_io_methods object for a particular database file. The pAppData
3157** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3158** the correct finder-function for that VFS.
3159**
3160** Most finder functions return a pointer to a fixed sqlite3_io_methods
3161** object. The only interesting finder-function is autolockIoFinder, which
3162** looks at the filesystem type and tries to guess the best locking
3163** strategy from that.
3164**
drh1875f7a2008-12-08 18:19:17 +00003165** For finder-funtion F, two objects are created:
3166**
3167** (1) The real finder-function named "FImpt()".
3168**
dane946c392009-08-22 11:39:46 +00003169** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003170**
3171**
3172** A pointer to the F pointer is used as the pAppData value for VFS
3173** objects. We have to do this instead of letting pAppData point
3174** directly at the finder-function since C90 rules prevent a void*
3175** from be cast into a function pointer.
3176**
drh6b9d6dd2008-12-03 19:34:47 +00003177**
drh7708e972008-11-29 00:56:52 +00003178** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003179**
drh7708e972008-11-29 00:56:52 +00003180** * A constant sqlite3_io_methods object call METHOD that has locking
3181** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3182**
3183** * An I/O method finder function called FINDER that returns a pointer
3184** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003185*/
drh7708e972008-11-29 00:56:52 +00003186#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3187static const sqlite3_io_methods METHOD = { \
3188 1, /* iVersion */ \
3189 CLOSE, /* xClose */ \
3190 unixRead, /* xRead */ \
3191 unixWrite, /* xWrite */ \
3192 unixTruncate, /* xTruncate */ \
3193 unixSync, /* xSync */ \
3194 unixFileSize, /* xFileSize */ \
3195 LOCK, /* xLock */ \
3196 UNLOCK, /* xUnlock */ \
3197 CKLOCK, /* xCheckReservedLock */ \
3198 unixFileControl, /* xFileControl */ \
3199 unixSectorSize, /* xSectorSize */ \
3200 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3201}; \
drh1875f7a2008-12-08 18:19:17 +00003202static const sqlite3_io_methods *FINDER##Impl(const char *z, int h){ \
drh7708e972008-11-29 00:56:52 +00003203 UNUSED_PARAMETER(z); UNUSED_PARAMETER(h); \
3204 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003205} \
3206static const sqlite3_io_methods *(*const FINDER)(const char*,int) \
3207 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003208
3209/*
3210** Here are all of the sqlite3_io_methods objects for each of the
3211** locking strategies. Functions that return pointers to these methods
3212** are also created.
3213*/
3214IOMETHODS(
3215 posixIoFinder, /* Finder function name */
3216 posixIoMethods, /* sqlite3_io_methods object name */
3217 unixClose, /* xClose method */
3218 unixLock, /* xLock method */
3219 unixUnlock, /* xUnlock method */
3220 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003221)
drh7708e972008-11-29 00:56:52 +00003222IOMETHODS(
3223 nolockIoFinder, /* Finder function name */
3224 nolockIoMethods, /* sqlite3_io_methods object name */
3225 nolockClose, /* xClose method */
3226 nolockLock, /* xLock method */
3227 nolockUnlock, /* xUnlock method */
3228 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003229)
drh7708e972008-11-29 00:56:52 +00003230IOMETHODS(
3231 dotlockIoFinder, /* Finder function name */
3232 dotlockIoMethods, /* sqlite3_io_methods object name */
3233 dotlockClose, /* xClose method */
3234 dotlockLock, /* xLock method */
3235 dotlockUnlock, /* xUnlock method */
3236 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003237)
drh7708e972008-11-29 00:56:52 +00003238
chw78a13182009-04-07 05:35:03 +00003239#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003240IOMETHODS(
3241 flockIoFinder, /* Finder function name */
3242 flockIoMethods, /* sqlite3_io_methods object name */
3243 flockClose, /* xClose method */
3244 flockLock, /* xLock method */
3245 flockUnlock, /* xUnlock method */
3246 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003247)
drh7708e972008-11-29 00:56:52 +00003248#endif
3249
drh6c7d5c52008-11-21 20:32:33 +00003250#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003251IOMETHODS(
3252 semIoFinder, /* Finder function name */
3253 semIoMethods, /* sqlite3_io_methods object name */
3254 semClose, /* xClose method */
3255 semLock, /* xLock method */
3256 semUnlock, /* xUnlock method */
3257 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003258)
aswiftaebf4132008-11-21 00:10:35 +00003259#endif
drh7708e972008-11-29 00:56:52 +00003260
drhd2cb50b2009-01-09 21:41:17 +00003261#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003262IOMETHODS(
3263 afpIoFinder, /* Finder function name */
3264 afpIoMethods, /* sqlite3_io_methods object name */
3265 afpClose, /* xClose method */
3266 afpLock, /* xLock method */
3267 afpUnlock, /* xUnlock method */
3268 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003269)
drh715ff302008-12-03 22:32:44 +00003270#endif
3271
3272/*
3273** The proxy locking method is a "super-method" in the sense that it
3274** opens secondary file descriptors for the conch and lock files and
3275** it uses proxy, dot-file, AFP, and flock() locking methods on those
3276** secondary files. For this reason, the division that implements
3277** proxy locking is located much further down in the file. But we need
3278** to go ahead and define the sqlite3_io_methods and finder function
3279** for proxy locking here. So we forward declare the I/O methods.
3280*/
drhd2cb50b2009-01-09 21:41:17 +00003281#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003282static int proxyClose(sqlite3_file*);
3283static int proxyLock(sqlite3_file*, int);
3284static int proxyUnlock(sqlite3_file*, int);
3285static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003286IOMETHODS(
3287 proxyIoFinder, /* Finder function name */
3288 proxyIoMethods, /* sqlite3_io_methods object name */
3289 proxyClose, /* xClose method */
3290 proxyLock, /* xLock method */
3291 proxyUnlock, /* xUnlock method */
3292 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003293)
aswiftaebf4132008-11-21 00:10:35 +00003294#endif
drh7708e972008-11-29 00:56:52 +00003295
3296
drhd2cb50b2009-01-09 21:41:17 +00003297#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003298/*
drh6b9d6dd2008-12-03 19:34:47 +00003299** This "finder" function attempts to determine the best locking strategy
3300** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003301** object that implements that strategy.
3302**
3303** This is for MacOSX only.
3304*/
drh1875f7a2008-12-08 18:19:17 +00003305static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003306 const char *filePath, /* name of the database file */
3307 int fd /* file descriptor open on the database file */
3308){
3309 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003310 const char *zFilesystem; /* Filesystem type name */
3311 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003312 } aMap[] = {
3313 { "hfs", &posixIoMethods },
3314 { "ufs", &posixIoMethods },
3315 { "afpfs", &afpIoMethods },
3316#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
3317 { "smbfs", &afpIoMethods },
3318#else
3319 { "smbfs", &flockIoMethods },
3320#endif
3321 { "webdav", &nolockIoMethods },
3322 { 0, 0 }
3323 };
3324 int i;
3325 struct statfs fsInfo;
3326 struct flock lockInfo;
3327
3328 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003329 /* If filePath==NULL that means we are dealing with a transient file
3330 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003331 return &nolockIoMethods;
3332 }
3333 if( statfs(filePath, &fsInfo) != -1 ){
3334 if( fsInfo.f_flags & MNT_RDONLY ){
3335 return &nolockIoMethods;
3336 }
3337 for(i=0; aMap[i].zFilesystem; i++){
3338 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3339 return aMap[i].pMethods;
3340 }
3341 }
3342 }
3343
3344 /* Default case. Handles, amongst others, "nfs".
3345 ** Test byte-range lock using fcntl(). If the call succeeds,
3346 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003347 */
drh7708e972008-11-29 00:56:52 +00003348 lockInfo.l_len = 1;
3349 lockInfo.l_start = 0;
3350 lockInfo.l_whence = SEEK_SET;
3351 lockInfo.l_type = F_RDLCK;
3352 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
3353 return &posixIoMethods;
3354 }else{
3355 return &dotlockIoMethods;
3356 }
3357}
danielk1977852e2322008-12-22 03:36:59 +00003358static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
drh1875f7a2008-12-08 18:19:17 +00003359 = autolockIoFinderImpl;
3360
drhd2cb50b2009-01-09 21:41:17 +00003361#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003362
chw78a13182009-04-07 05:35:03 +00003363#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
3364/*
3365** This "finder" function attempts to determine the best locking strategy
3366** for the database file "filePath". It then returns the sqlite3_io_methods
3367** object that implements that strategy.
3368**
3369** This is for VXWorks only.
3370*/
3371static const sqlite3_io_methods *autolockIoFinderImpl(
3372 const char *filePath, /* name of the database file */
3373 int fd /* file descriptor open on the database file */
3374){
3375 struct flock lockInfo;
3376
3377 if( !filePath ){
3378 /* If filePath==NULL that means we are dealing with a transient file
3379 ** that does not need to be locked. */
3380 return &nolockIoMethods;
3381 }
3382
3383 /* Test if fcntl() is supported and use POSIX style locks.
3384 ** Otherwise fall back to the named semaphore method.
3385 */
3386 lockInfo.l_len = 1;
3387 lockInfo.l_start = 0;
3388 lockInfo.l_whence = SEEK_SET;
3389 lockInfo.l_type = F_RDLCK;
3390 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
3391 return &posixIoMethods;
3392 }else{
3393 return &semIoMethods;
3394 }
3395}
3396static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
3397 = autolockIoFinderImpl;
3398
3399#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
3400
drh7708e972008-11-29 00:56:52 +00003401/*
3402** An abstract type for a pointer to a IO method finder function:
3403*/
3404typedef const sqlite3_io_methods *(*finder_type)(const char*,int);
3405
aswiftaebf4132008-11-21 00:10:35 +00003406
drh734c9862008-11-28 15:37:20 +00003407/****************************************************************************
3408**************************** sqlite3_vfs methods ****************************
3409**
3410** This division contains the implementation of methods on the
3411** sqlite3_vfs object.
3412*/
3413
danielk1977a3d4c882007-03-23 10:08:38 +00003414/*
danielk1977e339d652008-06-28 11:23:00 +00003415** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003416*/
3417static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003418 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003419 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003420 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003421 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003422 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003423 int noLock, /* Omit locking if true */
3424 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003425){
drh7708e972008-11-29 00:56:52 +00003426 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003427 unixFile *pNew = (unixFile *)pId;
3428 int rc = SQLITE_OK;
3429
danielk197717b90b52008-06-06 11:11:25 +00003430 assert( pNew->pLock==NULL );
3431 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003432
dane946c392009-08-22 11:39:46 +00003433 /* Parameter isDelete is only used on vxworks. Express this explicitly
3434 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003435 */
drh7708e972008-11-29 00:56:52 +00003436 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00003437
drh218c5082008-03-07 00:27:10 +00003438 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003439 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003440 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003441 SET_THREADID(pNew);
drh339eb0b2008-03-07 15:34:11 +00003442
drh6c7d5c52008-11-21 20:32:33 +00003443#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003444 pNew->pId = vxworksFindFileId(zFilename);
3445 if( pNew->pId==0 ){
3446 noLock = 1;
3447 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003448 }
3449#endif
3450
drhda0e7682008-07-30 15:27:54 +00003451 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003452 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003453 }else{
drh1875f7a2008-12-08 18:19:17 +00003454 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, h);
aswiftaebf4132008-11-21 00:10:35 +00003455#if SQLITE_ENABLE_LOCKING_STYLE
3456 /* Cache zFilename in the locking context (AFP and dotlock override) for
3457 ** proxyLock activation is possible (remote proxy is based on db name)
3458 ** zFilename remains valid until file is closed, to support */
3459 pNew->lockingContext = (void*)zFilename;
3460#endif
drhda0e7682008-07-30 15:27:54 +00003461 }
danielk1977e339d652008-06-28 11:23:00 +00003462
drh7708e972008-11-29 00:56:52 +00003463 if( pLockingStyle == &posixIoMethods ){
3464 unixEnterMutex();
3465 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
dane946c392009-08-22 11:39:46 +00003466 if( rc!=SQLITE_OK ){
3467 /* If an error occured in findLockInfo(), close the file descriptor
3468 ** immediately, before releasing the mutex. findLockInfo() may fail
3469 ** in two scenarios:
3470 **
3471 ** (a) A call to fstat() failed.
3472 ** (b) A malloc failed.
3473 **
3474 ** Scenario (b) may only occur if the process is holding no other
3475 ** file descriptors open on the same file. If there were other file
3476 ** descriptors on this file, then no malloc would be required by
3477 ** findLockInfo(). If this is the case, it is quite safe to close
3478 ** handle h - as it is guaranteed that no posix locks will be released
3479 ** by doing so.
3480 **
3481 ** If scenario (a) caused the error then things are not so safe. The
3482 ** implicit assumption here is that if fstat() fails, things are in
3483 ** such bad shape that dropping a lock or two doesn't matter much.
3484 */
3485 close(h);
3486 h = -1;
3487 }
drh7708e972008-11-29 00:56:52 +00003488 unixLeaveMutex();
3489 }
danielk1977e339d652008-06-28 11:23:00 +00003490
drhd2cb50b2009-01-09 21:41:17 +00003491#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003492 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003493 /* AFP locking uses the file path so it needs to be included in
3494 ** the afpLockingContext.
3495 */
3496 afpLockingContext *pCtx;
3497 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3498 if( pCtx==0 ){
3499 rc = SQLITE_NOMEM;
3500 }else{
3501 /* NB: zFilename exists and remains valid until the file is closed
3502 ** according to requirement F11141. So we do not need to make a
3503 ** copy of the filename. */
3504 pCtx->dbPath = zFilename;
3505 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003506 unixEnterMutex();
drh7708e972008-11-29 00:56:52 +00003507 rc = findLockInfo(pNew, NULL, &pNew->pOpen);
3508 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003509 }
drh7708e972008-11-29 00:56:52 +00003510 }
3511#endif
danielk1977e339d652008-06-28 11:23:00 +00003512
drh7708e972008-11-29 00:56:52 +00003513 else if( pLockingStyle == &dotlockIoMethods ){
3514 /* Dotfile locking uses the file path so it needs to be included in
3515 ** the dotlockLockingContext
3516 */
3517 char *zLockFile;
3518 int nFilename;
drhea678832008-12-10 19:26:22 +00003519 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003520 zLockFile = (char *)sqlite3_malloc(nFilename);
3521 if( zLockFile==0 ){
3522 rc = SQLITE_NOMEM;
3523 }else{
3524 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003525 }
drh7708e972008-11-29 00:56:52 +00003526 pNew->lockingContext = zLockFile;
3527 }
danielk1977e339d652008-06-28 11:23:00 +00003528
drh6c7d5c52008-11-21 20:32:33 +00003529#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003530 else if( pLockingStyle == &semIoMethods ){
3531 /* Named semaphore locking uses the file path so it needs to be
3532 ** included in the semLockingContext
3533 */
3534 unixEnterMutex();
3535 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3536 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3537 char *zSemName = pNew->pOpen->aSemName;
3538 int n;
drh2238dcc2009-08-27 17:56:20 +00003539 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00003540 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00003541 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00003542 if( zSemName[n]=='/' ) zSemName[n] = '_';
3543 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3544 if( pNew->pOpen->pSem == SEM_FAILED ){
3545 rc = SQLITE_NOMEM;
3546 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003547 }
chw97185482008-11-17 08:05:31 +00003548 }
drh7708e972008-11-29 00:56:52 +00003549 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003550 }
drh7708e972008-11-29 00:56:52 +00003551#endif
aswift5b1a2562008-08-22 00:22:35 +00003552
3553 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003554#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003555 if( rc!=SQLITE_OK ){
3556 unlink(zFilename);
3557 isDelete = 0;
3558 }
3559 pNew->isDelete = isDelete;
3560#endif
danielk1977e339d652008-06-28 11:23:00 +00003561 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003562 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00003563 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00003564 }else{
drh7708e972008-11-29 00:56:52 +00003565 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003566 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003567 }
danielk1977e339d652008-06-28 11:23:00 +00003568 return rc;
drh054889e2005-11-30 03:20:31 +00003569}
drh9c06c952005-11-26 00:25:00 +00003570
danielk1977ad94b582007-08-20 06:44:22 +00003571/*
3572** Open a file descriptor to the directory containing file zFilename.
3573** If successful, *pFd is set to the opened file descriptor and
3574** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3575** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3576** value.
3577**
3578** If SQLITE_OK is returned, the caller is responsible for closing
3579** the file descriptor *pFd using close().
3580*/
danielk1977fee2d252007-08-18 10:59:19 +00003581static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003582 int ii;
drh777b17a2007-09-20 10:02:54 +00003583 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003584 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003585
drh153c62c2007-08-24 03:51:33 +00003586 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003587 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003588 if( ii>0 ){
3589 zDirname[ii] = '\0';
3590 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003591 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003592#ifdef FD_CLOEXEC
3593 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3594#endif
3595 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3596 }
3597 }
danielk1977fee2d252007-08-18 10:59:19 +00003598 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00003599 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00003600}
3601
danielk1977b4b47412007-08-17 15:53:36 +00003602/*
danielk197717b90b52008-06-06 11:11:25 +00003603** Create a temporary file name in zBuf. zBuf must be allocated
3604** by the calling process and must be big enough to hold at least
3605** pVfs->mxPathname bytes.
3606*/
3607static int getTempname(int nBuf, char *zBuf){
3608 static const char *azDirs[] = {
3609 0,
aswiftaebf4132008-11-21 00:10:35 +00003610 0,
danielk197717b90b52008-06-06 11:11:25 +00003611 "/var/tmp",
3612 "/usr/tmp",
3613 "/tmp",
3614 ".",
3615 };
3616 static const unsigned char zChars[] =
3617 "abcdefghijklmnopqrstuvwxyz"
3618 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3619 "0123456789";
drh41022642008-11-21 00:24:42 +00003620 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003621 struct stat buf;
3622 const char *zDir = ".";
3623
3624 /* It's odd to simulate an io-error here, but really this is just
3625 ** using the io-error infrastructure to test that SQLite handles this
3626 ** function failing.
3627 */
3628 SimulateIOError( return SQLITE_IOERR );
3629
3630 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003631 if (NULL == azDirs[1]) {
3632 azDirs[1] = getenv("TMPDIR");
3633 }
3634
3635 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003636 if( azDirs[i]==0 ) continue;
3637 if( stat(azDirs[i], &buf) ) continue;
3638 if( !S_ISDIR(buf.st_mode) ) continue;
3639 if( access(azDirs[i], 07) ) continue;
3640 zDir = azDirs[i];
3641 break;
3642 }
3643
3644 /* Check that the output buffer is large enough for the temporary file
3645 ** name. If it is not, return SQLITE_ERROR.
3646 */
danielk197700e13612008-11-17 19:18:54 +00003647 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003648 return SQLITE_ERROR;
3649 }
3650
3651 do{
3652 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003653 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003654 sqlite3_randomness(15, &zBuf[j]);
3655 for(i=0; i<15; i++, j++){
3656 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3657 }
3658 zBuf[j] = 0;
3659 }while( access(zBuf,0)==0 );
3660 return SQLITE_OK;
3661}
3662
drhd2cb50b2009-01-09 21:41:17 +00003663#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003664/*
3665** Routine to transform a unixFile into a proxy-locking unixFile.
3666** Implementation in the proxy-lock division, but used by unixOpen()
3667** if SQLITE_PREFER_PROXY_LOCKING is defined.
3668*/
3669static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003670#endif
drhc66d5b62008-12-03 22:48:32 +00003671
dan08da86a2009-08-21 17:18:03 +00003672/*
3673** Search for an unused file descriptor that was opened on the database
3674** file (not a journal or master-journal file) identified by pathname
3675** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
3676** argument to this function.
3677**
3678** Such a file descriptor may exist if a database connection was closed
3679** but the associated file descriptor could not be closed because some
3680** other file descriptor open on the same file is holding a file-lock.
3681** Refer to comments in the unixClose() function and the lengthy comment
3682** describing "Posix Advisory Locking" at the start of this file for
3683** further details. Also, ticket #4018.
3684**
3685** If a suitable file descriptor is found, then it is returned. If no
3686** such file descriptor is located, -1 is returned.
3687*/
dane946c392009-08-22 11:39:46 +00003688static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
3689 UnixUnusedFd *pUnused = 0;
3690
3691 /* Do not search for an unused file descriptor on vxworks. Not because
3692 ** vxworks would not benefit from the change (it might, we're not sure),
3693 ** but because no way to test it is currently available. It is better
3694 ** not to risk breaking vxworks support for the sake of such an obscure
3695 ** feature. */
3696#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00003697 struct stat sStat; /* Results of stat() call */
3698
3699 /* A stat() call may fail for various reasons. If this happens, it is
3700 ** almost certain that an open() call on the same path will also fail.
3701 ** For this reason, if an error occurs in the stat() call here, it is
3702 ** ignored and -1 is returned. The caller will try to open a new file
3703 ** descriptor on the same path, fail, and return an error to SQLite.
3704 **
3705 ** Even if a subsequent open() call does succeed, the consequences of
3706 ** not searching for a resusable file descriptor are not dire. */
3707 if( 0==stat(zPath, &sStat) ){
dane946c392009-08-22 11:39:46 +00003708 struct unixOpenCnt *pO;
dan08da86a2009-08-21 17:18:03 +00003709 struct unixFileId id;
3710 id.dev = sStat.st_dev;
3711 id.ino = sStat.st_ino;
3712
3713 unixEnterMutex();
dane946c392009-08-22 11:39:46 +00003714 for(pO=openList; pO && memcmp(&id, &pO->fileId, sizeof(id)); pO=pO->pNext);
3715 if( pO ){
3716 UnixUnusedFd **pp;
3717 for(pp=&pO->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
3718 pUnused = *pp;
3719 if( pUnused ){
3720 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00003721 }
3722 }
3723 unixLeaveMutex();
3724 }
dane946c392009-08-22 11:39:46 +00003725#endif /* if !OS_VXWORKS */
3726 return pUnused;
dan08da86a2009-08-21 17:18:03 +00003727}
danielk197717b90b52008-06-06 11:11:25 +00003728
3729/*
danielk1977ad94b582007-08-20 06:44:22 +00003730** Open the file zPath.
3731**
danielk1977b4b47412007-08-17 15:53:36 +00003732** Previously, the SQLite OS layer used three functions in place of this
3733** one:
3734**
3735** sqlite3OsOpenReadWrite();
3736** sqlite3OsOpenReadOnly();
3737** sqlite3OsOpenExclusive();
3738**
3739** These calls correspond to the following combinations of flags:
3740**
3741** ReadWrite() -> (READWRITE | CREATE)
3742** ReadOnly() -> (READONLY)
3743** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
3744**
3745** The old OpenExclusive() accepted a boolean argument - "delFlag". If
3746** true, the file was configured to be automatically deleted when the
3747** file handle closed. To achieve the same effect using this new
3748** interface, add the DELETEONCLOSE flag to those specified above for
3749** OpenExclusive().
3750*/
3751static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00003752 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
3753 const char *zPath, /* Pathname of file to be opened */
3754 sqlite3_file *pFile, /* The file descriptor to be filled in */
3755 int flags, /* Input flags to control the opening */
3756 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00003757){
dan08da86a2009-08-21 17:18:03 +00003758 unixFile *p = (unixFile *)pFile;
3759 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00003760 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00003761 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00003762 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00003763 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00003764 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00003765
3766 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
3767 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
3768 int isCreate = (flags & SQLITE_OPEN_CREATE);
3769 int isReadonly = (flags & SQLITE_OPEN_READONLY);
3770 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
3771
danielk1977fee2d252007-08-18 10:59:19 +00003772 /* If creating a master or main-file journal, this function will open
3773 ** a file-descriptor on the directory too. The first time unixSync()
3774 ** is called the directory file descriptor will be fsync()ed and close()d.
3775 */
3776 int isOpenDirectory = (isCreate &&
3777 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
3778 );
3779
danielk197717b90b52008-06-06 11:11:25 +00003780 /* If argument zPath is a NULL pointer, this function is required to open
3781 ** a temporary file. Use this buffer to store the file name in.
3782 */
3783 char zTmpname[MAX_PATHNAME+1];
3784 const char *zName = zPath;
3785
danielk1977fee2d252007-08-18 10:59:19 +00003786 /* Check the following statements are true:
3787 **
3788 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
3789 ** (b) if CREATE is set, then READWRITE must also be set, and
3790 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00003791 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00003792 */
danielk1977b4b47412007-08-17 15:53:36 +00003793 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00003794 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00003795 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00003796 assert(isDelete==0 || isCreate);
3797
drh33f4e022007-09-03 15:19:34 +00003798 /* The main DB, main journal, and master journal are never automatically
dan08da86a2009-08-21 17:18:03 +00003799 ** deleted. Nor are they ever temporary files. */
3800 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
3801 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
3802 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danielk1977b4b47412007-08-17 15:53:36 +00003803
danielk1977fee2d252007-08-18 10:59:19 +00003804 /* Assert that the upper layer has set one of the "file-type" flags. */
3805 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
3806 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3807 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00003808 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00003809 );
3810
dan08da86a2009-08-21 17:18:03 +00003811 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00003812
dan08da86a2009-08-21 17:18:03 +00003813 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00003814 UnixUnusedFd *pUnused;
3815 pUnused = findReusableFd(zName, flags);
3816 if( pUnused ){
3817 fd = pUnused->fd;
3818 }else{
dan6aa657f2009-08-24 18:57:58 +00003819 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00003820 if( !pUnused ){
3821 return SQLITE_NOMEM;
3822 }
3823 }
3824 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00003825 }else if( !zName ){
3826 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00003827 assert(isDelete && !isOpenDirectory);
3828 rc = getTempname(MAX_PATHNAME+1, zTmpname);
3829 if( rc!=SQLITE_OK ){
3830 return rc;
3831 }
3832 zName = zTmpname;
3833 }
3834
dan08da86a2009-08-21 17:18:03 +00003835 /* Determine the value of the flags parameter passed to POSIX function
3836 ** open(). These must be calculated even if open() is not called, as
3837 ** they may be stored as part of the file handle and used by the
3838 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00003839 if( isReadonly ) openFlags |= O_RDONLY;
3840 if( isReadWrite ) openFlags |= O_RDWR;
3841 if( isCreate ) openFlags |= O_CREAT;
3842 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
3843 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00003844
danielk1977b4b47412007-08-17 15:53:36 +00003845 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00003846 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
3847 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00003848 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
3849 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
3850 /* Failed to open the file for read/write access. Try read-only. */
3851 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00003852 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00003853 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00003854 openFlags |= O_RDONLY;
3855 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00003856 }
3857 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00003858 rc = SQLITE_CANTOPEN;
3859 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00003860 }
danielk1977b4b47412007-08-17 15:53:36 +00003861 }
dan08da86a2009-08-21 17:18:03 +00003862 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00003863 if( pOutFlags ){
3864 *pOutFlags = flags;
3865 }
3866
dane946c392009-08-22 11:39:46 +00003867 if( p->pUnused ){
3868 p->pUnused->fd = fd;
3869 p->pUnused->flags = flags;
3870 }
3871
danielk1977b4b47412007-08-17 15:53:36 +00003872 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00003873#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003874 zPath = zName;
3875#else
danielk197717b90b52008-06-06 11:11:25 +00003876 unlink(zName);
chw97185482008-11-17 08:05:31 +00003877#endif
danielk1977b4b47412007-08-17 15:53:36 +00003878 }
drh41022642008-11-21 00:24:42 +00003879#if SQLITE_ENABLE_LOCKING_STYLE
3880 else{
dan08da86a2009-08-21 17:18:03 +00003881 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00003882 }
3883#endif
3884
danielk1977fee2d252007-08-18 10:59:19 +00003885 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00003886 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00003887 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00003888 /* It is safe to close fd at this point, because it is guaranteed not
3889 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00003890 ** it would not be safe to close as this would release any locks held
3891 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00003892 assert( eType!=SQLITE_OPEN_MAIN_DB );
3893 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00003894 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00003895 }
3896 }
danielk1977e339d652008-06-28 11:23:00 +00003897
3898#ifdef FD_CLOEXEC
3899 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3900#endif
3901
drhda0e7682008-07-30 15:27:54 +00003902 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00003903
3904#if SQLITE_PREFER_PROXY_LOCKING
dan15edd582009-08-25 05:57:47 +00003905 if( zPath!=NULL && !noLock && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00003906 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
3907 int useProxy = 0;
3908
dan08da86a2009-08-21 17:18:03 +00003909 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
3910 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00003911 if( envforce!=NULL ){
3912 useProxy = atoi(envforce)>0;
3913 }else{
3914 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00003915 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00003916 /* In theory, the close(fd) call is sub-optimal. If the file opened
3917 ** with fd is a database file, and there are other connections open
3918 ** on that file that are currently holding advisory locks on it,
3919 ** then the call to close() will cancel those locks. In practice,
3920 ** we're assuming that statfs() doesn't fail very often. At least
3921 ** not while other file descriptors opened by the same process on
3922 ** the same file are working. */
3923 p->lastErrno = errno;
3924 if( dirfd>=0 ){
3925 close(dirfd); /* silently leak if fail, in error */
3926 }
aswiftaebf4132008-11-21 00:10:35 +00003927 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00003928 rc = SQLITE_IOERR_ACCESS;
3929 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00003930 }
3931 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
3932 }
3933 if( useProxy ){
3934 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
3935 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00003936 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
aswiftaebf4132008-11-21 00:10:35 +00003937 }
dane946c392009-08-22 11:39:46 +00003938 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00003939 }
3940 }
3941#endif
3942
dane946c392009-08-22 11:39:46 +00003943 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
3944open_finished:
3945 if( rc!=SQLITE_OK ){
3946 sqlite3_free(p->pUnused);
3947 }
3948 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00003949}
3950
dane946c392009-08-22 11:39:46 +00003951
danielk1977b4b47412007-08-17 15:53:36 +00003952/*
danielk1977fee2d252007-08-18 10:59:19 +00003953** Delete the file at zPath. If the dirSync argument is true, fsync()
3954** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00003955*/
drh6b9d6dd2008-12-03 19:34:47 +00003956static int unixDelete(
3957 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
3958 const char *zPath, /* Name of file to be deleted */
3959 int dirSync /* If true, fsync() directory after deleting file */
3960){
danielk1977fee2d252007-08-18 10:59:19 +00003961 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00003962 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003963 SimulateIOError(return SQLITE_IOERR_DELETE);
3964 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00003965#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00003966 if( dirSync ){
3967 int fd;
3968 rc = openDirectory(zPath, &fd);
3969 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00003970#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003971 if( fsync(fd)==-1 )
3972#else
3973 if( fsync(fd) )
3974#endif
3975 {
danielk1977fee2d252007-08-18 10:59:19 +00003976 rc = SQLITE_IOERR_DIR_FSYNC;
3977 }
aswiftaebf4132008-11-21 00:10:35 +00003978 if( close(fd)&&!rc ){
3979 rc = SQLITE_IOERR_DIR_CLOSE;
3980 }
danielk1977fee2d252007-08-18 10:59:19 +00003981 }
3982 }
danielk1977d138dd82008-10-15 16:02:48 +00003983#endif
danielk1977fee2d252007-08-18 10:59:19 +00003984 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00003985}
3986
danielk197790949c22007-08-17 16:50:38 +00003987/*
3988** Test the existance of or access permissions of file zPath. The
3989** test performed depends on the value of flags:
3990**
3991** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
3992** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
3993** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
3994**
3995** Otherwise return 0.
3996*/
danielk1977861f7452008-06-05 11:39:11 +00003997static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00003998 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
3999 const char *zPath, /* Path of the file to examine */
4000 int flags, /* What do we want to learn about the zPath file? */
4001 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004002){
rse25c0d1a2007-09-20 08:38:14 +00004003 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004004 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004005 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004006 switch( flags ){
4007 case SQLITE_ACCESS_EXISTS:
4008 amode = F_OK;
4009 break;
4010 case SQLITE_ACCESS_READWRITE:
4011 amode = W_OK|R_OK;
4012 break;
drh50d3f902007-08-27 21:10:36 +00004013 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004014 amode = R_OK;
4015 break;
4016
4017 default:
4018 assert(!"Invalid flags argument");
4019 }
danielk1977861f7452008-06-05 11:39:11 +00004020 *pResOut = (access(zPath, amode)==0);
4021 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004022}
4023
danielk1977b4b47412007-08-17 15:53:36 +00004024
4025/*
4026** Turn a relative pathname into a full pathname. The relative path
4027** is stored as a nul-terminated string in the buffer pointed to by
4028** zPath.
4029**
4030** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4031** (in this case, MAX_PATHNAME bytes). The full-path is written to
4032** this buffer before returning.
4033*/
danielk1977adfb9b02007-09-17 07:02:56 +00004034static int unixFullPathname(
4035 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4036 const char *zPath, /* Possibly relative input path */
4037 int nOut, /* Size of output buffer in bytes */
4038 char *zOut /* Output buffer */
4039){
danielk1977843e65f2007-09-01 16:16:15 +00004040
4041 /* It's odd to simulate an io-error here, but really this is just
4042 ** using the io-error infrastructure to test that SQLite handles this
4043 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004044 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004045 */
4046 SimulateIOError( return SQLITE_ERROR );
4047
drh153c62c2007-08-24 03:51:33 +00004048 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004049 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004050
drh3c7f2dc2007-12-06 13:26:20 +00004051 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004052 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004053 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004054 }else{
4055 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004056 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00004057 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00004058 }
drhea678832008-12-10 19:26:22 +00004059 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004060 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004061 }
4062 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004063}
4064
drh0ccebe72005-06-07 22:22:50 +00004065
drh761df872006-12-21 01:29:22 +00004066#ifndef SQLITE_OMIT_LOAD_EXTENSION
4067/*
4068** Interfaces for opening a shared library, finding entry points
4069** within the shared library, and closing the shared library.
4070*/
4071#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004072static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4073 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004074 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4075}
danielk197795c8a542007-09-01 06:51:27 +00004076
4077/*
4078** SQLite calls this function immediately after a call to unixDlSym() or
4079** unixDlOpen() fails (returns a null pointer). If a more detailed error
4080** message is available, it is written to zBufOut. If no error message
4081** is available, zBufOut is left unmodified and SQLite uses a default
4082** error message.
4083*/
danielk1977397d65f2008-11-19 11:35:39 +00004084static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004085 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004086 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004087 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004088 zErr = dlerror();
4089 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004090 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004091 }
drh6c7d5c52008-11-21 20:32:33 +00004092 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004093}
drh1875f7a2008-12-08 18:19:17 +00004094static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4095 /*
4096 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4097 ** cast into a pointer to a function. And yet the library dlsym() routine
4098 ** returns a void* which is really a pointer to a function. So how do we
4099 ** use dlsym() with -pedantic-errors?
4100 **
4101 ** Variable x below is defined to be a pointer to a function taking
4102 ** parameters void* and const char* and returning a pointer to a function.
4103 ** We initialize x by assigning it a pointer to the dlsym() function.
4104 ** (That assignment requires a cast.) Then we call the function that
4105 ** x points to.
4106 **
4107 ** This work-around is unlikely to work correctly on any system where
4108 ** you really cannot cast a function pointer into void*. But then, on the
4109 ** other hand, dlsym() will not work on such a system either, so we have
4110 ** not really lost anything.
4111 */
4112 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004113 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004114 x = (void(*(*)(void*,const char*))(void))dlsym;
4115 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004116}
danielk1977397d65f2008-11-19 11:35:39 +00004117static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4118 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004119 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004120}
danielk1977b4b47412007-08-17 15:53:36 +00004121#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4122 #define unixDlOpen 0
4123 #define unixDlError 0
4124 #define unixDlSym 0
4125 #define unixDlClose 0
4126#endif
4127
4128/*
danielk197790949c22007-08-17 16:50:38 +00004129** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004130*/
danielk1977397d65f2008-11-19 11:35:39 +00004131static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4132 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004133 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004134
drhbbd42a62004-05-22 17:41:58 +00004135 /* We have to initialize zBuf to prevent valgrind from reporting
4136 ** errors. The reports issued by valgrind are incorrect - we would
4137 ** prefer that the randomness be increased by making use of the
4138 ** uninitialized space in zBuf - but valgrind errors tend to worry
4139 ** some users. Rather than argue, it seems easier just to initialize
4140 ** the whole array and silence valgrind, even if that means less randomness
4141 ** in the random seed.
4142 **
4143 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004144 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004145 ** tests repeatable.
4146 */
danielk1977b4b47412007-08-17 15:53:36 +00004147 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004148#if !defined(SQLITE_TEST)
4149 {
drh842b8642005-01-21 17:53:17 +00004150 int pid, fd;
4151 fd = open("/dev/urandom", O_RDONLY);
4152 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004153 time_t t;
4154 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004155 memcpy(zBuf, &t, sizeof(t));
4156 pid = getpid();
4157 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004158 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004159 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004160 }else{
drh72cbd072008-10-14 17:58:38 +00004161 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004162 close(fd);
4163 }
drhbbd42a62004-05-22 17:41:58 +00004164 }
4165#endif
drh72cbd072008-10-14 17:58:38 +00004166 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004167}
4168
danielk1977b4b47412007-08-17 15:53:36 +00004169
drhbbd42a62004-05-22 17:41:58 +00004170/*
4171** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004172** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004173** The return value is the number of microseconds of sleep actually
4174** requested from the underlying operating system, a number which
4175** might be greater than or equal to the argument, but not less
4176** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004177*/
danielk1977397d65f2008-11-19 11:35:39 +00004178static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004179#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004180 struct timespec sp;
4181
4182 sp.tv_sec = microseconds / 1000000;
4183 sp.tv_nsec = (microseconds % 1000000) * 1000;
4184 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004185 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004186 return microseconds;
4187#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004188 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004189 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004190 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004191#else
danielk1977b4b47412007-08-17 15:53:36 +00004192 int seconds = (microseconds+999999)/1000000;
4193 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004194 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004195 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004196#endif
drh88f474a2006-01-02 20:00:12 +00004197}
4198
4199/*
drh6b9d6dd2008-12-03 19:34:47 +00004200** The following variable, if set to a non-zero value, is interpreted as
4201** the number of seconds since 1970 and is used to set the result of
4202** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004203*/
4204#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004205int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004206#endif
4207
4208/*
4209** Find the current time (in Universal Coordinated Time). Write the
4210** current time and date as a Julian Day number into *prNow and
4211** return 0. Return 1 if the time and date cannot be found.
4212*/
danielk1977397d65f2008-11-19 11:35:39 +00004213static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh0b3bf922009-06-15 20:45:34 +00004214#if defined(SQLITE_OMIT_FLOATING_POINT)
4215 time_t t;
4216 time(&t);
4217 *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
4218#elif defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00004219 time_t t;
4220 time(&t);
4221 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00004222#elif OS_VXWORKS
4223 struct timespec sNow;
4224 clock_gettime(CLOCK_REALTIME, &sNow);
4225 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00004226#else
4227 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00004228 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00004229 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
4230#endif
danielk1977397d65f2008-11-19 11:35:39 +00004231
drhbbd42a62004-05-22 17:41:58 +00004232#ifdef SQLITE_TEST
4233 if( sqlite3_current_time ){
4234 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4235 }
4236#endif
danielk1977397d65f2008-11-19 11:35:39 +00004237 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004238 return 0;
4239}
danielk1977b4b47412007-08-17 15:53:36 +00004240
drh6b9d6dd2008-12-03 19:34:47 +00004241/*
4242** We added the xGetLastError() method with the intention of providing
4243** better low-level error messages when operating-system problems come up
4244** during SQLite operation. But so far, none of that has been implemented
4245** in the core. So this routine is never called. For now, it is merely
4246** a place-holder.
4247*/
danielk1977397d65f2008-11-19 11:35:39 +00004248static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4249 UNUSED_PARAMETER(NotUsed);
4250 UNUSED_PARAMETER(NotUsed2);
4251 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004252 return 0;
4253}
4254
drh153c62c2007-08-24 03:51:33 +00004255/*
drh734c9862008-11-28 15:37:20 +00004256************************ End of sqlite3_vfs methods ***************************
4257******************************************************************************/
4258
drh715ff302008-12-03 22:32:44 +00004259/******************************************************************************
4260************************** Begin Proxy Locking ********************************
4261**
4262** Proxy locking is a "uber-locking-method" in this sense: It uses the
4263** other locking methods on secondary lock files. Proxy locking is a
4264** meta-layer over top of the primitive locking implemented above. For
4265** this reason, the division that implements of proxy locking is deferred
4266** until late in the file (here) after all of the other I/O methods have
4267** been defined - so that the primitive locking methods are available
4268** as services to help with the implementation of proxy locking.
4269**
4270****
4271**
4272** The default locking schemes in SQLite use byte-range locks on the
4273** database file to coordinate safe, concurrent access by multiple readers
4274** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4275** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4276** as POSIX read & write locks over fixed set of locations (via fsctl),
4277** on AFP and SMB only exclusive byte-range locks are available via fsctl
4278** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4279** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4280** address in the shared range is taken for a SHARED lock, the entire
4281** shared range is taken for an EXCLUSIVE lock):
4282**
4283** PENDING_BYTE 0x40000000
4284** RESERVED_BYTE 0x40000001
4285** SHARED_RANGE 0x40000002 -> 0x40000200
4286**
4287** This works well on the local file system, but shows a nearly 100x
4288** slowdown in read performance on AFP because the AFP client disables
4289** the read cache when byte-range locks are present. Enabling the read
4290** cache exposes a cache coherency problem that is present on all OS X
4291** supported network file systems. NFS and AFP both observe the
4292** close-to-open semantics for ensuring cache coherency
4293** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4294** address the requirements for concurrent database access by multiple
4295** readers and writers
4296** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4297**
4298** To address the performance and cache coherency issues, proxy file locking
4299** changes the way database access is controlled by limiting access to a
4300** single host at a time and moving file locks off of the database file
4301** and onto a proxy file on the local file system.
4302**
4303**
4304** Using proxy locks
4305** -----------------
4306**
4307** C APIs
4308**
4309** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4310** <proxy_path> | ":auto:");
4311** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4312**
4313**
4314** SQL pragmas
4315**
4316** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4317** PRAGMA [database.]lock_proxy_file
4318**
4319** Specifying ":auto:" means that if there is a conch file with a matching
4320** host ID in it, the proxy path in the conch file will be used, otherwise
4321** a proxy path based on the user's temp dir
4322** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4323** actual proxy file name is generated from the name and path of the
4324** database file. For example:
4325**
4326** For database path "/Users/me/foo.db"
4327** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4328**
4329** Once a lock proxy is configured for a database connection, it can not
4330** be removed, however it may be switched to a different proxy path via
4331** the above APIs (assuming the conch file is not being held by another
4332** connection or process).
4333**
4334**
4335** How proxy locking works
4336** -----------------------
4337**
4338** Proxy file locking relies primarily on two new supporting files:
4339**
4340** * conch file to limit access to the database file to a single host
4341** at a time
4342**
4343** * proxy file to act as a proxy for the advisory locks normally
4344** taken on the database
4345**
4346** The conch file - to use a proxy file, sqlite must first "hold the conch"
4347** by taking an sqlite-style shared lock on the conch file, reading the
4348** contents and comparing the host's unique host ID (see below) and lock
4349** proxy path against the values stored in the conch. The conch file is
4350** stored in the same directory as the database file and the file name
4351** is patterned after the database file name as ".<databasename>-conch".
4352** If the conch file does not exist, or it's contents do not match the
4353** host ID and/or proxy path, then the lock is escalated to an exclusive
4354** lock and the conch file contents is updated with the host ID and proxy
4355** path and the lock is downgraded to a shared lock again. If the conch
4356** is held by another process (with a shared lock), the exclusive lock
4357** will fail and SQLITE_BUSY is returned.
4358**
4359** The proxy file - a single-byte file used for all advisory file locks
4360** normally taken on the database file. This allows for safe sharing
4361** of the database file for multiple readers and writers on the same
4362** host (the conch ensures that they all use the same local lock file).
4363**
4364** There is a third file - the host ID file - used as a persistent record
4365** of a unique identifier for the host, a 128-byte unique host id file
4366** in the path defined by the HOSTIDPATH macro (default value is
4367** /Library/Caches/.com.apple.sqliteConchHostId).
4368**
4369** Requesting the lock proxy does not immediately take the conch, it is
4370** only taken when the first request to lock database file is made.
4371** This matches the semantics of the traditional locking behavior, where
4372** opening a connection to a database file does not take a lock on it.
4373** The shared lock and an open file descriptor are maintained until
4374** the connection to the database is closed.
4375**
4376** The proxy file and the lock file are never deleted so they only need
4377** to be created the first time they are used.
4378**
4379** Configuration options
4380** ---------------------
4381**
4382** SQLITE_PREFER_PROXY_LOCKING
4383**
4384** Database files accessed on non-local file systems are
4385** automatically configured for proxy locking, lock files are
4386** named automatically using the same logic as
4387** PRAGMA lock_proxy_file=":auto:"
4388**
4389** SQLITE_PROXY_DEBUG
4390**
4391** Enables the logging of error messages during host id file
4392** retrieval and creation
4393**
4394** HOSTIDPATH
4395**
4396** Overrides the default host ID file path location
4397**
4398** LOCKPROXYDIR
4399**
4400** Overrides the default directory used for lock proxy files that
4401** are named automatically via the ":auto:" setting
4402**
4403** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4404**
4405** Permissions to use when creating a directory for storing the
4406** lock proxy files, only used when LOCKPROXYDIR is not set.
4407**
4408**
4409** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4410** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4411** force proxy locking to be used for every database file opened, and 0
4412** will force automatic proxy locking to be disabled for all database
4413** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4414** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4415*/
4416
4417/*
4418** Proxy locking is only available on MacOSX
4419*/
drhd2cb50b2009-01-09 21:41:17 +00004420#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004421
4422#ifdef SQLITE_TEST
4423/* simulate multiple hosts by creating unique hostid file paths */
4424int sqlite3_hostid_num = 0;
4425#endif
4426
4427/*
4428** The proxyLockingContext has the path and file structures for the remote
4429** and local proxy files in it
4430*/
4431typedef struct proxyLockingContext proxyLockingContext;
4432struct proxyLockingContext {
4433 unixFile *conchFile; /* Open conch file */
4434 char *conchFilePath; /* Name of the conch file */
4435 unixFile *lockProxy; /* Open proxy lock file */
4436 char *lockProxyPath; /* Name of the proxy lock file */
4437 char *dbPath; /* Name of the open file */
4438 int conchHeld; /* True if the conch is currently held */
4439 void *oldLockingContext; /* Original lockingcontext to restore on close */
4440 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4441};
4442
4443/* HOSTIDLEN and CONCHLEN both include space for the string
4444** terminating nul
4445*/
4446#define HOSTIDLEN 128
4447#define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
4448#ifndef HOSTIDPATH
4449# define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
4450#endif
4451
4452/* basically a copy of unixRandomness with different
4453** test behavior built in */
4454static int proxyGenerateHostID(char *pHostID){
4455 int pid, fd, len;
4456 unsigned char *key = (unsigned char *)pHostID;
4457
4458 memset(key, 0, HOSTIDLEN);
4459 len = 0;
4460 fd = open("/dev/urandom", O_RDONLY);
4461 if( fd>=0 ){
4462 len = read(fd, key, HOSTIDLEN);
4463 close(fd); /* silently leak the fd if it fails */
4464 }
4465 if( len < HOSTIDLEN ){
4466 time_t t;
4467 time(&t);
4468 memcpy(key, &t, sizeof(t));
4469 pid = getpid();
4470 memcpy(&key[sizeof(t)], &pid, sizeof(pid));
4471 }
4472
4473#ifdef MAKE_PRETTY_HOSTID
4474 {
4475 int i;
4476 /* filter the bytes into printable ascii characters and NUL terminate */
4477 key[(HOSTIDLEN-1)] = 0x00;
4478 for( i=0; i<(HOSTIDLEN-1); i++ ){
4479 unsigned char pa = key[i]&0x7F;
4480 if( pa<0x20 ){
4481 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
4482 }else if( pa==0x7F ){
4483 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
4484 }
4485 }
4486 }
4487#endif
4488 return SQLITE_OK;
4489}
4490
4491/* writes the host id path to path, path should be an pre-allocated buffer
4492** with enough space for a path
4493*/
4494static void proxyGetHostIDPath(char *path, size_t len){
4495 strlcpy(path, HOSTIDPATH, len);
4496#ifdef SQLITE_TEST
4497 if( sqlite3_hostid_num>0 ){
4498 char suffix[2] = "1";
4499 suffix[0] = suffix[0] + sqlite3_hostid_num;
4500 strlcat(path, suffix, len);
4501 }
4502#endif
4503 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
4504}
4505
4506/* get the host ID from a sqlite hostid file stored in the
4507** user-specific tmp directory, create the ID if it's not there already
4508*/
4509static int proxyGetHostID(char *pHostID, int *pError){
4510 int fd;
4511 char path[MAXPATHLEN];
4512 size_t len;
4513 int rc=SQLITE_OK;
4514
4515 proxyGetHostIDPath(path, MAXPATHLEN);
4516 /* try to create the host ID file, if it already exists read the contents */
4517 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
4518 if( fd<0 ){
4519 int err=errno;
4520
4521 if( err!=EEXIST ){
4522#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4523 fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
4524 path, strerror(err));
4525#endif
4526 return SQLITE_PERM;
4527 }
4528 /* couldn't create the file, read it instead */
4529 fd = open(path, O_RDONLY|O_EXCL);
4530 if( fd<0 ){
4531#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4532 int err = errno;
4533 fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
4534 path, strerror(err));
4535#endif
4536 return SQLITE_PERM;
4537 }
4538 len = pread(fd, pHostID, HOSTIDLEN, 0);
4539 if( len<0 ){
4540 *pError = errno;
4541 rc = SQLITE_IOERR_READ;
4542 }else if( len<HOSTIDLEN ){
4543 *pError = 0;
4544 rc = SQLITE_IOERR_SHORT_READ;
4545 }
4546 close(fd); /* silently leak the fd if it fails */
4547 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
4548 return rc;
4549 }else{
4550 /* we're creating the host ID file (use a random string of bytes) */
4551 proxyGenerateHostID(pHostID);
4552 len = pwrite(fd, pHostID, HOSTIDLEN, 0);
4553 if( len<0 ){
4554 *pError = errno;
4555 rc = SQLITE_IOERR_WRITE;
4556 }else if( len<HOSTIDLEN ){
4557 *pError = 0;
4558 rc = SQLITE_IOERR_WRITE;
4559 }
4560 close(fd); /* silently leak the fd if it fails */
4561 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
4562 return rc;
4563 }
4564}
4565
4566static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4567 int len;
4568 int dbLen;
4569 int i;
4570
4571#ifdef LOCKPROXYDIR
4572 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4573#else
4574# ifdef _CS_DARWIN_USER_TEMP_DIR
4575 {
4576 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
4577 len = strlcat(lPath, "sqliteplocks", maxLen);
4578 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4579 /* if mkdir fails, handle as lock file creation failure */
drh715ff302008-12-03 22:32:44 +00004580# ifdef SQLITE_DEBUG
danielk197750c55a92009-05-08 11:34:37 +00004581 int err = errno;
drh715ff302008-12-03 22:32:44 +00004582 if( err!=EEXIST ){
4583 fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
4584 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
4585 }
4586# endif
4587 }else{
4588 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
4589 }
4590
4591 }
4592# else
4593 len = strlcpy(lPath, "/tmp/", maxLen);
4594# endif
4595#endif
4596
4597 if( lPath[len-1]!='/' ){
4598 len = strlcat(lPath, "/", maxLen);
4599 }
4600
4601 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004602 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004603 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4604 char c = dbPath[i];
4605 lPath[i+len] = (c=='/')?'_':c;
4606 }
4607 lPath[i+len]='\0';
4608 strlcat(lPath, ":auto:", maxLen);
4609 return SQLITE_OK;
4610}
4611
4612/*
4613** Create a new VFS file descriptor (stored in memory obtained from
4614** sqlite3_malloc) and open the file named "path" in the file descriptor.
4615**
4616** The caller is responsible not only for closing the file descriptor
4617** but also for freeing the memory associated with the file descriptor.
4618*/
4619static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
drh715ff302008-12-03 22:32:44 +00004620 unixFile *pNew;
dan15edd582009-08-25 05:57:47 +00004621 int flags = SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
drh715ff302008-12-03 22:32:44 +00004622 int rc = SQLITE_OK;
4623 sqlite3_vfs dummyVfs;
4624
drh715ff302008-12-03 22:32:44 +00004625 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
dan15edd582009-08-25 05:57:47 +00004626 if( !pNew ){
4627 return SQLITE_NOMEM;
drh715ff302008-12-03 22:32:44 +00004628 }
4629 memset(pNew, 0, sizeof(unixFile));
4630
dan15edd582009-08-25 05:57:47 +00004631 /* Call unixOpen() to open the proxy file. The flags passed to unixOpen()
4632 ** suggest that the file being opened is a "main database". This is
4633 ** necessary as other file types do not necessarily support locking. It
4634 ** is better to use unixOpen() instead of opening the file directly with
4635 ** open(), as unixOpen() sets up the various mechanisms required to
4636 ** make sure a call to close() does not cause the system to discard
4637 ** POSIX locks prematurely.
4638 **
4639 ** It is important that the xOpen member of the VFS object passed to
4640 ** unixOpen() is NULL. This tells unixOpen() may try to open a proxy-file
4641 ** for the proxy-file (creating a potential infinite loop).
4642 */
drh1875f7a2008-12-08 18:19:17 +00004643 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan15edd582009-08-25 05:57:47 +00004644 dummyVfs.xOpen = 0;
4645 rc = unixOpen(&dummyVfs, path, (sqlite3_file *)pNew, flags, &flags);
4646 if( rc==SQLITE_OK && (flags&SQLITE_OPEN_READONLY) ){
4647 pNew->pMethod->xClose((sqlite3_file *)pNew);
4648 rc = SQLITE_CANTOPEN;
drh715ff302008-12-03 22:32:44 +00004649 }
dan15edd582009-08-25 05:57:47 +00004650
4651 if( rc!=SQLITE_OK ){
4652 sqlite3_free(pNew);
4653 pNew = 0;
4654 }
4655
4656 *ppFile = pNew;
drh715ff302008-12-03 22:32:44 +00004657 return rc;
4658}
4659
4660/* takes the conch by taking a shared lock and read the contents conch, if
4661** lockPath is non-NULL, the host ID and lock file path must match. A NULL
4662** lockPath means that the lockPath in the conch file will be used if the
4663** host IDs match, or a new lock path will be generated automatically
4664** and written to the conch file.
4665*/
4666static int proxyTakeConch(unixFile *pFile){
4667 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4668
4669 if( pCtx->conchHeld>0 ){
4670 return SQLITE_OK;
4671 }else{
4672 unixFile *conchFile = pCtx->conchFile;
4673 char testValue[CONCHLEN];
4674 char conchValue[CONCHLEN];
4675 char lockPath[MAXPATHLEN];
4676 char *tLockPath = NULL;
4677 int rc = SQLITE_OK;
4678 int readRc = SQLITE_OK;
4679 int syncPerms = 0;
4680
4681 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
4682 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
4683
4684 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
4685 if( rc==SQLITE_OK ){
4686 int pError = 0;
drh1875f7a2008-12-08 18:19:17 +00004687 memset(testValue, 0, CONCHLEN); /* conch is fixed size */
drh715ff302008-12-03 22:32:44 +00004688 rc = proxyGetHostID(testValue, &pError);
4689 if( (rc&0xff)==SQLITE_IOERR ){
4690 pFile->lastErrno = pError;
4691 }
4692 if( pCtx->lockProxyPath ){
4693 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
4694 }
4695 }
4696 if( rc!=SQLITE_OK ){
4697 goto end_takeconch;
4698 }
4699
4700 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
4701 if( readRc!=SQLITE_IOERR_SHORT_READ ){
4702 if( readRc!=SQLITE_OK ){
4703 if( (rc&0xff)==SQLITE_IOERR ){
4704 pFile->lastErrno = conchFile->lastErrno;
4705 }
4706 rc = readRc;
4707 goto end_takeconch;
4708 }
4709 /* if the conch has data compare the contents */
4710 if( !pCtx->lockProxyPath ){
4711 /* for auto-named local lock file, just check the host ID and we'll
4712 ** use the local lock file path that's already in there */
4713 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
4714 tLockPath = (char *)&conchValue[HOSTIDLEN];
4715 goto end_takeconch;
4716 }
4717 }else{
4718 /* we've got the conch if conchValue matches our path and host ID */
4719 if( !memcmp(testValue, conchValue, CONCHLEN) ){
4720 goto end_takeconch;
4721 }
4722 }
4723 }else{
4724 /* a short read means we're "creating" the conch (even though it could
4725 ** have been user-intervention), if we acquire the exclusive lock,
4726 ** we'll try to match the current on-disk permissions of the database
4727 */
4728 syncPerms = 1;
4729 }
4730
4731 /* either conch was emtpy or didn't match */
4732 if( !pCtx->lockProxyPath ){
4733 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
4734 tLockPath = lockPath;
4735 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
4736 }
4737
4738 /* update conch with host and path (this will fail if other process
4739 ** has a shared lock already) */
4740 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
4741 if( rc==SQLITE_OK ){
4742 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
4743 if( rc==SQLITE_OK && syncPerms ){
4744 struct stat buf;
4745 int err = fstat(pFile->h, &buf);
4746 if( err==0 ){
4747 /* try to match the database file permissions, ignore failure */
4748#ifndef SQLITE_PROXY_DEBUG
4749 fchmod(conchFile->h, buf.st_mode);
4750#else
4751 if( fchmod(conchFile->h, buf.st_mode)!=0 ){
4752 int code = errno;
4753 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
4754 buf.st_mode, code, strerror(code));
4755 } else {
4756 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
4757 }
4758 }else{
4759 int code = errno;
4760 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
4761 err, code, strerror(code));
4762#endif
4763 }
4764 }
4765 }
4766 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
4767
4768end_takeconch:
4769 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
4770 if( rc==SQLITE_OK && pFile->openFlags ){
4771 if( pFile->h>=0 ){
4772#ifdef STRICT_CLOSE_ERROR
4773 if( close(pFile->h) ){
4774 pFile->lastErrno = errno;
4775 return SQLITE_IOERR_CLOSE;
4776 }
4777#else
4778 close(pFile->h); /* silently leak fd if fail */
4779#endif
4780 }
4781 pFile->h = -1;
4782 int fd = open(pCtx->dbPath, pFile->openFlags,
4783 SQLITE_DEFAULT_FILE_PERMISSIONS);
4784 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
4785 if( fd>=0 ){
4786 pFile->h = fd;
4787 }else{
drh1875f7a2008-12-08 18:19:17 +00004788 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
4789 during locking */
drh715ff302008-12-03 22:32:44 +00004790 }
4791 }
4792 if( rc==SQLITE_OK && !pCtx->lockProxy ){
4793 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
drh1875f7a2008-12-08 18:19:17 +00004794 /* ACS: Need to make a copy of path sometimes */
drh715ff302008-12-03 22:32:44 +00004795 rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
4796 }
4797 if( rc==SQLITE_OK ){
4798 pCtx->conchHeld = 1;
4799
4800 if( tLockPath ){
4801 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
4802 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
4803 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
4804 pCtx->lockProxyPath;
4805 }
4806 }
4807 } else {
4808 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4809 }
4810 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
4811 return rc;
4812 }
4813}
4814
4815/*
4816** If pFile holds a lock on a conch file, then release that lock.
4817*/
4818static int proxyReleaseConch(unixFile *pFile){
4819 int rc; /* Subroutine return code */
4820 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
4821 unixFile *conchFile; /* Name of the conch file */
4822
4823 pCtx = (proxyLockingContext *)pFile->lockingContext;
4824 conchFile = pCtx->conchFile;
4825 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
4826 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
4827 getpid());
4828 pCtx->conchHeld = 0;
4829 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4830 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
4831 (rc==SQLITE_OK ? "ok" : "failed"));
4832 return rc;
4833}
4834
4835/*
4836** Given the name of a database file, compute the name of its conch file.
4837** Store the conch filename in memory obtained from sqlite3_malloc().
4838** Make *pConchPath point to the new name. Return SQLITE_OK on success
4839** or SQLITE_NOMEM if unable to obtain memory.
4840**
4841** The caller is responsible for ensuring that the allocated memory
4842** space is eventually freed.
4843**
4844** *pConchPath is set to NULL if a memory allocation error occurs.
4845*/
4846static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
4847 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00004848 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00004849 char *conchPath; /* buffer in which to construct conch name */
4850
4851 /* Allocate space for the conch filename and initialize the name to
4852 ** the name of the original database file. */
4853 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
4854 if( conchPath==0 ){
4855 return SQLITE_NOMEM;
4856 }
4857 memcpy(conchPath, dbPath, len+1);
4858
4859 /* now insert a "." before the last / character */
4860 for( i=(len-1); i>=0; i-- ){
4861 if( conchPath[i]=='/' ){
4862 i++;
4863 break;
4864 }
4865 }
4866 conchPath[i]='.';
4867 while ( i<len ){
4868 conchPath[i+1]=dbPath[i];
4869 i++;
4870 }
4871
4872 /* append the "-conch" suffix to the file */
4873 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00004874 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00004875
4876 return SQLITE_OK;
4877}
4878
4879
4880/* Takes a fully configured proxy locking-style unix file and switches
4881** the local lock file path
4882*/
4883static int switchLockProxyPath(unixFile *pFile, const char *path) {
4884 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4885 char *oldPath = pCtx->lockProxyPath;
4886 int rc = SQLITE_OK;
4887
4888 if( pFile->locktype!=NO_LOCK ){
4889 return SQLITE_BUSY;
4890 }
4891
4892 /* nothing to do if the path is NULL, :auto: or matches the existing path */
4893 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
4894 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
4895 return SQLITE_OK;
4896 }else{
4897 unixFile *lockProxy = pCtx->lockProxy;
4898 pCtx->lockProxy=NULL;
4899 pCtx->conchHeld = 0;
4900 if( lockProxy!=NULL ){
4901 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
4902 if( rc ) return rc;
4903 sqlite3_free(lockProxy);
4904 }
4905 sqlite3_free(oldPath);
4906 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
4907 }
4908
4909 return rc;
4910}
4911
4912/*
4913** pFile is a file that has been opened by a prior xOpen call. dbPath
4914** is a string buffer at least MAXPATHLEN+1 characters in size.
4915**
4916** This routine find the filename associated with pFile and writes it
4917** int dbPath.
4918*/
4919static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00004920#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00004921 if( pFile->pMethod == &afpIoMethods ){
4922 /* afp style keeps a reference to the db path in the filePath field
4923 ** of the struct */
drhea678832008-12-10 19:26:22 +00004924 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh715ff302008-12-03 22:32:44 +00004925 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
4926 }else
4927#endif
4928 if( pFile->pMethod == &dotlockIoMethods ){
4929 /* dot lock style uses the locking context to store the dot lock
4930 ** file path */
4931 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
4932 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
4933 }else{
4934 /* all other styles use the locking context to store the db file path */
4935 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
4936 strcpy(dbPath, (char *)pFile->lockingContext);
4937 }
4938 return SQLITE_OK;
4939}
4940
4941/*
4942** Takes an already filled in unix file and alters it so all file locking
4943** will be performed on the local proxy lock file. The following fields
4944** are preserved in the locking context so that they can be restored and
4945** the unix structure properly cleaned up at close time:
4946** ->lockingContext
4947** ->pMethod
4948*/
4949static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
4950 proxyLockingContext *pCtx;
4951 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
4952 char *lockPath=NULL;
4953 int rc = SQLITE_OK;
4954
4955 if( pFile->locktype!=NO_LOCK ){
4956 return SQLITE_BUSY;
4957 }
4958 proxyGetDbPathForUnixFile(pFile, dbPath);
4959 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
4960 lockPath=NULL;
4961 }else{
4962 lockPath=(char *)path;
4963 }
4964
4965 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
4966 (lockPath ? lockPath : ":auto:"), getpid());
4967
4968 pCtx = sqlite3_malloc( sizeof(*pCtx) );
4969 if( pCtx==0 ){
4970 return SQLITE_NOMEM;
4971 }
4972 memset(pCtx, 0, sizeof(*pCtx));
4973
4974 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
4975 if( rc==SQLITE_OK ){
4976 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
4977 }
4978 if( rc==SQLITE_OK && lockPath ){
4979 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
4980 }
4981
4982 if( rc==SQLITE_OK ){
4983 /* all memory is allocated, proxys are created and assigned,
4984 ** switch the locking context and pMethod then return.
4985 */
4986 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
4987 pCtx->oldLockingContext = pFile->lockingContext;
4988 pFile->lockingContext = pCtx;
4989 pCtx->pOldMethod = pFile->pMethod;
4990 pFile->pMethod = &proxyIoMethods;
4991 }else{
4992 if( pCtx->conchFile ){
4993 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
4994 if( rc ) return rc;
4995 sqlite3_free(pCtx->conchFile);
4996 }
4997 sqlite3_free(pCtx->conchFilePath);
4998 sqlite3_free(pCtx);
4999 }
5000 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
5001 (rc==SQLITE_OK ? "ok" : "failed"));
5002 return rc;
5003}
5004
5005
5006/*
5007** This routine handles sqlite3_file_control() calls that are specific
5008** to proxy locking.
5009*/
5010static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
5011 switch( op ){
5012 case SQLITE_GET_LOCKPROXYFILE: {
5013 unixFile *pFile = (unixFile*)id;
5014 if( pFile->pMethod == &proxyIoMethods ){
5015 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5016 proxyTakeConch(pFile);
5017 if( pCtx->lockProxyPath ){
5018 *(const char **)pArg = pCtx->lockProxyPath;
5019 }else{
5020 *(const char **)pArg = ":auto: (not held)";
5021 }
5022 } else {
5023 *(const char **)pArg = NULL;
5024 }
5025 return SQLITE_OK;
5026 }
5027 case SQLITE_SET_LOCKPROXYFILE: {
5028 unixFile *pFile = (unixFile*)id;
5029 int rc = SQLITE_OK;
5030 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
5031 if( pArg==NULL || (const char *)pArg==0 ){
5032 if( isProxyStyle ){
5033 /* turn off proxy locking - not supported */
5034 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
5035 }else{
5036 /* turn off proxy locking - already off - NOOP */
5037 rc = SQLITE_OK;
5038 }
5039 }else{
5040 const char *proxyPath = (const char *)pArg;
5041 if( isProxyStyle ){
5042 proxyLockingContext *pCtx =
5043 (proxyLockingContext*)pFile->lockingContext;
5044 if( !strcmp(pArg, ":auto:")
5045 || (pCtx->lockProxyPath &&
5046 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
5047 ){
5048 rc = SQLITE_OK;
5049 }else{
5050 rc = switchLockProxyPath(pFile, proxyPath);
5051 }
5052 }else{
5053 /* turn on proxy file locking */
5054 rc = proxyTransformUnixFile(pFile, proxyPath);
5055 }
5056 }
5057 return rc;
5058 }
5059 default: {
5060 assert( 0 ); /* The call assures that only valid opcodes are sent */
5061 }
5062 }
5063 /*NOTREACHED*/
5064 return SQLITE_ERROR;
5065}
5066
5067/*
5068** Within this division (the proxying locking implementation) the procedures
5069** above this point are all utilities. The lock-related methods of the
5070** proxy-locking sqlite3_io_method object follow.
5071*/
5072
5073
5074/*
5075** This routine checks if there is a RESERVED lock held on the specified
5076** file by this or any other process. If such a lock is held, set *pResOut
5077** to a non-zero value otherwise *pResOut is set to zero. The return value
5078** is set to SQLITE_OK unless an I/O error occurs during lock checking.
5079*/
5080static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
5081 unixFile *pFile = (unixFile*)id;
5082 int rc = proxyTakeConch(pFile);
5083 if( rc==SQLITE_OK ){
5084 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5085 unixFile *proxy = pCtx->lockProxy;
5086 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
5087 }
5088 return rc;
5089}
5090
5091/*
5092** Lock the file with the lock specified by parameter locktype - one
5093** of the following:
5094**
5095** (1) SHARED_LOCK
5096** (2) RESERVED_LOCK
5097** (3) PENDING_LOCK
5098** (4) EXCLUSIVE_LOCK
5099**
5100** Sometimes when requesting one lock state, additional lock states
5101** are inserted in between. The locking might fail on one of the later
5102** transitions leaving the lock state different from what it started but
5103** still short of its goal. The following chart shows the allowed
5104** transitions and the inserted intermediate states:
5105**
5106** UNLOCKED -> SHARED
5107** SHARED -> RESERVED
5108** SHARED -> (PENDING) -> EXCLUSIVE
5109** RESERVED -> (PENDING) -> EXCLUSIVE
5110** PENDING -> EXCLUSIVE
5111**
5112** This routine will only increase a lock. Use the sqlite3OsUnlock()
5113** routine to lower a locking level.
5114*/
5115static int proxyLock(sqlite3_file *id, int locktype) {
5116 unixFile *pFile = (unixFile*)id;
5117 int rc = proxyTakeConch(pFile);
5118 if( rc==SQLITE_OK ){
5119 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5120 unixFile *proxy = pCtx->lockProxy;
5121 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
5122 pFile->locktype = proxy->locktype;
5123 }
5124 return rc;
5125}
5126
5127
5128/*
5129** Lower the locking level on file descriptor pFile to locktype. locktype
5130** must be either NO_LOCK or SHARED_LOCK.
5131**
5132** If the locking level of the file descriptor is already at or below
5133** the requested locking level, this routine is a no-op.
5134*/
5135static int proxyUnlock(sqlite3_file *id, int locktype) {
5136 unixFile *pFile = (unixFile*)id;
5137 int rc = proxyTakeConch(pFile);
5138 if( rc==SQLITE_OK ){
5139 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5140 unixFile *proxy = pCtx->lockProxy;
5141 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
5142 pFile->locktype = proxy->locktype;
5143 }
5144 return rc;
5145}
5146
5147/*
5148** Close a file that uses proxy locks.
5149*/
5150static int proxyClose(sqlite3_file *id) {
5151 if( id ){
5152 unixFile *pFile = (unixFile*)id;
5153 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5154 unixFile *lockProxy = pCtx->lockProxy;
5155 unixFile *conchFile = pCtx->conchFile;
5156 int rc = SQLITE_OK;
5157
5158 if( lockProxy ){
5159 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
5160 if( rc ) return rc;
5161 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
5162 if( rc ) return rc;
5163 sqlite3_free(lockProxy);
5164 pCtx->lockProxy = 0;
5165 }
5166 if( conchFile ){
5167 if( pCtx->conchHeld ){
5168 rc = proxyReleaseConch(pFile);
5169 if( rc ) return rc;
5170 }
5171 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
5172 if( rc ) return rc;
5173 sqlite3_free(conchFile);
5174 }
5175 sqlite3_free(pCtx->lockProxyPath);
5176 sqlite3_free(pCtx->conchFilePath);
5177 sqlite3_free(pCtx->dbPath);
5178 /* restore the original locking context and pMethod then close it */
5179 pFile->lockingContext = pCtx->oldLockingContext;
5180 pFile->pMethod = pCtx->pOldMethod;
5181 sqlite3_free(pCtx);
5182 return pFile->pMethod->xClose(id);
5183 }
5184 return SQLITE_OK;
5185}
5186
5187
5188
drhd2cb50b2009-01-09 21:41:17 +00005189#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00005190/*
5191** The proxy locking style is intended for use with AFP filesystems.
5192** And since AFP is only supported on MacOSX, the proxy locking is also
5193** restricted to MacOSX.
5194**
5195**
5196******************* End of the proxy lock implementation **********************
5197******************************************************************************/
5198
drh734c9862008-11-28 15:37:20 +00005199/*
danielk1977e339d652008-06-28 11:23:00 +00005200** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00005201**
5202** This routine registers all VFS implementations for unix-like operating
5203** systems. This routine, and the sqlite3_os_end() routine that follows,
5204** should be the only routines in this file that are visible from other
5205** files.
drh6b9d6dd2008-12-03 19:34:47 +00005206**
5207** This routine is called once during SQLite initialization and by a
5208** single thread. The memory allocation and mutex subsystems have not
5209** necessarily been initialized when this routine is called, and so they
5210** should not be used.
drh153c62c2007-08-24 03:51:33 +00005211*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005212int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00005213 /*
5214 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00005215 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
5216 ** to the "finder" function. (pAppData is a pointer to a pointer because
5217 ** silly C90 rules prohibit a void* from being cast to a function pointer
5218 ** and so we have to go through the intermediate pointer to avoid problems
5219 ** when compiling with -pedantic-errors on GCC.)
5220 **
5221 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00005222 ** finder-function. The finder-function returns a pointer to the
5223 ** sqlite_io_methods object that implements the desired locking
5224 ** behaviors. See the division above that contains the IOMETHODS
5225 ** macro for addition information on finder-functions.
5226 **
5227 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
5228 ** object. But the "autolockIoFinder" available on MacOSX does a little
5229 ** more than that; it looks at the filesystem type that hosts the
5230 ** database file and tries to choose an locking method appropriate for
5231 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00005232 */
drh7708e972008-11-29 00:56:52 +00005233 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00005234 1, /* iVersion */ \
5235 sizeof(unixFile), /* szOsFile */ \
5236 MAX_PATHNAME, /* mxPathname */ \
5237 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00005238 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00005239 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00005240 unixOpen, /* xOpen */ \
5241 unixDelete, /* xDelete */ \
5242 unixAccess, /* xAccess */ \
5243 unixFullPathname, /* xFullPathname */ \
5244 unixDlOpen, /* xDlOpen */ \
5245 unixDlError, /* xDlError */ \
5246 unixDlSym, /* xDlSym */ \
5247 unixDlClose, /* xDlClose */ \
5248 unixRandomness, /* xRandomness */ \
5249 unixSleep, /* xSleep */ \
5250 unixCurrentTime, /* xCurrentTime */ \
5251 unixGetLastError /* xGetLastError */ \
5252 }
5253
drh6b9d6dd2008-12-03 19:34:47 +00005254 /*
5255 ** All default VFSes for unix are contained in the following array.
5256 **
5257 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5258 ** by the SQLite core when the VFS is registered. So the following
5259 ** array cannot be const.
5260 */
danielk1977e339d652008-06-28 11:23:00 +00005261 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00005262#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00005263 UNIXVFS("unix", autolockIoFinder ),
5264#else
5265 UNIXVFS("unix", posixIoFinder ),
5266#endif
5267 UNIXVFS("unix-none", nolockIoFinder ),
5268 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005269#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005270 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005271#endif
5272#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005273 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00005274#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005275 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005276#endif
chw78a13182009-04-07 05:35:03 +00005277#endif
drhd2cb50b2009-01-09 21:41:17 +00005278#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005279 UNIXVFS("unix-afp", afpIoFinder ),
5280 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005281#endif
drh153c62c2007-08-24 03:51:33 +00005282 };
drh6b9d6dd2008-12-03 19:34:47 +00005283 unsigned int i; /* Loop counter */
5284
5285 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005286 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005287 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005288 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005289 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005290}
danielk1977e339d652008-06-28 11:23:00 +00005291
5292/*
drh6b9d6dd2008-12-03 19:34:47 +00005293** Shutdown the operating system interface.
5294**
5295** Some operating systems might need to do some cleanup in this routine,
5296** to release dynamically allocated objects. But not on unix.
5297** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005298*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005299int sqlite3_os_end(void){
5300 return SQLITE_OK;
5301}
drhdce8bdb2007-08-16 13:01:44 +00005302
danielk197729bafea2008-06-26 10:41:19 +00005303#endif /* SQLITE_OS_UNIX */