blob: f972b591d81a7fb5fb1e25b85d615fb335407dd3 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
danielk1977e339d652008-06-28 11:23:00 +0000122
drh40bbb0a2008-09-23 10:23:26 +0000123#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000124# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000125# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000126# include <semaphore.h>
127# include <limits.h>
128# else
drh9b35ea62008-11-29 02:20:26 +0000129# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <sys/param.h>
131# include <sys/mount.h>
132# endif
drhbfe66312006-10-03 17:40:40 +0000133#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000134
135/*
drhf1a221e2006-01-15 17:27:17 +0000136** If we are to be thread-safe, include the pthreads header and define
137** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000138*/
drhd677b3d2007-08-20 22:48:41 +0000139#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000140# include <pthread.h>
141# define SQLITE_UNIX_THREADS 1
142#endif
143
144/*
145** Default permissions when creating a new file
146*/
147#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
148# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
149#endif
150
danielk1977b4b47412007-08-17 15:53:36 +0000151/*
aswiftaebf4132008-11-21 00:10:35 +0000152 ** Default permissions when creating auto proxy dir
153 */
154#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
155# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
156#endif
157
158/*
danielk1977b4b47412007-08-17 15:53:36 +0000159** Maximum supported path-length.
160*/
161#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000162
drh734c9862008-11-28 15:37:20 +0000163/*
drh734c9862008-11-28 15:37:20 +0000164** Only set the lastErrno if the error code is a real error and not
165** a normal expected return code of SQLITE_BUSY or SQLITE_OK
166*/
167#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
168
drh9cbe6352005-11-29 03:13:21 +0000169
170/*
drh9b35ea62008-11-29 02:20:26 +0000171** The unixFile structure is subclass of sqlite3_file specific to the unix
172** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000173*/
drh054889e2005-11-30 03:20:31 +0000174typedef struct unixFile unixFile;
175struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000176 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh6c7d5c52008-11-21 20:32:33 +0000177 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
178 struct unixLockInfo *pLock; /* Info about locks on this inode */
179 int h; /* The file descriptor */
180 int dirfd; /* File descriptor for the directory */
181 unsigned char locktype; /* The type of lock held on this fd */
182 int lastErrno; /* The unix errno from the last I/O error */
drh6c7d5c52008-11-21 20:32:33 +0000183 void *lockingContext; /* Locking style specific state */
drh08c6d442009-02-09 17:34:07 +0000184#if SQLITE_ENABLE_LOCKING_STYLE
185 int openFlags; /* The flags specified at open() */
186#endif
drh734c9862008-11-28 15:37:20 +0000187#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 */
drh08c6d442009-02-09 17:34:07 +0000205
206 /* If true, that means we are dealing with a database file that has
207 ** a range of locking bytes from PENDING_BYTE through PENDING_BYTE+511
208 ** which should never be read or written. Asserts() will verify this */
209 unsigned char isLockable; /* True if file might be locked */
drh8f941bc2009-01-14 23:03:40 +0000210#endif
danielk1977967a4a12007-08-20 14:23:44 +0000211#ifdef SQLITE_TEST
212 /* In test mode, increase the size of this structure a bit so that
213 ** it is larger than the struct CrashFile defined in test6.c.
214 */
215 char aPadding[32];
216#endif
drh9cbe6352005-11-29 03:13:21 +0000217};
218
drh0ccebe72005-06-07 22:22:50 +0000219/*
drh198bf392006-01-06 21:52:49 +0000220** Include code that is common to all os_*.c files
221*/
222#include "os_common.h"
223
224/*
drh0ccebe72005-06-07 22:22:50 +0000225** Define various macros that are missing from some systems.
226*/
drhbbd42a62004-05-22 17:41:58 +0000227#ifndef O_LARGEFILE
228# define O_LARGEFILE 0
229#endif
230#ifdef SQLITE_DISABLE_LFS
231# undef O_LARGEFILE
232# define O_LARGEFILE 0
233#endif
234#ifndef O_NOFOLLOW
235# define O_NOFOLLOW 0
236#endif
237#ifndef O_BINARY
238# define O_BINARY 0
239#endif
240
241/*
242** The DJGPP compiler environment looks mostly like Unix, but it
243** lacks the fcntl() system call. So redefine fcntl() to be something
244** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000245** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000246*/
247#ifdef __DJGPP__
248# define fcntl(A,B,C) 0
249#endif
250
251/*
drh2b4b5962005-06-15 17:47:55 +0000252** The threadid macro resolves to the thread-id or to 0. Used for
253** testing and debugging only.
254*/
drhd677b3d2007-08-20 22:48:41 +0000255#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000256#define threadid pthread_self()
257#else
258#define threadid 0
259#endif
260
danielk197713adf8a2004-06-03 16:08:41 +0000261
drh107886a2008-11-21 22:21:50 +0000262/*
dan9359c7b2009-08-21 08:29:10 +0000263** Helper functions to obtain and relinquish the global mutex. The
264** global mutex is used to protect the unixOpenCnt, unixLockInfo and
265** vxworksFileId objects used by this file, all of which may be
266** shared by multiple threads.
267**
268** Function unixMutexHeld() is used to assert() that the global mutex
269** is held when required. This function is only used as part of assert()
270** statements. e.g.
271**
272** unixEnterMutex()
273** assert( unixMutexHeld() );
274** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000275*/
276static void unixEnterMutex(void){
277 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
278}
279static void unixLeaveMutex(void){
280 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
281}
dan9359c7b2009-08-21 08:29:10 +0000282#ifdef SQLITE_DEBUG
283static int unixMutexHeld(void) {
284 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
285}
286#endif
drh107886a2008-11-21 22:21:50 +0000287
drh734c9862008-11-28 15:37:20 +0000288
289#ifdef SQLITE_DEBUG
290/*
291** Helper function for printing out trace information from debugging
292** binaries. This returns the string represetation of the supplied
293** integer lock-type.
294*/
295static const char *locktypeName(int locktype){
296 switch( locktype ){
dan9359c7b2009-08-21 08:29:10 +0000297 case NO_LOCK: return "NONE";
298 case SHARED_LOCK: return "SHARED";
299 case RESERVED_LOCK: return "RESERVED";
300 case PENDING_LOCK: return "PENDING";
301 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000302 }
303 return "ERROR";
304}
305#endif
306
307#ifdef SQLITE_LOCK_TRACE
308/*
309** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000310**
drh734c9862008-11-28 15:37:20 +0000311** This routine is used for troubleshooting locks on multithreaded
312** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
313** command-line option on the compiler. This code is normally
314** turned off.
315*/
316static int lockTrace(int fd, int op, struct flock *p){
317 char *zOpName, *zType;
318 int s;
319 int savedErrno;
320 if( op==F_GETLK ){
321 zOpName = "GETLK";
322 }else if( op==F_SETLK ){
323 zOpName = "SETLK";
324 }else{
325 s = fcntl(fd, op, p);
326 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
327 return s;
328 }
329 if( p->l_type==F_RDLCK ){
330 zType = "RDLCK";
331 }else if( p->l_type==F_WRLCK ){
332 zType = "WRLCK";
333 }else if( p->l_type==F_UNLCK ){
334 zType = "UNLCK";
335 }else{
336 assert( 0 );
337 }
338 assert( p->l_whence==SEEK_SET );
339 s = fcntl(fd, op, p);
340 savedErrno = errno;
341 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
342 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
343 (int)p->l_pid, s);
344 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
345 struct flock l2;
346 l2 = *p;
347 fcntl(fd, F_GETLK, &l2);
348 if( l2.l_type==F_RDLCK ){
349 zType = "RDLCK";
350 }else if( l2.l_type==F_WRLCK ){
351 zType = "WRLCK";
352 }else if( l2.l_type==F_UNLCK ){
353 zType = "UNLCK";
354 }else{
355 assert( 0 );
356 }
357 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
358 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
359 }
360 errno = savedErrno;
361 return s;
362}
363#define fcntl lockTrace
364#endif /* SQLITE_LOCK_TRACE */
365
366
367
368/*
369** This routine translates a standard POSIX errno code into something
370** useful to the clients of the sqlite3 functions. Specifically, it is
371** intended to translate a variety of "try again" errors into SQLITE_BUSY
372** and a variety of "please close the file descriptor NOW" errors into
373** SQLITE_IOERR
374**
375** Errors during initialization of locks, or file system support for locks,
376** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
377*/
378static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
379 switch (posixError) {
380 case 0:
381 return SQLITE_OK;
382
383 case EAGAIN:
384 case ETIMEDOUT:
385 case EBUSY:
386 case EINTR:
387 case ENOLCK:
388 /* random NFS retry error, unless during file system support
389 * introspection, in which it actually means what it says */
390 return SQLITE_BUSY;
391
392 case EACCES:
393 /* EACCES is like EAGAIN during locking operations, but not any other time*/
394 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
395 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
396 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
397 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
398 return SQLITE_BUSY;
399 }
400 /* else fall through */
401 case EPERM:
402 return SQLITE_PERM;
403
404 case EDEADLK:
405 return SQLITE_IOERR_BLOCKED;
406
407#if EOPNOTSUPP!=ENOTSUP
408 case EOPNOTSUPP:
409 /* something went terribly awry, unless during file system support
410 * introspection, in which it actually means what it says */
411#endif
412#ifdef ENOTSUP
413 case ENOTSUP:
414 /* invalid fd, unless during file system support introspection, in which
415 * it actually means what it says */
416#endif
417 case EIO:
418 case EBADF:
419 case EINVAL:
420 case ENOTCONN:
421 case ENODEV:
422 case ENXIO:
423 case ENOENT:
424 case ESTALE:
425 case ENOSYS:
426 /* these should force the client to close the file and reconnect */
427
428 default:
429 return sqliteIOErr;
430 }
431}
432
433
434
435/******************************************************************************
436****************** Begin Unique File ID Utility Used By VxWorks ***************
437**
438** On most versions of unix, we can get a unique ID for a file by concatenating
439** the device number and the inode number. But this does not work on VxWorks.
440** On VxWorks, a unique file id must be based on the canonical filename.
441**
442** A pointer to an instance of the following structure can be used as a
443** unique file ID in VxWorks. Each instance of this structure contains
444** a copy of the canonical filename. There is also a reference count.
445** The structure is reclaimed when the number of pointers to it drops to
446** zero.
447**
448** There are never very many files open at one time and lookups are not
449** a performance-critical path, so it is sufficient to put these
450** structures on a linked list.
451*/
452struct vxworksFileId {
453 struct vxworksFileId *pNext; /* Next in a list of them all */
454 int nRef; /* Number of references to this one */
455 int nName; /* Length of the zCanonicalName[] string */
456 char *zCanonicalName; /* Canonical filename */
457};
458
459#if OS_VXWORKS
460/*
drh9b35ea62008-11-29 02:20:26 +0000461** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000462** variable:
463*/
464static struct vxworksFileId *vxworksFileList = 0;
465
466/*
467** Simplify a filename into its canonical form
468** by making the following changes:
469**
470** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000471** * convert /./ into just /
472** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000473**
474** Changes are made in-place. Return the new name length.
475**
476** The original filename is in z[0..n-1]. Return the number of
477** characters in the simplified name.
478*/
479static int vxworksSimplifyName(char *z, int n){
480 int i, j;
481 while( n>1 && z[n-1]=='/' ){ n--; }
482 for(i=j=0; i<n; i++){
483 if( z[i]=='/' ){
484 if( z[i+1]=='/' ) continue;
485 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
486 i += 1;
487 continue;
488 }
489 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
490 while( j>0 && z[j-1]!='/' ){ j--; }
491 if( j>0 ){ j--; }
492 i += 2;
493 continue;
494 }
495 }
496 z[j++] = z[i];
497 }
498 z[j] = 0;
499 return j;
500}
501
502/*
503** Find a unique file ID for the given absolute pathname. Return
504** a pointer to the vxworksFileId object. This pointer is the unique
505** file ID.
506**
507** The nRef field of the vxworksFileId object is incremented before
508** the object is returned. A new vxworksFileId object is created
509** and added to the global list if necessary.
510**
511** If a memory allocation error occurs, return NULL.
512*/
513static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
514 struct vxworksFileId *pNew; /* search key and new file ID */
515 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
516 int n; /* Length of zAbsoluteName string */
517
518 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000519 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000520 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
521 if( pNew==0 ) return 0;
522 pNew->zCanonicalName = (char*)&pNew[1];
523 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
524 n = vxworksSimplifyName(pNew->zCanonicalName, n);
525
526 /* Search for an existing entry that matching the canonical name.
527 ** If found, increment the reference count and return a pointer to
528 ** the existing file ID.
529 */
530 unixEnterMutex();
531 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
532 if( pCandidate->nName==n
533 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
534 ){
535 sqlite3_free(pNew);
536 pCandidate->nRef++;
537 unixLeaveMutex();
538 return pCandidate;
539 }
540 }
541
542 /* No match was found. We will make a new file ID */
543 pNew->nRef = 1;
544 pNew->nName = n;
545 pNew->pNext = vxworksFileList;
546 vxworksFileList = pNew;
547 unixLeaveMutex();
548 return pNew;
549}
550
551/*
552** Decrement the reference count on a vxworksFileId object. Free
553** the object when the reference count reaches zero.
554*/
555static void vxworksReleaseFileId(struct vxworksFileId *pId){
556 unixEnterMutex();
557 assert( pId->nRef>0 );
558 pId->nRef--;
559 if( pId->nRef==0 ){
560 struct vxworksFileId **pp;
561 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
562 assert( *pp==pId );
563 *pp = pId->pNext;
564 sqlite3_free(pId);
565 }
566 unixLeaveMutex();
567}
568#endif /* OS_VXWORKS */
569/*************** End of Unique File ID Utility Used By VxWorks ****************
570******************************************************************************/
571
572
573/******************************************************************************
574*************************** Posix Advisory Locking ****************************
575**
drh9b35ea62008-11-29 02:20:26 +0000576** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000577** section 6.5.2.2 lines 483 through 490 specify that when a process
578** sets or clears a lock, that operation overrides any prior locks set
579** by the same process. It does not explicitly say so, but this implies
580** that it overrides locks set by the same process using a different
581** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000582**
583** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000584** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
585**
586** Suppose ./file1 and ./file2 are really the same file (because
587** one is a hard or symbolic link to the other) then if you set
588** an exclusive lock on fd1, then try to get an exclusive lock
589** on fd2, it works. I would have expected the second lock to
590** fail since there was already a lock on the file due to fd1.
591** But not so. Since both locks came from the same process, the
592** second overrides the first, even though they were on different
593** file descriptors opened on different file names.
594**
drh734c9862008-11-28 15:37:20 +0000595** This means that we cannot use POSIX locks to synchronize file access
596** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000597** to synchronize access for threads in separate processes, but not
598** threads within the same process.
599**
600** To work around the problem, SQLite has to manage file locks internally
601** on its own. Whenever a new database is opened, we have to find the
602** specific inode of the database file (the inode is determined by the
603** st_dev and st_ino fields of the stat structure that fstat() fills in)
604** and check for locks already existing on that inode. When locks are
605** created or removed, we have to look at our own internal record of the
606** locks to see if another thread has previously set a lock on that same
607** inode.
608**
drh9b35ea62008-11-29 02:20:26 +0000609** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
610** For VxWorks, we have to use the alternative unique ID system based on
611** canonical filename and implemented in the previous division.)
612**
danielk1977ad94b582007-08-20 06:44:22 +0000613** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000614** descriptor. It is now a structure that holds the integer file
615** descriptor and a pointer to a structure that describes the internal
616** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000617** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000618** point to the same locking structure. The locking structure keeps
619** a reference count (so we will know when to delete it) and a "cnt"
620** field that tells us its internal lock status. cnt==0 means the
621** file is unlocked. cnt==-1 means the file has an exclusive lock.
622** cnt>0 means there are cnt shared locks on the file.
623**
624** Any attempt to lock or unlock a file first checks the locking
625** structure. The fcntl() system call is only invoked to set a
626** POSIX lock if the internal lock structure transitions between
627** a locked and an unlocked state.
628**
drh734c9862008-11-28 15:37:20 +0000629** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000630**
631** If you close a file descriptor that points to a file that has locks,
632** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000633** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000634** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000635** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000636** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000637** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000638** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000639** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000640** be closed and that list is walked (and cleared) when the last lock
641** clears.
642**
drh9b35ea62008-11-29 02:20:26 +0000643** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000644**
drh9b35ea62008-11-29 02:20:26 +0000645** Many older versions of linux use the LinuxThreads library which is
646** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000647** A cannot be modified or overridden by a different thread B.
648** Only thread A can modify the lock. Locking behavior is correct
649** if the appliation uses the newer Native Posix Thread Library (NPTL)
650** on linux - with NPTL a lock created by thread A can override locks
651** in thread B. But there is no way to know at compile-time which
652** threading library is being used. So there is no way to know at
653** compile-time whether or not thread A can override locks on thread B.
654** We have to do a run-time check to discover the behavior of the
655** current process.
drh5fdae772004-06-29 03:29:00 +0000656**
drh734c9862008-11-28 15:37:20 +0000657** On systems where thread A is unable to modify locks created by
658** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000659** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000660** structure to record this information. And on those systems it
661** is illegal to begin a transaction in one thread and finish it
662** in another. For this latter restriction, there is no work-around.
663** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000664*/
665
666/*
drh6c7d5c52008-11-21 20:32:33 +0000667** Set or check the unixFile.tid field. This field is set when an unixFile
668** is first opened. All subsequent uses of the unixFile verify that the
669** same thread is operating on the unixFile. Some operating systems do
670** not allow locks to be overridden by other threads and that restriction
671** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000672** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000673**
674** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
675** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000676** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000677** or if no locks are held. But the unixFile.pLock field needs to be
678** recomputed because its key includes the thread-id. See the
679** transferOwnership() function below for additional information
680*/
drh734c9862008-11-28 15:37:20 +0000681#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000682# define SET_THREADID(X) (X)->tid = pthread_self()
683# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
684 !pthread_equal((X)->tid, pthread_self()))
685#else
686# define SET_THREADID(X)
687# define CHECK_THREADID(X) 0
688#endif
689
690/*
drhbbd42a62004-05-22 17:41:58 +0000691** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000692** to locate a particular unixOpenCnt structure given its inode. This
693** is the same as the unixLockKey except that the thread ID is omitted.
694*/
695struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000696 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000697#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000698 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000699#else
drh107886a2008-11-21 22:21:50 +0000700 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000701#endif
702};
703
704/*
705** An instance of the following structure serves as the key used
706** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000707**
drh734c9862008-11-28 15:37:20 +0000708** If threads cannot override each others locks (LinuxThreads), then we
709** set the unixLockKey.tid field to the thread ID. If threads can override
710** each others locks (Posix and NPTL) then tid is always set to zero.
711** tid is omitted if we compile without threading support or on an OS
712** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000713*/
drh6c7d5c52008-11-21 20:32:33 +0000714struct unixLockKey {
715 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000716#if SQLITE_THREADSAFE && defined(__linux__)
717 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000718#endif
drhbbd42a62004-05-22 17:41:58 +0000719};
720
721/*
722** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000723** inode. Or, on LinuxThreads, there is one of these structures for
724** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000725**
danielk1977ad94b582007-08-20 06:44:22 +0000726** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000727** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000728** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000729*/
drh6c7d5c52008-11-21 20:32:33 +0000730struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000731 struct unixLockKey lockKey; /* The lookup key */
732 int cnt; /* Number of SHARED locks held */
733 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
734 int nRef; /* Number of pointers to this structure */
735 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
736 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000737};
738
739/*
740** An instance of the following structure is allocated for each open
741** inode. This structure keeps track of the number of locks on that
742** inode. If a close is attempted against an inode that is holding
743** locks, the close is deferred until all locks clear by adding the
744** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000745**
746** TODO: Consider changing this so that there is only a single file
747** descriptor for each open file, even when it is opened multiple times.
748** The close() system call would only occur when the last database
749** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000750*/
drh6c7d5c52008-11-21 20:32:33 +0000751struct unixOpenCnt {
752 struct unixFileId fileId; /* The lookup key */
753 int nRef; /* Number of pointers to this structure */
754 int nLock; /* Number of outstanding locks */
755 int nPending; /* Number of pending close() operations */
dan9359c7b2009-08-21 08:29:10 +0000756 int *aPending; /* Malloced space holding fds awaiting close() */
drh6c7d5c52008-11-21 20:32:33 +0000757#if OS_VXWORKS
758 sem_t *pSem; /* Named POSIX semaphore */
chw97185482008-11-17 08:05:31 +0000759 char aSemName[MAX_PATHNAME+1]; /* Name of that semaphore */
760#endif
drh6c7d5c52008-11-21 20:32:33 +0000761 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000762};
763
drhda0e7682008-07-30 15:27:54 +0000764/*
drh9b35ea62008-11-29 02:20:26 +0000765** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
766** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000767** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000768** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000769*/
drh6c7d5c52008-11-21 20:32:33 +0000770static struct unixLockInfo *lockList = 0;
771static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000772
drh5fdae772004-06-29 03:29:00 +0000773/*
drh9b35ea62008-11-29 02:20:26 +0000774** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000775** locks.
776**
drh9b35ea62008-11-29 02:20:26 +0000777** 0: No. Threads cannot override each others locks. (LinuxThreads)
778** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000779** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000780**
drh5062d3a2006-01-31 23:03:35 +0000781** On some systems, we know at compile-time if threads can override each
782** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
783** will be set appropriately. On other systems, we have to check at
784** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
785** undefined.
786**
drhf1a221e2006-01-15 17:27:17 +0000787** This variable normally has file scope only. But during testing, we make
788** it a global so that the test code can change its value in order to verify
789** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000790*/
drh715ff302008-12-03 22:32:44 +0000791#if SQLITE_THREADSAFE && defined(__linux__)
792# ifndef SQLITE_THREAD_OVERRIDE_LOCK
793# define SQLITE_THREAD_OVERRIDE_LOCK -1
794# endif
795# ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000796int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000797# else
drh5062d3a2006-01-31 23:03:35 +0000798static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000799# endif
drh029b44b2006-01-15 00:13:15 +0000800#endif
drh5fdae772004-06-29 03:29:00 +0000801
802/*
803** This structure holds information passed into individual test
804** threads by the testThreadLockingBehavior() routine.
805*/
806struct threadTestData {
807 int fd; /* File to be locked */
808 struct flock lock; /* The locking operation */
809 int result; /* Result of the locking operation */
810};
811
drh6c7d5c52008-11-21 20:32:33 +0000812#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000813/*
danielk197741a6a612008-11-11 18:34:35 +0000814** This function is used as the main routine for a thread launched by
815** testThreadLockingBehavior(). It tests whether the shared-lock obtained
816** by the main thread in testThreadLockingBehavior() conflicts with a
817** hypothetical write-lock obtained by this thread on the same file.
818**
819** The write-lock is not actually acquired, as this is not possible if
820** the file is open in read-only mode (see ticket #3472).
821*/
drh5fdae772004-06-29 03:29:00 +0000822static void *threadLockingTest(void *pArg){
823 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000824 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000825 return pArg;
826}
drh6c7d5c52008-11-21 20:32:33 +0000827#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000828
drh6c7d5c52008-11-21 20:32:33 +0000829
830#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000831/*
832** This procedure attempts to determine whether or not threads
833** can override each others locks then sets the
834** threadsOverrideEachOthersLocks variable appropriately.
835*/
danielk19774d5238f2006-01-27 06:32:00 +0000836static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000837 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000838 int rc;
839 struct threadTestData d;
840 struct flock l;
841 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000842
843 fd = dup(fd_orig);
844 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000845 memset(&l, 0, sizeof(l));
846 l.l_type = F_RDLCK;
847 l.l_len = 1;
848 l.l_start = 0;
849 l.l_whence = SEEK_SET;
850 rc = fcntl(fd_orig, F_SETLK, &l);
851 if( rc!=0 ) return;
852 memset(&d, 0, sizeof(d));
853 d.fd = fd;
854 d.lock = l;
855 d.lock.l_type = F_WRLCK;
drh06150f92009-07-03 12:57:58 +0000856 if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
857 pthread_join(t, 0);
858 }
drh5fdae772004-06-29 03:29:00 +0000859 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000860 if( d.result!=0 ) return;
861 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000862}
drh06150f92009-07-03 12:57:58 +0000863#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000864
drhbbd42a62004-05-22 17:41:58 +0000865/*
drh6c7d5c52008-11-21 20:32:33 +0000866** Release a unixLockInfo structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000867**
868** The mutex entered using the unixEnterMutex() function must be held
869** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000870*/
871static void releaseLockInfo(struct unixLockInfo *pLock){
dan9359c7b2009-08-21 08:29:10 +0000872 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000873 if( pLock ){
874 pLock->nRef--;
875 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000876 if( pLock->pPrev ){
877 assert( pLock->pPrev->pNext==pLock );
878 pLock->pPrev->pNext = pLock->pNext;
879 }else{
880 assert( lockList==pLock );
881 lockList = pLock->pNext;
882 }
883 if( pLock->pNext ){
884 assert( pLock->pNext->pPrev==pLock );
885 pLock->pNext->pPrev = pLock->pPrev;
886 }
danielk1977e339d652008-06-28 11:23:00 +0000887 sqlite3_free(pLock);
888 }
drhbbd42a62004-05-22 17:41:58 +0000889 }
890}
891
892/*
drh6c7d5c52008-11-21 20:32:33 +0000893** Release a unixOpenCnt structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000894**
895** The mutex entered using the unixEnterMutex() function must be held
896** when this function is called.
drhbbd42a62004-05-22 17:41:58 +0000897*/
drh6c7d5c52008-11-21 20:32:33 +0000898static void releaseOpenCnt(struct unixOpenCnt *pOpen){
dan9359c7b2009-08-21 08:29:10 +0000899 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000900 if( pOpen ){
901 pOpen->nRef--;
902 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000903 if( pOpen->pPrev ){
904 assert( pOpen->pPrev->pNext==pOpen );
905 pOpen->pPrev->pNext = pOpen->pNext;
906 }else{
907 assert( openList==pOpen );
908 openList = pOpen->pNext;
909 }
910 if( pOpen->pNext ){
911 assert( pOpen->pNext->pPrev==pOpen );
912 pOpen->pNext->pPrev = pOpen->pPrev;
913 }
914 sqlite3_free(pOpen->aPending);
danielk1977e339d652008-06-28 11:23:00 +0000915 sqlite3_free(pOpen);
916 }
drhbbd42a62004-05-22 17:41:58 +0000917 }
918}
919
drh6c7d5c52008-11-21 20:32:33 +0000920/*
921** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
922** describes that file descriptor. Create new ones if necessary. The
923** return values might be uninitialized if an error occurs.
924**
dan9359c7b2009-08-21 08:29:10 +0000925** The mutex entered using the unixEnterMutex() function must be held
926** when this function is called.
927**
drh6c7d5c52008-11-21 20:32:33 +0000928** Return an appropriate error code.
929*/
930static int findLockInfo(
931 unixFile *pFile, /* Unix file with file desc used in the key */
932 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
933 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
934){
935 int rc; /* System call return code */
936 int fd; /* The file descriptor for pFile */
937 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
938 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
939 struct stat statbuf; /* Low-level file information */
drh0d588bb2009-06-17 13:09:38 +0000940 struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000941 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
942
dan9359c7b2009-08-21 08:29:10 +0000943 assert( unixMutexHeld() );
944
drh6c7d5c52008-11-21 20:32:33 +0000945 /* Get low-level information about the file that we can used to
946 ** create a unique name for the file.
947 */
948 fd = pFile->h;
949 rc = fstat(fd, &statbuf);
950 if( rc!=0 ){
951 pFile->lastErrno = errno;
952#ifdef EOVERFLOW
953 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
954#endif
955 return SQLITE_IOERR;
956 }
957
drheb0d74f2009-02-03 15:27:02 +0000958#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000959 /* On OS X on an msdos filesystem, the inode number is reported
960 ** incorrectly for zero-size files. See ticket #3260. To work
961 ** around this problem (we consider it a bug in OS X, not SQLite)
962 ** we always increase the file size to 1 by writing a single byte
963 ** prior to accessing the inode number. The one byte written is
964 ** an ASCII 'S' character which also happens to be the first byte
965 ** in the header of every SQLite database. In this way, if there
966 ** is a race condition such that another thread has already populated
967 ** the first page of the database, no damage is done.
968 */
969 if( statbuf.st_size==0 ){
drheb0d74f2009-02-03 15:27:02 +0000970 rc = write(fd, "S", 1);
971 if( rc!=1 ){
972 return SQLITE_IOERR;
973 }
drh6c7d5c52008-11-21 20:32:33 +0000974 rc = fstat(fd, &statbuf);
975 if( rc!=0 ){
976 pFile->lastErrno = errno;
977 return SQLITE_IOERR;
978 }
979 }
drheb0d74f2009-02-03 15:27:02 +0000980#endif
drh6c7d5c52008-11-21 20:32:33 +0000981
982 memset(&lockKey, 0, sizeof(lockKey));
983 lockKey.fid.dev = statbuf.st_dev;
984#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000985 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000986#else
987 lockKey.fid.ino = statbuf.st_ino;
988#endif
drh734c9862008-11-28 15:37:20 +0000989#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000990 if( threadsOverrideEachOthersLocks<0 ){
991 testThreadLockingBehavior(fd);
992 }
993 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
994#endif
995 fileId = lockKey.fid;
996 if( ppLock!=0 ){
997 pLock = lockList;
998 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
999 pLock = pLock->pNext;
1000 }
1001 if( pLock==0 ){
1002 pLock = sqlite3_malloc( sizeof(*pLock) );
1003 if( pLock==0 ){
1004 rc = SQLITE_NOMEM;
1005 goto exit_findlockinfo;
1006 }
1007 pLock->lockKey = lockKey;
1008 pLock->nRef = 1;
1009 pLock->cnt = 0;
1010 pLock->locktype = 0;
1011 pLock->pNext = lockList;
1012 pLock->pPrev = 0;
1013 if( lockList ) lockList->pPrev = pLock;
1014 lockList = pLock;
1015 }else{
1016 pLock->nRef++;
1017 }
1018 *ppLock = pLock;
1019 }
1020 if( ppOpen!=0 ){
1021 pOpen = openList;
1022 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
1023 pOpen = pOpen->pNext;
1024 }
1025 if( pOpen==0 ){
1026 pOpen = sqlite3_malloc( sizeof(*pOpen) );
1027 if( pOpen==0 ){
1028 releaseLockInfo(pLock);
1029 rc = SQLITE_NOMEM;
1030 goto exit_findlockinfo;
1031 }
1032 pOpen->fileId = fileId;
1033 pOpen->nRef = 1;
1034 pOpen->nLock = 0;
1035 pOpen->nPending = 0;
1036 pOpen->aPending = 0;
1037 pOpen->pNext = openList;
1038 pOpen->pPrev = 0;
1039 if( openList ) openList->pPrev = pOpen;
1040 openList = pOpen;
1041#if OS_VXWORKS
1042 pOpen->pSem = NULL;
1043 pOpen->aSemName[0] = '\0';
1044#endif
1045 }else{
1046 pOpen->nRef++;
1047 }
1048 *ppOpen = pOpen;
1049 }
1050
1051exit_findlockinfo:
1052 return rc;
1053}
drh6c7d5c52008-11-21 20:32:33 +00001054
drh7708e972008-11-29 00:56:52 +00001055/*
1056** If we are currently in a different thread than the thread that the
1057** unixFile argument belongs to, then transfer ownership of the unixFile
1058** over to the current thread.
1059**
1060** A unixFile is only owned by a thread on systems that use LinuxThreads.
1061**
1062** Ownership transfer is only allowed if the unixFile is currently unlocked.
1063** If the unixFile is locked and an ownership is wrong, then return
1064** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1065*/
1066#if SQLITE_THREADSAFE && defined(__linux__)
1067static int transferOwnership(unixFile *pFile){
1068 int rc;
1069 pthread_t hSelf;
1070 if( threadsOverrideEachOthersLocks ){
1071 /* Ownership transfers not needed on this system */
1072 return SQLITE_OK;
1073 }
1074 hSelf = pthread_self();
1075 if( pthread_equal(pFile->tid, hSelf) ){
1076 /* We are still in the same thread */
1077 OSTRACE1("No-transfer, same thread\n");
1078 return SQLITE_OK;
1079 }
1080 if( pFile->locktype!=NO_LOCK ){
1081 /* We cannot change ownership while we are holding a lock! */
1082 return SQLITE_MISUSE;
1083 }
1084 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1085 pFile->h, pFile->tid, hSelf);
1086 pFile->tid = hSelf;
1087 if (pFile->pLock != NULL) {
1088 releaseLockInfo(pFile->pLock);
1089 rc = findLockInfo(pFile, &pFile->pLock, 0);
1090 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1091 locktypeName(pFile->locktype),
1092 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1093 return rc;
1094 } else {
1095 return SQLITE_OK;
1096 }
1097}
1098#else /* if not SQLITE_THREADSAFE */
1099 /* On single-threaded builds, ownership transfer is a no-op */
1100# define transferOwnership(X) SQLITE_OK
1101#endif /* SQLITE_THREADSAFE */
1102
aswift5b1a2562008-08-22 00:22:35 +00001103
1104/*
danielk197713adf8a2004-06-03 16:08:41 +00001105** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001106** file by this or any other process. If such a lock is held, set *pResOut
1107** to a non-zero value otherwise *pResOut is set to zero. The return value
1108** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001109*/
danielk1977861f7452008-06-05 11:39:11 +00001110static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001111 int rc = SQLITE_OK;
1112 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001113 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001114
danielk1977861f7452008-06-05 11:39:11 +00001115 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1116
drh054889e2005-11-30 03:20:31 +00001117 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001118 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001119
1120 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001121 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001122 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001123 }
1124
drh2ac3ee92004-06-07 16:27:46 +00001125 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001126 */
danielk197709480a92009-02-09 05:32:32 +00001127#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001128 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001129 struct flock lock;
1130 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001131 lock.l_start = RESERVED_BYTE;
1132 lock.l_len = 1;
1133 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001134 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1135 int tErrno = errno;
1136 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1137 pFile->lastErrno = tErrno;
1138 } else if( lock.l_type!=F_UNLCK ){
1139 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001140 }
1141 }
danielk197709480a92009-02-09 05:32:32 +00001142#endif
danielk197713adf8a2004-06-03 16:08:41 +00001143
drh6c7d5c52008-11-21 20:32:33 +00001144 unixLeaveMutex();
aswift5b1a2562008-08-22 00:22:35 +00001145 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001146
aswift5b1a2562008-08-22 00:22:35 +00001147 *pResOut = reserved;
1148 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001149}
1150
1151/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001152** Lock the file with the lock specified by parameter locktype - one
1153** of the following:
1154**
drh2ac3ee92004-06-07 16:27:46 +00001155** (1) SHARED_LOCK
1156** (2) RESERVED_LOCK
1157** (3) PENDING_LOCK
1158** (4) EXCLUSIVE_LOCK
1159**
drhb3e04342004-06-08 00:47:47 +00001160** Sometimes when requesting one lock state, additional lock states
1161** are inserted in between. The locking might fail on one of the later
1162** transitions leaving the lock state different from what it started but
1163** still short of its goal. The following chart shows the allowed
1164** transitions and the inserted intermediate states:
1165**
1166** UNLOCKED -> SHARED
1167** SHARED -> RESERVED
1168** SHARED -> (PENDING) -> EXCLUSIVE
1169** RESERVED -> (PENDING) -> EXCLUSIVE
1170** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001171**
drha6abd042004-06-09 17:37:22 +00001172** This routine will only increase a lock. Use the sqlite3OsUnlock()
1173** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001174*/
danielk197762079062007-08-15 17:08:46 +00001175static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001176 /* The following describes the implementation of the various locks and
1177 ** lock transitions in terms of the POSIX advisory shared and exclusive
1178 ** lock primitives (called read-locks and write-locks below, to avoid
1179 ** confusion with SQLite lock names). The algorithms are complicated
1180 ** slightly in order to be compatible with windows systems simultaneously
1181 ** accessing the same database file, in case that is ever required.
1182 **
1183 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1184 ** byte', each single bytes at well known offsets, and the 'shared byte
1185 ** range', a range of 510 bytes at a well known offset.
1186 **
1187 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1188 ** byte'. If this is successful, a random byte from the 'shared byte
1189 ** range' is read-locked and the lock on the 'pending byte' released.
1190 **
danielk197790ba3bd2004-06-25 08:32:25 +00001191 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1192 ** A RESERVED lock is implemented by grabbing a write-lock on the
1193 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001194 **
1195 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001196 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1197 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1198 ** obtained, but existing SHARED locks are allowed to persist. A process
1199 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1200 ** This property is used by the algorithm for rolling back a journal file
1201 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001202 **
danielk197790ba3bd2004-06-25 08:32:25 +00001203 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1204 ** implemented by obtaining a write-lock on the entire 'shared byte
1205 ** range'. Since all other locks require a read-lock on one of the bytes
1206 ** within this range, this ensures that no other locks are held on the
1207 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001208 **
1209 ** The reason a single byte cannot be used instead of the 'shared byte
1210 ** range' is that some versions of windows do not support read-locks. By
1211 ** locking a random byte from a range, concurrent SHARED locks may exist
1212 ** even if the locking primitive used is always a write-lock.
1213 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001214 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001215 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001216 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001217 struct flock lock;
1218 int s;
1219
drh054889e2005-11-30 03:20:31 +00001220 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001221 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001222 locktypeName(locktype), locktypeName(pFile->locktype),
1223 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001224
1225 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001226 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001227 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001228 */
drh054889e2005-11-30 03:20:31 +00001229 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001230 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001231 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001232 return SQLITE_OK;
1233 }
1234
drhb3e04342004-06-08 00:47:47 +00001235 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001236 */
drh054889e2005-11-30 03:20:31 +00001237 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001238 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001239 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001240
drh054889e2005-11-30 03:20:31 +00001241 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001242 */
drh6c7d5c52008-11-21 20:32:33 +00001243 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001244
drh029b44b2006-01-15 00:13:15 +00001245 /* Make sure the current thread owns the pFile.
1246 */
1247 rc = transferOwnership(pFile);
1248 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001249 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001250 return rc;
1251 }
drh64b1bea2006-01-15 02:30:57 +00001252 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001253
danielk1977ad94b582007-08-20 06:44:22 +00001254 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001255 ** handle that precludes the requested lock, return BUSY.
1256 */
drh054889e2005-11-30 03:20:31 +00001257 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001258 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001259 ){
1260 rc = SQLITE_BUSY;
1261 goto end_lock;
1262 }
1263
1264 /* If a SHARED lock is requested, and some thread using this PID already
1265 ** has a SHARED or RESERVED lock, then increment reference counts and
1266 ** return SQLITE_OK.
1267 */
1268 if( locktype==SHARED_LOCK &&
1269 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1270 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001271 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001272 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001273 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001274 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001275 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001276 goto end_lock;
1277 }
1278
danielk197713adf8a2004-06-03 16:08:41 +00001279 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001280
danielk19779a1d0ab2004-06-01 14:09:28 +00001281 lock.l_whence = SEEK_SET;
1282
drh3cde3bb2004-06-12 02:17:14 +00001283 /* A PENDING lock is needed before acquiring a SHARED lock and before
1284 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1285 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001286 */
drh3cde3bb2004-06-12 02:17:14 +00001287 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001288 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001289 ){
danielk1977489468c2004-06-28 08:25:47 +00001290 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001291 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001292 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001293 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001294 int tErrno = errno;
1295 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1296 if( IS_LOCK_ERROR(rc) ){
1297 pFile->lastErrno = tErrno;
1298 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001299 goto end_lock;
1300 }
drh3cde3bb2004-06-12 02:17:14 +00001301 }
1302
1303
1304 /* If control gets to this point, then actually go ahead and make
1305 ** operating system calls for the specified lock.
1306 */
1307 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001308 int tErrno = 0;
drh3cde3bb2004-06-12 02:17:14 +00001309 assert( pLock->cnt==0 );
1310 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001311
drh2ac3ee92004-06-07 16:27:46 +00001312 /* Now get the read-lock */
1313 lock.l_start = SHARED_FIRST;
1314 lock.l_len = SHARED_SIZE;
aswift5b1a2562008-08-22 00:22:35 +00001315 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1316 tErrno = errno;
1317 }
drh2ac3ee92004-06-07 16:27:46 +00001318 /* Drop the temporary PENDING lock */
1319 lock.l_start = PENDING_BYTE;
1320 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001321 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001322 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001323 if( s != -1 ){
1324 /* This could happen with a network mount */
1325 tErrno = errno;
1326 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1327 if( IS_LOCK_ERROR(rc) ){
1328 pFile->lastErrno = tErrno;
1329 }
1330 goto end_lock;
1331 }
drh2b4b5962005-06-15 17:47:55 +00001332 }
drhe2396a12007-03-29 20:19:58 +00001333 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001334 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1335 if( IS_LOCK_ERROR(rc) ){
1336 pFile->lastErrno = tErrno;
1337 }
drhbbd42a62004-05-22 17:41:58 +00001338 }else{
drh054889e2005-11-30 03:20:31 +00001339 pFile->locktype = SHARED_LOCK;
1340 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001341 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001342 }
drh3cde3bb2004-06-12 02:17:14 +00001343 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1344 /* We are trying for an exclusive lock but another thread in this
1345 ** same process is still holding a shared lock. */
1346 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001347 }else{
drh3cde3bb2004-06-12 02:17:14 +00001348 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001349 ** assumed that there is a SHARED or greater lock on the file
1350 ** already.
1351 */
drh054889e2005-11-30 03:20:31 +00001352 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001353 lock.l_type = F_WRLCK;
1354 switch( locktype ){
1355 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001356 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001357 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001358 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001359 lock.l_start = SHARED_FIRST;
1360 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001361 break;
1362 default:
1363 assert(0);
1364 }
drh054889e2005-11-30 03:20:31 +00001365 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001366 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001367 int tErrno = errno;
1368 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1369 if( IS_LOCK_ERROR(rc) ){
1370 pFile->lastErrno = tErrno;
1371 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001372 }
drhbbd42a62004-05-22 17:41:58 +00001373 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001374
drh8f941bc2009-01-14 23:03:40 +00001375
1376#ifndef NDEBUG
1377 /* Set up the transaction-counter change checking flags when
1378 ** transitioning from a SHARED to a RESERVED lock. The change
1379 ** from SHARED to RESERVED marks the beginning of a normal
1380 ** write operation (not a hot journal rollback).
1381 */
1382 if( rc==SQLITE_OK
1383 && pFile->locktype<=SHARED_LOCK
1384 && locktype==RESERVED_LOCK
1385 ){
1386 pFile->transCntrChng = 0;
1387 pFile->dbUpdate = 0;
1388 pFile->inNormalWrite = 1;
1389 }
1390#endif
1391
1392
danielk1977ecb2a962004-06-02 06:30:16 +00001393 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001394 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001395 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001396 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001397 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001398 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001399 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001400
1401end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001402 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001403 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001404 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001405 return rc;
1406}
1407
1408/*
drh054889e2005-11-30 03:20:31 +00001409** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001410** must be either NO_LOCK or SHARED_LOCK.
1411**
1412** If the locking level of the file descriptor is already at or below
1413** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001414*/
danielk197762079062007-08-15 17:08:46 +00001415static int unixUnlock(sqlite3_file *id, int locktype){
drh6c7d5c52008-11-21 20:32:33 +00001416 struct unixLockInfo *pLock;
drha6abd042004-06-09 17:37:22 +00001417 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001418 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001419 unixFile *pFile = (unixFile*)id;
drh1aa5af12008-03-07 19:51:14 +00001420 int h;
drha6abd042004-06-09 17:37:22 +00001421
drh054889e2005-11-30 03:20:31 +00001422 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001423 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001424 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001425
1426 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001427 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001428 return SQLITE_OK;
1429 }
drhf1a221e2006-01-15 17:27:17 +00001430 if( CHECK_THREADID(pFile) ){
1431 return SQLITE_MISUSE;
1432 }
drh6c7d5c52008-11-21 20:32:33 +00001433 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001434 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001435 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001436 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001437 if( pFile->locktype>SHARED_LOCK ){
1438 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001439 SimulateIOErrorBenign(1);
1440 SimulateIOError( h=(-1) )
1441 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001442
1443#ifndef NDEBUG
1444 /* When reducing a lock such that other processes can start
1445 ** reading the database file again, make sure that the
1446 ** transaction counter was updated if any part of the database
1447 ** file changed. If the transaction counter is not updated,
1448 ** other connections to the same file might not realize that
1449 ** the file has changed and hence might not know to flush their
1450 ** cache. The use of a stale cache can lead to database corruption.
1451 */
1452 assert( pFile->inNormalWrite==0
1453 || pFile->dbUpdate==0
1454 || pFile->transCntrChng==1 );
1455 pFile->inNormalWrite = 0;
1456#endif
1457
1458
drh9c105bb2004-10-02 20:38:28 +00001459 if( locktype==SHARED_LOCK ){
1460 lock.l_type = F_RDLCK;
1461 lock.l_whence = SEEK_SET;
1462 lock.l_start = SHARED_FIRST;
1463 lock.l_len = SHARED_SIZE;
drh1aa5af12008-03-07 19:51:14 +00001464 if( fcntl(h, F_SETLK, &lock)==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001465 int tErrno = errno;
1466 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1467 if( IS_LOCK_ERROR(rc) ){
1468 pFile->lastErrno = tErrno;
1469 }
danielk197709480a92009-02-09 05:32:32 +00001470 goto end_unlock;
drh9c105bb2004-10-02 20:38:28 +00001471 }
1472 }
drhbbd42a62004-05-22 17:41:58 +00001473 lock.l_type = F_UNLCK;
1474 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001475 lock.l_start = PENDING_BYTE;
1476 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001477 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001478 pLock->locktype = SHARED_LOCK;
1479 }else{
aswift5b1a2562008-08-22 00:22:35 +00001480 int tErrno = errno;
1481 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1482 if( IS_LOCK_ERROR(rc) ){
1483 pFile->lastErrno = tErrno;
1484 }
drhcd731cf2009-03-28 23:23:02 +00001485 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001486 }
drhbbd42a62004-05-22 17:41:58 +00001487 }
drha6abd042004-06-09 17:37:22 +00001488 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001489 struct unixOpenCnt *pOpen;
danielk197764a54c52009-03-30 07:39:35 +00001490 int rc2 = SQLITE_OK;
danielk1977ecb2a962004-06-02 06:30:16 +00001491
drha6abd042004-06-09 17:37:22 +00001492 /* Decrement the shared lock counter. Release the lock using an
1493 ** OS call only when all threads in this same process have released
1494 ** the lock.
1495 */
1496 pLock->cnt--;
1497 if( pLock->cnt==0 ){
1498 lock.l_type = F_UNLCK;
1499 lock.l_whence = SEEK_SET;
1500 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001501 SimulateIOErrorBenign(1);
1502 SimulateIOError( h=(-1) )
1503 SimulateIOErrorBenign(0);
1504 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001505 pLock->locktype = NO_LOCK;
1506 }else{
aswift5b1a2562008-08-22 00:22:35 +00001507 int tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001508 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001509 if( IS_LOCK_ERROR(rc) ){
1510 pFile->lastErrno = tErrno;
1511 }
drhf48f9ca2009-03-28 23:47:10 +00001512 pLock->locktype = NO_LOCK;
1513 pFile->locktype = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001514 }
drha6abd042004-06-09 17:37:22 +00001515 }
1516
drhbbd42a62004-05-22 17:41:58 +00001517 /* Decrement the count of locks against this same file. When the
1518 ** count reaches zero, close any other file descriptors whose close
1519 ** was deferred because of outstanding locks.
1520 */
danielk197764a54c52009-03-30 07:39:35 +00001521 pOpen = pFile->pOpen;
1522 pOpen->nLock--;
1523 assert( pOpen->nLock>=0 );
1524 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1525 int i;
1526 for(i=0; i<pOpen->nPending; i++){
1527 /* close pending fds, but if closing fails don't free the array
1528 ** assign -1 to the successfully closed descriptors and record the
1529 ** error. The next attempt to unlock will try again. */
1530 if( pOpen->aPending[i] < 0 ) continue;
1531 if( close(pOpen->aPending[i]) ){
1532 pFile->lastErrno = errno;
1533 rc2 = SQLITE_IOERR_CLOSE;
1534 }else{
1535 pOpen->aPending[i] = -1;
aswiftaebf4132008-11-21 00:10:35 +00001536 }
drhbbd42a62004-05-22 17:41:58 +00001537 }
danielk197764a54c52009-03-30 07:39:35 +00001538 if( rc2==SQLITE_OK ){
1539 sqlite3_free(pOpen->aPending);
1540 pOpen->nPending = 0;
1541 pOpen->aPending = 0;
1542 }
1543 }
1544 if( rc==SQLITE_OK ){
1545 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001546 }
1547 }
aswift5b1a2562008-08-22 00:22:35 +00001548
1549end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001550 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001551 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001552 return rc;
drhbbd42a62004-05-22 17:41:58 +00001553}
1554
1555/*
danielk1977e339d652008-06-28 11:23:00 +00001556** This function performs the parts of the "close file" operation
1557** common to all locking schemes. It closes the directory and file
1558** handles, if they are valid, and sets all fields of the unixFile
1559** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001560**
1561** It is *not* necessary to hold the mutex when this routine is called,
1562** even on VxWorks. A mutex will be acquired on VxWorks by the
1563** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001564*/
1565static int closeUnixFile(sqlite3_file *id){
1566 unixFile *pFile = (unixFile*)id;
1567 if( pFile ){
1568 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001569 int err = close(pFile->dirfd);
1570 if( err ){
1571 pFile->lastErrno = errno;
1572 return SQLITE_IOERR_DIR_CLOSE;
1573 }else{
1574 pFile->dirfd=-1;
1575 }
danielk1977e339d652008-06-28 11:23:00 +00001576 }
1577 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001578 int err = close(pFile->h);
1579 if( err ){
1580 pFile->lastErrno = errno;
1581 return SQLITE_IOERR_CLOSE;
1582 }
danielk1977e339d652008-06-28 11:23:00 +00001583 }
drh6c7d5c52008-11-21 20:32:33 +00001584#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001585 if( pFile->pId ){
1586 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001587 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001588 }
drh107886a2008-11-21 22:21:50 +00001589 vxworksReleaseFileId(pFile->pId);
1590 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001591 }
1592#endif
danielk1977e339d652008-06-28 11:23:00 +00001593 OSTRACE2("CLOSE %-3d\n", pFile->h);
1594 OpenCounter(-1);
1595 memset(pFile, 0, sizeof(unixFile));
1596 }
1597 return SQLITE_OK;
1598}
1599
1600/*
danielk1977e3026632004-06-22 11:29:02 +00001601** Close a file.
1602*/
danielk197762079062007-08-15 17:08:46 +00001603static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001604 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001605 if( id ){
1606 unixFile *pFile = (unixFile *)id;
1607 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001608 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001609 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001610 /* If there are outstanding locks, do not actually close the file just
1611 ** yet because that would clear those locks. Instead, add the file
1612 ** descriptor to pOpen->aPending. It will be automatically closed when
1613 ** the last lock is cleared.
1614 */
1615 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00001616 struct unixOpenCnt *pOpen = pFile->pOpen;
drhda0e7682008-07-30 15:27:54 +00001617 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e339d652008-06-28 11:23:00 +00001618 if( aNew==0 ){
1619 /* If a malloc fails, just leak the file descriptor */
1620 }else{
1621 pOpen->aPending = aNew;
1622 pOpen->aPending[pOpen->nPending] = pFile->h;
1623 pOpen->nPending++;
1624 pFile->h = -1;
1625 }
danielk1977e3026632004-06-22 11:29:02 +00001626 }
danielk1977e339d652008-06-28 11:23:00 +00001627 releaseLockInfo(pFile->pLock);
1628 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001629 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001630 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001631 }
aswiftaebf4132008-11-21 00:10:35 +00001632 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001633}
1634
drh734c9862008-11-28 15:37:20 +00001635/************** End of the posix advisory lock implementation *****************
1636******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001637
drh734c9862008-11-28 15:37:20 +00001638/******************************************************************************
1639****************************** No-op Locking **********************************
1640**
1641** Of the various locking implementations available, this is by far the
1642** simplest: locking is ignored. No attempt is made to lock the database
1643** file for reading or writing.
1644**
1645** This locking mode is appropriate for use on read-only databases
1646** (ex: databases that are burned into CD-ROM, for example.) It can
1647** also be used if the application employs some external mechanism to
1648** prevent simultaneous access of the same database by two or more
1649** database connections. But there is a serious risk of database
1650** corruption if this locking mode is used in situations where multiple
1651** database connections are accessing the same database file at the same
1652** time and one or more of those connections are writing.
1653*/
drhbfe66312006-10-03 17:40:40 +00001654
drh734c9862008-11-28 15:37:20 +00001655static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1656 UNUSED_PARAMETER(NotUsed);
1657 *pResOut = 0;
1658 return SQLITE_OK;
1659}
drh734c9862008-11-28 15:37:20 +00001660static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1661 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1662 return SQLITE_OK;
1663}
drh734c9862008-11-28 15:37:20 +00001664static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1665 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1666 return SQLITE_OK;
1667}
1668
1669/*
drh9b35ea62008-11-29 02:20:26 +00001670** Close the file.
drh734c9862008-11-28 15:37:20 +00001671*/
1672static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001673 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001674}
1675
1676/******************* End of the no-op lock implementation *********************
1677******************************************************************************/
1678
1679/******************************************************************************
1680************************* Begin dot-file Locking ******************************
1681**
1682** The dotfile locking implementation uses the existing of separate lock
1683** files in order to control access to the database. This works on just
1684** about every filesystem imaginable. But there are serious downsides:
1685**
1686** (1) There is zero concurrency. A single reader blocks all other
1687** connections from reading or writing the database.
1688**
1689** (2) An application crash or power loss can leave stale lock files
1690** sitting around that need to be cleared manually.
1691**
1692** Nevertheless, a dotlock is an appropriate locking mode for use if no
1693** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001694**
1695** Dotfile locking works by creating a file in the same directory as the
1696** database and with the same name but with a ".lock" extension added.
1697** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1698** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001699*/
1700
1701/*
1702** The file suffix added to the data base filename in order to create the
1703** lock file.
1704*/
1705#define DOTLOCK_SUFFIX ".lock"
1706
drh7708e972008-11-29 00:56:52 +00001707/*
1708** This routine checks if there is a RESERVED lock held on the specified
1709** file by this or any other process. If such a lock is held, set *pResOut
1710** to a non-zero value otherwise *pResOut is set to zero. The return value
1711** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1712**
1713** In dotfile locking, either a lock exists or it does not. So in this
1714** variation of CheckReservedLock(), *pResOut is set to true if any lock
1715** is held on the file and false if the file is unlocked.
1716*/
drh734c9862008-11-28 15:37:20 +00001717static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1718 int rc = SQLITE_OK;
1719 int reserved = 0;
1720 unixFile *pFile = (unixFile*)id;
1721
1722 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1723
1724 assert( pFile );
1725
1726 /* Check if a thread in this process holds such a lock */
1727 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001728 /* Either this connection or some other connection in the same process
1729 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001730 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001731 }else{
1732 /* The lock is held if and only if the lockfile exists */
1733 const char *zLockFile = (const char*)pFile->lockingContext;
1734 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001735 }
1736 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001737 *pResOut = reserved;
1738 return rc;
1739}
1740
drh7708e972008-11-29 00:56:52 +00001741/*
1742** Lock the file with the lock specified by parameter locktype - one
1743** of the following:
1744**
1745** (1) SHARED_LOCK
1746** (2) RESERVED_LOCK
1747** (3) PENDING_LOCK
1748** (4) EXCLUSIVE_LOCK
1749**
1750** Sometimes when requesting one lock state, additional lock states
1751** are inserted in between. The locking might fail on one of the later
1752** transitions leaving the lock state different from what it started but
1753** still short of its goal. The following chart shows the allowed
1754** transitions and the inserted intermediate states:
1755**
1756** UNLOCKED -> SHARED
1757** SHARED -> RESERVED
1758** SHARED -> (PENDING) -> EXCLUSIVE
1759** RESERVED -> (PENDING) -> EXCLUSIVE
1760** PENDING -> EXCLUSIVE
1761**
1762** This routine will only increase a lock. Use the sqlite3OsUnlock()
1763** routine to lower a locking level.
1764**
1765** With dotfile locking, we really only support state (4): EXCLUSIVE.
1766** But we track the other locking levels internally.
1767*/
drh734c9862008-11-28 15:37:20 +00001768static int dotlockLock(sqlite3_file *id, int locktype) {
1769 unixFile *pFile = (unixFile*)id;
1770 int fd;
1771 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001772 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001773
drh7708e972008-11-29 00:56:52 +00001774
1775 /* If we have any lock, then the lock file already exists. All we have
1776 ** to do is adjust our internal record of the lock level.
1777 */
1778 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001779 pFile->locktype = locktype;
1780#if !OS_VXWORKS
1781 /* Always update the timestamp on the old file */
1782 utimes(zLockFile, NULL);
1783#endif
drh7708e972008-11-29 00:56:52 +00001784 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001785 }
1786
1787 /* grab an exclusive lock */
1788 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1789 if( fd<0 ){
1790 /* failed to open/create the file, someone else may have stolen the lock */
1791 int tErrno = errno;
1792 if( EEXIST == tErrno ){
1793 rc = SQLITE_BUSY;
1794 } else {
1795 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1796 if( IS_LOCK_ERROR(rc) ){
1797 pFile->lastErrno = tErrno;
1798 }
1799 }
drh7708e972008-11-29 00:56:52 +00001800 return rc;
drh734c9862008-11-28 15:37:20 +00001801 }
1802 if( close(fd) ){
1803 pFile->lastErrno = errno;
1804 rc = SQLITE_IOERR_CLOSE;
1805 }
1806
1807 /* got it, set the type and return ok */
1808 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001809 return rc;
1810}
1811
drh7708e972008-11-29 00:56:52 +00001812/*
1813** Lower the locking level on file descriptor pFile to locktype. locktype
1814** must be either NO_LOCK or SHARED_LOCK.
1815**
1816** If the locking level of the file descriptor is already at or below
1817** the requested locking level, this routine is a no-op.
1818**
1819** When the locking level reaches NO_LOCK, delete the lock file.
1820*/
drh734c9862008-11-28 15:37:20 +00001821static int dotlockUnlock(sqlite3_file *id, int locktype) {
1822 unixFile *pFile = (unixFile*)id;
1823 char *zLockFile = (char *)pFile->lockingContext;
1824
1825 assert( pFile );
1826 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1827 pFile->locktype, getpid());
1828 assert( locktype<=SHARED_LOCK );
1829
1830 /* no-op if possible */
1831 if( pFile->locktype==locktype ){
1832 return SQLITE_OK;
1833 }
drh7708e972008-11-29 00:56:52 +00001834
1835 /* To downgrade to shared, simply update our internal notion of the
1836 ** lock state. No need to mess with the file on disk.
1837 */
1838 if( locktype==SHARED_LOCK ){
1839 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001840 return SQLITE_OK;
1841 }
1842
drh7708e972008-11-29 00:56:52 +00001843 /* To fully unlock the database, delete the lock file */
1844 assert( locktype==NO_LOCK );
1845 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001846 int rc = 0;
1847 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001848 if( ENOENT != tErrno ){
1849 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1850 }
1851 if( IS_LOCK_ERROR(rc) ){
1852 pFile->lastErrno = tErrno;
1853 }
1854 return rc;
1855 }
1856 pFile->locktype = NO_LOCK;
1857 return SQLITE_OK;
1858}
1859
1860/*
drh9b35ea62008-11-29 02:20:26 +00001861** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001862*/
1863static int dotlockClose(sqlite3_file *id) {
1864 int rc;
1865 if( id ){
1866 unixFile *pFile = (unixFile*)id;
1867 dotlockUnlock(id, NO_LOCK);
1868 sqlite3_free(pFile->lockingContext);
1869 }
drh734c9862008-11-28 15:37:20 +00001870 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001871 return rc;
1872}
1873/****************** End of the dot-file lock implementation *******************
1874******************************************************************************/
1875
1876/******************************************************************************
1877************************** Begin flock Locking ********************************
1878**
1879** Use the flock() system call to do file locking.
1880**
drh6b9d6dd2008-12-03 19:34:47 +00001881** flock() locking is like dot-file locking in that the various
1882** fine-grain locking levels supported by SQLite are collapsed into
1883** a single exclusive lock. In other words, SHARED, RESERVED, and
1884** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1885** still works when you do this, but concurrency is reduced since
1886** only a single process can be reading the database at a time.
1887**
drh734c9862008-11-28 15:37:20 +00001888** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1889** compiling for VXWORKS.
1890*/
1891#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001892
drh6b9d6dd2008-12-03 19:34:47 +00001893/*
1894** This routine checks if there is a RESERVED lock held on the specified
1895** file by this or any other process. If such a lock is held, set *pResOut
1896** to a non-zero value otherwise *pResOut is set to zero. The return value
1897** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1898*/
drh734c9862008-11-28 15:37:20 +00001899static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1900 int rc = SQLITE_OK;
1901 int reserved = 0;
1902 unixFile *pFile = (unixFile*)id;
1903
1904 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1905
1906 assert( pFile );
1907
1908 /* Check if a thread in this process holds such a lock */
1909 if( pFile->locktype>SHARED_LOCK ){
1910 reserved = 1;
1911 }
1912
1913 /* Otherwise see if some other process holds it. */
1914 if( !reserved ){
1915 /* attempt to get the lock */
1916 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1917 if( !lrc ){
1918 /* got the lock, unlock it */
1919 lrc = flock(pFile->h, LOCK_UN);
1920 if ( lrc ) {
1921 int tErrno = errno;
1922 /* unlock failed with an error */
1923 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1924 if( IS_LOCK_ERROR(lrc) ){
1925 pFile->lastErrno = tErrno;
1926 rc = lrc;
1927 }
1928 }
1929 } else {
1930 int tErrno = errno;
1931 reserved = 1;
1932 /* someone else might have it reserved */
1933 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1934 if( IS_LOCK_ERROR(lrc) ){
1935 pFile->lastErrno = tErrno;
1936 rc = lrc;
1937 }
1938 }
1939 }
1940 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
1941
1942#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1943 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1944 rc = SQLITE_OK;
1945 reserved=1;
1946 }
1947#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1948 *pResOut = reserved;
1949 return rc;
1950}
1951
drh6b9d6dd2008-12-03 19:34:47 +00001952/*
1953** Lock the file with the lock specified by parameter locktype - one
1954** of the following:
1955**
1956** (1) SHARED_LOCK
1957** (2) RESERVED_LOCK
1958** (3) PENDING_LOCK
1959** (4) EXCLUSIVE_LOCK
1960**
1961** Sometimes when requesting one lock state, additional lock states
1962** are inserted in between. The locking might fail on one of the later
1963** transitions leaving the lock state different from what it started but
1964** still short of its goal. The following chart shows the allowed
1965** transitions and the inserted intermediate states:
1966**
1967** UNLOCKED -> SHARED
1968** SHARED -> RESERVED
1969** SHARED -> (PENDING) -> EXCLUSIVE
1970** RESERVED -> (PENDING) -> EXCLUSIVE
1971** PENDING -> EXCLUSIVE
1972**
1973** flock() only really support EXCLUSIVE locks. We track intermediate
1974** lock states in the sqlite3_file structure, but all locks SHARED or
1975** above are really EXCLUSIVE locks and exclude all other processes from
1976** access the file.
1977**
1978** This routine will only increase a lock. Use the sqlite3OsUnlock()
1979** routine to lower a locking level.
1980*/
drh734c9862008-11-28 15:37:20 +00001981static int flockLock(sqlite3_file *id, int locktype) {
1982 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001983 unixFile *pFile = (unixFile*)id;
1984
1985 assert( pFile );
1986
1987 /* if we already have a lock, it is exclusive.
1988 ** Just adjust level and punt on outta here. */
1989 if (pFile->locktype > NO_LOCK) {
1990 pFile->locktype = locktype;
1991 return SQLITE_OK;
1992 }
1993
1994 /* grab an exclusive lock */
1995
1996 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1997 int tErrno = errno;
1998 /* didn't get, must be busy */
1999 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2000 if( IS_LOCK_ERROR(rc) ){
2001 pFile->lastErrno = tErrno;
2002 }
2003 } else {
2004 /* got it, set the type and return ok */
2005 pFile->locktype = locktype;
2006 }
2007 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
2008 rc==SQLITE_OK ? "ok" : "failed");
2009#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2010 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2011 rc = SQLITE_BUSY;
2012 }
2013#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2014 return rc;
2015}
2016
drh6b9d6dd2008-12-03 19:34:47 +00002017
2018/*
2019** Lower the locking level on file descriptor pFile to locktype. locktype
2020** must be either NO_LOCK or SHARED_LOCK.
2021**
2022** If the locking level of the file descriptor is already at or below
2023** the requested locking level, this routine is a no-op.
2024*/
drh734c9862008-11-28 15:37:20 +00002025static int flockUnlock(sqlite3_file *id, int locktype) {
2026 unixFile *pFile = (unixFile*)id;
2027
2028 assert( pFile );
2029 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2030 pFile->locktype, getpid());
2031 assert( locktype<=SHARED_LOCK );
2032
2033 /* no-op if possible */
2034 if( pFile->locktype==locktype ){
2035 return SQLITE_OK;
2036 }
2037
2038 /* shared can just be set because we always have an exclusive */
2039 if (locktype==SHARED_LOCK) {
2040 pFile->locktype = locktype;
2041 return SQLITE_OK;
2042 }
2043
2044 /* no, really, unlock. */
2045 int rc = flock(pFile->h, LOCK_UN);
2046 if (rc) {
2047 int r, tErrno = errno;
2048 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2049 if( IS_LOCK_ERROR(r) ){
2050 pFile->lastErrno = tErrno;
2051 }
2052#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2053 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2054 r = SQLITE_BUSY;
2055 }
2056#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2057
2058 return r;
2059 } else {
2060 pFile->locktype = NO_LOCK;
2061 return SQLITE_OK;
2062 }
2063}
2064
2065/*
2066** Close a file.
2067*/
2068static int flockClose(sqlite3_file *id) {
2069 if( id ){
2070 flockUnlock(id, NO_LOCK);
2071 }
2072 return closeUnixFile(id);
2073}
2074
2075#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2076
2077/******************* End of the flock lock implementation *********************
2078******************************************************************************/
2079
2080/******************************************************************************
2081************************ Begin Named Semaphore Locking ************************
2082**
2083** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002084**
2085** Semaphore locking is like dot-lock and flock in that it really only
2086** supports EXCLUSIVE locking. Only a single process can read or write
2087** the database file at a time. This reduces potential concurrency, but
2088** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002089*/
2090#if OS_VXWORKS
2091
drh6b9d6dd2008-12-03 19:34:47 +00002092/*
2093** This routine checks if there is a RESERVED lock held on the specified
2094** file by this or any other process. If such a lock is held, set *pResOut
2095** to a non-zero value otherwise *pResOut is set to zero. The return value
2096** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2097*/
drh734c9862008-11-28 15:37:20 +00002098static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2099 int rc = SQLITE_OK;
2100 int reserved = 0;
2101 unixFile *pFile = (unixFile*)id;
2102
2103 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2104
2105 assert( pFile );
2106
2107 /* Check if a thread in this process holds such a lock */
2108 if( pFile->locktype>SHARED_LOCK ){
2109 reserved = 1;
2110 }
2111
2112 /* Otherwise see if some other process holds it. */
2113 if( !reserved ){
2114 sem_t *pSem = pFile->pOpen->pSem;
2115 struct stat statBuf;
2116
2117 if( sem_trywait(pSem)==-1 ){
2118 int tErrno = errno;
2119 if( EAGAIN != tErrno ){
2120 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2121 pFile->lastErrno = tErrno;
2122 } else {
2123 /* someone else has the lock when we are in NO_LOCK */
2124 reserved = (pFile->locktype < SHARED_LOCK);
2125 }
2126 }else{
2127 /* we could have it if we want it */
2128 sem_post(pSem);
2129 }
2130 }
2131 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2132
2133 *pResOut = reserved;
2134 return rc;
2135}
2136
drh6b9d6dd2008-12-03 19:34:47 +00002137/*
2138** Lock the file with the lock specified by parameter locktype - one
2139** of the following:
2140**
2141** (1) SHARED_LOCK
2142** (2) RESERVED_LOCK
2143** (3) PENDING_LOCK
2144** (4) EXCLUSIVE_LOCK
2145**
2146** Sometimes when requesting one lock state, additional lock states
2147** are inserted in between. The locking might fail on one of the later
2148** transitions leaving the lock state different from what it started but
2149** still short of its goal. The following chart shows the allowed
2150** transitions and the inserted intermediate states:
2151**
2152** UNLOCKED -> SHARED
2153** SHARED -> RESERVED
2154** SHARED -> (PENDING) -> EXCLUSIVE
2155** RESERVED -> (PENDING) -> EXCLUSIVE
2156** PENDING -> EXCLUSIVE
2157**
2158** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2159** lock states in the sqlite3_file structure, but all locks SHARED or
2160** above are really EXCLUSIVE locks and exclude all other processes from
2161** access the file.
2162**
2163** This routine will only increase a lock. Use the sqlite3OsUnlock()
2164** routine to lower a locking level.
2165*/
drh734c9862008-11-28 15:37:20 +00002166static int semLock(sqlite3_file *id, int locktype) {
2167 unixFile *pFile = (unixFile*)id;
2168 int fd;
2169 sem_t *pSem = pFile->pOpen->pSem;
2170 int rc = SQLITE_OK;
2171
2172 /* if we already have a lock, it is exclusive.
2173 ** Just adjust level and punt on outta here. */
2174 if (pFile->locktype > NO_LOCK) {
2175 pFile->locktype = locktype;
2176 rc = SQLITE_OK;
2177 goto sem_end_lock;
2178 }
2179
2180 /* lock semaphore now but bail out when already locked. */
2181 if( sem_trywait(pSem)==-1 ){
2182 rc = SQLITE_BUSY;
2183 goto sem_end_lock;
2184 }
2185
2186 /* got it, set the type and return ok */
2187 pFile->locktype = locktype;
2188
2189 sem_end_lock:
2190 return rc;
2191}
2192
drh6b9d6dd2008-12-03 19:34:47 +00002193/*
2194** Lower the locking level on file descriptor pFile to locktype. locktype
2195** must be either NO_LOCK or SHARED_LOCK.
2196**
2197** If the locking level of the file descriptor is already at or below
2198** the requested locking level, this routine is a no-op.
2199*/
drh734c9862008-11-28 15:37:20 +00002200static int semUnlock(sqlite3_file *id, int locktype) {
2201 unixFile *pFile = (unixFile*)id;
2202 sem_t *pSem = pFile->pOpen->pSem;
2203
2204 assert( pFile );
2205 assert( pSem );
2206 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2207 pFile->locktype, getpid());
2208 assert( locktype<=SHARED_LOCK );
2209
2210 /* no-op if possible */
2211 if( pFile->locktype==locktype ){
2212 return SQLITE_OK;
2213 }
2214
2215 /* shared can just be set because we always have an exclusive */
2216 if (locktype==SHARED_LOCK) {
2217 pFile->locktype = locktype;
2218 return SQLITE_OK;
2219 }
2220
2221 /* no, really unlock. */
2222 if ( sem_post(pSem)==-1 ) {
2223 int rc, tErrno = errno;
2224 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2225 if( IS_LOCK_ERROR(rc) ){
2226 pFile->lastErrno = tErrno;
2227 }
2228 return rc;
2229 }
2230 pFile->locktype = NO_LOCK;
2231 return SQLITE_OK;
2232}
2233
2234/*
2235 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002236 */
drh734c9862008-11-28 15:37:20 +00002237static int semClose(sqlite3_file *id) {
2238 if( id ){
2239 unixFile *pFile = (unixFile*)id;
2240 semUnlock(id, NO_LOCK);
2241 assert( pFile );
2242 unixEnterMutex();
2243 releaseLockInfo(pFile->pLock);
2244 releaseOpenCnt(pFile->pOpen);
drh734c9862008-11-28 15:37:20 +00002245 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002246 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002247 }
2248 return SQLITE_OK;
2249}
2250
2251#endif /* OS_VXWORKS */
2252/*
2253** Named semaphore locking is only available on VxWorks.
2254**
2255*************** End of the named semaphore lock implementation ****************
2256******************************************************************************/
2257
2258
2259/******************************************************************************
2260*************************** Begin AFP Locking *********************************
2261**
2262** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2263** on Apple Macintosh computers - both OS9 and OSX.
2264**
2265** Third-party implementations of AFP are available. But this code here
2266** only works on OSX.
2267*/
2268
drhd2cb50b2009-01-09 21:41:17 +00002269#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002270/*
2271** The afpLockingContext structure contains all afp lock specific state
2272*/
drhbfe66312006-10-03 17:40:40 +00002273typedef struct afpLockingContext afpLockingContext;
2274struct afpLockingContext {
aswiftaebf4132008-11-21 00:10:35 +00002275 unsigned long long sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002276 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002277};
2278
2279struct ByteRangeLockPB2
2280{
2281 unsigned long long offset; /* offset to first byte to lock */
2282 unsigned long long length; /* nbr of bytes to lock */
2283 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2284 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2285 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2286 int fd; /* file desc to assoc this lock with */
2287};
2288
drhfd131da2007-08-07 17:13:03 +00002289#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002290
drh6b9d6dd2008-12-03 19:34:47 +00002291/*
2292** This is a utility for setting or clearing a bit-range lock on an
2293** AFP filesystem.
2294**
2295** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2296*/
2297static int afpSetLock(
2298 const char *path, /* Name of the file to be locked or unlocked */
2299 unixFile *pFile, /* Open file descriptor on path */
2300 unsigned long long offset, /* First byte to be locked */
2301 unsigned long long length, /* Number of bytes to lock */
2302 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002303){
drh6b9d6dd2008-12-03 19:34:47 +00002304 struct ByteRangeLockPB2 pb;
2305 int err;
drhbfe66312006-10-03 17:40:40 +00002306
2307 pb.unLockFlag = setLockFlag ? 0 : 1;
2308 pb.startEndFlag = 0;
2309 pb.offset = offset;
2310 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002311 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002312
2313 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002314 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2315 offset, length);
drhbfe66312006-10-03 17:40:40 +00002316 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2317 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002318 int rc;
2319 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002320 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2321 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002322#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2323 rc = SQLITE_BUSY;
2324#else
drh734c9862008-11-28 15:37:20 +00002325 rc = sqliteErrorFromPosixError(tErrno,
2326 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002327#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002328 if( IS_LOCK_ERROR(rc) ){
2329 pFile->lastErrno = tErrno;
2330 }
2331 return rc;
drhbfe66312006-10-03 17:40:40 +00002332 } else {
aswift5b1a2562008-08-22 00:22:35 +00002333 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002334 }
2335}
2336
drh6b9d6dd2008-12-03 19:34:47 +00002337/*
2338** This routine checks if there is a RESERVED lock held on the specified
2339** file by this or any other process. If such a lock is held, set *pResOut
2340** to a non-zero value otherwise *pResOut is set to zero. The return value
2341** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2342*/
danielk1977e339d652008-06-28 11:23:00 +00002343static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002344 int rc = SQLITE_OK;
2345 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002346 unixFile *pFile = (unixFile*)id;
2347
aswift5b1a2562008-08-22 00:22:35 +00002348 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2349
2350 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002351 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2352
2353 /* Check if a thread in this process holds such a lock */
2354 if( pFile->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002355 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002356 }
2357
2358 /* Otherwise see if some other process holds it.
2359 */
aswift5b1a2562008-08-22 00:22:35 +00002360 if( !reserved ){
2361 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002362 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002363 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002364 /* if we succeeded in taking the reserved lock, unlock it to restore
2365 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002366 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002367 } else {
2368 /* if we failed to get the lock then someone else must have it */
2369 reserved = 1;
2370 }
2371 if( IS_LOCK_ERROR(lrc) ){
2372 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002373 }
2374 }
drhbfe66312006-10-03 17:40:40 +00002375
aswift5b1a2562008-08-22 00:22:35 +00002376 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2377
2378 *pResOut = reserved;
2379 return rc;
drhbfe66312006-10-03 17:40:40 +00002380}
2381
drh6b9d6dd2008-12-03 19:34:47 +00002382/*
2383** Lock the file with the lock specified by parameter locktype - one
2384** of the following:
2385**
2386** (1) SHARED_LOCK
2387** (2) RESERVED_LOCK
2388** (3) PENDING_LOCK
2389** (4) EXCLUSIVE_LOCK
2390**
2391** Sometimes when requesting one lock state, additional lock states
2392** are inserted in between. The locking might fail on one of the later
2393** transitions leaving the lock state different from what it started but
2394** still short of its goal. The following chart shows the allowed
2395** transitions and the inserted intermediate states:
2396**
2397** UNLOCKED -> SHARED
2398** SHARED -> RESERVED
2399** SHARED -> (PENDING) -> EXCLUSIVE
2400** RESERVED -> (PENDING) -> EXCLUSIVE
2401** PENDING -> EXCLUSIVE
2402**
2403** This routine will only increase a lock. Use the sqlite3OsUnlock()
2404** routine to lower a locking level.
2405*/
danielk1977e339d652008-06-28 11:23:00 +00002406static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002407 int rc = SQLITE_OK;
2408 unixFile *pFile = (unixFile*)id;
2409 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002410
2411 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002412 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00002413 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
2414
drhbfe66312006-10-03 17:40:40 +00002415 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002416 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002417 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002418 */
drhbfe66312006-10-03 17:40:40 +00002419 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00002420 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002421 locktypeName(locktype));
2422 return SQLITE_OK;
2423 }
2424
2425 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00002426 */
drhbfe66312006-10-03 17:40:40 +00002427 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2428 assert( locktype!=PENDING_LOCK );
2429 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2430
2431 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002432 */
drh6c7d5c52008-11-21 20:32:33 +00002433 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002434
2435 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002436 */
drhbfe66312006-10-03 17:40:40 +00002437 rc = transferOwnership(pFile);
2438 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002439 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002440 return rc;
2441 }
2442
2443 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002444 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2445 ** be released.
2446 */
drhbfe66312006-10-03 17:40:40 +00002447 if( locktype==SHARED_LOCK
2448 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002449 ){
2450 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002451 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002452 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002453 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002454 goto afp_end_lock;
2455 }
2456 }
2457
2458 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002459 ** operating system calls for the specified lock.
2460 */
drhbfe66312006-10-03 17:40:40 +00002461 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002462 int lk, lrc1, lrc2, lrc1Errno;
drhbfe66312006-10-03 17:40:40 +00002463
aswift5b1a2562008-08-22 00:22:35 +00002464 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002465 /* note that the quality of the randomness doesn't matter that much */
2466 lk = random();
aswiftaebf4132008-11-21 00:10:35 +00002467 context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002468 lrc1 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002469 SHARED_FIRST+context->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002470 if( IS_LOCK_ERROR(lrc1) ){
2471 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002472 }
aswift5b1a2562008-08-22 00:22:35 +00002473 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002474 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002475
aswift5b1a2562008-08-22 00:22:35 +00002476 if( IS_LOCK_ERROR(lrc1) ) {
2477 pFile->lastErrno = lrc1Errno;
2478 rc = lrc1;
2479 goto afp_end_lock;
2480 } else if( IS_LOCK_ERROR(lrc2) ){
2481 rc = lrc2;
2482 goto afp_end_lock;
2483 } else if( lrc1 != SQLITE_OK ) {
2484 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002485 } else {
2486 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002487 pFile->pOpen->nLock++;
drhbfe66312006-10-03 17:40:40 +00002488 }
2489 }else{
2490 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2491 ** assumed that there is a SHARED or greater lock on the file
2492 ** already.
2493 */
2494 int failed = 0;
2495 assert( 0!=pFile->locktype );
2496 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2497 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002498 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drhbfe66312006-10-03 17:40:40 +00002499 }
2500 if (!failed && locktype == EXCLUSIVE_LOCK) {
2501 /* Acquire an EXCLUSIVE lock */
2502
2503 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002504 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002505 */
drh6b9d6dd2008-12-03 19:34:47 +00002506 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
aswiftaebf4132008-11-21 00:10:35 +00002507 context->sharedByte, 1, 0)) ){
2508 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002509 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002510 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002511 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002512 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002513 SHARED_FIRST + context->sharedByte, 1, 1)) ){
2514 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2515 ** a critical I/O error
2516 */
2517 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2518 SQLITE_IOERR_LOCK;
2519 goto afp_end_lock;
2520 }
2521 }else{
aswift5b1a2562008-08-22 00:22:35 +00002522 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002523 }
2524 }
aswift5b1a2562008-08-22 00:22:35 +00002525 if( failed ){
2526 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002527 }
2528 }
2529
2530 if( rc==SQLITE_OK ){
2531 pFile->locktype = locktype;
2532 }else if( locktype==EXCLUSIVE_LOCK ){
2533 pFile->locktype = PENDING_LOCK;
2534 }
2535
2536afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002537 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00002538 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002539 rc==SQLITE_OK ? "ok" : "failed");
2540 return rc;
2541}
2542
2543/*
drh339eb0b2008-03-07 15:34:11 +00002544** Lower the locking level on file descriptor pFile to locktype. locktype
2545** must be either NO_LOCK or SHARED_LOCK.
2546**
2547** If the locking level of the file descriptor is already at or below
2548** the requested locking level, this routine is a no-op.
2549*/
danielk1977e339d652008-06-28 11:23:00 +00002550static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002551 int rc = SQLITE_OK;
2552 unixFile *pFile = (unixFile*)id;
aswiftaebf4132008-11-21 00:10:35 +00002553 afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002554
2555 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002556 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00002557 pFile->locktype, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002558
drhbfe66312006-10-03 17:40:40 +00002559 assert( locktype<=SHARED_LOCK );
2560 if( pFile->locktype<=locktype ){
2561 return SQLITE_OK;
2562 }
2563 if( CHECK_THREADID(pFile) ){
2564 return SQLITE_MISUSE;
2565 }
drh6c7d5c52008-11-21 20:32:33 +00002566 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002567 if( pFile->locktype>SHARED_LOCK ){
aswiftaebf4132008-11-21 00:10:35 +00002568
2569 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002570 rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
aswiftaebf4132008-11-21 00:10:35 +00002571 if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
2572 /* only re-establish the shared lock if necessary */
2573 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002574 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
aswiftaebf4132008-11-21 00:10:35 +00002575 }
2576 }
2577 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002578 rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002579 }
2580 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002581 rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002582 }
2583 }else if( locktype==NO_LOCK ){
2584 /* clear the shared lock */
2585 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002586 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002587 }
drhbfe66312006-10-03 17:40:40 +00002588
aswiftaebf4132008-11-21 00:10:35 +00002589 if( rc==SQLITE_OK ){
2590 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00002591 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002592 pOpen->nLock--;
2593 assert( pOpen->nLock>=0 );
2594 if( pOpen->nLock==0 && pOpen->nPending>0 ){
2595 int i;
2596 for(i=0; i<pOpen->nPending; i++){
2597 if( pOpen->aPending[i] < 0 ) continue;
2598 if( close(pOpen->aPending[i]) ){
2599 pFile->lastErrno = errno;
2600 rc = SQLITE_IOERR_CLOSE;
2601 }else{
2602 pOpen->aPending[i] = -1;
drhbfe66312006-10-03 17:40:40 +00002603 }
aswiftaebf4132008-11-21 00:10:35 +00002604 }
2605 if( rc==SQLITE_OK ){
2606 sqlite3_free(pOpen->aPending);
2607 pOpen->nPending = 0;
2608 pOpen->aPending = 0;
2609 }
drhbfe66312006-10-03 17:40:40 +00002610 }
2611 }
drhbfe66312006-10-03 17:40:40 +00002612 }
drh6c7d5c52008-11-21 20:32:33 +00002613 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002614 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002615 return rc;
2616}
2617
2618/*
drh339eb0b2008-03-07 15:34:11 +00002619** Close a file & cleanup AFP specific locking context
2620*/
danielk1977e339d652008-06-28 11:23:00 +00002621static int afpClose(sqlite3_file *id) {
2622 if( id ){
2623 unixFile *pFile = (unixFile*)id;
2624 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002625 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002626 if( pFile->pOpen && pFile->pOpen->nLock ){
2627 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002628 ** yet because that would clear those locks. Instead, add the file
2629 ** descriptor to pOpen->aPending. It will be automatically closed when
2630 ** the last lock is cleared.
2631 */
aswiftaebf4132008-11-21 00:10:35 +00002632 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00002633 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002634 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
2635 if( aNew==0 ){
2636 /* If a malloc fails, just leak the file descriptor */
2637 }else{
2638 pOpen->aPending = aNew;
2639 pOpen->aPending[pOpen->nPending] = pFile->h;
2640 pOpen->nPending++;
2641 pFile->h = -1;
2642 }
2643 }
2644 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002645 sqlite3_free(pFile->lockingContext);
aswiftaebf4132008-11-21 00:10:35 +00002646 closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002647 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002648 }
aswiftaebf4132008-11-21 00:10:35 +00002649 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002650}
2651
drhd2cb50b2009-01-09 21:41:17 +00002652#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002653/*
2654** The code above is the AFP lock implementation. The code is specific
2655** to MacOSX and does not work on other unix platforms. No alternative
2656** is available. If you don't compile for a mac, then the "unix-afp"
2657** VFS is not available.
2658**
2659********************* End of the AFP lock implementation **********************
2660******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002661
drh734c9862008-11-28 15:37:20 +00002662
2663/******************************************************************************
2664**************** Non-locking sqlite3_file methods *****************************
2665**
2666** The next division contains implementations for all methods of the
2667** sqlite3_file object other than the locking methods. The locking
2668** methods were defined in divisions above (one locking method per
2669** division). Those methods that are common to all locking modes
2670** are gather together into this division.
2671*/
drhbfe66312006-10-03 17:40:40 +00002672
2673/*
drh734c9862008-11-28 15:37:20 +00002674** Seek to the offset passed as the second argument, then read cnt
2675** bytes into pBuf. Return the number of bytes actually read.
2676**
2677** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2678** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2679** one system to another. Since SQLite does not define USE_PREAD
2680** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2681** See tickets #2741 and #2681.
2682**
2683** To avoid stomping the errno value on a failed read the lastErrno value
2684** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002685*/
drh734c9862008-11-28 15:37:20 +00002686static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2687 int got;
2688 i64 newOffset;
2689 TIMER_START;
2690#if defined(USE_PREAD)
2691 got = pread(id->h, pBuf, cnt, offset);
2692 SimulateIOError( got = -1 );
2693#elif defined(USE_PREAD64)
2694 got = pread64(id->h, pBuf, cnt, offset);
2695 SimulateIOError( got = -1 );
2696#else
2697 newOffset = lseek(id->h, offset, SEEK_SET);
2698 SimulateIOError( newOffset-- );
2699 if( newOffset!=offset ){
2700 if( newOffset == -1 ){
2701 ((unixFile*)id)->lastErrno = errno;
2702 }else{
2703 ((unixFile*)id)->lastErrno = 0;
2704 }
2705 return -1;
2706 }
2707 got = read(id->h, pBuf, cnt);
2708#endif
2709 TIMER_END;
2710 if( got<0 ){
2711 ((unixFile*)id)->lastErrno = errno;
2712 }
2713 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2714 return got;
drhbfe66312006-10-03 17:40:40 +00002715}
2716
2717/*
drh734c9862008-11-28 15:37:20 +00002718** Read data from a file into a buffer. Return SQLITE_OK if all
2719** bytes were read successfully and SQLITE_IOERR if anything goes
2720** wrong.
drh339eb0b2008-03-07 15:34:11 +00002721*/
drh734c9862008-11-28 15:37:20 +00002722static int unixRead(
2723 sqlite3_file *id,
2724 void *pBuf,
2725 int amt,
2726 sqlite3_int64 offset
2727){
2728 int got;
2729 assert( id );
drh08c6d442009-02-09 17:34:07 +00002730
2731 /* Never read or write any of the bytes in the locking range */
2732 assert( ((unixFile*)id)->isLockable==0
2733 || offset>=PENDING_BYTE+512
2734 || offset+amt<=PENDING_BYTE );
2735
drh734c9862008-11-28 15:37:20 +00002736 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
2737 if( got==amt ){
2738 return SQLITE_OK;
2739 }else if( got<0 ){
2740 /* lastErrno set by seekAndRead */
2741 return SQLITE_IOERR_READ;
2742 }else{
2743 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2744 /* Unread parts of the buffer must be zero-filled */
2745 memset(&((char*)pBuf)[got], 0, amt-got);
2746 return SQLITE_IOERR_SHORT_READ;
2747 }
2748}
2749
2750/*
2751** Seek to the offset in id->offset then read cnt bytes into pBuf.
2752** Return the number of bytes actually read. Update the offset.
2753**
2754** To avoid stomping the errno value on a failed write the lastErrno value
2755** is set before returning.
2756*/
2757static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2758 int got;
2759 i64 newOffset;
2760 TIMER_START;
2761#if defined(USE_PREAD)
2762 got = pwrite(id->h, pBuf, cnt, offset);
2763#elif defined(USE_PREAD64)
2764 got = pwrite64(id->h, pBuf, cnt, offset);
2765#else
2766 newOffset = lseek(id->h, offset, SEEK_SET);
2767 if( newOffset!=offset ){
2768 if( newOffset == -1 ){
2769 ((unixFile*)id)->lastErrno = errno;
2770 }else{
2771 ((unixFile*)id)->lastErrno = 0;
2772 }
2773 return -1;
2774 }
2775 got = write(id->h, pBuf, cnt);
2776#endif
2777 TIMER_END;
2778 if( got<0 ){
2779 ((unixFile*)id)->lastErrno = errno;
2780 }
2781
2782 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2783 return got;
2784}
2785
2786
2787/*
2788** Write data from a buffer into a file. Return SQLITE_OK on success
2789** or some other error code on failure.
2790*/
2791static int unixWrite(
2792 sqlite3_file *id,
2793 const void *pBuf,
2794 int amt,
2795 sqlite3_int64 offset
2796){
2797 int wrote = 0;
2798 assert( id );
2799 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002800
drh08c6d442009-02-09 17:34:07 +00002801 /* Never read or write any of the bytes in the locking range */
2802 assert( ((unixFile*)id)->isLockable==0
2803 || offset>=PENDING_BYTE+512
2804 || offset+amt<=PENDING_BYTE );
2805
drh8f941bc2009-01-14 23:03:40 +00002806#ifndef NDEBUG
2807 /* If we are doing a normal write to a database file (as opposed to
2808 ** doing a hot-journal rollback or a write to some file other than a
2809 ** normal database file) then record the fact that the database
2810 ** has changed. If the transaction counter is modified, record that
2811 ** fact too.
2812 */
2813 if( ((unixFile*)id)->inNormalWrite ){
2814 unixFile *pFile = (unixFile*)id;
2815 pFile->dbUpdate = 1; /* The database has been modified */
2816 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002817 int rc;
drh8f941bc2009-01-14 23:03:40 +00002818 char oldCntr[4];
2819 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002820 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002821 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002822 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002823 pFile->transCntrChng = 1; /* The transaction counter has changed */
2824 }
2825 }
2826 }
2827#endif
2828
drh734c9862008-11-28 15:37:20 +00002829 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
2830 amt -= wrote;
2831 offset += wrote;
2832 pBuf = &((char*)pBuf)[wrote];
2833 }
2834 SimulateIOError(( wrote=(-1), amt=1 ));
2835 SimulateDiskfullError(( wrote=0, amt=1 ));
2836 if( amt>0 ){
2837 if( wrote<0 ){
2838 /* lastErrno set by seekAndWrite */
2839 return SQLITE_IOERR_WRITE;
2840 }else{
2841 ((unixFile*)id)->lastErrno = 0; /* not a system error */
2842 return SQLITE_FULL;
2843 }
2844 }
2845 return SQLITE_OK;
2846}
2847
2848#ifdef SQLITE_TEST
2849/*
2850** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002851** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002852*/
2853int sqlite3_sync_count = 0;
2854int sqlite3_fullsync_count = 0;
2855#endif
2856
2857/*
drh89240432009-03-25 01:06:01 +00002858** We do not trust systems to provide a working fdatasync(). Some do.
2859** Others do no. To be safe, we will stick with the (slower) fsync().
2860** If you know that your system does support fdatasync() correctly,
2861** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002862*/
drh89240432009-03-25 01:06:01 +00002863#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002864# define fdatasync fsync
2865#endif
2866
2867/*
2868** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2869** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2870** only available on Mac OS X. But that could change.
2871*/
2872#ifdef F_FULLFSYNC
2873# define HAVE_FULLFSYNC 1
2874#else
2875# define HAVE_FULLFSYNC 0
2876#endif
2877
2878
2879/*
2880** The fsync() system call does not work as advertised on many
2881** unix systems. The following procedure is an attempt to make
2882** it work better.
2883**
2884** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2885** for testing when we want to run through the test suite quickly.
2886** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2887** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2888** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002889**
2890** SQLite sets the dataOnly flag if the size of the file is unchanged.
2891** The idea behind dataOnly is that it should only write the file content
2892** to disk, not the inode. We only set dataOnly if the file size is
2893** unchanged since the file size is part of the inode. However,
2894** Ted Ts'o tells us that fdatasync() will also write the inode if the
2895** file size has changed. The only real difference between fdatasync()
2896** and fsync(), Ted tells us, is that fdatasync() will not flush the
2897** inode if the mtime or owner or other inode attributes have changed.
2898** We only care about the file size, not the other file attributes, so
2899** as far as SQLite is concerned, an fdatasync() is always adequate.
2900** So, we always use fdatasync() if it is available, regardless of
2901** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002902*/
2903static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002904 int rc;
drh734c9862008-11-28 15:37:20 +00002905
2906 /* The following "ifdef/elif/else/" block has the same structure as
2907 ** the one below. It is replicated here solely to avoid cluttering
2908 ** up the real code with the UNUSED_PARAMETER() macros.
2909 */
2910#ifdef SQLITE_NO_SYNC
2911 UNUSED_PARAMETER(fd);
2912 UNUSED_PARAMETER(fullSync);
2913 UNUSED_PARAMETER(dataOnly);
2914#elif HAVE_FULLFSYNC
2915 UNUSED_PARAMETER(dataOnly);
2916#else
2917 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002918 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002919#endif
2920
2921 /* Record the number of times that we do a normal fsync() and
2922 ** FULLSYNC. This is used during testing to verify that this procedure
2923 ** gets called with the correct arguments.
2924 */
2925#ifdef SQLITE_TEST
2926 if( fullSync ) sqlite3_fullsync_count++;
2927 sqlite3_sync_count++;
2928#endif
2929
2930 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2931 ** no-op
2932 */
2933#ifdef SQLITE_NO_SYNC
2934 rc = SQLITE_OK;
2935#elif HAVE_FULLFSYNC
2936 if( fullSync ){
2937 rc = fcntl(fd, F_FULLFSYNC, 0);
2938 }else{
2939 rc = 1;
2940 }
2941 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00002942 ** It shouldn't be possible for fullfsync to fail on the local
2943 ** file system (on OSX), so failure indicates that FULLFSYNC
2944 ** isn't supported for this file system. So, attempt an fsync
2945 ** and (for now) ignore the overhead of a superfluous fcntl call.
2946 ** It'd be better to detect fullfsync support once and avoid
2947 ** the fcntl call every time sync is called.
2948 */
drh734c9862008-11-28 15:37:20 +00002949 if( rc ) rc = fsync(fd);
2950
2951#else
drh0b647ff2009-03-21 14:41:04 +00002952 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00002953#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00002954 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00002955 rc = fsync(fd);
2956 }
drh0b647ff2009-03-21 14:41:04 +00002957#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00002958#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
2959
2960 if( OS_VXWORKS && rc!= -1 ){
2961 rc = 0;
2962 }
chw97185482008-11-17 08:05:31 +00002963 return rc;
drhbfe66312006-10-03 17:40:40 +00002964}
2965
drh734c9862008-11-28 15:37:20 +00002966/*
2967** Make sure all writes to a particular file are committed to disk.
2968**
2969** If dataOnly==0 then both the file itself and its metadata (file
2970** size, access time, etc) are synced. If dataOnly!=0 then only the
2971** file data is synced.
2972**
2973** Under Unix, also make sure that the directory entry for the file
2974** has been created by fsync-ing the directory that contains the file.
2975** If we do not do this and we encounter a power failure, the directory
2976** entry for the journal might not exist after we reboot. The next
2977** SQLite to access the file will not know that the journal exists (because
2978** the directory entry for the journal was never created) and the transaction
2979** will not roll back - possibly leading to database corruption.
2980*/
2981static int unixSync(sqlite3_file *id, int flags){
2982 int rc;
2983 unixFile *pFile = (unixFile*)id;
2984
2985 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
2986 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
2987
2988 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2989 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2990 || (flags&0x0F)==SQLITE_SYNC_FULL
2991 );
2992
2993 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2994 ** line is to test that doing so does not cause any problems.
2995 */
2996 SimulateDiskfullError( return SQLITE_FULL );
2997
2998 assert( pFile );
2999 OSTRACE2("SYNC %-3d\n", pFile->h);
3000 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3001 SimulateIOError( rc=1 );
3002 if( rc ){
3003 pFile->lastErrno = errno;
3004 return SQLITE_IOERR_FSYNC;
3005 }
3006 if( pFile->dirfd>=0 ){
3007 int err;
3008 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3009 HAVE_FULLFSYNC, isFullsync);
3010#ifndef SQLITE_DISABLE_DIRSYNC
3011 /* The directory sync is only attempted if full_fsync is
3012 ** turned off or unavailable. If a full_fsync occurred above,
3013 ** then the directory sync is superfluous.
3014 */
3015 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3016 /*
3017 ** We have received multiple reports of fsync() returning
3018 ** errors when applied to directories on certain file systems.
3019 ** A failed directory sync is not a big deal. So it seems
3020 ** better to ignore the error. Ticket #1657
3021 */
3022 /* pFile->lastErrno = errno; */
3023 /* return SQLITE_IOERR; */
3024 }
3025#endif
3026 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3027 if( err==0 ){ /* directory when we are done */
3028 pFile->dirfd = -1;
3029 }else{
3030 pFile->lastErrno = errno;
3031 rc = SQLITE_IOERR_DIR_CLOSE;
3032 }
3033 }
3034 return rc;
3035}
3036
3037/*
3038** Truncate an open file to a specified size
3039*/
3040static int unixTruncate(sqlite3_file *id, i64 nByte){
3041 int rc;
3042 assert( id );
3043 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3044 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3045 if( rc ){
3046 ((unixFile*)id)->lastErrno = errno;
3047 return SQLITE_IOERR_TRUNCATE;
3048 }else{
3049 return SQLITE_OK;
3050 }
3051}
3052
3053/*
3054** Determine the current size of a file in bytes
3055*/
3056static int unixFileSize(sqlite3_file *id, i64 *pSize){
3057 int rc;
3058 struct stat buf;
3059 assert( id );
3060 rc = fstat(((unixFile*)id)->h, &buf);
3061 SimulateIOError( rc=1 );
3062 if( rc!=0 ){
3063 ((unixFile*)id)->lastErrno = errno;
3064 return SQLITE_IOERR_FSTAT;
3065 }
3066 *pSize = buf.st_size;
3067
3068 /* When opening a zero-size database, the findLockInfo() procedure
3069 ** writes a single byte into that file in order to work around a bug
3070 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3071 ** layers, we need to report this file size as zero even though it is
3072 ** really 1. Ticket #3260.
3073 */
3074 if( *pSize==1 ) *pSize = 0;
3075
3076
3077 return SQLITE_OK;
3078}
3079
drhd2cb50b2009-01-09 21:41:17 +00003080#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003081/*
3082** Handler for proxy-locking file-control verbs. Defined below in the
3083** proxying locking division.
3084*/
3085static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003086#endif
drh715ff302008-12-03 22:32:44 +00003087
danielk1977ad94b582007-08-20 06:44:22 +00003088
danielk1977e3026632004-06-22 11:29:02 +00003089/*
drh9e33c2c2007-08-31 18:34:59 +00003090** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003091*/
drhcc6bb3e2007-08-31 16:11:35 +00003092static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003093 switch( op ){
3094 case SQLITE_FCNTL_LOCKSTATE: {
3095 *(int*)pArg = ((unixFile*)id)->locktype;
3096 return SQLITE_OK;
3097 }
drh7708e972008-11-29 00:56:52 +00003098 case SQLITE_LAST_ERRNO: {
3099 *(int*)pArg = ((unixFile*)id)->lastErrno;
3100 return SQLITE_OK;
3101 }
drh8f941bc2009-01-14 23:03:40 +00003102#ifndef NDEBUG
3103 /* The pager calls this method to signal that it has done
3104 ** a rollback and that the database is therefore unchanged and
3105 ** it hence it is OK for the transaction change counter to be
3106 ** unchanged.
3107 */
3108 case SQLITE_FCNTL_DB_UNCHANGED: {
3109 ((unixFile*)id)->dbUpdate = 0;
3110 return SQLITE_OK;
3111 }
3112#endif
drhd2cb50b2009-01-09 21:41:17 +00003113#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003114 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003115 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003116 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003117 }
drhd2cb50b2009-01-09 21:41:17 +00003118#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003119 }
drhcc6bb3e2007-08-31 16:11:35 +00003120 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003121}
3122
3123/*
danielk1977a3d4c882007-03-23 10:08:38 +00003124** Return the sector size in bytes of the underlying block device for
3125** the specified file. This is almost always 512 bytes, but may be
3126** larger for some devices.
3127**
3128** SQLite code assumes this function cannot fail. It also assumes that
3129** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003130** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003131** same for both.
3132*/
danielk1977397d65f2008-11-19 11:35:39 +00003133static int unixSectorSize(sqlite3_file *NotUsed){
3134 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003135 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003136}
3137
danielk197790949c22007-08-17 16:50:38 +00003138/*
danielk1977397d65f2008-11-19 11:35:39 +00003139** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003140*/
danielk1977397d65f2008-11-19 11:35:39 +00003141static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3142 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003143 return 0;
3144}
3145
drh734c9862008-11-28 15:37:20 +00003146/*
3147** Here ends the implementation of all sqlite3_file methods.
3148**
3149********************** End sqlite3_file Methods *******************************
3150******************************************************************************/
3151
3152/*
drh6b9d6dd2008-12-03 19:34:47 +00003153** This division contains definitions of sqlite3_io_methods objects that
3154** implement various file locking strategies. It also contains definitions
3155** of "finder" functions. A finder-function is used to locate the appropriate
3156** sqlite3_io_methods object for a particular database file. The pAppData
3157** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3158** the correct finder-function for that VFS.
3159**
3160** Most finder functions return a pointer to a fixed sqlite3_io_methods
3161** object. The only interesting finder-function is autolockIoFinder, which
3162** looks at the filesystem type and tries to guess the best locking
3163** strategy from that.
3164**
drh1875f7a2008-12-08 18:19:17 +00003165** For finder-funtion F, two objects are created:
3166**
3167** (1) The real finder-function named "FImpt()".
3168**
3169** (2) A constant pointer to this functio named just "F".
3170**
3171**
3172** A pointer to the F pointer is used as the pAppData value for VFS
3173** objects. We have to do this instead of letting pAppData point
3174** directly at the finder-function since C90 rules prevent a void*
3175** from be cast into a function pointer.
3176**
drh6b9d6dd2008-12-03 19:34:47 +00003177**
drh7708e972008-11-29 00:56:52 +00003178** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003179**
drh7708e972008-11-29 00:56:52 +00003180** * A constant sqlite3_io_methods object call METHOD that has locking
3181** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3182**
3183** * An I/O method finder function called FINDER that returns a pointer
3184** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003185*/
drh7708e972008-11-29 00:56:52 +00003186#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3187static const sqlite3_io_methods METHOD = { \
3188 1, /* iVersion */ \
3189 CLOSE, /* xClose */ \
3190 unixRead, /* xRead */ \
3191 unixWrite, /* xWrite */ \
3192 unixTruncate, /* xTruncate */ \
3193 unixSync, /* xSync */ \
3194 unixFileSize, /* xFileSize */ \
3195 LOCK, /* xLock */ \
3196 UNLOCK, /* xUnlock */ \
3197 CKLOCK, /* xCheckReservedLock */ \
3198 unixFileControl, /* xFileControl */ \
3199 unixSectorSize, /* xSectorSize */ \
3200 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3201}; \
drh1875f7a2008-12-08 18:19:17 +00003202static const sqlite3_io_methods *FINDER##Impl(const char *z, int h){ \
drh7708e972008-11-29 00:56:52 +00003203 UNUSED_PARAMETER(z); UNUSED_PARAMETER(h); \
3204 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003205} \
3206static const sqlite3_io_methods *(*const FINDER)(const char*,int) \
3207 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003208
3209/*
3210** Here are all of the sqlite3_io_methods objects for each of the
3211** locking strategies. Functions that return pointers to these methods
3212** are also created.
3213*/
3214IOMETHODS(
3215 posixIoFinder, /* Finder function name */
3216 posixIoMethods, /* sqlite3_io_methods object name */
3217 unixClose, /* xClose method */
3218 unixLock, /* xLock method */
3219 unixUnlock, /* xUnlock method */
3220 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003221)
drh7708e972008-11-29 00:56:52 +00003222IOMETHODS(
3223 nolockIoFinder, /* Finder function name */
3224 nolockIoMethods, /* sqlite3_io_methods object name */
3225 nolockClose, /* xClose method */
3226 nolockLock, /* xLock method */
3227 nolockUnlock, /* xUnlock method */
3228 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003229)
drh7708e972008-11-29 00:56:52 +00003230IOMETHODS(
3231 dotlockIoFinder, /* Finder function name */
3232 dotlockIoMethods, /* sqlite3_io_methods object name */
3233 dotlockClose, /* xClose method */
3234 dotlockLock, /* xLock method */
3235 dotlockUnlock, /* xUnlock method */
3236 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003237)
drh7708e972008-11-29 00:56:52 +00003238
chw78a13182009-04-07 05:35:03 +00003239#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003240IOMETHODS(
3241 flockIoFinder, /* Finder function name */
3242 flockIoMethods, /* sqlite3_io_methods object name */
3243 flockClose, /* xClose method */
3244 flockLock, /* xLock method */
3245 flockUnlock, /* xUnlock method */
3246 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003247)
drh7708e972008-11-29 00:56:52 +00003248#endif
3249
drh6c7d5c52008-11-21 20:32:33 +00003250#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003251IOMETHODS(
3252 semIoFinder, /* Finder function name */
3253 semIoMethods, /* sqlite3_io_methods object name */
3254 semClose, /* xClose method */
3255 semLock, /* xLock method */
3256 semUnlock, /* xUnlock method */
3257 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003258)
aswiftaebf4132008-11-21 00:10:35 +00003259#endif
drh7708e972008-11-29 00:56:52 +00003260
drhd2cb50b2009-01-09 21:41:17 +00003261#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003262IOMETHODS(
3263 afpIoFinder, /* Finder function name */
3264 afpIoMethods, /* sqlite3_io_methods object name */
3265 afpClose, /* xClose method */
3266 afpLock, /* xLock method */
3267 afpUnlock, /* xUnlock method */
3268 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003269)
drh715ff302008-12-03 22:32:44 +00003270#endif
3271
3272/*
3273** The proxy locking method is a "super-method" in the sense that it
3274** opens secondary file descriptors for the conch and lock files and
3275** it uses proxy, dot-file, AFP, and flock() locking methods on those
3276** secondary files. For this reason, the division that implements
3277** proxy locking is located much further down in the file. But we need
3278** to go ahead and define the sqlite3_io_methods and finder function
3279** for proxy locking here. So we forward declare the I/O methods.
3280*/
drhd2cb50b2009-01-09 21:41:17 +00003281#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003282static int proxyClose(sqlite3_file*);
3283static int proxyLock(sqlite3_file*, int);
3284static int proxyUnlock(sqlite3_file*, int);
3285static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003286IOMETHODS(
3287 proxyIoFinder, /* Finder function name */
3288 proxyIoMethods, /* sqlite3_io_methods object name */
3289 proxyClose, /* xClose method */
3290 proxyLock, /* xLock method */
3291 proxyUnlock, /* xUnlock method */
3292 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003293)
aswiftaebf4132008-11-21 00:10:35 +00003294#endif
drh7708e972008-11-29 00:56:52 +00003295
3296
drhd2cb50b2009-01-09 21:41:17 +00003297#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003298/*
drh6b9d6dd2008-12-03 19:34:47 +00003299** This "finder" function attempts to determine the best locking strategy
3300** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003301** object that implements that strategy.
3302**
3303** This is for MacOSX only.
3304*/
drh1875f7a2008-12-08 18:19:17 +00003305static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003306 const char *filePath, /* name of the database file */
3307 int fd /* file descriptor open on the database file */
3308){
3309 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003310 const char *zFilesystem; /* Filesystem type name */
3311 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003312 } aMap[] = {
3313 { "hfs", &posixIoMethods },
3314 { "ufs", &posixIoMethods },
3315 { "afpfs", &afpIoMethods },
3316#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
3317 { "smbfs", &afpIoMethods },
3318#else
3319 { "smbfs", &flockIoMethods },
3320#endif
3321 { "webdav", &nolockIoMethods },
3322 { 0, 0 }
3323 };
3324 int i;
3325 struct statfs fsInfo;
3326 struct flock lockInfo;
3327
3328 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003329 /* If filePath==NULL that means we are dealing with a transient file
3330 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003331 return &nolockIoMethods;
3332 }
3333 if( statfs(filePath, &fsInfo) != -1 ){
3334 if( fsInfo.f_flags & MNT_RDONLY ){
3335 return &nolockIoMethods;
3336 }
3337 for(i=0; aMap[i].zFilesystem; i++){
3338 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3339 return aMap[i].pMethods;
3340 }
3341 }
3342 }
3343
3344 /* Default case. Handles, amongst others, "nfs".
3345 ** Test byte-range lock using fcntl(). If the call succeeds,
3346 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003347 */
drh7708e972008-11-29 00:56:52 +00003348 lockInfo.l_len = 1;
3349 lockInfo.l_start = 0;
3350 lockInfo.l_whence = SEEK_SET;
3351 lockInfo.l_type = F_RDLCK;
3352 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
3353 return &posixIoMethods;
3354 }else{
3355 return &dotlockIoMethods;
3356 }
3357}
danielk1977852e2322008-12-22 03:36:59 +00003358static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
drh1875f7a2008-12-08 18:19:17 +00003359 = autolockIoFinderImpl;
3360
drhd2cb50b2009-01-09 21:41:17 +00003361#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003362
chw78a13182009-04-07 05:35:03 +00003363#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
3364/*
3365** This "finder" function attempts to determine the best locking strategy
3366** for the database file "filePath". It then returns the sqlite3_io_methods
3367** object that implements that strategy.
3368**
3369** This is for VXWorks only.
3370*/
3371static const sqlite3_io_methods *autolockIoFinderImpl(
3372 const char *filePath, /* name of the database file */
3373 int fd /* file descriptor open on the database file */
3374){
3375 struct flock lockInfo;
3376
3377 if( !filePath ){
3378 /* If filePath==NULL that means we are dealing with a transient file
3379 ** that does not need to be locked. */
3380 return &nolockIoMethods;
3381 }
3382
3383 /* Test if fcntl() is supported and use POSIX style locks.
3384 ** Otherwise fall back to the named semaphore method.
3385 */
3386 lockInfo.l_len = 1;
3387 lockInfo.l_start = 0;
3388 lockInfo.l_whence = SEEK_SET;
3389 lockInfo.l_type = F_RDLCK;
3390 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
3391 return &posixIoMethods;
3392 }else{
3393 return &semIoMethods;
3394 }
3395}
3396static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
3397 = autolockIoFinderImpl;
3398
3399#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
3400
drh7708e972008-11-29 00:56:52 +00003401/*
3402** An abstract type for a pointer to a IO method finder function:
3403*/
3404typedef const sqlite3_io_methods *(*finder_type)(const char*,int);
3405
aswiftaebf4132008-11-21 00:10:35 +00003406
drh734c9862008-11-28 15:37:20 +00003407/****************************************************************************
3408**************************** sqlite3_vfs methods ****************************
3409**
3410** This division contains the implementation of methods on the
3411** sqlite3_vfs object.
3412*/
3413
danielk1977a3d4c882007-03-23 10:08:38 +00003414/*
danielk1977e339d652008-06-28 11:23:00 +00003415** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003416*/
3417static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003418 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003419 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003420 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003421 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003422 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003423 int noLock, /* Omit locking if true */
3424 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003425){
drh7708e972008-11-29 00:56:52 +00003426 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003427 unixFile *pNew = (unixFile *)pId;
3428 int rc = SQLITE_OK;
3429
danielk197717b90b52008-06-06 11:11:25 +00003430 assert( pNew->pLock==NULL );
3431 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003432
drh715ff302008-12-03 22:32:44 +00003433 /* Parameter isDelete is only used on vxworks.
3434 ** Express this explicitly here to prevent compiler warnings
3435 ** about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003436 */
drh7708e972008-11-29 00:56:52 +00003437#if !OS_VXWORKS
3438 UNUSED_PARAMETER(isDelete);
3439#endif
danielk1977a03396a2008-11-19 14:35:46 +00003440
drh218c5082008-03-07 00:27:10 +00003441 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003442 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003443 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003444 SET_THREADID(pNew);
drh339eb0b2008-03-07 15:34:11 +00003445
drh6c7d5c52008-11-21 20:32:33 +00003446#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003447 pNew->pId = vxworksFindFileId(zFilename);
3448 if( pNew->pId==0 ){
3449 noLock = 1;
3450 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003451 }
3452#endif
3453
drhda0e7682008-07-30 15:27:54 +00003454 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003455 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003456 }else{
drh1875f7a2008-12-08 18:19:17 +00003457 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, h);
aswiftaebf4132008-11-21 00:10:35 +00003458#if SQLITE_ENABLE_LOCKING_STYLE
3459 /* Cache zFilename in the locking context (AFP and dotlock override) for
3460 ** proxyLock activation is possible (remote proxy is based on db name)
3461 ** zFilename remains valid until file is closed, to support */
3462 pNew->lockingContext = (void*)zFilename;
3463#endif
drhda0e7682008-07-30 15:27:54 +00003464 }
danielk1977e339d652008-06-28 11:23:00 +00003465
drh7708e972008-11-29 00:56:52 +00003466 if( pLockingStyle == &posixIoMethods ){
3467 unixEnterMutex();
3468 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3469 unixLeaveMutex();
3470 }
danielk1977e339d652008-06-28 11:23:00 +00003471
drhd2cb50b2009-01-09 21:41:17 +00003472#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003473 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003474 /* AFP locking uses the file path so it needs to be included in
3475 ** the afpLockingContext.
3476 */
3477 afpLockingContext *pCtx;
3478 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3479 if( pCtx==0 ){
3480 rc = SQLITE_NOMEM;
3481 }else{
3482 /* NB: zFilename exists and remains valid until the file is closed
3483 ** according to requirement F11141. So we do not need to make a
3484 ** copy of the filename. */
3485 pCtx->dbPath = zFilename;
3486 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003487 unixEnterMutex();
drh7708e972008-11-29 00:56:52 +00003488 rc = findLockInfo(pNew, NULL, &pNew->pOpen);
3489 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003490 }
drh7708e972008-11-29 00:56:52 +00003491 }
3492#endif
danielk1977e339d652008-06-28 11:23:00 +00003493
drh7708e972008-11-29 00:56:52 +00003494 else if( pLockingStyle == &dotlockIoMethods ){
3495 /* Dotfile locking uses the file path so it needs to be included in
3496 ** the dotlockLockingContext
3497 */
3498 char *zLockFile;
3499 int nFilename;
drhea678832008-12-10 19:26:22 +00003500 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003501 zLockFile = (char *)sqlite3_malloc(nFilename);
3502 if( zLockFile==0 ){
3503 rc = SQLITE_NOMEM;
3504 }else{
3505 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003506 }
drh7708e972008-11-29 00:56:52 +00003507 pNew->lockingContext = zLockFile;
3508 }
danielk1977e339d652008-06-28 11:23:00 +00003509
drh6c7d5c52008-11-21 20:32:33 +00003510#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003511 else if( pLockingStyle == &semIoMethods ){
3512 /* Named semaphore locking uses the file path so it needs to be
3513 ** included in the semLockingContext
3514 */
3515 unixEnterMutex();
3516 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3517 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3518 char *zSemName = pNew->pOpen->aSemName;
3519 int n;
3520 sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem",
3521 pNew->pId->zCanonicalName);
3522 for( n=0; zSemName[n]; n++ )
3523 if( zSemName[n]=='/' ) zSemName[n] = '_';
3524 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3525 if( pNew->pOpen->pSem == SEM_FAILED ){
3526 rc = SQLITE_NOMEM;
3527 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003528 }
chw97185482008-11-17 08:05:31 +00003529 }
drh7708e972008-11-29 00:56:52 +00003530 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003531 }
drh7708e972008-11-29 00:56:52 +00003532#endif
aswift5b1a2562008-08-22 00:22:35 +00003533
3534 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003535#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003536 if( rc!=SQLITE_OK ){
3537 unlink(zFilename);
3538 isDelete = 0;
3539 }
3540 pNew->isDelete = isDelete;
3541#endif
danielk1977e339d652008-06-28 11:23:00 +00003542 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003543 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
drhbfe66312006-10-03 17:40:40 +00003544 close(h);
danielk1977e339d652008-06-28 11:23:00 +00003545 }else{
drh7708e972008-11-29 00:56:52 +00003546 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003547 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003548 }
danielk1977e339d652008-06-28 11:23:00 +00003549 return rc;
drh054889e2005-11-30 03:20:31 +00003550}
drh9c06c952005-11-26 00:25:00 +00003551
danielk1977ad94b582007-08-20 06:44:22 +00003552/*
3553** Open a file descriptor to the directory containing file zFilename.
3554** If successful, *pFd is set to the opened file descriptor and
3555** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3556** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3557** value.
3558**
3559** If SQLITE_OK is returned, the caller is responsible for closing
3560** the file descriptor *pFd using close().
3561*/
danielk1977fee2d252007-08-18 10:59:19 +00003562static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003563 int ii;
drh777b17a2007-09-20 10:02:54 +00003564 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003565 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003566
drh153c62c2007-08-24 03:51:33 +00003567 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003568 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003569 if( ii>0 ){
3570 zDirname[ii] = '\0';
3571 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003572 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003573#ifdef FD_CLOEXEC
3574 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3575#endif
3576 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3577 }
3578 }
danielk1977fee2d252007-08-18 10:59:19 +00003579 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00003580 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00003581}
3582
danielk1977b4b47412007-08-17 15:53:36 +00003583/*
danielk197717b90b52008-06-06 11:11:25 +00003584** Create a temporary file name in zBuf. zBuf must be allocated
3585** by the calling process and must be big enough to hold at least
3586** pVfs->mxPathname bytes.
3587*/
3588static int getTempname(int nBuf, char *zBuf){
3589 static const char *azDirs[] = {
3590 0,
aswiftaebf4132008-11-21 00:10:35 +00003591 0,
danielk197717b90b52008-06-06 11:11:25 +00003592 "/var/tmp",
3593 "/usr/tmp",
3594 "/tmp",
3595 ".",
3596 };
3597 static const unsigned char zChars[] =
3598 "abcdefghijklmnopqrstuvwxyz"
3599 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3600 "0123456789";
drh41022642008-11-21 00:24:42 +00003601 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003602 struct stat buf;
3603 const char *zDir = ".";
3604
3605 /* It's odd to simulate an io-error here, but really this is just
3606 ** using the io-error infrastructure to test that SQLite handles this
3607 ** function failing.
3608 */
3609 SimulateIOError( return SQLITE_IOERR );
3610
3611 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003612 if (NULL == azDirs[1]) {
3613 azDirs[1] = getenv("TMPDIR");
3614 }
3615
3616 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003617 if( azDirs[i]==0 ) continue;
3618 if( stat(azDirs[i], &buf) ) continue;
3619 if( !S_ISDIR(buf.st_mode) ) continue;
3620 if( access(azDirs[i], 07) ) continue;
3621 zDir = azDirs[i];
3622 break;
3623 }
3624
3625 /* Check that the output buffer is large enough for the temporary file
3626 ** name. If it is not, return SQLITE_ERROR.
3627 */
danielk197700e13612008-11-17 19:18:54 +00003628 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003629 return SQLITE_ERROR;
3630 }
3631
3632 do{
3633 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003634 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003635 sqlite3_randomness(15, &zBuf[j]);
3636 for(i=0; i<15; i++, j++){
3637 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3638 }
3639 zBuf[j] = 0;
3640 }while( access(zBuf,0)==0 );
3641 return SQLITE_OK;
3642}
3643
drhd2cb50b2009-01-09 21:41:17 +00003644#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003645/*
3646** Routine to transform a unixFile into a proxy-locking unixFile.
3647** Implementation in the proxy-lock division, but used by unixOpen()
3648** if SQLITE_PREFER_PROXY_LOCKING is defined.
3649*/
3650static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003651#endif
drhc66d5b62008-12-03 22:48:32 +00003652
danielk197717b90b52008-06-06 11:11:25 +00003653
3654/*
danielk1977ad94b582007-08-20 06:44:22 +00003655** Open the file zPath.
3656**
danielk1977b4b47412007-08-17 15:53:36 +00003657** Previously, the SQLite OS layer used three functions in place of this
3658** one:
3659**
3660** sqlite3OsOpenReadWrite();
3661** sqlite3OsOpenReadOnly();
3662** sqlite3OsOpenExclusive();
3663**
3664** These calls correspond to the following combinations of flags:
3665**
3666** ReadWrite() -> (READWRITE | CREATE)
3667** ReadOnly() -> (READONLY)
3668** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
3669**
3670** The old OpenExclusive() accepted a boolean argument - "delFlag". If
3671** true, the file was configured to be automatically deleted when the
3672** file handle closed. To achieve the same effect using this new
3673** interface, add the DELETEONCLOSE flag to those specified above for
3674** OpenExclusive().
3675*/
3676static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00003677 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
3678 const char *zPath, /* Pathname of file to be opened */
3679 sqlite3_file *pFile, /* The file descriptor to be filled in */
3680 int flags, /* Input flags to control the opening */
3681 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00003682){
drh577d6742009-04-07 00:35:20 +00003683 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00003684 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00003685 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00003686 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00003687 int noLock; /* True to omit locking primitives */
aswiftaebf4132008-11-21 00:10:35 +00003688 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003689
3690 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
3691 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
3692 int isCreate = (flags & SQLITE_OPEN_CREATE);
3693 int isReadonly = (flags & SQLITE_OPEN_READONLY);
3694 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
3695
danielk1977fee2d252007-08-18 10:59:19 +00003696 /* If creating a master or main-file journal, this function will open
3697 ** a file-descriptor on the directory too. The first time unixSync()
3698 ** is called the directory file descriptor will be fsync()ed and close()d.
3699 */
3700 int isOpenDirectory = (isCreate &&
3701 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
3702 );
3703
danielk197717b90b52008-06-06 11:11:25 +00003704 /* If argument zPath is a NULL pointer, this function is required to open
3705 ** a temporary file. Use this buffer to store the file name in.
3706 */
3707 char zTmpname[MAX_PATHNAME+1];
3708 const char *zName = zPath;
3709
danielk1977fee2d252007-08-18 10:59:19 +00003710 /* Check the following statements are true:
3711 **
3712 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
3713 ** (b) if CREATE is set, then READWRITE must also be set, and
3714 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00003715 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00003716 */
danielk1977b4b47412007-08-17 15:53:36 +00003717 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00003718 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00003719 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00003720 assert(isDelete==0 || isCreate);
3721
drh33f4e022007-09-03 15:19:34 +00003722 /* The main DB, main journal, and master journal are never automatically
3723 ** deleted
3724 */
3725 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
3726 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
3727 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00003728
danielk1977fee2d252007-08-18 10:59:19 +00003729 /* Assert that the upper layer has set one of the "file-type" flags. */
3730 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
3731 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3732 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00003733 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00003734 );
3735
danielk1977e339d652008-06-28 11:23:00 +00003736 memset(pFile, 0, sizeof(unixFile));
3737
danielk197717b90b52008-06-06 11:11:25 +00003738 if( !zName ){
danielk197717b90b52008-06-06 11:11:25 +00003739 assert(isDelete && !isOpenDirectory);
3740 rc = getTempname(MAX_PATHNAME+1, zTmpname);
3741 if( rc!=SQLITE_OK ){
3742 return rc;
3743 }
3744 zName = zTmpname;
3745 }
3746
drh734c9862008-11-28 15:37:20 +00003747 if( isReadonly ) openFlags |= O_RDONLY;
3748 if( isReadWrite ) openFlags |= O_RDWR;
3749 if( isCreate ) openFlags |= O_CREAT;
3750 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
3751 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00003752
drh734c9862008-11-28 15:37:20 +00003753 fd = open(zName, openFlags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
3754 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
danielk19772f2d8c72007-08-30 16:13:33 +00003755 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00003756 /* Failed to open the file for read/write access. Try read-only. */
3757 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3758 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00003759 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00003760 }
3761 if( fd<0 ){
3762 return SQLITE_CANTOPEN;
3763 }
3764 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00003765#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003766 zPath = zName;
3767#else
danielk197717b90b52008-06-06 11:11:25 +00003768 unlink(zName);
chw97185482008-11-17 08:05:31 +00003769#endif
danielk1977b4b47412007-08-17 15:53:36 +00003770 }
drh41022642008-11-21 00:24:42 +00003771#if SQLITE_ENABLE_LOCKING_STYLE
3772 else{
drh734c9862008-11-28 15:37:20 +00003773 ((unixFile*)pFile)->openFlags = openFlags;
drh41022642008-11-21 00:24:42 +00003774 }
3775#endif
danielk1977b4b47412007-08-17 15:53:36 +00003776 if( pOutFlags ){
3777 *pOutFlags = flags;
3778 }
3779
drh08c6d442009-02-09 17:34:07 +00003780#ifndef NDEBUG
3781 if( (flags & SQLITE_OPEN_MAIN_DB)!=0 ){
3782 ((unixFile*)pFile)->isLockable = 1;
3783 }
3784#endif
3785
drh577d6742009-04-07 00:35:20 +00003786 assert( fd>=0 );
danielk1977fee2d252007-08-18 10:59:19 +00003787 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00003788 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00003789 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003790 close(fd); /* silently leak if fail, already in error */
danielk1977fee2d252007-08-18 10:59:19 +00003791 return rc;
3792 }
3793 }
danielk1977e339d652008-06-28 11:23:00 +00003794
3795#ifdef FD_CLOEXEC
3796 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3797#endif
3798
drhda0e7682008-07-30 15:27:54 +00003799 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00003800
3801#if SQLITE_PREFER_PROXY_LOCKING
3802 if( zPath!=NULL && !noLock ){
3803 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
3804 int useProxy = 0;
3805
3806 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy,
drh7708e972008-11-29 00:56:52 +00003807 ** 0 means never use proxy, NULL means use proxy for non-local files only
3808 */
aswiftaebf4132008-11-21 00:10:35 +00003809 if( envforce!=NULL ){
3810 useProxy = atoi(envforce)>0;
3811 }else{
3812 struct statfs fsInfo;
3813
3814 if( statfs(zPath, &fsInfo) == -1 ){
3815 ((unixFile*)pFile)->lastErrno = errno;
3816 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
3817 close(fd); /* silently leak if fail, in error */
3818 return SQLITE_IOERR_ACCESS;
3819 }
3820 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
3821 }
3822 if( useProxy ){
3823 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
3824 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00003825 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
aswiftaebf4132008-11-21 00:10:35 +00003826 }
3827 return rc;
3828 }
3829 }
3830#endif
3831
chw97185482008-11-17 08:05:31 +00003832 return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
danielk1977b4b47412007-08-17 15:53:36 +00003833}
3834
3835/*
danielk1977fee2d252007-08-18 10:59:19 +00003836** Delete the file at zPath. If the dirSync argument is true, fsync()
3837** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00003838*/
drh6b9d6dd2008-12-03 19:34:47 +00003839static int unixDelete(
3840 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
3841 const char *zPath, /* Name of file to be deleted */
3842 int dirSync /* If true, fsync() directory after deleting file */
3843){
danielk1977fee2d252007-08-18 10:59:19 +00003844 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00003845 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00003846 SimulateIOError(return SQLITE_IOERR_DELETE);
3847 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00003848#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00003849 if( dirSync ){
3850 int fd;
3851 rc = openDirectory(zPath, &fd);
3852 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00003853#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003854 if( fsync(fd)==-1 )
3855#else
3856 if( fsync(fd) )
3857#endif
3858 {
danielk1977fee2d252007-08-18 10:59:19 +00003859 rc = SQLITE_IOERR_DIR_FSYNC;
3860 }
aswiftaebf4132008-11-21 00:10:35 +00003861 if( close(fd)&&!rc ){
3862 rc = SQLITE_IOERR_DIR_CLOSE;
3863 }
danielk1977fee2d252007-08-18 10:59:19 +00003864 }
3865 }
danielk1977d138dd82008-10-15 16:02:48 +00003866#endif
danielk1977fee2d252007-08-18 10:59:19 +00003867 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00003868}
3869
danielk197790949c22007-08-17 16:50:38 +00003870/*
3871** Test the existance of or access permissions of file zPath. The
3872** test performed depends on the value of flags:
3873**
3874** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
3875** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
3876** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
3877**
3878** Otherwise return 0.
3879*/
danielk1977861f7452008-06-05 11:39:11 +00003880static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00003881 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
3882 const char *zPath, /* Path of the file to examine */
3883 int flags, /* What do we want to learn about the zPath file? */
3884 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00003885){
rse25c0d1a2007-09-20 08:38:14 +00003886 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00003887 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00003888 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00003889 switch( flags ){
3890 case SQLITE_ACCESS_EXISTS:
3891 amode = F_OK;
3892 break;
3893 case SQLITE_ACCESS_READWRITE:
3894 amode = W_OK|R_OK;
3895 break;
drh50d3f902007-08-27 21:10:36 +00003896 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00003897 amode = R_OK;
3898 break;
3899
3900 default:
3901 assert(!"Invalid flags argument");
3902 }
danielk1977861f7452008-06-05 11:39:11 +00003903 *pResOut = (access(zPath, amode)==0);
3904 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003905}
3906
danielk1977b4b47412007-08-17 15:53:36 +00003907
3908/*
3909** Turn a relative pathname into a full pathname. The relative path
3910** is stored as a nul-terminated string in the buffer pointed to by
3911** zPath.
3912**
3913** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
3914** (in this case, MAX_PATHNAME bytes). The full-path is written to
3915** this buffer before returning.
3916*/
danielk1977adfb9b02007-09-17 07:02:56 +00003917static int unixFullPathname(
3918 sqlite3_vfs *pVfs, /* Pointer to vfs object */
3919 const char *zPath, /* Possibly relative input path */
3920 int nOut, /* Size of output buffer in bytes */
3921 char *zOut /* Output buffer */
3922){
danielk1977843e65f2007-09-01 16:16:15 +00003923
3924 /* It's odd to simulate an io-error here, but really this is just
3925 ** using the io-error infrastructure to test that SQLite handles this
3926 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00003927 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00003928 */
3929 SimulateIOError( return SQLITE_ERROR );
3930
drh153c62c2007-08-24 03:51:33 +00003931 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00003932 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00003933
drh3c7f2dc2007-12-06 13:26:20 +00003934 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00003935 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00003936 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003937 }else{
3938 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00003939 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00003940 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00003941 }
drhea678832008-12-10 19:26:22 +00003942 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00003943 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003944 }
3945 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003946}
3947
drh0ccebe72005-06-07 22:22:50 +00003948
drh761df872006-12-21 01:29:22 +00003949#ifndef SQLITE_OMIT_LOAD_EXTENSION
3950/*
3951** Interfaces for opening a shared library, finding entry points
3952** within the shared library, and closing the shared library.
3953*/
3954#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00003955static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
3956 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00003957 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
3958}
danielk197795c8a542007-09-01 06:51:27 +00003959
3960/*
3961** SQLite calls this function immediately after a call to unixDlSym() or
3962** unixDlOpen() fails (returns a null pointer). If a more detailed error
3963** message is available, it is written to zBufOut. If no error message
3964** is available, zBufOut is left unmodified and SQLite uses a default
3965** error message.
3966*/
danielk1977397d65f2008-11-19 11:35:39 +00003967static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00003968 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00003969 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00003970 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003971 zErr = dlerror();
3972 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00003973 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00003974 }
drh6c7d5c52008-11-21 20:32:33 +00003975 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00003976}
drh1875f7a2008-12-08 18:19:17 +00003977static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
3978 /*
3979 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
3980 ** cast into a pointer to a function. And yet the library dlsym() routine
3981 ** returns a void* which is really a pointer to a function. So how do we
3982 ** use dlsym() with -pedantic-errors?
3983 **
3984 ** Variable x below is defined to be a pointer to a function taking
3985 ** parameters void* and const char* and returning a pointer to a function.
3986 ** We initialize x by assigning it a pointer to the dlsym() function.
3987 ** (That assignment requires a cast.) Then we call the function that
3988 ** x points to.
3989 **
3990 ** This work-around is unlikely to work correctly on any system where
3991 ** you really cannot cast a function pointer into void*. But then, on the
3992 ** other hand, dlsym() will not work on such a system either, so we have
3993 ** not really lost anything.
3994 */
3995 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00003996 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00003997 x = (void(*(*)(void*,const char*))(void))dlsym;
3998 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00003999}
danielk1977397d65f2008-11-19 11:35:39 +00004000static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4001 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004002 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004003}
danielk1977b4b47412007-08-17 15:53:36 +00004004#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4005 #define unixDlOpen 0
4006 #define unixDlError 0
4007 #define unixDlSym 0
4008 #define unixDlClose 0
4009#endif
4010
4011/*
danielk197790949c22007-08-17 16:50:38 +00004012** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004013*/
danielk1977397d65f2008-11-19 11:35:39 +00004014static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4015 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004016 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004017
drhbbd42a62004-05-22 17:41:58 +00004018 /* We have to initialize zBuf to prevent valgrind from reporting
4019 ** errors. The reports issued by valgrind are incorrect - we would
4020 ** prefer that the randomness be increased by making use of the
4021 ** uninitialized space in zBuf - but valgrind errors tend to worry
4022 ** some users. Rather than argue, it seems easier just to initialize
4023 ** the whole array and silence valgrind, even if that means less randomness
4024 ** in the random seed.
4025 **
4026 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004027 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004028 ** tests repeatable.
4029 */
danielk1977b4b47412007-08-17 15:53:36 +00004030 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004031#if !defined(SQLITE_TEST)
4032 {
drh842b8642005-01-21 17:53:17 +00004033 int pid, fd;
4034 fd = open("/dev/urandom", O_RDONLY);
4035 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004036 time_t t;
4037 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004038 memcpy(zBuf, &t, sizeof(t));
4039 pid = getpid();
4040 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004041 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004042 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004043 }else{
drh72cbd072008-10-14 17:58:38 +00004044 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004045 close(fd);
4046 }
drhbbd42a62004-05-22 17:41:58 +00004047 }
4048#endif
drh72cbd072008-10-14 17:58:38 +00004049 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004050}
4051
danielk1977b4b47412007-08-17 15:53:36 +00004052
drhbbd42a62004-05-22 17:41:58 +00004053/*
4054** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004055** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004056** The return value is the number of microseconds of sleep actually
4057** requested from the underlying operating system, a number which
4058** might be greater than or equal to the argument, but not less
4059** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004060*/
danielk1977397d65f2008-11-19 11:35:39 +00004061static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004062#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004063 struct timespec sp;
4064
4065 sp.tv_sec = microseconds / 1000000;
4066 sp.tv_nsec = (microseconds % 1000000) * 1000;
4067 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004068 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004069 return microseconds;
4070#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004071 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004072 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004073 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004074#else
danielk1977b4b47412007-08-17 15:53:36 +00004075 int seconds = (microseconds+999999)/1000000;
4076 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004077 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004078 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004079#endif
drh88f474a2006-01-02 20:00:12 +00004080}
4081
4082/*
drh6b9d6dd2008-12-03 19:34:47 +00004083** The following variable, if set to a non-zero value, is interpreted as
4084** the number of seconds since 1970 and is used to set the result of
4085** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004086*/
4087#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004088int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004089#endif
4090
4091/*
4092** Find the current time (in Universal Coordinated Time). Write the
4093** current time and date as a Julian Day number into *prNow and
4094** return 0. Return 1 if the time and date cannot be found.
4095*/
danielk1977397d65f2008-11-19 11:35:39 +00004096static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh0b3bf922009-06-15 20:45:34 +00004097#if defined(SQLITE_OMIT_FLOATING_POINT)
4098 time_t t;
4099 time(&t);
4100 *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
4101#elif defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00004102 time_t t;
4103 time(&t);
4104 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00004105#elif OS_VXWORKS
4106 struct timespec sNow;
4107 clock_gettime(CLOCK_REALTIME, &sNow);
4108 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00004109#else
4110 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00004111 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00004112 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
4113#endif
danielk1977397d65f2008-11-19 11:35:39 +00004114
drhbbd42a62004-05-22 17:41:58 +00004115#ifdef SQLITE_TEST
4116 if( sqlite3_current_time ){
4117 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4118 }
4119#endif
danielk1977397d65f2008-11-19 11:35:39 +00004120 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004121 return 0;
4122}
danielk1977b4b47412007-08-17 15:53:36 +00004123
drh6b9d6dd2008-12-03 19:34:47 +00004124/*
4125** We added the xGetLastError() method with the intention of providing
4126** better low-level error messages when operating-system problems come up
4127** during SQLite operation. But so far, none of that has been implemented
4128** in the core. So this routine is never called. For now, it is merely
4129** a place-holder.
4130*/
danielk1977397d65f2008-11-19 11:35:39 +00004131static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4132 UNUSED_PARAMETER(NotUsed);
4133 UNUSED_PARAMETER(NotUsed2);
4134 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004135 return 0;
4136}
4137
drh153c62c2007-08-24 03:51:33 +00004138/*
drh734c9862008-11-28 15:37:20 +00004139************************ End of sqlite3_vfs methods ***************************
4140******************************************************************************/
4141
drh715ff302008-12-03 22:32:44 +00004142/******************************************************************************
4143************************** Begin Proxy Locking ********************************
4144**
4145** Proxy locking is a "uber-locking-method" in this sense: It uses the
4146** other locking methods on secondary lock files. Proxy locking is a
4147** meta-layer over top of the primitive locking implemented above. For
4148** this reason, the division that implements of proxy locking is deferred
4149** until late in the file (here) after all of the other I/O methods have
4150** been defined - so that the primitive locking methods are available
4151** as services to help with the implementation of proxy locking.
4152**
4153****
4154**
4155** The default locking schemes in SQLite use byte-range locks on the
4156** database file to coordinate safe, concurrent access by multiple readers
4157** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4158** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4159** as POSIX read & write locks over fixed set of locations (via fsctl),
4160** on AFP and SMB only exclusive byte-range locks are available via fsctl
4161** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4162** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4163** address in the shared range is taken for a SHARED lock, the entire
4164** shared range is taken for an EXCLUSIVE lock):
4165**
4166** PENDING_BYTE 0x40000000
4167** RESERVED_BYTE 0x40000001
4168** SHARED_RANGE 0x40000002 -> 0x40000200
4169**
4170** This works well on the local file system, but shows a nearly 100x
4171** slowdown in read performance on AFP because the AFP client disables
4172** the read cache when byte-range locks are present. Enabling the read
4173** cache exposes a cache coherency problem that is present on all OS X
4174** supported network file systems. NFS and AFP both observe the
4175** close-to-open semantics for ensuring cache coherency
4176** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4177** address the requirements for concurrent database access by multiple
4178** readers and writers
4179** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4180**
4181** To address the performance and cache coherency issues, proxy file locking
4182** changes the way database access is controlled by limiting access to a
4183** single host at a time and moving file locks off of the database file
4184** and onto a proxy file on the local file system.
4185**
4186**
4187** Using proxy locks
4188** -----------------
4189**
4190** C APIs
4191**
4192** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4193** <proxy_path> | ":auto:");
4194** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4195**
4196**
4197** SQL pragmas
4198**
4199** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4200** PRAGMA [database.]lock_proxy_file
4201**
4202** Specifying ":auto:" means that if there is a conch file with a matching
4203** host ID in it, the proxy path in the conch file will be used, otherwise
4204** a proxy path based on the user's temp dir
4205** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4206** actual proxy file name is generated from the name and path of the
4207** database file. For example:
4208**
4209** For database path "/Users/me/foo.db"
4210** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4211**
4212** Once a lock proxy is configured for a database connection, it can not
4213** be removed, however it may be switched to a different proxy path via
4214** the above APIs (assuming the conch file is not being held by another
4215** connection or process).
4216**
4217**
4218** How proxy locking works
4219** -----------------------
4220**
4221** Proxy file locking relies primarily on two new supporting files:
4222**
4223** * conch file to limit access to the database file to a single host
4224** at a time
4225**
4226** * proxy file to act as a proxy for the advisory locks normally
4227** taken on the database
4228**
4229** The conch file - to use a proxy file, sqlite must first "hold the conch"
4230** by taking an sqlite-style shared lock on the conch file, reading the
4231** contents and comparing the host's unique host ID (see below) and lock
4232** proxy path against the values stored in the conch. The conch file is
4233** stored in the same directory as the database file and the file name
4234** is patterned after the database file name as ".<databasename>-conch".
4235** If the conch file does not exist, or it's contents do not match the
4236** host ID and/or proxy path, then the lock is escalated to an exclusive
4237** lock and the conch file contents is updated with the host ID and proxy
4238** path and the lock is downgraded to a shared lock again. If the conch
4239** is held by another process (with a shared lock), the exclusive lock
4240** will fail and SQLITE_BUSY is returned.
4241**
4242** The proxy file - a single-byte file used for all advisory file locks
4243** normally taken on the database file. This allows for safe sharing
4244** of the database file for multiple readers and writers on the same
4245** host (the conch ensures that they all use the same local lock file).
4246**
4247** There is a third file - the host ID file - used as a persistent record
4248** of a unique identifier for the host, a 128-byte unique host id file
4249** in the path defined by the HOSTIDPATH macro (default value is
4250** /Library/Caches/.com.apple.sqliteConchHostId).
4251**
4252** Requesting the lock proxy does not immediately take the conch, it is
4253** only taken when the first request to lock database file is made.
4254** This matches the semantics of the traditional locking behavior, where
4255** opening a connection to a database file does not take a lock on it.
4256** The shared lock and an open file descriptor are maintained until
4257** the connection to the database is closed.
4258**
4259** The proxy file and the lock file are never deleted so they only need
4260** to be created the first time they are used.
4261**
4262** Configuration options
4263** ---------------------
4264**
4265** SQLITE_PREFER_PROXY_LOCKING
4266**
4267** Database files accessed on non-local file systems are
4268** automatically configured for proxy locking, lock files are
4269** named automatically using the same logic as
4270** PRAGMA lock_proxy_file=":auto:"
4271**
4272** SQLITE_PROXY_DEBUG
4273**
4274** Enables the logging of error messages during host id file
4275** retrieval and creation
4276**
4277** HOSTIDPATH
4278**
4279** Overrides the default host ID file path location
4280**
4281** LOCKPROXYDIR
4282**
4283** Overrides the default directory used for lock proxy files that
4284** are named automatically via the ":auto:" setting
4285**
4286** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4287**
4288** Permissions to use when creating a directory for storing the
4289** lock proxy files, only used when LOCKPROXYDIR is not set.
4290**
4291**
4292** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4293** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4294** force proxy locking to be used for every database file opened, and 0
4295** will force automatic proxy locking to be disabled for all database
4296** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4297** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4298*/
4299
4300/*
4301** Proxy locking is only available on MacOSX
4302*/
drhd2cb50b2009-01-09 21:41:17 +00004303#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004304
4305#ifdef SQLITE_TEST
4306/* simulate multiple hosts by creating unique hostid file paths */
4307int sqlite3_hostid_num = 0;
4308#endif
4309
4310/*
4311** The proxyLockingContext has the path and file structures for the remote
4312** and local proxy files in it
4313*/
4314typedef struct proxyLockingContext proxyLockingContext;
4315struct proxyLockingContext {
4316 unixFile *conchFile; /* Open conch file */
4317 char *conchFilePath; /* Name of the conch file */
4318 unixFile *lockProxy; /* Open proxy lock file */
4319 char *lockProxyPath; /* Name of the proxy lock file */
4320 char *dbPath; /* Name of the open file */
4321 int conchHeld; /* True if the conch is currently held */
4322 void *oldLockingContext; /* Original lockingcontext to restore on close */
4323 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4324};
4325
4326/* HOSTIDLEN and CONCHLEN both include space for the string
4327** terminating nul
4328*/
4329#define HOSTIDLEN 128
4330#define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
4331#ifndef HOSTIDPATH
4332# define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
4333#endif
4334
4335/* basically a copy of unixRandomness with different
4336** test behavior built in */
4337static int proxyGenerateHostID(char *pHostID){
4338 int pid, fd, len;
4339 unsigned char *key = (unsigned char *)pHostID;
4340
4341 memset(key, 0, HOSTIDLEN);
4342 len = 0;
4343 fd = open("/dev/urandom", O_RDONLY);
4344 if( fd>=0 ){
4345 len = read(fd, key, HOSTIDLEN);
4346 close(fd); /* silently leak the fd if it fails */
4347 }
4348 if( len < HOSTIDLEN ){
4349 time_t t;
4350 time(&t);
4351 memcpy(key, &t, sizeof(t));
4352 pid = getpid();
4353 memcpy(&key[sizeof(t)], &pid, sizeof(pid));
4354 }
4355
4356#ifdef MAKE_PRETTY_HOSTID
4357 {
4358 int i;
4359 /* filter the bytes into printable ascii characters and NUL terminate */
4360 key[(HOSTIDLEN-1)] = 0x00;
4361 for( i=0; i<(HOSTIDLEN-1); i++ ){
4362 unsigned char pa = key[i]&0x7F;
4363 if( pa<0x20 ){
4364 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
4365 }else if( pa==0x7F ){
4366 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
4367 }
4368 }
4369 }
4370#endif
4371 return SQLITE_OK;
4372}
4373
4374/* writes the host id path to path, path should be an pre-allocated buffer
4375** with enough space for a path
4376*/
4377static void proxyGetHostIDPath(char *path, size_t len){
4378 strlcpy(path, HOSTIDPATH, len);
4379#ifdef SQLITE_TEST
4380 if( sqlite3_hostid_num>0 ){
4381 char suffix[2] = "1";
4382 suffix[0] = suffix[0] + sqlite3_hostid_num;
4383 strlcat(path, suffix, len);
4384 }
4385#endif
4386 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
4387}
4388
4389/* get the host ID from a sqlite hostid file stored in the
4390** user-specific tmp directory, create the ID if it's not there already
4391*/
4392static int proxyGetHostID(char *pHostID, int *pError){
4393 int fd;
4394 char path[MAXPATHLEN];
4395 size_t len;
4396 int rc=SQLITE_OK;
4397
4398 proxyGetHostIDPath(path, MAXPATHLEN);
4399 /* try to create the host ID file, if it already exists read the contents */
4400 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
4401 if( fd<0 ){
4402 int err=errno;
4403
4404 if( err!=EEXIST ){
4405#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4406 fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
4407 path, strerror(err));
4408#endif
4409 return SQLITE_PERM;
4410 }
4411 /* couldn't create the file, read it instead */
4412 fd = open(path, O_RDONLY|O_EXCL);
4413 if( fd<0 ){
4414#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4415 int err = errno;
4416 fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
4417 path, strerror(err));
4418#endif
4419 return SQLITE_PERM;
4420 }
4421 len = pread(fd, pHostID, HOSTIDLEN, 0);
4422 if( len<0 ){
4423 *pError = errno;
4424 rc = SQLITE_IOERR_READ;
4425 }else if( len<HOSTIDLEN ){
4426 *pError = 0;
4427 rc = SQLITE_IOERR_SHORT_READ;
4428 }
4429 close(fd); /* silently leak the fd if it fails */
4430 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
4431 return rc;
4432 }else{
4433 /* we're creating the host ID file (use a random string of bytes) */
4434 proxyGenerateHostID(pHostID);
4435 len = pwrite(fd, pHostID, HOSTIDLEN, 0);
4436 if( len<0 ){
4437 *pError = errno;
4438 rc = SQLITE_IOERR_WRITE;
4439 }else if( len<HOSTIDLEN ){
4440 *pError = 0;
4441 rc = SQLITE_IOERR_WRITE;
4442 }
4443 close(fd); /* silently leak the fd if it fails */
4444 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
4445 return rc;
4446 }
4447}
4448
4449static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4450 int len;
4451 int dbLen;
4452 int i;
4453
4454#ifdef LOCKPROXYDIR
4455 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4456#else
4457# ifdef _CS_DARWIN_USER_TEMP_DIR
4458 {
4459 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
4460 len = strlcat(lPath, "sqliteplocks", maxLen);
4461 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4462 /* if mkdir fails, handle as lock file creation failure */
drh715ff302008-12-03 22:32:44 +00004463# ifdef SQLITE_DEBUG
danielk197750c55a92009-05-08 11:34:37 +00004464 int err = errno;
drh715ff302008-12-03 22:32:44 +00004465 if( err!=EEXIST ){
4466 fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
4467 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
4468 }
4469# endif
4470 }else{
4471 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
4472 }
4473
4474 }
4475# else
4476 len = strlcpy(lPath, "/tmp/", maxLen);
4477# endif
4478#endif
4479
4480 if( lPath[len-1]!='/' ){
4481 len = strlcat(lPath, "/", maxLen);
4482 }
4483
4484 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004485 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004486 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4487 char c = dbPath[i];
4488 lPath[i+len] = (c=='/')?'_':c;
4489 }
4490 lPath[i+len]='\0';
4491 strlcat(lPath, ":auto:", maxLen);
4492 return SQLITE_OK;
4493}
4494
4495/*
4496** Create a new VFS file descriptor (stored in memory obtained from
4497** sqlite3_malloc) and open the file named "path" in the file descriptor.
4498**
4499** The caller is responsible not only for closing the file descriptor
4500** but also for freeing the memory associated with the file descriptor.
4501*/
4502static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
4503 int fd;
4504 int dirfd = -1;
4505 unixFile *pNew;
4506 int rc = SQLITE_OK;
4507 sqlite3_vfs dummyVfs;
4508
4509 fd = open(path, O_RDWR | O_CREAT, SQLITE_DEFAULT_FILE_PERMISSIONS);
4510 if( fd<0 ){
4511 return SQLITE_CANTOPEN;
4512 }
4513
4514 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
4515 if( pNew==NULL ){
4516 rc = SQLITE_NOMEM;
4517 goto end_create_proxy;
4518 }
4519 memset(pNew, 0, sizeof(unixFile));
4520
drh1875f7a2008-12-08 18:19:17 +00004521 dummyVfs.pAppData = (void*)&autolockIoFinder;
drh715ff302008-12-03 22:32:44 +00004522 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
4523 if( rc==SQLITE_OK ){
4524 *ppFile = pNew;
4525 return SQLITE_OK;
4526 }
4527end_create_proxy:
4528 close(fd); /* silently leak fd if error, we're already in error */
4529 sqlite3_free(pNew);
4530 return rc;
4531}
4532
4533/* takes the conch by taking a shared lock and read the contents conch, if
4534** lockPath is non-NULL, the host ID and lock file path must match. A NULL
4535** lockPath means that the lockPath in the conch file will be used if the
4536** host IDs match, or a new lock path will be generated automatically
4537** and written to the conch file.
4538*/
4539static int proxyTakeConch(unixFile *pFile){
4540 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4541
4542 if( pCtx->conchHeld>0 ){
4543 return SQLITE_OK;
4544 }else{
4545 unixFile *conchFile = pCtx->conchFile;
4546 char testValue[CONCHLEN];
4547 char conchValue[CONCHLEN];
4548 char lockPath[MAXPATHLEN];
4549 char *tLockPath = NULL;
4550 int rc = SQLITE_OK;
4551 int readRc = SQLITE_OK;
4552 int syncPerms = 0;
4553
4554 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
4555 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
4556
4557 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
4558 if( rc==SQLITE_OK ){
4559 int pError = 0;
drh1875f7a2008-12-08 18:19:17 +00004560 memset(testValue, 0, CONCHLEN); /* conch is fixed size */
drh715ff302008-12-03 22:32:44 +00004561 rc = proxyGetHostID(testValue, &pError);
4562 if( (rc&0xff)==SQLITE_IOERR ){
4563 pFile->lastErrno = pError;
4564 }
4565 if( pCtx->lockProxyPath ){
4566 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
4567 }
4568 }
4569 if( rc!=SQLITE_OK ){
4570 goto end_takeconch;
4571 }
4572
4573 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
4574 if( readRc!=SQLITE_IOERR_SHORT_READ ){
4575 if( readRc!=SQLITE_OK ){
4576 if( (rc&0xff)==SQLITE_IOERR ){
4577 pFile->lastErrno = conchFile->lastErrno;
4578 }
4579 rc = readRc;
4580 goto end_takeconch;
4581 }
4582 /* if the conch has data compare the contents */
4583 if( !pCtx->lockProxyPath ){
4584 /* for auto-named local lock file, just check the host ID and we'll
4585 ** use the local lock file path that's already in there */
4586 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
4587 tLockPath = (char *)&conchValue[HOSTIDLEN];
4588 goto end_takeconch;
4589 }
4590 }else{
4591 /* we've got the conch if conchValue matches our path and host ID */
4592 if( !memcmp(testValue, conchValue, CONCHLEN) ){
4593 goto end_takeconch;
4594 }
4595 }
4596 }else{
4597 /* a short read means we're "creating" the conch (even though it could
4598 ** have been user-intervention), if we acquire the exclusive lock,
4599 ** we'll try to match the current on-disk permissions of the database
4600 */
4601 syncPerms = 1;
4602 }
4603
4604 /* either conch was emtpy or didn't match */
4605 if( !pCtx->lockProxyPath ){
4606 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
4607 tLockPath = lockPath;
4608 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
4609 }
4610
4611 /* update conch with host and path (this will fail if other process
4612 ** has a shared lock already) */
4613 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
4614 if( rc==SQLITE_OK ){
4615 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
4616 if( rc==SQLITE_OK && syncPerms ){
4617 struct stat buf;
4618 int err = fstat(pFile->h, &buf);
4619 if( err==0 ){
4620 /* try to match the database file permissions, ignore failure */
4621#ifndef SQLITE_PROXY_DEBUG
4622 fchmod(conchFile->h, buf.st_mode);
4623#else
4624 if( fchmod(conchFile->h, buf.st_mode)!=0 ){
4625 int code = errno;
4626 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
4627 buf.st_mode, code, strerror(code));
4628 } else {
4629 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
4630 }
4631 }else{
4632 int code = errno;
4633 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
4634 err, code, strerror(code));
4635#endif
4636 }
4637 }
4638 }
4639 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
4640
4641end_takeconch:
4642 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
4643 if( rc==SQLITE_OK && pFile->openFlags ){
4644 if( pFile->h>=0 ){
4645#ifdef STRICT_CLOSE_ERROR
4646 if( close(pFile->h) ){
4647 pFile->lastErrno = errno;
4648 return SQLITE_IOERR_CLOSE;
4649 }
4650#else
4651 close(pFile->h); /* silently leak fd if fail */
4652#endif
4653 }
4654 pFile->h = -1;
4655 int fd = open(pCtx->dbPath, pFile->openFlags,
4656 SQLITE_DEFAULT_FILE_PERMISSIONS);
4657 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
4658 if( fd>=0 ){
4659 pFile->h = fd;
4660 }else{
drh1875f7a2008-12-08 18:19:17 +00004661 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
4662 during locking */
drh715ff302008-12-03 22:32:44 +00004663 }
4664 }
4665 if( rc==SQLITE_OK && !pCtx->lockProxy ){
4666 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
drh1875f7a2008-12-08 18:19:17 +00004667 /* ACS: Need to make a copy of path sometimes */
drh715ff302008-12-03 22:32:44 +00004668 rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
4669 }
4670 if( rc==SQLITE_OK ){
4671 pCtx->conchHeld = 1;
4672
4673 if( tLockPath ){
4674 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
4675 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
4676 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
4677 pCtx->lockProxyPath;
4678 }
4679 }
4680 } else {
4681 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4682 }
4683 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
4684 return rc;
4685 }
4686}
4687
4688/*
4689** If pFile holds a lock on a conch file, then release that lock.
4690*/
4691static int proxyReleaseConch(unixFile *pFile){
4692 int rc; /* Subroutine return code */
4693 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
4694 unixFile *conchFile; /* Name of the conch file */
4695
4696 pCtx = (proxyLockingContext *)pFile->lockingContext;
4697 conchFile = pCtx->conchFile;
4698 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
4699 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
4700 getpid());
4701 pCtx->conchHeld = 0;
4702 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4703 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
4704 (rc==SQLITE_OK ? "ok" : "failed"));
4705 return rc;
4706}
4707
4708/*
4709** Given the name of a database file, compute the name of its conch file.
4710** Store the conch filename in memory obtained from sqlite3_malloc().
4711** Make *pConchPath point to the new name. Return SQLITE_OK on success
4712** or SQLITE_NOMEM if unable to obtain memory.
4713**
4714** The caller is responsible for ensuring that the allocated memory
4715** space is eventually freed.
4716**
4717** *pConchPath is set to NULL if a memory allocation error occurs.
4718*/
4719static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
4720 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00004721 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00004722 char *conchPath; /* buffer in which to construct conch name */
4723
4724 /* Allocate space for the conch filename and initialize the name to
4725 ** the name of the original database file. */
4726 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
4727 if( conchPath==0 ){
4728 return SQLITE_NOMEM;
4729 }
4730 memcpy(conchPath, dbPath, len+1);
4731
4732 /* now insert a "." before the last / character */
4733 for( i=(len-1); i>=0; i-- ){
4734 if( conchPath[i]=='/' ){
4735 i++;
4736 break;
4737 }
4738 }
4739 conchPath[i]='.';
4740 while ( i<len ){
4741 conchPath[i+1]=dbPath[i];
4742 i++;
4743 }
4744
4745 /* append the "-conch" suffix to the file */
4746 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00004747 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00004748
4749 return SQLITE_OK;
4750}
4751
4752
4753/* Takes a fully configured proxy locking-style unix file and switches
4754** the local lock file path
4755*/
4756static int switchLockProxyPath(unixFile *pFile, const char *path) {
4757 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4758 char *oldPath = pCtx->lockProxyPath;
4759 int rc = SQLITE_OK;
4760
4761 if( pFile->locktype!=NO_LOCK ){
4762 return SQLITE_BUSY;
4763 }
4764
4765 /* nothing to do if the path is NULL, :auto: or matches the existing path */
4766 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
4767 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
4768 return SQLITE_OK;
4769 }else{
4770 unixFile *lockProxy = pCtx->lockProxy;
4771 pCtx->lockProxy=NULL;
4772 pCtx->conchHeld = 0;
4773 if( lockProxy!=NULL ){
4774 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
4775 if( rc ) return rc;
4776 sqlite3_free(lockProxy);
4777 }
4778 sqlite3_free(oldPath);
4779 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
4780 }
4781
4782 return rc;
4783}
4784
4785/*
4786** pFile is a file that has been opened by a prior xOpen call. dbPath
4787** is a string buffer at least MAXPATHLEN+1 characters in size.
4788**
4789** This routine find the filename associated with pFile and writes it
4790** int dbPath.
4791*/
4792static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00004793#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00004794 if( pFile->pMethod == &afpIoMethods ){
4795 /* afp style keeps a reference to the db path in the filePath field
4796 ** of the struct */
drhea678832008-12-10 19:26:22 +00004797 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh715ff302008-12-03 22:32:44 +00004798 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
4799 }else
4800#endif
4801 if( pFile->pMethod == &dotlockIoMethods ){
4802 /* dot lock style uses the locking context to store the dot lock
4803 ** file path */
4804 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
4805 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
4806 }else{
4807 /* all other styles use the locking context to store the db file path */
4808 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
4809 strcpy(dbPath, (char *)pFile->lockingContext);
4810 }
4811 return SQLITE_OK;
4812}
4813
4814/*
4815** Takes an already filled in unix file and alters it so all file locking
4816** will be performed on the local proxy lock file. The following fields
4817** are preserved in the locking context so that they can be restored and
4818** the unix structure properly cleaned up at close time:
4819** ->lockingContext
4820** ->pMethod
4821*/
4822static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
4823 proxyLockingContext *pCtx;
4824 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
4825 char *lockPath=NULL;
4826 int rc = SQLITE_OK;
4827
4828 if( pFile->locktype!=NO_LOCK ){
4829 return SQLITE_BUSY;
4830 }
4831 proxyGetDbPathForUnixFile(pFile, dbPath);
4832 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
4833 lockPath=NULL;
4834 }else{
4835 lockPath=(char *)path;
4836 }
4837
4838 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
4839 (lockPath ? lockPath : ":auto:"), getpid());
4840
4841 pCtx = sqlite3_malloc( sizeof(*pCtx) );
4842 if( pCtx==0 ){
4843 return SQLITE_NOMEM;
4844 }
4845 memset(pCtx, 0, sizeof(*pCtx));
4846
4847 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
4848 if( rc==SQLITE_OK ){
4849 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
4850 }
4851 if( rc==SQLITE_OK && lockPath ){
4852 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
4853 }
4854
4855 if( rc==SQLITE_OK ){
4856 /* all memory is allocated, proxys are created and assigned,
4857 ** switch the locking context and pMethod then return.
4858 */
4859 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
4860 pCtx->oldLockingContext = pFile->lockingContext;
4861 pFile->lockingContext = pCtx;
4862 pCtx->pOldMethod = pFile->pMethod;
4863 pFile->pMethod = &proxyIoMethods;
4864 }else{
4865 if( pCtx->conchFile ){
4866 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
4867 if( rc ) return rc;
4868 sqlite3_free(pCtx->conchFile);
4869 }
4870 sqlite3_free(pCtx->conchFilePath);
4871 sqlite3_free(pCtx);
4872 }
4873 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
4874 (rc==SQLITE_OK ? "ok" : "failed"));
4875 return rc;
4876}
4877
4878
4879/*
4880** This routine handles sqlite3_file_control() calls that are specific
4881** to proxy locking.
4882*/
4883static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
4884 switch( op ){
4885 case SQLITE_GET_LOCKPROXYFILE: {
4886 unixFile *pFile = (unixFile*)id;
4887 if( pFile->pMethod == &proxyIoMethods ){
4888 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4889 proxyTakeConch(pFile);
4890 if( pCtx->lockProxyPath ){
4891 *(const char **)pArg = pCtx->lockProxyPath;
4892 }else{
4893 *(const char **)pArg = ":auto: (not held)";
4894 }
4895 } else {
4896 *(const char **)pArg = NULL;
4897 }
4898 return SQLITE_OK;
4899 }
4900 case SQLITE_SET_LOCKPROXYFILE: {
4901 unixFile *pFile = (unixFile*)id;
4902 int rc = SQLITE_OK;
4903 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
4904 if( pArg==NULL || (const char *)pArg==0 ){
4905 if( isProxyStyle ){
4906 /* turn off proxy locking - not supported */
4907 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
4908 }else{
4909 /* turn off proxy locking - already off - NOOP */
4910 rc = SQLITE_OK;
4911 }
4912 }else{
4913 const char *proxyPath = (const char *)pArg;
4914 if( isProxyStyle ){
4915 proxyLockingContext *pCtx =
4916 (proxyLockingContext*)pFile->lockingContext;
4917 if( !strcmp(pArg, ":auto:")
4918 || (pCtx->lockProxyPath &&
4919 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
4920 ){
4921 rc = SQLITE_OK;
4922 }else{
4923 rc = switchLockProxyPath(pFile, proxyPath);
4924 }
4925 }else{
4926 /* turn on proxy file locking */
4927 rc = proxyTransformUnixFile(pFile, proxyPath);
4928 }
4929 }
4930 return rc;
4931 }
4932 default: {
4933 assert( 0 ); /* The call assures that only valid opcodes are sent */
4934 }
4935 }
4936 /*NOTREACHED*/
4937 return SQLITE_ERROR;
4938}
4939
4940/*
4941** Within this division (the proxying locking implementation) the procedures
4942** above this point are all utilities. The lock-related methods of the
4943** proxy-locking sqlite3_io_method object follow.
4944*/
4945
4946
4947/*
4948** This routine checks if there is a RESERVED lock held on the specified
4949** file by this or any other process. If such a lock is held, set *pResOut
4950** to a non-zero value otherwise *pResOut is set to zero. The return value
4951** is set to SQLITE_OK unless an I/O error occurs during lock checking.
4952*/
4953static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
4954 unixFile *pFile = (unixFile*)id;
4955 int rc = proxyTakeConch(pFile);
4956 if( rc==SQLITE_OK ){
4957 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4958 unixFile *proxy = pCtx->lockProxy;
4959 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
4960 }
4961 return rc;
4962}
4963
4964/*
4965** Lock the file with the lock specified by parameter locktype - one
4966** of the following:
4967**
4968** (1) SHARED_LOCK
4969** (2) RESERVED_LOCK
4970** (3) PENDING_LOCK
4971** (4) EXCLUSIVE_LOCK
4972**
4973** Sometimes when requesting one lock state, additional lock states
4974** are inserted in between. The locking might fail on one of the later
4975** transitions leaving the lock state different from what it started but
4976** still short of its goal. The following chart shows the allowed
4977** transitions and the inserted intermediate states:
4978**
4979** UNLOCKED -> SHARED
4980** SHARED -> RESERVED
4981** SHARED -> (PENDING) -> EXCLUSIVE
4982** RESERVED -> (PENDING) -> EXCLUSIVE
4983** PENDING -> EXCLUSIVE
4984**
4985** This routine will only increase a lock. Use the sqlite3OsUnlock()
4986** routine to lower a locking level.
4987*/
4988static int proxyLock(sqlite3_file *id, int locktype) {
4989 unixFile *pFile = (unixFile*)id;
4990 int rc = proxyTakeConch(pFile);
4991 if( rc==SQLITE_OK ){
4992 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4993 unixFile *proxy = pCtx->lockProxy;
4994 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
4995 pFile->locktype = proxy->locktype;
4996 }
4997 return rc;
4998}
4999
5000
5001/*
5002** Lower the locking level on file descriptor pFile to locktype. locktype
5003** must be either NO_LOCK or SHARED_LOCK.
5004**
5005** If the locking level of the file descriptor is already at or below
5006** the requested locking level, this routine is a no-op.
5007*/
5008static int proxyUnlock(sqlite3_file *id, int locktype) {
5009 unixFile *pFile = (unixFile*)id;
5010 int rc = proxyTakeConch(pFile);
5011 if( rc==SQLITE_OK ){
5012 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5013 unixFile *proxy = pCtx->lockProxy;
5014 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
5015 pFile->locktype = proxy->locktype;
5016 }
5017 return rc;
5018}
5019
5020/*
5021** Close a file that uses proxy locks.
5022*/
5023static int proxyClose(sqlite3_file *id) {
5024 if( id ){
5025 unixFile *pFile = (unixFile*)id;
5026 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5027 unixFile *lockProxy = pCtx->lockProxy;
5028 unixFile *conchFile = pCtx->conchFile;
5029 int rc = SQLITE_OK;
5030
5031 if( lockProxy ){
5032 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
5033 if( rc ) return rc;
5034 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
5035 if( rc ) return rc;
5036 sqlite3_free(lockProxy);
5037 pCtx->lockProxy = 0;
5038 }
5039 if( conchFile ){
5040 if( pCtx->conchHeld ){
5041 rc = proxyReleaseConch(pFile);
5042 if( rc ) return rc;
5043 }
5044 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
5045 if( rc ) return rc;
5046 sqlite3_free(conchFile);
5047 }
5048 sqlite3_free(pCtx->lockProxyPath);
5049 sqlite3_free(pCtx->conchFilePath);
5050 sqlite3_free(pCtx->dbPath);
5051 /* restore the original locking context and pMethod then close it */
5052 pFile->lockingContext = pCtx->oldLockingContext;
5053 pFile->pMethod = pCtx->pOldMethod;
5054 sqlite3_free(pCtx);
5055 return pFile->pMethod->xClose(id);
5056 }
5057 return SQLITE_OK;
5058}
5059
5060
5061
drhd2cb50b2009-01-09 21:41:17 +00005062#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00005063/*
5064** The proxy locking style is intended for use with AFP filesystems.
5065** And since AFP is only supported on MacOSX, the proxy locking is also
5066** restricted to MacOSX.
5067**
5068**
5069******************* End of the proxy lock implementation **********************
5070******************************************************************************/
5071
drh734c9862008-11-28 15:37:20 +00005072/*
danielk1977e339d652008-06-28 11:23:00 +00005073** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00005074**
5075** This routine registers all VFS implementations for unix-like operating
5076** systems. This routine, and the sqlite3_os_end() routine that follows,
5077** should be the only routines in this file that are visible from other
5078** files.
drh6b9d6dd2008-12-03 19:34:47 +00005079**
5080** This routine is called once during SQLite initialization and by a
5081** single thread. The memory allocation and mutex subsystems have not
5082** necessarily been initialized when this routine is called, and so they
5083** should not be used.
drh153c62c2007-08-24 03:51:33 +00005084*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005085int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00005086 /*
5087 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00005088 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
5089 ** to the "finder" function. (pAppData is a pointer to a pointer because
5090 ** silly C90 rules prohibit a void* from being cast to a function pointer
5091 ** and so we have to go through the intermediate pointer to avoid problems
5092 ** when compiling with -pedantic-errors on GCC.)
5093 **
5094 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00005095 ** finder-function. The finder-function returns a pointer to the
5096 ** sqlite_io_methods object that implements the desired locking
5097 ** behaviors. See the division above that contains the IOMETHODS
5098 ** macro for addition information on finder-functions.
5099 **
5100 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
5101 ** object. But the "autolockIoFinder" available on MacOSX does a little
5102 ** more than that; it looks at the filesystem type that hosts the
5103 ** database file and tries to choose an locking method appropriate for
5104 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00005105 */
drh7708e972008-11-29 00:56:52 +00005106 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00005107 1, /* iVersion */ \
5108 sizeof(unixFile), /* szOsFile */ \
5109 MAX_PATHNAME, /* mxPathname */ \
5110 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00005111 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00005112 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00005113 unixOpen, /* xOpen */ \
5114 unixDelete, /* xDelete */ \
5115 unixAccess, /* xAccess */ \
5116 unixFullPathname, /* xFullPathname */ \
5117 unixDlOpen, /* xDlOpen */ \
5118 unixDlError, /* xDlError */ \
5119 unixDlSym, /* xDlSym */ \
5120 unixDlClose, /* xDlClose */ \
5121 unixRandomness, /* xRandomness */ \
5122 unixSleep, /* xSleep */ \
5123 unixCurrentTime, /* xCurrentTime */ \
5124 unixGetLastError /* xGetLastError */ \
5125 }
5126
drh6b9d6dd2008-12-03 19:34:47 +00005127 /*
5128 ** All default VFSes for unix are contained in the following array.
5129 **
5130 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5131 ** by the SQLite core when the VFS is registered. So the following
5132 ** array cannot be const.
5133 */
danielk1977e339d652008-06-28 11:23:00 +00005134 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00005135#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00005136 UNIXVFS("unix", autolockIoFinder ),
5137#else
5138 UNIXVFS("unix", posixIoFinder ),
5139#endif
5140 UNIXVFS("unix-none", nolockIoFinder ),
5141 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005142#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005143 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005144#endif
5145#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005146 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00005147#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005148 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005149#endif
chw78a13182009-04-07 05:35:03 +00005150#endif
drhd2cb50b2009-01-09 21:41:17 +00005151#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005152 UNIXVFS("unix-afp", afpIoFinder ),
5153 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005154#endif
drh153c62c2007-08-24 03:51:33 +00005155 };
drh6b9d6dd2008-12-03 19:34:47 +00005156 unsigned int i; /* Loop counter */
5157
5158 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005159 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005160 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005161 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005162 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005163}
danielk1977e339d652008-06-28 11:23:00 +00005164
5165/*
drh6b9d6dd2008-12-03 19:34:47 +00005166** Shutdown the operating system interface.
5167**
5168** Some operating systems might need to do some cleanup in this routine,
5169** to release dynamically allocated objects. But not on unix.
5170** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005171*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005172int sqlite3_os_end(void){
5173 return SQLITE_OK;
5174}
drhdce8bdb2007-08-16 13:01:44 +00005175
danielk197729bafea2008-06-26 10:41:19 +00005176#endif /* SQLITE_OS_UNIX */