blob: 918a1edf697331fa6f64e65358e1a5e679741a0f [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**
drha6d90f02009-01-16 23:47:42 +000046** $Id: os_unix.c,v 1.238 2009/01/16 23:47:42 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 ){
drha6d90f02009-01-16 23:47:42 +00002761 int rc;
drh8f941bc2009-01-14 23:03:40 +00002762 char oldCntr[4];
2763 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002764 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002765 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002766 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002767 pFile->transCntrChng = 1; /* The transaction counter has changed */
2768 }
2769 }
2770 }
2771#endif
2772
drh734c9862008-11-28 15:37:20 +00002773 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
2774 amt -= wrote;
2775 offset += wrote;
2776 pBuf = &((char*)pBuf)[wrote];
2777 }
2778 SimulateIOError(( wrote=(-1), amt=1 ));
2779 SimulateDiskfullError(( wrote=0, amt=1 ));
2780 if( amt>0 ){
2781 if( wrote<0 ){
2782 /* lastErrno set by seekAndWrite */
2783 return SQLITE_IOERR_WRITE;
2784 }else{
2785 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2786 return SQLITE_FULL;
2787 }
2788 }
2789 return SQLITE_OK;
2790}
2791
2792#ifdef SQLITE_TEST
2793/*
2794** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002795** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002796*/
2797int sqlite3_sync_count = 0;
2798int sqlite3_fullsync_count = 0;
2799#endif
2800
2801/*
2802** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
2803** Otherwise use fsync() in its place.
2804*/
2805#ifndef HAVE_FDATASYNC
2806# define fdatasync fsync
2807#endif
2808
2809/*
2810** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2811** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2812** only available on Mac OS X. But that could change.
2813*/
2814#ifdef F_FULLFSYNC
2815# define HAVE_FULLFSYNC 1
2816#else
2817# define HAVE_FULLFSYNC 0
2818#endif
2819
2820
2821/*
2822** The fsync() system call does not work as advertised on many
2823** unix systems. The following procedure is an attempt to make
2824** it work better.
2825**
2826** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2827** for testing when we want to run through the test suite quickly.
2828** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2829** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2830** or power failure will likely corrupt the database file.
2831*/
2832static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002833 int rc;
drh734c9862008-11-28 15:37:20 +00002834
2835 /* The following "ifdef/elif/else/" block has the same structure as
2836 ** the one below. It is replicated here solely to avoid cluttering
2837 ** up the real code with the UNUSED_PARAMETER() macros.
2838 */
2839#ifdef SQLITE_NO_SYNC
2840 UNUSED_PARAMETER(fd);
2841 UNUSED_PARAMETER(fullSync);
2842 UNUSED_PARAMETER(dataOnly);
2843#elif HAVE_FULLFSYNC
2844 UNUSED_PARAMETER(dataOnly);
2845#else
2846 UNUSED_PARAMETER(fullSync);
2847#endif
2848
2849 /* Record the number of times that we do a normal fsync() and
2850 ** FULLSYNC. This is used during testing to verify that this procedure
2851 ** gets called with the correct arguments.
2852 */
2853#ifdef SQLITE_TEST
2854 if( fullSync ) sqlite3_fullsync_count++;
2855 sqlite3_sync_count++;
2856#endif
2857
2858 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2859 ** no-op
2860 */
2861#ifdef SQLITE_NO_SYNC
2862 rc = SQLITE_OK;
2863#elif HAVE_FULLFSYNC
2864 if( fullSync ){
2865 rc = fcntl(fd, F_FULLFSYNC, 0);
2866 }else{
2867 rc = 1;
2868 }
2869 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002870 ** It shouldn't be possible for fullfsync to fail on the local
2871 ** file system (on OSX), so failure indicates that FULLFSYNC
2872 ** isn't supported for this file system. So, attempt an fsync
2873 ** and (for now) ignore the overhead of a superfluous fcntl call.
2874 ** It'd be better to detect fullfsync support once and avoid
2875 ** the fcntl call every time sync is called.
2876 */
drh734c9862008-11-28 15:37:20 +00002877 if( rc ) rc = fsync(fd);
2878
2879#else
2880 if( dataOnly ){
2881 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002882#if OS_VXWORKS
2883 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002884 rc = fsync(fd);
2885 }
drhc7288ee2009-01-15 04:30:02 +00002886#endif
drh734c9862008-11-28 15:37:20 +00002887 }else{
2888 rc = fsync(fd);
2889 }
2890#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2891
2892 if( OS_VXWORKS && rc!= -1 ){
2893 rc = 0;
2894 }
chw97185482008-11-17 08:05:31 +00002895 return rc;
drhbfe66312006-10-03 17:40:40 +00002896}
2897
drh734c9862008-11-28 15:37:20 +00002898/*
2899** Make sure all writes to a particular file are committed to disk.
2900**
2901** If dataOnly==0 then both the file itself and its metadata (file
2902** size, access time, etc) are synced. If dataOnly!=0 then only the
2903** file data is synced.
2904**
2905** Under Unix, also make sure that the directory entry for the file
2906** has been created by fsync-ing the directory that contains the file.
2907** If we do not do this and we encounter a power failure, the directory
2908** entry for the journal might not exist after we reboot. The next
2909** SQLite to access the file will not know that the journal exists (because
2910** the directory entry for the journal was never created) and the transaction
2911** will not roll back - possibly leading to database corruption.
2912*/
2913static int unixSync(sqlite3_file *id, int flags){
2914 int rc;
2915 unixFile *pFile = (unixFile*)id;
2916
2917 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2918 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2919
2920 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2921 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2922 || (flags&0x0F)==SQLITE_SYNC_FULL
2923 );
2924
2925 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2926 ** line is to test that doing so does not cause any problems.
2927 */
2928 SimulateDiskfullError( return SQLITE_FULL );
2929
2930 assert( pFile );
2931 OSTRACE2("SYNC %-3d\n", pFile->h);
2932 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
2933 SimulateIOError( rc=1 );
2934 if( rc ){
2935 pFile->lastErrno = errno;
2936 return SQLITE_IOERR_FSYNC;
2937 }
2938 if( pFile->dirfd>=0 ){
2939 int err;
2940 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
2941 HAVE_FULLFSYNC, isFullsync);
2942#ifndef SQLITE_DISABLE_DIRSYNC
2943 /* The directory sync is only attempted if full_fsync is
2944 ** turned off or unavailable. If a full_fsync occurred above,
2945 ** then the directory sync is superfluous.
2946 */
2947 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
2948 /*
2949 ** We have received multiple reports of fsync() returning
2950 ** errors when applied to directories on certain file systems.
2951 ** A failed directory sync is not a big deal. So it seems
2952 ** better to ignore the error. Ticket #1657
2953 */
2954 /* pFile->lastErrno = errno; */
2955 /* return SQLITE_IOERR; */
2956 }
2957#endif
2958 err = close(pFile->dirfd); /* Only need to sync once, so close the */
2959 if( err==0 ){ /* directory when we are done */
2960 pFile->dirfd = -1;
2961 }else{
2962 pFile->lastErrno = errno;
2963 rc = SQLITE_IOERR_DIR_CLOSE;
2964 }
2965 }
2966 return rc;
2967}
2968
2969/*
2970** Truncate an open file to a specified size
2971*/
2972static int unixTruncate(sqlite3_file *id, i64 nByte){
2973 int rc;
2974 assert( id );
2975 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
2976 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
2977 if( rc ){
2978 ((unixFile*)id)->lastErrno = errno;
2979 return SQLITE_IOERR_TRUNCATE;
2980 }else{
2981 return SQLITE_OK;
2982 }
2983}
2984
2985/*
2986** Determine the current size of a file in bytes
2987*/
2988static int unixFileSize(sqlite3_file *id, i64 *pSize){
2989 int rc;
2990 struct stat buf;
2991 assert( id );
2992 rc = fstat(((unixFile*)id)->h, &buf);
2993 SimulateIOError( rc=1 );
2994 if( rc!=0 ){
2995 ((unixFile*)id)->lastErrno = errno;
2996 return SQLITE_IOERR_FSTAT;
2997 }
2998 *pSize = buf.st_size;
2999
3000 /* When opening a zero-size database, the findLockInfo() procedure
3001 ** writes a single byte into that file in order to work around a bug
3002 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3003 ** layers, we need to report this file size as zero even though it is
3004 ** really 1. Ticket #3260.
3005 */
3006 if( *pSize==1 ) *pSize = 0;
3007
3008
3009 return SQLITE_OK;
3010}
3011
drhd2cb50b2009-01-09 21:41:17 +00003012#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003013/*
3014** Handler for proxy-locking file-control verbs. Defined below in the
3015** proxying locking division.
3016*/
3017static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003018#endif
drh715ff302008-12-03 22:32:44 +00003019
danielk1977ad94b582007-08-20 06:44:22 +00003020
danielk1977e3026632004-06-22 11:29:02 +00003021/*
drh9e33c2c2007-08-31 18:34:59 +00003022** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003023*/
drhcc6bb3e2007-08-31 16:11:35 +00003024static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003025 switch( op ){
3026 case SQLITE_FCNTL_LOCKSTATE: {
3027 *(int*)pArg = ((unixFile*)id)->locktype;
3028 return SQLITE_OK;
3029 }
drh7708e972008-11-29 00:56:52 +00003030 case SQLITE_LAST_ERRNO: {
3031 *(int*)pArg = ((unixFile*)id)->lastErrno;
3032 return SQLITE_OK;
3033 }
drh8f941bc2009-01-14 23:03:40 +00003034#ifndef NDEBUG
3035 /* The pager calls this method to signal that it has done
3036 ** a rollback and that the database is therefore unchanged and
3037 ** it hence it is OK for the transaction change counter to be
3038 ** unchanged.
3039 */
3040 case SQLITE_FCNTL_DB_UNCHANGED: {
3041 ((unixFile*)id)->dbUpdate = 0;
3042 return SQLITE_OK;
3043 }
3044#endif
drhd2cb50b2009-01-09 21:41:17 +00003045#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003046 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003047 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003048 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003049 }
drhd2cb50b2009-01-09 21:41:17 +00003050#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003051 }
drhcc6bb3e2007-08-31 16:11:35 +00003052 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003053}
3054
3055/*
danielk1977a3d4c882007-03-23 10:08:38 +00003056** Return the sector size in bytes of the underlying block device for
3057** the specified file. This is almost always 512 bytes, but may be
3058** larger for some devices.
3059**
3060** SQLite code assumes this function cannot fail. It also assumes that
3061** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003062** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003063** same for both.
3064*/
danielk1977397d65f2008-11-19 11:35:39 +00003065static int unixSectorSize(sqlite3_file *NotUsed){
3066 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003067 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003068}
3069
danielk197790949c22007-08-17 16:50:38 +00003070/*
danielk1977397d65f2008-11-19 11:35:39 +00003071** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003072*/
danielk1977397d65f2008-11-19 11:35:39 +00003073static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3074 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003075 return 0;
3076}
3077
drh734c9862008-11-28 15:37:20 +00003078/*
3079** Here ends the implementation of all sqlite3_file methods.
3080**
3081********************** End sqlite3_file Methods *******************************
3082******************************************************************************/
3083
3084/*
drh6b9d6dd2008-12-03 19:34:47 +00003085** This division contains definitions of sqlite3_io_methods objects that
3086** implement various file locking strategies. It also contains definitions
3087** of "finder" functions. A finder-function is used to locate the appropriate
3088** sqlite3_io_methods object for a particular database file. The pAppData
3089** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3090** the correct finder-function for that VFS.
3091**
3092** Most finder functions return a pointer to a fixed sqlite3_io_methods
3093** object. The only interesting finder-function is autolockIoFinder, which
3094** looks at the filesystem type and tries to guess the best locking
3095** strategy from that.
3096**
drh1875f7a2008-12-08 18:19:17 +00003097** For finder-funtion F, two objects are created:
3098**
3099** (1) The real finder-function named "FImpt()".
3100**
3101** (2) A constant pointer to this functio named just "F".
3102**
3103**
3104** A pointer to the F pointer is used as the pAppData value for VFS
3105** objects. We have to do this instead of letting pAppData point
3106** directly at the finder-function since C90 rules prevent a void*
3107** from be cast into a function pointer.
3108**
drh6b9d6dd2008-12-03 19:34:47 +00003109**
drh7708e972008-11-29 00:56:52 +00003110** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003111**
drh7708e972008-11-29 00:56:52 +00003112** * A constant sqlite3_io_methods object call METHOD that has locking
3113** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3114**
3115** * An I/O method finder function called FINDER that returns a pointer
3116** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003117*/
drh7708e972008-11-29 00:56:52 +00003118#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3119static const sqlite3_io_methods METHOD = { \
3120 1, /* iVersion */ \
3121 CLOSE, /* xClose */ \
3122 unixRead, /* xRead */ \
3123 unixWrite, /* xWrite */ \
3124 unixTruncate, /* xTruncate */ \
3125 unixSync, /* xSync */ \
3126 unixFileSize, /* xFileSize */ \
3127 LOCK, /* xLock */ \
3128 UNLOCK, /* xUnlock */ \
3129 CKLOCK, /* xCheckReservedLock */ \
3130 unixFileControl, /* xFileControl */ \
3131 unixSectorSize, /* xSectorSize */ \
3132 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3133}; \
drh1875f7a2008-12-08 18:19:17 +00003134static const sqlite3_io_methods *FINDER##Impl(const char *z, int h){ \
drh7708e972008-11-29 00:56:52 +00003135 UNUSED_PARAMETER(z); UNUSED_PARAMETER(h); \
3136 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003137} \
3138static const sqlite3_io_methods *(*const FINDER)(const char*,int) \
3139 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003140
3141/*
3142** Here are all of the sqlite3_io_methods objects for each of the
3143** locking strategies. Functions that return pointers to these methods
3144** are also created.
3145*/
3146IOMETHODS(
3147 posixIoFinder, /* Finder function name */
3148 posixIoMethods, /* sqlite3_io_methods object name */
3149 unixClose, /* xClose method */
3150 unixLock, /* xLock method */
3151 unixUnlock, /* xUnlock method */
3152 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003153)
drh7708e972008-11-29 00:56:52 +00003154IOMETHODS(
3155 nolockIoFinder, /* Finder function name */
3156 nolockIoMethods, /* sqlite3_io_methods object name */
3157 nolockClose, /* xClose method */
3158 nolockLock, /* xLock method */
3159 nolockUnlock, /* xUnlock method */
3160 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003161)
drh7708e972008-11-29 00:56:52 +00003162IOMETHODS(
3163 dotlockIoFinder, /* Finder function name */
3164 dotlockIoMethods, /* sqlite3_io_methods object name */
3165 dotlockClose, /* xClose method */
3166 dotlockLock, /* xLock method */
3167 dotlockUnlock, /* xUnlock method */
3168 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003169)
drh7708e972008-11-29 00:56:52 +00003170
3171#if SQLITE_ENABLE_LOCKING_STYLE
3172IOMETHODS(
3173 flockIoFinder, /* Finder function name */
3174 flockIoMethods, /* sqlite3_io_methods object name */
3175 flockClose, /* xClose method */
3176 flockLock, /* xLock method */
3177 flockUnlock, /* xUnlock method */
3178 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003179)
drh7708e972008-11-29 00:56:52 +00003180#endif
3181
drh6c7d5c52008-11-21 20:32:33 +00003182#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003183IOMETHODS(
3184 semIoFinder, /* Finder function name */
3185 semIoMethods, /* sqlite3_io_methods object name */
3186 semClose, /* xClose method */
3187 semLock, /* xLock method */
3188 semUnlock, /* xUnlock method */
3189 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003190)
aswiftaebf4132008-11-21 00:10:35 +00003191#endif
drh7708e972008-11-29 00:56:52 +00003192
drhd2cb50b2009-01-09 21:41:17 +00003193#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003194IOMETHODS(
3195 afpIoFinder, /* Finder function name */
3196 afpIoMethods, /* sqlite3_io_methods object name */
3197 afpClose, /* xClose method */
3198 afpLock, /* xLock method */
3199 afpUnlock, /* xUnlock method */
3200 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003201)
drh715ff302008-12-03 22:32:44 +00003202#endif
3203
3204/*
3205** The proxy locking method is a "super-method" in the sense that it
3206** opens secondary file descriptors for the conch and lock files and
3207** it uses proxy, dot-file, AFP, and flock() locking methods on those
3208** secondary files. For this reason, the division that implements
3209** proxy locking is located much further down in the file. But we need
3210** to go ahead and define the sqlite3_io_methods and finder function
3211** for proxy locking here. So we forward declare the I/O methods.
3212*/
drhd2cb50b2009-01-09 21:41:17 +00003213#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003214static int proxyClose(sqlite3_file*);
3215static int proxyLock(sqlite3_file*, int);
3216static int proxyUnlock(sqlite3_file*, int);
3217static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003218IOMETHODS(
3219 proxyIoFinder, /* Finder function name */
3220 proxyIoMethods, /* sqlite3_io_methods object name */
3221 proxyClose, /* xClose method */
3222 proxyLock, /* xLock method */
3223 proxyUnlock, /* xUnlock method */
3224 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003225)
aswiftaebf4132008-11-21 00:10:35 +00003226#endif
drh7708e972008-11-29 00:56:52 +00003227
3228
drhd2cb50b2009-01-09 21:41:17 +00003229#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003230/*
drh6b9d6dd2008-12-03 19:34:47 +00003231** This "finder" function attempts to determine the best locking strategy
3232** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003233** object that implements that strategy.
3234**
3235** This is for MacOSX only.
3236*/
drh1875f7a2008-12-08 18:19:17 +00003237static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003238 const char *filePath, /* name of the database file */
3239 int fd /* file descriptor open on the database file */
3240){
3241 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003242 const char *zFilesystem; /* Filesystem type name */
3243 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003244 } aMap[] = {
3245 { "hfs", &posixIoMethods },
3246 { "ufs", &posixIoMethods },
3247 { "afpfs", &afpIoMethods },
3248#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
3249 { "smbfs", &afpIoMethods },
3250#else
3251 { "smbfs", &flockIoMethods },
3252#endif
3253 { "webdav", &nolockIoMethods },
3254 { 0, 0 }
3255 };
3256 int i;
3257 struct statfs fsInfo;
3258 struct flock lockInfo;
3259
3260 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003261 /* If filePath==NULL that means we are dealing with a transient file
3262 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003263 return &nolockIoMethods;
3264 }
3265 if( statfs(filePath, &fsInfo) != -1 ){
3266 if( fsInfo.f_flags & MNT_RDONLY ){
3267 return &nolockIoMethods;
3268 }
3269 for(i=0; aMap[i].zFilesystem; i++){
3270 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3271 return aMap[i].pMethods;
3272 }
3273 }
3274 }
3275
3276 /* Default case. Handles, amongst others, "nfs".
3277 ** Test byte-range lock using fcntl(). If the call succeeds,
3278 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003279 */
drh7708e972008-11-29 00:56:52 +00003280 lockInfo.l_len = 1;
3281 lockInfo.l_start = 0;
3282 lockInfo.l_whence = SEEK_SET;
3283 lockInfo.l_type = F_RDLCK;
3284 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
3285 return &posixIoMethods;
3286 }else{
3287 return &dotlockIoMethods;
3288 }
3289}
danielk1977852e2322008-12-22 03:36:59 +00003290static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
drh1875f7a2008-12-08 18:19:17 +00003291 = autolockIoFinderImpl;
3292
drhd2cb50b2009-01-09 21:41:17 +00003293#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003294
3295/*
3296** An abstract type for a pointer to a IO method finder function:
3297*/
3298typedef const sqlite3_io_methods *(*finder_type)(const char*,int);
3299
aswiftaebf4132008-11-21 00:10:35 +00003300
drh734c9862008-11-28 15:37:20 +00003301/****************************************************************************
3302**************************** sqlite3_vfs methods ****************************
3303**
3304** This division contains the implementation of methods on the
3305** sqlite3_vfs object.
3306*/
3307
danielk1977a3d4c882007-03-23 10:08:38 +00003308/*
danielk1977e339d652008-06-28 11:23:00 +00003309** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003310*/
3311static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003312 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003313 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003314 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003315 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003316 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003317 int noLock, /* Omit locking if true */
3318 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003319){
drh7708e972008-11-29 00:56:52 +00003320 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003321 unixFile *pNew = (unixFile *)pId;
3322 int rc = SQLITE_OK;
3323
danielk197717b90b52008-06-06 11:11:25 +00003324 assert( pNew->pLock==NULL );
3325 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003326
drh715ff302008-12-03 22:32:44 +00003327 /* Parameter isDelete is only used on vxworks.
3328 ** Express this explicitly here to prevent compiler warnings
3329 ** about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003330 */
drh7708e972008-11-29 00:56:52 +00003331#if !OS_VXWORKS
3332 UNUSED_PARAMETER(isDelete);
3333#endif
danielk1977a03396a2008-11-19 14:35:46 +00003334
drh218c5082008-03-07 00:27:10 +00003335 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003336 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003337 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003338 SET_THREADID(pNew);
drh339eb0b2008-03-07 15:34:11 +00003339
drh6c7d5c52008-11-21 20:32:33 +00003340#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003341 pNew->pId = vxworksFindFileId(zFilename);
3342 if( pNew->pId==0 ){
3343 noLock = 1;
3344 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003345 }
3346#endif
3347
drhda0e7682008-07-30 15:27:54 +00003348 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003349 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003350 }else{
drh1875f7a2008-12-08 18:19:17 +00003351 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, h);
aswiftaebf4132008-11-21 00:10:35 +00003352#if SQLITE_ENABLE_LOCKING_STYLE
3353 /* Cache zFilename in the locking context (AFP and dotlock override) for
3354 ** proxyLock activation is possible (remote proxy is based on db name)
3355 ** zFilename remains valid until file is closed, to support */
3356 pNew->lockingContext = (void*)zFilename;
3357#endif
drhda0e7682008-07-30 15:27:54 +00003358 }
danielk1977e339d652008-06-28 11:23:00 +00003359
drh7708e972008-11-29 00:56:52 +00003360 if( pLockingStyle == &posixIoMethods ){
3361 unixEnterMutex();
3362 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3363 unixLeaveMutex();
3364 }
danielk1977e339d652008-06-28 11:23:00 +00003365
drhd2cb50b2009-01-09 21:41:17 +00003366#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003367 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003368 /* AFP locking uses the file path so it needs to be included in
3369 ** the afpLockingContext.
3370 */
3371 afpLockingContext *pCtx;
3372 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3373 if( pCtx==0 ){
3374 rc = SQLITE_NOMEM;
3375 }else{
3376 /* NB: zFilename exists and remains valid until the file is closed
3377 ** according to requirement F11141. So we do not need to make a
3378 ** copy of the filename. */
3379 pCtx->dbPath = zFilename;
3380 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003381 unixEnterMutex();
drh7708e972008-11-29 00:56:52 +00003382 rc = findLockInfo(pNew, NULL, &pNew->pOpen);
3383 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003384 }
drh7708e972008-11-29 00:56:52 +00003385 }
3386#endif
danielk1977e339d652008-06-28 11:23:00 +00003387
drh7708e972008-11-29 00:56:52 +00003388 else if( pLockingStyle == &dotlockIoMethods ){
3389 /* Dotfile locking uses the file path so it needs to be included in
3390 ** the dotlockLockingContext
3391 */
3392 char *zLockFile;
3393 int nFilename;
drhea678832008-12-10 19:26:22 +00003394 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003395 zLockFile = (char *)sqlite3_malloc(nFilename);
3396 if( zLockFile==0 ){
3397 rc = SQLITE_NOMEM;
3398 }else{
3399 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003400 }
drh7708e972008-11-29 00:56:52 +00003401 pNew->lockingContext = zLockFile;
3402 }
danielk1977e339d652008-06-28 11:23:00 +00003403
drh6c7d5c52008-11-21 20:32:33 +00003404#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003405 else if( pLockingStyle == &semIoMethods ){
3406 /* Named semaphore locking uses the file path so it needs to be
3407 ** included in the semLockingContext
3408 */
3409 unixEnterMutex();
3410 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3411 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3412 char *zSemName = pNew->pOpen->aSemName;
3413 int n;
3414 sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem",
3415 pNew->pId->zCanonicalName);
3416 for( n=0; zSemName[n]; n++ )
3417 if( zSemName[n]=='/' ) zSemName[n] = '_';
3418 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3419 if( pNew->pOpen->pSem == SEM_FAILED ){
3420 rc = SQLITE_NOMEM;
3421 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003422 }
chw97185482008-11-17 08:05:31 +00003423 }
drh7708e972008-11-29 00:56:52 +00003424 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003425 }
drh7708e972008-11-29 00:56:52 +00003426#endif
aswift5b1a2562008-08-22 00:22:35 +00003427
3428 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003429#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003430 if( rc!=SQLITE_OK ){
3431 unlink(zFilename);
3432 isDelete = 0;
3433 }
3434 pNew->isDelete = isDelete;
3435#endif
danielk1977e339d652008-06-28 11:23:00 +00003436 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003437 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
drhbfe66312006-10-03 17:40:40 +00003438 close(h);
danielk1977e339d652008-06-28 11:23:00 +00003439 }else{
drh7708e972008-11-29 00:56:52 +00003440 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003441 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003442 }
danielk1977e339d652008-06-28 11:23:00 +00003443 return rc;
drh054889e2005-11-30 03:20:31 +00003444}
drh9c06c952005-11-26 00:25:00 +00003445
danielk1977ad94b582007-08-20 06:44:22 +00003446/*
3447** Open a file descriptor to the directory containing file zFilename.
3448** If successful, *pFd is set to the opened file descriptor and
3449** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3450** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3451** value.
3452**
3453** If SQLITE_OK is returned, the caller is responsible for closing
3454** the file descriptor *pFd using close().
3455*/
danielk1977fee2d252007-08-18 10:59:19 +00003456static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003457 int ii;
drh777b17a2007-09-20 10:02:54 +00003458 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003459 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003460
drh153c62c2007-08-24 03:51:33 +00003461 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003462 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003463 if( ii>0 ){
3464 zDirname[ii] = '\0';
3465 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003466 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003467#ifdef FD_CLOEXEC
3468 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3469#endif
3470 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3471 }
3472 }
danielk1977fee2d252007-08-18 10:59:19 +00003473 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00003474 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00003475}
3476
danielk1977b4b47412007-08-17 15:53:36 +00003477/*
danielk197717b90b52008-06-06 11:11:25 +00003478** Create a temporary file name in zBuf. zBuf must be allocated
3479** by the calling process and must be big enough to hold at least
3480** pVfs->mxPathname bytes.
3481*/
3482static int getTempname(int nBuf, char *zBuf){
3483 static const char *azDirs[] = {
3484 0,
aswiftaebf4132008-11-21 00:10:35 +00003485 0,
danielk197717b90b52008-06-06 11:11:25 +00003486 "/var/tmp",
3487 "/usr/tmp",
3488 "/tmp",
3489 ".",
3490 };
3491 static const unsigned char zChars[] =
3492 "abcdefghijklmnopqrstuvwxyz"
3493 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3494 "0123456789";
drh41022642008-11-21 00:24:42 +00003495 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003496 struct stat buf;
3497 const char *zDir = ".";
3498
3499 /* It's odd to simulate an io-error here, but really this is just
3500 ** using the io-error infrastructure to test that SQLite handles this
3501 ** function failing.
3502 */
3503 SimulateIOError( return SQLITE_IOERR );
3504
3505 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003506 if (NULL == azDirs[1]) {
3507 azDirs[1] = getenv("TMPDIR");
3508 }
3509
3510 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003511 if( azDirs[i]==0 ) continue;
3512 if( stat(azDirs[i], &buf) ) continue;
3513 if( !S_ISDIR(buf.st_mode) ) continue;
3514 if( access(azDirs[i], 07) ) continue;
3515 zDir = azDirs[i];
3516 break;
3517 }
3518
3519 /* Check that the output buffer is large enough for the temporary file
3520 ** name. If it is not, return SQLITE_ERROR.
3521 */
danielk197700e13612008-11-17 19:18:54 +00003522 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003523 return SQLITE_ERROR;
3524 }
3525
3526 do{
3527 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003528 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003529 sqlite3_randomness(15, &zBuf[j]);
3530 for(i=0; i<15; i++, j++){
3531 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3532 }
3533 zBuf[j] = 0;
3534 }while( access(zBuf,0)==0 );
3535 return SQLITE_OK;
3536}
3537
drhd2cb50b2009-01-09 21:41:17 +00003538#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003539/*
3540** Routine to transform a unixFile into a proxy-locking unixFile.
3541** Implementation in the proxy-lock division, but used by unixOpen()
3542** if SQLITE_PREFER_PROXY_LOCKING is defined.
3543*/
3544static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003545#endif
drhc66d5b62008-12-03 22:48:32 +00003546
danielk197717b90b52008-06-06 11:11:25 +00003547
3548/*
danielk1977ad94b582007-08-20 06:44:22 +00003549** Open the file zPath.
3550**
danielk1977b4b47412007-08-17 15:53:36 +00003551** Previously, the SQLite OS layer used three functions in place of this
3552** one:
3553**
3554** sqlite3OsOpenReadWrite();
3555** sqlite3OsOpenReadOnly();
3556** sqlite3OsOpenExclusive();
3557**
3558** These calls correspond to the following combinations of flags:
3559**
3560** ReadWrite() -> (READWRITE | CREATE)
3561** ReadOnly() -> (READONLY)
3562** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
3563**
3564** The old OpenExclusive() accepted a boolean argument - "delFlag". If
3565** true, the file was configured to be automatically deleted when the
3566** file handle closed. To achieve the same effect using this new
3567** interface, add the DELETEONCLOSE flag to those specified above for
3568** OpenExclusive().
3569*/
3570static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00003571 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
3572 const char *zPath, /* Pathname of file to be opened */
3573 sqlite3_file *pFile, /* The file descriptor to be filled in */
3574 int flags, /* Input flags to control the opening */
3575 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00003576){
danielk1977fee2d252007-08-18 10:59:19 +00003577 int fd = 0; /* File descriptor returned by open() */
3578 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00003579 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00003580 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00003581 int noLock; /* True to omit locking primitives */
aswiftaebf4132008-11-21 00:10:35 +00003582 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003583
3584 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
3585 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
3586 int isCreate = (flags & SQLITE_OPEN_CREATE);
3587 int isReadonly = (flags & SQLITE_OPEN_READONLY);
3588 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
3589
danielk1977fee2d252007-08-18 10:59:19 +00003590 /* If creating a master or main-file journal, this function will open
3591 ** a file-descriptor on the directory too. The first time unixSync()
3592 ** is called the directory file descriptor will be fsync()ed and close()d.
3593 */
3594 int isOpenDirectory = (isCreate &&
3595 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
3596 );
3597
danielk197717b90b52008-06-06 11:11:25 +00003598 /* If argument zPath is a NULL pointer, this function is required to open
3599 ** a temporary file. Use this buffer to store the file name in.
3600 */
3601 char zTmpname[MAX_PATHNAME+1];
3602 const char *zName = zPath;
3603
danielk1977fee2d252007-08-18 10:59:19 +00003604 /* Check the following statements are true:
3605 **
3606 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
3607 ** (b) if CREATE is set, then READWRITE must also be set, and
3608 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00003609 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00003610 */
danielk1977b4b47412007-08-17 15:53:36 +00003611 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00003612 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00003613 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00003614 assert(isDelete==0 || isCreate);
3615
drh33f4e022007-09-03 15:19:34 +00003616 /* The main DB, main journal, and master journal are never automatically
3617 ** deleted
3618 */
3619 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
3620 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
3621 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00003622
danielk1977fee2d252007-08-18 10:59:19 +00003623 /* Assert that the upper layer has set one of the "file-type" flags. */
3624 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
3625 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3626 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00003627 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00003628 );
3629
danielk1977e339d652008-06-28 11:23:00 +00003630 memset(pFile, 0, sizeof(unixFile));
3631
danielk197717b90b52008-06-06 11:11:25 +00003632 if( !zName ){
danielk197717b90b52008-06-06 11:11:25 +00003633 assert(isDelete && !isOpenDirectory);
3634 rc = getTempname(MAX_PATHNAME+1, zTmpname);
3635 if( rc!=SQLITE_OK ){
3636 return rc;
3637 }
3638 zName = zTmpname;
3639 }
3640
drh734c9862008-11-28 15:37:20 +00003641 if( isReadonly ) openFlags |= O_RDONLY;
3642 if( isReadWrite ) openFlags |= O_RDWR;
3643 if( isCreate ) openFlags |= O_CREAT;
3644 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
3645 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00003646
drh734c9862008-11-28 15:37:20 +00003647 fd = open(zName, openFlags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
3648 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
danielk19772f2d8c72007-08-30 16:13:33 +00003649 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00003650 /* Failed to open the file for read/write access. Try read-only. */
3651 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3652 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00003653 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00003654 }
3655 if( fd<0 ){
3656 return SQLITE_CANTOPEN;
3657 }
3658 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00003659#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003660 zPath = zName;
3661#else
danielk197717b90b52008-06-06 11:11:25 +00003662 unlink(zName);
chw97185482008-11-17 08:05:31 +00003663#endif
danielk1977b4b47412007-08-17 15:53:36 +00003664 }
drh41022642008-11-21 00:24:42 +00003665#if SQLITE_ENABLE_LOCKING_STYLE
3666 else{
drh734c9862008-11-28 15:37:20 +00003667 ((unixFile*)pFile)->openFlags = openFlags;
drh41022642008-11-21 00:24:42 +00003668 }
3669#endif
danielk1977b4b47412007-08-17 15:53:36 +00003670 if( pOutFlags ){
3671 *pOutFlags = flags;
3672 }
3673
3674 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00003675 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00003676 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00003677 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003678 close(fd); /* silently leak if fail, already in error */
danielk1977fee2d252007-08-18 10:59:19 +00003679 return rc;
3680 }
3681 }
danielk1977e339d652008-06-28 11:23:00 +00003682
3683#ifdef FD_CLOEXEC
3684 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3685#endif
3686
drhda0e7682008-07-30 15:27:54 +00003687 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00003688
3689#if SQLITE_PREFER_PROXY_LOCKING
3690 if( zPath!=NULL && !noLock ){
3691 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
3692 int useProxy = 0;
3693
3694 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy,
drh7708e972008-11-29 00:56:52 +00003695 ** 0 means never use proxy, NULL means use proxy for non-local files only
3696 */
aswiftaebf4132008-11-21 00:10:35 +00003697 if( envforce!=NULL ){
3698 useProxy = atoi(envforce)>0;
3699 }else{
3700 struct statfs fsInfo;
3701
3702 if( statfs(zPath, &fsInfo) == -1 ){
3703 ((unixFile*)pFile)->lastErrno = errno;
3704 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
3705 close(fd); /* silently leak if fail, in error */
3706 return SQLITE_IOERR_ACCESS;
3707 }
3708 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
3709 }
3710 if( useProxy ){
3711 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
3712 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00003713 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
aswiftaebf4132008-11-21 00:10:35 +00003714 }
3715 return rc;
3716 }
3717 }
3718#endif
3719
chw97185482008-11-17 08:05:31 +00003720 return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
danielk1977b4b47412007-08-17 15:53:36 +00003721}
3722
3723/*
danielk1977fee2d252007-08-18 10:59:19 +00003724** Delete the file at zPath. If the dirSync argument is true, fsync()
3725** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00003726*/
drh6b9d6dd2008-12-03 19:34:47 +00003727static int unixDelete(
3728 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
3729 const char *zPath, /* Name of file to be deleted */
3730 int dirSync /* If true, fsync() directory after deleting file */
3731){
danielk1977fee2d252007-08-18 10:59:19 +00003732 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00003733 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003734 SimulateIOError(return SQLITE_IOERR_DELETE);
3735 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00003736#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00003737 if( dirSync ){
3738 int fd;
3739 rc = openDirectory(zPath, &fd);
3740 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00003741#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003742 if( fsync(fd)==-1 )
3743#else
3744 if( fsync(fd) )
3745#endif
3746 {
danielk1977fee2d252007-08-18 10:59:19 +00003747 rc = SQLITE_IOERR_DIR_FSYNC;
3748 }
aswiftaebf4132008-11-21 00:10:35 +00003749 if( close(fd)&&!rc ){
3750 rc = SQLITE_IOERR_DIR_CLOSE;
3751 }
danielk1977fee2d252007-08-18 10:59:19 +00003752 }
3753 }
danielk1977d138dd82008-10-15 16:02:48 +00003754#endif
danielk1977fee2d252007-08-18 10:59:19 +00003755 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00003756}
3757
danielk197790949c22007-08-17 16:50:38 +00003758/*
3759** Test the existance of or access permissions of file zPath. The
3760** test performed depends on the value of flags:
3761**
3762** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
3763** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
3764** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
3765**
3766** Otherwise return 0.
3767*/
danielk1977861f7452008-06-05 11:39:11 +00003768static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00003769 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
3770 const char *zPath, /* Path of the file to examine */
3771 int flags, /* What do we want to learn about the zPath file? */
3772 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00003773){
rse25c0d1a2007-09-20 08:38:14 +00003774 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00003775 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00003776 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00003777 switch( flags ){
3778 case SQLITE_ACCESS_EXISTS:
3779 amode = F_OK;
3780 break;
3781 case SQLITE_ACCESS_READWRITE:
3782 amode = W_OK|R_OK;
3783 break;
drh50d3f902007-08-27 21:10:36 +00003784 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00003785 amode = R_OK;
3786 break;
3787
3788 default:
3789 assert(!"Invalid flags argument");
3790 }
danielk1977861f7452008-06-05 11:39:11 +00003791 *pResOut = (access(zPath, amode)==0);
3792 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003793}
3794
danielk1977b4b47412007-08-17 15:53:36 +00003795
3796/*
3797** Turn a relative pathname into a full pathname. The relative path
3798** is stored as a nul-terminated string in the buffer pointed to by
3799** zPath.
3800**
3801** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
3802** (in this case, MAX_PATHNAME bytes). The full-path is written to
3803** this buffer before returning.
3804*/
danielk1977adfb9b02007-09-17 07:02:56 +00003805static int unixFullPathname(
3806 sqlite3_vfs *pVfs, /* Pointer to vfs object */
3807 const char *zPath, /* Possibly relative input path */
3808 int nOut, /* Size of output buffer in bytes */
3809 char *zOut /* Output buffer */
3810){
danielk1977843e65f2007-09-01 16:16:15 +00003811
3812 /* It's odd to simulate an io-error here, but really this is just
3813 ** using the io-error infrastructure to test that SQLite handles this
3814 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00003815 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00003816 */
3817 SimulateIOError( return SQLITE_ERROR );
3818
drh153c62c2007-08-24 03:51:33 +00003819 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00003820 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00003821
drh3c7f2dc2007-12-06 13:26:20 +00003822 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00003823 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00003824 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003825 }else{
3826 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00003827 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00003828 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00003829 }
drhea678832008-12-10 19:26:22 +00003830 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00003831 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003832 }
3833 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003834}
3835
drh0ccebe72005-06-07 22:22:50 +00003836
drh761df872006-12-21 01:29:22 +00003837#ifndef SQLITE_OMIT_LOAD_EXTENSION
3838/*
3839** Interfaces for opening a shared library, finding entry points
3840** within the shared library, and closing the shared library.
3841*/
3842#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00003843static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
3844 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00003845 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
3846}
danielk197795c8a542007-09-01 06:51:27 +00003847
3848/*
3849** SQLite calls this function immediately after a call to unixDlSym() or
3850** unixDlOpen() fails (returns a null pointer). If a more detailed error
3851** message is available, it is written to zBufOut. If no error message
3852** is available, zBufOut is left unmodified and SQLite uses a default
3853** error message.
3854*/
danielk1977397d65f2008-11-19 11:35:39 +00003855static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00003856 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00003857 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00003858 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003859 zErr = dlerror();
3860 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00003861 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00003862 }
drh6c7d5c52008-11-21 20:32:33 +00003863 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003864}
drh1875f7a2008-12-08 18:19:17 +00003865static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
3866 /*
3867 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
3868 ** cast into a pointer to a function. And yet the library dlsym() routine
3869 ** returns a void* which is really a pointer to a function. So how do we
3870 ** use dlsym() with -pedantic-errors?
3871 **
3872 ** Variable x below is defined to be a pointer to a function taking
3873 ** parameters void* and const char* and returning a pointer to a function.
3874 ** We initialize x by assigning it a pointer to the dlsym() function.
3875 ** (That assignment requires a cast.) Then we call the function that
3876 ** x points to.
3877 **
3878 ** This work-around is unlikely to work correctly on any system where
3879 ** you really cannot cast a function pointer into void*. But then, on the
3880 ** other hand, dlsym() will not work on such a system either, so we have
3881 ** not really lost anything.
3882 */
3883 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00003884 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00003885 x = (void(*(*)(void*,const char*))(void))dlsym;
3886 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00003887}
danielk1977397d65f2008-11-19 11:35:39 +00003888static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
3889 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003890 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00003891}
danielk1977b4b47412007-08-17 15:53:36 +00003892#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
3893 #define unixDlOpen 0
3894 #define unixDlError 0
3895 #define unixDlSym 0
3896 #define unixDlClose 0
3897#endif
3898
3899/*
danielk197790949c22007-08-17 16:50:38 +00003900** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00003901*/
danielk1977397d65f2008-11-19 11:35:39 +00003902static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
3903 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00003904 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00003905
drhbbd42a62004-05-22 17:41:58 +00003906 /* We have to initialize zBuf to prevent valgrind from reporting
3907 ** errors. The reports issued by valgrind are incorrect - we would
3908 ** prefer that the randomness be increased by making use of the
3909 ** uninitialized space in zBuf - but valgrind errors tend to worry
3910 ** some users. Rather than argue, it seems easier just to initialize
3911 ** the whole array and silence valgrind, even if that means less randomness
3912 ** in the random seed.
3913 **
3914 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00003915 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00003916 ** tests repeatable.
3917 */
danielk1977b4b47412007-08-17 15:53:36 +00003918 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00003919#if !defined(SQLITE_TEST)
3920 {
drh842b8642005-01-21 17:53:17 +00003921 int pid, fd;
3922 fd = open("/dev/urandom", O_RDONLY);
3923 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00003924 time_t t;
3925 time(&t);
danielk197790949c22007-08-17 16:50:38 +00003926 memcpy(zBuf, &t, sizeof(t));
3927 pid = getpid();
3928 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00003929 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00003930 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00003931 }else{
drh72cbd072008-10-14 17:58:38 +00003932 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00003933 close(fd);
3934 }
drhbbd42a62004-05-22 17:41:58 +00003935 }
3936#endif
drh72cbd072008-10-14 17:58:38 +00003937 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00003938}
3939
danielk1977b4b47412007-08-17 15:53:36 +00003940
drhbbd42a62004-05-22 17:41:58 +00003941/*
3942** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00003943** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00003944** The return value is the number of microseconds of sleep actually
3945** requested from the underlying operating system, a number which
3946** might be greater than or equal to the argument, but not less
3947** than the argument.
drhbbd42a62004-05-22 17:41:58 +00003948*/
danielk1977397d65f2008-11-19 11:35:39 +00003949static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00003950#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003951 struct timespec sp;
3952
3953 sp.tv_sec = microseconds / 1000000;
3954 sp.tv_nsec = (microseconds % 1000000) * 1000;
3955 nanosleep(&sp, NULL);
danielk1977397d65f2008-11-19 11:35:39 +00003956 return microseconds;
3957#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00003958 usleep(microseconds);
3959 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00003960#else
danielk1977b4b47412007-08-17 15:53:36 +00003961 int seconds = (microseconds+999999)/1000000;
3962 sleep(seconds);
drh4a50aac2007-08-23 02:47:53 +00003963 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00003964#endif
danielk1977397d65f2008-11-19 11:35:39 +00003965 UNUSED_PARAMETER(NotUsed);
drh88f474a2006-01-02 20:00:12 +00003966}
3967
3968/*
drh6b9d6dd2008-12-03 19:34:47 +00003969** The following variable, if set to a non-zero value, is interpreted as
3970** the number of seconds since 1970 and is used to set the result of
3971** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00003972*/
3973#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00003974int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00003975#endif
3976
3977/*
3978** Find the current time (in Universal Coordinated Time). Write the
3979** current time and date as a Julian Day number into *prNow and
3980** return 0. Return 1 if the time and date cannot be found.
3981*/
danielk1977397d65f2008-11-19 11:35:39 +00003982static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh6c7d5c52008-11-21 20:32:33 +00003983#if defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00003984 time_t t;
3985 time(&t);
3986 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00003987#elif OS_VXWORKS
3988 struct timespec sNow;
3989 clock_gettime(CLOCK_REALTIME, &sNow);
3990 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00003991#else
3992 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00003993 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00003994 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
3995#endif
danielk1977397d65f2008-11-19 11:35:39 +00003996
drhbbd42a62004-05-22 17:41:58 +00003997#ifdef SQLITE_TEST
3998 if( sqlite3_current_time ){
3999 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4000 }
4001#endif
danielk1977397d65f2008-11-19 11:35:39 +00004002 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004003 return 0;
4004}
danielk1977b4b47412007-08-17 15:53:36 +00004005
drh6b9d6dd2008-12-03 19:34:47 +00004006/*
4007** We added the xGetLastError() method with the intention of providing
4008** better low-level error messages when operating-system problems come up
4009** during SQLite operation. But so far, none of that has been implemented
4010** in the core. So this routine is never called. For now, it is merely
4011** a place-holder.
4012*/
danielk1977397d65f2008-11-19 11:35:39 +00004013static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4014 UNUSED_PARAMETER(NotUsed);
4015 UNUSED_PARAMETER(NotUsed2);
4016 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004017 return 0;
4018}
4019
drh153c62c2007-08-24 03:51:33 +00004020/*
drh734c9862008-11-28 15:37:20 +00004021************************ End of sqlite3_vfs methods ***************************
4022******************************************************************************/
4023
drh715ff302008-12-03 22:32:44 +00004024/******************************************************************************
4025************************** Begin Proxy Locking ********************************
4026**
4027** Proxy locking is a "uber-locking-method" in this sense: It uses the
4028** other locking methods on secondary lock files. Proxy locking is a
4029** meta-layer over top of the primitive locking implemented above. For
4030** this reason, the division that implements of proxy locking is deferred
4031** until late in the file (here) after all of the other I/O methods have
4032** been defined - so that the primitive locking methods are available
4033** as services to help with the implementation of proxy locking.
4034**
4035****
4036**
4037** The default locking schemes in SQLite use byte-range locks on the
4038** database file to coordinate safe, concurrent access by multiple readers
4039** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4040** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4041** as POSIX read & write locks over fixed set of locations (via fsctl),
4042** on AFP and SMB only exclusive byte-range locks are available via fsctl
4043** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4044** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4045** address in the shared range is taken for a SHARED lock, the entire
4046** shared range is taken for an EXCLUSIVE lock):
4047**
4048** PENDING_BYTE 0x40000000
4049** RESERVED_BYTE 0x40000001
4050** SHARED_RANGE 0x40000002 -> 0x40000200
4051**
4052** This works well on the local file system, but shows a nearly 100x
4053** slowdown in read performance on AFP because the AFP client disables
4054** the read cache when byte-range locks are present. Enabling the read
4055** cache exposes a cache coherency problem that is present on all OS X
4056** supported network file systems. NFS and AFP both observe the
4057** close-to-open semantics for ensuring cache coherency
4058** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4059** address the requirements for concurrent database access by multiple
4060** readers and writers
4061** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4062**
4063** To address the performance and cache coherency issues, proxy file locking
4064** changes the way database access is controlled by limiting access to a
4065** single host at a time and moving file locks off of the database file
4066** and onto a proxy file on the local file system.
4067**
4068**
4069** Using proxy locks
4070** -----------------
4071**
4072** C APIs
4073**
4074** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4075** <proxy_path> | ":auto:");
4076** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4077**
4078**
4079** SQL pragmas
4080**
4081** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4082** PRAGMA [database.]lock_proxy_file
4083**
4084** Specifying ":auto:" means that if there is a conch file with a matching
4085** host ID in it, the proxy path in the conch file will be used, otherwise
4086** a proxy path based on the user's temp dir
4087** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4088** actual proxy file name is generated from the name and path of the
4089** database file. For example:
4090**
4091** For database path "/Users/me/foo.db"
4092** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4093**
4094** Once a lock proxy is configured for a database connection, it can not
4095** be removed, however it may be switched to a different proxy path via
4096** the above APIs (assuming the conch file is not being held by another
4097** connection or process).
4098**
4099**
4100** How proxy locking works
4101** -----------------------
4102**
4103** Proxy file locking relies primarily on two new supporting files:
4104**
4105** * conch file to limit access to the database file to a single host
4106** at a time
4107**
4108** * proxy file to act as a proxy for the advisory locks normally
4109** taken on the database
4110**
4111** The conch file - to use a proxy file, sqlite must first "hold the conch"
4112** by taking an sqlite-style shared lock on the conch file, reading the
4113** contents and comparing the host's unique host ID (see below) and lock
4114** proxy path against the values stored in the conch. The conch file is
4115** stored in the same directory as the database file and the file name
4116** is patterned after the database file name as ".<databasename>-conch".
4117** If the conch file does not exist, or it's contents do not match the
4118** host ID and/or proxy path, then the lock is escalated to an exclusive
4119** lock and the conch file contents is updated with the host ID and proxy
4120** path and the lock is downgraded to a shared lock again. If the conch
4121** is held by another process (with a shared lock), the exclusive lock
4122** will fail and SQLITE_BUSY is returned.
4123**
4124** The proxy file - a single-byte file used for all advisory file locks
4125** normally taken on the database file. This allows for safe sharing
4126** of the database file for multiple readers and writers on the same
4127** host (the conch ensures that they all use the same local lock file).
4128**
4129** There is a third file - the host ID file - used as a persistent record
4130** of a unique identifier for the host, a 128-byte unique host id file
4131** in the path defined by the HOSTIDPATH macro (default value is
4132** /Library/Caches/.com.apple.sqliteConchHostId).
4133**
4134** Requesting the lock proxy does not immediately take the conch, it is
4135** only taken when the first request to lock database file is made.
4136** This matches the semantics of the traditional locking behavior, where
4137** opening a connection to a database file does not take a lock on it.
4138** The shared lock and an open file descriptor are maintained until
4139** the connection to the database is closed.
4140**
4141** The proxy file and the lock file are never deleted so they only need
4142** to be created the first time they are used.
4143**
4144** Configuration options
4145** ---------------------
4146**
4147** SQLITE_PREFER_PROXY_LOCKING
4148**
4149** Database files accessed on non-local file systems are
4150** automatically configured for proxy locking, lock files are
4151** named automatically using the same logic as
4152** PRAGMA lock_proxy_file=":auto:"
4153**
4154** SQLITE_PROXY_DEBUG
4155**
4156** Enables the logging of error messages during host id file
4157** retrieval and creation
4158**
4159** HOSTIDPATH
4160**
4161** Overrides the default host ID file path location
4162**
4163** LOCKPROXYDIR
4164**
4165** Overrides the default directory used for lock proxy files that
4166** are named automatically via the ":auto:" setting
4167**
4168** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4169**
4170** Permissions to use when creating a directory for storing the
4171** lock proxy files, only used when LOCKPROXYDIR is not set.
4172**
4173**
4174** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4175** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4176** force proxy locking to be used for every database file opened, and 0
4177** will force automatic proxy locking to be disabled for all database
4178** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4179** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4180*/
4181
4182/*
4183** Proxy locking is only available on MacOSX
4184*/
drhd2cb50b2009-01-09 21:41:17 +00004185#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004186
4187#ifdef SQLITE_TEST
4188/* simulate multiple hosts by creating unique hostid file paths */
4189int sqlite3_hostid_num = 0;
4190#endif
4191
4192/*
4193** The proxyLockingContext has the path and file structures for the remote
4194** and local proxy files in it
4195*/
4196typedef struct proxyLockingContext proxyLockingContext;
4197struct proxyLockingContext {
4198 unixFile *conchFile; /* Open conch file */
4199 char *conchFilePath; /* Name of the conch file */
4200 unixFile *lockProxy; /* Open proxy lock file */
4201 char *lockProxyPath; /* Name of the proxy lock file */
4202 char *dbPath; /* Name of the open file */
4203 int conchHeld; /* True if the conch is currently held */
4204 void *oldLockingContext; /* Original lockingcontext to restore on close */
4205 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4206};
4207
4208/* HOSTIDLEN and CONCHLEN both include space for the string
4209** terminating nul
4210*/
4211#define HOSTIDLEN 128
4212#define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
4213#ifndef HOSTIDPATH
4214# define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
4215#endif
4216
4217/* basically a copy of unixRandomness with different
4218** test behavior built in */
4219static int proxyGenerateHostID(char *pHostID){
4220 int pid, fd, len;
4221 unsigned char *key = (unsigned char *)pHostID;
4222
4223 memset(key, 0, HOSTIDLEN);
4224 len = 0;
4225 fd = open("/dev/urandom", O_RDONLY);
4226 if( fd>=0 ){
4227 len = read(fd, key, HOSTIDLEN);
4228 close(fd); /* silently leak the fd if it fails */
4229 }
4230 if( len < HOSTIDLEN ){
4231 time_t t;
4232 time(&t);
4233 memcpy(key, &t, sizeof(t));
4234 pid = getpid();
4235 memcpy(&key[sizeof(t)], &pid, sizeof(pid));
4236 }
4237
4238#ifdef MAKE_PRETTY_HOSTID
4239 {
4240 int i;
4241 /* filter the bytes into printable ascii characters and NUL terminate */
4242 key[(HOSTIDLEN-1)] = 0x00;
4243 for( i=0; i<(HOSTIDLEN-1); i++ ){
4244 unsigned char pa = key[i]&0x7F;
4245 if( pa<0x20 ){
4246 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
4247 }else if( pa==0x7F ){
4248 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
4249 }
4250 }
4251 }
4252#endif
4253 return SQLITE_OK;
4254}
4255
4256/* writes the host id path to path, path should be an pre-allocated buffer
4257** with enough space for a path
4258*/
4259static void proxyGetHostIDPath(char *path, size_t len){
4260 strlcpy(path, HOSTIDPATH, len);
4261#ifdef SQLITE_TEST
4262 if( sqlite3_hostid_num>0 ){
4263 char suffix[2] = "1";
4264 suffix[0] = suffix[0] + sqlite3_hostid_num;
4265 strlcat(path, suffix, len);
4266 }
4267#endif
4268 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
4269}
4270
4271/* get the host ID from a sqlite hostid file stored in the
4272** user-specific tmp directory, create the ID if it's not there already
4273*/
4274static int proxyGetHostID(char *pHostID, int *pError){
4275 int fd;
4276 char path[MAXPATHLEN];
4277 size_t len;
4278 int rc=SQLITE_OK;
4279
4280 proxyGetHostIDPath(path, MAXPATHLEN);
4281 /* try to create the host ID file, if it already exists read the contents */
4282 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
4283 if( fd<0 ){
4284 int err=errno;
4285
4286 if( err!=EEXIST ){
4287#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4288 fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
4289 path, strerror(err));
4290#endif
4291 return SQLITE_PERM;
4292 }
4293 /* couldn't create the file, read it instead */
4294 fd = open(path, O_RDONLY|O_EXCL);
4295 if( fd<0 ){
4296#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4297 int err = errno;
4298 fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
4299 path, strerror(err));
4300#endif
4301 return SQLITE_PERM;
4302 }
4303 len = pread(fd, pHostID, HOSTIDLEN, 0);
4304 if( len<0 ){
4305 *pError = errno;
4306 rc = SQLITE_IOERR_READ;
4307 }else if( len<HOSTIDLEN ){
4308 *pError = 0;
4309 rc = SQLITE_IOERR_SHORT_READ;
4310 }
4311 close(fd); /* silently leak the fd if it fails */
4312 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
4313 return rc;
4314 }else{
4315 /* we're creating the host ID file (use a random string of bytes) */
4316 proxyGenerateHostID(pHostID);
4317 len = pwrite(fd, pHostID, HOSTIDLEN, 0);
4318 if( len<0 ){
4319 *pError = errno;
4320 rc = SQLITE_IOERR_WRITE;
4321 }else if( len<HOSTIDLEN ){
4322 *pError = 0;
4323 rc = SQLITE_IOERR_WRITE;
4324 }
4325 close(fd); /* silently leak the fd if it fails */
4326 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
4327 return rc;
4328 }
4329}
4330
4331static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4332 int len;
4333 int dbLen;
4334 int i;
4335
4336#ifdef LOCKPROXYDIR
4337 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4338#else
4339# ifdef _CS_DARWIN_USER_TEMP_DIR
4340 {
4341 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
4342 len = strlcat(lPath, "sqliteplocks", maxLen);
4343 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4344 /* if mkdir fails, handle as lock file creation failure */
4345 int err = errno;
4346# ifdef SQLITE_DEBUG
4347 if( err!=EEXIST ){
4348 fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
4349 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
4350 }
4351# endif
4352 }else{
4353 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
4354 }
4355
4356 }
4357# else
4358 len = strlcpy(lPath, "/tmp/", maxLen);
4359# endif
4360#endif
4361
4362 if( lPath[len-1]!='/' ){
4363 len = strlcat(lPath, "/", maxLen);
4364 }
4365
4366 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004367 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004368 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4369 char c = dbPath[i];
4370 lPath[i+len] = (c=='/')?'_':c;
4371 }
4372 lPath[i+len]='\0';
4373 strlcat(lPath, ":auto:", maxLen);
4374 return SQLITE_OK;
4375}
4376
4377/*
4378** Create a new VFS file descriptor (stored in memory obtained from
4379** sqlite3_malloc) and open the file named "path" in the file descriptor.
4380**
4381** The caller is responsible not only for closing the file descriptor
4382** but also for freeing the memory associated with the file descriptor.
4383*/
4384static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
4385 int fd;
4386 int dirfd = -1;
4387 unixFile *pNew;
4388 int rc = SQLITE_OK;
4389 sqlite3_vfs dummyVfs;
4390
4391 fd = open(path, O_RDWR | O_CREAT, SQLITE_DEFAULT_FILE_PERMISSIONS);
4392 if( fd<0 ){
4393 return SQLITE_CANTOPEN;
4394 }
4395
4396 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
4397 if( pNew==NULL ){
4398 rc = SQLITE_NOMEM;
4399 goto end_create_proxy;
4400 }
4401 memset(pNew, 0, sizeof(unixFile));
4402
drh1875f7a2008-12-08 18:19:17 +00004403 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh715ff302008-12-03 22:32:44 +00004404 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
4405 if( rc==SQLITE_OK ){
4406 *ppFile = pNew;
4407 return SQLITE_OK;
4408 }
4409end_create_proxy:
4410 close(fd); /* silently leak fd if error, we're already in error */
4411 sqlite3_free(pNew);
4412 return rc;
4413}
4414
4415/* takes the conch by taking a shared lock and read the contents conch, if
4416** lockPath is non-NULL, the host ID and lock file path must match. A NULL
4417** lockPath means that the lockPath in the conch file will be used if the
4418** host IDs match, or a new lock path will be generated automatically
4419** and written to the conch file.
4420*/
4421static int proxyTakeConch(unixFile *pFile){
4422 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4423
4424 if( pCtx->conchHeld>0 ){
4425 return SQLITE_OK;
4426 }else{
4427 unixFile *conchFile = pCtx->conchFile;
4428 char testValue[CONCHLEN];
4429 char conchValue[CONCHLEN];
4430 char lockPath[MAXPATHLEN];
4431 char *tLockPath = NULL;
4432 int rc = SQLITE_OK;
4433 int readRc = SQLITE_OK;
4434 int syncPerms = 0;
4435
4436 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
4437 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
4438
4439 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
4440 if( rc==SQLITE_OK ){
4441 int pError = 0;
drh1875f7a2008-12-08 18:19:17 +00004442 memset(testValue, 0, CONCHLEN); /* conch is fixed size */
drh715ff302008-12-03 22:32:44 +00004443 rc = proxyGetHostID(testValue, &pError);
4444 if( (rc&0xff)==SQLITE_IOERR ){
4445 pFile->lastErrno = pError;
4446 }
4447 if( pCtx->lockProxyPath ){
4448 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
4449 }
4450 }
4451 if( rc!=SQLITE_OK ){
4452 goto end_takeconch;
4453 }
4454
4455 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
4456 if( readRc!=SQLITE_IOERR_SHORT_READ ){
4457 if( readRc!=SQLITE_OK ){
4458 if( (rc&0xff)==SQLITE_IOERR ){
4459 pFile->lastErrno = conchFile->lastErrno;
4460 }
4461 rc = readRc;
4462 goto end_takeconch;
4463 }
4464 /* if the conch has data compare the contents */
4465 if( !pCtx->lockProxyPath ){
4466 /* for auto-named local lock file, just check the host ID and we'll
4467 ** use the local lock file path that's already in there */
4468 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
4469 tLockPath = (char *)&conchValue[HOSTIDLEN];
4470 goto end_takeconch;
4471 }
4472 }else{
4473 /* we've got the conch if conchValue matches our path and host ID */
4474 if( !memcmp(testValue, conchValue, CONCHLEN) ){
4475 goto end_takeconch;
4476 }
4477 }
4478 }else{
4479 /* a short read means we're "creating" the conch (even though it could
4480 ** have been user-intervention), if we acquire the exclusive lock,
4481 ** we'll try to match the current on-disk permissions of the database
4482 */
4483 syncPerms = 1;
4484 }
4485
4486 /* either conch was emtpy or didn't match */
4487 if( !pCtx->lockProxyPath ){
4488 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
4489 tLockPath = lockPath;
4490 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
4491 }
4492
4493 /* update conch with host and path (this will fail if other process
4494 ** has a shared lock already) */
4495 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
4496 if( rc==SQLITE_OK ){
4497 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
4498 if( rc==SQLITE_OK && syncPerms ){
4499 struct stat buf;
4500 int err = fstat(pFile->h, &buf);
4501 if( err==0 ){
4502 /* try to match the database file permissions, ignore failure */
4503#ifndef SQLITE_PROXY_DEBUG
4504 fchmod(conchFile->h, buf.st_mode);
4505#else
4506 if( fchmod(conchFile->h, buf.st_mode)!=0 ){
4507 int code = errno;
4508 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
4509 buf.st_mode, code, strerror(code));
4510 } else {
4511 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
4512 }
4513 }else{
4514 int code = errno;
4515 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
4516 err, code, strerror(code));
4517#endif
4518 }
4519 }
4520 }
4521 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
4522
4523end_takeconch:
4524 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
4525 if( rc==SQLITE_OK && pFile->openFlags ){
4526 if( pFile->h>=0 ){
4527#ifdef STRICT_CLOSE_ERROR
4528 if( close(pFile->h) ){
4529 pFile->lastErrno = errno;
4530 return SQLITE_IOERR_CLOSE;
4531 }
4532#else
4533 close(pFile->h); /* silently leak fd if fail */
4534#endif
4535 }
4536 pFile->h = -1;
4537 int fd = open(pCtx->dbPath, pFile->openFlags,
4538 SQLITE_DEFAULT_FILE_PERMISSIONS);
4539 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
4540 if( fd>=0 ){
4541 pFile->h = fd;
4542 }else{
drh1875f7a2008-12-08 18:19:17 +00004543 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
4544 during locking */
drh715ff302008-12-03 22:32:44 +00004545 }
4546 }
4547 if( rc==SQLITE_OK && !pCtx->lockProxy ){
4548 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
drh1875f7a2008-12-08 18:19:17 +00004549 /* ACS: Need to make a copy of path sometimes */
drh715ff302008-12-03 22:32:44 +00004550 rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
4551 }
4552 if( rc==SQLITE_OK ){
4553 pCtx->conchHeld = 1;
4554
4555 if( tLockPath ){
4556 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
4557 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
4558 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
4559 pCtx->lockProxyPath;
4560 }
4561 }
4562 } else {
4563 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4564 }
4565 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
4566 return rc;
4567 }
4568}
4569
4570/*
4571** If pFile holds a lock on a conch file, then release that lock.
4572*/
4573static int proxyReleaseConch(unixFile *pFile){
4574 int rc; /* Subroutine return code */
4575 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
4576 unixFile *conchFile; /* Name of the conch file */
4577
4578 pCtx = (proxyLockingContext *)pFile->lockingContext;
4579 conchFile = pCtx->conchFile;
4580 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
4581 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
4582 getpid());
4583 pCtx->conchHeld = 0;
4584 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4585 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
4586 (rc==SQLITE_OK ? "ok" : "failed"));
4587 return rc;
4588}
4589
4590/*
4591** Given the name of a database file, compute the name of its conch file.
4592** Store the conch filename in memory obtained from sqlite3_malloc().
4593** Make *pConchPath point to the new name. Return SQLITE_OK on success
4594** or SQLITE_NOMEM if unable to obtain memory.
4595**
4596** The caller is responsible for ensuring that the allocated memory
4597** space is eventually freed.
4598**
4599** *pConchPath is set to NULL if a memory allocation error occurs.
4600*/
4601static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
4602 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00004603 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00004604 char *conchPath; /* buffer in which to construct conch name */
4605
4606 /* Allocate space for the conch filename and initialize the name to
4607 ** the name of the original database file. */
4608 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
4609 if( conchPath==0 ){
4610 return SQLITE_NOMEM;
4611 }
4612 memcpy(conchPath, dbPath, len+1);
4613
4614 /* now insert a "." before the last / character */
4615 for( i=(len-1); i>=0; i-- ){
4616 if( conchPath[i]=='/' ){
4617 i++;
4618 break;
4619 }
4620 }
4621 conchPath[i]='.';
4622 while ( i<len ){
4623 conchPath[i+1]=dbPath[i];
4624 i++;
4625 }
4626
4627 /* append the "-conch" suffix to the file */
4628 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00004629 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00004630
4631 return SQLITE_OK;
4632}
4633
4634
4635/* Takes a fully configured proxy locking-style unix file and switches
4636** the local lock file path
4637*/
4638static int switchLockProxyPath(unixFile *pFile, const char *path) {
4639 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4640 char *oldPath = pCtx->lockProxyPath;
4641 int rc = SQLITE_OK;
4642
4643 if( pFile->locktype!=NO_LOCK ){
4644 return SQLITE_BUSY;
4645 }
4646
4647 /* nothing to do if the path is NULL, :auto: or matches the existing path */
4648 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
4649 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
4650 return SQLITE_OK;
4651 }else{
4652 unixFile *lockProxy = pCtx->lockProxy;
4653 pCtx->lockProxy=NULL;
4654 pCtx->conchHeld = 0;
4655 if( lockProxy!=NULL ){
4656 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
4657 if( rc ) return rc;
4658 sqlite3_free(lockProxy);
4659 }
4660 sqlite3_free(oldPath);
4661 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
4662 }
4663
4664 return rc;
4665}
4666
4667/*
4668** pFile is a file that has been opened by a prior xOpen call. dbPath
4669** is a string buffer at least MAXPATHLEN+1 characters in size.
4670**
4671** This routine find the filename associated with pFile and writes it
4672** int dbPath.
4673*/
4674static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00004675#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00004676 if( pFile->pMethod == &afpIoMethods ){
4677 /* afp style keeps a reference to the db path in the filePath field
4678 ** of the struct */
drhea678832008-12-10 19:26:22 +00004679 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh715ff302008-12-03 22:32:44 +00004680 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
4681 }else
4682#endif
4683 if( pFile->pMethod == &dotlockIoMethods ){
4684 /* dot lock style uses the locking context to store the dot lock
4685 ** file path */
4686 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
4687 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
4688 }else{
4689 /* all other styles use the locking context to store the db file path */
4690 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
4691 strcpy(dbPath, (char *)pFile->lockingContext);
4692 }
4693 return SQLITE_OK;
4694}
4695
4696/*
4697** Takes an already filled in unix file and alters it so all file locking
4698** will be performed on the local proxy lock file. The following fields
4699** are preserved in the locking context so that they can be restored and
4700** the unix structure properly cleaned up at close time:
4701** ->lockingContext
4702** ->pMethod
4703*/
4704static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
4705 proxyLockingContext *pCtx;
4706 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
4707 char *lockPath=NULL;
4708 int rc = SQLITE_OK;
4709
4710 if( pFile->locktype!=NO_LOCK ){
4711 return SQLITE_BUSY;
4712 }
4713 proxyGetDbPathForUnixFile(pFile, dbPath);
4714 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
4715 lockPath=NULL;
4716 }else{
4717 lockPath=(char *)path;
4718 }
4719
4720 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
4721 (lockPath ? lockPath : ":auto:"), getpid());
4722
4723 pCtx = sqlite3_malloc( sizeof(*pCtx) );
4724 if( pCtx==0 ){
4725 return SQLITE_NOMEM;
4726 }
4727 memset(pCtx, 0, sizeof(*pCtx));
4728
4729 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
4730 if( rc==SQLITE_OK ){
4731 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
4732 }
4733 if( rc==SQLITE_OK && lockPath ){
4734 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
4735 }
4736
4737 if( rc==SQLITE_OK ){
4738 /* all memory is allocated, proxys are created and assigned,
4739 ** switch the locking context and pMethod then return.
4740 */
4741 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
4742 pCtx->oldLockingContext = pFile->lockingContext;
4743 pFile->lockingContext = pCtx;
4744 pCtx->pOldMethod = pFile->pMethod;
4745 pFile->pMethod = &proxyIoMethods;
4746 }else{
4747 if( pCtx->conchFile ){
4748 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
4749 if( rc ) return rc;
4750 sqlite3_free(pCtx->conchFile);
4751 }
4752 sqlite3_free(pCtx->conchFilePath);
4753 sqlite3_free(pCtx);
4754 }
4755 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
4756 (rc==SQLITE_OK ? "ok" : "failed"));
4757 return rc;
4758}
4759
4760
4761/*
4762** This routine handles sqlite3_file_control() calls that are specific
4763** to proxy locking.
4764*/
4765static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
4766 switch( op ){
4767 case SQLITE_GET_LOCKPROXYFILE: {
4768 unixFile *pFile = (unixFile*)id;
4769 if( pFile->pMethod == &proxyIoMethods ){
4770 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4771 proxyTakeConch(pFile);
4772 if( pCtx->lockProxyPath ){
4773 *(const char **)pArg = pCtx->lockProxyPath;
4774 }else{
4775 *(const char **)pArg = ":auto: (not held)";
4776 }
4777 } else {
4778 *(const char **)pArg = NULL;
4779 }
4780 return SQLITE_OK;
4781 }
4782 case SQLITE_SET_LOCKPROXYFILE: {
4783 unixFile *pFile = (unixFile*)id;
4784 int rc = SQLITE_OK;
4785 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
4786 if( pArg==NULL || (const char *)pArg==0 ){
4787 if( isProxyStyle ){
4788 /* turn off proxy locking - not supported */
4789 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
4790 }else{
4791 /* turn off proxy locking - already off - NOOP */
4792 rc = SQLITE_OK;
4793 }
4794 }else{
4795 const char *proxyPath = (const char *)pArg;
4796 if( isProxyStyle ){
4797 proxyLockingContext *pCtx =
4798 (proxyLockingContext*)pFile->lockingContext;
4799 if( !strcmp(pArg, ":auto:")
4800 || (pCtx->lockProxyPath &&
4801 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
4802 ){
4803 rc = SQLITE_OK;
4804 }else{
4805 rc = switchLockProxyPath(pFile, proxyPath);
4806 }
4807 }else{
4808 /* turn on proxy file locking */
4809 rc = proxyTransformUnixFile(pFile, proxyPath);
4810 }
4811 }
4812 return rc;
4813 }
4814 default: {
4815 assert( 0 ); /* The call assures that only valid opcodes are sent */
4816 }
4817 }
4818 /*NOTREACHED*/
4819 return SQLITE_ERROR;
4820}
4821
4822/*
4823** Within this division (the proxying locking implementation) the procedures
4824** above this point are all utilities. The lock-related methods of the
4825** proxy-locking sqlite3_io_method object follow.
4826*/
4827
4828
4829/*
4830** This routine checks if there is a RESERVED lock held on the specified
4831** file by this or any other process. If such a lock is held, set *pResOut
4832** to a non-zero value otherwise *pResOut is set to zero. The return value
4833** is set to SQLITE_OK unless an I/O error occurs during lock checking.
4834*/
4835static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
4836 unixFile *pFile = (unixFile*)id;
4837 int rc = proxyTakeConch(pFile);
4838 if( rc==SQLITE_OK ){
4839 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4840 unixFile *proxy = pCtx->lockProxy;
4841 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
4842 }
4843 return rc;
4844}
4845
4846/*
4847** Lock the file with the lock specified by parameter locktype - one
4848** of the following:
4849**
4850** (1) SHARED_LOCK
4851** (2) RESERVED_LOCK
4852** (3) PENDING_LOCK
4853** (4) EXCLUSIVE_LOCK
4854**
4855** Sometimes when requesting one lock state, additional lock states
4856** are inserted in between. The locking might fail on one of the later
4857** transitions leaving the lock state different from what it started but
4858** still short of its goal. The following chart shows the allowed
4859** transitions and the inserted intermediate states:
4860**
4861** UNLOCKED -> SHARED
4862** SHARED -> RESERVED
4863** SHARED -> (PENDING) -> EXCLUSIVE
4864** RESERVED -> (PENDING) -> EXCLUSIVE
4865** PENDING -> EXCLUSIVE
4866**
4867** This routine will only increase a lock. Use the sqlite3OsUnlock()
4868** routine to lower a locking level.
4869*/
4870static int proxyLock(sqlite3_file *id, int locktype) {
4871 unixFile *pFile = (unixFile*)id;
4872 int rc = proxyTakeConch(pFile);
4873 if( rc==SQLITE_OK ){
4874 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4875 unixFile *proxy = pCtx->lockProxy;
4876 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
4877 pFile->locktype = proxy->locktype;
4878 }
4879 return rc;
4880}
4881
4882
4883/*
4884** Lower the locking level on file descriptor pFile to locktype. locktype
4885** must be either NO_LOCK or SHARED_LOCK.
4886**
4887** If the locking level of the file descriptor is already at or below
4888** the requested locking level, this routine is a no-op.
4889*/
4890static int proxyUnlock(sqlite3_file *id, int locktype) {
4891 unixFile *pFile = (unixFile*)id;
4892 int rc = proxyTakeConch(pFile);
4893 if( rc==SQLITE_OK ){
4894 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4895 unixFile *proxy = pCtx->lockProxy;
4896 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
4897 pFile->locktype = proxy->locktype;
4898 }
4899 return rc;
4900}
4901
4902/*
4903** Close a file that uses proxy locks.
4904*/
4905static int proxyClose(sqlite3_file *id) {
4906 if( id ){
4907 unixFile *pFile = (unixFile*)id;
4908 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4909 unixFile *lockProxy = pCtx->lockProxy;
4910 unixFile *conchFile = pCtx->conchFile;
4911 int rc = SQLITE_OK;
4912
4913 if( lockProxy ){
4914 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
4915 if( rc ) return rc;
4916 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
4917 if( rc ) return rc;
4918 sqlite3_free(lockProxy);
4919 pCtx->lockProxy = 0;
4920 }
4921 if( conchFile ){
4922 if( pCtx->conchHeld ){
4923 rc = proxyReleaseConch(pFile);
4924 if( rc ) return rc;
4925 }
4926 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
4927 if( rc ) return rc;
4928 sqlite3_free(conchFile);
4929 }
4930 sqlite3_free(pCtx->lockProxyPath);
4931 sqlite3_free(pCtx->conchFilePath);
4932 sqlite3_free(pCtx->dbPath);
4933 /* restore the original locking context and pMethod then close it */
4934 pFile->lockingContext = pCtx->oldLockingContext;
4935 pFile->pMethod = pCtx->pOldMethod;
4936 sqlite3_free(pCtx);
4937 return pFile->pMethod->xClose(id);
4938 }
4939 return SQLITE_OK;
4940}
4941
4942
4943
drhd2cb50b2009-01-09 21:41:17 +00004944#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00004945/*
4946** The proxy locking style is intended for use with AFP filesystems.
4947** And since AFP is only supported on MacOSX, the proxy locking is also
4948** restricted to MacOSX.
4949**
4950**
4951******************* End of the proxy lock implementation **********************
4952******************************************************************************/
4953
drh734c9862008-11-28 15:37:20 +00004954/*
danielk1977e339d652008-06-28 11:23:00 +00004955** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00004956**
4957** This routine registers all VFS implementations for unix-like operating
4958** systems. This routine, and the sqlite3_os_end() routine that follows,
4959** should be the only routines in this file that are visible from other
4960** files.
drh6b9d6dd2008-12-03 19:34:47 +00004961**
4962** This routine is called once during SQLite initialization and by a
4963** single thread. The memory allocation and mutex subsystems have not
4964** necessarily been initialized when this routine is called, and so they
4965** should not be used.
drh153c62c2007-08-24 03:51:33 +00004966*/
danielk1977c0fa4c52008-06-25 17:19:00 +00004967int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00004968 /*
4969 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00004970 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
4971 ** to the "finder" function. (pAppData is a pointer to a pointer because
4972 ** silly C90 rules prohibit a void* from being cast to a function pointer
4973 ** and so we have to go through the intermediate pointer to avoid problems
4974 ** when compiling with -pedantic-errors on GCC.)
4975 **
4976 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00004977 ** finder-function. The finder-function returns a pointer to the
4978 ** sqlite_io_methods object that implements the desired locking
4979 ** behaviors. See the division above that contains the IOMETHODS
4980 ** macro for addition information on finder-functions.
4981 **
4982 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
4983 ** object. But the "autolockIoFinder" available on MacOSX does a little
4984 ** more than that; it looks at the filesystem type that hosts the
4985 ** database file and tries to choose an locking method appropriate for
4986 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00004987 */
drh7708e972008-11-29 00:56:52 +00004988 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00004989 1, /* iVersion */ \
4990 sizeof(unixFile), /* szOsFile */ \
4991 MAX_PATHNAME, /* mxPathname */ \
4992 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00004993 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00004994 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00004995 unixOpen, /* xOpen */ \
4996 unixDelete, /* xDelete */ \
4997 unixAccess, /* xAccess */ \
4998 unixFullPathname, /* xFullPathname */ \
4999 unixDlOpen, /* xDlOpen */ \
5000 unixDlError, /* xDlError */ \
5001 unixDlSym, /* xDlSym */ \
5002 unixDlClose, /* xDlClose */ \
5003 unixRandomness, /* xRandomness */ \
5004 unixSleep, /* xSleep */ \
5005 unixCurrentTime, /* xCurrentTime */ \
5006 unixGetLastError /* xGetLastError */ \
5007 }
5008
drh6b9d6dd2008-12-03 19:34:47 +00005009 /*
5010 ** All default VFSes for unix are contained in the following array.
5011 **
5012 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5013 ** by the SQLite core when the VFS is registered. So the following
5014 ** array cannot be const.
5015 */
danielk1977e339d652008-06-28 11:23:00 +00005016 static sqlite3_vfs aVfs[] = {
drhd2cb50b2009-01-09 21:41:17 +00005017#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005018 UNIXVFS("unix", autolockIoFinder ),
5019#else
5020 UNIXVFS("unix", posixIoFinder ),
5021#endif
5022 UNIXVFS("unix-none", nolockIoFinder ),
5023 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005024#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005025 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005026#endif
5027#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005028 UNIXVFS("unix-posix", posixIoFinder ),
5029 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005030#endif
drhd2cb50b2009-01-09 21:41:17 +00005031#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005032 UNIXVFS("unix-afp", afpIoFinder ),
5033 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005034#endif
drh153c62c2007-08-24 03:51:33 +00005035 };
drh6b9d6dd2008-12-03 19:34:47 +00005036 unsigned int i; /* Loop counter */
5037
5038 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005039 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005040 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005041 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005042 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005043}
danielk1977e339d652008-06-28 11:23:00 +00005044
5045/*
drh6b9d6dd2008-12-03 19:34:47 +00005046** Shutdown the operating system interface.
5047**
5048** Some operating systems might need to do some cleanup in this routine,
5049** to release dynamically allocated objects. But not on unix.
5050** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005051*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005052int sqlite3_os_end(void){
5053 return SQLITE_OK;
5054}
drhdce8bdb2007-08-16 13:01:44 +00005055
danielk197729bafea2008-06-26 10:41:19 +00005056#endif /* SQLITE_OS_UNIX */