blob: 9ac7f7b2bfe757c88043d571c825063b0dde0e06 [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**
drheb0d74f2009-02-03 15:27:02 +000046** $Id: os_unix.c,v 1.239 2009/02/03 15:27:02 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
drheb0d74f2009-02-03 15:27:02 +0000923#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000924 /* On OS X on an msdos filesystem, the inode number is reported
925 ** incorrectly for zero-size files. See ticket #3260. To work
926 ** around this problem (we consider it a bug in OS X, not SQLite)
927 ** we always increase the file size to 1 by writing a single byte
928 ** prior to accessing the inode number. The one byte written is
929 ** an ASCII 'S' character which also happens to be the first byte
930 ** in the header of every SQLite database. In this way, if there
931 ** is a race condition such that another thread has already populated
932 ** the first page of the database, no damage is done.
933 */
934 if( statbuf.st_size==0 ){
drheb0d74f2009-02-03 15:27:02 +0000935 rc = write(fd, "S", 1);
936 if( rc!=1 ){
937 return SQLITE_IOERR;
938 }
drh6c7d5c52008-11-21 20:32:33 +0000939 rc = fstat(fd, &statbuf);
940 if( rc!=0 ){
941 pFile->lastErrno = errno;
942 return SQLITE_IOERR;
943 }
944 }
drheb0d74f2009-02-03 15:27:02 +0000945#endif
drh6c7d5c52008-11-21 20:32:33 +0000946
947 memset(&lockKey, 0, sizeof(lockKey));
948 lockKey.fid.dev = statbuf.st_dev;
949#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000950 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000951#else
952 lockKey.fid.ino = statbuf.st_ino;
953#endif
drh734c9862008-11-28 15:37:20 +0000954#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000955 if( threadsOverrideEachOthersLocks<0 ){
956 testThreadLockingBehavior(fd);
957 }
958 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
959#endif
960 fileId = lockKey.fid;
961 if( ppLock!=0 ){
962 pLock = lockList;
963 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
964 pLock = pLock->pNext;
965 }
966 if( pLock==0 ){
967 pLock = sqlite3_malloc( sizeof(*pLock) );
968 if( pLock==0 ){
969 rc = SQLITE_NOMEM;
970 goto exit_findlockinfo;
971 }
972 pLock->lockKey = lockKey;
973 pLock->nRef = 1;
974 pLock->cnt = 0;
975 pLock->locktype = 0;
976 pLock->pNext = lockList;
977 pLock->pPrev = 0;
978 if( lockList ) lockList->pPrev = pLock;
979 lockList = pLock;
980 }else{
981 pLock->nRef++;
982 }
983 *ppLock = pLock;
984 }
985 if( ppOpen!=0 ){
986 pOpen = openList;
987 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
988 pOpen = pOpen->pNext;
989 }
990 if( pOpen==0 ){
991 pOpen = sqlite3_malloc( sizeof(*pOpen) );
992 if( pOpen==0 ){
993 releaseLockInfo(pLock);
994 rc = SQLITE_NOMEM;
995 goto exit_findlockinfo;
996 }
997 pOpen->fileId = fileId;
998 pOpen->nRef = 1;
999 pOpen->nLock = 0;
1000 pOpen->nPending = 0;
1001 pOpen->aPending = 0;
1002 pOpen->pNext = openList;
1003 pOpen->pPrev = 0;
1004 if( openList ) openList->pPrev = pOpen;
1005 openList = pOpen;
1006#if OS_VXWORKS
1007 pOpen->pSem = NULL;
1008 pOpen->aSemName[0] = '\0';
1009#endif
1010 }else{
1011 pOpen->nRef++;
1012 }
1013 *ppOpen = pOpen;
1014 }
1015
1016exit_findlockinfo:
1017 return rc;
1018}
drh6c7d5c52008-11-21 20:32:33 +00001019
drh7708e972008-11-29 00:56:52 +00001020/*
1021** If we are currently in a different thread than the thread that the
1022** unixFile argument belongs to, then transfer ownership of the unixFile
1023** over to the current thread.
1024**
1025** A unixFile is only owned by a thread on systems that use LinuxThreads.
1026**
1027** Ownership transfer is only allowed if the unixFile is currently unlocked.
1028** If the unixFile is locked and an ownership is wrong, then return
1029** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1030*/
1031#if SQLITE_THREADSAFE && defined(__linux__)
1032static int transferOwnership(unixFile *pFile){
1033 int rc;
1034 pthread_t hSelf;
1035 if( threadsOverrideEachOthersLocks ){
1036 /* Ownership transfers not needed on this system */
1037 return SQLITE_OK;
1038 }
1039 hSelf = pthread_self();
1040 if( pthread_equal(pFile->tid, hSelf) ){
1041 /* We are still in the same thread */
1042 OSTRACE1("No-transfer, same thread\n");
1043 return SQLITE_OK;
1044 }
1045 if( pFile->locktype!=NO_LOCK ){
1046 /* We cannot change ownership while we are holding a lock! */
1047 return SQLITE_MISUSE;
1048 }
1049 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1050 pFile->h, pFile->tid, hSelf);
1051 pFile->tid = hSelf;
1052 if (pFile->pLock != NULL) {
1053 releaseLockInfo(pFile->pLock);
1054 rc = findLockInfo(pFile, &pFile->pLock, 0);
1055 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1056 locktypeName(pFile->locktype),
1057 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1058 return rc;
1059 } else {
1060 return SQLITE_OK;
1061 }
1062}
1063#else /* if not SQLITE_THREADSAFE */
1064 /* On single-threaded builds, ownership transfer is a no-op */
1065# define transferOwnership(X) SQLITE_OK
1066#endif /* SQLITE_THREADSAFE */
1067
aswift5b1a2562008-08-22 00:22:35 +00001068
1069/*
danielk197713adf8a2004-06-03 16:08:41 +00001070** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001071** file by this or any other process. If such a lock is held, set *pResOut
1072** to a non-zero value otherwise *pResOut is set to zero. The return value
1073** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001074*/
danielk1977861f7452008-06-05 11:39:11 +00001075static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001076 int rc = SQLITE_OK;
1077 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001078 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001079
danielk1977861f7452008-06-05 11:39:11 +00001080 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1081
drh054889e2005-11-30 03:20:31 +00001082 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001083 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001084
1085 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001086 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001087 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001088 }
1089
drh2ac3ee92004-06-07 16:27:46 +00001090 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001091 */
aswift5b1a2562008-08-22 00:22:35 +00001092 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001093 struct flock lock;
1094 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001095 lock.l_start = RESERVED_BYTE;
1096 lock.l_len = 1;
1097 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001098 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1099 int tErrno = errno;
1100 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1101 pFile->lastErrno = tErrno;
1102 } else if( lock.l_type!=F_UNLCK ){
1103 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001104 }
1105 }
1106
drh6c7d5c52008-11-21 20:32:33 +00001107 unixLeaveMutex();
aswift5b1a2562008-08-22 00:22:35 +00001108 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001109
aswift5b1a2562008-08-22 00:22:35 +00001110 *pResOut = reserved;
1111 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001112}
1113
1114/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001115** Lock the file with the lock specified by parameter locktype - one
1116** of the following:
1117**
drh2ac3ee92004-06-07 16:27:46 +00001118** (1) SHARED_LOCK
1119** (2) RESERVED_LOCK
1120** (3) PENDING_LOCK
1121** (4) EXCLUSIVE_LOCK
1122**
drhb3e04342004-06-08 00:47:47 +00001123** Sometimes when requesting one lock state, additional lock states
1124** are inserted in between. The locking might fail on one of the later
1125** transitions leaving the lock state different from what it started but
1126** still short of its goal. The following chart shows the allowed
1127** transitions and the inserted intermediate states:
1128**
1129** UNLOCKED -> SHARED
1130** SHARED -> RESERVED
1131** SHARED -> (PENDING) -> EXCLUSIVE
1132** RESERVED -> (PENDING) -> EXCLUSIVE
1133** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001134**
drha6abd042004-06-09 17:37:22 +00001135** This routine will only increase a lock. Use the sqlite3OsUnlock()
1136** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001137*/
danielk197762079062007-08-15 17:08:46 +00001138static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001139 /* The following describes the implementation of the various locks and
1140 ** lock transitions in terms of the POSIX advisory shared and exclusive
1141 ** lock primitives (called read-locks and write-locks below, to avoid
1142 ** confusion with SQLite lock names). The algorithms are complicated
1143 ** slightly in order to be compatible with windows systems simultaneously
1144 ** accessing the same database file, in case that is ever required.
1145 **
1146 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1147 ** byte', each single bytes at well known offsets, and the 'shared byte
1148 ** range', a range of 510 bytes at a well known offset.
1149 **
1150 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1151 ** byte'. If this is successful, a random byte from the 'shared byte
1152 ** range' is read-locked and the lock on the 'pending byte' released.
1153 **
danielk197790ba3bd2004-06-25 08:32:25 +00001154 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1155 ** A RESERVED lock is implemented by grabbing a write-lock on the
1156 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001157 **
1158 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001159 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1160 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1161 ** obtained, but existing SHARED locks are allowed to persist. A process
1162 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1163 ** This property is used by the algorithm for rolling back a journal file
1164 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001165 **
danielk197790ba3bd2004-06-25 08:32:25 +00001166 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1167 ** implemented by obtaining a write-lock on the entire 'shared byte
1168 ** range'. Since all other locks require a read-lock on one of the bytes
1169 ** within this range, this ensures that no other locks are held on the
1170 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001171 **
1172 ** The reason a single byte cannot be used instead of the 'shared byte
1173 ** range' is that some versions of windows do not support read-locks. By
1174 ** locking a random byte from a range, concurrent SHARED locks may exist
1175 ** even if the locking primitive used is always a write-lock.
1176 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001177 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001178 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001179 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001180 struct flock lock;
1181 int s;
1182
drh054889e2005-11-30 03:20:31 +00001183 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001184 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001185 locktypeName(locktype), locktypeName(pFile->locktype),
1186 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001187
1188 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001189 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001190 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001191 */
drh054889e2005-11-30 03:20:31 +00001192 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001193 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001194 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001195 return SQLITE_OK;
1196 }
1197
drhb3e04342004-06-08 00:47:47 +00001198 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001199 */
drh054889e2005-11-30 03:20:31 +00001200 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001201 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001202 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001203
drh054889e2005-11-30 03:20:31 +00001204 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001205 */
drh6c7d5c52008-11-21 20:32:33 +00001206 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001207
drh029b44b2006-01-15 00:13:15 +00001208 /* Make sure the current thread owns the pFile.
1209 */
1210 rc = transferOwnership(pFile);
1211 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001212 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001213 return rc;
1214 }
drh64b1bea2006-01-15 02:30:57 +00001215 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001216
danielk1977ad94b582007-08-20 06:44:22 +00001217 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001218 ** handle that precludes the requested lock, return BUSY.
1219 */
drh054889e2005-11-30 03:20:31 +00001220 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001221 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001222 ){
1223 rc = SQLITE_BUSY;
1224 goto end_lock;
1225 }
1226
1227 /* If a SHARED lock is requested, and some thread using this PID already
1228 ** has a SHARED or RESERVED lock, then increment reference counts and
1229 ** return SQLITE_OK.
1230 */
1231 if( locktype==SHARED_LOCK &&
1232 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1233 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001234 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001235 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001236 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001237 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001238 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001239 goto end_lock;
1240 }
1241
danielk197713adf8a2004-06-03 16:08:41 +00001242 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001243
danielk19779a1d0ab2004-06-01 14:09:28 +00001244 lock.l_whence = SEEK_SET;
1245
drh3cde3bb2004-06-12 02:17:14 +00001246 /* A PENDING lock is needed before acquiring a SHARED lock and before
1247 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1248 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001249 */
drh3cde3bb2004-06-12 02:17:14 +00001250 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001251 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001252 ){
danielk1977489468c2004-06-28 08:25:47 +00001253 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001254 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001255 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001256 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001257 int tErrno = errno;
1258 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1259 if( IS_LOCK_ERROR(rc) ){
1260 pFile->lastErrno = tErrno;
1261 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001262 goto end_lock;
1263 }
drh3cde3bb2004-06-12 02:17:14 +00001264 }
1265
1266
1267 /* If control gets to this point, then actually go ahead and make
1268 ** operating system calls for the specified lock.
1269 */
1270 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001271 int tErrno = 0;
drh3cde3bb2004-06-12 02:17:14 +00001272 assert( pLock->cnt==0 );
1273 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001274
drh2ac3ee92004-06-07 16:27:46 +00001275 /* Now get the read-lock */
1276 lock.l_start = SHARED_FIRST;
1277 lock.l_len = SHARED_SIZE;
aswift5b1a2562008-08-22 00:22:35 +00001278 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1279 tErrno = errno;
1280 }
drh2ac3ee92004-06-07 16:27:46 +00001281 /* Drop the temporary PENDING lock */
1282 lock.l_start = PENDING_BYTE;
1283 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001284 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001285 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001286 if( s != -1 ){
1287 /* This could happen with a network mount */
1288 tErrno = errno;
1289 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1290 if( IS_LOCK_ERROR(rc) ){
1291 pFile->lastErrno = tErrno;
1292 }
1293 goto end_lock;
1294 }
drh2b4b5962005-06-15 17:47:55 +00001295 }
drhe2396a12007-03-29 20:19:58 +00001296 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001297 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1298 if( IS_LOCK_ERROR(rc) ){
1299 pFile->lastErrno = tErrno;
1300 }
drhbbd42a62004-05-22 17:41:58 +00001301 }else{
drh054889e2005-11-30 03:20:31 +00001302 pFile->locktype = SHARED_LOCK;
1303 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001304 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001305 }
drh3cde3bb2004-06-12 02:17:14 +00001306 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1307 /* We are trying for an exclusive lock but another thread in this
1308 ** same process is still holding a shared lock. */
1309 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001310 }else{
drh3cde3bb2004-06-12 02:17:14 +00001311 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001312 ** assumed that there is a SHARED or greater lock on the file
1313 ** already.
1314 */
drh054889e2005-11-30 03:20:31 +00001315 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001316 lock.l_type = F_WRLCK;
1317 switch( locktype ){
1318 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001319 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001320 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001321 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001322 lock.l_start = SHARED_FIRST;
1323 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001324 break;
1325 default:
1326 assert(0);
1327 }
drh054889e2005-11-30 03:20:31 +00001328 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001329 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001330 int tErrno = errno;
1331 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1332 if( IS_LOCK_ERROR(rc) ){
1333 pFile->lastErrno = tErrno;
1334 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001335 }
drhbbd42a62004-05-22 17:41:58 +00001336 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001337
drh8f941bc2009-01-14 23:03:40 +00001338
1339#ifndef NDEBUG
1340 /* Set up the transaction-counter change checking flags when
1341 ** transitioning from a SHARED to a RESERVED lock. The change
1342 ** from SHARED to RESERVED marks the beginning of a normal
1343 ** write operation (not a hot journal rollback).
1344 */
1345 if( rc==SQLITE_OK
1346 && pFile->locktype<=SHARED_LOCK
1347 && locktype==RESERVED_LOCK
1348 ){
1349 pFile->transCntrChng = 0;
1350 pFile->dbUpdate = 0;
1351 pFile->inNormalWrite = 1;
1352 }
1353#endif
1354
1355
danielk1977ecb2a962004-06-02 06:30:16 +00001356 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001357 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001358 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001359 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001360 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001361 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001362 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001363
1364end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001365 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001366 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001367 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001368 return rc;
1369}
1370
1371/*
drh054889e2005-11-30 03:20:31 +00001372** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001373** must be either NO_LOCK or SHARED_LOCK.
1374**
1375** If the locking level of the file descriptor is already at or below
1376** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001377*/
danielk197762079062007-08-15 17:08:46 +00001378static int unixUnlock(sqlite3_file *id, int locktype){
drh6c7d5c52008-11-21 20:32:33 +00001379 struct unixLockInfo *pLock;
drha6abd042004-06-09 17:37:22 +00001380 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001381 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001382 unixFile *pFile = (unixFile*)id;
drh1aa5af12008-03-07 19:51:14 +00001383 int h;
drha6abd042004-06-09 17:37:22 +00001384
drh054889e2005-11-30 03:20:31 +00001385 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001386 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001387 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001388
1389 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001390 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001391 return SQLITE_OK;
1392 }
drhf1a221e2006-01-15 17:27:17 +00001393 if( CHECK_THREADID(pFile) ){
1394 return SQLITE_MISUSE;
1395 }
drh6c7d5c52008-11-21 20:32:33 +00001396 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001397 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001398 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001399 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001400 if( pFile->locktype>SHARED_LOCK ){
1401 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001402 SimulateIOErrorBenign(1);
1403 SimulateIOError( h=(-1) )
1404 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001405
1406#ifndef NDEBUG
1407 /* When reducing a lock such that other processes can start
1408 ** reading the database file again, make sure that the
1409 ** transaction counter was updated if any part of the database
1410 ** file changed. If the transaction counter is not updated,
1411 ** other connections to the same file might not realize that
1412 ** the file has changed and hence might not know to flush their
1413 ** cache. The use of a stale cache can lead to database corruption.
1414 */
1415 assert( pFile->inNormalWrite==0
1416 || pFile->dbUpdate==0
1417 || pFile->transCntrChng==1 );
1418 pFile->inNormalWrite = 0;
1419#endif
1420
1421
drh9c105bb2004-10-02 20:38:28 +00001422 if( locktype==SHARED_LOCK ){
1423 lock.l_type = F_RDLCK;
1424 lock.l_whence = SEEK_SET;
1425 lock.l_start = SHARED_FIRST;
1426 lock.l_len = SHARED_SIZE;
drh1aa5af12008-03-07 19:51:14 +00001427 if( fcntl(h, F_SETLK, &lock)==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001428 int tErrno = errno;
1429 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1430 if( IS_LOCK_ERROR(rc) ){
1431 pFile->lastErrno = tErrno;
1432 }
1433 goto end_unlock;
drh9c105bb2004-10-02 20:38:28 +00001434 }
1435 }
drhbbd42a62004-05-22 17:41:58 +00001436 lock.l_type = F_UNLCK;
1437 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001438 lock.l_start = PENDING_BYTE;
1439 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001440 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001441 pLock->locktype = SHARED_LOCK;
1442 }else{
aswift5b1a2562008-08-22 00:22:35 +00001443 int tErrno = errno;
1444 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1445 if( IS_LOCK_ERROR(rc) ){
1446 pFile->lastErrno = tErrno;
1447 }
1448 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001449 }
drhbbd42a62004-05-22 17:41:58 +00001450 }
drha6abd042004-06-09 17:37:22 +00001451 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001452 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001453
drha6abd042004-06-09 17:37:22 +00001454 /* Decrement the shared lock counter. Release the lock using an
1455 ** OS call only when all threads in this same process have released
1456 ** the lock.
1457 */
1458 pLock->cnt--;
1459 if( pLock->cnt==0 ){
1460 lock.l_type = F_UNLCK;
1461 lock.l_whence = SEEK_SET;
1462 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001463 SimulateIOErrorBenign(1);
1464 SimulateIOError( h=(-1) )
1465 SimulateIOErrorBenign(0);
1466 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001467 pLock->locktype = NO_LOCK;
1468 }else{
aswift5b1a2562008-08-22 00:22:35 +00001469 int tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001470 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001471 if( IS_LOCK_ERROR(rc) ){
1472 pFile->lastErrno = tErrno;
1473 }
drh1aa5af12008-03-07 19:51:14 +00001474 pLock->cnt = 1;
aswift5b1a2562008-08-22 00:22:35 +00001475 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001476 }
drha6abd042004-06-09 17:37:22 +00001477 }
1478
drhbbd42a62004-05-22 17:41:58 +00001479 /* Decrement the count of locks against this same file. When the
1480 ** count reaches zero, close any other file descriptors whose close
1481 ** was deferred because of outstanding locks.
1482 */
drh1aa5af12008-03-07 19:51:14 +00001483 if( rc==SQLITE_OK ){
1484 pOpen = pFile->pOpen;
1485 pOpen->nLock--;
1486 assert( pOpen->nLock>=0 );
1487 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1488 int i;
1489 for(i=0; i<pOpen->nPending; i++){
aswiftaebf4132008-11-21 00:10:35 +00001490 /* close pending fds, but if closing fails don't free the array
1491 ** assign -1 to the successfully closed descriptors and record the
1492 ** error. The next attempt to unlock will try again. */
1493 if( pOpen->aPending[i] < 0 ) continue;
1494 if( close(pOpen->aPending[i]) ){
1495 pFile->lastErrno = errno;
1496 rc = SQLITE_IOERR_CLOSE;
1497 }else{
1498 pOpen->aPending[i] = -1;
1499 }
drh1aa5af12008-03-07 19:51:14 +00001500 }
aswiftaebf4132008-11-21 00:10:35 +00001501 if( rc==SQLITE_OK ){
1502 sqlite3_free(pOpen->aPending);
1503 pOpen->nPending = 0;
1504 pOpen->aPending = 0;
1505 }
drhbbd42a62004-05-22 17:41:58 +00001506 }
drhbbd42a62004-05-22 17:41:58 +00001507 }
1508 }
aswift5b1a2562008-08-22 00:22:35 +00001509
1510end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001511 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001512 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001513 return rc;
drhbbd42a62004-05-22 17:41:58 +00001514}
1515
1516/*
danielk1977e339d652008-06-28 11:23:00 +00001517** This function performs the parts of the "close file" operation
1518** common to all locking schemes. It closes the directory and file
1519** handles, if they are valid, and sets all fields of the unixFile
1520** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001521**
1522** It is *not* necessary to hold the mutex when this routine is called,
1523** even on VxWorks. A mutex will be acquired on VxWorks by the
1524** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001525*/
1526static int closeUnixFile(sqlite3_file *id){
1527 unixFile *pFile = (unixFile*)id;
1528 if( pFile ){
1529 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001530 int err = close(pFile->dirfd);
1531 if( err ){
1532 pFile->lastErrno = errno;
1533 return SQLITE_IOERR_DIR_CLOSE;
1534 }else{
1535 pFile->dirfd=-1;
1536 }
danielk1977e339d652008-06-28 11:23:00 +00001537 }
1538 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001539 int err = close(pFile->h);
1540 if( err ){
1541 pFile->lastErrno = errno;
1542 return SQLITE_IOERR_CLOSE;
1543 }
danielk1977e339d652008-06-28 11:23:00 +00001544 }
drh6c7d5c52008-11-21 20:32:33 +00001545#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001546 if( pFile->pId ){
1547 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001548 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001549 }
drh107886a2008-11-21 22:21:50 +00001550 vxworksReleaseFileId(pFile->pId);
1551 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001552 }
1553#endif
danielk1977e339d652008-06-28 11:23:00 +00001554 OSTRACE2("CLOSE %-3d\n", pFile->h);
1555 OpenCounter(-1);
1556 memset(pFile, 0, sizeof(unixFile));
1557 }
1558 return SQLITE_OK;
1559}
1560
1561/*
danielk1977e3026632004-06-22 11:29:02 +00001562** Close a file.
1563*/
danielk197762079062007-08-15 17:08:46 +00001564static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001565 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001566 if( id ){
1567 unixFile *pFile = (unixFile *)id;
1568 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001569 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001570 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001571 /* If there are outstanding locks, do not actually close the file just
1572 ** yet because that would clear those locks. Instead, add the file
1573 ** descriptor to pOpen->aPending. It will be automatically closed when
1574 ** the last lock is cleared.
1575 */
1576 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00001577 struct unixOpenCnt *pOpen = pFile->pOpen;
drhda0e7682008-07-30 15:27:54 +00001578 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e339d652008-06-28 11:23:00 +00001579 if( aNew==0 ){
1580 /* If a malloc fails, just leak the file descriptor */
1581 }else{
1582 pOpen->aPending = aNew;
1583 pOpen->aPending[pOpen->nPending] = pFile->h;
1584 pOpen->nPending++;
1585 pFile->h = -1;
1586 }
danielk1977e3026632004-06-22 11:29:02 +00001587 }
danielk1977e339d652008-06-28 11:23:00 +00001588 releaseLockInfo(pFile->pLock);
1589 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001590 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001591 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001592 }
aswiftaebf4132008-11-21 00:10:35 +00001593 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001594}
1595
drh734c9862008-11-28 15:37:20 +00001596/************** End of the posix advisory lock implementation *****************
1597******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001598
drh734c9862008-11-28 15:37:20 +00001599/******************************************************************************
1600****************************** No-op Locking **********************************
1601**
1602** Of the various locking implementations available, this is by far the
1603** simplest: locking is ignored. No attempt is made to lock the database
1604** file for reading or writing.
1605**
1606** This locking mode is appropriate for use on read-only databases
1607** (ex: databases that are burned into CD-ROM, for example.) It can
1608** also be used if the application employs some external mechanism to
1609** prevent simultaneous access of the same database by two or more
1610** database connections. But there is a serious risk of database
1611** corruption if this locking mode is used in situations where multiple
1612** database connections are accessing the same database file at the same
1613** time and one or more of those connections are writing.
1614*/
drhbfe66312006-10-03 17:40:40 +00001615
drh734c9862008-11-28 15:37:20 +00001616static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1617 UNUSED_PARAMETER(NotUsed);
1618 *pResOut = 0;
1619 return SQLITE_OK;
1620}
drh734c9862008-11-28 15:37:20 +00001621static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1622 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1623 return SQLITE_OK;
1624}
drh734c9862008-11-28 15:37:20 +00001625static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1626 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1627 return SQLITE_OK;
1628}
1629
1630/*
drh9b35ea62008-11-29 02:20:26 +00001631** Close the file.
drh734c9862008-11-28 15:37:20 +00001632*/
1633static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001634 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001635}
1636
1637/******************* End of the no-op lock implementation *********************
1638******************************************************************************/
1639
1640/******************************************************************************
1641************************* Begin dot-file Locking ******************************
1642**
1643** The dotfile locking implementation uses the existing of separate lock
1644** files in order to control access to the database. This works on just
1645** about every filesystem imaginable. But there are serious downsides:
1646**
1647** (1) There is zero concurrency. A single reader blocks all other
1648** connections from reading or writing the database.
1649**
1650** (2) An application crash or power loss can leave stale lock files
1651** sitting around that need to be cleared manually.
1652**
1653** Nevertheless, a dotlock is an appropriate locking mode for use if no
1654** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001655**
1656** Dotfile locking works by creating a file in the same directory as the
1657** database and with the same name but with a ".lock" extension added.
1658** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1659** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001660*/
1661
1662/*
1663** The file suffix added to the data base filename in order to create the
1664** lock file.
1665*/
1666#define DOTLOCK_SUFFIX ".lock"
1667
drh7708e972008-11-29 00:56:52 +00001668/*
1669** This routine checks if there is a RESERVED lock held on the specified
1670** file by this or any other process. If such a lock is held, set *pResOut
1671** to a non-zero value otherwise *pResOut is set to zero. The return value
1672** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1673**
1674** In dotfile locking, either a lock exists or it does not. So in this
1675** variation of CheckReservedLock(), *pResOut is set to true if any lock
1676** is held on the file and false if the file is unlocked.
1677*/
drh734c9862008-11-28 15:37:20 +00001678static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1679 int rc = SQLITE_OK;
1680 int reserved = 0;
1681 unixFile *pFile = (unixFile*)id;
1682
1683 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1684
1685 assert( pFile );
1686
1687 /* Check if a thread in this process holds such a lock */
1688 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001689 /* Either this connection or some other connection in the same process
1690 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001691 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001692 }else{
1693 /* The lock is held if and only if the lockfile exists */
1694 const char *zLockFile = (const char*)pFile->lockingContext;
1695 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001696 }
1697 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001698 *pResOut = reserved;
1699 return rc;
1700}
1701
drh7708e972008-11-29 00:56:52 +00001702/*
1703** Lock the file with the lock specified by parameter locktype - one
1704** of the following:
1705**
1706** (1) SHARED_LOCK
1707** (2) RESERVED_LOCK
1708** (3) PENDING_LOCK
1709** (4) EXCLUSIVE_LOCK
1710**
1711** Sometimes when requesting one lock state, additional lock states
1712** are inserted in between. The locking might fail on one of the later
1713** transitions leaving the lock state different from what it started but
1714** still short of its goal. The following chart shows the allowed
1715** transitions and the inserted intermediate states:
1716**
1717** UNLOCKED -> SHARED
1718** SHARED -> RESERVED
1719** SHARED -> (PENDING) -> EXCLUSIVE
1720** RESERVED -> (PENDING) -> EXCLUSIVE
1721** PENDING -> EXCLUSIVE
1722**
1723** This routine will only increase a lock. Use the sqlite3OsUnlock()
1724** routine to lower a locking level.
1725**
1726** With dotfile locking, we really only support state (4): EXCLUSIVE.
1727** But we track the other locking levels internally.
1728*/
drh734c9862008-11-28 15:37:20 +00001729static int dotlockLock(sqlite3_file *id, int locktype) {
1730 unixFile *pFile = (unixFile*)id;
1731 int fd;
1732 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001733 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001734
drh7708e972008-11-29 00:56:52 +00001735
1736 /* If we have any lock, then the lock file already exists. All we have
1737 ** to do is adjust our internal record of the lock level.
1738 */
1739 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001740 pFile->locktype = locktype;
1741#if !OS_VXWORKS
1742 /* Always update the timestamp on the old file */
1743 utimes(zLockFile, NULL);
1744#endif
drh7708e972008-11-29 00:56:52 +00001745 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001746 }
1747
1748 /* grab an exclusive lock */
1749 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1750 if( fd<0 ){
1751 /* failed to open/create the file, someone else may have stolen the lock */
1752 int tErrno = errno;
1753 if( EEXIST == tErrno ){
1754 rc = SQLITE_BUSY;
1755 } else {
1756 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1757 if( IS_LOCK_ERROR(rc) ){
1758 pFile->lastErrno = tErrno;
1759 }
1760 }
drh7708e972008-11-29 00:56:52 +00001761 return rc;
drh734c9862008-11-28 15:37:20 +00001762 }
1763 if( close(fd) ){
1764 pFile->lastErrno = errno;
1765 rc = SQLITE_IOERR_CLOSE;
1766 }
1767
1768 /* got it, set the type and return ok */
1769 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001770 return rc;
1771}
1772
drh7708e972008-11-29 00:56:52 +00001773/*
1774** Lower the locking level on file descriptor pFile to locktype. locktype
1775** must be either NO_LOCK or SHARED_LOCK.
1776**
1777** If the locking level of the file descriptor is already at or below
1778** the requested locking level, this routine is a no-op.
1779**
1780** When the locking level reaches NO_LOCK, delete the lock file.
1781*/
drh734c9862008-11-28 15:37:20 +00001782static int dotlockUnlock(sqlite3_file *id, int locktype) {
1783 unixFile *pFile = (unixFile*)id;
1784 char *zLockFile = (char *)pFile->lockingContext;
1785
1786 assert( pFile );
1787 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1788 pFile->locktype, getpid());
1789 assert( locktype<=SHARED_LOCK );
1790
1791 /* no-op if possible */
1792 if( pFile->locktype==locktype ){
1793 return SQLITE_OK;
1794 }
drh7708e972008-11-29 00:56:52 +00001795
1796 /* To downgrade to shared, simply update our internal notion of the
1797 ** lock state. No need to mess with the file on disk.
1798 */
1799 if( locktype==SHARED_LOCK ){
1800 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001801 return SQLITE_OK;
1802 }
1803
drh7708e972008-11-29 00:56:52 +00001804 /* To fully unlock the database, delete the lock file */
1805 assert( locktype==NO_LOCK );
1806 if( unlink(zLockFile) ){
drh734c9862008-11-28 15:37:20 +00001807 int rc, tErrno = errno;
1808 if( ENOENT != tErrno ){
1809 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1810 }
1811 if( IS_LOCK_ERROR(rc) ){
1812 pFile->lastErrno = tErrno;
1813 }
1814 return rc;
1815 }
1816 pFile->locktype = NO_LOCK;
1817 return SQLITE_OK;
1818}
1819
1820/*
drh9b35ea62008-11-29 02:20:26 +00001821** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001822*/
1823static int dotlockClose(sqlite3_file *id) {
1824 int rc;
1825 if( id ){
1826 unixFile *pFile = (unixFile*)id;
1827 dotlockUnlock(id, NO_LOCK);
1828 sqlite3_free(pFile->lockingContext);
1829 }
drh734c9862008-11-28 15:37:20 +00001830 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001831 return rc;
1832}
1833/****************** End of the dot-file lock implementation *******************
1834******************************************************************************/
1835
1836/******************************************************************************
1837************************** Begin flock Locking ********************************
1838**
1839** Use the flock() system call to do file locking.
1840**
drh6b9d6dd2008-12-03 19:34:47 +00001841** flock() locking is like dot-file locking in that the various
1842** fine-grain locking levels supported by SQLite are collapsed into
1843** a single exclusive lock. In other words, SHARED, RESERVED, and
1844** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1845** still works when you do this, but concurrency is reduced since
1846** only a single process can be reading the database at a time.
1847**
drh734c9862008-11-28 15:37:20 +00001848** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1849** compiling for VXWORKS.
1850*/
1851#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001852
drh6b9d6dd2008-12-03 19:34:47 +00001853/*
1854** This routine checks if there is a RESERVED lock held on the specified
1855** file by this or any other process. If such a lock is held, set *pResOut
1856** to a non-zero value otherwise *pResOut is set to zero. The return value
1857** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1858*/
drh734c9862008-11-28 15:37:20 +00001859static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1860 int rc = SQLITE_OK;
1861 int reserved = 0;
1862 unixFile *pFile = (unixFile*)id;
1863
1864 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1865
1866 assert( pFile );
1867
1868 /* Check if a thread in this process holds such a lock */
1869 if( pFile->locktype>SHARED_LOCK ){
1870 reserved = 1;
1871 }
1872
1873 /* Otherwise see if some other process holds it. */
1874 if( !reserved ){
1875 /* attempt to get the lock */
1876 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1877 if( !lrc ){
1878 /* got the lock, unlock it */
1879 lrc = flock(pFile->h, LOCK_UN);
1880 if ( lrc ) {
1881 int tErrno = errno;
1882 /* unlock failed with an error */
1883 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1884 if( IS_LOCK_ERROR(lrc) ){
1885 pFile->lastErrno = tErrno;
1886 rc = lrc;
1887 }
1888 }
1889 } else {
1890 int tErrno = errno;
1891 reserved = 1;
1892 /* someone else might have it reserved */
1893 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1894 if( IS_LOCK_ERROR(lrc) ){
1895 pFile->lastErrno = tErrno;
1896 rc = lrc;
1897 }
1898 }
1899 }
1900 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
1901
1902#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1903 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1904 rc = SQLITE_OK;
1905 reserved=1;
1906 }
1907#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1908 *pResOut = reserved;
1909 return rc;
1910}
1911
drh6b9d6dd2008-12-03 19:34:47 +00001912/*
1913** Lock the file with the lock specified by parameter locktype - one
1914** of the following:
1915**
1916** (1) SHARED_LOCK
1917** (2) RESERVED_LOCK
1918** (3) PENDING_LOCK
1919** (4) EXCLUSIVE_LOCK
1920**
1921** Sometimes when requesting one lock state, additional lock states
1922** are inserted in between. The locking might fail on one of the later
1923** transitions leaving the lock state different from what it started but
1924** still short of its goal. The following chart shows the allowed
1925** transitions and the inserted intermediate states:
1926**
1927** UNLOCKED -> SHARED
1928** SHARED -> RESERVED
1929** SHARED -> (PENDING) -> EXCLUSIVE
1930** RESERVED -> (PENDING) -> EXCLUSIVE
1931** PENDING -> EXCLUSIVE
1932**
1933** flock() only really support EXCLUSIVE locks. We track intermediate
1934** lock states in the sqlite3_file structure, but all locks SHARED or
1935** above are really EXCLUSIVE locks and exclude all other processes from
1936** access the file.
1937**
1938** This routine will only increase a lock. Use the sqlite3OsUnlock()
1939** routine to lower a locking level.
1940*/
drh734c9862008-11-28 15:37:20 +00001941static int flockLock(sqlite3_file *id, int locktype) {
1942 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001943 unixFile *pFile = (unixFile*)id;
1944
1945 assert( pFile );
1946
1947 /* if we already have a lock, it is exclusive.
1948 ** Just adjust level and punt on outta here. */
1949 if (pFile->locktype > NO_LOCK) {
1950 pFile->locktype = locktype;
1951 return SQLITE_OK;
1952 }
1953
1954 /* grab an exclusive lock */
1955
1956 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1957 int tErrno = errno;
1958 /* didn't get, must be busy */
1959 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1960 if( IS_LOCK_ERROR(rc) ){
1961 pFile->lastErrno = tErrno;
1962 }
1963 } else {
1964 /* got it, set the type and return ok */
1965 pFile->locktype = locktype;
1966 }
1967 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
1968 rc==SQLITE_OK ? "ok" : "failed");
1969#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1970 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1971 rc = SQLITE_BUSY;
1972 }
1973#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1974 return rc;
1975}
1976
drh6b9d6dd2008-12-03 19:34:47 +00001977
1978/*
1979** Lower the locking level on file descriptor pFile to locktype. locktype
1980** must be either NO_LOCK or SHARED_LOCK.
1981**
1982** If the locking level of the file descriptor is already at or below
1983** the requested locking level, this routine is a no-op.
1984*/
drh734c9862008-11-28 15:37:20 +00001985static int flockUnlock(sqlite3_file *id, int locktype) {
1986 unixFile *pFile = (unixFile*)id;
1987
1988 assert( pFile );
1989 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1990 pFile->locktype, getpid());
1991 assert( locktype<=SHARED_LOCK );
1992
1993 /* no-op if possible */
1994 if( pFile->locktype==locktype ){
1995 return SQLITE_OK;
1996 }
1997
1998 /* shared can just be set because we always have an exclusive */
1999 if (locktype==SHARED_LOCK) {
2000 pFile->locktype = locktype;
2001 return SQLITE_OK;
2002 }
2003
2004 /* no, really, unlock. */
2005 int rc = flock(pFile->h, LOCK_UN);
2006 if (rc) {
2007 int r, tErrno = errno;
2008 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2009 if( IS_LOCK_ERROR(r) ){
2010 pFile->lastErrno = tErrno;
2011 }
2012#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2013 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2014 r = SQLITE_BUSY;
2015 }
2016#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2017
2018 return r;
2019 } else {
2020 pFile->locktype = NO_LOCK;
2021 return SQLITE_OK;
2022 }
2023}
2024
2025/*
2026** Close a file.
2027*/
2028static int flockClose(sqlite3_file *id) {
2029 if( id ){
2030 flockUnlock(id, NO_LOCK);
2031 }
2032 return closeUnixFile(id);
2033}
2034
2035#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2036
2037/******************* End of the flock lock implementation *********************
2038******************************************************************************/
2039
2040/******************************************************************************
2041************************ Begin Named Semaphore Locking ************************
2042**
2043** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002044**
2045** Semaphore locking is like dot-lock and flock in that it really only
2046** supports EXCLUSIVE locking. Only a single process can read or write
2047** the database file at a time. This reduces potential concurrency, but
2048** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002049*/
2050#if OS_VXWORKS
2051
drh6b9d6dd2008-12-03 19:34:47 +00002052/*
2053** This routine checks if there is a RESERVED lock held on the specified
2054** file by this or any other process. If such a lock is held, set *pResOut
2055** to a non-zero value otherwise *pResOut is set to zero. The return value
2056** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2057*/
drh734c9862008-11-28 15:37:20 +00002058static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2059 int rc = SQLITE_OK;
2060 int reserved = 0;
2061 unixFile *pFile = (unixFile*)id;
2062
2063 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2064
2065 assert( pFile );
2066
2067 /* Check if a thread in this process holds such a lock */
2068 if( pFile->locktype>SHARED_LOCK ){
2069 reserved = 1;
2070 }
2071
2072 /* Otherwise see if some other process holds it. */
2073 if( !reserved ){
2074 sem_t *pSem = pFile->pOpen->pSem;
2075 struct stat statBuf;
2076
2077 if( sem_trywait(pSem)==-1 ){
2078 int tErrno = errno;
2079 if( EAGAIN != tErrno ){
2080 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2081 pFile->lastErrno = tErrno;
2082 } else {
2083 /* someone else has the lock when we are in NO_LOCK */
2084 reserved = (pFile->locktype < SHARED_LOCK);
2085 }
2086 }else{
2087 /* we could have it if we want it */
2088 sem_post(pSem);
2089 }
2090 }
2091 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2092
2093 *pResOut = reserved;
2094 return rc;
2095}
2096
drh6b9d6dd2008-12-03 19:34:47 +00002097/*
2098** Lock the file with the lock specified by parameter locktype - one
2099** of the following:
2100**
2101** (1) SHARED_LOCK
2102** (2) RESERVED_LOCK
2103** (3) PENDING_LOCK
2104** (4) EXCLUSIVE_LOCK
2105**
2106** Sometimes when requesting one lock state, additional lock states
2107** are inserted in between. The locking might fail on one of the later
2108** transitions leaving the lock state different from what it started but
2109** still short of its goal. The following chart shows the allowed
2110** transitions and the inserted intermediate states:
2111**
2112** UNLOCKED -> SHARED
2113** SHARED -> RESERVED
2114** SHARED -> (PENDING) -> EXCLUSIVE
2115** RESERVED -> (PENDING) -> EXCLUSIVE
2116** PENDING -> EXCLUSIVE
2117**
2118** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2119** lock states in the sqlite3_file structure, but all locks SHARED or
2120** above are really EXCLUSIVE locks and exclude all other processes from
2121** access the file.
2122**
2123** This routine will only increase a lock. Use the sqlite3OsUnlock()
2124** routine to lower a locking level.
2125*/
drh734c9862008-11-28 15:37:20 +00002126static int semLock(sqlite3_file *id, int locktype) {
2127 unixFile *pFile = (unixFile*)id;
2128 int fd;
2129 sem_t *pSem = pFile->pOpen->pSem;
2130 int rc = SQLITE_OK;
2131
2132 /* if we already have a lock, it is exclusive.
2133 ** Just adjust level and punt on outta here. */
2134 if (pFile->locktype > NO_LOCK) {
2135 pFile->locktype = locktype;
2136 rc = SQLITE_OK;
2137 goto sem_end_lock;
2138 }
2139
2140 /* lock semaphore now but bail out when already locked. */
2141 if( sem_trywait(pSem)==-1 ){
2142 rc = SQLITE_BUSY;
2143 goto sem_end_lock;
2144 }
2145
2146 /* got it, set the type and return ok */
2147 pFile->locktype = locktype;
2148
2149 sem_end_lock:
2150 return rc;
2151}
2152
drh6b9d6dd2008-12-03 19:34:47 +00002153/*
2154** Lower the locking level on file descriptor pFile to locktype. locktype
2155** must be either NO_LOCK or SHARED_LOCK.
2156**
2157** If the locking level of the file descriptor is already at or below
2158** the requested locking level, this routine is a no-op.
2159*/
drh734c9862008-11-28 15:37:20 +00002160static int semUnlock(sqlite3_file *id, int locktype) {
2161 unixFile *pFile = (unixFile*)id;
2162 sem_t *pSem = pFile->pOpen->pSem;
2163
2164 assert( pFile );
2165 assert( pSem );
2166 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2167 pFile->locktype, getpid());
2168 assert( locktype<=SHARED_LOCK );
2169
2170 /* no-op if possible */
2171 if( pFile->locktype==locktype ){
2172 return SQLITE_OK;
2173 }
2174
2175 /* shared can just be set because we always have an exclusive */
2176 if (locktype==SHARED_LOCK) {
2177 pFile->locktype = locktype;
2178 return SQLITE_OK;
2179 }
2180
2181 /* no, really unlock. */
2182 if ( sem_post(pSem)==-1 ) {
2183 int rc, tErrno = errno;
2184 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2185 if( IS_LOCK_ERROR(rc) ){
2186 pFile->lastErrno = tErrno;
2187 }
2188 return rc;
2189 }
2190 pFile->locktype = NO_LOCK;
2191 return SQLITE_OK;
2192}
2193
2194/*
2195 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002196 */
drh734c9862008-11-28 15:37:20 +00002197static int semClose(sqlite3_file *id) {
2198 if( id ){
2199 unixFile *pFile = (unixFile*)id;
2200 semUnlock(id, NO_LOCK);
2201 assert( pFile );
2202 unixEnterMutex();
2203 releaseLockInfo(pFile->pLock);
2204 releaseOpenCnt(pFile->pOpen);
2205 closeUnixFile(id);
2206 unixLeaveMutex();
2207 }
2208 return SQLITE_OK;
2209}
2210
2211#endif /* OS_VXWORKS */
2212/*
2213** Named semaphore locking is only available on VxWorks.
2214**
2215*************** End of the named semaphore lock implementation ****************
2216******************************************************************************/
2217
2218
2219/******************************************************************************
2220*************************** Begin AFP Locking *********************************
2221**
2222** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2223** on Apple Macintosh computers - both OS9 and OSX.
2224**
2225** Third-party implementations of AFP are available. But this code here
2226** only works on OSX.
2227*/
2228
drhd2cb50b2009-01-09 21:41:17 +00002229#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002230/*
2231** The afpLockingContext structure contains all afp lock specific state
2232*/
drhbfe66312006-10-03 17:40:40 +00002233typedef struct afpLockingContext afpLockingContext;
2234struct afpLockingContext {
aswiftaebf4132008-11-21 00:10:35 +00002235 unsigned long long sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002236 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002237};
2238
2239struct ByteRangeLockPB2
2240{
2241 unsigned long long offset; /* offset to first byte to lock */
2242 unsigned long long length; /* nbr of bytes to lock */
2243 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2244 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2245 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2246 int fd; /* file desc to assoc this lock with */
2247};
2248
drhfd131da2007-08-07 17:13:03 +00002249#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002250
drh6b9d6dd2008-12-03 19:34:47 +00002251/*
2252** This is a utility for setting or clearing a bit-range lock on an
2253** AFP filesystem.
2254**
2255** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2256*/
2257static int afpSetLock(
2258 const char *path, /* Name of the file to be locked or unlocked */
2259 unixFile *pFile, /* Open file descriptor on path */
2260 unsigned long long offset, /* First byte to be locked */
2261 unsigned long long length, /* Number of bytes to lock */
2262 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002263){
drh6b9d6dd2008-12-03 19:34:47 +00002264 struct ByteRangeLockPB2 pb;
2265 int err;
drhbfe66312006-10-03 17:40:40 +00002266
2267 pb.unLockFlag = setLockFlag ? 0 : 1;
2268 pb.startEndFlag = 0;
2269 pb.offset = offset;
2270 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002271 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002272
2273 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002274 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2275 offset, length);
drhbfe66312006-10-03 17:40:40 +00002276 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2277 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002278 int rc;
2279 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002280 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2281 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002282#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2283 rc = SQLITE_BUSY;
2284#else
drh734c9862008-11-28 15:37:20 +00002285 rc = sqliteErrorFromPosixError(tErrno,
2286 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002287#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002288 if( IS_LOCK_ERROR(rc) ){
2289 pFile->lastErrno = tErrno;
2290 }
2291 return rc;
drhbfe66312006-10-03 17:40:40 +00002292 } else {
aswift5b1a2562008-08-22 00:22:35 +00002293 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002294 }
2295}
2296
drh6b9d6dd2008-12-03 19:34:47 +00002297/*
2298** This routine checks if there is a RESERVED lock held on the specified
2299** file by this or any other process. If such a lock is held, set *pResOut
2300** to a non-zero value otherwise *pResOut is set to zero. The return value
2301** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2302*/
danielk1977e339d652008-06-28 11:23:00 +00002303static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002304 int rc = SQLITE_OK;
2305 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002306 unixFile *pFile = (unixFile*)id;
2307
aswift5b1a2562008-08-22 00:22:35 +00002308 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2309
2310 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002311 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2312
2313 /* Check if a thread in this process holds such a lock */
2314 if( pFile->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002315 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002316 }
2317
2318 /* Otherwise see if some other process holds it.
2319 */
aswift5b1a2562008-08-22 00:22:35 +00002320 if( !reserved ){
2321 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002322 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002323 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002324 /* if we succeeded in taking the reserved lock, unlock it to restore
2325 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002326 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002327 } else {
2328 /* if we failed to get the lock then someone else must have it */
2329 reserved = 1;
2330 }
2331 if( IS_LOCK_ERROR(lrc) ){
2332 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002333 }
2334 }
drhbfe66312006-10-03 17:40:40 +00002335
aswift5b1a2562008-08-22 00:22:35 +00002336 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2337
2338 *pResOut = reserved;
2339 return rc;
drhbfe66312006-10-03 17:40:40 +00002340}
2341
drh6b9d6dd2008-12-03 19:34:47 +00002342/*
2343** Lock the file with the lock specified by parameter locktype - one
2344** of the following:
2345**
2346** (1) SHARED_LOCK
2347** (2) RESERVED_LOCK
2348** (3) PENDING_LOCK
2349** (4) EXCLUSIVE_LOCK
2350**
2351** Sometimes when requesting one lock state, additional lock states
2352** are inserted in between. The locking might fail on one of the later
2353** transitions leaving the lock state different from what it started but
2354** still short of its goal. The following chart shows the allowed
2355** transitions and the inserted intermediate states:
2356**
2357** UNLOCKED -> SHARED
2358** SHARED -> RESERVED
2359** SHARED -> (PENDING) -> EXCLUSIVE
2360** RESERVED -> (PENDING) -> EXCLUSIVE
2361** PENDING -> EXCLUSIVE
2362**
2363** This routine will only increase a lock. Use the sqlite3OsUnlock()
2364** routine to lower a locking level.
2365*/
danielk1977e339d652008-06-28 11:23:00 +00002366static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002367 int rc = SQLITE_OK;
2368 unixFile *pFile = (unixFile*)id;
2369 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002370
2371 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002372 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00002373 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
2374
drhbfe66312006-10-03 17:40:40 +00002375 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002376 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002377 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002378 */
drhbfe66312006-10-03 17:40:40 +00002379 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00002380 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002381 locktypeName(locktype));
2382 return SQLITE_OK;
2383 }
2384
2385 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00002386 */
drhbfe66312006-10-03 17:40:40 +00002387 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2388 assert( locktype!=PENDING_LOCK );
2389 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2390
2391 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002392 */
drh6c7d5c52008-11-21 20:32:33 +00002393 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002394
2395 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002396 */
drhbfe66312006-10-03 17:40:40 +00002397 rc = transferOwnership(pFile);
2398 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002399 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002400 return rc;
2401 }
2402
2403 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002404 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2405 ** be released.
2406 */
drhbfe66312006-10-03 17:40:40 +00002407 if( locktype==SHARED_LOCK
2408 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002409 ){
2410 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002411 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002412 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002413 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002414 goto afp_end_lock;
2415 }
2416 }
2417
2418 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002419 ** operating system calls for the specified lock.
2420 */
drhbfe66312006-10-03 17:40:40 +00002421 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002422 int lk, lrc1, lrc2, lrc1Errno;
drhbfe66312006-10-03 17:40:40 +00002423
aswift5b1a2562008-08-22 00:22:35 +00002424 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002425 /* note that the quality of the randomness doesn't matter that much */
2426 lk = random();
aswiftaebf4132008-11-21 00:10:35 +00002427 context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002428 lrc1 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002429 SHARED_FIRST+context->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002430 if( IS_LOCK_ERROR(lrc1) ){
2431 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002432 }
aswift5b1a2562008-08-22 00:22:35 +00002433 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002434 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002435
aswift5b1a2562008-08-22 00:22:35 +00002436 if( IS_LOCK_ERROR(lrc1) ) {
2437 pFile->lastErrno = lrc1Errno;
2438 rc = lrc1;
2439 goto afp_end_lock;
2440 } else if( IS_LOCK_ERROR(lrc2) ){
2441 rc = lrc2;
2442 goto afp_end_lock;
2443 } else if( lrc1 != SQLITE_OK ) {
2444 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002445 } else {
2446 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002447 pFile->pOpen->nLock++;
drhbfe66312006-10-03 17:40:40 +00002448 }
2449 }else{
2450 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2451 ** assumed that there is a SHARED or greater lock on the file
2452 ** already.
2453 */
2454 int failed = 0;
2455 assert( 0!=pFile->locktype );
2456 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2457 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002458 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drhbfe66312006-10-03 17:40:40 +00002459 }
2460 if (!failed && locktype == EXCLUSIVE_LOCK) {
2461 /* Acquire an EXCLUSIVE lock */
2462
2463 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002464 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002465 */
drh6b9d6dd2008-12-03 19:34:47 +00002466 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
aswiftaebf4132008-11-21 00:10:35 +00002467 context->sharedByte, 1, 0)) ){
2468 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002469 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002470 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002471 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002472 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002473 SHARED_FIRST + context->sharedByte, 1, 1)) ){
2474 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2475 ** a critical I/O error
2476 */
2477 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2478 SQLITE_IOERR_LOCK;
2479 goto afp_end_lock;
2480 }
2481 }else{
aswift5b1a2562008-08-22 00:22:35 +00002482 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002483 }
2484 }
aswift5b1a2562008-08-22 00:22:35 +00002485 if( failed ){
2486 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002487 }
2488 }
2489
2490 if( rc==SQLITE_OK ){
2491 pFile->locktype = locktype;
2492 }else if( locktype==EXCLUSIVE_LOCK ){
2493 pFile->locktype = PENDING_LOCK;
2494 }
2495
2496afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002497 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00002498 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002499 rc==SQLITE_OK ? "ok" : "failed");
2500 return rc;
2501}
2502
2503/*
drh339eb0b2008-03-07 15:34:11 +00002504** Lower the locking level on file descriptor pFile to locktype. locktype
2505** must be either NO_LOCK or SHARED_LOCK.
2506**
2507** If the locking level of the file descriptor is already at or below
2508** the requested locking level, this routine is a no-op.
2509*/
danielk1977e339d652008-06-28 11:23:00 +00002510static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002511 int rc = SQLITE_OK;
2512 unixFile *pFile = (unixFile*)id;
aswiftaebf4132008-11-21 00:10:35 +00002513 afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002514
2515 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002516 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00002517 pFile->locktype, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002518
drhbfe66312006-10-03 17:40:40 +00002519 assert( locktype<=SHARED_LOCK );
2520 if( pFile->locktype<=locktype ){
2521 return SQLITE_OK;
2522 }
2523 if( CHECK_THREADID(pFile) ){
2524 return SQLITE_MISUSE;
2525 }
drh6c7d5c52008-11-21 20:32:33 +00002526 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002527 if( pFile->locktype>SHARED_LOCK ){
aswiftaebf4132008-11-21 00:10:35 +00002528
2529 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002530 rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
aswiftaebf4132008-11-21 00:10:35 +00002531 if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
2532 /* only re-establish the shared lock if necessary */
2533 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002534 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
aswiftaebf4132008-11-21 00:10:35 +00002535 }
2536 }
2537 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002538 rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002539 }
2540 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002541 rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002542 }
2543 }else if( locktype==NO_LOCK ){
2544 /* clear the shared lock */
2545 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002546 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002547 }
drhbfe66312006-10-03 17:40:40 +00002548
aswiftaebf4132008-11-21 00:10:35 +00002549 if( rc==SQLITE_OK ){
2550 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00002551 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002552 pOpen->nLock--;
2553 assert( pOpen->nLock>=0 );
2554 if( pOpen->nLock==0 && pOpen->nPending>0 ){
2555 int i;
2556 for(i=0; i<pOpen->nPending; i++){
2557 if( pOpen->aPending[i] < 0 ) continue;
2558 if( close(pOpen->aPending[i]) ){
2559 pFile->lastErrno = errno;
2560 rc = SQLITE_IOERR_CLOSE;
2561 }else{
2562 pOpen->aPending[i] = -1;
drhbfe66312006-10-03 17:40:40 +00002563 }
aswiftaebf4132008-11-21 00:10:35 +00002564 }
2565 if( rc==SQLITE_OK ){
2566 sqlite3_free(pOpen->aPending);
2567 pOpen->nPending = 0;
2568 pOpen->aPending = 0;
2569 }
drhbfe66312006-10-03 17:40:40 +00002570 }
2571 }
drhbfe66312006-10-03 17:40:40 +00002572 }
drh6c7d5c52008-11-21 20:32:33 +00002573 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002574 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002575 return rc;
2576}
2577
2578/*
drh339eb0b2008-03-07 15:34:11 +00002579** Close a file & cleanup AFP specific locking context
2580*/
danielk1977e339d652008-06-28 11:23:00 +00002581static int afpClose(sqlite3_file *id) {
2582 if( id ){
2583 unixFile *pFile = (unixFile*)id;
2584 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002585 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002586 if( pFile->pOpen && pFile->pOpen->nLock ){
2587 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002588 ** yet because that would clear those locks. Instead, add the file
2589 ** descriptor to pOpen->aPending. It will be automatically closed when
2590 ** the last lock is cleared.
2591 */
aswiftaebf4132008-11-21 00:10:35 +00002592 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00002593 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002594 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
2595 if( aNew==0 ){
2596 /* If a malloc fails, just leak the file descriptor */
2597 }else{
2598 pOpen->aPending = aNew;
2599 pOpen->aPending[pOpen->nPending] = pFile->h;
2600 pOpen->nPending++;
2601 pFile->h = -1;
2602 }
2603 }
2604 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002605 sqlite3_free(pFile->lockingContext);
aswiftaebf4132008-11-21 00:10:35 +00002606 closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002607 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002608 }
aswiftaebf4132008-11-21 00:10:35 +00002609 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002610}
2611
drhd2cb50b2009-01-09 21:41:17 +00002612#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002613/*
2614** The code above is the AFP lock implementation. The code is specific
2615** to MacOSX and does not work on other unix platforms. No alternative
2616** is available. If you don't compile for a mac, then the "unix-afp"
2617** VFS is not available.
2618**
2619********************* End of the AFP lock implementation **********************
2620******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002621
drh734c9862008-11-28 15:37:20 +00002622
2623/******************************************************************************
2624**************** Non-locking sqlite3_file methods *****************************
2625**
2626** The next division contains implementations for all methods of the
2627** sqlite3_file object other than the locking methods. The locking
2628** methods were defined in divisions above (one locking method per
2629** division). Those methods that are common to all locking modes
2630** are gather together into this division.
2631*/
drhbfe66312006-10-03 17:40:40 +00002632
2633/*
drh734c9862008-11-28 15:37:20 +00002634** Seek to the offset passed as the second argument, then read cnt
2635** bytes into pBuf. Return the number of bytes actually read.
2636**
2637** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2638** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2639** one system to another. Since SQLite does not define USE_PREAD
2640** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2641** See tickets #2741 and #2681.
2642**
2643** To avoid stomping the errno value on a failed read the lastErrno value
2644** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002645*/
drh734c9862008-11-28 15:37:20 +00002646static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2647 int got;
2648 i64 newOffset;
2649 TIMER_START;
2650#if defined(USE_PREAD)
2651 got = pread(id->h, pBuf, cnt, offset);
2652 SimulateIOError( got = -1 );
2653#elif defined(USE_PREAD64)
2654 got = pread64(id->h, pBuf, cnt, offset);
2655 SimulateIOError( got = -1 );
2656#else
2657 newOffset = lseek(id->h, offset, SEEK_SET);
2658 SimulateIOError( newOffset-- );
2659 if( newOffset!=offset ){
2660 if( newOffset == -1 ){
2661 ((unixFile*)id)->lastErrno = errno;
2662 }else{
2663 ((unixFile*)id)->lastErrno = 0;
2664 }
2665 return -1;
2666 }
2667 got = read(id->h, pBuf, cnt);
2668#endif
2669 TIMER_END;
2670 if( got<0 ){
2671 ((unixFile*)id)->lastErrno = errno;
2672 }
2673 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2674 return got;
drhbfe66312006-10-03 17:40:40 +00002675}
2676
2677/*
drh734c9862008-11-28 15:37:20 +00002678** Read data from a file into a buffer. Return SQLITE_OK if all
2679** bytes were read successfully and SQLITE_IOERR if anything goes
2680** wrong.
drh339eb0b2008-03-07 15:34:11 +00002681*/
drh734c9862008-11-28 15:37:20 +00002682static int unixRead(
2683 sqlite3_file *id,
2684 void *pBuf,
2685 int amt,
2686 sqlite3_int64 offset
2687){
2688 int got;
2689 assert( id );
2690 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
2691 if( got==amt ){
2692 return SQLITE_OK;
2693 }else if( got<0 ){
2694 /* lastErrno set by seekAndRead */
2695 return SQLITE_IOERR_READ;
2696 }else{
2697 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2698 /* Unread parts of the buffer must be zero-filled */
2699 memset(&((char*)pBuf)[got], 0, amt-got);
2700 return SQLITE_IOERR_SHORT_READ;
2701 }
2702}
2703
2704/*
2705** Seek to the offset in id->offset then read cnt bytes into pBuf.
2706** Return the number of bytes actually read. Update the offset.
2707**
2708** To avoid stomping the errno value on a failed write the lastErrno value
2709** is set before returning.
2710*/
2711static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2712 int got;
2713 i64 newOffset;
2714 TIMER_START;
2715#if defined(USE_PREAD)
2716 got = pwrite(id->h, pBuf, cnt, offset);
2717#elif defined(USE_PREAD64)
2718 got = pwrite64(id->h, pBuf, cnt, offset);
2719#else
2720 newOffset = lseek(id->h, offset, SEEK_SET);
2721 if( newOffset!=offset ){
2722 if( newOffset == -1 ){
2723 ((unixFile*)id)->lastErrno = errno;
2724 }else{
2725 ((unixFile*)id)->lastErrno = 0;
2726 }
2727 return -1;
2728 }
2729 got = write(id->h, pBuf, cnt);
2730#endif
2731 TIMER_END;
2732 if( got<0 ){
2733 ((unixFile*)id)->lastErrno = errno;
2734 }
2735
2736 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2737 return got;
2738}
2739
2740
2741/*
2742** Write data from a buffer into a file. Return SQLITE_OK on success
2743** or some other error code on failure.
2744*/
2745static int unixWrite(
2746 sqlite3_file *id,
2747 const void *pBuf,
2748 int amt,
2749 sqlite3_int64 offset
2750){
2751 int wrote = 0;
2752 assert( id );
2753 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002754
2755#ifndef NDEBUG
2756 /* If we are doing a normal write to a database file (as opposed to
2757 ** doing a hot-journal rollback or a write to some file other than a
2758 ** normal database file) then record the fact that the database
2759 ** has changed. If the transaction counter is modified, record that
2760 ** fact too.
2761 */
2762 if( ((unixFile*)id)->inNormalWrite ){
2763 unixFile *pFile = (unixFile*)id;
2764 pFile->dbUpdate = 1; /* The database has been modified */
2765 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002766 int rc;
drh8f941bc2009-01-14 23:03:40 +00002767 char oldCntr[4];
2768 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002769 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002770 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002771 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002772 pFile->transCntrChng = 1; /* The transaction counter has changed */
2773 }
2774 }
2775 }
2776#endif
2777
drh734c9862008-11-28 15:37:20 +00002778 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
2779 amt -= wrote;
2780 offset += wrote;
2781 pBuf = &((char*)pBuf)[wrote];
2782 }
2783 SimulateIOError(( wrote=(-1), amt=1 ));
2784 SimulateDiskfullError(( wrote=0, amt=1 ));
2785 if( amt>0 ){
2786 if( wrote<0 ){
2787 /* lastErrno set by seekAndWrite */
2788 return SQLITE_IOERR_WRITE;
2789 }else{
2790 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2791 return SQLITE_FULL;
2792 }
2793 }
2794 return SQLITE_OK;
2795}
2796
2797#ifdef SQLITE_TEST
2798/*
2799** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002800** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002801*/
2802int sqlite3_sync_count = 0;
2803int sqlite3_fullsync_count = 0;
2804#endif
2805
2806/*
2807** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
2808** Otherwise use fsync() in its place.
2809*/
2810#ifndef HAVE_FDATASYNC
2811# define fdatasync fsync
2812#endif
2813
2814/*
2815** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2816** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2817** only available on Mac OS X. But that could change.
2818*/
2819#ifdef F_FULLFSYNC
2820# define HAVE_FULLFSYNC 1
2821#else
2822# define HAVE_FULLFSYNC 0
2823#endif
2824
2825
2826/*
2827** The fsync() system call does not work as advertised on many
2828** unix systems. The following procedure is an attempt to make
2829** it work better.
2830**
2831** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2832** for testing when we want to run through the test suite quickly.
2833** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2834** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2835** or power failure will likely corrupt the database file.
2836*/
2837static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002838 int rc;
drh734c9862008-11-28 15:37:20 +00002839
2840 /* The following "ifdef/elif/else/" block has the same structure as
2841 ** the one below. It is replicated here solely to avoid cluttering
2842 ** up the real code with the UNUSED_PARAMETER() macros.
2843 */
2844#ifdef SQLITE_NO_SYNC
2845 UNUSED_PARAMETER(fd);
2846 UNUSED_PARAMETER(fullSync);
2847 UNUSED_PARAMETER(dataOnly);
2848#elif HAVE_FULLFSYNC
2849 UNUSED_PARAMETER(dataOnly);
2850#else
2851 UNUSED_PARAMETER(fullSync);
2852#endif
2853
2854 /* Record the number of times that we do a normal fsync() and
2855 ** FULLSYNC. This is used during testing to verify that this procedure
2856 ** gets called with the correct arguments.
2857 */
2858#ifdef SQLITE_TEST
2859 if( fullSync ) sqlite3_fullsync_count++;
2860 sqlite3_sync_count++;
2861#endif
2862
2863 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2864 ** no-op
2865 */
2866#ifdef SQLITE_NO_SYNC
2867 rc = SQLITE_OK;
2868#elif HAVE_FULLFSYNC
2869 if( fullSync ){
2870 rc = fcntl(fd, F_FULLFSYNC, 0);
2871 }else{
2872 rc = 1;
2873 }
2874 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002875 ** It shouldn't be possible for fullfsync to fail on the local
2876 ** file system (on OSX), so failure indicates that FULLFSYNC
2877 ** isn't supported for this file system. So, attempt an fsync
2878 ** and (for now) ignore the overhead of a superfluous fcntl call.
2879 ** It'd be better to detect fullfsync support once and avoid
2880 ** the fcntl call every time sync is called.
2881 */
drh734c9862008-11-28 15:37:20 +00002882 if( rc ) rc = fsync(fd);
2883
2884#else
2885 if( dataOnly ){
2886 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002887#if OS_VXWORKS
2888 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002889 rc = fsync(fd);
2890 }
drhc7288ee2009-01-15 04:30:02 +00002891#endif
drh734c9862008-11-28 15:37:20 +00002892 }else{
2893 rc = fsync(fd);
2894 }
2895#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2896
2897 if( OS_VXWORKS && rc!= -1 ){
2898 rc = 0;
2899 }
chw97185482008-11-17 08:05:31 +00002900 return rc;
drhbfe66312006-10-03 17:40:40 +00002901}
2902
drh734c9862008-11-28 15:37:20 +00002903/*
2904** Make sure all writes to a particular file are committed to disk.
2905**
2906** If dataOnly==0 then both the file itself and its metadata (file
2907** size, access time, etc) are synced. If dataOnly!=0 then only the
2908** file data is synced.
2909**
2910** Under Unix, also make sure that the directory entry for the file
2911** has been created by fsync-ing the directory that contains the file.
2912** If we do not do this and we encounter a power failure, the directory
2913** entry for the journal might not exist after we reboot. The next
2914** SQLite to access the file will not know that the journal exists (because
2915** the directory entry for the journal was never created) and the transaction
2916** will not roll back - possibly leading to database corruption.
2917*/
2918static int unixSync(sqlite3_file *id, int flags){
2919 int rc;
2920 unixFile *pFile = (unixFile*)id;
2921
2922 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2923 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2924
2925 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2926 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2927 || (flags&0x0F)==SQLITE_SYNC_FULL
2928 );
2929
2930 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2931 ** line is to test that doing so does not cause any problems.
2932 */
2933 SimulateDiskfullError( return SQLITE_FULL );
2934
2935 assert( pFile );
2936 OSTRACE2("SYNC %-3d\n", pFile->h);
2937 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
2938 SimulateIOError( rc=1 );
2939 if( rc ){
2940 pFile->lastErrno = errno;
2941 return SQLITE_IOERR_FSYNC;
2942 }
2943 if( pFile->dirfd>=0 ){
2944 int err;
2945 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
2946 HAVE_FULLFSYNC, isFullsync);
2947#ifndef SQLITE_DISABLE_DIRSYNC
2948 /* The directory sync is only attempted if full_fsync is
2949 ** turned off or unavailable. If a full_fsync occurred above,
2950 ** then the directory sync is superfluous.
2951 */
2952 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
2953 /*
2954 ** We have received multiple reports of fsync() returning
2955 ** errors when applied to directories on certain file systems.
2956 ** A failed directory sync is not a big deal. So it seems
2957 ** better to ignore the error. Ticket #1657
2958 */
2959 /* pFile->lastErrno = errno; */
2960 /* return SQLITE_IOERR; */
2961 }
2962#endif
2963 err = close(pFile->dirfd); /* Only need to sync once, so close the */
2964 if( err==0 ){ /* directory when we are done */
2965 pFile->dirfd = -1;
2966 }else{
2967 pFile->lastErrno = errno;
2968 rc = SQLITE_IOERR_DIR_CLOSE;
2969 }
2970 }
2971 return rc;
2972}
2973
2974/*
2975** Truncate an open file to a specified size
2976*/
2977static int unixTruncate(sqlite3_file *id, i64 nByte){
2978 int rc;
2979 assert( id );
2980 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
2981 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
2982 if( rc ){
2983 ((unixFile*)id)->lastErrno = errno;
2984 return SQLITE_IOERR_TRUNCATE;
2985 }else{
2986 return SQLITE_OK;
2987 }
2988}
2989
2990/*
2991** Determine the current size of a file in bytes
2992*/
2993static int unixFileSize(sqlite3_file *id, i64 *pSize){
2994 int rc;
2995 struct stat buf;
2996 assert( id );
2997 rc = fstat(((unixFile*)id)->h, &buf);
2998 SimulateIOError( rc=1 );
2999 if( rc!=0 ){
3000 ((unixFile*)id)->lastErrno = errno;
3001 return SQLITE_IOERR_FSTAT;
3002 }
3003 *pSize = buf.st_size;
3004
3005 /* When opening a zero-size database, the findLockInfo() procedure
3006 ** writes a single byte into that file in order to work around a bug
3007 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3008 ** layers, we need to report this file size as zero even though it is
3009 ** really 1. Ticket #3260.
3010 */
3011 if( *pSize==1 ) *pSize = 0;
3012
3013
3014 return SQLITE_OK;
3015}
3016
drhd2cb50b2009-01-09 21:41:17 +00003017#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003018/*
3019** Handler for proxy-locking file-control verbs. Defined below in the
3020** proxying locking division.
3021*/
3022static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003023#endif
drh715ff302008-12-03 22:32:44 +00003024
danielk1977ad94b582007-08-20 06:44:22 +00003025
danielk1977e3026632004-06-22 11:29:02 +00003026/*
drh9e33c2c2007-08-31 18:34:59 +00003027** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003028*/
drhcc6bb3e2007-08-31 16:11:35 +00003029static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003030 switch( op ){
3031 case SQLITE_FCNTL_LOCKSTATE: {
3032 *(int*)pArg = ((unixFile*)id)->locktype;
3033 return SQLITE_OK;
3034 }
drh7708e972008-11-29 00:56:52 +00003035 case SQLITE_LAST_ERRNO: {
3036 *(int*)pArg = ((unixFile*)id)->lastErrno;
3037 return SQLITE_OK;
3038 }
drh8f941bc2009-01-14 23:03:40 +00003039#ifndef NDEBUG
3040 /* The pager calls this method to signal that it has done
3041 ** a rollback and that the database is therefore unchanged and
3042 ** it hence it is OK for the transaction change counter to be
3043 ** unchanged.
3044 */
3045 case SQLITE_FCNTL_DB_UNCHANGED: {
3046 ((unixFile*)id)->dbUpdate = 0;
3047 return SQLITE_OK;
3048 }
3049#endif
drhd2cb50b2009-01-09 21:41:17 +00003050#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003051 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003052 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003053 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003054 }
drhd2cb50b2009-01-09 21:41:17 +00003055#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003056 }
drhcc6bb3e2007-08-31 16:11:35 +00003057 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003058}
3059
3060/*
danielk1977a3d4c882007-03-23 10:08:38 +00003061** Return the sector size in bytes of the underlying block device for
3062** the specified file. This is almost always 512 bytes, but may be
3063** larger for some devices.
3064**
3065** SQLite code assumes this function cannot fail. It also assumes that
3066** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003067** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003068** same for both.
3069*/
danielk1977397d65f2008-11-19 11:35:39 +00003070static int unixSectorSize(sqlite3_file *NotUsed){
3071 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003072 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003073}
3074
danielk197790949c22007-08-17 16:50:38 +00003075/*
danielk1977397d65f2008-11-19 11:35:39 +00003076** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003077*/
danielk1977397d65f2008-11-19 11:35:39 +00003078static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3079 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003080 return 0;
3081}
3082
drh734c9862008-11-28 15:37:20 +00003083/*
3084** Here ends the implementation of all sqlite3_file methods.
3085**
3086********************** End sqlite3_file Methods *******************************
3087******************************************************************************/
3088
3089/*
drh6b9d6dd2008-12-03 19:34:47 +00003090** This division contains definitions of sqlite3_io_methods objects that
3091** implement various file locking strategies. It also contains definitions
3092** of "finder" functions. A finder-function is used to locate the appropriate
3093** sqlite3_io_methods object for a particular database file. The pAppData
3094** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3095** the correct finder-function for that VFS.
3096**
3097** Most finder functions return a pointer to a fixed sqlite3_io_methods
3098** object. The only interesting finder-function is autolockIoFinder, which
3099** looks at the filesystem type and tries to guess the best locking
3100** strategy from that.
3101**
drh1875f7a2008-12-08 18:19:17 +00003102** For finder-funtion F, two objects are created:
3103**
3104** (1) The real finder-function named "FImpt()".
3105**
3106** (2) A constant pointer to this functio named just "F".
3107**
3108**
3109** A pointer to the F pointer is used as the pAppData value for VFS
3110** objects. We have to do this instead of letting pAppData point
3111** directly at the finder-function since C90 rules prevent a void*
3112** from be cast into a function pointer.
3113**
drh6b9d6dd2008-12-03 19:34:47 +00003114**
drh7708e972008-11-29 00:56:52 +00003115** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003116**
drh7708e972008-11-29 00:56:52 +00003117** * A constant sqlite3_io_methods object call METHOD that has locking
3118** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3119**
3120** * An I/O method finder function called FINDER that returns a pointer
3121** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003122*/
drh7708e972008-11-29 00:56:52 +00003123#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3124static const sqlite3_io_methods METHOD = { \
3125 1, /* iVersion */ \
3126 CLOSE, /* xClose */ \
3127 unixRead, /* xRead */ \
3128 unixWrite, /* xWrite */ \
3129 unixTruncate, /* xTruncate */ \
3130 unixSync, /* xSync */ \
3131 unixFileSize, /* xFileSize */ \
3132 LOCK, /* xLock */ \
3133 UNLOCK, /* xUnlock */ \
3134 CKLOCK, /* xCheckReservedLock */ \
3135 unixFileControl, /* xFileControl */ \
3136 unixSectorSize, /* xSectorSize */ \
3137 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3138}; \
drh1875f7a2008-12-08 18:19:17 +00003139static const sqlite3_io_methods *FINDER##Impl(const char *z, int h){ \
drh7708e972008-11-29 00:56:52 +00003140 UNUSED_PARAMETER(z); UNUSED_PARAMETER(h); \
3141 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003142} \
3143static const sqlite3_io_methods *(*const FINDER)(const char*,int) \
3144 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003145
3146/*
3147** Here are all of the sqlite3_io_methods objects for each of the
3148** locking strategies. Functions that return pointers to these methods
3149** are also created.
3150*/
3151IOMETHODS(
3152 posixIoFinder, /* Finder function name */
3153 posixIoMethods, /* sqlite3_io_methods object name */
3154 unixClose, /* xClose method */
3155 unixLock, /* xLock method */
3156 unixUnlock, /* xUnlock method */
3157 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003158)
drh7708e972008-11-29 00:56:52 +00003159IOMETHODS(
3160 nolockIoFinder, /* Finder function name */
3161 nolockIoMethods, /* sqlite3_io_methods object name */
3162 nolockClose, /* xClose method */
3163 nolockLock, /* xLock method */
3164 nolockUnlock, /* xUnlock method */
3165 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003166)
drh7708e972008-11-29 00:56:52 +00003167IOMETHODS(
3168 dotlockIoFinder, /* Finder function name */
3169 dotlockIoMethods, /* sqlite3_io_methods object name */
3170 dotlockClose, /* xClose method */
3171 dotlockLock, /* xLock method */
3172 dotlockUnlock, /* xUnlock method */
3173 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003174)
drh7708e972008-11-29 00:56:52 +00003175
3176#if SQLITE_ENABLE_LOCKING_STYLE
3177IOMETHODS(
3178 flockIoFinder, /* Finder function name */
3179 flockIoMethods, /* sqlite3_io_methods object name */
3180 flockClose, /* xClose method */
3181 flockLock, /* xLock method */
3182 flockUnlock, /* xUnlock method */
3183 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003184)
drh7708e972008-11-29 00:56:52 +00003185#endif
3186
drh6c7d5c52008-11-21 20:32:33 +00003187#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003188IOMETHODS(
3189 semIoFinder, /* Finder function name */
3190 semIoMethods, /* sqlite3_io_methods object name */
3191 semClose, /* xClose method */
3192 semLock, /* xLock method */
3193 semUnlock, /* xUnlock method */
3194 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003195)
aswiftaebf4132008-11-21 00:10:35 +00003196#endif
drh7708e972008-11-29 00:56:52 +00003197
drhd2cb50b2009-01-09 21:41:17 +00003198#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003199IOMETHODS(
3200 afpIoFinder, /* Finder function name */
3201 afpIoMethods, /* sqlite3_io_methods object name */
3202 afpClose, /* xClose method */
3203 afpLock, /* xLock method */
3204 afpUnlock, /* xUnlock method */
3205 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003206)
drh715ff302008-12-03 22:32:44 +00003207#endif
3208
3209/*
3210** The proxy locking method is a "super-method" in the sense that it
3211** opens secondary file descriptors for the conch and lock files and
3212** it uses proxy, dot-file, AFP, and flock() locking methods on those
3213** secondary files. For this reason, the division that implements
3214** proxy locking is located much further down in the file. But we need
3215** to go ahead and define the sqlite3_io_methods and finder function
3216** for proxy locking here. So we forward declare the I/O methods.
3217*/
drhd2cb50b2009-01-09 21:41:17 +00003218#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003219static int proxyClose(sqlite3_file*);
3220static int proxyLock(sqlite3_file*, int);
3221static int proxyUnlock(sqlite3_file*, int);
3222static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003223IOMETHODS(
3224 proxyIoFinder, /* Finder function name */
3225 proxyIoMethods, /* sqlite3_io_methods object name */
3226 proxyClose, /* xClose method */
3227 proxyLock, /* xLock method */
3228 proxyUnlock, /* xUnlock method */
3229 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003230)
aswiftaebf4132008-11-21 00:10:35 +00003231#endif
drh7708e972008-11-29 00:56:52 +00003232
3233
drhd2cb50b2009-01-09 21:41:17 +00003234#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003235/*
drh6b9d6dd2008-12-03 19:34:47 +00003236** This "finder" function attempts to determine the best locking strategy
3237** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003238** object that implements that strategy.
3239**
3240** This is for MacOSX only.
3241*/
drh1875f7a2008-12-08 18:19:17 +00003242static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003243 const char *filePath, /* name of the database file */
3244 int fd /* file descriptor open on the database file */
3245){
3246 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003247 const char *zFilesystem; /* Filesystem type name */
3248 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003249 } aMap[] = {
3250 { "hfs", &posixIoMethods },
3251 { "ufs", &posixIoMethods },
3252 { "afpfs", &afpIoMethods },
3253#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
3254 { "smbfs", &afpIoMethods },
3255#else
3256 { "smbfs", &flockIoMethods },
3257#endif
3258 { "webdav", &nolockIoMethods },
3259 { 0, 0 }
3260 };
3261 int i;
3262 struct statfs fsInfo;
3263 struct flock lockInfo;
3264
3265 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003266 /* If filePath==NULL that means we are dealing with a transient file
3267 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003268 return &nolockIoMethods;
3269 }
3270 if( statfs(filePath, &fsInfo) != -1 ){
3271 if( fsInfo.f_flags & MNT_RDONLY ){
3272 return &nolockIoMethods;
3273 }
3274 for(i=0; aMap[i].zFilesystem; i++){
3275 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3276 return aMap[i].pMethods;
3277 }
3278 }
3279 }
3280
3281 /* Default case. Handles, amongst others, "nfs".
3282 ** Test byte-range lock using fcntl(). If the call succeeds,
3283 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003284 */
drh7708e972008-11-29 00:56:52 +00003285 lockInfo.l_len = 1;
3286 lockInfo.l_start = 0;
3287 lockInfo.l_whence = SEEK_SET;
3288 lockInfo.l_type = F_RDLCK;
3289 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
3290 return &posixIoMethods;
3291 }else{
3292 return &dotlockIoMethods;
3293 }
3294}
danielk1977852e2322008-12-22 03:36:59 +00003295static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
drh1875f7a2008-12-08 18:19:17 +00003296 = autolockIoFinderImpl;
3297
drhd2cb50b2009-01-09 21:41:17 +00003298#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003299
3300/*
3301** An abstract type for a pointer to a IO method finder function:
3302*/
3303typedef const sqlite3_io_methods *(*finder_type)(const char*,int);
3304
aswiftaebf4132008-11-21 00:10:35 +00003305
drh734c9862008-11-28 15:37:20 +00003306/****************************************************************************
3307**************************** sqlite3_vfs methods ****************************
3308**
3309** This division contains the implementation of methods on the
3310** sqlite3_vfs object.
3311*/
3312
danielk1977a3d4c882007-03-23 10:08:38 +00003313/*
danielk1977e339d652008-06-28 11:23:00 +00003314** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003315*/
3316static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003317 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003318 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003319 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003320 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003321 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003322 int noLock, /* Omit locking if true */
3323 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003324){
drh7708e972008-11-29 00:56:52 +00003325 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003326 unixFile *pNew = (unixFile *)pId;
3327 int rc = SQLITE_OK;
3328
danielk197717b90b52008-06-06 11:11:25 +00003329 assert( pNew->pLock==NULL );
3330 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003331
drh715ff302008-12-03 22:32:44 +00003332 /* Parameter isDelete is only used on vxworks.
3333 ** Express this explicitly here to prevent compiler warnings
3334 ** about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003335 */
drh7708e972008-11-29 00:56:52 +00003336#if !OS_VXWORKS
3337 UNUSED_PARAMETER(isDelete);
3338#endif
danielk1977a03396a2008-11-19 14:35:46 +00003339
drh218c5082008-03-07 00:27:10 +00003340 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003341 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003342 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003343 SET_THREADID(pNew);
drh339eb0b2008-03-07 15:34:11 +00003344
drh6c7d5c52008-11-21 20:32:33 +00003345#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003346 pNew->pId = vxworksFindFileId(zFilename);
3347 if( pNew->pId==0 ){
3348 noLock = 1;
3349 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003350 }
3351#endif
3352
drhda0e7682008-07-30 15:27:54 +00003353 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003354 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003355 }else{
drh1875f7a2008-12-08 18:19:17 +00003356 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, h);
aswiftaebf4132008-11-21 00:10:35 +00003357#if SQLITE_ENABLE_LOCKING_STYLE
3358 /* Cache zFilename in the locking context (AFP and dotlock override) for
3359 ** proxyLock activation is possible (remote proxy is based on db name)
3360 ** zFilename remains valid until file is closed, to support */
3361 pNew->lockingContext = (void*)zFilename;
3362#endif
drhda0e7682008-07-30 15:27:54 +00003363 }
danielk1977e339d652008-06-28 11:23:00 +00003364
drh7708e972008-11-29 00:56:52 +00003365 if( pLockingStyle == &posixIoMethods ){
3366 unixEnterMutex();
3367 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3368 unixLeaveMutex();
3369 }
danielk1977e339d652008-06-28 11:23:00 +00003370
drhd2cb50b2009-01-09 21:41:17 +00003371#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003372 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003373 /* AFP locking uses the file path so it needs to be included in
3374 ** the afpLockingContext.
3375 */
3376 afpLockingContext *pCtx;
3377 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3378 if( pCtx==0 ){
3379 rc = SQLITE_NOMEM;
3380 }else{
3381 /* NB: zFilename exists and remains valid until the file is closed
3382 ** according to requirement F11141. So we do not need to make a
3383 ** copy of the filename. */
3384 pCtx->dbPath = zFilename;
3385 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003386 unixEnterMutex();
drh7708e972008-11-29 00:56:52 +00003387 rc = findLockInfo(pNew, NULL, &pNew->pOpen);
3388 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003389 }
drh7708e972008-11-29 00:56:52 +00003390 }
3391#endif
danielk1977e339d652008-06-28 11:23:00 +00003392
drh7708e972008-11-29 00:56:52 +00003393 else if( pLockingStyle == &dotlockIoMethods ){
3394 /* Dotfile locking uses the file path so it needs to be included in
3395 ** the dotlockLockingContext
3396 */
3397 char *zLockFile;
3398 int nFilename;
drhea678832008-12-10 19:26:22 +00003399 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003400 zLockFile = (char *)sqlite3_malloc(nFilename);
3401 if( zLockFile==0 ){
3402 rc = SQLITE_NOMEM;
3403 }else{
3404 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003405 }
drh7708e972008-11-29 00:56:52 +00003406 pNew->lockingContext = zLockFile;
3407 }
danielk1977e339d652008-06-28 11:23:00 +00003408
drh6c7d5c52008-11-21 20:32:33 +00003409#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003410 else if( pLockingStyle == &semIoMethods ){
3411 /* Named semaphore locking uses the file path so it needs to be
3412 ** included in the semLockingContext
3413 */
3414 unixEnterMutex();
3415 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3416 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3417 char *zSemName = pNew->pOpen->aSemName;
3418 int n;
3419 sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem",
3420 pNew->pId->zCanonicalName);
3421 for( n=0; zSemName[n]; n++ )
3422 if( zSemName[n]=='/' ) zSemName[n] = '_';
3423 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3424 if( pNew->pOpen->pSem == SEM_FAILED ){
3425 rc = SQLITE_NOMEM;
3426 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003427 }
chw97185482008-11-17 08:05:31 +00003428 }
drh7708e972008-11-29 00:56:52 +00003429 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003430 }
drh7708e972008-11-29 00:56:52 +00003431#endif
aswift5b1a2562008-08-22 00:22:35 +00003432
3433 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003434#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003435 if( rc!=SQLITE_OK ){
3436 unlink(zFilename);
3437 isDelete = 0;
3438 }
3439 pNew->isDelete = isDelete;
3440#endif
danielk1977e339d652008-06-28 11:23:00 +00003441 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003442 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
drhbfe66312006-10-03 17:40:40 +00003443 close(h);
danielk1977e339d652008-06-28 11:23:00 +00003444 }else{
drh7708e972008-11-29 00:56:52 +00003445 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003446 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003447 }
danielk1977e339d652008-06-28 11:23:00 +00003448 return rc;
drh054889e2005-11-30 03:20:31 +00003449}
drh9c06c952005-11-26 00:25:00 +00003450
danielk1977ad94b582007-08-20 06:44:22 +00003451/*
3452** Open a file descriptor to the directory containing file zFilename.
3453** If successful, *pFd is set to the opened file descriptor and
3454** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3455** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3456** value.
3457**
3458** If SQLITE_OK is returned, the caller is responsible for closing
3459** the file descriptor *pFd using close().
3460*/
danielk1977fee2d252007-08-18 10:59:19 +00003461static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003462 int ii;
drh777b17a2007-09-20 10:02:54 +00003463 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003464 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003465
drh153c62c2007-08-24 03:51:33 +00003466 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003467 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003468 if( ii>0 ){
3469 zDirname[ii] = '\0';
3470 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003471 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003472#ifdef FD_CLOEXEC
3473 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3474#endif
3475 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3476 }
3477 }
danielk1977fee2d252007-08-18 10:59:19 +00003478 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00003479 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00003480}
3481
danielk1977b4b47412007-08-17 15:53:36 +00003482/*
danielk197717b90b52008-06-06 11:11:25 +00003483** Create a temporary file name in zBuf. zBuf must be allocated
3484** by the calling process and must be big enough to hold at least
3485** pVfs->mxPathname bytes.
3486*/
3487static int getTempname(int nBuf, char *zBuf){
3488 static const char *azDirs[] = {
3489 0,
aswiftaebf4132008-11-21 00:10:35 +00003490 0,
danielk197717b90b52008-06-06 11:11:25 +00003491 "/var/tmp",
3492 "/usr/tmp",
3493 "/tmp",
3494 ".",
3495 };
3496 static const unsigned char zChars[] =
3497 "abcdefghijklmnopqrstuvwxyz"
3498 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3499 "0123456789";
drh41022642008-11-21 00:24:42 +00003500 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003501 struct stat buf;
3502 const char *zDir = ".";
3503
3504 /* It's odd to simulate an io-error here, but really this is just
3505 ** using the io-error infrastructure to test that SQLite handles this
3506 ** function failing.
3507 */
3508 SimulateIOError( return SQLITE_IOERR );
3509
3510 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003511 if (NULL == azDirs[1]) {
3512 azDirs[1] = getenv("TMPDIR");
3513 }
3514
3515 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003516 if( azDirs[i]==0 ) continue;
3517 if( stat(azDirs[i], &buf) ) continue;
3518 if( !S_ISDIR(buf.st_mode) ) continue;
3519 if( access(azDirs[i], 07) ) continue;
3520 zDir = azDirs[i];
3521 break;
3522 }
3523
3524 /* Check that the output buffer is large enough for the temporary file
3525 ** name. If it is not, return SQLITE_ERROR.
3526 */
danielk197700e13612008-11-17 19:18:54 +00003527 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003528 return SQLITE_ERROR;
3529 }
3530
3531 do{
3532 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003533 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003534 sqlite3_randomness(15, &zBuf[j]);
3535 for(i=0; i<15; i++, j++){
3536 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3537 }
3538 zBuf[j] = 0;
3539 }while( access(zBuf,0)==0 );
3540 return SQLITE_OK;
3541}
3542
drhd2cb50b2009-01-09 21:41:17 +00003543#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003544/*
3545** Routine to transform a unixFile into a proxy-locking unixFile.
3546** Implementation in the proxy-lock division, but used by unixOpen()
3547** if SQLITE_PREFER_PROXY_LOCKING is defined.
3548*/
3549static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003550#endif
drhc66d5b62008-12-03 22:48:32 +00003551
danielk197717b90b52008-06-06 11:11:25 +00003552
3553/*
danielk1977ad94b582007-08-20 06:44:22 +00003554** Open the file zPath.
3555**
danielk1977b4b47412007-08-17 15:53:36 +00003556** Previously, the SQLite OS layer used three functions in place of this
3557** one:
3558**
3559** sqlite3OsOpenReadWrite();
3560** sqlite3OsOpenReadOnly();
3561** sqlite3OsOpenExclusive();
3562**
3563** These calls correspond to the following combinations of flags:
3564**
3565** ReadWrite() -> (READWRITE | CREATE)
3566** ReadOnly() -> (READONLY)
3567** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
3568**
3569** The old OpenExclusive() accepted a boolean argument - "delFlag". If
3570** true, the file was configured to be automatically deleted when the
3571** file handle closed. To achieve the same effect using this new
3572** interface, add the DELETEONCLOSE flag to those specified above for
3573** OpenExclusive().
3574*/
3575static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00003576 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
3577 const char *zPath, /* Pathname of file to be opened */
3578 sqlite3_file *pFile, /* The file descriptor to be filled in */
3579 int flags, /* Input flags to control the opening */
3580 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00003581){
danielk1977fee2d252007-08-18 10:59:19 +00003582 int fd = 0; /* File descriptor returned by open() */
3583 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00003584 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00003585 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00003586 int noLock; /* True to omit locking primitives */
aswiftaebf4132008-11-21 00:10:35 +00003587 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003588
3589 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
3590 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
3591 int isCreate = (flags & SQLITE_OPEN_CREATE);
3592 int isReadonly = (flags & SQLITE_OPEN_READONLY);
3593 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
3594
danielk1977fee2d252007-08-18 10:59:19 +00003595 /* If creating a master or main-file journal, this function will open
3596 ** a file-descriptor on the directory too. The first time unixSync()
3597 ** is called the directory file descriptor will be fsync()ed and close()d.
3598 */
3599 int isOpenDirectory = (isCreate &&
3600 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
3601 );
3602
danielk197717b90b52008-06-06 11:11:25 +00003603 /* If argument zPath is a NULL pointer, this function is required to open
3604 ** a temporary file. Use this buffer to store the file name in.
3605 */
3606 char zTmpname[MAX_PATHNAME+1];
3607 const char *zName = zPath;
3608
danielk1977fee2d252007-08-18 10:59:19 +00003609 /* Check the following statements are true:
3610 **
3611 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
3612 ** (b) if CREATE is set, then READWRITE must also be set, and
3613 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00003614 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00003615 */
danielk1977b4b47412007-08-17 15:53:36 +00003616 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00003617 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00003618 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00003619 assert(isDelete==0 || isCreate);
3620
drh33f4e022007-09-03 15:19:34 +00003621 /* The main DB, main journal, and master journal are never automatically
3622 ** deleted
3623 */
3624 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
3625 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
3626 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00003627
danielk1977fee2d252007-08-18 10:59:19 +00003628 /* Assert that the upper layer has set one of the "file-type" flags. */
3629 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
3630 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3631 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00003632 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00003633 );
3634
danielk1977e339d652008-06-28 11:23:00 +00003635 memset(pFile, 0, sizeof(unixFile));
3636
danielk197717b90b52008-06-06 11:11:25 +00003637 if( !zName ){
danielk197717b90b52008-06-06 11:11:25 +00003638 assert(isDelete && !isOpenDirectory);
3639 rc = getTempname(MAX_PATHNAME+1, zTmpname);
3640 if( rc!=SQLITE_OK ){
3641 return rc;
3642 }
3643 zName = zTmpname;
3644 }
3645
drh734c9862008-11-28 15:37:20 +00003646 if( isReadonly ) openFlags |= O_RDONLY;
3647 if( isReadWrite ) openFlags |= O_RDWR;
3648 if( isCreate ) openFlags |= O_CREAT;
3649 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
3650 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00003651
drh734c9862008-11-28 15:37:20 +00003652 fd = open(zName, openFlags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
3653 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
danielk19772f2d8c72007-08-30 16:13:33 +00003654 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00003655 /* Failed to open the file for read/write access. Try read-only. */
3656 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3657 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00003658 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00003659 }
3660 if( fd<0 ){
3661 return SQLITE_CANTOPEN;
3662 }
3663 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00003664#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003665 zPath = zName;
3666#else
danielk197717b90b52008-06-06 11:11:25 +00003667 unlink(zName);
chw97185482008-11-17 08:05:31 +00003668#endif
danielk1977b4b47412007-08-17 15:53:36 +00003669 }
drh41022642008-11-21 00:24:42 +00003670#if SQLITE_ENABLE_LOCKING_STYLE
3671 else{
drh734c9862008-11-28 15:37:20 +00003672 ((unixFile*)pFile)->openFlags = openFlags;
drh41022642008-11-21 00:24:42 +00003673 }
3674#endif
danielk1977b4b47412007-08-17 15:53:36 +00003675 if( pOutFlags ){
3676 *pOutFlags = flags;
3677 }
3678
3679 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00003680 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00003681 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00003682 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003683 close(fd); /* silently leak if fail, already in error */
danielk1977fee2d252007-08-18 10:59:19 +00003684 return rc;
3685 }
3686 }
danielk1977e339d652008-06-28 11:23:00 +00003687
3688#ifdef FD_CLOEXEC
3689 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3690#endif
3691
drhda0e7682008-07-30 15:27:54 +00003692 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00003693
3694#if SQLITE_PREFER_PROXY_LOCKING
3695 if( zPath!=NULL && !noLock ){
3696 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
3697 int useProxy = 0;
3698
3699 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy,
drh7708e972008-11-29 00:56:52 +00003700 ** 0 means never use proxy, NULL means use proxy for non-local files only
3701 */
aswiftaebf4132008-11-21 00:10:35 +00003702 if( envforce!=NULL ){
3703 useProxy = atoi(envforce)>0;
3704 }else{
3705 struct statfs fsInfo;
3706
3707 if( statfs(zPath, &fsInfo) == -1 ){
3708 ((unixFile*)pFile)->lastErrno = errno;
3709 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
3710 close(fd); /* silently leak if fail, in error */
3711 return SQLITE_IOERR_ACCESS;
3712 }
3713 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
3714 }
3715 if( useProxy ){
3716 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
3717 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00003718 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
aswiftaebf4132008-11-21 00:10:35 +00003719 }
3720 return rc;
3721 }
3722 }
3723#endif
3724
chw97185482008-11-17 08:05:31 +00003725 return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
danielk1977b4b47412007-08-17 15:53:36 +00003726}
3727
3728/*
danielk1977fee2d252007-08-18 10:59:19 +00003729** Delete the file at zPath. If the dirSync argument is true, fsync()
3730** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00003731*/
drh6b9d6dd2008-12-03 19:34:47 +00003732static int unixDelete(
3733 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
3734 const char *zPath, /* Name of file to be deleted */
3735 int dirSync /* If true, fsync() directory after deleting file */
3736){
danielk1977fee2d252007-08-18 10:59:19 +00003737 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00003738 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003739 SimulateIOError(return SQLITE_IOERR_DELETE);
3740 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00003741#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00003742 if( dirSync ){
3743 int fd;
3744 rc = openDirectory(zPath, &fd);
3745 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00003746#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003747 if( fsync(fd)==-1 )
3748#else
3749 if( fsync(fd) )
3750#endif
3751 {
danielk1977fee2d252007-08-18 10:59:19 +00003752 rc = SQLITE_IOERR_DIR_FSYNC;
3753 }
aswiftaebf4132008-11-21 00:10:35 +00003754 if( close(fd)&&!rc ){
3755 rc = SQLITE_IOERR_DIR_CLOSE;
3756 }
danielk1977fee2d252007-08-18 10:59:19 +00003757 }
3758 }
danielk1977d138dd82008-10-15 16:02:48 +00003759#endif
danielk1977fee2d252007-08-18 10:59:19 +00003760 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00003761}
3762
danielk197790949c22007-08-17 16:50:38 +00003763/*
3764** Test the existance of or access permissions of file zPath. The
3765** test performed depends on the value of flags:
3766**
3767** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
3768** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
3769** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
3770**
3771** Otherwise return 0.
3772*/
danielk1977861f7452008-06-05 11:39:11 +00003773static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00003774 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
3775 const char *zPath, /* Path of the file to examine */
3776 int flags, /* What do we want to learn about the zPath file? */
3777 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00003778){
rse25c0d1a2007-09-20 08:38:14 +00003779 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00003780 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00003781 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00003782 switch( flags ){
3783 case SQLITE_ACCESS_EXISTS:
3784 amode = F_OK;
3785 break;
3786 case SQLITE_ACCESS_READWRITE:
3787 amode = W_OK|R_OK;
3788 break;
drh50d3f902007-08-27 21:10:36 +00003789 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00003790 amode = R_OK;
3791 break;
3792
3793 default:
3794 assert(!"Invalid flags argument");
3795 }
danielk1977861f7452008-06-05 11:39:11 +00003796 *pResOut = (access(zPath, amode)==0);
3797 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003798}
3799
danielk1977b4b47412007-08-17 15:53:36 +00003800
3801/*
3802** Turn a relative pathname into a full pathname. The relative path
3803** is stored as a nul-terminated string in the buffer pointed to by
3804** zPath.
3805**
3806** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
3807** (in this case, MAX_PATHNAME bytes). The full-path is written to
3808** this buffer before returning.
3809*/
danielk1977adfb9b02007-09-17 07:02:56 +00003810static int unixFullPathname(
3811 sqlite3_vfs *pVfs, /* Pointer to vfs object */
3812 const char *zPath, /* Possibly relative input path */
3813 int nOut, /* Size of output buffer in bytes */
3814 char *zOut /* Output buffer */
3815){
danielk1977843e65f2007-09-01 16:16:15 +00003816
3817 /* It's odd to simulate an io-error here, but really this is just
3818 ** using the io-error infrastructure to test that SQLite handles this
3819 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00003820 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00003821 */
3822 SimulateIOError( return SQLITE_ERROR );
3823
drh153c62c2007-08-24 03:51:33 +00003824 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00003825 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00003826
drh3c7f2dc2007-12-06 13:26:20 +00003827 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00003828 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00003829 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003830 }else{
3831 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00003832 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00003833 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00003834 }
drhea678832008-12-10 19:26:22 +00003835 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00003836 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003837 }
3838 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003839}
3840
drh0ccebe72005-06-07 22:22:50 +00003841
drh761df872006-12-21 01:29:22 +00003842#ifndef SQLITE_OMIT_LOAD_EXTENSION
3843/*
3844** Interfaces for opening a shared library, finding entry points
3845** within the shared library, and closing the shared library.
3846*/
3847#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00003848static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
3849 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00003850 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
3851}
danielk197795c8a542007-09-01 06:51:27 +00003852
3853/*
3854** SQLite calls this function immediately after a call to unixDlSym() or
3855** unixDlOpen() fails (returns a null pointer). If a more detailed error
3856** message is available, it is written to zBufOut. If no error message
3857** is available, zBufOut is left unmodified and SQLite uses a default
3858** error message.
3859*/
danielk1977397d65f2008-11-19 11:35:39 +00003860static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00003861 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00003862 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00003863 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003864 zErr = dlerror();
3865 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00003866 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00003867 }
drh6c7d5c52008-11-21 20:32:33 +00003868 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003869}
drh1875f7a2008-12-08 18:19:17 +00003870static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
3871 /*
3872 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
3873 ** cast into a pointer to a function. And yet the library dlsym() routine
3874 ** returns a void* which is really a pointer to a function. So how do we
3875 ** use dlsym() with -pedantic-errors?
3876 **
3877 ** Variable x below is defined to be a pointer to a function taking
3878 ** parameters void* and const char* and returning a pointer to a function.
3879 ** We initialize x by assigning it a pointer to the dlsym() function.
3880 ** (That assignment requires a cast.) Then we call the function that
3881 ** x points to.
3882 **
3883 ** This work-around is unlikely to work correctly on any system where
3884 ** you really cannot cast a function pointer into void*. But then, on the
3885 ** other hand, dlsym() will not work on such a system either, so we have
3886 ** not really lost anything.
3887 */
3888 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00003889 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00003890 x = (void(*(*)(void*,const char*))(void))dlsym;
3891 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00003892}
danielk1977397d65f2008-11-19 11:35:39 +00003893static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
3894 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003895 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00003896}
danielk1977b4b47412007-08-17 15:53:36 +00003897#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
3898 #define unixDlOpen 0
3899 #define unixDlError 0
3900 #define unixDlSym 0
3901 #define unixDlClose 0
3902#endif
3903
3904/*
danielk197790949c22007-08-17 16:50:38 +00003905** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00003906*/
danielk1977397d65f2008-11-19 11:35:39 +00003907static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
3908 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00003909 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00003910
drhbbd42a62004-05-22 17:41:58 +00003911 /* We have to initialize zBuf to prevent valgrind from reporting
3912 ** errors. The reports issued by valgrind are incorrect - we would
3913 ** prefer that the randomness be increased by making use of the
3914 ** uninitialized space in zBuf - but valgrind errors tend to worry
3915 ** some users. Rather than argue, it seems easier just to initialize
3916 ** the whole array and silence valgrind, even if that means less randomness
3917 ** in the random seed.
3918 **
3919 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00003920 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00003921 ** tests repeatable.
3922 */
danielk1977b4b47412007-08-17 15:53:36 +00003923 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00003924#if !defined(SQLITE_TEST)
3925 {
drh842b8642005-01-21 17:53:17 +00003926 int pid, fd;
3927 fd = open("/dev/urandom", O_RDONLY);
3928 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00003929 time_t t;
3930 time(&t);
danielk197790949c22007-08-17 16:50:38 +00003931 memcpy(zBuf, &t, sizeof(t));
3932 pid = getpid();
3933 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00003934 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00003935 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00003936 }else{
drh72cbd072008-10-14 17:58:38 +00003937 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00003938 close(fd);
3939 }
drhbbd42a62004-05-22 17:41:58 +00003940 }
3941#endif
drh72cbd072008-10-14 17:58:38 +00003942 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00003943}
3944
danielk1977b4b47412007-08-17 15:53:36 +00003945
drhbbd42a62004-05-22 17:41:58 +00003946/*
3947** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00003948** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00003949** The return value is the number of microseconds of sleep actually
3950** requested from the underlying operating system, a number which
3951** might be greater than or equal to the argument, but not less
3952** than the argument.
drhbbd42a62004-05-22 17:41:58 +00003953*/
danielk1977397d65f2008-11-19 11:35:39 +00003954static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00003955#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003956 struct timespec sp;
3957
3958 sp.tv_sec = microseconds / 1000000;
3959 sp.tv_nsec = (microseconds % 1000000) * 1000;
3960 nanosleep(&sp, NULL);
danielk1977397d65f2008-11-19 11:35:39 +00003961 return microseconds;
3962#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00003963 usleep(microseconds);
3964 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00003965#else
danielk1977b4b47412007-08-17 15:53:36 +00003966 int seconds = (microseconds+999999)/1000000;
3967 sleep(seconds);
drh4a50aac2007-08-23 02:47:53 +00003968 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00003969#endif
danielk1977397d65f2008-11-19 11:35:39 +00003970 UNUSED_PARAMETER(NotUsed);
drh88f474a2006-01-02 20:00:12 +00003971}
3972
3973/*
drh6b9d6dd2008-12-03 19:34:47 +00003974** The following variable, if set to a non-zero value, is interpreted as
3975** the number of seconds since 1970 and is used to set the result of
3976** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00003977*/
3978#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00003979int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00003980#endif
3981
3982/*
3983** Find the current time (in Universal Coordinated Time). Write the
3984** current time and date as a Julian Day number into *prNow and
3985** return 0. Return 1 if the time and date cannot be found.
3986*/
danielk1977397d65f2008-11-19 11:35:39 +00003987static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh6c7d5c52008-11-21 20:32:33 +00003988#if defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00003989 time_t t;
3990 time(&t);
3991 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00003992#elif OS_VXWORKS
3993 struct timespec sNow;
3994 clock_gettime(CLOCK_REALTIME, &sNow);
3995 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00003996#else
3997 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00003998 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00003999 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
4000#endif
danielk1977397d65f2008-11-19 11:35:39 +00004001
drhbbd42a62004-05-22 17:41:58 +00004002#ifdef SQLITE_TEST
4003 if( sqlite3_current_time ){
4004 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4005 }
4006#endif
danielk1977397d65f2008-11-19 11:35:39 +00004007 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004008 return 0;
4009}
danielk1977b4b47412007-08-17 15:53:36 +00004010
drh6b9d6dd2008-12-03 19:34:47 +00004011/*
4012** We added the xGetLastError() method with the intention of providing
4013** better low-level error messages when operating-system problems come up
4014** during SQLite operation. But so far, none of that has been implemented
4015** in the core. So this routine is never called. For now, it is merely
4016** a place-holder.
4017*/
danielk1977397d65f2008-11-19 11:35:39 +00004018static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4019 UNUSED_PARAMETER(NotUsed);
4020 UNUSED_PARAMETER(NotUsed2);
4021 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004022 return 0;
4023}
4024
drh153c62c2007-08-24 03:51:33 +00004025/*
drh734c9862008-11-28 15:37:20 +00004026************************ End of sqlite3_vfs methods ***************************
4027******************************************************************************/
4028
drh715ff302008-12-03 22:32:44 +00004029/******************************************************************************
4030************************** Begin Proxy Locking ********************************
4031**
4032** Proxy locking is a "uber-locking-method" in this sense: It uses the
4033** other locking methods on secondary lock files. Proxy locking is a
4034** meta-layer over top of the primitive locking implemented above. For
4035** this reason, the division that implements of proxy locking is deferred
4036** until late in the file (here) after all of the other I/O methods have
4037** been defined - so that the primitive locking methods are available
4038** as services to help with the implementation of proxy locking.
4039**
4040****
4041**
4042** The default locking schemes in SQLite use byte-range locks on the
4043** database file to coordinate safe, concurrent access by multiple readers
4044** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4045** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4046** as POSIX read & write locks over fixed set of locations (via fsctl),
4047** on AFP and SMB only exclusive byte-range locks are available via fsctl
4048** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4049** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4050** address in the shared range is taken for a SHARED lock, the entire
4051** shared range is taken for an EXCLUSIVE lock):
4052**
4053** PENDING_BYTE 0x40000000
4054** RESERVED_BYTE 0x40000001
4055** SHARED_RANGE 0x40000002 -> 0x40000200
4056**
4057** This works well on the local file system, but shows a nearly 100x
4058** slowdown in read performance on AFP because the AFP client disables
4059** the read cache when byte-range locks are present. Enabling the read
4060** cache exposes a cache coherency problem that is present on all OS X
4061** supported network file systems. NFS and AFP both observe the
4062** close-to-open semantics for ensuring cache coherency
4063** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4064** address the requirements for concurrent database access by multiple
4065** readers and writers
4066** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4067**
4068** To address the performance and cache coherency issues, proxy file locking
4069** changes the way database access is controlled by limiting access to a
4070** single host at a time and moving file locks off of the database file
4071** and onto a proxy file on the local file system.
4072**
4073**
4074** Using proxy locks
4075** -----------------
4076**
4077** C APIs
4078**
4079** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4080** <proxy_path> | ":auto:");
4081** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4082**
4083**
4084** SQL pragmas
4085**
4086** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4087** PRAGMA [database.]lock_proxy_file
4088**
4089** Specifying ":auto:" means that if there is a conch file with a matching
4090** host ID in it, the proxy path in the conch file will be used, otherwise
4091** a proxy path based on the user's temp dir
4092** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4093** actual proxy file name is generated from the name and path of the
4094** database file. For example:
4095**
4096** For database path "/Users/me/foo.db"
4097** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4098**
4099** Once a lock proxy is configured for a database connection, it can not
4100** be removed, however it may be switched to a different proxy path via
4101** the above APIs (assuming the conch file is not being held by another
4102** connection or process).
4103**
4104**
4105** How proxy locking works
4106** -----------------------
4107**
4108** Proxy file locking relies primarily on two new supporting files:
4109**
4110** * conch file to limit access to the database file to a single host
4111** at a time
4112**
4113** * proxy file to act as a proxy for the advisory locks normally
4114** taken on the database
4115**
4116** The conch file - to use a proxy file, sqlite must first "hold the conch"
4117** by taking an sqlite-style shared lock on the conch file, reading the
4118** contents and comparing the host's unique host ID (see below) and lock
4119** proxy path against the values stored in the conch. The conch file is
4120** stored in the same directory as the database file and the file name
4121** is patterned after the database file name as ".<databasename>-conch".
4122** If the conch file does not exist, or it's contents do not match the
4123** host ID and/or proxy path, then the lock is escalated to an exclusive
4124** lock and the conch file contents is updated with the host ID and proxy
4125** path and the lock is downgraded to a shared lock again. If the conch
4126** is held by another process (with a shared lock), the exclusive lock
4127** will fail and SQLITE_BUSY is returned.
4128**
4129** The proxy file - a single-byte file used for all advisory file locks
4130** normally taken on the database file. This allows for safe sharing
4131** of the database file for multiple readers and writers on the same
4132** host (the conch ensures that they all use the same local lock file).
4133**
4134** There is a third file - the host ID file - used as a persistent record
4135** of a unique identifier for the host, a 128-byte unique host id file
4136** in the path defined by the HOSTIDPATH macro (default value is
4137** /Library/Caches/.com.apple.sqliteConchHostId).
4138**
4139** Requesting the lock proxy does not immediately take the conch, it is
4140** only taken when the first request to lock database file is made.
4141** This matches the semantics of the traditional locking behavior, where
4142** opening a connection to a database file does not take a lock on it.
4143** The shared lock and an open file descriptor are maintained until
4144** the connection to the database is closed.
4145**
4146** The proxy file and the lock file are never deleted so they only need
4147** to be created the first time they are used.
4148**
4149** Configuration options
4150** ---------------------
4151**
4152** SQLITE_PREFER_PROXY_LOCKING
4153**
4154** Database files accessed on non-local file systems are
4155** automatically configured for proxy locking, lock files are
4156** named automatically using the same logic as
4157** PRAGMA lock_proxy_file=":auto:"
4158**
4159** SQLITE_PROXY_DEBUG
4160**
4161** Enables the logging of error messages during host id file
4162** retrieval and creation
4163**
4164** HOSTIDPATH
4165**
4166** Overrides the default host ID file path location
4167**
4168** LOCKPROXYDIR
4169**
4170** Overrides the default directory used for lock proxy files that
4171** are named automatically via the ":auto:" setting
4172**
4173** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4174**
4175** Permissions to use when creating a directory for storing the
4176** lock proxy files, only used when LOCKPROXYDIR is not set.
4177**
4178**
4179** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4180** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4181** force proxy locking to be used for every database file opened, and 0
4182** will force automatic proxy locking to be disabled for all database
4183** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4184** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4185*/
4186
4187/*
4188** Proxy locking is only available on MacOSX
4189*/
drhd2cb50b2009-01-09 21:41:17 +00004190#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004191
4192#ifdef SQLITE_TEST
4193/* simulate multiple hosts by creating unique hostid file paths */
4194int sqlite3_hostid_num = 0;
4195#endif
4196
4197/*
4198** The proxyLockingContext has the path and file structures for the remote
4199** and local proxy files in it
4200*/
4201typedef struct proxyLockingContext proxyLockingContext;
4202struct proxyLockingContext {
4203 unixFile *conchFile; /* Open conch file */
4204 char *conchFilePath; /* Name of the conch file */
4205 unixFile *lockProxy; /* Open proxy lock file */
4206 char *lockProxyPath; /* Name of the proxy lock file */
4207 char *dbPath; /* Name of the open file */
4208 int conchHeld; /* True if the conch is currently held */
4209 void *oldLockingContext; /* Original lockingcontext to restore on close */
4210 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4211};
4212
4213/* HOSTIDLEN and CONCHLEN both include space for the string
4214** terminating nul
4215*/
4216#define HOSTIDLEN 128
4217#define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
4218#ifndef HOSTIDPATH
4219# define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
4220#endif
4221
4222/* basically a copy of unixRandomness with different
4223** test behavior built in */
4224static int proxyGenerateHostID(char *pHostID){
4225 int pid, fd, len;
4226 unsigned char *key = (unsigned char *)pHostID;
4227
4228 memset(key, 0, HOSTIDLEN);
4229 len = 0;
4230 fd = open("/dev/urandom", O_RDONLY);
4231 if( fd>=0 ){
4232 len = read(fd, key, HOSTIDLEN);
4233 close(fd); /* silently leak the fd if it fails */
4234 }
4235 if( len < HOSTIDLEN ){
4236 time_t t;
4237 time(&t);
4238 memcpy(key, &t, sizeof(t));
4239 pid = getpid();
4240 memcpy(&key[sizeof(t)], &pid, sizeof(pid));
4241 }
4242
4243#ifdef MAKE_PRETTY_HOSTID
4244 {
4245 int i;
4246 /* filter the bytes into printable ascii characters and NUL terminate */
4247 key[(HOSTIDLEN-1)] = 0x00;
4248 for( i=0; i<(HOSTIDLEN-1); i++ ){
4249 unsigned char pa = key[i]&0x7F;
4250 if( pa<0x20 ){
4251 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
4252 }else if( pa==0x7F ){
4253 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
4254 }
4255 }
4256 }
4257#endif
4258 return SQLITE_OK;
4259}
4260
4261/* writes the host id path to path, path should be an pre-allocated buffer
4262** with enough space for a path
4263*/
4264static void proxyGetHostIDPath(char *path, size_t len){
4265 strlcpy(path, HOSTIDPATH, len);
4266#ifdef SQLITE_TEST
4267 if( sqlite3_hostid_num>0 ){
4268 char suffix[2] = "1";
4269 suffix[0] = suffix[0] + sqlite3_hostid_num;
4270 strlcat(path, suffix, len);
4271 }
4272#endif
4273 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
4274}
4275
4276/* get the host ID from a sqlite hostid file stored in the
4277** user-specific tmp directory, create the ID if it's not there already
4278*/
4279static int proxyGetHostID(char *pHostID, int *pError){
4280 int fd;
4281 char path[MAXPATHLEN];
4282 size_t len;
4283 int rc=SQLITE_OK;
4284
4285 proxyGetHostIDPath(path, MAXPATHLEN);
4286 /* try to create the host ID file, if it already exists read the contents */
4287 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
4288 if( fd<0 ){
4289 int err=errno;
4290
4291 if( err!=EEXIST ){
4292#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4293 fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
4294 path, strerror(err));
4295#endif
4296 return SQLITE_PERM;
4297 }
4298 /* couldn't create the file, read it instead */
4299 fd = open(path, O_RDONLY|O_EXCL);
4300 if( fd<0 ){
4301#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4302 int err = errno;
4303 fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
4304 path, strerror(err));
4305#endif
4306 return SQLITE_PERM;
4307 }
4308 len = pread(fd, pHostID, HOSTIDLEN, 0);
4309 if( len<0 ){
4310 *pError = errno;
4311 rc = SQLITE_IOERR_READ;
4312 }else if( len<HOSTIDLEN ){
4313 *pError = 0;
4314 rc = SQLITE_IOERR_SHORT_READ;
4315 }
4316 close(fd); /* silently leak the fd if it fails */
4317 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
4318 return rc;
4319 }else{
4320 /* we're creating the host ID file (use a random string of bytes) */
4321 proxyGenerateHostID(pHostID);
4322 len = pwrite(fd, pHostID, HOSTIDLEN, 0);
4323 if( len<0 ){
4324 *pError = errno;
4325 rc = SQLITE_IOERR_WRITE;
4326 }else if( len<HOSTIDLEN ){
4327 *pError = 0;
4328 rc = SQLITE_IOERR_WRITE;
4329 }
4330 close(fd); /* silently leak the fd if it fails */
4331 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
4332 return rc;
4333 }
4334}
4335
4336static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4337 int len;
4338 int dbLen;
4339 int i;
4340
4341#ifdef LOCKPROXYDIR
4342 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4343#else
4344# ifdef _CS_DARWIN_USER_TEMP_DIR
4345 {
4346 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
4347 len = strlcat(lPath, "sqliteplocks", maxLen);
4348 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4349 /* if mkdir fails, handle as lock file creation failure */
4350 int err = errno;
4351# ifdef SQLITE_DEBUG
4352 if( err!=EEXIST ){
4353 fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
4354 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
4355 }
4356# endif
4357 }else{
4358 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
4359 }
4360
4361 }
4362# else
4363 len = strlcpy(lPath, "/tmp/", maxLen);
4364# endif
4365#endif
4366
4367 if( lPath[len-1]!='/' ){
4368 len = strlcat(lPath, "/", maxLen);
4369 }
4370
4371 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004372 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004373 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4374 char c = dbPath[i];
4375 lPath[i+len] = (c=='/')?'_':c;
4376 }
4377 lPath[i+len]='\0';
4378 strlcat(lPath, ":auto:", maxLen);
4379 return SQLITE_OK;
4380}
4381
4382/*
4383** Create a new VFS file descriptor (stored in memory obtained from
4384** sqlite3_malloc) and open the file named "path" in the file descriptor.
4385**
4386** The caller is responsible not only for closing the file descriptor
4387** but also for freeing the memory associated with the file descriptor.
4388*/
4389static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
4390 int fd;
4391 int dirfd = -1;
4392 unixFile *pNew;
4393 int rc = SQLITE_OK;
4394 sqlite3_vfs dummyVfs;
4395
4396 fd = open(path, O_RDWR | O_CREAT, SQLITE_DEFAULT_FILE_PERMISSIONS);
4397 if( fd<0 ){
4398 return SQLITE_CANTOPEN;
4399 }
4400
4401 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
4402 if( pNew==NULL ){
4403 rc = SQLITE_NOMEM;
4404 goto end_create_proxy;
4405 }
4406 memset(pNew, 0, sizeof(unixFile));
4407
drh1875f7a2008-12-08 18:19:17 +00004408 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh715ff302008-12-03 22:32:44 +00004409 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
4410 if( rc==SQLITE_OK ){
4411 *ppFile = pNew;
4412 return SQLITE_OK;
4413 }
4414end_create_proxy:
4415 close(fd); /* silently leak fd if error, we're already in error */
4416 sqlite3_free(pNew);
4417 return rc;
4418}
4419
4420/* takes the conch by taking a shared lock and read the contents conch, if
4421** lockPath is non-NULL, the host ID and lock file path must match. A NULL
4422** lockPath means that the lockPath in the conch file will be used if the
4423** host IDs match, or a new lock path will be generated automatically
4424** and written to the conch file.
4425*/
4426static int proxyTakeConch(unixFile *pFile){
4427 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4428
4429 if( pCtx->conchHeld>0 ){
4430 return SQLITE_OK;
4431 }else{
4432 unixFile *conchFile = pCtx->conchFile;
4433 char testValue[CONCHLEN];
4434 char conchValue[CONCHLEN];
4435 char lockPath[MAXPATHLEN];
4436 char *tLockPath = NULL;
4437 int rc = SQLITE_OK;
4438 int readRc = SQLITE_OK;
4439 int syncPerms = 0;
4440
4441 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
4442 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
4443
4444 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
4445 if( rc==SQLITE_OK ){
4446 int pError = 0;
drh1875f7a2008-12-08 18:19:17 +00004447 memset(testValue, 0, CONCHLEN); /* conch is fixed size */
drh715ff302008-12-03 22:32:44 +00004448 rc = proxyGetHostID(testValue, &pError);
4449 if( (rc&0xff)==SQLITE_IOERR ){
4450 pFile->lastErrno = pError;
4451 }
4452 if( pCtx->lockProxyPath ){
4453 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
4454 }
4455 }
4456 if( rc!=SQLITE_OK ){
4457 goto end_takeconch;
4458 }
4459
4460 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
4461 if( readRc!=SQLITE_IOERR_SHORT_READ ){
4462 if( readRc!=SQLITE_OK ){
4463 if( (rc&0xff)==SQLITE_IOERR ){
4464 pFile->lastErrno = conchFile->lastErrno;
4465 }
4466 rc = readRc;
4467 goto end_takeconch;
4468 }
4469 /* if the conch has data compare the contents */
4470 if( !pCtx->lockProxyPath ){
4471 /* for auto-named local lock file, just check the host ID and we'll
4472 ** use the local lock file path that's already in there */
4473 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
4474 tLockPath = (char *)&conchValue[HOSTIDLEN];
4475 goto end_takeconch;
4476 }
4477 }else{
4478 /* we've got the conch if conchValue matches our path and host ID */
4479 if( !memcmp(testValue, conchValue, CONCHLEN) ){
4480 goto end_takeconch;
4481 }
4482 }
4483 }else{
4484 /* a short read means we're "creating" the conch (even though it could
4485 ** have been user-intervention), if we acquire the exclusive lock,
4486 ** we'll try to match the current on-disk permissions of the database
4487 */
4488 syncPerms = 1;
4489 }
4490
4491 /* either conch was emtpy or didn't match */
4492 if( !pCtx->lockProxyPath ){
4493 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
4494 tLockPath = lockPath;
4495 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
4496 }
4497
4498 /* update conch with host and path (this will fail if other process
4499 ** has a shared lock already) */
4500 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
4501 if( rc==SQLITE_OK ){
4502 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
4503 if( rc==SQLITE_OK && syncPerms ){
4504 struct stat buf;
4505 int err = fstat(pFile->h, &buf);
4506 if( err==0 ){
4507 /* try to match the database file permissions, ignore failure */
4508#ifndef SQLITE_PROXY_DEBUG
4509 fchmod(conchFile->h, buf.st_mode);
4510#else
4511 if( fchmod(conchFile->h, buf.st_mode)!=0 ){
4512 int code = errno;
4513 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
4514 buf.st_mode, code, strerror(code));
4515 } else {
4516 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
4517 }
4518 }else{
4519 int code = errno;
4520 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
4521 err, code, strerror(code));
4522#endif
4523 }
4524 }
4525 }
4526 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
4527
4528end_takeconch:
4529 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
4530 if( rc==SQLITE_OK && pFile->openFlags ){
4531 if( pFile->h>=0 ){
4532#ifdef STRICT_CLOSE_ERROR
4533 if( close(pFile->h) ){
4534 pFile->lastErrno = errno;
4535 return SQLITE_IOERR_CLOSE;
4536 }
4537#else
4538 close(pFile->h); /* silently leak fd if fail */
4539#endif
4540 }
4541 pFile->h = -1;
4542 int fd = open(pCtx->dbPath, pFile->openFlags,
4543 SQLITE_DEFAULT_FILE_PERMISSIONS);
4544 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
4545 if( fd>=0 ){
4546 pFile->h = fd;
4547 }else{
drh1875f7a2008-12-08 18:19:17 +00004548 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
4549 during locking */
drh715ff302008-12-03 22:32:44 +00004550 }
4551 }
4552 if( rc==SQLITE_OK && !pCtx->lockProxy ){
4553 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
drh1875f7a2008-12-08 18:19:17 +00004554 /* ACS: Need to make a copy of path sometimes */
drh715ff302008-12-03 22:32:44 +00004555 rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
4556 }
4557 if( rc==SQLITE_OK ){
4558 pCtx->conchHeld = 1;
4559
4560 if( tLockPath ){
4561 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
4562 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
4563 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
4564 pCtx->lockProxyPath;
4565 }
4566 }
4567 } else {
4568 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4569 }
4570 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
4571 return rc;
4572 }
4573}
4574
4575/*
4576** If pFile holds a lock on a conch file, then release that lock.
4577*/
4578static int proxyReleaseConch(unixFile *pFile){
4579 int rc; /* Subroutine return code */
4580 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
4581 unixFile *conchFile; /* Name of the conch file */
4582
4583 pCtx = (proxyLockingContext *)pFile->lockingContext;
4584 conchFile = pCtx->conchFile;
4585 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
4586 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
4587 getpid());
4588 pCtx->conchHeld = 0;
4589 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4590 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
4591 (rc==SQLITE_OK ? "ok" : "failed"));
4592 return rc;
4593}
4594
4595/*
4596** Given the name of a database file, compute the name of its conch file.
4597** Store the conch filename in memory obtained from sqlite3_malloc().
4598** Make *pConchPath point to the new name. Return SQLITE_OK on success
4599** or SQLITE_NOMEM if unable to obtain memory.
4600**
4601** The caller is responsible for ensuring that the allocated memory
4602** space is eventually freed.
4603**
4604** *pConchPath is set to NULL if a memory allocation error occurs.
4605*/
4606static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
4607 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00004608 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00004609 char *conchPath; /* buffer in which to construct conch name */
4610
4611 /* Allocate space for the conch filename and initialize the name to
4612 ** the name of the original database file. */
4613 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
4614 if( conchPath==0 ){
4615 return SQLITE_NOMEM;
4616 }
4617 memcpy(conchPath, dbPath, len+1);
4618
4619 /* now insert a "." before the last / character */
4620 for( i=(len-1); i>=0; i-- ){
4621 if( conchPath[i]=='/' ){
4622 i++;
4623 break;
4624 }
4625 }
4626 conchPath[i]='.';
4627 while ( i<len ){
4628 conchPath[i+1]=dbPath[i];
4629 i++;
4630 }
4631
4632 /* append the "-conch" suffix to the file */
4633 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00004634 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00004635
4636 return SQLITE_OK;
4637}
4638
4639
4640/* Takes a fully configured proxy locking-style unix file and switches
4641** the local lock file path
4642*/
4643static int switchLockProxyPath(unixFile *pFile, const char *path) {
4644 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4645 char *oldPath = pCtx->lockProxyPath;
4646 int rc = SQLITE_OK;
4647
4648 if( pFile->locktype!=NO_LOCK ){
4649 return SQLITE_BUSY;
4650 }
4651
4652 /* nothing to do if the path is NULL, :auto: or matches the existing path */
4653 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
4654 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
4655 return SQLITE_OK;
4656 }else{
4657 unixFile *lockProxy = pCtx->lockProxy;
4658 pCtx->lockProxy=NULL;
4659 pCtx->conchHeld = 0;
4660 if( lockProxy!=NULL ){
4661 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
4662 if( rc ) return rc;
4663 sqlite3_free(lockProxy);
4664 }
4665 sqlite3_free(oldPath);
4666 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
4667 }
4668
4669 return rc;
4670}
4671
4672/*
4673** pFile is a file that has been opened by a prior xOpen call. dbPath
4674** is a string buffer at least MAXPATHLEN+1 characters in size.
4675**
4676** This routine find the filename associated with pFile and writes it
4677** int dbPath.
4678*/
4679static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00004680#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00004681 if( pFile->pMethod == &afpIoMethods ){
4682 /* afp style keeps a reference to the db path in the filePath field
4683 ** of the struct */
drhea678832008-12-10 19:26:22 +00004684 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh715ff302008-12-03 22:32:44 +00004685 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
4686 }else
4687#endif
4688 if( pFile->pMethod == &dotlockIoMethods ){
4689 /* dot lock style uses the locking context to store the dot lock
4690 ** file path */
4691 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
4692 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
4693 }else{
4694 /* all other styles use the locking context to store the db file path */
4695 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
4696 strcpy(dbPath, (char *)pFile->lockingContext);
4697 }
4698 return SQLITE_OK;
4699}
4700
4701/*
4702** Takes an already filled in unix file and alters it so all file locking
4703** will be performed on the local proxy lock file. The following fields
4704** are preserved in the locking context so that they can be restored and
4705** the unix structure properly cleaned up at close time:
4706** ->lockingContext
4707** ->pMethod
4708*/
4709static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
4710 proxyLockingContext *pCtx;
4711 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
4712 char *lockPath=NULL;
4713 int rc = SQLITE_OK;
4714
4715 if( pFile->locktype!=NO_LOCK ){
4716 return SQLITE_BUSY;
4717 }
4718 proxyGetDbPathForUnixFile(pFile, dbPath);
4719 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
4720 lockPath=NULL;
4721 }else{
4722 lockPath=(char *)path;
4723 }
4724
4725 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
4726 (lockPath ? lockPath : ":auto:"), getpid());
4727
4728 pCtx = sqlite3_malloc( sizeof(*pCtx) );
4729 if( pCtx==0 ){
4730 return SQLITE_NOMEM;
4731 }
4732 memset(pCtx, 0, sizeof(*pCtx));
4733
4734 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
4735 if( rc==SQLITE_OK ){
4736 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
4737 }
4738 if( rc==SQLITE_OK && lockPath ){
4739 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
4740 }
4741
4742 if( rc==SQLITE_OK ){
4743 /* all memory is allocated, proxys are created and assigned,
4744 ** switch the locking context and pMethod then return.
4745 */
4746 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
4747 pCtx->oldLockingContext = pFile->lockingContext;
4748 pFile->lockingContext = pCtx;
4749 pCtx->pOldMethod = pFile->pMethod;
4750 pFile->pMethod = &proxyIoMethods;
4751 }else{
4752 if( pCtx->conchFile ){
4753 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
4754 if( rc ) return rc;
4755 sqlite3_free(pCtx->conchFile);
4756 }
4757 sqlite3_free(pCtx->conchFilePath);
4758 sqlite3_free(pCtx);
4759 }
4760 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
4761 (rc==SQLITE_OK ? "ok" : "failed"));
4762 return rc;
4763}
4764
4765
4766/*
4767** This routine handles sqlite3_file_control() calls that are specific
4768** to proxy locking.
4769*/
4770static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
4771 switch( op ){
4772 case SQLITE_GET_LOCKPROXYFILE: {
4773 unixFile *pFile = (unixFile*)id;
4774 if( pFile->pMethod == &proxyIoMethods ){
4775 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4776 proxyTakeConch(pFile);
4777 if( pCtx->lockProxyPath ){
4778 *(const char **)pArg = pCtx->lockProxyPath;
4779 }else{
4780 *(const char **)pArg = ":auto: (not held)";
4781 }
4782 } else {
4783 *(const char **)pArg = NULL;
4784 }
4785 return SQLITE_OK;
4786 }
4787 case SQLITE_SET_LOCKPROXYFILE: {
4788 unixFile *pFile = (unixFile*)id;
4789 int rc = SQLITE_OK;
4790 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
4791 if( pArg==NULL || (const char *)pArg==0 ){
4792 if( isProxyStyle ){
4793 /* turn off proxy locking - not supported */
4794 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
4795 }else{
4796 /* turn off proxy locking - already off - NOOP */
4797 rc = SQLITE_OK;
4798 }
4799 }else{
4800 const char *proxyPath = (const char *)pArg;
4801 if( isProxyStyle ){
4802 proxyLockingContext *pCtx =
4803 (proxyLockingContext*)pFile->lockingContext;
4804 if( !strcmp(pArg, ":auto:")
4805 || (pCtx->lockProxyPath &&
4806 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
4807 ){
4808 rc = SQLITE_OK;
4809 }else{
4810 rc = switchLockProxyPath(pFile, proxyPath);
4811 }
4812 }else{
4813 /* turn on proxy file locking */
4814 rc = proxyTransformUnixFile(pFile, proxyPath);
4815 }
4816 }
4817 return rc;
4818 }
4819 default: {
4820 assert( 0 ); /* The call assures that only valid opcodes are sent */
4821 }
4822 }
4823 /*NOTREACHED*/
4824 return SQLITE_ERROR;
4825}
4826
4827/*
4828** Within this division (the proxying locking implementation) the procedures
4829** above this point are all utilities. The lock-related methods of the
4830** proxy-locking sqlite3_io_method object follow.
4831*/
4832
4833
4834/*
4835** This routine checks if there is a RESERVED lock held on the specified
4836** file by this or any other process. If such a lock is held, set *pResOut
4837** to a non-zero value otherwise *pResOut is set to zero. The return value
4838** is set to SQLITE_OK unless an I/O error occurs during lock checking.
4839*/
4840static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
4841 unixFile *pFile = (unixFile*)id;
4842 int rc = proxyTakeConch(pFile);
4843 if( rc==SQLITE_OK ){
4844 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4845 unixFile *proxy = pCtx->lockProxy;
4846 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
4847 }
4848 return rc;
4849}
4850
4851/*
4852** Lock the file with the lock specified by parameter locktype - one
4853** of the following:
4854**
4855** (1) SHARED_LOCK
4856** (2) RESERVED_LOCK
4857** (3) PENDING_LOCK
4858** (4) EXCLUSIVE_LOCK
4859**
4860** Sometimes when requesting one lock state, additional lock states
4861** are inserted in between. The locking might fail on one of the later
4862** transitions leaving the lock state different from what it started but
4863** still short of its goal. The following chart shows the allowed
4864** transitions and the inserted intermediate states:
4865**
4866** UNLOCKED -> SHARED
4867** SHARED -> RESERVED
4868** SHARED -> (PENDING) -> EXCLUSIVE
4869** RESERVED -> (PENDING) -> EXCLUSIVE
4870** PENDING -> EXCLUSIVE
4871**
4872** This routine will only increase a lock. Use the sqlite3OsUnlock()
4873** routine to lower a locking level.
4874*/
4875static int proxyLock(sqlite3_file *id, int locktype) {
4876 unixFile *pFile = (unixFile*)id;
4877 int rc = proxyTakeConch(pFile);
4878 if( rc==SQLITE_OK ){
4879 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4880 unixFile *proxy = pCtx->lockProxy;
4881 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
4882 pFile->locktype = proxy->locktype;
4883 }
4884 return rc;
4885}
4886
4887
4888/*
4889** Lower the locking level on file descriptor pFile to locktype. locktype
4890** must be either NO_LOCK or SHARED_LOCK.
4891**
4892** If the locking level of the file descriptor is already at or below
4893** the requested locking level, this routine is a no-op.
4894*/
4895static int proxyUnlock(sqlite3_file *id, int locktype) {
4896 unixFile *pFile = (unixFile*)id;
4897 int rc = proxyTakeConch(pFile);
4898 if( rc==SQLITE_OK ){
4899 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4900 unixFile *proxy = pCtx->lockProxy;
4901 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
4902 pFile->locktype = proxy->locktype;
4903 }
4904 return rc;
4905}
4906
4907/*
4908** Close a file that uses proxy locks.
4909*/
4910static int proxyClose(sqlite3_file *id) {
4911 if( id ){
4912 unixFile *pFile = (unixFile*)id;
4913 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4914 unixFile *lockProxy = pCtx->lockProxy;
4915 unixFile *conchFile = pCtx->conchFile;
4916 int rc = SQLITE_OK;
4917
4918 if( lockProxy ){
4919 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
4920 if( rc ) return rc;
4921 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
4922 if( rc ) return rc;
4923 sqlite3_free(lockProxy);
4924 pCtx->lockProxy = 0;
4925 }
4926 if( conchFile ){
4927 if( pCtx->conchHeld ){
4928 rc = proxyReleaseConch(pFile);
4929 if( rc ) return rc;
4930 }
4931 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
4932 if( rc ) return rc;
4933 sqlite3_free(conchFile);
4934 }
4935 sqlite3_free(pCtx->lockProxyPath);
4936 sqlite3_free(pCtx->conchFilePath);
4937 sqlite3_free(pCtx->dbPath);
4938 /* restore the original locking context and pMethod then close it */
4939 pFile->lockingContext = pCtx->oldLockingContext;
4940 pFile->pMethod = pCtx->pOldMethod;
4941 sqlite3_free(pCtx);
4942 return pFile->pMethod->xClose(id);
4943 }
4944 return SQLITE_OK;
4945}
4946
4947
4948
drhd2cb50b2009-01-09 21:41:17 +00004949#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00004950/*
4951** The proxy locking style is intended for use with AFP filesystems.
4952** And since AFP is only supported on MacOSX, the proxy locking is also
4953** restricted to MacOSX.
4954**
4955**
4956******************* End of the proxy lock implementation **********************
4957******************************************************************************/
4958
drh734c9862008-11-28 15:37:20 +00004959/*
danielk1977e339d652008-06-28 11:23:00 +00004960** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00004961**
4962** This routine registers all VFS implementations for unix-like operating
4963** systems. This routine, and the sqlite3_os_end() routine that follows,
4964** should be the only routines in this file that are visible from other
4965** files.
drh6b9d6dd2008-12-03 19:34:47 +00004966**
4967** This routine is called once during SQLite initialization and by a
4968** single thread. The memory allocation and mutex subsystems have not
4969** necessarily been initialized when this routine is called, and so they
4970** should not be used.
drh153c62c2007-08-24 03:51:33 +00004971*/
danielk1977c0fa4c52008-06-25 17:19:00 +00004972int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00004973 /*
4974 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00004975 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
4976 ** to the "finder" function. (pAppData is a pointer to a pointer because
4977 ** silly C90 rules prohibit a void* from being cast to a function pointer
4978 ** and so we have to go through the intermediate pointer to avoid problems
4979 ** when compiling with -pedantic-errors on GCC.)
4980 **
4981 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00004982 ** finder-function. The finder-function returns a pointer to the
4983 ** sqlite_io_methods object that implements the desired locking
4984 ** behaviors. See the division above that contains the IOMETHODS
4985 ** macro for addition information on finder-functions.
4986 **
4987 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
4988 ** object. But the "autolockIoFinder" available on MacOSX does a little
4989 ** more than that; it looks at the filesystem type that hosts the
4990 ** database file and tries to choose an locking method appropriate for
4991 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00004992 */
drh7708e972008-11-29 00:56:52 +00004993 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00004994 1, /* iVersion */ \
4995 sizeof(unixFile), /* szOsFile */ \
4996 MAX_PATHNAME, /* mxPathname */ \
4997 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00004998 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00004999 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00005000 unixOpen, /* xOpen */ \
5001 unixDelete, /* xDelete */ \
5002 unixAccess, /* xAccess */ \
5003 unixFullPathname, /* xFullPathname */ \
5004 unixDlOpen, /* xDlOpen */ \
5005 unixDlError, /* xDlError */ \
5006 unixDlSym, /* xDlSym */ \
5007 unixDlClose, /* xDlClose */ \
5008 unixRandomness, /* xRandomness */ \
5009 unixSleep, /* xSleep */ \
5010 unixCurrentTime, /* xCurrentTime */ \
5011 unixGetLastError /* xGetLastError */ \
5012 }
5013
drh6b9d6dd2008-12-03 19:34:47 +00005014 /*
5015 ** All default VFSes for unix are contained in the following array.
5016 **
5017 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5018 ** by the SQLite core when the VFS is registered. So the following
5019 ** array cannot be const.
5020 */
danielk1977e339d652008-06-28 11:23:00 +00005021 static sqlite3_vfs aVfs[] = {
drhd2cb50b2009-01-09 21:41:17 +00005022#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005023 UNIXVFS("unix", autolockIoFinder ),
5024#else
5025 UNIXVFS("unix", posixIoFinder ),
5026#endif
5027 UNIXVFS("unix-none", nolockIoFinder ),
5028 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005029#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005030 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005031#endif
5032#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005033 UNIXVFS("unix-posix", posixIoFinder ),
5034 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005035#endif
drhd2cb50b2009-01-09 21:41:17 +00005036#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005037 UNIXVFS("unix-afp", afpIoFinder ),
5038 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005039#endif
drh153c62c2007-08-24 03:51:33 +00005040 };
drh6b9d6dd2008-12-03 19:34:47 +00005041 unsigned int i; /* Loop counter */
5042
5043 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005044 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005045 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005046 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005047 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005048}
danielk1977e339d652008-06-28 11:23:00 +00005049
5050/*
drh6b9d6dd2008-12-03 19:34:47 +00005051** Shutdown the operating system interface.
5052**
5053** Some operating systems might need to do some cleanup in this routine,
5054** to release dynamically allocated objects. But not on unix.
5055** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005056*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005057int sqlite3_os_end(void){
5058 return SQLITE_OK;
5059}
drhdce8bdb2007-08-16 13:01:44 +00005060
danielk197729bafea2008-06-26 10:41:19 +00005061#endif /* SQLITE_OS_UNIX */