blob: 177b7994dcd8e2a09220c424de729b3f3426a193 [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().
drh734c9862008-11-28 15:37:20 +000045**
drh8f941bc2009-01-14 23:03:40 +000046** $Id: os_unix.c,v 1.236 2009/01/14 23:03:41 drh Exp $
drhbbd42a62004-05-22 17:41:58 +000047*/
drhbbd42a62004-05-22 17:41:58 +000048#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000049#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000050
danielk1977e339d652008-06-28 11:23:00 +000051/*
drh6b9d6dd2008-12-03 19:34:47 +000052** There are various methods for file locking used for concurrency
53** control:
danielk1977e339d652008-06-28 11:23:00 +000054**
drh734c9862008-11-28 15:37:20 +000055** 1. POSIX locking (the default),
56** 2. No locking,
57** 3. Dot-file locking,
58** 4. flock() locking,
59** 5. AFP locking (OSX only),
60** 6. Named POSIX semaphores (VXWorks only),
61** 7. proxy locking. (OSX only)
62**
63** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
64** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
65** selection of the appropriate locking style based on the filesystem
66** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000067*/
drh40bbb0a2008-09-23 10:23:26 +000068#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000069# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000070# define SQLITE_ENABLE_LOCKING_STYLE 1
71# else
72# define SQLITE_ENABLE_LOCKING_STYLE 0
73# endif
74#endif
drhbfe66312006-10-03 17:40:40 +000075
drh9cbe6352005-11-29 03:13:21 +000076/*
drh6c7d5c52008-11-21 20:32:33 +000077** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000078** vxworks, or 0 otherwise.
79*/
drh6c7d5c52008-11-21 20:32:33 +000080#ifndef OS_VXWORKS
81# if defined(__RTP__) || defined(_WRS_KERNEL)
82# define OS_VXWORKS 1
83# else
84# define OS_VXWORKS 0
85# endif
danielk1977397d65f2008-11-19 11:35:39 +000086#endif
87
88/*
drh9cbe6352005-11-29 03:13:21 +000089** These #defines should enable >2GB file support on Posix if the
90** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000091** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000092**
93** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
94** on the compiler command line. This is necessary if you are compiling
95** on a recent machine (ex: RedHat 7.2) but you want your code to work
96** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
97** without this option, LFS is enable. But LFS does not exist in the kernel
98** in RedHat 6.0, so the code won't work. Hence, for maximum binary
99** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +0000100**
101** The previous paragraph was written in 2005. (This paragraph is written
102** on 2008-11-28.) These days, all Linux kernels support large files, so
103** you should probably leave LFS enabled. But some embedded platforms might
104** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000105*/
106#ifndef SQLITE_DISABLE_LFS
107# define _LARGE_FILE 1
108# ifndef _FILE_OFFSET_BITS
109# define _FILE_OFFSET_BITS 64
110# endif
111# define _LARGEFILE_SOURCE 1
112#endif
drhbbd42a62004-05-22 17:41:58 +0000113
drh9cbe6352005-11-29 03:13:21 +0000114/*
115** standard include files.
116*/
117#include <sys/types.h>
118#include <sys/stat.h>
119#include <fcntl.h>
120#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000122#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000123#include <errno.h>
danielk1977e339d652008-06-28 11:23:00 +0000124
drh40bbb0a2008-09-23 10:23:26 +0000125#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000126# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000127# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000128# include <semaphore.h>
129# include <limits.h>
130# else
drh9b35ea62008-11-29 02:20:26 +0000131# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000132# include <sys/param.h>
133# include <sys/mount.h>
134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
137/*
drhf1a221e2006-01-15 17:27:17 +0000138** If we are to be thread-safe, include the pthreads header and define
139** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000140*/
drhd677b3d2007-08-20 22:48:41 +0000141#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000142# include <pthread.h>
143# define SQLITE_UNIX_THREADS 1
144#endif
145
146/*
147** Default permissions when creating a new file
148*/
149#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
150# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
151#endif
152
danielk1977b4b47412007-08-17 15:53:36 +0000153/*
aswiftaebf4132008-11-21 00:10:35 +0000154 ** Default permissions when creating auto proxy dir
155 */
156#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
157# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
158#endif
159
160/*
danielk1977b4b47412007-08-17 15:53:36 +0000161** Maximum supported path-length.
162*/
163#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000164
drh734c9862008-11-28 15:37:20 +0000165/*
drh734c9862008-11-28 15:37:20 +0000166** Only set the lastErrno if the error code is a real error and not
167** a normal expected return code of SQLITE_BUSY or SQLITE_OK
168*/
169#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
170
drh9cbe6352005-11-29 03:13:21 +0000171
172/*
drh9b35ea62008-11-29 02:20:26 +0000173** The unixFile structure is subclass of sqlite3_file specific to the unix
174** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000175*/
drh054889e2005-11-30 03:20:31 +0000176typedef struct unixFile unixFile;
177struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000178 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh6c7d5c52008-11-21 20:32:33 +0000179 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
180 struct unixLockInfo *pLock; /* Info about locks on this inode */
181 int h; /* The file descriptor */
182 int dirfd; /* File descriptor for the directory */
183 unsigned char locktype; /* The type of lock held on this fd */
184 int lastErrno; /* The unix errno from the last I/O error */
drh6c7d5c52008-11-21 20:32:33 +0000185 void *lockingContext; /* Locking style specific state */
drh734c9862008-11-28 15:37:20 +0000186 int openFlags; /* The flags specified at open */
187#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000188 pthread_t tid; /* The thread that "owns" this unixFile */
189#endif
190#if OS_VXWORKS
191 int isDelete; /* Delete on close if true */
drh107886a2008-11-21 22:21:50 +0000192 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000193#endif
drh8f941bc2009-01-14 23:03:40 +0000194#ifndef NDEBUG
195 /* The next group of variables are used to track whether or not the
196 ** transaction counter in bytes 24-27 of database files are updated
197 ** whenever any part of the database changes. An assertion fault will
198 ** occur if a file is updated without also updating the transaction
199 ** counter. This test is made to avoid new problems similar to the
200 ** one described by ticket #3584.
201 */
202 unsigned char transCntrChng; /* True if the transaction counter changed */
203 unsigned char dbUpdate; /* True if any part of database file changed */
204 unsigned char inNormalWrite; /* True if in a normal write operation */
205#endif
danielk1977967a4a12007-08-20 14:23:44 +0000206#ifdef SQLITE_TEST
207 /* In test mode, increase the size of this structure a bit so that
208 ** it is larger than the struct CrashFile defined in test6.c.
209 */
210 char aPadding[32];
211#endif
drh9cbe6352005-11-29 03:13:21 +0000212};
213
drh0ccebe72005-06-07 22:22:50 +0000214/*
drh198bf392006-01-06 21:52:49 +0000215** Include code that is common to all os_*.c files
216*/
217#include "os_common.h"
218
219/*
drh0ccebe72005-06-07 22:22:50 +0000220** Define various macros that are missing from some systems.
221*/
drhbbd42a62004-05-22 17:41:58 +0000222#ifndef O_LARGEFILE
223# define O_LARGEFILE 0
224#endif
225#ifdef SQLITE_DISABLE_LFS
226# undef O_LARGEFILE
227# define O_LARGEFILE 0
228#endif
229#ifndef O_NOFOLLOW
230# define O_NOFOLLOW 0
231#endif
232#ifndef O_BINARY
233# define O_BINARY 0
234#endif
235
236/*
237** The DJGPP compiler environment looks mostly like Unix, but it
238** lacks the fcntl() system call. So redefine fcntl() to be something
239** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000240** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000241*/
242#ifdef __DJGPP__
243# define fcntl(A,B,C) 0
244#endif
245
246/*
drh2b4b5962005-06-15 17:47:55 +0000247** The threadid macro resolves to the thread-id or to 0. Used for
248** testing and debugging only.
249*/
drhd677b3d2007-08-20 22:48:41 +0000250#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000251#define threadid pthread_self()
252#else
253#define threadid 0
254#endif
255
danielk197713adf8a2004-06-03 16:08:41 +0000256
drh107886a2008-11-21 22:21:50 +0000257/*
258** Helper functions to obtain and relinquish the global mutex.
259*/
260static void unixEnterMutex(void){
261 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
262}
263static void unixLeaveMutex(void){
264 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
265}
266
drh734c9862008-11-28 15:37:20 +0000267
268#ifdef SQLITE_DEBUG
269/*
270** Helper function for printing out trace information from debugging
271** binaries. This returns the string represetation of the supplied
272** integer lock-type.
273*/
274static const char *locktypeName(int locktype){
275 switch( locktype ){
276 case NO_LOCK: return "NONE";
277 case SHARED_LOCK: return "SHARED";
278 case RESERVED_LOCK: return "RESERVED";
279 case PENDING_LOCK: return "PENDING";
280 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
281 }
282 return "ERROR";
283}
284#endif
285
286#ifdef SQLITE_LOCK_TRACE
287/*
288** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000289**
drh734c9862008-11-28 15:37:20 +0000290** This routine is used for troubleshooting locks on multithreaded
291** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
292** command-line option on the compiler. This code is normally
293** turned off.
294*/
295static int lockTrace(int fd, int op, struct flock *p){
296 char *zOpName, *zType;
297 int s;
298 int savedErrno;
299 if( op==F_GETLK ){
300 zOpName = "GETLK";
301 }else if( op==F_SETLK ){
302 zOpName = "SETLK";
303 }else{
304 s = fcntl(fd, op, p);
305 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
306 return s;
307 }
308 if( p->l_type==F_RDLCK ){
309 zType = "RDLCK";
310 }else if( p->l_type==F_WRLCK ){
311 zType = "WRLCK";
312 }else if( p->l_type==F_UNLCK ){
313 zType = "UNLCK";
314 }else{
315 assert( 0 );
316 }
317 assert( p->l_whence==SEEK_SET );
318 s = fcntl(fd, op, p);
319 savedErrno = errno;
320 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
321 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
322 (int)p->l_pid, s);
323 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
324 struct flock l2;
325 l2 = *p;
326 fcntl(fd, F_GETLK, &l2);
327 if( l2.l_type==F_RDLCK ){
328 zType = "RDLCK";
329 }else if( l2.l_type==F_WRLCK ){
330 zType = "WRLCK";
331 }else if( l2.l_type==F_UNLCK ){
332 zType = "UNLCK";
333 }else{
334 assert( 0 );
335 }
336 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
337 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
338 }
339 errno = savedErrno;
340 return s;
341}
342#define fcntl lockTrace
343#endif /* SQLITE_LOCK_TRACE */
344
345
346
347/*
348** This routine translates a standard POSIX errno code into something
349** useful to the clients of the sqlite3 functions. Specifically, it is
350** intended to translate a variety of "try again" errors into SQLITE_BUSY
351** and a variety of "please close the file descriptor NOW" errors into
352** SQLITE_IOERR
353**
354** Errors during initialization of locks, or file system support for locks,
355** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
356*/
357static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
358 switch (posixError) {
359 case 0:
360 return SQLITE_OK;
361
362 case EAGAIN:
363 case ETIMEDOUT:
364 case EBUSY:
365 case EINTR:
366 case ENOLCK:
367 /* random NFS retry error, unless during file system support
368 * introspection, in which it actually means what it says */
369 return SQLITE_BUSY;
370
371 case EACCES:
372 /* EACCES is like EAGAIN during locking operations, but not any other time*/
373 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
374 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
375 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
376 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
377 return SQLITE_BUSY;
378 }
379 /* else fall through */
380 case EPERM:
381 return SQLITE_PERM;
382
383 case EDEADLK:
384 return SQLITE_IOERR_BLOCKED;
385
386#if EOPNOTSUPP!=ENOTSUP
387 case EOPNOTSUPP:
388 /* something went terribly awry, unless during file system support
389 * introspection, in which it actually means what it says */
390#endif
391#ifdef ENOTSUP
392 case ENOTSUP:
393 /* invalid fd, unless during file system support introspection, in which
394 * it actually means what it says */
395#endif
396 case EIO:
397 case EBADF:
398 case EINVAL:
399 case ENOTCONN:
400 case ENODEV:
401 case ENXIO:
402 case ENOENT:
403 case ESTALE:
404 case ENOSYS:
405 /* these should force the client to close the file and reconnect */
406
407 default:
408 return sqliteIOErr;
409 }
410}
411
412
413
414/******************************************************************************
415****************** Begin Unique File ID Utility Used By VxWorks ***************
416**
417** On most versions of unix, we can get a unique ID for a file by concatenating
418** the device number and the inode number. But this does not work on VxWorks.
419** On VxWorks, a unique file id must be based on the canonical filename.
420**
421** A pointer to an instance of the following structure can be used as a
422** unique file ID in VxWorks. Each instance of this structure contains
423** a copy of the canonical filename. There is also a reference count.
424** The structure is reclaimed when the number of pointers to it drops to
425** zero.
426**
427** There are never very many files open at one time and lookups are not
428** a performance-critical path, so it is sufficient to put these
429** structures on a linked list.
430*/
431struct vxworksFileId {
432 struct vxworksFileId *pNext; /* Next in a list of them all */
433 int nRef; /* Number of references to this one */
434 int nName; /* Length of the zCanonicalName[] string */
435 char *zCanonicalName; /* Canonical filename */
436};
437
438#if OS_VXWORKS
439/*
drh9b35ea62008-11-29 02:20:26 +0000440** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000441** variable:
442*/
443static struct vxworksFileId *vxworksFileList = 0;
444
445/*
446** Simplify a filename into its canonical form
447** by making the following changes:
448**
449** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000450** * convert /./ into just /
451** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000452**
453** Changes are made in-place. Return the new name length.
454**
455** The original filename is in z[0..n-1]. Return the number of
456** characters in the simplified name.
457*/
458static int vxworksSimplifyName(char *z, int n){
459 int i, j;
460 while( n>1 && z[n-1]=='/' ){ n--; }
461 for(i=j=0; i<n; i++){
462 if( z[i]=='/' ){
463 if( z[i+1]=='/' ) continue;
464 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
465 i += 1;
466 continue;
467 }
468 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
469 while( j>0 && z[j-1]!='/' ){ j--; }
470 if( j>0 ){ j--; }
471 i += 2;
472 continue;
473 }
474 }
475 z[j++] = z[i];
476 }
477 z[j] = 0;
478 return j;
479}
480
481/*
482** Find a unique file ID for the given absolute pathname. Return
483** a pointer to the vxworksFileId object. This pointer is the unique
484** file ID.
485**
486** The nRef field of the vxworksFileId object is incremented before
487** the object is returned. A new vxworksFileId object is created
488** and added to the global list if necessary.
489**
490** If a memory allocation error occurs, return NULL.
491*/
492static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
493 struct vxworksFileId *pNew; /* search key and new file ID */
494 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
495 int n; /* Length of zAbsoluteName string */
496
497 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000498 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000499 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
500 if( pNew==0 ) return 0;
501 pNew->zCanonicalName = (char*)&pNew[1];
502 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
503 n = vxworksSimplifyName(pNew->zCanonicalName, n);
504
505 /* Search for an existing entry that matching the canonical name.
506 ** If found, increment the reference count and return a pointer to
507 ** the existing file ID.
508 */
509 unixEnterMutex();
510 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
511 if( pCandidate->nName==n
512 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
513 ){
514 sqlite3_free(pNew);
515 pCandidate->nRef++;
516 unixLeaveMutex();
517 return pCandidate;
518 }
519 }
520
521 /* No match was found. We will make a new file ID */
522 pNew->nRef = 1;
523 pNew->nName = n;
524 pNew->pNext = vxworksFileList;
525 vxworksFileList = pNew;
526 unixLeaveMutex();
527 return pNew;
528}
529
530/*
531** Decrement the reference count on a vxworksFileId object. Free
532** the object when the reference count reaches zero.
533*/
534static void vxworksReleaseFileId(struct vxworksFileId *pId){
535 unixEnterMutex();
536 assert( pId->nRef>0 );
537 pId->nRef--;
538 if( pId->nRef==0 ){
539 struct vxworksFileId **pp;
540 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
541 assert( *pp==pId );
542 *pp = pId->pNext;
543 sqlite3_free(pId);
544 }
545 unixLeaveMutex();
546}
547#endif /* OS_VXWORKS */
548/*************** End of Unique File ID Utility Used By VxWorks ****************
549******************************************************************************/
550
551
552/******************************************************************************
553*************************** Posix Advisory Locking ****************************
554**
drh9b35ea62008-11-29 02:20:26 +0000555** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000556** section 6.5.2.2 lines 483 through 490 specify that when a process
557** sets or clears a lock, that operation overrides any prior locks set
558** by the same process. It does not explicitly say so, but this implies
559** that it overrides locks set by the same process using a different
560** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000561**
562** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000563** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
564**
565** Suppose ./file1 and ./file2 are really the same file (because
566** one is a hard or symbolic link to the other) then if you set
567** an exclusive lock on fd1, then try to get an exclusive lock
568** on fd2, it works. I would have expected the second lock to
569** fail since there was already a lock on the file due to fd1.
570** But not so. Since both locks came from the same process, the
571** second overrides the first, even though they were on different
572** file descriptors opened on different file names.
573**
drh734c9862008-11-28 15:37:20 +0000574** This means that we cannot use POSIX locks to synchronize file access
575** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000576** to synchronize access for threads in separate processes, but not
577** threads within the same process.
578**
579** To work around the problem, SQLite has to manage file locks internally
580** on its own. Whenever a new database is opened, we have to find the
581** specific inode of the database file (the inode is determined by the
582** st_dev and st_ino fields of the stat structure that fstat() fills in)
583** and check for locks already existing on that inode. When locks are
584** created or removed, we have to look at our own internal record of the
585** locks to see if another thread has previously set a lock on that same
586** inode.
587**
drh9b35ea62008-11-29 02:20:26 +0000588** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
589** For VxWorks, we have to use the alternative unique ID system based on
590** canonical filename and implemented in the previous division.)
591**
danielk1977ad94b582007-08-20 06:44:22 +0000592** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000593** descriptor. It is now a structure that holds the integer file
594** descriptor and a pointer to a structure that describes the internal
595** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000596** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000597** point to the same locking structure. The locking structure keeps
598** a reference count (so we will know when to delete it) and a "cnt"
599** field that tells us its internal lock status. cnt==0 means the
600** file is unlocked. cnt==-1 means the file has an exclusive lock.
601** cnt>0 means there are cnt shared locks on the file.
602**
603** Any attempt to lock or unlock a file first checks the locking
604** structure. The fcntl() system call is only invoked to set a
605** POSIX lock if the internal lock structure transitions between
606** a locked and an unlocked state.
607**
drh734c9862008-11-28 15:37:20 +0000608** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000609**
610** If you close a file descriptor that points to a file that has locks,
611** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000612** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000613** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000614** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000615** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000616** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000617** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000618** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000619** be closed and that list is walked (and cleared) when the last lock
620** clears.
621**
drh9b35ea62008-11-29 02:20:26 +0000622** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000623**
drh9b35ea62008-11-29 02:20:26 +0000624** Many older versions of linux use the LinuxThreads library which is
625** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000626** A cannot be modified or overridden by a different thread B.
627** Only thread A can modify the lock. Locking behavior is correct
628** if the appliation uses the newer Native Posix Thread Library (NPTL)
629** on linux - with NPTL a lock created by thread A can override locks
630** in thread B. But there is no way to know at compile-time which
631** threading library is being used. So there is no way to know at
632** compile-time whether or not thread A can override locks on thread B.
633** We have to do a run-time check to discover the behavior of the
634** current process.
drh5fdae772004-06-29 03:29:00 +0000635**
drh734c9862008-11-28 15:37:20 +0000636** On systems where thread A is unable to modify locks created by
637** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000638** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000639** structure to record this information. And on those systems it
640** is illegal to begin a transaction in one thread and finish it
641** in another. For this latter restriction, there is no work-around.
642** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000643*/
644
645/*
drh6c7d5c52008-11-21 20:32:33 +0000646** Set or check the unixFile.tid field. This field is set when an unixFile
647** is first opened. All subsequent uses of the unixFile verify that the
648** same thread is operating on the unixFile. Some operating systems do
649** not allow locks to be overridden by other threads and that restriction
650** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000651** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000652**
653** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
654** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000655** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000656** or if no locks are held. But the unixFile.pLock field needs to be
657** recomputed because its key includes the thread-id. See the
658** transferOwnership() function below for additional information
659*/
drh734c9862008-11-28 15:37:20 +0000660#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000661# define SET_THREADID(X) (X)->tid = pthread_self()
662# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
663 !pthread_equal((X)->tid, pthread_self()))
664#else
665# define SET_THREADID(X)
666# define CHECK_THREADID(X) 0
667#endif
668
669/*
drhbbd42a62004-05-22 17:41:58 +0000670** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000671** to locate a particular unixOpenCnt structure given its inode. This
672** is the same as the unixLockKey except that the thread ID is omitted.
673*/
674struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000675 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000676#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000677 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000678#else
drh107886a2008-11-21 22:21:50 +0000679 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000680#endif
681};
682
683/*
684** An instance of the following structure serves as the key used
685** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000686**
drh734c9862008-11-28 15:37:20 +0000687** If threads cannot override each others locks (LinuxThreads), then we
688** set the unixLockKey.tid field to the thread ID. If threads can override
689** each others locks (Posix and NPTL) then tid is always set to zero.
690** tid is omitted if we compile without threading support or on an OS
691** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000692*/
drh6c7d5c52008-11-21 20:32:33 +0000693struct unixLockKey {
694 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000695#if SQLITE_THREADSAFE && defined(__linux__)
696 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000697#endif
drhbbd42a62004-05-22 17:41:58 +0000698};
699
700/*
701** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000702** inode. Or, on LinuxThreads, there is one of these structures for
703** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000704**
danielk1977ad94b582007-08-20 06:44:22 +0000705** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000706** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000707** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000708*/
drh6c7d5c52008-11-21 20:32:33 +0000709struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000710 struct unixLockKey lockKey; /* The lookup key */
711 int cnt; /* Number of SHARED locks held */
712 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
713 int nRef; /* Number of pointers to this structure */
714 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
715 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000716};
717
718/*
719** An instance of the following structure is allocated for each open
720** inode. This structure keeps track of the number of locks on that
721** inode. If a close is attempted against an inode that is holding
722** locks, the close is deferred until all locks clear by adding the
723** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000724**
725** TODO: Consider changing this so that there is only a single file
726** descriptor for each open file, even when it is opened multiple times.
727** The close() system call would only occur when the last database
728** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000729*/
drh6c7d5c52008-11-21 20:32:33 +0000730struct unixOpenCnt {
731 struct unixFileId fileId; /* The lookup key */
732 int nRef; /* Number of pointers to this structure */
733 int nLock; /* Number of outstanding locks */
734 int nPending; /* Number of pending close() operations */
735 int *aPending; /* Malloced space holding fd's awaiting a close() */
736#if OS_VXWORKS
737 sem_t *pSem; /* Named POSIX semaphore */
chw97185482008-11-17 08:05:31 +0000738 char aSemName[MAX_PATHNAME+1]; /* Name of that semaphore */
739#endif
drh6c7d5c52008-11-21 20:32:33 +0000740 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000741};
742
drhda0e7682008-07-30 15:27:54 +0000743/*
drh9b35ea62008-11-29 02:20:26 +0000744** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
745** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000746** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000747** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000748*/
drh6c7d5c52008-11-21 20:32:33 +0000749static struct unixLockInfo *lockList = 0;
750static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000751
drh5fdae772004-06-29 03:29:00 +0000752/*
drh9b35ea62008-11-29 02:20:26 +0000753** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000754** locks.
755**
drh9b35ea62008-11-29 02:20:26 +0000756** 0: No. Threads cannot override each others locks. (LinuxThreads)
757** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000758** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000759**
drh5062d3a2006-01-31 23:03:35 +0000760** On some systems, we know at compile-time if threads can override each
761** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
762** will be set appropriately. On other systems, we have to check at
763** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
764** undefined.
765**
drhf1a221e2006-01-15 17:27:17 +0000766** This variable normally has file scope only. But during testing, we make
767** it a global so that the test code can change its value in order to verify
768** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000769*/
drh715ff302008-12-03 22:32:44 +0000770#if SQLITE_THREADSAFE && defined(__linux__)
771# ifndef SQLITE_THREAD_OVERRIDE_LOCK
772# define SQLITE_THREAD_OVERRIDE_LOCK -1
773# endif
774# ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000775int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000776# else
drh5062d3a2006-01-31 23:03:35 +0000777static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000778# endif
drh029b44b2006-01-15 00:13:15 +0000779#endif
drh5fdae772004-06-29 03:29:00 +0000780
781/*
782** This structure holds information passed into individual test
783** threads by the testThreadLockingBehavior() routine.
784*/
785struct threadTestData {
786 int fd; /* File to be locked */
787 struct flock lock; /* The locking operation */
788 int result; /* Result of the locking operation */
789};
790
drh6c7d5c52008-11-21 20:32:33 +0000791#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000792/*
danielk197741a6a612008-11-11 18:34:35 +0000793** This function is used as the main routine for a thread launched by
794** testThreadLockingBehavior(). It tests whether the shared-lock obtained
795** by the main thread in testThreadLockingBehavior() conflicts with a
796** hypothetical write-lock obtained by this thread on the same file.
797**
798** The write-lock is not actually acquired, as this is not possible if
799** the file is open in read-only mode (see ticket #3472).
800*/
drh5fdae772004-06-29 03:29:00 +0000801static void *threadLockingTest(void *pArg){
802 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000803 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000804 return pArg;
805}
drh6c7d5c52008-11-21 20:32:33 +0000806#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000807
drh6c7d5c52008-11-21 20:32:33 +0000808
809#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000810/*
811** This procedure attempts to determine whether or not threads
812** can override each others locks then sets the
813** threadsOverrideEachOthersLocks variable appropriately.
814*/
danielk19774d5238f2006-01-27 06:32:00 +0000815static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000816 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000817 int rc;
818 struct threadTestData d;
819 struct flock l;
820 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000821
822 fd = dup(fd_orig);
823 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000824 memset(&l, 0, sizeof(l));
825 l.l_type = F_RDLCK;
826 l.l_len = 1;
827 l.l_start = 0;
828 l.l_whence = SEEK_SET;
829 rc = fcntl(fd_orig, F_SETLK, &l);
830 if( rc!=0 ) return;
831 memset(&d, 0, sizeof(d));
832 d.fd = fd;
833 d.lock = l;
834 d.lock.l_type = F_WRLCK;
835 pthread_create(&t, 0, threadLockingTest, &d);
836 pthread_join(t, 0);
drh5fdae772004-06-29 03:29:00 +0000837 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000838 if( d.result!=0 ) return;
839 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000840}
drh6c7d5c52008-11-21 20:32:33 +0000841#endif /* SQLITE_THERADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000842
drhbbd42a62004-05-22 17:41:58 +0000843/*
drh6c7d5c52008-11-21 20:32:33 +0000844** Release a unixLockInfo structure previously allocated by findLockInfo().
845*/
846static void releaseLockInfo(struct unixLockInfo *pLock){
danielk1977e339d652008-06-28 11:23:00 +0000847 if( pLock ){
848 pLock->nRef--;
849 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000850 if( pLock->pPrev ){
851 assert( pLock->pPrev->pNext==pLock );
852 pLock->pPrev->pNext = pLock->pNext;
853 }else{
854 assert( lockList==pLock );
855 lockList = pLock->pNext;
856 }
857 if( pLock->pNext ){
858 assert( pLock->pNext->pPrev==pLock );
859 pLock->pNext->pPrev = pLock->pPrev;
860 }
danielk1977e339d652008-06-28 11:23:00 +0000861 sqlite3_free(pLock);
862 }
drhbbd42a62004-05-22 17:41:58 +0000863 }
864}
865
866/*
drh6c7d5c52008-11-21 20:32:33 +0000867** Release a unixOpenCnt structure previously allocated by findLockInfo().
drhbbd42a62004-05-22 17:41:58 +0000868*/
drh6c7d5c52008-11-21 20:32:33 +0000869static void releaseOpenCnt(struct unixOpenCnt *pOpen){
danielk1977e339d652008-06-28 11:23:00 +0000870 if( pOpen ){
871 pOpen->nRef--;
872 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000873 if( pOpen->pPrev ){
874 assert( pOpen->pPrev->pNext==pOpen );
875 pOpen->pPrev->pNext = pOpen->pNext;
876 }else{
877 assert( openList==pOpen );
878 openList = pOpen->pNext;
879 }
880 if( pOpen->pNext ){
881 assert( pOpen->pNext->pPrev==pOpen );
882 pOpen->pNext->pPrev = pOpen->pPrev;
883 }
884 sqlite3_free(pOpen->aPending);
danielk1977e339d652008-06-28 11:23:00 +0000885 sqlite3_free(pOpen);
886 }
drhbbd42a62004-05-22 17:41:58 +0000887 }
888}
889
drh6c7d5c52008-11-21 20:32:33 +0000890/*
891** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
892** describes that file descriptor. Create new ones if necessary. The
893** return values might be uninitialized if an error occurs.
894**
895** Return an appropriate error code.
896*/
897static int findLockInfo(
898 unixFile *pFile, /* Unix file with file desc used in the key */
899 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
900 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
901){
902 int rc; /* System call return code */
903 int fd; /* The file descriptor for pFile */
904 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
905 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
906 struct stat statbuf; /* Low-level file information */
907 struct unixLockInfo *pLock; /* Candidate unixLockInfo object */
908 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
909
910 /* Get low-level information about the file that we can used to
911 ** create a unique name for the file.
912 */
913 fd = pFile->h;
914 rc = fstat(fd, &statbuf);
915 if( rc!=0 ){
916 pFile->lastErrno = errno;
917#ifdef EOVERFLOW
918 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
919#endif
920 return SQLITE_IOERR;
921 }
922
923 /* On OS X on an msdos filesystem, the inode number is reported
924 ** incorrectly for zero-size files. See ticket #3260. To work
925 ** around this problem (we consider it a bug in OS X, not SQLite)
926 ** we always increase the file size to 1 by writing a single byte
927 ** prior to accessing the inode number. The one byte written is
928 ** an ASCII 'S' character which also happens to be the first byte
929 ** in the header of every SQLite database. In this way, if there
930 ** is a race condition such that another thread has already populated
931 ** the first page of the database, no damage is done.
932 */
933 if( statbuf.st_size==0 ){
934 write(fd, "S", 1);
935 rc = fstat(fd, &statbuf);
936 if( rc!=0 ){
937 pFile->lastErrno = errno;
938 return SQLITE_IOERR;
939 }
940 }
941
942 memset(&lockKey, 0, sizeof(lockKey));
943 lockKey.fid.dev = statbuf.st_dev;
944#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000945 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000946#else
947 lockKey.fid.ino = statbuf.st_ino;
948#endif
drh734c9862008-11-28 15:37:20 +0000949#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000950 if( threadsOverrideEachOthersLocks<0 ){
951 testThreadLockingBehavior(fd);
952 }
953 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
954#endif
955 fileId = lockKey.fid;
956 if( ppLock!=0 ){
957 pLock = lockList;
958 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
959 pLock = pLock->pNext;
960 }
961 if( pLock==0 ){
962 pLock = sqlite3_malloc( sizeof(*pLock) );
963 if( pLock==0 ){
964 rc = SQLITE_NOMEM;
965 goto exit_findlockinfo;
966 }
967 pLock->lockKey = lockKey;
968 pLock->nRef = 1;
969 pLock->cnt = 0;
970 pLock->locktype = 0;
971 pLock->pNext = lockList;
972 pLock->pPrev = 0;
973 if( lockList ) lockList->pPrev = pLock;
974 lockList = pLock;
975 }else{
976 pLock->nRef++;
977 }
978 *ppLock = pLock;
979 }
980 if( ppOpen!=0 ){
981 pOpen = openList;
982 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
983 pOpen = pOpen->pNext;
984 }
985 if( pOpen==0 ){
986 pOpen = sqlite3_malloc( sizeof(*pOpen) );
987 if( pOpen==0 ){
988 releaseLockInfo(pLock);
989 rc = SQLITE_NOMEM;
990 goto exit_findlockinfo;
991 }
992 pOpen->fileId = fileId;
993 pOpen->nRef = 1;
994 pOpen->nLock = 0;
995 pOpen->nPending = 0;
996 pOpen->aPending = 0;
997 pOpen->pNext = openList;
998 pOpen->pPrev = 0;
999 if( openList ) openList->pPrev = pOpen;
1000 openList = pOpen;
1001#if OS_VXWORKS
1002 pOpen->pSem = NULL;
1003 pOpen->aSemName[0] = '\0';
1004#endif
1005 }else{
1006 pOpen->nRef++;
1007 }
1008 *ppOpen = pOpen;
1009 }
1010
1011exit_findlockinfo:
1012 return rc;
1013}
drh6c7d5c52008-11-21 20:32:33 +00001014
drh7708e972008-11-29 00:56:52 +00001015/*
1016** If we are currently in a different thread than the thread that the
1017** unixFile argument belongs to, then transfer ownership of the unixFile
1018** over to the current thread.
1019**
1020** A unixFile is only owned by a thread on systems that use LinuxThreads.
1021**
1022** Ownership transfer is only allowed if the unixFile is currently unlocked.
1023** If the unixFile is locked and an ownership is wrong, then return
1024** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1025*/
1026#if SQLITE_THREADSAFE && defined(__linux__)
1027static int transferOwnership(unixFile *pFile){
1028 int rc;
1029 pthread_t hSelf;
1030 if( threadsOverrideEachOthersLocks ){
1031 /* Ownership transfers not needed on this system */
1032 return SQLITE_OK;
1033 }
1034 hSelf = pthread_self();
1035 if( pthread_equal(pFile->tid, hSelf) ){
1036 /* We are still in the same thread */
1037 OSTRACE1("No-transfer, same thread\n");
1038 return SQLITE_OK;
1039 }
1040 if( pFile->locktype!=NO_LOCK ){
1041 /* We cannot change ownership while we are holding a lock! */
1042 return SQLITE_MISUSE;
1043 }
1044 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1045 pFile->h, pFile->tid, hSelf);
1046 pFile->tid = hSelf;
1047 if (pFile->pLock != NULL) {
1048 releaseLockInfo(pFile->pLock);
1049 rc = findLockInfo(pFile, &pFile->pLock, 0);
1050 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1051 locktypeName(pFile->locktype),
1052 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1053 return rc;
1054 } else {
1055 return SQLITE_OK;
1056 }
1057}
1058#else /* if not SQLITE_THREADSAFE */
1059 /* On single-threaded builds, ownership transfer is a no-op */
1060# define transferOwnership(X) SQLITE_OK
1061#endif /* SQLITE_THREADSAFE */
1062
aswift5b1a2562008-08-22 00:22:35 +00001063
1064/*
danielk197713adf8a2004-06-03 16:08:41 +00001065** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001066** file by this or any other process. If such a lock is held, set *pResOut
1067** to a non-zero value otherwise *pResOut is set to zero. The return value
1068** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001069*/
danielk1977861f7452008-06-05 11:39:11 +00001070static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001071 int rc = SQLITE_OK;
1072 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001073 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001074
danielk1977861f7452008-06-05 11:39:11 +00001075 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1076
drh054889e2005-11-30 03:20:31 +00001077 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001078 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001079
1080 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001081 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001082 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001083 }
1084
drh2ac3ee92004-06-07 16:27:46 +00001085 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001086 */
aswift5b1a2562008-08-22 00:22:35 +00001087 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001088 struct flock lock;
1089 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001090 lock.l_start = RESERVED_BYTE;
1091 lock.l_len = 1;
1092 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001093 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1094 int tErrno = errno;
1095 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1096 pFile->lastErrno = tErrno;
1097 } else if( lock.l_type!=F_UNLCK ){
1098 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001099 }
1100 }
1101
drh6c7d5c52008-11-21 20:32:33 +00001102 unixLeaveMutex();
aswift5b1a2562008-08-22 00:22:35 +00001103 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001104
aswift5b1a2562008-08-22 00:22:35 +00001105 *pResOut = reserved;
1106 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001107}
1108
1109/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001110** Lock the file with the lock specified by parameter locktype - one
1111** of the following:
1112**
drh2ac3ee92004-06-07 16:27:46 +00001113** (1) SHARED_LOCK
1114** (2) RESERVED_LOCK
1115** (3) PENDING_LOCK
1116** (4) EXCLUSIVE_LOCK
1117**
drhb3e04342004-06-08 00:47:47 +00001118** Sometimes when requesting one lock state, additional lock states
1119** are inserted in between. The locking might fail on one of the later
1120** transitions leaving the lock state different from what it started but
1121** still short of its goal. The following chart shows the allowed
1122** transitions and the inserted intermediate states:
1123**
1124** UNLOCKED -> SHARED
1125** SHARED -> RESERVED
1126** SHARED -> (PENDING) -> EXCLUSIVE
1127** RESERVED -> (PENDING) -> EXCLUSIVE
1128** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001129**
drha6abd042004-06-09 17:37:22 +00001130** This routine will only increase a lock. Use the sqlite3OsUnlock()
1131** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001132*/
danielk197762079062007-08-15 17:08:46 +00001133static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001134 /* The following describes the implementation of the various locks and
1135 ** lock transitions in terms of the POSIX advisory shared and exclusive
1136 ** lock primitives (called read-locks and write-locks below, to avoid
1137 ** confusion with SQLite lock names). The algorithms are complicated
1138 ** slightly in order to be compatible with windows systems simultaneously
1139 ** accessing the same database file, in case that is ever required.
1140 **
1141 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1142 ** byte', each single bytes at well known offsets, and the 'shared byte
1143 ** range', a range of 510 bytes at a well known offset.
1144 **
1145 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1146 ** byte'. If this is successful, a random byte from the 'shared byte
1147 ** range' is read-locked and the lock on the 'pending byte' released.
1148 **
danielk197790ba3bd2004-06-25 08:32:25 +00001149 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1150 ** A RESERVED lock is implemented by grabbing a write-lock on the
1151 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001152 **
1153 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001154 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1155 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1156 ** obtained, but existing SHARED locks are allowed to persist. A process
1157 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1158 ** This property is used by the algorithm for rolling back a journal file
1159 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001160 **
danielk197790ba3bd2004-06-25 08:32:25 +00001161 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1162 ** implemented by obtaining a write-lock on the entire 'shared byte
1163 ** range'. Since all other locks require a read-lock on one of the bytes
1164 ** within this range, this ensures that no other locks are held on the
1165 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001166 **
1167 ** The reason a single byte cannot be used instead of the 'shared byte
1168 ** range' is that some versions of windows do not support read-locks. By
1169 ** locking a random byte from a range, concurrent SHARED locks may exist
1170 ** even if the locking primitive used is always a write-lock.
1171 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001172 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001173 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001174 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001175 struct flock lock;
1176 int s;
1177
drh054889e2005-11-30 03:20:31 +00001178 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001179 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001180 locktypeName(locktype), locktypeName(pFile->locktype),
1181 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001182
1183 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001184 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001185 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001186 */
drh054889e2005-11-30 03:20:31 +00001187 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001188 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001189 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001190 return SQLITE_OK;
1191 }
1192
drhb3e04342004-06-08 00:47:47 +00001193 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001194 */
drh054889e2005-11-30 03:20:31 +00001195 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001196 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001197 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001198
drh054889e2005-11-30 03:20:31 +00001199 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001200 */
drh6c7d5c52008-11-21 20:32:33 +00001201 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001202
drh029b44b2006-01-15 00:13:15 +00001203 /* Make sure the current thread owns the pFile.
1204 */
1205 rc = transferOwnership(pFile);
1206 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001207 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001208 return rc;
1209 }
drh64b1bea2006-01-15 02:30:57 +00001210 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001211
danielk1977ad94b582007-08-20 06:44:22 +00001212 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001213 ** handle that precludes the requested lock, return BUSY.
1214 */
drh054889e2005-11-30 03:20:31 +00001215 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001216 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001217 ){
1218 rc = SQLITE_BUSY;
1219 goto end_lock;
1220 }
1221
1222 /* If a SHARED lock is requested, and some thread using this PID already
1223 ** has a SHARED or RESERVED lock, then increment reference counts and
1224 ** return SQLITE_OK.
1225 */
1226 if( locktype==SHARED_LOCK &&
1227 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1228 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001229 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001230 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001231 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001232 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001233 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001234 goto end_lock;
1235 }
1236
danielk197713adf8a2004-06-03 16:08:41 +00001237 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001238
danielk19779a1d0ab2004-06-01 14:09:28 +00001239 lock.l_whence = SEEK_SET;
1240
drh3cde3bb2004-06-12 02:17:14 +00001241 /* A PENDING lock is needed before acquiring a SHARED lock and before
1242 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1243 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001244 */
drh3cde3bb2004-06-12 02:17:14 +00001245 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001246 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001247 ){
danielk1977489468c2004-06-28 08:25:47 +00001248 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001249 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001250 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001251 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001252 int tErrno = errno;
1253 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1254 if( IS_LOCK_ERROR(rc) ){
1255 pFile->lastErrno = tErrno;
1256 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001257 goto end_lock;
1258 }
drh3cde3bb2004-06-12 02:17:14 +00001259 }
1260
1261
1262 /* If control gets to this point, then actually go ahead and make
1263 ** operating system calls for the specified lock.
1264 */
1265 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001266 int tErrno = 0;
drh3cde3bb2004-06-12 02:17:14 +00001267 assert( pLock->cnt==0 );
1268 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001269
drh2ac3ee92004-06-07 16:27:46 +00001270 /* Now get the read-lock */
1271 lock.l_start = SHARED_FIRST;
1272 lock.l_len = SHARED_SIZE;
aswift5b1a2562008-08-22 00:22:35 +00001273 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1274 tErrno = errno;
1275 }
drh2ac3ee92004-06-07 16:27:46 +00001276 /* Drop the temporary PENDING lock */
1277 lock.l_start = PENDING_BYTE;
1278 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001279 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001280 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001281 if( s != -1 ){
1282 /* This could happen with a network mount */
1283 tErrno = errno;
1284 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1285 if( IS_LOCK_ERROR(rc) ){
1286 pFile->lastErrno = tErrno;
1287 }
1288 goto end_lock;
1289 }
drh2b4b5962005-06-15 17:47:55 +00001290 }
drhe2396a12007-03-29 20:19:58 +00001291 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001292 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1293 if( IS_LOCK_ERROR(rc) ){
1294 pFile->lastErrno = tErrno;
1295 }
drhbbd42a62004-05-22 17:41:58 +00001296 }else{
drh054889e2005-11-30 03:20:31 +00001297 pFile->locktype = SHARED_LOCK;
1298 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001299 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001300 }
drh3cde3bb2004-06-12 02:17:14 +00001301 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1302 /* We are trying for an exclusive lock but another thread in this
1303 ** same process is still holding a shared lock. */
1304 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001305 }else{
drh3cde3bb2004-06-12 02:17:14 +00001306 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001307 ** assumed that there is a SHARED or greater lock on the file
1308 ** already.
1309 */
drh054889e2005-11-30 03:20:31 +00001310 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001311 lock.l_type = F_WRLCK;
1312 switch( locktype ){
1313 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001314 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001315 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001316 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001317 lock.l_start = SHARED_FIRST;
1318 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001319 break;
1320 default:
1321 assert(0);
1322 }
drh054889e2005-11-30 03:20:31 +00001323 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001324 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001325 int tErrno = errno;
1326 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1327 if( IS_LOCK_ERROR(rc) ){
1328 pFile->lastErrno = tErrno;
1329 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001330 }
drhbbd42a62004-05-22 17:41:58 +00001331 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001332
drh8f941bc2009-01-14 23:03:40 +00001333
1334#ifndef NDEBUG
1335 /* Set up the transaction-counter change checking flags when
1336 ** transitioning from a SHARED to a RESERVED lock. The change
1337 ** from SHARED to RESERVED marks the beginning of a normal
1338 ** write operation (not a hot journal rollback).
1339 */
1340 if( rc==SQLITE_OK
1341 && pFile->locktype<=SHARED_LOCK
1342 && locktype==RESERVED_LOCK
1343 ){
1344 pFile->transCntrChng = 0;
1345 pFile->dbUpdate = 0;
1346 pFile->inNormalWrite = 1;
1347 }
1348#endif
1349
1350
danielk1977ecb2a962004-06-02 06:30:16 +00001351 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001352 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001353 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001354 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001355 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001356 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001357 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001358
1359end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001360 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001361 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001362 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001363 return rc;
1364}
1365
1366/*
drh054889e2005-11-30 03:20:31 +00001367** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001368** must be either NO_LOCK or SHARED_LOCK.
1369**
1370** If the locking level of the file descriptor is already at or below
1371** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001372*/
danielk197762079062007-08-15 17:08:46 +00001373static int unixUnlock(sqlite3_file *id, int locktype){
drh6c7d5c52008-11-21 20:32:33 +00001374 struct unixLockInfo *pLock;
drha6abd042004-06-09 17:37:22 +00001375 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001376 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001377 unixFile *pFile = (unixFile*)id;
drh1aa5af12008-03-07 19:51:14 +00001378 int h;
drha6abd042004-06-09 17:37:22 +00001379
drh054889e2005-11-30 03:20:31 +00001380 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001381 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001382 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001383
1384 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001385 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001386 return SQLITE_OK;
1387 }
drhf1a221e2006-01-15 17:27:17 +00001388 if( CHECK_THREADID(pFile) ){
1389 return SQLITE_MISUSE;
1390 }
drh6c7d5c52008-11-21 20:32:33 +00001391 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001392 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001393 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001394 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001395 if( pFile->locktype>SHARED_LOCK ){
1396 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001397 SimulateIOErrorBenign(1);
1398 SimulateIOError( h=(-1) )
1399 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001400
1401#ifndef NDEBUG
1402 /* When reducing a lock such that other processes can start
1403 ** reading the database file again, make sure that the
1404 ** transaction counter was updated if any part of the database
1405 ** file changed. If the transaction counter is not updated,
1406 ** other connections to the same file might not realize that
1407 ** the file has changed and hence might not know to flush their
1408 ** cache. The use of a stale cache can lead to database corruption.
1409 */
1410 assert( pFile->inNormalWrite==0
1411 || pFile->dbUpdate==0
1412 || pFile->transCntrChng==1 );
1413 pFile->inNormalWrite = 0;
1414#endif
1415
1416
drh9c105bb2004-10-02 20:38:28 +00001417 if( locktype==SHARED_LOCK ){
1418 lock.l_type = F_RDLCK;
1419 lock.l_whence = SEEK_SET;
1420 lock.l_start = SHARED_FIRST;
1421 lock.l_len = SHARED_SIZE;
drh1aa5af12008-03-07 19:51:14 +00001422 if( fcntl(h, F_SETLK, &lock)==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001423 int tErrno = errno;
1424 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1425 if( IS_LOCK_ERROR(rc) ){
1426 pFile->lastErrno = tErrno;
1427 }
1428 goto end_unlock;
drh9c105bb2004-10-02 20:38:28 +00001429 }
1430 }
drhbbd42a62004-05-22 17:41:58 +00001431 lock.l_type = F_UNLCK;
1432 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001433 lock.l_start = PENDING_BYTE;
1434 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001435 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001436 pLock->locktype = SHARED_LOCK;
1437 }else{
aswift5b1a2562008-08-22 00:22:35 +00001438 int tErrno = errno;
1439 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1440 if( IS_LOCK_ERROR(rc) ){
1441 pFile->lastErrno = tErrno;
1442 }
1443 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001444 }
drhbbd42a62004-05-22 17:41:58 +00001445 }
drha6abd042004-06-09 17:37:22 +00001446 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001447 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001448
drha6abd042004-06-09 17:37:22 +00001449 /* Decrement the shared lock counter. Release the lock using an
1450 ** OS call only when all threads in this same process have released
1451 ** the lock.
1452 */
1453 pLock->cnt--;
1454 if( pLock->cnt==0 ){
1455 lock.l_type = F_UNLCK;
1456 lock.l_whence = SEEK_SET;
1457 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001458 SimulateIOErrorBenign(1);
1459 SimulateIOError( h=(-1) )
1460 SimulateIOErrorBenign(0);
1461 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001462 pLock->locktype = NO_LOCK;
1463 }else{
aswift5b1a2562008-08-22 00:22:35 +00001464 int tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001465 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001466 if( IS_LOCK_ERROR(rc) ){
1467 pFile->lastErrno = tErrno;
1468 }
drh1aa5af12008-03-07 19:51:14 +00001469 pLock->cnt = 1;
aswift5b1a2562008-08-22 00:22:35 +00001470 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001471 }
drha6abd042004-06-09 17:37:22 +00001472 }
1473
drhbbd42a62004-05-22 17:41:58 +00001474 /* Decrement the count of locks against this same file. When the
1475 ** count reaches zero, close any other file descriptors whose close
1476 ** was deferred because of outstanding locks.
1477 */
drh1aa5af12008-03-07 19:51:14 +00001478 if( rc==SQLITE_OK ){
1479 pOpen = pFile->pOpen;
1480 pOpen->nLock--;
1481 assert( pOpen->nLock>=0 );
1482 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1483 int i;
1484 for(i=0; i<pOpen->nPending; i++){
aswiftaebf4132008-11-21 00:10:35 +00001485 /* close pending fds, but if closing fails don't free the array
1486 ** assign -1 to the successfully closed descriptors and record the
1487 ** error. The next attempt to unlock will try again. */
1488 if( pOpen->aPending[i] < 0 ) continue;
1489 if( close(pOpen->aPending[i]) ){
1490 pFile->lastErrno = errno;
1491 rc = SQLITE_IOERR_CLOSE;
1492 }else{
1493 pOpen->aPending[i] = -1;
1494 }
drh1aa5af12008-03-07 19:51:14 +00001495 }
aswiftaebf4132008-11-21 00:10:35 +00001496 if( rc==SQLITE_OK ){
1497 sqlite3_free(pOpen->aPending);
1498 pOpen->nPending = 0;
1499 pOpen->aPending = 0;
1500 }
drhbbd42a62004-05-22 17:41:58 +00001501 }
drhbbd42a62004-05-22 17:41:58 +00001502 }
1503 }
aswift5b1a2562008-08-22 00:22:35 +00001504
1505end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001506 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001507 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001508 return rc;
drhbbd42a62004-05-22 17:41:58 +00001509}
1510
1511/*
danielk1977e339d652008-06-28 11:23:00 +00001512** This function performs the parts of the "close file" operation
1513** common to all locking schemes. It closes the directory and file
1514** handles, if they are valid, and sets all fields of the unixFile
1515** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001516**
1517** It is *not* necessary to hold the mutex when this routine is called,
1518** even on VxWorks. A mutex will be acquired on VxWorks by the
1519** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001520*/
1521static int closeUnixFile(sqlite3_file *id){
1522 unixFile *pFile = (unixFile*)id;
1523 if( pFile ){
1524 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001525 int err = close(pFile->dirfd);
1526 if( err ){
1527 pFile->lastErrno = errno;
1528 return SQLITE_IOERR_DIR_CLOSE;
1529 }else{
1530 pFile->dirfd=-1;
1531 }
danielk1977e339d652008-06-28 11:23:00 +00001532 }
1533 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001534 int err = close(pFile->h);
1535 if( err ){
1536 pFile->lastErrno = errno;
1537 return SQLITE_IOERR_CLOSE;
1538 }
danielk1977e339d652008-06-28 11:23:00 +00001539 }
drh6c7d5c52008-11-21 20:32:33 +00001540#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001541 if( pFile->pId ){
1542 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001543 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001544 }
drh107886a2008-11-21 22:21:50 +00001545 vxworksReleaseFileId(pFile->pId);
1546 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001547 }
1548#endif
danielk1977e339d652008-06-28 11:23:00 +00001549 OSTRACE2("CLOSE %-3d\n", pFile->h);
1550 OpenCounter(-1);
1551 memset(pFile, 0, sizeof(unixFile));
1552 }
1553 return SQLITE_OK;
1554}
1555
1556/*
danielk1977e3026632004-06-22 11:29:02 +00001557** Close a file.
1558*/
danielk197762079062007-08-15 17:08:46 +00001559static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001560 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001561 if( id ){
1562 unixFile *pFile = (unixFile *)id;
1563 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001564 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001565 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001566 /* If there are outstanding locks, do not actually close the file just
1567 ** yet because that would clear those locks. Instead, add the file
1568 ** descriptor to pOpen->aPending. It will be automatically closed when
1569 ** the last lock is cleared.
1570 */
1571 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00001572 struct unixOpenCnt *pOpen = pFile->pOpen;
drhda0e7682008-07-30 15:27:54 +00001573 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e339d652008-06-28 11:23:00 +00001574 if( aNew==0 ){
1575 /* If a malloc fails, just leak the file descriptor */
1576 }else{
1577 pOpen->aPending = aNew;
1578 pOpen->aPending[pOpen->nPending] = pFile->h;
1579 pOpen->nPending++;
1580 pFile->h = -1;
1581 }
danielk1977e3026632004-06-22 11:29:02 +00001582 }
danielk1977e339d652008-06-28 11:23:00 +00001583 releaseLockInfo(pFile->pLock);
1584 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001585 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001586 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001587 }
aswiftaebf4132008-11-21 00:10:35 +00001588 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001589}
1590
drh734c9862008-11-28 15:37:20 +00001591/************** End of the posix advisory lock implementation *****************
1592******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001593
drh734c9862008-11-28 15:37:20 +00001594/******************************************************************************
1595****************************** No-op Locking **********************************
1596**
1597** Of the various locking implementations available, this is by far the
1598** simplest: locking is ignored. No attempt is made to lock the database
1599** file for reading or writing.
1600**
1601** This locking mode is appropriate for use on read-only databases
1602** (ex: databases that are burned into CD-ROM, for example.) It can
1603** also be used if the application employs some external mechanism to
1604** prevent simultaneous access of the same database by two or more
1605** database connections. But there is a serious risk of database
1606** corruption if this locking mode is used in situations where multiple
1607** database connections are accessing the same database file at the same
1608** time and one or more of those connections are writing.
1609*/
drhbfe66312006-10-03 17:40:40 +00001610
drh734c9862008-11-28 15:37:20 +00001611static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1612 UNUSED_PARAMETER(NotUsed);
1613 *pResOut = 0;
1614 return SQLITE_OK;
1615}
drh734c9862008-11-28 15:37:20 +00001616static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1617 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1618 return SQLITE_OK;
1619}
drh734c9862008-11-28 15:37:20 +00001620static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1621 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1622 return SQLITE_OK;
1623}
1624
1625/*
drh9b35ea62008-11-29 02:20:26 +00001626** Close the file.
drh734c9862008-11-28 15:37:20 +00001627*/
1628static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001629 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001630}
1631
1632/******************* End of the no-op lock implementation *********************
1633******************************************************************************/
1634
1635/******************************************************************************
1636************************* Begin dot-file Locking ******************************
1637**
1638** The dotfile locking implementation uses the existing of separate lock
1639** files in order to control access to the database. This works on just
1640** about every filesystem imaginable. But there are serious downsides:
1641**
1642** (1) There is zero concurrency. A single reader blocks all other
1643** connections from reading or writing the database.
1644**
1645** (2) An application crash or power loss can leave stale lock files
1646** sitting around that need to be cleared manually.
1647**
1648** Nevertheless, a dotlock is an appropriate locking mode for use if no
1649** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001650**
1651** Dotfile locking works by creating a file in the same directory as the
1652** database and with the same name but with a ".lock" extension added.
1653** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1654** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001655*/
1656
1657/*
1658** The file suffix added to the data base filename in order to create the
1659** lock file.
1660*/
1661#define DOTLOCK_SUFFIX ".lock"
1662
drh7708e972008-11-29 00:56:52 +00001663/*
1664** This routine checks if there is a RESERVED lock held on the specified
1665** file by this or any other process. If such a lock is held, set *pResOut
1666** to a non-zero value otherwise *pResOut is set to zero. The return value
1667** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1668**
1669** In dotfile locking, either a lock exists or it does not. So in this
1670** variation of CheckReservedLock(), *pResOut is set to true if any lock
1671** is held on the file and false if the file is unlocked.
1672*/
drh734c9862008-11-28 15:37:20 +00001673static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1674 int rc = SQLITE_OK;
1675 int reserved = 0;
1676 unixFile *pFile = (unixFile*)id;
1677
1678 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1679
1680 assert( pFile );
1681
1682 /* Check if a thread in this process holds such a lock */
1683 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001684 /* Either this connection or some other connection in the same process
1685 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001686 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001687 }else{
1688 /* The lock is held if and only if the lockfile exists */
1689 const char *zLockFile = (const char*)pFile->lockingContext;
1690 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001691 }
1692 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001693 *pResOut = reserved;
1694 return rc;
1695}
1696
drh7708e972008-11-29 00:56:52 +00001697/*
1698** Lock the file with the lock specified by parameter locktype - one
1699** of the following:
1700**
1701** (1) SHARED_LOCK
1702** (2) RESERVED_LOCK
1703** (3) PENDING_LOCK
1704** (4) EXCLUSIVE_LOCK
1705**
1706** Sometimes when requesting one lock state, additional lock states
1707** are inserted in between. The locking might fail on one of the later
1708** transitions leaving the lock state different from what it started but
1709** still short of its goal. The following chart shows the allowed
1710** transitions and the inserted intermediate states:
1711**
1712** UNLOCKED -> SHARED
1713** SHARED -> RESERVED
1714** SHARED -> (PENDING) -> EXCLUSIVE
1715** RESERVED -> (PENDING) -> EXCLUSIVE
1716** PENDING -> EXCLUSIVE
1717**
1718** This routine will only increase a lock. Use the sqlite3OsUnlock()
1719** routine to lower a locking level.
1720**
1721** With dotfile locking, we really only support state (4): EXCLUSIVE.
1722** But we track the other locking levels internally.
1723*/
drh734c9862008-11-28 15:37:20 +00001724static int dotlockLock(sqlite3_file *id, int locktype) {
1725 unixFile *pFile = (unixFile*)id;
1726 int fd;
1727 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001728 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001729
drh7708e972008-11-29 00:56:52 +00001730
1731 /* If we have any lock, then the lock file already exists. All we have
1732 ** to do is adjust our internal record of the lock level.
1733 */
1734 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001735 pFile->locktype = locktype;
1736#if !OS_VXWORKS
1737 /* Always update the timestamp on the old file */
1738 utimes(zLockFile, NULL);
1739#endif
drh7708e972008-11-29 00:56:52 +00001740 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001741 }
1742
1743 /* grab an exclusive lock */
1744 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1745 if( fd<0 ){
1746 /* failed to open/create the file, someone else may have stolen the lock */
1747 int tErrno = errno;
1748 if( EEXIST == tErrno ){
1749 rc = SQLITE_BUSY;
1750 } else {
1751 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1752 if( IS_LOCK_ERROR(rc) ){
1753 pFile->lastErrno = tErrno;
1754 }
1755 }
drh7708e972008-11-29 00:56:52 +00001756 return rc;
drh734c9862008-11-28 15:37:20 +00001757 }
1758 if( close(fd) ){
1759 pFile->lastErrno = errno;
1760 rc = SQLITE_IOERR_CLOSE;
1761 }
1762
1763 /* got it, set the type and return ok */
1764 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001765 return rc;
1766}
1767
drh7708e972008-11-29 00:56:52 +00001768/*
1769** Lower the locking level on file descriptor pFile to locktype. locktype
1770** must be either NO_LOCK or SHARED_LOCK.
1771**
1772** If the locking level of the file descriptor is already at or below
1773** the requested locking level, this routine is a no-op.
1774**
1775** When the locking level reaches NO_LOCK, delete the lock file.
1776*/
drh734c9862008-11-28 15:37:20 +00001777static int dotlockUnlock(sqlite3_file *id, int locktype) {
1778 unixFile *pFile = (unixFile*)id;
1779 char *zLockFile = (char *)pFile->lockingContext;
1780
1781 assert( pFile );
1782 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1783 pFile->locktype, getpid());
1784 assert( locktype<=SHARED_LOCK );
1785
1786 /* no-op if possible */
1787 if( pFile->locktype==locktype ){
1788 return SQLITE_OK;
1789 }
drh7708e972008-11-29 00:56:52 +00001790
1791 /* To downgrade to shared, simply update our internal notion of the
1792 ** lock state. No need to mess with the file on disk.
1793 */
1794 if( locktype==SHARED_LOCK ){
1795 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001796 return SQLITE_OK;
1797 }
1798
drh7708e972008-11-29 00:56:52 +00001799 /* To fully unlock the database, delete the lock file */
1800 assert( locktype==NO_LOCK );
1801 if( unlink(zLockFile) ){
drh734c9862008-11-28 15:37:20 +00001802 int rc, tErrno = errno;
1803 if( ENOENT != tErrno ){
1804 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1805 }
1806 if( IS_LOCK_ERROR(rc) ){
1807 pFile->lastErrno = tErrno;
1808 }
1809 return rc;
1810 }
1811 pFile->locktype = NO_LOCK;
1812 return SQLITE_OK;
1813}
1814
1815/*
drh9b35ea62008-11-29 02:20:26 +00001816** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001817*/
1818static int dotlockClose(sqlite3_file *id) {
1819 int rc;
1820 if( id ){
1821 unixFile *pFile = (unixFile*)id;
1822 dotlockUnlock(id, NO_LOCK);
1823 sqlite3_free(pFile->lockingContext);
1824 }
drh734c9862008-11-28 15:37:20 +00001825 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001826 return rc;
1827}
1828/****************** End of the dot-file lock implementation *******************
1829******************************************************************************/
1830
1831/******************************************************************************
1832************************** Begin flock Locking ********************************
1833**
1834** Use the flock() system call to do file locking.
1835**
drh6b9d6dd2008-12-03 19:34:47 +00001836** flock() locking is like dot-file locking in that the various
1837** fine-grain locking levels supported by SQLite are collapsed into
1838** a single exclusive lock. In other words, SHARED, RESERVED, and
1839** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1840** still works when you do this, but concurrency is reduced since
1841** only a single process can be reading the database at a time.
1842**
drh734c9862008-11-28 15:37:20 +00001843** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1844** compiling for VXWORKS.
1845*/
1846#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001847
drh6b9d6dd2008-12-03 19:34:47 +00001848/*
1849** This routine checks if there is a RESERVED lock held on the specified
1850** file by this or any other process. If such a lock is held, set *pResOut
1851** to a non-zero value otherwise *pResOut is set to zero. The return value
1852** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1853*/
drh734c9862008-11-28 15:37:20 +00001854static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1855 int rc = SQLITE_OK;
1856 int reserved = 0;
1857 unixFile *pFile = (unixFile*)id;
1858
1859 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1860
1861 assert( pFile );
1862
1863 /* Check if a thread in this process holds such a lock */
1864 if( pFile->locktype>SHARED_LOCK ){
1865 reserved = 1;
1866 }
1867
1868 /* Otherwise see if some other process holds it. */
1869 if( !reserved ){
1870 /* attempt to get the lock */
1871 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1872 if( !lrc ){
1873 /* got the lock, unlock it */
1874 lrc = flock(pFile->h, LOCK_UN);
1875 if ( lrc ) {
1876 int tErrno = errno;
1877 /* unlock failed with an error */
1878 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1879 if( IS_LOCK_ERROR(lrc) ){
1880 pFile->lastErrno = tErrno;
1881 rc = lrc;
1882 }
1883 }
1884 } else {
1885 int tErrno = errno;
1886 reserved = 1;
1887 /* someone else might have it reserved */
1888 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1889 if( IS_LOCK_ERROR(lrc) ){
1890 pFile->lastErrno = tErrno;
1891 rc = lrc;
1892 }
1893 }
1894 }
1895 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
1896
1897#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1898 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1899 rc = SQLITE_OK;
1900 reserved=1;
1901 }
1902#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1903 *pResOut = reserved;
1904 return rc;
1905}
1906
drh6b9d6dd2008-12-03 19:34:47 +00001907/*
1908** Lock the file with the lock specified by parameter locktype - one
1909** of the following:
1910**
1911** (1) SHARED_LOCK
1912** (2) RESERVED_LOCK
1913** (3) PENDING_LOCK
1914** (4) EXCLUSIVE_LOCK
1915**
1916** Sometimes when requesting one lock state, additional lock states
1917** are inserted in between. The locking might fail on one of the later
1918** transitions leaving the lock state different from what it started but
1919** still short of its goal. The following chart shows the allowed
1920** transitions and the inserted intermediate states:
1921**
1922** UNLOCKED -> SHARED
1923** SHARED -> RESERVED
1924** SHARED -> (PENDING) -> EXCLUSIVE
1925** RESERVED -> (PENDING) -> EXCLUSIVE
1926** PENDING -> EXCLUSIVE
1927**
1928** flock() only really support EXCLUSIVE locks. We track intermediate
1929** lock states in the sqlite3_file structure, but all locks SHARED or
1930** above are really EXCLUSIVE locks and exclude all other processes from
1931** access the file.
1932**
1933** This routine will only increase a lock. Use the sqlite3OsUnlock()
1934** routine to lower a locking level.
1935*/
drh734c9862008-11-28 15:37:20 +00001936static int flockLock(sqlite3_file *id, int locktype) {
1937 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001938 unixFile *pFile = (unixFile*)id;
1939
1940 assert( pFile );
1941
1942 /* if we already have a lock, it is exclusive.
1943 ** Just adjust level and punt on outta here. */
1944 if (pFile->locktype > NO_LOCK) {
1945 pFile->locktype = locktype;
1946 return SQLITE_OK;
1947 }
1948
1949 /* grab an exclusive lock */
1950
1951 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1952 int tErrno = errno;
1953 /* didn't get, must be busy */
1954 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1955 if( IS_LOCK_ERROR(rc) ){
1956 pFile->lastErrno = tErrno;
1957 }
1958 } else {
1959 /* got it, set the type and return ok */
1960 pFile->locktype = locktype;
1961 }
1962 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
1963 rc==SQLITE_OK ? "ok" : "failed");
1964#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1965 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1966 rc = SQLITE_BUSY;
1967 }
1968#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1969 return rc;
1970}
1971
drh6b9d6dd2008-12-03 19:34:47 +00001972
1973/*
1974** Lower the locking level on file descriptor pFile to locktype. locktype
1975** must be either NO_LOCK or SHARED_LOCK.
1976**
1977** If the locking level of the file descriptor is already at or below
1978** the requested locking level, this routine is a no-op.
1979*/
drh734c9862008-11-28 15:37:20 +00001980static int flockUnlock(sqlite3_file *id, int locktype) {
1981 unixFile *pFile = (unixFile*)id;
1982
1983 assert( pFile );
1984 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1985 pFile->locktype, getpid());
1986 assert( locktype<=SHARED_LOCK );
1987
1988 /* no-op if possible */
1989 if( pFile->locktype==locktype ){
1990 return SQLITE_OK;
1991 }
1992
1993 /* shared can just be set because we always have an exclusive */
1994 if (locktype==SHARED_LOCK) {
1995 pFile->locktype = locktype;
1996 return SQLITE_OK;
1997 }
1998
1999 /* no, really, unlock. */
2000 int rc = flock(pFile->h, LOCK_UN);
2001 if (rc) {
2002 int r, tErrno = errno;
2003 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2004 if( IS_LOCK_ERROR(r) ){
2005 pFile->lastErrno = tErrno;
2006 }
2007#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2008 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2009 r = SQLITE_BUSY;
2010 }
2011#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2012
2013 return r;
2014 } else {
2015 pFile->locktype = NO_LOCK;
2016 return SQLITE_OK;
2017 }
2018}
2019
2020/*
2021** Close a file.
2022*/
2023static int flockClose(sqlite3_file *id) {
2024 if( id ){
2025 flockUnlock(id, NO_LOCK);
2026 }
2027 return closeUnixFile(id);
2028}
2029
2030#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2031
2032/******************* End of the flock lock implementation *********************
2033******************************************************************************/
2034
2035/******************************************************************************
2036************************ Begin Named Semaphore Locking ************************
2037**
2038** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002039**
2040** Semaphore locking is like dot-lock and flock in that it really only
2041** supports EXCLUSIVE locking. Only a single process can read or write
2042** the database file at a time. This reduces potential concurrency, but
2043** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002044*/
2045#if OS_VXWORKS
2046
drh6b9d6dd2008-12-03 19:34:47 +00002047/*
2048** This routine checks if there is a RESERVED lock held on the specified
2049** file by this or any other process. If such a lock is held, set *pResOut
2050** to a non-zero value otherwise *pResOut is set to zero. The return value
2051** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2052*/
drh734c9862008-11-28 15:37:20 +00002053static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2054 int rc = SQLITE_OK;
2055 int reserved = 0;
2056 unixFile *pFile = (unixFile*)id;
2057
2058 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2059
2060 assert( pFile );
2061
2062 /* Check if a thread in this process holds such a lock */
2063 if( pFile->locktype>SHARED_LOCK ){
2064 reserved = 1;
2065 }
2066
2067 /* Otherwise see if some other process holds it. */
2068 if( !reserved ){
2069 sem_t *pSem = pFile->pOpen->pSem;
2070 struct stat statBuf;
2071
2072 if( sem_trywait(pSem)==-1 ){
2073 int tErrno = errno;
2074 if( EAGAIN != tErrno ){
2075 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2076 pFile->lastErrno = tErrno;
2077 } else {
2078 /* someone else has the lock when we are in NO_LOCK */
2079 reserved = (pFile->locktype < SHARED_LOCK);
2080 }
2081 }else{
2082 /* we could have it if we want it */
2083 sem_post(pSem);
2084 }
2085 }
2086 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2087
2088 *pResOut = reserved;
2089 return rc;
2090}
2091
drh6b9d6dd2008-12-03 19:34:47 +00002092/*
2093** Lock the file with the lock specified by parameter locktype - one
2094** of the following:
2095**
2096** (1) SHARED_LOCK
2097** (2) RESERVED_LOCK
2098** (3) PENDING_LOCK
2099** (4) EXCLUSIVE_LOCK
2100**
2101** Sometimes when requesting one lock state, additional lock states
2102** are inserted in between. The locking might fail on one of the later
2103** transitions leaving the lock state different from what it started but
2104** still short of its goal. The following chart shows the allowed
2105** transitions and the inserted intermediate states:
2106**
2107** UNLOCKED -> SHARED
2108** SHARED -> RESERVED
2109** SHARED -> (PENDING) -> EXCLUSIVE
2110** RESERVED -> (PENDING) -> EXCLUSIVE
2111** PENDING -> EXCLUSIVE
2112**
2113** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2114** lock states in the sqlite3_file structure, but all locks SHARED or
2115** above are really EXCLUSIVE locks and exclude all other processes from
2116** access the file.
2117**
2118** This routine will only increase a lock. Use the sqlite3OsUnlock()
2119** routine to lower a locking level.
2120*/
drh734c9862008-11-28 15:37:20 +00002121static int semLock(sqlite3_file *id, int locktype) {
2122 unixFile *pFile = (unixFile*)id;
2123 int fd;
2124 sem_t *pSem = pFile->pOpen->pSem;
2125 int rc = SQLITE_OK;
2126
2127 /* if we already have a lock, it is exclusive.
2128 ** Just adjust level and punt on outta here. */
2129 if (pFile->locktype > NO_LOCK) {
2130 pFile->locktype = locktype;
2131 rc = SQLITE_OK;
2132 goto sem_end_lock;
2133 }
2134
2135 /* lock semaphore now but bail out when already locked. */
2136 if( sem_trywait(pSem)==-1 ){
2137 rc = SQLITE_BUSY;
2138 goto sem_end_lock;
2139 }
2140
2141 /* got it, set the type and return ok */
2142 pFile->locktype = locktype;
2143
2144 sem_end_lock:
2145 return rc;
2146}
2147
drh6b9d6dd2008-12-03 19:34:47 +00002148/*
2149** Lower the locking level on file descriptor pFile to locktype. locktype
2150** must be either NO_LOCK or SHARED_LOCK.
2151**
2152** If the locking level of the file descriptor is already at or below
2153** the requested locking level, this routine is a no-op.
2154*/
drh734c9862008-11-28 15:37:20 +00002155static int semUnlock(sqlite3_file *id, int locktype) {
2156 unixFile *pFile = (unixFile*)id;
2157 sem_t *pSem = pFile->pOpen->pSem;
2158
2159 assert( pFile );
2160 assert( pSem );
2161 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2162 pFile->locktype, getpid());
2163 assert( locktype<=SHARED_LOCK );
2164
2165 /* no-op if possible */
2166 if( pFile->locktype==locktype ){
2167 return SQLITE_OK;
2168 }
2169
2170 /* shared can just be set because we always have an exclusive */
2171 if (locktype==SHARED_LOCK) {
2172 pFile->locktype = locktype;
2173 return SQLITE_OK;
2174 }
2175
2176 /* no, really unlock. */
2177 if ( sem_post(pSem)==-1 ) {
2178 int rc, tErrno = errno;
2179 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2180 if( IS_LOCK_ERROR(rc) ){
2181 pFile->lastErrno = tErrno;
2182 }
2183 return rc;
2184 }
2185 pFile->locktype = NO_LOCK;
2186 return SQLITE_OK;
2187}
2188
2189/*
2190 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002191 */
drh734c9862008-11-28 15:37:20 +00002192static int semClose(sqlite3_file *id) {
2193 if( id ){
2194 unixFile *pFile = (unixFile*)id;
2195 semUnlock(id, NO_LOCK);
2196 assert( pFile );
2197 unixEnterMutex();
2198 releaseLockInfo(pFile->pLock);
2199 releaseOpenCnt(pFile->pOpen);
2200 closeUnixFile(id);
2201 unixLeaveMutex();
2202 }
2203 return SQLITE_OK;
2204}
2205
2206#endif /* OS_VXWORKS */
2207/*
2208** Named semaphore locking is only available on VxWorks.
2209**
2210*************** End of the named semaphore lock implementation ****************
2211******************************************************************************/
2212
2213
2214/******************************************************************************
2215*************************** Begin AFP Locking *********************************
2216**
2217** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2218** on Apple Macintosh computers - both OS9 and OSX.
2219**
2220** Third-party implementations of AFP are available. But this code here
2221** only works on OSX.
2222*/
2223
drhd2cb50b2009-01-09 21:41:17 +00002224#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002225/*
2226** The afpLockingContext structure contains all afp lock specific state
2227*/
drhbfe66312006-10-03 17:40:40 +00002228typedef struct afpLockingContext afpLockingContext;
2229struct afpLockingContext {
aswiftaebf4132008-11-21 00:10:35 +00002230 unsigned long long sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002231 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002232};
2233
2234struct ByteRangeLockPB2
2235{
2236 unsigned long long offset; /* offset to first byte to lock */
2237 unsigned long long length; /* nbr of bytes to lock */
2238 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2239 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2240 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2241 int fd; /* file desc to assoc this lock with */
2242};
2243
drhfd131da2007-08-07 17:13:03 +00002244#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002245
drh6b9d6dd2008-12-03 19:34:47 +00002246/*
2247** This is a utility for setting or clearing a bit-range lock on an
2248** AFP filesystem.
2249**
2250** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2251*/
2252static int afpSetLock(
2253 const char *path, /* Name of the file to be locked or unlocked */
2254 unixFile *pFile, /* Open file descriptor on path */
2255 unsigned long long offset, /* First byte to be locked */
2256 unsigned long long length, /* Number of bytes to lock */
2257 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002258){
drh6b9d6dd2008-12-03 19:34:47 +00002259 struct ByteRangeLockPB2 pb;
2260 int err;
drhbfe66312006-10-03 17:40:40 +00002261
2262 pb.unLockFlag = setLockFlag ? 0 : 1;
2263 pb.startEndFlag = 0;
2264 pb.offset = offset;
2265 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002266 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002267
2268 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002269 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2270 offset, length);
drhbfe66312006-10-03 17:40:40 +00002271 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2272 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002273 int rc;
2274 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002275 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2276 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002277#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2278 rc = SQLITE_BUSY;
2279#else
drh734c9862008-11-28 15:37:20 +00002280 rc = sqliteErrorFromPosixError(tErrno,
2281 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002282#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002283 if( IS_LOCK_ERROR(rc) ){
2284 pFile->lastErrno = tErrno;
2285 }
2286 return rc;
drhbfe66312006-10-03 17:40:40 +00002287 } else {
aswift5b1a2562008-08-22 00:22:35 +00002288 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002289 }
2290}
2291
drh6b9d6dd2008-12-03 19:34:47 +00002292/*
2293** This routine checks if there is a RESERVED lock held on the specified
2294** file by this or any other process. If such a lock is held, set *pResOut
2295** to a non-zero value otherwise *pResOut is set to zero. The return value
2296** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2297*/
danielk1977e339d652008-06-28 11:23:00 +00002298static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002299 int rc = SQLITE_OK;
2300 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002301 unixFile *pFile = (unixFile*)id;
2302
aswift5b1a2562008-08-22 00:22:35 +00002303 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2304
2305 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002306 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2307
2308 /* Check if a thread in this process holds such a lock */
2309 if( pFile->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002310 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002311 }
2312
2313 /* Otherwise see if some other process holds it.
2314 */
aswift5b1a2562008-08-22 00:22:35 +00002315 if( !reserved ){
2316 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002317 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002318 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002319 /* if we succeeded in taking the reserved lock, unlock it to restore
2320 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002321 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002322 } else {
2323 /* if we failed to get the lock then someone else must have it */
2324 reserved = 1;
2325 }
2326 if( IS_LOCK_ERROR(lrc) ){
2327 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002328 }
2329 }
drhbfe66312006-10-03 17:40:40 +00002330
aswift5b1a2562008-08-22 00:22:35 +00002331 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2332
2333 *pResOut = reserved;
2334 return rc;
drhbfe66312006-10-03 17:40:40 +00002335}
2336
drh6b9d6dd2008-12-03 19:34:47 +00002337/*
2338** Lock the file with the lock specified by parameter locktype - one
2339** of the following:
2340**
2341** (1) SHARED_LOCK
2342** (2) RESERVED_LOCK
2343** (3) PENDING_LOCK
2344** (4) EXCLUSIVE_LOCK
2345**
2346** Sometimes when requesting one lock state, additional lock states
2347** are inserted in between. The locking might fail on one of the later
2348** transitions leaving the lock state different from what it started but
2349** still short of its goal. The following chart shows the allowed
2350** transitions and the inserted intermediate states:
2351**
2352** UNLOCKED -> SHARED
2353** SHARED -> RESERVED
2354** SHARED -> (PENDING) -> EXCLUSIVE
2355** RESERVED -> (PENDING) -> EXCLUSIVE
2356** PENDING -> EXCLUSIVE
2357**
2358** This routine will only increase a lock. Use the sqlite3OsUnlock()
2359** routine to lower a locking level.
2360*/
danielk1977e339d652008-06-28 11:23:00 +00002361static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002362 int rc = SQLITE_OK;
2363 unixFile *pFile = (unixFile*)id;
2364 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002365
2366 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002367 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00002368 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
2369
drhbfe66312006-10-03 17:40:40 +00002370 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002371 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002372 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002373 */
drhbfe66312006-10-03 17:40:40 +00002374 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00002375 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002376 locktypeName(locktype));
2377 return SQLITE_OK;
2378 }
2379
2380 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00002381 */
drhbfe66312006-10-03 17:40:40 +00002382 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2383 assert( locktype!=PENDING_LOCK );
2384 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2385
2386 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002387 */
drh6c7d5c52008-11-21 20:32:33 +00002388 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002389
2390 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002391 */
drhbfe66312006-10-03 17:40:40 +00002392 rc = transferOwnership(pFile);
2393 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002394 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002395 return rc;
2396 }
2397
2398 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002399 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2400 ** be released.
2401 */
drhbfe66312006-10-03 17:40:40 +00002402 if( locktype==SHARED_LOCK
2403 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002404 ){
2405 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002406 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002407 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002408 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002409 goto afp_end_lock;
2410 }
2411 }
2412
2413 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002414 ** operating system calls for the specified lock.
2415 */
drhbfe66312006-10-03 17:40:40 +00002416 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002417 int lk, lrc1, lrc2, lrc1Errno;
drhbfe66312006-10-03 17:40:40 +00002418
aswift5b1a2562008-08-22 00:22:35 +00002419 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002420 /* note that the quality of the randomness doesn't matter that much */
2421 lk = random();
aswiftaebf4132008-11-21 00:10:35 +00002422 context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002423 lrc1 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002424 SHARED_FIRST+context->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002425 if( IS_LOCK_ERROR(lrc1) ){
2426 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002427 }
aswift5b1a2562008-08-22 00:22:35 +00002428 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002429 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002430
aswift5b1a2562008-08-22 00:22:35 +00002431 if( IS_LOCK_ERROR(lrc1) ) {
2432 pFile->lastErrno = lrc1Errno;
2433 rc = lrc1;
2434 goto afp_end_lock;
2435 } else if( IS_LOCK_ERROR(lrc2) ){
2436 rc = lrc2;
2437 goto afp_end_lock;
2438 } else if( lrc1 != SQLITE_OK ) {
2439 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002440 } else {
2441 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002442 pFile->pOpen->nLock++;
drhbfe66312006-10-03 17:40:40 +00002443 }
2444 }else{
2445 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2446 ** assumed that there is a SHARED or greater lock on the file
2447 ** already.
2448 */
2449 int failed = 0;
2450 assert( 0!=pFile->locktype );
2451 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2452 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002453 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drhbfe66312006-10-03 17:40:40 +00002454 }
2455 if (!failed && locktype == EXCLUSIVE_LOCK) {
2456 /* Acquire an EXCLUSIVE lock */
2457
2458 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002459 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002460 */
drh6b9d6dd2008-12-03 19:34:47 +00002461 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
aswiftaebf4132008-11-21 00:10:35 +00002462 context->sharedByte, 1, 0)) ){
2463 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002464 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002465 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002466 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002467 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002468 SHARED_FIRST + context->sharedByte, 1, 1)) ){
2469 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2470 ** a critical I/O error
2471 */
2472 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2473 SQLITE_IOERR_LOCK;
2474 goto afp_end_lock;
2475 }
2476 }else{
aswift5b1a2562008-08-22 00:22:35 +00002477 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002478 }
2479 }
aswift5b1a2562008-08-22 00:22:35 +00002480 if( failed ){
2481 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002482 }
2483 }
2484
2485 if( rc==SQLITE_OK ){
2486 pFile->locktype = locktype;
2487 }else if( locktype==EXCLUSIVE_LOCK ){
2488 pFile->locktype = PENDING_LOCK;
2489 }
2490
2491afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002492 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00002493 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002494 rc==SQLITE_OK ? "ok" : "failed");
2495 return rc;
2496}
2497
2498/*
drh339eb0b2008-03-07 15:34:11 +00002499** Lower the locking level on file descriptor pFile to locktype. locktype
2500** must be either NO_LOCK or SHARED_LOCK.
2501**
2502** If the locking level of the file descriptor is already at or below
2503** the requested locking level, this routine is a no-op.
2504*/
danielk1977e339d652008-06-28 11:23:00 +00002505static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002506 int rc = SQLITE_OK;
2507 unixFile *pFile = (unixFile*)id;
aswiftaebf4132008-11-21 00:10:35 +00002508 afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002509
2510 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002511 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00002512 pFile->locktype, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002513
drhbfe66312006-10-03 17:40:40 +00002514 assert( locktype<=SHARED_LOCK );
2515 if( pFile->locktype<=locktype ){
2516 return SQLITE_OK;
2517 }
2518 if( CHECK_THREADID(pFile) ){
2519 return SQLITE_MISUSE;
2520 }
drh6c7d5c52008-11-21 20:32:33 +00002521 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002522 if( pFile->locktype>SHARED_LOCK ){
aswiftaebf4132008-11-21 00:10:35 +00002523
2524 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002525 rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
aswiftaebf4132008-11-21 00:10:35 +00002526 if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
2527 /* only re-establish the shared lock if necessary */
2528 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002529 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
aswiftaebf4132008-11-21 00:10:35 +00002530 }
2531 }
2532 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002533 rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002534 }
2535 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002536 rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002537 }
2538 }else if( locktype==NO_LOCK ){
2539 /* clear the shared lock */
2540 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002541 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002542 }
drhbfe66312006-10-03 17:40:40 +00002543
aswiftaebf4132008-11-21 00:10:35 +00002544 if( rc==SQLITE_OK ){
2545 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00002546 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002547 pOpen->nLock--;
2548 assert( pOpen->nLock>=0 );
2549 if( pOpen->nLock==0 && pOpen->nPending>0 ){
2550 int i;
2551 for(i=0; i<pOpen->nPending; i++){
2552 if( pOpen->aPending[i] < 0 ) continue;
2553 if( close(pOpen->aPending[i]) ){
2554 pFile->lastErrno = errno;
2555 rc = SQLITE_IOERR_CLOSE;
2556 }else{
2557 pOpen->aPending[i] = -1;
drhbfe66312006-10-03 17:40:40 +00002558 }
aswiftaebf4132008-11-21 00:10:35 +00002559 }
2560 if( rc==SQLITE_OK ){
2561 sqlite3_free(pOpen->aPending);
2562 pOpen->nPending = 0;
2563 pOpen->aPending = 0;
2564 }
drhbfe66312006-10-03 17:40:40 +00002565 }
2566 }
drhbfe66312006-10-03 17:40:40 +00002567 }
drh6c7d5c52008-11-21 20:32:33 +00002568 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002569 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002570 return rc;
2571}
2572
2573/*
drh339eb0b2008-03-07 15:34:11 +00002574** Close a file & cleanup AFP specific locking context
2575*/
danielk1977e339d652008-06-28 11:23:00 +00002576static int afpClose(sqlite3_file *id) {
2577 if( id ){
2578 unixFile *pFile = (unixFile*)id;
2579 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002580 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002581 if( pFile->pOpen && pFile->pOpen->nLock ){
2582 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002583 ** yet because that would clear those locks. Instead, add the file
2584 ** descriptor to pOpen->aPending. It will be automatically closed when
2585 ** the last lock is cleared.
2586 */
aswiftaebf4132008-11-21 00:10:35 +00002587 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00002588 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002589 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
2590 if( aNew==0 ){
2591 /* If a malloc fails, just leak the file descriptor */
2592 }else{
2593 pOpen->aPending = aNew;
2594 pOpen->aPending[pOpen->nPending] = pFile->h;
2595 pOpen->nPending++;
2596 pFile->h = -1;
2597 }
2598 }
2599 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002600 sqlite3_free(pFile->lockingContext);
aswiftaebf4132008-11-21 00:10:35 +00002601 closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002602 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002603 }
aswiftaebf4132008-11-21 00:10:35 +00002604 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002605}
2606
drhd2cb50b2009-01-09 21:41:17 +00002607#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002608/*
2609** The code above is the AFP lock implementation. The code is specific
2610** to MacOSX and does not work on other unix platforms. No alternative
2611** is available. If you don't compile for a mac, then the "unix-afp"
2612** VFS is not available.
2613**
2614********************* End of the AFP lock implementation **********************
2615******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002616
drh734c9862008-11-28 15:37:20 +00002617
2618/******************************************************************************
2619**************** Non-locking sqlite3_file methods *****************************
2620**
2621** The next division contains implementations for all methods of the
2622** sqlite3_file object other than the locking methods. The locking
2623** methods were defined in divisions above (one locking method per
2624** division). Those methods that are common to all locking modes
2625** are gather together into this division.
2626*/
drhbfe66312006-10-03 17:40:40 +00002627
2628/*
drh734c9862008-11-28 15:37:20 +00002629** Seek to the offset passed as the second argument, then read cnt
2630** bytes into pBuf. Return the number of bytes actually read.
2631**
2632** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2633** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2634** one system to another. Since SQLite does not define USE_PREAD
2635** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2636** See tickets #2741 and #2681.
2637**
2638** To avoid stomping the errno value on a failed read the lastErrno value
2639** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002640*/
drh734c9862008-11-28 15:37:20 +00002641static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2642 int got;
2643 i64 newOffset;
2644 TIMER_START;
2645#if defined(USE_PREAD)
2646 got = pread(id->h, pBuf, cnt, offset);
2647 SimulateIOError( got = -1 );
2648#elif defined(USE_PREAD64)
2649 got = pread64(id->h, pBuf, cnt, offset);
2650 SimulateIOError( got = -1 );
2651#else
2652 newOffset = lseek(id->h, offset, SEEK_SET);
2653 SimulateIOError( newOffset-- );
2654 if( newOffset!=offset ){
2655 if( newOffset == -1 ){
2656 ((unixFile*)id)->lastErrno = errno;
2657 }else{
2658 ((unixFile*)id)->lastErrno = 0;
2659 }
2660 return -1;
2661 }
2662 got = read(id->h, pBuf, cnt);
2663#endif
2664 TIMER_END;
2665 if( got<0 ){
2666 ((unixFile*)id)->lastErrno = errno;
2667 }
2668 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2669 return got;
drhbfe66312006-10-03 17:40:40 +00002670}
2671
2672/*
drh734c9862008-11-28 15:37:20 +00002673** Read data from a file into a buffer. Return SQLITE_OK if all
2674** bytes were read successfully and SQLITE_IOERR if anything goes
2675** wrong.
drh339eb0b2008-03-07 15:34:11 +00002676*/
drh734c9862008-11-28 15:37:20 +00002677static int unixRead(
2678 sqlite3_file *id,
2679 void *pBuf,
2680 int amt,
2681 sqlite3_int64 offset
2682){
2683 int got;
2684 assert( id );
2685 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
2686 if( got==amt ){
2687 return SQLITE_OK;
2688 }else if( got<0 ){
2689 /* lastErrno set by seekAndRead */
2690 return SQLITE_IOERR_READ;
2691 }else{
2692 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2693 /* Unread parts of the buffer must be zero-filled */
2694 memset(&((char*)pBuf)[got], 0, amt-got);
2695 return SQLITE_IOERR_SHORT_READ;
2696 }
2697}
2698
2699/*
2700** Seek to the offset in id->offset then read cnt bytes into pBuf.
2701** Return the number of bytes actually read. Update the offset.
2702**
2703** To avoid stomping the errno value on a failed write the lastErrno value
2704** is set before returning.
2705*/
2706static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2707 int got;
2708 i64 newOffset;
2709 TIMER_START;
2710#if defined(USE_PREAD)
2711 got = pwrite(id->h, pBuf, cnt, offset);
2712#elif defined(USE_PREAD64)
2713 got = pwrite64(id->h, pBuf, cnt, offset);
2714#else
2715 newOffset = lseek(id->h, offset, SEEK_SET);
2716 if( newOffset!=offset ){
2717 if( newOffset == -1 ){
2718 ((unixFile*)id)->lastErrno = errno;
2719 }else{
2720 ((unixFile*)id)->lastErrno = 0;
2721 }
2722 return -1;
2723 }
2724 got = write(id->h, pBuf, cnt);
2725#endif
2726 TIMER_END;
2727 if( got<0 ){
2728 ((unixFile*)id)->lastErrno = errno;
2729 }
2730
2731 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2732 return got;
2733}
2734
2735
2736/*
2737** Write data from a buffer into a file. Return SQLITE_OK on success
2738** or some other error code on failure.
2739*/
2740static int unixWrite(
2741 sqlite3_file *id,
2742 const void *pBuf,
2743 int amt,
2744 sqlite3_int64 offset
2745){
2746 int wrote = 0;
2747 assert( id );
2748 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002749
2750#ifndef NDEBUG
2751 /* If we are doing a normal write to a database file (as opposed to
2752 ** doing a hot-journal rollback or a write to some file other than a
2753 ** normal database file) then record the fact that the database
2754 ** has changed. If the transaction counter is modified, record that
2755 ** fact too.
2756 */
2757 if( ((unixFile*)id)->inNormalWrite ){
2758 unixFile *pFile = (unixFile*)id;
2759 pFile->dbUpdate = 1; /* The database has been modified */
2760 if( offset<=24 && offset+amt>=27 ){
2761 char oldCntr[4];
2762 SimulateIOErrorBenign(1);
2763 seekAndRead(pFile, 24, oldCntr, 4);
2764 SimulateIOErrorBenign(0);
2765 if( memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
2766 pFile->transCntrChng = 1; /* The transaction counter has changed */
2767 }
2768 }
2769 }
2770#endif
2771
drh734c9862008-11-28 15:37:20 +00002772 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
2773 amt -= wrote;
2774 offset += wrote;
2775 pBuf = &((char*)pBuf)[wrote];
2776 }
2777 SimulateIOError(( wrote=(-1), amt=1 ));
2778 SimulateDiskfullError(( wrote=0, amt=1 ));
2779 if( amt>0 ){
2780 if( wrote<0 ){
2781 /* lastErrno set by seekAndWrite */
2782 return SQLITE_IOERR_WRITE;
2783 }else{
2784 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2785 return SQLITE_FULL;
2786 }
2787 }
2788 return SQLITE_OK;
2789}
2790
2791#ifdef SQLITE_TEST
2792/*
2793** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002794** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002795*/
2796int sqlite3_sync_count = 0;
2797int sqlite3_fullsync_count = 0;
2798#endif
2799
2800/*
2801** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
2802** Otherwise use fsync() in its place.
2803*/
2804#ifndef HAVE_FDATASYNC
2805# define fdatasync fsync
2806#endif
2807
2808/*
2809** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2810** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2811** only available on Mac OS X. But that could change.
2812*/
2813#ifdef F_FULLFSYNC
2814# define HAVE_FULLFSYNC 1
2815#else
2816# define HAVE_FULLFSYNC 0
2817#endif
2818
2819
2820/*
2821** The fsync() system call does not work as advertised on many
2822** unix systems. The following procedure is an attempt to make
2823** it work better.
2824**
2825** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2826** for testing when we want to run through the test suite quickly.
2827** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2828** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2829** or power failure will likely corrupt the database file.
2830*/
2831static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002832 int rc;
drh734c9862008-11-28 15:37:20 +00002833
2834 /* The following "ifdef/elif/else/" block has the same structure as
2835 ** the one below. It is replicated here solely to avoid cluttering
2836 ** up the real code with the UNUSED_PARAMETER() macros.
2837 */
2838#ifdef SQLITE_NO_SYNC
2839 UNUSED_PARAMETER(fd);
2840 UNUSED_PARAMETER(fullSync);
2841 UNUSED_PARAMETER(dataOnly);
2842#elif HAVE_FULLFSYNC
2843 UNUSED_PARAMETER(dataOnly);
2844#else
2845 UNUSED_PARAMETER(fullSync);
2846#endif
2847
2848 /* Record the number of times that we do a normal fsync() and
2849 ** FULLSYNC. This is used during testing to verify that this procedure
2850 ** gets called with the correct arguments.
2851 */
2852#ifdef SQLITE_TEST
2853 if( fullSync ) sqlite3_fullsync_count++;
2854 sqlite3_sync_count++;
2855#endif
2856
2857 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2858 ** no-op
2859 */
2860#ifdef SQLITE_NO_SYNC
2861 rc = SQLITE_OK;
2862#elif HAVE_FULLFSYNC
2863 if( fullSync ){
2864 rc = fcntl(fd, F_FULLFSYNC, 0);
2865 }else{
2866 rc = 1;
2867 }
2868 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002869 ** It shouldn't be possible for fullfsync to fail on the local
2870 ** file system (on OSX), so failure indicates that FULLFSYNC
2871 ** isn't supported for this file system. So, attempt an fsync
2872 ** and (for now) ignore the overhead of a superfluous fcntl call.
2873 ** It'd be better to detect fullfsync support once and avoid
2874 ** the fcntl call every time sync is called.
2875 */
drh734c9862008-11-28 15:37:20 +00002876 if( rc ) rc = fsync(fd);
2877
2878#else
2879 if( dataOnly ){
2880 rc = fdatasync(fd);
2881 if( OS_VXWORKS && rc==-1 && errno==ENOTSUP ){
2882 rc = fsync(fd);
2883 }
2884 }else{
2885 rc = fsync(fd);
2886 }
2887#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2888
2889 if( OS_VXWORKS && rc!= -1 ){
2890 rc = 0;
2891 }
chw97185482008-11-17 08:05:31 +00002892 return rc;
drhbfe66312006-10-03 17:40:40 +00002893}
2894
drh734c9862008-11-28 15:37:20 +00002895/*
2896** Make sure all writes to a particular file are committed to disk.
2897**
2898** If dataOnly==0 then both the file itself and its metadata (file
2899** size, access time, etc) are synced. If dataOnly!=0 then only the
2900** file data is synced.
2901**
2902** Under Unix, also make sure that the directory entry for the file
2903** has been created by fsync-ing the directory that contains the file.
2904** If we do not do this and we encounter a power failure, the directory
2905** entry for the journal might not exist after we reboot. The next
2906** SQLite to access the file will not know that the journal exists (because
2907** the directory entry for the journal was never created) and the transaction
2908** will not roll back - possibly leading to database corruption.
2909*/
2910static int unixSync(sqlite3_file *id, int flags){
2911 int rc;
2912 unixFile *pFile = (unixFile*)id;
2913
2914 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2915 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2916
2917 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2918 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2919 || (flags&0x0F)==SQLITE_SYNC_FULL
2920 );
2921
2922 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2923 ** line is to test that doing so does not cause any problems.
2924 */
2925 SimulateDiskfullError( return SQLITE_FULL );
2926
2927 assert( pFile );
2928 OSTRACE2("SYNC %-3d\n", pFile->h);
2929 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
2930 SimulateIOError( rc=1 );
2931 if( rc ){
2932 pFile->lastErrno = errno;
2933 return SQLITE_IOERR_FSYNC;
2934 }
2935 if( pFile->dirfd>=0 ){
2936 int err;
2937 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
2938 HAVE_FULLFSYNC, isFullsync);
2939#ifndef SQLITE_DISABLE_DIRSYNC
2940 /* The directory sync is only attempted if full_fsync is
2941 ** turned off or unavailable. If a full_fsync occurred above,
2942 ** then the directory sync is superfluous.
2943 */
2944 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
2945 /*
2946 ** We have received multiple reports of fsync() returning
2947 ** errors when applied to directories on certain file systems.
2948 ** A failed directory sync is not a big deal. So it seems
2949 ** better to ignore the error. Ticket #1657
2950 */
2951 /* pFile->lastErrno = errno; */
2952 /* return SQLITE_IOERR; */
2953 }
2954#endif
2955 err = close(pFile->dirfd); /* Only need to sync once, so close the */
2956 if( err==0 ){ /* directory when we are done */
2957 pFile->dirfd = -1;
2958 }else{
2959 pFile->lastErrno = errno;
2960 rc = SQLITE_IOERR_DIR_CLOSE;
2961 }
2962 }
2963 return rc;
2964}
2965
2966/*
2967** Truncate an open file to a specified size
2968*/
2969static int unixTruncate(sqlite3_file *id, i64 nByte){
2970 int rc;
2971 assert( id );
2972 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
2973 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
2974 if( rc ){
2975 ((unixFile*)id)->lastErrno = errno;
2976 return SQLITE_IOERR_TRUNCATE;
2977 }else{
2978 return SQLITE_OK;
2979 }
2980}
2981
2982/*
2983** Determine the current size of a file in bytes
2984*/
2985static int unixFileSize(sqlite3_file *id, i64 *pSize){
2986 int rc;
2987 struct stat buf;
2988 assert( id );
2989 rc = fstat(((unixFile*)id)->h, &buf);
2990 SimulateIOError( rc=1 );
2991 if( rc!=0 ){
2992 ((unixFile*)id)->lastErrno = errno;
2993 return SQLITE_IOERR_FSTAT;
2994 }
2995 *pSize = buf.st_size;
2996
2997 /* When opening a zero-size database, the findLockInfo() procedure
2998 ** writes a single byte into that file in order to work around a bug
2999 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3000 ** layers, we need to report this file size as zero even though it is
3001 ** really 1. Ticket #3260.
3002 */
3003 if( *pSize==1 ) *pSize = 0;
3004
3005
3006 return SQLITE_OK;
3007}
3008
drhd2cb50b2009-01-09 21:41:17 +00003009#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003010/*
3011** Handler for proxy-locking file-control verbs. Defined below in the
3012** proxying locking division.
3013*/
3014static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003015#endif
drh715ff302008-12-03 22:32:44 +00003016
danielk1977ad94b582007-08-20 06:44:22 +00003017
danielk1977e3026632004-06-22 11:29:02 +00003018/*
drh9e33c2c2007-08-31 18:34:59 +00003019** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003020*/
drhcc6bb3e2007-08-31 16:11:35 +00003021static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003022 switch( op ){
3023 case SQLITE_FCNTL_LOCKSTATE: {
3024 *(int*)pArg = ((unixFile*)id)->locktype;
3025 return SQLITE_OK;
3026 }
drh7708e972008-11-29 00:56:52 +00003027 case SQLITE_LAST_ERRNO: {
3028 *(int*)pArg = ((unixFile*)id)->lastErrno;
3029 return SQLITE_OK;
3030 }
drh8f941bc2009-01-14 23:03:40 +00003031#ifndef NDEBUG
3032 /* The pager calls this method to signal that it has done
3033 ** a rollback and that the database is therefore unchanged and
3034 ** it hence it is OK for the transaction change counter to be
3035 ** unchanged.
3036 */
3037 case SQLITE_FCNTL_DB_UNCHANGED: {
3038 ((unixFile*)id)->dbUpdate = 0;
3039 return SQLITE_OK;
3040 }
3041#endif
drhd2cb50b2009-01-09 21:41:17 +00003042#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003043 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003044 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003045 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003046 }
drhd2cb50b2009-01-09 21:41:17 +00003047#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003048 }
drhcc6bb3e2007-08-31 16:11:35 +00003049 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003050}
3051
3052/*
danielk1977a3d4c882007-03-23 10:08:38 +00003053** Return the sector size in bytes of the underlying block device for
3054** the specified file. This is almost always 512 bytes, but may be
3055** larger for some devices.
3056**
3057** SQLite code assumes this function cannot fail. It also assumes that
3058** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003059** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003060** same for both.
3061*/
danielk1977397d65f2008-11-19 11:35:39 +00003062static int unixSectorSize(sqlite3_file *NotUsed){
3063 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003064 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003065}
3066
danielk197790949c22007-08-17 16:50:38 +00003067/*
danielk1977397d65f2008-11-19 11:35:39 +00003068** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003069*/
danielk1977397d65f2008-11-19 11:35:39 +00003070static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3071 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003072 return 0;
3073}
3074
drh734c9862008-11-28 15:37:20 +00003075/*
3076** Here ends the implementation of all sqlite3_file methods.
3077**
3078********************** End sqlite3_file Methods *******************************
3079******************************************************************************/
3080
3081/*
drh6b9d6dd2008-12-03 19:34:47 +00003082** This division contains definitions of sqlite3_io_methods objects that
3083** implement various file locking strategies. It also contains definitions
3084** of "finder" functions. A finder-function is used to locate the appropriate
3085** sqlite3_io_methods object for a particular database file. The pAppData
3086** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3087** the correct finder-function for that VFS.
3088**
3089** Most finder functions return a pointer to a fixed sqlite3_io_methods
3090** object. The only interesting finder-function is autolockIoFinder, which
3091** looks at the filesystem type and tries to guess the best locking
3092** strategy from that.
3093**
drh1875f7a2008-12-08 18:19:17 +00003094** For finder-funtion F, two objects are created:
3095**
3096** (1) The real finder-function named "FImpt()".
3097**
3098** (2) A constant pointer to this functio named just "F".
3099**
3100**
3101** A pointer to the F pointer is used as the pAppData value for VFS
3102** objects. We have to do this instead of letting pAppData point
3103** directly at the finder-function since C90 rules prevent a void*
3104** from be cast into a function pointer.
3105**
drh6b9d6dd2008-12-03 19:34:47 +00003106**
drh7708e972008-11-29 00:56:52 +00003107** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003108**
drh7708e972008-11-29 00:56:52 +00003109** * A constant sqlite3_io_methods object call METHOD that has locking
3110** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3111**
3112** * An I/O method finder function called FINDER that returns a pointer
3113** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003114*/
drh7708e972008-11-29 00:56:52 +00003115#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3116static const sqlite3_io_methods METHOD = { \
3117 1, /* iVersion */ \
3118 CLOSE, /* xClose */ \
3119 unixRead, /* xRead */ \
3120 unixWrite, /* xWrite */ \
3121 unixTruncate, /* xTruncate */ \
3122 unixSync, /* xSync */ \
3123 unixFileSize, /* xFileSize */ \
3124 LOCK, /* xLock */ \
3125 UNLOCK, /* xUnlock */ \
3126 CKLOCK, /* xCheckReservedLock */ \
3127 unixFileControl, /* xFileControl */ \
3128 unixSectorSize, /* xSectorSize */ \
3129 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3130}; \
drh1875f7a2008-12-08 18:19:17 +00003131static const sqlite3_io_methods *FINDER##Impl(const char *z, int h){ \
drh7708e972008-11-29 00:56:52 +00003132 UNUSED_PARAMETER(z); UNUSED_PARAMETER(h); \
3133 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003134} \
3135static const sqlite3_io_methods *(*const FINDER)(const char*,int) \
3136 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003137
3138/*
3139** Here are all of the sqlite3_io_methods objects for each of the
3140** locking strategies. Functions that return pointers to these methods
3141** are also created.
3142*/
3143IOMETHODS(
3144 posixIoFinder, /* Finder function name */
3145 posixIoMethods, /* sqlite3_io_methods object name */
3146 unixClose, /* xClose method */
3147 unixLock, /* xLock method */
3148 unixUnlock, /* xUnlock method */
3149 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003150)
drh7708e972008-11-29 00:56:52 +00003151IOMETHODS(
3152 nolockIoFinder, /* Finder function name */
3153 nolockIoMethods, /* sqlite3_io_methods object name */
3154 nolockClose, /* xClose method */
3155 nolockLock, /* xLock method */
3156 nolockUnlock, /* xUnlock method */
3157 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003158)
drh7708e972008-11-29 00:56:52 +00003159IOMETHODS(
3160 dotlockIoFinder, /* Finder function name */
3161 dotlockIoMethods, /* sqlite3_io_methods object name */
3162 dotlockClose, /* xClose method */
3163 dotlockLock, /* xLock method */
3164 dotlockUnlock, /* xUnlock method */
3165 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003166)
drh7708e972008-11-29 00:56:52 +00003167
3168#if SQLITE_ENABLE_LOCKING_STYLE
3169IOMETHODS(
3170 flockIoFinder, /* Finder function name */
3171 flockIoMethods, /* sqlite3_io_methods object name */
3172 flockClose, /* xClose method */
3173 flockLock, /* xLock method */
3174 flockUnlock, /* xUnlock method */
3175 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003176)
drh7708e972008-11-29 00:56:52 +00003177#endif
3178
drh6c7d5c52008-11-21 20:32:33 +00003179#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003180IOMETHODS(
3181 semIoFinder, /* Finder function name */
3182 semIoMethods, /* sqlite3_io_methods object name */
3183 semClose, /* xClose method */
3184 semLock, /* xLock method */
3185 semUnlock, /* xUnlock method */
3186 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003187)
aswiftaebf4132008-11-21 00:10:35 +00003188#endif
drh7708e972008-11-29 00:56:52 +00003189
drhd2cb50b2009-01-09 21:41:17 +00003190#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003191IOMETHODS(
3192 afpIoFinder, /* Finder function name */
3193 afpIoMethods, /* sqlite3_io_methods object name */
3194 afpClose, /* xClose method */
3195 afpLock, /* xLock method */
3196 afpUnlock, /* xUnlock method */
3197 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003198)
drh715ff302008-12-03 22:32:44 +00003199#endif
3200
3201/*
3202** The proxy locking method is a "super-method" in the sense that it
3203** opens secondary file descriptors for the conch and lock files and
3204** it uses proxy, dot-file, AFP, and flock() locking methods on those
3205** secondary files. For this reason, the division that implements
3206** proxy locking is located much further down in the file. But we need
3207** to go ahead and define the sqlite3_io_methods and finder function
3208** for proxy locking here. So we forward declare the I/O methods.
3209*/
drhd2cb50b2009-01-09 21:41:17 +00003210#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003211static int proxyClose(sqlite3_file*);
3212static int proxyLock(sqlite3_file*, int);
3213static int proxyUnlock(sqlite3_file*, int);
3214static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003215IOMETHODS(
3216 proxyIoFinder, /* Finder function name */
3217 proxyIoMethods, /* sqlite3_io_methods object name */
3218 proxyClose, /* xClose method */
3219 proxyLock, /* xLock method */
3220 proxyUnlock, /* xUnlock method */
3221 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003222)
aswiftaebf4132008-11-21 00:10:35 +00003223#endif
drh7708e972008-11-29 00:56:52 +00003224
3225
drhd2cb50b2009-01-09 21:41:17 +00003226#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003227/*
drh6b9d6dd2008-12-03 19:34:47 +00003228** This "finder" function attempts to determine the best locking strategy
3229** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003230** object that implements that strategy.
3231**
3232** This is for MacOSX only.
3233*/
drh1875f7a2008-12-08 18:19:17 +00003234static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003235 const char *filePath, /* name of the database file */
3236 int fd /* file descriptor open on the database file */
3237){
3238 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003239 const char *zFilesystem; /* Filesystem type name */
3240 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003241 } aMap[] = {
3242 { "hfs", &posixIoMethods },
3243 { "ufs", &posixIoMethods },
3244 { "afpfs", &afpIoMethods },
3245#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
3246 { "smbfs", &afpIoMethods },
3247#else
3248 { "smbfs", &flockIoMethods },
3249#endif
3250 { "webdav", &nolockIoMethods },
3251 { 0, 0 }
3252 };
3253 int i;
3254 struct statfs fsInfo;
3255 struct flock lockInfo;
3256
3257 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003258 /* If filePath==NULL that means we are dealing with a transient file
3259 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003260 return &nolockIoMethods;
3261 }
3262 if( statfs(filePath, &fsInfo) != -1 ){
3263 if( fsInfo.f_flags & MNT_RDONLY ){
3264 return &nolockIoMethods;
3265 }
3266 for(i=0; aMap[i].zFilesystem; i++){
3267 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3268 return aMap[i].pMethods;
3269 }
3270 }
3271 }
3272
3273 /* Default case. Handles, amongst others, "nfs".
3274 ** Test byte-range lock using fcntl(). If the call succeeds,
3275 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003276 */
drh7708e972008-11-29 00:56:52 +00003277 lockInfo.l_len = 1;
3278 lockInfo.l_start = 0;
3279 lockInfo.l_whence = SEEK_SET;
3280 lockInfo.l_type = F_RDLCK;
3281 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
3282 return &posixIoMethods;
3283 }else{
3284 return &dotlockIoMethods;
3285 }
3286}
danielk1977852e2322008-12-22 03:36:59 +00003287static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
drh1875f7a2008-12-08 18:19:17 +00003288 = autolockIoFinderImpl;
3289
drhd2cb50b2009-01-09 21:41:17 +00003290#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003291
3292/*
3293** An abstract type for a pointer to a IO method finder function:
3294*/
3295typedef const sqlite3_io_methods *(*finder_type)(const char*,int);
3296
aswiftaebf4132008-11-21 00:10:35 +00003297
drh734c9862008-11-28 15:37:20 +00003298/****************************************************************************
3299**************************** sqlite3_vfs methods ****************************
3300**
3301** This division contains the implementation of methods on the
3302** sqlite3_vfs object.
3303*/
3304
danielk1977a3d4c882007-03-23 10:08:38 +00003305/*
danielk1977e339d652008-06-28 11:23:00 +00003306** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003307*/
3308static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003309 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003310 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003311 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003312 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003313 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003314 int noLock, /* Omit locking if true */
3315 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003316){
drh7708e972008-11-29 00:56:52 +00003317 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003318 unixFile *pNew = (unixFile *)pId;
3319 int rc = SQLITE_OK;
3320
danielk197717b90b52008-06-06 11:11:25 +00003321 assert( pNew->pLock==NULL );
3322 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003323
drh715ff302008-12-03 22:32:44 +00003324 /* Parameter isDelete is only used on vxworks.
3325 ** Express this explicitly here to prevent compiler warnings
3326 ** about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003327 */
drh7708e972008-11-29 00:56:52 +00003328#if !OS_VXWORKS
3329 UNUSED_PARAMETER(isDelete);
3330#endif
danielk1977a03396a2008-11-19 14:35:46 +00003331
drh218c5082008-03-07 00:27:10 +00003332 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003333 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003334 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003335 SET_THREADID(pNew);
drh339eb0b2008-03-07 15:34:11 +00003336
drh6c7d5c52008-11-21 20:32:33 +00003337#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003338 pNew->pId = vxworksFindFileId(zFilename);
3339 if( pNew->pId==0 ){
3340 noLock = 1;
3341 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003342 }
3343#endif
3344
drhda0e7682008-07-30 15:27:54 +00003345 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003346 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003347 }else{
drh1875f7a2008-12-08 18:19:17 +00003348 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, h);
aswiftaebf4132008-11-21 00:10:35 +00003349#if SQLITE_ENABLE_LOCKING_STYLE
3350 /* Cache zFilename in the locking context (AFP and dotlock override) for
3351 ** proxyLock activation is possible (remote proxy is based on db name)
3352 ** zFilename remains valid until file is closed, to support */
3353 pNew->lockingContext = (void*)zFilename;
3354#endif
drhda0e7682008-07-30 15:27:54 +00003355 }
danielk1977e339d652008-06-28 11:23:00 +00003356
drh7708e972008-11-29 00:56:52 +00003357 if( pLockingStyle == &posixIoMethods ){
3358 unixEnterMutex();
3359 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3360 unixLeaveMutex();
3361 }
danielk1977e339d652008-06-28 11:23:00 +00003362
drhd2cb50b2009-01-09 21:41:17 +00003363#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003364 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003365 /* AFP locking uses the file path so it needs to be included in
3366 ** the afpLockingContext.
3367 */
3368 afpLockingContext *pCtx;
3369 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3370 if( pCtx==0 ){
3371 rc = SQLITE_NOMEM;
3372 }else{
3373 /* NB: zFilename exists and remains valid until the file is closed
3374 ** according to requirement F11141. So we do not need to make a
3375 ** copy of the filename. */
3376 pCtx->dbPath = zFilename;
3377 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003378 unixEnterMutex();
drh7708e972008-11-29 00:56:52 +00003379 rc = findLockInfo(pNew, NULL, &pNew->pOpen);
3380 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003381 }
drh7708e972008-11-29 00:56:52 +00003382 }
3383#endif
danielk1977e339d652008-06-28 11:23:00 +00003384
drh7708e972008-11-29 00:56:52 +00003385 else if( pLockingStyle == &dotlockIoMethods ){
3386 /* Dotfile locking uses the file path so it needs to be included in
3387 ** the dotlockLockingContext
3388 */
3389 char *zLockFile;
3390 int nFilename;
drhea678832008-12-10 19:26:22 +00003391 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003392 zLockFile = (char *)sqlite3_malloc(nFilename);
3393 if( zLockFile==0 ){
3394 rc = SQLITE_NOMEM;
3395 }else{
3396 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003397 }
drh7708e972008-11-29 00:56:52 +00003398 pNew->lockingContext = zLockFile;
3399 }
danielk1977e339d652008-06-28 11:23:00 +00003400
drh6c7d5c52008-11-21 20:32:33 +00003401#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003402 else if( pLockingStyle == &semIoMethods ){
3403 /* Named semaphore locking uses the file path so it needs to be
3404 ** included in the semLockingContext
3405 */
3406 unixEnterMutex();
3407 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3408 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3409 char *zSemName = pNew->pOpen->aSemName;
3410 int n;
3411 sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem",
3412 pNew->pId->zCanonicalName);
3413 for( n=0; zSemName[n]; n++ )
3414 if( zSemName[n]=='/' ) zSemName[n] = '_';
3415 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3416 if( pNew->pOpen->pSem == SEM_FAILED ){
3417 rc = SQLITE_NOMEM;
3418 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003419 }
chw97185482008-11-17 08:05:31 +00003420 }
drh7708e972008-11-29 00:56:52 +00003421 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003422 }
drh7708e972008-11-29 00:56:52 +00003423#endif
aswift5b1a2562008-08-22 00:22:35 +00003424
3425 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003426#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003427 if( rc!=SQLITE_OK ){
3428 unlink(zFilename);
3429 isDelete = 0;
3430 }
3431 pNew->isDelete = isDelete;
3432#endif
danielk1977e339d652008-06-28 11:23:00 +00003433 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003434 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
drhbfe66312006-10-03 17:40:40 +00003435 close(h);
danielk1977e339d652008-06-28 11:23:00 +00003436 }else{
drh7708e972008-11-29 00:56:52 +00003437 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003438 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003439 }
danielk1977e339d652008-06-28 11:23:00 +00003440 return rc;
drh054889e2005-11-30 03:20:31 +00003441}
drh9c06c952005-11-26 00:25:00 +00003442
danielk1977ad94b582007-08-20 06:44:22 +00003443/*
3444** Open a file descriptor to the directory containing file zFilename.
3445** If successful, *pFd is set to the opened file descriptor and
3446** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3447** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3448** value.
3449**
3450** If SQLITE_OK is returned, the caller is responsible for closing
3451** the file descriptor *pFd using close().
3452*/
danielk1977fee2d252007-08-18 10:59:19 +00003453static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003454 int ii;
drh777b17a2007-09-20 10:02:54 +00003455 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003456 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003457
drh153c62c2007-08-24 03:51:33 +00003458 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003459 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003460 if( ii>0 ){
3461 zDirname[ii] = '\0';
3462 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003463 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003464#ifdef FD_CLOEXEC
3465 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3466#endif
3467 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3468 }
3469 }
danielk1977fee2d252007-08-18 10:59:19 +00003470 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00003471 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00003472}
3473
danielk1977b4b47412007-08-17 15:53:36 +00003474/*
danielk197717b90b52008-06-06 11:11:25 +00003475** Create a temporary file name in zBuf. zBuf must be allocated
3476** by the calling process and must be big enough to hold at least
3477** pVfs->mxPathname bytes.
3478*/
3479static int getTempname(int nBuf, char *zBuf){
3480 static const char *azDirs[] = {
3481 0,
aswiftaebf4132008-11-21 00:10:35 +00003482 0,
danielk197717b90b52008-06-06 11:11:25 +00003483 "/var/tmp",
3484 "/usr/tmp",
3485 "/tmp",
3486 ".",
3487 };
3488 static const unsigned char zChars[] =
3489 "abcdefghijklmnopqrstuvwxyz"
3490 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3491 "0123456789";
drh41022642008-11-21 00:24:42 +00003492 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003493 struct stat buf;
3494 const char *zDir = ".";
3495
3496 /* It's odd to simulate an io-error here, but really this is just
3497 ** using the io-error infrastructure to test that SQLite handles this
3498 ** function failing.
3499 */
3500 SimulateIOError( return SQLITE_IOERR );
3501
3502 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003503 if (NULL == azDirs[1]) {
3504 azDirs[1] = getenv("TMPDIR");
3505 }
3506
3507 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003508 if( azDirs[i]==0 ) continue;
3509 if( stat(azDirs[i], &buf) ) continue;
3510 if( !S_ISDIR(buf.st_mode) ) continue;
3511 if( access(azDirs[i], 07) ) continue;
3512 zDir = azDirs[i];
3513 break;
3514 }
3515
3516 /* Check that the output buffer is large enough for the temporary file
3517 ** name. If it is not, return SQLITE_ERROR.
3518 */
danielk197700e13612008-11-17 19:18:54 +00003519 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003520 return SQLITE_ERROR;
3521 }
3522
3523 do{
3524 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003525 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003526 sqlite3_randomness(15, &zBuf[j]);
3527 for(i=0; i<15; i++, j++){
3528 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3529 }
3530 zBuf[j] = 0;
3531 }while( access(zBuf,0)==0 );
3532 return SQLITE_OK;
3533}
3534
drhd2cb50b2009-01-09 21:41:17 +00003535#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003536/*
3537** Routine to transform a unixFile into a proxy-locking unixFile.
3538** Implementation in the proxy-lock division, but used by unixOpen()
3539** if SQLITE_PREFER_PROXY_LOCKING is defined.
3540*/
3541static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003542#endif
drhc66d5b62008-12-03 22:48:32 +00003543
danielk197717b90b52008-06-06 11:11:25 +00003544
3545/*
danielk1977ad94b582007-08-20 06:44:22 +00003546** Open the file zPath.
3547**
danielk1977b4b47412007-08-17 15:53:36 +00003548** Previously, the SQLite OS layer used three functions in place of this
3549** one:
3550**
3551** sqlite3OsOpenReadWrite();
3552** sqlite3OsOpenReadOnly();
3553** sqlite3OsOpenExclusive();
3554**
3555** These calls correspond to the following combinations of flags:
3556**
3557** ReadWrite() -> (READWRITE | CREATE)
3558** ReadOnly() -> (READONLY)
3559** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
3560**
3561** The old OpenExclusive() accepted a boolean argument - "delFlag". If
3562** true, the file was configured to be automatically deleted when the
3563** file handle closed. To achieve the same effect using this new
3564** interface, add the DELETEONCLOSE flag to those specified above for
3565** OpenExclusive().
3566*/
3567static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00003568 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
3569 const char *zPath, /* Pathname of file to be opened */
3570 sqlite3_file *pFile, /* The file descriptor to be filled in */
3571 int flags, /* Input flags to control the opening */
3572 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00003573){
danielk1977fee2d252007-08-18 10:59:19 +00003574 int fd = 0; /* File descriptor returned by open() */
3575 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00003576 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00003577 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00003578 int noLock; /* True to omit locking primitives */
aswiftaebf4132008-11-21 00:10:35 +00003579 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003580
3581 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
3582 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
3583 int isCreate = (flags & SQLITE_OPEN_CREATE);
3584 int isReadonly = (flags & SQLITE_OPEN_READONLY);
3585 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
3586
danielk1977fee2d252007-08-18 10:59:19 +00003587 /* If creating a master or main-file journal, this function will open
3588 ** a file-descriptor on the directory too. The first time unixSync()
3589 ** is called the directory file descriptor will be fsync()ed and close()d.
3590 */
3591 int isOpenDirectory = (isCreate &&
3592 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
3593 );
3594
danielk197717b90b52008-06-06 11:11:25 +00003595 /* If argument zPath is a NULL pointer, this function is required to open
3596 ** a temporary file. Use this buffer to store the file name in.
3597 */
3598 char zTmpname[MAX_PATHNAME+1];
3599 const char *zName = zPath;
3600
danielk1977fee2d252007-08-18 10:59:19 +00003601 /* Check the following statements are true:
3602 **
3603 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
3604 ** (b) if CREATE is set, then READWRITE must also be set, and
3605 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00003606 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00003607 */
danielk1977b4b47412007-08-17 15:53:36 +00003608 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00003609 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00003610 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00003611 assert(isDelete==0 || isCreate);
3612
drh33f4e022007-09-03 15:19:34 +00003613 /* The main DB, main journal, and master journal are never automatically
3614 ** deleted
3615 */
3616 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
3617 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
3618 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00003619
danielk1977fee2d252007-08-18 10:59:19 +00003620 /* Assert that the upper layer has set one of the "file-type" flags. */
3621 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
3622 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3623 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00003624 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00003625 );
3626
danielk1977e339d652008-06-28 11:23:00 +00003627 memset(pFile, 0, sizeof(unixFile));
3628
danielk197717b90b52008-06-06 11:11:25 +00003629 if( !zName ){
danielk197717b90b52008-06-06 11:11:25 +00003630 assert(isDelete && !isOpenDirectory);
3631 rc = getTempname(MAX_PATHNAME+1, zTmpname);
3632 if( rc!=SQLITE_OK ){
3633 return rc;
3634 }
3635 zName = zTmpname;
3636 }
3637
drh734c9862008-11-28 15:37:20 +00003638 if( isReadonly ) openFlags |= O_RDONLY;
3639 if( isReadWrite ) openFlags |= O_RDWR;
3640 if( isCreate ) openFlags |= O_CREAT;
3641 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
3642 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00003643
drh734c9862008-11-28 15:37:20 +00003644 fd = open(zName, openFlags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
3645 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
danielk19772f2d8c72007-08-30 16:13:33 +00003646 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00003647 /* Failed to open the file for read/write access. Try read-only. */
3648 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3649 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00003650 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00003651 }
3652 if( fd<0 ){
3653 return SQLITE_CANTOPEN;
3654 }
3655 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00003656#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003657 zPath = zName;
3658#else
danielk197717b90b52008-06-06 11:11:25 +00003659 unlink(zName);
chw97185482008-11-17 08:05:31 +00003660#endif
danielk1977b4b47412007-08-17 15:53:36 +00003661 }
drh41022642008-11-21 00:24:42 +00003662#if SQLITE_ENABLE_LOCKING_STYLE
3663 else{
drh734c9862008-11-28 15:37:20 +00003664 ((unixFile*)pFile)->openFlags = openFlags;
drh41022642008-11-21 00:24:42 +00003665 }
3666#endif
danielk1977b4b47412007-08-17 15:53:36 +00003667 if( pOutFlags ){
3668 *pOutFlags = flags;
3669 }
3670
3671 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00003672 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00003673 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00003674 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003675 close(fd); /* silently leak if fail, already in error */
danielk1977fee2d252007-08-18 10:59:19 +00003676 return rc;
3677 }
3678 }
danielk1977e339d652008-06-28 11:23:00 +00003679
3680#ifdef FD_CLOEXEC
3681 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3682#endif
3683
drhda0e7682008-07-30 15:27:54 +00003684 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00003685
3686#if SQLITE_PREFER_PROXY_LOCKING
3687 if( zPath!=NULL && !noLock ){
3688 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
3689 int useProxy = 0;
3690
3691 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy,
drh7708e972008-11-29 00:56:52 +00003692 ** 0 means never use proxy, NULL means use proxy for non-local files only
3693 */
aswiftaebf4132008-11-21 00:10:35 +00003694 if( envforce!=NULL ){
3695 useProxy = atoi(envforce)>0;
3696 }else{
3697 struct statfs fsInfo;
3698
3699 if( statfs(zPath, &fsInfo) == -1 ){
3700 ((unixFile*)pFile)->lastErrno = errno;
3701 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
3702 close(fd); /* silently leak if fail, in error */
3703 return SQLITE_IOERR_ACCESS;
3704 }
3705 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
3706 }
3707 if( useProxy ){
3708 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
3709 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00003710 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
aswiftaebf4132008-11-21 00:10:35 +00003711 }
3712 return rc;
3713 }
3714 }
3715#endif
3716
chw97185482008-11-17 08:05:31 +00003717 return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
danielk1977b4b47412007-08-17 15:53:36 +00003718}
3719
3720/*
danielk1977fee2d252007-08-18 10:59:19 +00003721** Delete the file at zPath. If the dirSync argument is true, fsync()
3722** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00003723*/
drh6b9d6dd2008-12-03 19:34:47 +00003724static int unixDelete(
3725 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
3726 const char *zPath, /* Name of file to be deleted */
3727 int dirSync /* If true, fsync() directory after deleting file */
3728){
danielk1977fee2d252007-08-18 10:59:19 +00003729 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00003730 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003731 SimulateIOError(return SQLITE_IOERR_DELETE);
3732 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00003733#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00003734 if( dirSync ){
3735 int fd;
3736 rc = openDirectory(zPath, &fd);
3737 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00003738#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003739 if( fsync(fd)==-1 )
3740#else
3741 if( fsync(fd) )
3742#endif
3743 {
danielk1977fee2d252007-08-18 10:59:19 +00003744 rc = SQLITE_IOERR_DIR_FSYNC;
3745 }
aswiftaebf4132008-11-21 00:10:35 +00003746 if( close(fd)&&!rc ){
3747 rc = SQLITE_IOERR_DIR_CLOSE;
3748 }
danielk1977fee2d252007-08-18 10:59:19 +00003749 }
3750 }
danielk1977d138dd82008-10-15 16:02:48 +00003751#endif
danielk1977fee2d252007-08-18 10:59:19 +00003752 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00003753}
3754
danielk197790949c22007-08-17 16:50:38 +00003755/*
3756** Test the existance of or access permissions of file zPath. The
3757** test performed depends on the value of flags:
3758**
3759** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
3760** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
3761** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
3762**
3763** Otherwise return 0.
3764*/
danielk1977861f7452008-06-05 11:39:11 +00003765static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00003766 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
3767 const char *zPath, /* Path of the file to examine */
3768 int flags, /* What do we want to learn about the zPath file? */
3769 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00003770){
rse25c0d1a2007-09-20 08:38:14 +00003771 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00003772 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00003773 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00003774 switch( flags ){
3775 case SQLITE_ACCESS_EXISTS:
3776 amode = F_OK;
3777 break;
3778 case SQLITE_ACCESS_READWRITE:
3779 amode = W_OK|R_OK;
3780 break;
drh50d3f902007-08-27 21:10:36 +00003781 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00003782 amode = R_OK;
3783 break;
3784
3785 default:
3786 assert(!"Invalid flags argument");
3787 }
danielk1977861f7452008-06-05 11:39:11 +00003788 *pResOut = (access(zPath, amode)==0);
3789 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003790}
3791
danielk1977b4b47412007-08-17 15:53:36 +00003792
3793/*
3794** Turn a relative pathname into a full pathname. The relative path
3795** is stored as a nul-terminated string in the buffer pointed to by
3796** zPath.
3797**
3798** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
3799** (in this case, MAX_PATHNAME bytes). The full-path is written to
3800** this buffer before returning.
3801*/
danielk1977adfb9b02007-09-17 07:02:56 +00003802static int unixFullPathname(
3803 sqlite3_vfs *pVfs, /* Pointer to vfs object */
3804 const char *zPath, /* Possibly relative input path */
3805 int nOut, /* Size of output buffer in bytes */
3806 char *zOut /* Output buffer */
3807){
danielk1977843e65f2007-09-01 16:16:15 +00003808
3809 /* It's odd to simulate an io-error here, but really this is just
3810 ** using the io-error infrastructure to test that SQLite handles this
3811 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00003812 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00003813 */
3814 SimulateIOError( return SQLITE_ERROR );
3815
drh153c62c2007-08-24 03:51:33 +00003816 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00003817 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00003818
drh3c7f2dc2007-12-06 13:26:20 +00003819 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00003820 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00003821 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003822 }else{
3823 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00003824 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00003825 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00003826 }
drhea678832008-12-10 19:26:22 +00003827 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00003828 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003829 }
3830 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003831}
3832
drh0ccebe72005-06-07 22:22:50 +00003833
drh761df872006-12-21 01:29:22 +00003834#ifndef SQLITE_OMIT_LOAD_EXTENSION
3835/*
3836** Interfaces for opening a shared library, finding entry points
3837** within the shared library, and closing the shared library.
3838*/
3839#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00003840static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
3841 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00003842 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
3843}
danielk197795c8a542007-09-01 06:51:27 +00003844
3845/*
3846** SQLite calls this function immediately after a call to unixDlSym() or
3847** unixDlOpen() fails (returns a null pointer). If a more detailed error
3848** message is available, it is written to zBufOut. If no error message
3849** is available, zBufOut is left unmodified and SQLite uses a default
3850** error message.
3851*/
danielk1977397d65f2008-11-19 11:35:39 +00003852static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00003853 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00003854 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00003855 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003856 zErr = dlerror();
3857 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00003858 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00003859 }
drh6c7d5c52008-11-21 20:32:33 +00003860 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003861}
drh1875f7a2008-12-08 18:19:17 +00003862static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
3863 /*
3864 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
3865 ** cast into a pointer to a function. And yet the library dlsym() routine
3866 ** returns a void* which is really a pointer to a function. So how do we
3867 ** use dlsym() with -pedantic-errors?
3868 **
3869 ** Variable x below is defined to be a pointer to a function taking
3870 ** parameters void* and const char* and returning a pointer to a function.
3871 ** We initialize x by assigning it a pointer to the dlsym() function.
3872 ** (That assignment requires a cast.) Then we call the function that
3873 ** x points to.
3874 **
3875 ** This work-around is unlikely to work correctly on any system where
3876 ** you really cannot cast a function pointer into void*. But then, on the
3877 ** other hand, dlsym() will not work on such a system either, so we have
3878 ** not really lost anything.
3879 */
3880 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00003881 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00003882 x = (void(*(*)(void*,const char*))(void))dlsym;
3883 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00003884}
danielk1977397d65f2008-11-19 11:35:39 +00003885static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
3886 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003887 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00003888}
danielk1977b4b47412007-08-17 15:53:36 +00003889#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
3890 #define unixDlOpen 0
3891 #define unixDlError 0
3892 #define unixDlSym 0
3893 #define unixDlClose 0
3894#endif
3895
3896/*
danielk197790949c22007-08-17 16:50:38 +00003897** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00003898*/
danielk1977397d65f2008-11-19 11:35:39 +00003899static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
3900 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00003901 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00003902
drhbbd42a62004-05-22 17:41:58 +00003903 /* We have to initialize zBuf to prevent valgrind from reporting
3904 ** errors. The reports issued by valgrind are incorrect - we would
3905 ** prefer that the randomness be increased by making use of the
3906 ** uninitialized space in zBuf - but valgrind errors tend to worry
3907 ** some users. Rather than argue, it seems easier just to initialize
3908 ** the whole array and silence valgrind, even if that means less randomness
3909 ** in the random seed.
3910 **
3911 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00003912 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00003913 ** tests repeatable.
3914 */
danielk1977b4b47412007-08-17 15:53:36 +00003915 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00003916#if !defined(SQLITE_TEST)
3917 {
drh842b8642005-01-21 17:53:17 +00003918 int pid, fd;
3919 fd = open("/dev/urandom", O_RDONLY);
3920 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00003921 time_t t;
3922 time(&t);
danielk197790949c22007-08-17 16:50:38 +00003923 memcpy(zBuf, &t, sizeof(t));
3924 pid = getpid();
3925 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00003926 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00003927 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00003928 }else{
drh72cbd072008-10-14 17:58:38 +00003929 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00003930 close(fd);
3931 }
drhbbd42a62004-05-22 17:41:58 +00003932 }
3933#endif
drh72cbd072008-10-14 17:58:38 +00003934 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00003935}
3936
danielk1977b4b47412007-08-17 15:53:36 +00003937
drhbbd42a62004-05-22 17:41:58 +00003938/*
3939** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00003940** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00003941** The return value is the number of microseconds of sleep actually
3942** requested from the underlying operating system, a number which
3943** might be greater than or equal to the argument, but not less
3944** than the argument.
drhbbd42a62004-05-22 17:41:58 +00003945*/
danielk1977397d65f2008-11-19 11:35:39 +00003946static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00003947#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003948 struct timespec sp;
3949
3950 sp.tv_sec = microseconds / 1000000;
3951 sp.tv_nsec = (microseconds % 1000000) * 1000;
3952 nanosleep(&sp, NULL);
danielk1977397d65f2008-11-19 11:35:39 +00003953 return microseconds;
3954#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00003955 usleep(microseconds);
3956 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00003957#else
danielk1977b4b47412007-08-17 15:53:36 +00003958 int seconds = (microseconds+999999)/1000000;
3959 sleep(seconds);
drh4a50aac2007-08-23 02:47:53 +00003960 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00003961#endif
danielk1977397d65f2008-11-19 11:35:39 +00003962 UNUSED_PARAMETER(NotUsed);
drh88f474a2006-01-02 20:00:12 +00003963}
3964
3965/*
drh6b9d6dd2008-12-03 19:34:47 +00003966** The following variable, if set to a non-zero value, is interpreted as
3967** the number of seconds since 1970 and is used to set the result of
3968** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00003969*/
3970#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00003971int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00003972#endif
3973
3974/*
3975** Find the current time (in Universal Coordinated Time). Write the
3976** current time and date as a Julian Day number into *prNow and
3977** return 0. Return 1 if the time and date cannot be found.
3978*/
danielk1977397d65f2008-11-19 11:35:39 +00003979static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh6c7d5c52008-11-21 20:32:33 +00003980#if defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00003981 time_t t;
3982 time(&t);
3983 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00003984#elif OS_VXWORKS
3985 struct timespec sNow;
3986 clock_gettime(CLOCK_REALTIME, &sNow);
3987 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00003988#else
3989 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00003990 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00003991 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
3992#endif
danielk1977397d65f2008-11-19 11:35:39 +00003993
drhbbd42a62004-05-22 17:41:58 +00003994#ifdef SQLITE_TEST
3995 if( sqlite3_current_time ){
3996 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
3997 }
3998#endif
danielk1977397d65f2008-11-19 11:35:39 +00003999 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004000 return 0;
4001}
danielk1977b4b47412007-08-17 15:53:36 +00004002
drh6b9d6dd2008-12-03 19:34:47 +00004003/*
4004** We added the xGetLastError() method with the intention of providing
4005** better low-level error messages when operating-system problems come up
4006** during SQLite operation. But so far, none of that has been implemented
4007** in the core. So this routine is never called. For now, it is merely
4008** a place-holder.
4009*/
danielk1977397d65f2008-11-19 11:35:39 +00004010static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4011 UNUSED_PARAMETER(NotUsed);
4012 UNUSED_PARAMETER(NotUsed2);
4013 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004014 return 0;
4015}
4016
drh153c62c2007-08-24 03:51:33 +00004017/*
drh734c9862008-11-28 15:37:20 +00004018************************ End of sqlite3_vfs methods ***************************
4019******************************************************************************/
4020
drh715ff302008-12-03 22:32:44 +00004021/******************************************************************************
4022************************** Begin Proxy Locking ********************************
4023**
4024** Proxy locking is a "uber-locking-method" in this sense: It uses the
4025** other locking methods on secondary lock files. Proxy locking is a
4026** meta-layer over top of the primitive locking implemented above. For
4027** this reason, the division that implements of proxy locking is deferred
4028** until late in the file (here) after all of the other I/O methods have
4029** been defined - so that the primitive locking methods are available
4030** as services to help with the implementation of proxy locking.
4031**
4032****
4033**
4034** The default locking schemes in SQLite use byte-range locks on the
4035** database file to coordinate safe, concurrent access by multiple readers
4036** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4037** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4038** as POSIX read & write locks over fixed set of locations (via fsctl),
4039** on AFP and SMB only exclusive byte-range locks are available via fsctl
4040** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4041** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4042** address in the shared range is taken for a SHARED lock, the entire
4043** shared range is taken for an EXCLUSIVE lock):
4044**
4045** PENDING_BYTE 0x40000000
4046** RESERVED_BYTE 0x40000001
4047** SHARED_RANGE 0x40000002 -> 0x40000200
4048**
4049** This works well on the local file system, but shows a nearly 100x
4050** slowdown in read performance on AFP because the AFP client disables
4051** the read cache when byte-range locks are present. Enabling the read
4052** cache exposes a cache coherency problem that is present on all OS X
4053** supported network file systems. NFS and AFP both observe the
4054** close-to-open semantics for ensuring cache coherency
4055** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4056** address the requirements for concurrent database access by multiple
4057** readers and writers
4058** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4059**
4060** To address the performance and cache coherency issues, proxy file locking
4061** changes the way database access is controlled by limiting access to a
4062** single host at a time and moving file locks off of the database file
4063** and onto a proxy file on the local file system.
4064**
4065**
4066** Using proxy locks
4067** -----------------
4068**
4069** C APIs
4070**
4071** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4072** <proxy_path> | ":auto:");
4073** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4074**
4075**
4076** SQL pragmas
4077**
4078** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4079** PRAGMA [database.]lock_proxy_file
4080**
4081** Specifying ":auto:" means that if there is a conch file with a matching
4082** host ID in it, the proxy path in the conch file will be used, otherwise
4083** a proxy path based on the user's temp dir
4084** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4085** actual proxy file name is generated from the name and path of the
4086** database file. For example:
4087**
4088** For database path "/Users/me/foo.db"
4089** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4090**
4091** Once a lock proxy is configured for a database connection, it can not
4092** be removed, however it may be switched to a different proxy path via
4093** the above APIs (assuming the conch file is not being held by another
4094** connection or process).
4095**
4096**
4097** How proxy locking works
4098** -----------------------
4099**
4100** Proxy file locking relies primarily on two new supporting files:
4101**
4102** * conch file to limit access to the database file to a single host
4103** at a time
4104**
4105** * proxy file to act as a proxy for the advisory locks normally
4106** taken on the database
4107**
4108** The conch file - to use a proxy file, sqlite must first "hold the conch"
4109** by taking an sqlite-style shared lock on the conch file, reading the
4110** contents and comparing the host's unique host ID (see below) and lock
4111** proxy path against the values stored in the conch. The conch file is
4112** stored in the same directory as the database file and the file name
4113** is patterned after the database file name as ".<databasename>-conch".
4114** If the conch file does not exist, or it's contents do not match the
4115** host ID and/or proxy path, then the lock is escalated to an exclusive
4116** lock and the conch file contents is updated with the host ID and proxy
4117** path and the lock is downgraded to a shared lock again. If the conch
4118** is held by another process (with a shared lock), the exclusive lock
4119** will fail and SQLITE_BUSY is returned.
4120**
4121** The proxy file - a single-byte file used for all advisory file locks
4122** normally taken on the database file. This allows for safe sharing
4123** of the database file for multiple readers and writers on the same
4124** host (the conch ensures that they all use the same local lock file).
4125**
4126** There is a third file - the host ID file - used as a persistent record
4127** of a unique identifier for the host, a 128-byte unique host id file
4128** in the path defined by the HOSTIDPATH macro (default value is
4129** /Library/Caches/.com.apple.sqliteConchHostId).
4130**
4131** Requesting the lock proxy does not immediately take the conch, it is
4132** only taken when the first request to lock database file is made.
4133** This matches the semantics of the traditional locking behavior, where
4134** opening a connection to a database file does not take a lock on it.
4135** The shared lock and an open file descriptor are maintained until
4136** the connection to the database is closed.
4137**
4138** The proxy file and the lock file are never deleted so they only need
4139** to be created the first time they are used.
4140**
4141** Configuration options
4142** ---------------------
4143**
4144** SQLITE_PREFER_PROXY_LOCKING
4145**
4146** Database files accessed on non-local file systems are
4147** automatically configured for proxy locking, lock files are
4148** named automatically using the same logic as
4149** PRAGMA lock_proxy_file=":auto:"
4150**
4151** SQLITE_PROXY_DEBUG
4152**
4153** Enables the logging of error messages during host id file
4154** retrieval and creation
4155**
4156** HOSTIDPATH
4157**
4158** Overrides the default host ID file path location
4159**
4160** LOCKPROXYDIR
4161**
4162** Overrides the default directory used for lock proxy files that
4163** are named automatically via the ":auto:" setting
4164**
4165** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4166**
4167** Permissions to use when creating a directory for storing the
4168** lock proxy files, only used when LOCKPROXYDIR is not set.
4169**
4170**
4171** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4172** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4173** force proxy locking to be used for every database file opened, and 0
4174** will force automatic proxy locking to be disabled for all database
4175** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4176** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4177*/
4178
4179/*
4180** Proxy locking is only available on MacOSX
4181*/
drhd2cb50b2009-01-09 21:41:17 +00004182#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004183
4184#ifdef SQLITE_TEST
4185/* simulate multiple hosts by creating unique hostid file paths */
4186int sqlite3_hostid_num = 0;
4187#endif
4188
4189/*
4190** The proxyLockingContext has the path and file structures for the remote
4191** and local proxy files in it
4192*/
4193typedef struct proxyLockingContext proxyLockingContext;
4194struct proxyLockingContext {
4195 unixFile *conchFile; /* Open conch file */
4196 char *conchFilePath; /* Name of the conch file */
4197 unixFile *lockProxy; /* Open proxy lock file */
4198 char *lockProxyPath; /* Name of the proxy lock file */
4199 char *dbPath; /* Name of the open file */
4200 int conchHeld; /* True if the conch is currently held */
4201 void *oldLockingContext; /* Original lockingcontext to restore on close */
4202 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4203};
4204
4205/* HOSTIDLEN and CONCHLEN both include space for the string
4206** terminating nul
4207*/
4208#define HOSTIDLEN 128
4209#define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
4210#ifndef HOSTIDPATH
4211# define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
4212#endif
4213
4214/* basically a copy of unixRandomness with different
4215** test behavior built in */
4216static int proxyGenerateHostID(char *pHostID){
4217 int pid, fd, len;
4218 unsigned char *key = (unsigned char *)pHostID;
4219
4220 memset(key, 0, HOSTIDLEN);
4221 len = 0;
4222 fd = open("/dev/urandom", O_RDONLY);
4223 if( fd>=0 ){
4224 len = read(fd, key, HOSTIDLEN);
4225 close(fd); /* silently leak the fd if it fails */
4226 }
4227 if( len < HOSTIDLEN ){
4228 time_t t;
4229 time(&t);
4230 memcpy(key, &t, sizeof(t));
4231 pid = getpid();
4232 memcpy(&key[sizeof(t)], &pid, sizeof(pid));
4233 }
4234
4235#ifdef MAKE_PRETTY_HOSTID
4236 {
4237 int i;
4238 /* filter the bytes into printable ascii characters and NUL terminate */
4239 key[(HOSTIDLEN-1)] = 0x00;
4240 for( i=0; i<(HOSTIDLEN-1); i++ ){
4241 unsigned char pa = key[i]&0x7F;
4242 if( pa<0x20 ){
4243 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
4244 }else if( pa==0x7F ){
4245 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
4246 }
4247 }
4248 }
4249#endif
4250 return SQLITE_OK;
4251}
4252
4253/* writes the host id path to path, path should be an pre-allocated buffer
4254** with enough space for a path
4255*/
4256static void proxyGetHostIDPath(char *path, size_t len){
4257 strlcpy(path, HOSTIDPATH, len);
4258#ifdef SQLITE_TEST
4259 if( sqlite3_hostid_num>0 ){
4260 char suffix[2] = "1";
4261 suffix[0] = suffix[0] + sqlite3_hostid_num;
4262 strlcat(path, suffix, len);
4263 }
4264#endif
4265 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
4266}
4267
4268/* get the host ID from a sqlite hostid file stored in the
4269** user-specific tmp directory, create the ID if it's not there already
4270*/
4271static int proxyGetHostID(char *pHostID, int *pError){
4272 int fd;
4273 char path[MAXPATHLEN];
4274 size_t len;
4275 int rc=SQLITE_OK;
4276
4277 proxyGetHostIDPath(path, MAXPATHLEN);
4278 /* try to create the host ID file, if it already exists read the contents */
4279 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
4280 if( fd<0 ){
4281 int err=errno;
4282
4283 if( err!=EEXIST ){
4284#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4285 fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
4286 path, strerror(err));
4287#endif
4288 return SQLITE_PERM;
4289 }
4290 /* couldn't create the file, read it instead */
4291 fd = open(path, O_RDONLY|O_EXCL);
4292 if( fd<0 ){
4293#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4294 int err = errno;
4295 fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
4296 path, strerror(err));
4297#endif
4298 return SQLITE_PERM;
4299 }
4300 len = pread(fd, pHostID, HOSTIDLEN, 0);
4301 if( len<0 ){
4302 *pError = errno;
4303 rc = SQLITE_IOERR_READ;
4304 }else if( len<HOSTIDLEN ){
4305 *pError = 0;
4306 rc = SQLITE_IOERR_SHORT_READ;
4307 }
4308 close(fd); /* silently leak the fd if it fails */
4309 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
4310 return rc;
4311 }else{
4312 /* we're creating the host ID file (use a random string of bytes) */
4313 proxyGenerateHostID(pHostID);
4314 len = pwrite(fd, pHostID, HOSTIDLEN, 0);
4315 if( len<0 ){
4316 *pError = errno;
4317 rc = SQLITE_IOERR_WRITE;
4318 }else if( len<HOSTIDLEN ){
4319 *pError = 0;
4320 rc = SQLITE_IOERR_WRITE;
4321 }
4322 close(fd); /* silently leak the fd if it fails */
4323 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
4324 return rc;
4325 }
4326}
4327
4328static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4329 int len;
4330 int dbLen;
4331 int i;
4332
4333#ifdef LOCKPROXYDIR
4334 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4335#else
4336# ifdef _CS_DARWIN_USER_TEMP_DIR
4337 {
4338 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
4339 len = strlcat(lPath, "sqliteplocks", maxLen);
4340 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4341 /* if mkdir fails, handle as lock file creation failure */
4342 int err = errno;
4343# ifdef SQLITE_DEBUG
4344 if( err!=EEXIST ){
4345 fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
4346 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
4347 }
4348# endif
4349 }else{
4350 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
4351 }
4352
4353 }
4354# else
4355 len = strlcpy(lPath, "/tmp/", maxLen);
4356# endif
4357#endif
4358
4359 if( lPath[len-1]!='/' ){
4360 len = strlcat(lPath, "/", maxLen);
4361 }
4362
4363 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004364 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004365 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4366 char c = dbPath[i];
4367 lPath[i+len] = (c=='/')?'_':c;
4368 }
4369 lPath[i+len]='\0';
4370 strlcat(lPath, ":auto:", maxLen);
4371 return SQLITE_OK;
4372}
4373
4374/*
4375** Create a new VFS file descriptor (stored in memory obtained from
4376** sqlite3_malloc) and open the file named "path" in the file descriptor.
4377**
4378** The caller is responsible not only for closing the file descriptor
4379** but also for freeing the memory associated with the file descriptor.
4380*/
4381static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
4382 int fd;
4383 int dirfd = -1;
4384 unixFile *pNew;
4385 int rc = SQLITE_OK;
4386 sqlite3_vfs dummyVfs;
4387
4388 fd = open(path, O_RDWR | O_CREAT, SQLITE_DEFAULT_FILE_PERMISSIONS);
4389 if( fd<0 ){
4390 return SQLITE_CANTOPEN;
4391 }
4392
4393 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
4394 if( pNew==NULL ){
4395 rc = SQLITE_NOMEM;
4396 goto end_create_proxy;
4397 }
4398 memset(pNew, 0, sizeof(unixFile));
4399
drh1875f7a2008-12-08 18:19:17 +00004400 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh715ff302008-12-03 22:32:44 +00004401 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
4402 if( rc==SQLITE_OK ){
4403 *ppFile = pNew;
4404 return SQLITE_OK;
4405 }
4406end_create_proxy:
4407 close(fd); /* silently leak fd if error, we're already in error */
4408 sqlite3_free(pNew);
4409 return rc;
4410}
4411
4412/* takes the conch by taking a shared lock and read the contents conch, if
4413** lockPath is non-NULL, the host ID and lock file path must match. A NULL
4414** lockPath means that the lockPath in the conch file will be used if the
4415** host IDs match, or a new lock path will be generated automatically
4416** and written to the conch file.
4417*/
4418static int proxyTakeConch(unixFile *pFile){
4419 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4420
4421 if( pCtx->conchHeld>0 ){
4422 return SQLITE_OK;
4423 }else{
4424 unixFile *conchFile = pCtx->conchFile;
4425 char testValue[CONCHLEN];
4426 char conchValue[CONCHLEN];
4427 char lockPath[MAXPATHLEN];
4428 char *tLockPath = NULL;
4429 int rc = SQLITE_OK;
4430 int readRc = SQLITE_OK;
4431 int syncPerms = 0;
4432
4433 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
4434 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
4435
4436 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
4437 if( rc==SQLITE_OK ){
4438 int pError = 0;
drh1875f7a2008-12-08 18:19:17 +00004439 memset(testValue, 0, CONCHLEN); /* conch is fixed size */
drh715ff302008-12-03 22:32:44 +00004440 rc = proxyGetHostID(testValue, &pError);
4441 if( (rc&0xff)==SQLITE_IOERR ){
4442 pFile->lastErrno = pError;
4443 }
4444 if( pCtx->lockProxyPath ){
4445 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
4446 }
4447 }
4448 if( rc!=SQLITE_OK ){
4449 goto end_takeconch;
4450 }
4451
4452 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
4453 if( readRc!=SQLITE_IOERR_SHORT_READ ){
4454 if( readRc!=SQLITE_OK ){
4455 if( (rc&0xff)==SQLITE_IOERR ){
4456 pFile->lastErrno = conchFile->lastErrno;
4457 }
4458 rc = readRc;
4459 goto end_takeconch;
4460 }
4461 /* if the conch has data compare the contents */
4462 if( !pCtx->lockProxyPath ){
4463 /* for auto-named local lock file, just check the host ID and we'll
4464 ** use the local lock file path that's already in there */
4465 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
4466 tLockPath = (char *)&conchValue[HOSTIDLEN];
4467 goto end_takeconch;
4468 }
4469 }else{
4470 /* we've got the conch if conchValue matches our path and host ID */
4471 if( !memcmp(testValue, conchValue, CONCHLEN) ){
4472 goto end_takeconch;
4473 }
4474 }
4475 }else{
4476 /* a short read means we're "creating" the conch (even though it could
4477 ** have been user-intervention), if we acquire the exclusive lock,
4478 ** we'll try to match the current on-disk permissions of the database
4479 */
4480 syncPerms = 1;
4481 }
4482
4483 /* either conch was emtpy or didn't match */
4484 if( !pCtx->lockProxyPath ){
4485 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
4486 tLockPath = lockPath;
4487 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
4488 }
4489
4490 /* update conch with host and path (this will fail if other process
4491 ** has a shared lock already) */
4492 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
4493 if( rc==SQLITE_OK ){
4494 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
4495 if( rc==SQLITE_OK && syncPerms ){
4496 struct stat buf;
4497 int err = fstat(pFile->h, &buf);
4498 if( err==0 ){
4499 /* try to match the database file permissions, ignore failure */
4500#ifndef SQLITE_PROXY_DEBUG
4501 fchmod(conchFile->h, buf.st_mode);
4502#else
4503 if( fchmod(conchFile->h, buf.st_mode)!=0 ){
4504 int code = errno;
4505 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
4506 buf.st_mode, code, strerror(code));
4507 } else {
4508 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
4509 }
4510 }else{
4511 int code = errno;
4512 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
4513 err, code, strerror(code));
4514#endif
4515 }
4516 }
4517 }
4518 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
4519
4520end_takeconch:
4521 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
4522 if( rc==SQLITE_OK && pFile->openFlags ){
4523 if( pFile->h>=0 ){
4524#ifdef STRICT_CLOSE_ERROR
4525 if( close(pFile->h) ){
4526 pFile->lastErrno = errno;
4527 return SQLITE_IOERR_CLOSE;
4528 }
4529#else
4530 close(pFile->h); /* silently leak fd if fail */
4531#endif
4532 }
4533 pFile->h = -1;
4534 int fd = open(pCtx->dbPath, pFile->openFlags,
4535 SQLITE_DEFAULT_FILE_PERMISSIONS);
4536 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
4537 if( fd>=0 ){
4538 pFile->h = fd;
4539 }else{
drh1875f7a2008-12-08 18:19:17 +00004540 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
4541 during locking */
drh715ff302008-12-03 22:32:44 +00004542 }
4543 }
4544 if( rc==SQLITE_OK && !pCtx->lockProxy ){
4545 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
drh1875f7a2008-12-08 18:19:17 +00004546 /* ACS: Need to make a copy of path sometimes */
drh715ff302008-12-03 22:32:44 +00004547 rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
4548 }
4549 if( rc==SQLITE_OK ){
4550 pCtx->conchHeld = 1;
4551
4552 if( tLockPath ){
4553 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
4554 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
4555 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
4556 pCtx->lockProxyPath;
4557 }
4558 }
4559 } else {
4560 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4561 }
4562 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
4563 return rc;
4564 }
4565}
4566
4567/*
4568** If pFile holds a lock on a conch file, then release that lock.
4569*/
4570static int proxyReleaseConch(unixFile *pFile){
4571 int rc; /* Subroutine return code */
4572 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
4573 unixFile *conchFile; /* Name of the conch file */
4574
4575 pCtx = (proxyLockingContext *)pFile->lockingContext;
4576 conchFile = pCtx->conchFile;
4577 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
4578 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
4579 getpid());
4580 pCtx->conchHeld = 0;
4581 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4582 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
4583 (rc==SQLITE_OK ? "ok" : "failed"));
4584 return rc;
4585}
4586
4587/*
4588** Given the name of a database file, compute the name of its conch file.
4589** Store the conch filename in memory obtained from sqlite3_malloc().
4590** Make *pConchPath point to the new name. Return SQLITE_OK on success
4591** or SQLITE_NOMEM if unable to obtain memory.
4592**
4593** The caller is responsible for ensuring that the allocated memory
4594** space is eventually freed.
4595**
4596** *pConchPath is set to NULL if a memory allocation error occurs.
4597*/
4598static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
4599 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00004600 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00004601 char *conchPath; /* buffer in which to construct conch name */
4602
4603 /* Allocate space for the conch filename and initialize the name to
4604 ** the name of the original database file. */
4605 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
4606 if( conchPath==0 ){
4607 return SQLITE_NOMEM;
4608 }
4609 memcpy(conchPath, dbPath, len+1);
4610
4611 /* now insert a "." before the last / character */
4612 for( i=(len-1); i>=0; i-- ){
4613 if( conchPath[i]=='/' ){
4614 i++;
4615 break;
4616 }
4617 }
4618 conchPath[i]='.';
4619 while ( i<len ){
4620 conchPath[i+1]=dbPath[i];
4621 i++;
4622 }
4623
4624 /* append the "-conch" suffix to the file */
4625 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00004626 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00004627
4628 return SQLITE_OK;
4629}
4630
4631
4632/* Takes a fully configured proxy locking-style unix file and switches
4633** the local lock file path
4634*/
4635static int switchLockProxyPath(unixFile *pFile, const char *path) {
4636 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4637 char *oldPath = pCtx->lockProxyPath;
4638 int rc = SQLITE_OK;
4639
4640 if( pFile->locktype!=NO_LOCK ){
4641 return SQLITE_BUSY;
4642 }
4643
4644 /* nothing to do if the path is NULL, :auto: or matches the existing path */
4645 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
4646 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
4647 return SQLITE_OK;
4648 }else{
4649 unixFile *lockProxy = pCtx->lockProxy;
4650 pCtx->lockProxy=NULL;
4651 pCtx->conchHeld = 0;
4652 if( lockProxy!=NULL ){
4653 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
4654 if( rc ) return rc;
4655 sqlite3_free(lockProxy);
4656 }
4657 sqlite3_free(oldPath);
4658 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
4659 }
4660
4661 return rc;
4662}
4663
4664/*
4665** pFile is a file that has been opened by a prior xOpen call. dbPath
4666** is a string buffer at least MAXPATHLEN+1 characters in size.
4667**
4668** This routine find the filename associated with pFile and writes it
4669** int dbPath.
4670*/
4671static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00004672#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00004673 if( pFile->pMethod == &afpIoMethods ){
4674 /* afp style keeps a reference to the db path in the filePath field
4675 ** of the struct */
drhea678832008-12-10 19:26:22 +00004676 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh715ff302008-12-03 22:32:44 +00004677 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
4678 }else
4679#endif
4680 if( pFile->pMethod == &dotlockIoMethods ){
4681 /* dot lock style uses the locking context to store the dot lock
4682 ** file path */
4683 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
4684 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
4685 }else{
4686 /* all other styles use the locking context to store the db file path */
4687 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
4688 strcpy(dbPath, (char *)pFile->lockingContext);
4689 }
4690 return SQLITE_OK;
4691}
4692
4693/*
4694** Takes an already filled in unix file and alters it so all file locking
4695** will be performed on the local proxy lock file. The following fields
4696** are preserved in the locking context so that they can be restored and
4697** the unix structure properly cleaned up at close time:
4698** ->lockingContext
4699** ->pMethod
4700*/
4701static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
4702 proxyLockingContext *pCtx;
4703 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
4704 char *lockPath=NULL;
4705 int rc = SQLITE_OK;
4706
4707 if( pFile->locktype!=NO_LOCK ){
4708 return SQLITE_BUSY;
4709 }
4710 proxyGetDbPathForUnixFile(pFile, dbPath);
4711 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
4712 lockPath=NULL;
4713 }else{
4714 lockPath=(char *)path;
4715 }
4716
4717 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
4718 (lockPath ? lockPath : ":auto:"), getpid());
4719
4720 pCtx = sqlite3_malloc( sizeof(*pCtx) );
4721 if( pCtx==0 ){
4722 return SQLITE_NOMEM;
4723 }
4724 memset(pCtx, 0, sizeof(*pCtx));
4725
4726 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
4727 if( rc==SQLITE_OK ){
4728 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
4729 }
4730 if( rc==SQLITE_OK && lockPath ){
4731 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
4732 }
4733
4734 if( rc==SQLITE_OK ){
4735 /* all memory is allocated, proxys are created and assigned,
4736 ** switch the locking context and pMethod then return.
4737 */
4738 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
4739 pCtx->oldLockingContext = pFile->lockingContext;
4740 pFile->lockingContext = pCtx;
4741 pCtx->pOldMethod = pFile->pMethod;
4742 pFile->pMethod = &proxyIoMethods;
4743 }else{
4744 if( pCtx->conchFile ){
4745 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
4746 if( rc ) return rc;
4747 sqlite3_free(pCtx->conchFile);
4748 }
4749 sqlite3_free(pCtx->conchFilePath);
4750 sqlite3_free(pCtx);
4751 }
4752 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
4753 (rc==SQLITE_OK ? "ok" : "failed"));
4754 return rc;
4755}
4756
4757
4758/*
4759** This routine handles sqlite3_file_control() calls that are specific
4760** to proxy locking.
4761*/
4762static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
4763 switch( op ){
4764 case SQLITE_GET_LOCKPROXYFILE: {
4765 unixFile *pFile = (unixFile*)id;
4766 if( pFile->pMethod == &proxyIoMethods ){
4767 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4768 proxyTakeConch(pFile);
4769 if( pCtx->lockProxyPath ){
4770 *(const char **)pArg = pCtx->lockProxyPath;
4771 }else{
4772 *(const char **)pArg = ":auto: (not held)";
4773 }
4774 } else {
4775 *(const char **)pArg = NULL;
4776 }
4777 return SQLITE_OK;
4778 }
4779 case SQLITE_SET_LOCKPROXYFILE: {
4780 unixFile *pFile = (unixFile*)id;
4781 int rc = SQLITE_OK;
4782 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
4783 if( pArg==NULL || (const char *)pArg==0 ){
4784 if( isProxyStyle ){
4785 /* turn off proxy locking - not supported */
4786 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
4787 }else{
4788 /* turn off proxy locking - already off - NOOP */
4789 rc = SQLITE_OK;
4790 }
4791 }else{
4792 const char *proxyPath = (const char *)pArg;
4793 if( isProxyStyle ){
4794 proxyLockingContext *pCtx =
4795 (proxyLockingContext*)pFile->lockingContext;
4796 if( !strcmp(pArg, ":auto:")
4797 || (pCtx->lockProxyPath &&
4798 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
4799 ){
4800 rc = SQLITE_OK;
4801 }else{
4802 rc = switchLockProxyPath(pFile, proxyPath);
4803 }
4804 }else{
4805 /* turn on proxy file locking */
4806 rc = proxyTransformUnixFile(pFile, proxyPath);
4807 }
4808 }
4809 return rc;
4810 }
4811 default: {
4812 assert( 0 ); /* The call assures that only valid opcodes are sent */
4813 }
4814 }
4815 /*NOTREACHED*/
4816 return SQLITE_ERROR;
4817}
4818
4819/*
4820** Within this division (the proxying locking implementation) the procedures
4821** above this point are all utilities. The lock-related methods of the
4822** proxy-locking sqlite3_io_method object follow.
4823*/
4824
4825
4826/*
4827** This routine checks if there is a RESERVED lock held on the specified
4828** file by this or any other process. If such a lock is held, set *pResOut
4829** to a non-zero value otherwise *pResOut is set to zero. The return value
4830** is set to SQLITE_OK unless an I/O error occurs during lock checking.
4831*/
4832static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
4833 unixFile *pFile = (unixFile*)id;
4834 int rc = proxyTakeConch(pFile);
4835 if( rc==SQLITE_OK ){
4836 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4837 unixFile *proxy = pCtx->lockProxy;
4838 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
4839 }
4840 return rc;
4841}
4842
4843/*
4844** Lock the file with the lock specified by parameter locktype - one
4845** of the following:
4846**
4847** (1) SHARED_LOCK
4848** (2) RESERVED_LOCK
4849** (3) PENDING_LOCK
4850** (4) EXCLUSIVE_LOCK
4851**
4852** Sometimes when requesting one lock state, additional lock states
4853** are inserted in between. The locking might fail on one of the later
4854** transitions leaving the lock state different from what it started but
4855** still short of its goal. The following chart shows the allowed
4856** transitions and the inserted intermediate states:
4857**
4858** UNLOCKED -> SHARED
4859** SHARED -> RESERVED
4860** SHARED -> (PENDING) -> EXCLUSIVE
4861** RESERVED -> (PENDING) -> EXCLUSIVE
4862** PENDING -> EXCLUSIVE
4863**
4864** This routine will only increase a lock. Use the sqlite3OsUnlock()
4865** routine to lower a locking level.
4866*/
4867static int proxyLock(sqlite3_file *id, int locktype) {
4868 unixFile *pFile = (unixFile*)id;
4869 int rc = proxyTakeConch(pFile);
4870 if( rc==SQLITE_OK ){
4871 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4872 unixFile *proxy = pCtx->lockProxy;
4873 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
4874 pFile->locktype = proxy->locktype;
4875 }
4876 return rc;
4877}
4878
4879
4880/*
4881** Lower the locking level on file descriptor pFile to locktype. locktype
4882** must be either NO_LOCK or SHARED_LOCK.
4883**
4884** If the locking level of the file descriptor is already at or below
4885** the requested locking level, this routine is a no-op.
4886*/
4887static int proxyUnlock(sqlite3_file *id, int locktype) {
4888 unixFile *pFile = (unixFile*)id;
4889 int rc = proxyTakeConch(pFile);
4890 if( rc==SQLITE_OK ){
4891 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4892 unixFile *proxy = pCtx->lockProxy;
4893 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
4894 pFile->locktype = proxy->locktype;
4895 }
4896 return rc;
4897}
4898
4899/*
4900** Close a file that uses proxy locks.
4901*/
4902static int proxyClose(sqlite3_file *id) {
4903 if( id ){
4904 unixFile *pFile = (unixFile*)id;
4905 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4906 unixFile *lockProxy = pCtx->lockProxy;
4907 unixFile *conchFile = pCtx->conchFile;
4908 int rc = SQLITE_OK;
4909
4910 if( lockProxy ){
4911 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
4912 if( rc ) return rc;
4913 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
4914 if( rc ) return rc;
4915 sqlite3_free(lockProxy);
4916 pCtx->lockProxy = 0;
4917 }
4918 if( conchFile ){
4919 if( pCtx->conchHeld ){
4920 rc = proxyReleaseConch(pFile);
4921 if( rc ) return rc;
4922 }
4923 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
4924 if( rc ) return rc;
4925 sqlite3_free(conchFile);
4926 }
4927 sqlite3_free(pCtx->lockProxyPath);
4928 sqlite3_free(pCtx->conchFilePath);
4929 sqlite3_free(pCtx->dbPath);
4930 /* restore the original locking context and pMethod then close it */
4931 pFile->lockingContext = pCtx->oldLockingContext;
4932 pFile->pMethod = pCtx->pOldMethod;
4933 sqlite3_free(pCtx);
4934 return pFile->pMethod->xClose(id);
4935 }
4936 return SQLITE_OK;
4937}
4938
4939
4940
drhd2cb50b2009-01-09 21:41:17 +00004941#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00004942/*
4943** The proxy locking style is intended for use with AFP filesystems.
4944** And since AFP is only supported on MacOSX, the proxy locking is also
4945** restricted to MacOSX.
4946**
4947**
4948******************* End of the proxy lock implementation **********************
4949******************************************************************************/
4950
drh734c9862008-11-28 15:37:20 +00004951/*
danielk1977e339d652008-06-28 11:23:00 +00004952** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00004953**
4954** This routine registers all VFS implementations for unix-like operating
4955** systems. This routine, and the sqlite3_os_end() routine that follows,
4956** should be the only routines in this file that are visible from other
4957** files.
drh6b9d6dd2008-12-03 19:34:47 +00004958**
4959** This routine is called once during SQLite initialization and by a
4960** single thread. The memory allocation and mutex subsystems have not
4961** necessarily been initialized when this routine is called, and so they
4962** should not be used.
drh153c62c2007-08-24 03:51:33 +00004963*/
danielk1977c0fa4c52008-06-25 17:19:00 +00004964int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00004965 /*
4966 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00004967 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
4968 ** to the "finder" function. (pAppData is a pointer to a pointer because
4969 ** silly C90 rules prohibit a void* from being cast to a function pointer
4970 ** and so we have to go through the intermediate pointer to avoid problems
4971 ** when compiling with -pedantic-errors on GCC.)
4972 **
4973 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00004974 ** finder-function. The finder-function returns a pointer to the
4975 ** sqlite_io_methods object that implements the desired locking
4976 ** behaviors. See the division above that contains the IOMETHODS
4977 ** macro for addition information on finder-functions.
4978 **
4979 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
4980 ** object. But the "autolockIoFinder" available on MacOSX does a little
4981 ** more than that; it looks at the filesystem type that hosts the
4982 ** database file and tries to choose an locking method appropriate for
4983 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00004984 */
drh7708e972008-11-29 00:56:52 +00004985 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00004986 1, /* iVersion */ \
4987 sizeof(unixFile), /* szOsFile */ \
4988 MAX_PATHNAME, /* mxPathname */ \
4989 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00004990 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00004991 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00004992 unixOpen, /* xOpen */ \
4993 unixDelete, /* xDelete */ \
4994 unixAccess, /* xAccess */ \
4995 unixFullPathname, /* xFullPathname */ \
4996 unixDlOpen, /* xDlOpen */ \
4997 unixDlError, /* xDlError */ \
4998 unixDlSym, /* xDlSym */ \
4999 unixDlClose, /* xDlClose */ \
5000 unixRandomness, /* xRandomness */ \
5001 unixSleep, /* xSleep */ \
5002 unixCurrentTime, /* xCurrentTime */ \
5003 unixGetLastError /* xGetLastError */ \
5004 }
5005
drh6b9d6dd2008-12-03 19:34:47 +00005006 /*
5007 ** All default VFSes for unix are contained in the following array.
5008 **
5009 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5010 ** by the SQLite core when the VFS is registered. So the following
5011 ** array cannot be const.
5012 */
danielk1977e339d652008-06-28 11:23:00 +00005013 static sqlite3_vfs aVfs[] = {
drhd2cb50b2009-01-09 21:41:17 +00005014#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005015 UNIXVFS("unix", autolockIoFinder ),
5016#else
5017 UNIXVFS("unix", posixIoFinder ),
5018#endif
5019 UNIXVFS("unix-none", nolockIoFinder ),
5020 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005021#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005022 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005023#endif
5024#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005025 UNIXVFS("unix-posix", posixIoFinder ),
5026 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005027#endif
drhd2cb50b2009-01-09 21:41:17 +00005028#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005029 UNIXVFS("unix-afp", afpIoFinder ),
5030 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005031#endif
drh153c62c2007-08-24 03:51:33 +00005032 };
drh6b9d6dd2008-12-03 19:34:47 +00005033 unsigned int i; /* Loop counter */
5034
5035 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005036 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005037 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005038 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005039 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005040}
danielk1977e339d652008-06-28 11:23:00 +00005041
5042/*
drh6b9d6dd2008-12-03 19:34:47 +00005043** Shutdown the operating system interface.
5044**
5045** Some operating systems might need to do some cleanup in this routine,
5046** to release dynamically allocated objects. But not on unix.
5047** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005048*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005049int sqlite3_os_end(void){
5050 return SQLITE_OK;
5051}
drhdce8bdb2007-08-16 13:01:44 +00005052
danielk197729bafea2008-06-26 10:41:19 +00005053#endif /* SQLITE_OS_UNIX */