blob: 4dd451fedcfec54034bcf8c39ef9c2f2871a9be9 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
danielk1977e339d652008-06-28 11:23:00 +0000122
drh40bbb0a2008-09-23 10:23:26 +0000123#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000124# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000125# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000126# include <semaphore.h>
127# include <limits.h>
128# else
drh9b35ea62008-11-29 02:20:26 +0000129# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <sys/param.h>
131# include <sys/mount.h>
132# endif
drhbfe66312006-10-03 17:40:40 +0000133#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000134
135/*
drhf1a221e2006-01-15 17:27:17 +0000136** If we are to be thread-safe, include the pthreads header and define
137** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000138*/
drhd677b3d2007-08-20 22:48:41 +0000139#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000140# include <pthread.h>
141# define SQLITE_UNIX_THREADS 1
142#endif
143
144/*
145** Default permissions when creating a new file
146*/
147#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
148# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
149#endif
150
danielk1977b4b47412007-08-17 15:53:36 +0000151/*
aswiftaebf4132008-11-21 00:10:35 +0000152 ** Default permissions when creating auto proxy dir
153 */
154#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
155# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
156#endif
157
158/*
danielk1977b4b47412007-08-17 15:53:36 +0000159** Maximum supported path-length.
160*/
161#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000162
drh734c9862008-11-28 15:37:20 +0000163/*
drh734c9862008-11-28 15:37:20 +0000164** Only set the lastErrno if the error code is a real error and not
165** a normal expected return code of SQLITE_BUSY or SQLITE_OK
166*/
167#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
168
drh9cbe6352005-11-29 03:13:21 +0000169
170/*
dane946c392009-08-22 11:39:46 +0000171** Sometimes, after a file handle is closed by SQLite, the file descriptor
172** cannot be closed immediately. In these cases, instances of the following
173** structure are used to store the file descriptor while waiting for an
174** opportunity to either close or reuse it.
175*/
176typedef struct UnixUnusedFd UnixUnusedFd;
177struct UnixUnusedFd {
178 int fd; /* File descriptor to close */
179 int flags; /* Flags this file descriptor was opened with */
180 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
181};
182
183/*
drh9b35ea62008-11-29 02:20:26 +0000184** The unixFile structure is subclass of sqlite3_file specific to the unix
185** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000186*/
drh054889e2005-11-30 03:20:31 +0000187typedef struct unixFile unixFile;
188struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000189 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh6c7d5c52008-11-21 20:32:33 +0000190 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
191 struct unixLockInfo *pLock; /* Info about locks on this inode */
192 int h; /* The file descriptor */
193 int dirfd; /* File descriptor for the directory */
194 unsigned char locktype; /* The type of lock held on this fd */
195 int lastErrno; /* The unix errno from the last I/O error */
drh6c7d5c52008-11-21 20:32:33 +0000196 void *lockingContext; /* Locking style specific state */
dane946c392009-08-22 11:39:46 +0000197 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh0c2694b2009-09-03 16:23:44 +0000198 int fileFlags; /* Miscellanous flags */
drh08c6d442009-02-09 17:34:07 +0000199#if SQLITE_ENABLE_LOCKING_STYLE
200 int openFlags; /* The flags specified at open() */
201#endif
drh734c9862008-11-28 15:37:20 +0000202#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000203 pthread_t tid; /* The thread that "owns" this unixFile */
204#endif
205#if OS_VXWORKS
206 int isDelete; /* Delete on close if true */
drh107886a2008-11-21 22:21:50 +0000207 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000208#endif
drh8f941bc2009-01-14 23:03:40 +0000209#ifndef NDEBUG
210 /* The next group of variables are used to track whether or not the
211 ** transaction counter in bytes 24-27 of database files are updated
212 ** whenever any part of the database changes. An assertion fault will
213 ** occur if a file is updated without also updating the transaction
214 ** counter. This test is made to avoid new problems similar to the
215 ** one described by ticket #3584.
216 */
217 unsigned char transCntrChng; /* True if the transaction counter changed */
218 unsigned char dbUpdate; /* True if any part of database file changed */
219 unsigned char inNormalWrite; /* True if in a normal write operation */
220#endif
danielk1977967a4a12007-08-20 14:23:44 +0000221#ifdef SQLITE_TEST
222 /* In test mode, increase the size of this structure a bit so that
223 ** it is larger than the struct CrashFile defined in test6.c.
224 */
225 char aPadding[32];
226#endif
drh9cbe6352005-11-29 03:13:21 +0000227};
228
drh0ccebe72005-06-07 22:22:50 +0000229/*
drh0c2694b2009-09-03 16:23:44 +0000230** The following macros define bits in unixFile.fileFlags
231*/
232#define SQLITE_WHOLE_FILE_LOCKING 0x0001 /* Use whole-file locking */
233
234/*
drh198bf392006-01-06 21:52:49 +0000235** Include code that is common to all os_*.c files
236*/
237#include "os_common.h"
238
239/*
drh0ccebe72005-06-07 22:22:50 +0000240** Define various macros that are missing from some systems.
241*/
drhbbd42a62004-05-22 17:41:58 +0000242#ifndef O_LARGEFILE
243# define O_LARGEFILE 0
244#endif
245#ifdef SQLITE_DISABLE_LFS
246# undef O_LARGEFILE
247# define O_LARGEFILE 0
248#endif
249#ifndef O_NOFOLLOW
250# define O_NOFOLLOW 0
251#endif
252#ifndef O_BINARY
253# define O_BINARY 0
254#endif
255
256/*
257** The DJGPP compiler environment looks mostly like Unix, but it
258** lacks the fcntl() system call. So redefine fcntl() to be something
259** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000260** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000261*/
262#ifdef __DJGPP__
263# define fcntl(A,B,C) 0
264#endif
265
266/*
drh2b4b5962005-06-15 17:47:55 +0000267** The threadid macro resolves to the thread-id or to 0. Used for
268** testing and debugging only.
269*/
drhd677b3d2007-08-20 22:48:41 +0000270#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000271#define threadid pthread_self()
272#else
273#define threadid 0
274#endif
275
danielk197713adf8a2004-06-03 16:08:41 +0000276
drh107886a2008-11-21 22:21:50 +0000277/*
dan9359c7b2009-08-21 08:29:10 +0000278** Helper functions to obtain and relinquish the global mutex. The
279** global mutex is used to protect the unixOpenCnt, unixLockInfo and
280** vxworksFileId objects used by this file, all of which may be
281** shared by multiple threads.
282**
283** Function unixMutexHeld() is used to assert() that the global mutex
284** is held when required. This function is only used as part of assert()
285** statements. e.g.
286**
287** unixEnterMutex()
288** assert( unixMutexHeld() );
289** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000290*/
291static void unixEnterMutex(void){
292 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
293}
294static void unixLeaveMutex(void){
295 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
296}
dan9359c7b2009-08-21 08:29:10 +0000297#ifdef SQLITE_DEBUG
298static int unixMutexHeld(void) {
299 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
300}
301#endif
drh107886a2008-11-21 22:21:50 +0000302
drh734c9862008-11-28 15:37:20 +0000303
304#ifdef SQLITE_DEBUG
305/*
306** Helper function for printing out trace information from debugging
307** binaries. This returns the string represetation of the supplied
308** integer lock-type.
309*/
310static const char *locktypeName(int locktype){
311 switch( locktype ){
dan9359c7b2009-08-21 08:29:10 +0000312 case NO_LOCK: return "NONE";
313 case SHARED_LOCK: return "SHARED";
314 case RESERVED_LOCK: return "RESERVED";
315 case PENDING_LOCK: return "PENDING";
316 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000317 }
318 return "ERROR";
319}
320#endif
321
322#ifdef SQLITE_LOCK_TRACE
323/*
324** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000325**
drh734c9862008-11-28 15:37:20 +0000326** This routine is used for troubleshooting locks on multithreaded
327** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
328** command-line option on the compiler. This code is normally
329** turned off.
330*/
331static int lockTrace(int fd, int op, struct flock *p){
332 char *zOpName, *zType;
333 int s;
334 int savedErrno;
335 if( op==F_GETLK ){
336 zOpName = "GETLK";
337 }else if( op==F_SETLK ){
338 zOpName = "SETLK";
339 }else{
340 s = fcntl(fd, op, p);
341 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
342 return s;
343 }
344 if( p->l_type==F_RDLCK ){
345 zType = "RDLCK";
346 }else if( p->l_type==F_WRLCK ){
347 zType = "WRLCK";
348 }else if( p->l_type==F_UNLCK ){
349 zType = "UNLCK";
350 }else{
351 assert( 0 );
352 }
353 assert( p->l_whence==SEEK_SET );
354 s = fcntl(fd, op, p);
355 savedErrno = errno;
356 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
357 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
358 (int)p->l_pid, s);
359 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
360 struct flock l2;
361 l2 = *p;
362 fcntl(fd, F_GETLK, &l2);
363 if( l2.l_type==F_RDLCK ){
364 zType = "RDLCK";
365 }else if( l2.l_type==F_WRLCK ){
366 zType = "WRLCK";
367 }else if( l2.l_type==F_UNLCK ){
368 zType = "UNLCK";
369 }else{
370 assert( 0 );
371 }
372 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
373 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
374 }
375 errno = savedErrno;
376 return s;
377}
378#define fcntl lockTrace
379#endif /* SQLITE_LOCK_TRACE */
380
381
382
383/*
384** This routine translates a standard POSIX errno code into something
385** useful to the clients of the sqlite3 functions. Specifically, it is
386** intended to translate a variety of "try again" errors into SQLITE_BUSY
387** and a variety of "please close the file descriptor NOW" errors into
388** SQLITE_IOERR
389**
390** Errors during initialization of locks, or file system support for locks,
391** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
392*/
393static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
394 switch (posixError) {
395 case 0:
396 return SQLITE_OK;
397
398 case EAGAIN:
399 case ETIMEDOUT:
400 case EBUSY:
401 case EINTR:
402 case ENOLCK:
403 /* random NFS retry error, unless during file system support
404 * introspection, in which it actually means what it says */
405 return SQLITE_BUSY;
406
407 case EACCES:
408 /* EACCES is like EAGAIN during locking operations, but not any other time*/
409 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
410 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
411 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
412 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
413 return SQLITE_BUSY;
414 }
415 /* else fall through */
416 case EPERM:
417 return SQLITE_PERM;
418
419 case EDEADLK:
420 return SQLITE_IOERR_BLOCKED;
421
422#if EOPNOTSUPP!=ENOTSUP
423 case EOPNOTSUPP:
424 /* something went terribly awry, unless during file system support
425 * introspection, in which it actually means what it says */
426#endif
427#ifdef ENOTSUP
428 case ENOTSUP:
429 /* invalid fd, unless during file system support introspection, in which
430 * it actually means what it says */
431#endif
432 case EIO:
433 case EBADF:
434 case EINVAL:
435 case ENOTCONN:
436 case ENODEV:
437 case ENXIO:
438 case ENOENT:
439 case ESTALE:
440 case ENOSYS:
441 /* these should force the client to close the file and reconnect */
442
443 default:
444 return sqliteIOErr;
445 }
446}
447
448
449
450/******************************************************************************
451****************** Begin Unique File ID Utility Used By VxWorks ***************
452**
453** On most versions of unix, we can get a unique ID for a file by concatenating
454** the device number and the inode number. But this does not work on VxWorks.
455** On VxWorks, a unique file id must be based on the canonical filename.
456**
457** A pointer to an instance of the following structure can be used as a
458** unique file ID in VxWorks. Each instance of this structure contains
459** a copy of the canonical filename. There is also a reference count.
460** The structure is reclaimed when the number of pointers to it drops to
461** zero.
462**
463** There are never very many files open at one time and lookups are not
464** a performance-critical path, so it is sufficient to put these
465** structures on a linked list.
466*/
467struct vxworksFileId {
468 struct vxworksFileId *pNext; /* Next in a list of them all */
469 int nRef; /* Number of references to this one */
470 int nName; /* Length of the zCanonicalName[] string */
471 char *zCanonicalName; /* Canonical filename */
472};
473
474#if OS_VXWORKS
475/*
drh9b35ea62008-11-29 02:20:26 +0000476** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000477** variable:
478*/
479static struct vxworksFileId *vxworksFileList = 0;
480
481/*
482** Simplify a filename into its canonical form
483** by making the following changes:
484**
485** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000486** * convert /./ into just /
487** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000488**
489** Changes are made in-place. Return the new name length.
490**
491** The original filename is in z[0..n-1]. Return the number of
492** characters in the simplified name.
493*/
494static int vxworksSimplifyName(char *z, int n){
495 int i, j;
496 while( n>1 && z[n-1]=='/' ){ n--; }
497 for(i=j=0; i<n; i++){
498 if( z[i]=='/' ){
499 if( z[i+1]=='/' ) continue;
500 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
501 i += 1;
502 continue;
503 }
504 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
505 while( j>0 && z[j-1]!='/' ){ j--; }
506 if( j>0 ){ j--; }
507 i += 2;
508 continue;
509 }
510 }
511 z[j++] = z[i];
512 }
513 z[j] = 0;
514 return j;
515}
516
517/*
518** Find a unique file ID for the given absolute pathname. Return
519** a pointer to the vxworksFileId object. This pointer is the unique
520** file ID.
521**
522** The nRef field of the vxworksFileId object is incremented before
523** the object is returned. A new vxworksFileId object is created
524** and added to the global list if necessary.
525**
526** If a memory allocation error occurs, return NULL.
527*/
528static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
529 struct vxworksFileId *pNew; /* search key and new file ID */
530 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
531 int n; /* Length of zAbsoluteName string */
532
533 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000534 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000535 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
536 if( pNew==0 ) return 0;
537 pNew->zCanonicalName = (char*)&pNew[1];
538 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
539 n = vxworksSimplifyName(pNew->zCanonicalName, n);
540
541 /* Search for an existing entry that matching the canonical name.
542 ** If found, increment the reference count and return a pointer to
543 ** the existing file ID.
544 */
545 unixEnterMutex();
546 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
547 if( pCandidate->nName==n
548 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
549 ){
550 sqlite3_free(pNew);
551 pCandidate->nRef++;
552 unixLeaveMutex();
553 return pCandidate;
554 }
555 }
556
557 /* No match was found. We will make a new file ID */
558 pNew->nRef = 1;
559 pNew->nName = n;
560 pNew->pNext = vxworksFileList;
561 vxworksFileList = pNew;
562 unixLeaveMutex();
563 return pNew;
564}
565
566/*
567** Decrement the reference count on a vxworksFileId object. Free
568** the object when the reference count reaches zero.
569*/
570static void vxworksReleaseFileId(struct vxworksFileId *pId){
571 unixEnterMutex();
572 assert( pId->nRef>0 );
573 pId->nRef--;
574 if( pId->nRef==0 ){
575 struct vxworksFileId **pp;
576 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
577 assert( *pp==pId );
578 *pp = pId->pNext;
579 sqlite3_free(pId);
580 }
581 unixLeaveMutex();
582}
583#endif /* OS_VXWORKS */
584/*************** End of Unique File ID Utility Used By VxWorks ****************
585******************************************************************************/
586
587
588/******************************************************************************
589*************************** Posix Advisory Locking ****************************
590**
drh9b35ea62008-11-29 02:20:26 +0000591** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000592** section 6.5.2.2 lines 483 through 490 specify that when a process
593** sets or clears a lock, that operation overrides any prior locks set
594** by the same process. It does not explicitly say so, but this implies
595** that it overrides locks set by the same process using a different
596** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000597**
598** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000599** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
600**
601** Suppose ./file1 and ./file2 are really the same file (because
602** one is a hard or symbolic link to the other) then if you set
603** an exclusive lock on fd1, then try to get an exclusive lock
604** on fd2, it works. I would have expected the second lock to
605** fail since there was already a lock on the file due to fd1.
606** But not so. Since both locks came from the same process, the
607** second overrides the first, even though they were on different
608** file descriptors opened on different file names.
609**
drh734c9862008-11-28 15:37:20 +0000610** This means that we cannot use POSIX locks to synchronize file access
611** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000612** to synchronize access for threads in separate processes, but not
613** threads within the same process.
614**
615** To work around the problem, SQLite has to manage file locks internally
616** on its own. Whenever a new database is opened, we have to find the
617** specific inode of the database file (the inode is determined by the
618** st_dev and st_ino fields of the stat structure that fstat() fills in)
619** and check for locks already existing on that inode. When locks are
620** created or removed, we have to look at our own internal record of the
621** locks to see if another thread has previously set a lock on that same
622** inode.
623**
drh9b35ea62008-11-29 02:20:26 +0000624** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
625** For VxWorks, we have to use the alternative unique ID system based on
626** canonical filename and implemented in the previous division.)
627**
danielk1977ad94b582007-08-20 06:44:22 +0000628** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000629** descriptor. It is now a structure that holds the integer file
630** descriptor and a pointer to a structure that describes the internal
631** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000632** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000633** point to the same locking structure. The locking structure keeps
634** a reference count (so we will know when to delete it) and a "cnt"
635** field that tells us its internal lock status. cnt==0 means the
636** file is unlocked. cnt==-1 means the file has an exclusive lock.
637** cnt>0 means there are cnt shared locks on the file.
638**
639** Any attempt to lock or unlock a file first checks the locking
640** structure. The fcntl() system call is only invoked to set a
641** POSIX lock if the internal lock structure transitions between
642** a locked and an unlocked state.
643**
drh734c9862008-11-28 15:37:20 +0000644** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000645**
646** If you close a file descriptor that points to a file that has locks,
647** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000648** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000649** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000650** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000651** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000652** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000653** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000654** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000655** be closed and that list is walked (and cleared) when the last lock
656** clears.
657**
drh9b35ea62008-11-29 02:20:26 +0000658** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000659**
drh9b35ea62008-11-29 02:20:26 +0000660** Many older versions of linux use the LinuxThreads library which is
661** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000662** A cannot be modified or overridden by a different thread B.
663** Only thread A can modify the lock. Locking behavior is correct
664** if the appliation uses the newer Native Posix Thread Library (NPTL)
665** on linux - with NPTL a lock created by thread A can override locks
666** in thread B. But there is no way to know at compile-time which
667** threading library is being used. So there is no way to know at
668** compile-time whether or not thread A can override locks on thread B.
669** We have to do a run-time check to discover the behavior of the
670** current process.
drh5fdae772004-06-29 03:29:00 +0000671**
drh734c9862008-11-28 15:37:20 +0000672** On systems where thread A is unable to modify locks created by
673** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000674** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000675** structure to record this information. And on those systems it
676** is illegal to begin a transaction in one thread and finish it
677** in another. For this latter restriction, there is no work-around.
678** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000679*/
680
681/*
drh6c7d5c52008-11-21 20:32:33 +0000682** Set or check the unixFile.tid field. This field is set when an unixFile
683** is first opened. All subsequent uses of the unixFile verify that the
684** same thread is operating on the unixFile. Some operating systems do
685** not allow locks to be overridden by other threads and that restriction
686** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000687** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000688**
689** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
690** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000691** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000692** or if no locks are held. But the unixFile.pLock field needs to be
693** recomputed because its key includes the thread-id. See the
694** transferOwnership() function below for additional information
695*/
drh734c9862008-11-28 15:37:20 +0000696#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000697# define SET_THREADID(X) (X)->tid = pthread_self()
698# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
699 !pthread_equal((X)->tid, pthread_self()))
700#else
701# define SET_THREADID(X)
702# define CHECK_THREADID(X) 0
703#endif
704
705/*
drhbbd42a62004-05-22 17:41:58 +0000706** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000707** to locate a particular unixOpenCnt structure given its inode. This
708** is the same as the unixLockKey except that the thread ID is omitted.
709*/
710struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000711 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000712#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000713 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000714#else
drh107886a2008-11-21 22:21:50 +0000715 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000716#endif
717};
718
719/*
720** An instance of the following structure serves as the key used
721** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000722**
drh734c9862008-11-28 15:37:20 +0000723** If threads cannot override each others locks (LinuxThreads), then we
724** set the unixLockKey.tid field to the thread ID. If threads can override
725** each others locks (Posix and NPTL) then tid is always set to zero.
726** tid is omitted if we compile without threading support or on an OS
727** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000728*/
drh6c7d5c52008-11-21 20:32:33 +0000729struct unixLockKey {
730 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000731#if SQLITE_THREADSAFE && defined(__linux__)
732 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000733#endif
drhbbd42a62004-05-22 17:41:58 +0000734};
735
736/*
737** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000738** inode. Or, on LinuxThreads, there is one of these structures for
739** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000740**
danielk1977ad94b582007-08-20 06:44:22 +0000741** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000742** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000743** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000744*/
drh6c7d5c52008-11-21 20:32:33 +0000745struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000746 struct unixLockKey lockKey; /* The lookup key */
747 int cnt; /* Number of SHARED locks held */
748 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
749 int nRef; /* Number of pointers to this structure */
750 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
751 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000752};
753
754/*
755** An instance of the following structure is allocated for each open
756** inode. This structure keeps track of the number of locks on that
757** inode. If a close is attempted against an inode that is holding
758** locks, the close is deferred until all locks clear by adding the
759** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000760**
761** TODO: Consider changing this so that there is only a single file
762** descriptor for each open file, even when it is opened multiple times.
763** The close() system call would only occur when the last database
764** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000765*/
drh6c7d5c52008-11-21 20:32:33 +0000766struct unixOpenCnt {
767 struct unixFileId fileId; /* The lookup key */
768 int nRef; /* Number of pointers to this structure */
769 int nLock; /* Number of outstanding locks */
dane946c392009-08-22 11:39:46 +0000770 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh6c7d5c52008-11-21 20:32:33 +0000771#if OS_VXWORKS
772 sem_t *pSem; /* Named POSIX semaphore */
drh2238dcc2009-08-27 17:56:20 +0000773 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000774#endif
drh6c7d5c52008-11-21 20:32:33 +0000775 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000776};
777
drhda0e7682008-07-30 15:27:54 +0000778/*
drh9b35ea62008-11-29 02:20:26 +0000779** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
780** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000781** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000782** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000783*/
drh6c7d5c52008-11-21 20:32:33 +0000784static struct unixLockInfo *lockList = 0;
785static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000786
drh5fdae772004-06-29 03:29:00 +0000787/*
drh9b35ea62008-11-29 02:20:26 +0000788** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000789** locks.
790**
drh9b35ea62008-11-29 02:20:26 +0000791** 0: No. Threads cannot override each others locks. (LinuxThreads)
792** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000793** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000794**
drh5062d3a2006-01-31 23:03:35 +0000795** On some systems, we know at compile-time if threads can override each
796** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
797** will be set appropriately. On other systems, we have to check at
798** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
799** undefined.
800**
drhf1a221e2006-01-15 17:27:17 +0000801** This variable normally has file scope only. But during testing, we make
802** it a global so that the test code can change its value in order to verify
803** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000804*/
drh715ff302008-12-03 22:32:44 +0000805#if SQLITE_THREADSAFE && defined(__linux__)
806# ifndef SQLITE_THREAD_OVERRIDE_LOCK
807# define SQLITE_THREAD_OVERRIDE_LOCK -1
808# endif
809# ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000810int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000811# else
drh5062d3a2006-01-31 23:03:35 +0000812static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh715ff302008-12-03 22:32:44 +0000813# endif
drh029b44b2006-01-15 00:13:15 +0000814#endif
drh5fdae772004-06-29 03:29:00 +0000815
816/*
817** This structure holds information passed into individual test
818** threads by the testThreadLockingBehavior() routine.
819*/
820struct threadTestData {
821 int fd; /* File to be locked */
822 struct flock lock; /* The locking operation */
823 int result; /* Result of the locking operation */
824};
825
drh6c7d5c52008-11-21 20:32:33 +0000826#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000827/*
danielk197741a6a612008-11-11 18:34:35 +0000828** This function is used as the main routine for a thread launched by
829** testThreadLockingBehavior(). It tests whether the shared-lock obtained
830** by the main thread in testThreadLockingBehavior() conflicts with a
831** hypothetical write-lock obtained by this thread on the same file.
832**
833** The write-lock is not actually acquired, as this is not possible if
834** the file is open in read-only mode (see ticket #3472).
835*/
drh5fdae772004-06-29 03:29:00 +0000836static void *threadLockingTest(void *pArg){
837 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000838 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000839 return pArg;
840}
drh6c7d5c52008-11-21 20:32:33 +0000841#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000842
drh6c7d5c52008-11-21 20:32:33 +0000843
844#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000845/*
846** This procedure attempts to determine whether or not threads
847** can override each others locks then sets the
848** threadsOverrideEachOthersLocks variable appropriately.
849*/
danielk19774d5238f2006-01-27 06:32:00 +0000850static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000851 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000852 int rc;
853 struct threadTestData d;
854 struct flock l;
855 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000856
857 fd = dup(fd_orig);
858 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000859 memset(&l, 0, sizeof(l));
860 l.l_type = F_RDLCK;
861 l.l_len = 1;
862 l.l_start = 0;
863 l.l_whence = SEEK_SET;
864 rc = fcntl(fd_orig, F_SETLK, &l);
865 if( rc!=0 ) return;
866 memset(&d, 0, sizeof(d));
867 d.fd = fd;
868 d.lock = l;
869 d.lock.l_type = F_WRLCK;
drh06150f92009-07-03 12:57:58 +0000870 if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
871 pthread_join(t, 0);
872 }
drh5fdae772004-06-29 03:29:00 +0000873 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000874 if( d.result!=0 ) return;
875 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000876}
drh06150f92009-07-03 12:57:58 +0000877#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000878
drhbbd42a62004-05-22 17:41:58 +0000879/*
drh6c7d5c52008-11-21 20:32:33 +0000880** Release a unixLockInfo structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000881**
882** The mutex entered using the unixEnterMutex() function must be held
883** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +0000884*/
885static void releaseLockInfo(struct unixLockInfo *pLock){
dan9359c7b2009-08-21 08:29:10 +0000886 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000887 if( pLock ){
888 pLock->nRef--;
889 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000890 if( pLock->pPrev ){
891 assert( pLock->pPrev->pNext==pLock );
892 pLock->pPrev->pNext = pLock->pNext;
893 }else{
894 assert( lockList==pLock );
895 lockList = pLock->pNext;
896 }
897 if( pLock->pNext ){
898 assert( pLock->pNext->pPrev==pLock );
899 pLock->pNext->pPrev = pLock->pPrev;
900 }
danielk1977e339d652008-06-28 11:23:00 +0000901 sqlite3_free(pLock);
902 }
drhbbd42a62004-05-22 17:41:58 +0000903 }
904}
905
906/*
drh6c7d5c52008-11-21 20:32:33 +0000907** Release a unixOpenCnt structure previously allocated by findLockInfo().
dan9359c7b2009-08-21 08:29:10 +0000908**
909** The mutex entered using the unixEnterMutex() function must be held
910** when this function is called.
drhbbd42a62004-05-22 17:41:58 +0000911*/
drh6c7d5c52008-11-21 20:32:33 +0000912static void releaseOpenCnt(struct unixOpenCnt *pOpen){
dan9359c7b2009-08-21 08:29:10 +0000913 assert( unixMutexHeld() );
danielk1977e339d652008-06-28 11:23:00 +0000914 if( pOpen ){
915 pOpen->nRef--;
916 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000917 if( pOpen->pPrev ){
918 assert( pOpen->pPrev->pNext==pOpen );
919 pOpen->pPrev->pNext = pOpen->pNext;
920 }else{
921 assert( openList==pOpen );
922 openList = pOpen->pNext;
923 }
924 if( pOpen->pNext ){
925 assert( pOpen->pNext->pPrev==pOpen );
926 pOpen->pNext->pPrev = pOpen->pPrev;
927 }
drh08da4bb2009-09-10 19:20:03 +0000928#if SQLITE_THREADSAFE && defined(__linux__)
dan11b38792009-09-09 18:46:52 +0000929 assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
drh08da4bb2009-09-10 19:20:03 +0000930#endif
dan11b38792009-09-09 18:46:52 +0000931
932 /* If pOpen->pUnused is not null, then memory and file-descriptors
933 ** are leaked.
934 **
935 ** This will only happen if, under Linuxthreads, the user has opened
936 ** a transaction in one thread, then attempts to close the database
937 ** handle from another thread (without first unlocking the db file).
938 ** This is a misuse. */
danielk1977e339d652008-06-28 11:23:00 +0000939 sqlite3_free(pOpen);
940 }
drhbbd42a62004-05-22 17:41:58 +0000941 }
942}
943
drh6c7d5c52008-11-21 20:32:33 +0000944/*
945** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
946** describes that file descriptor. Create new ones if necessary. The
947** return values might be uninitialized if an error occurs.
948**
dan9359c7b2009-08-21 08:29:10 +0000949** The mutex entered using the unixEnterMutex() function must be held
950** when this function is called.
951**
drh6c7d5c52008-11-21 20:32:33 +0000952** Return an appropriate error code.
953*/
954static int findLockInfo(
955 unixFile *pFile, /* Unix file with file desc used in the key */
956 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
957 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
958){
959 int rc; /* System call return code */
960 int fd; /* The file descriptor for pFile */
961 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
962 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
963 struct stat statbuf; /* Low-level file information */
drh0d588bb2009-06-17 13:09:38 +0000964 struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
drh6c7d5c52008-11-21 20:32:33 +0000965 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
966
dan9359c7b2009-08-21 08:29:10 +0000967 assert( unixMutexHeld() );
968
drh6c7d5c52008-11-21 20:32:33 +0000969 /* Get low-level information about the file that we can used to
970 ** create a unique name for the file.
971 */
972 fd = pFile->h;
973 rc = fstat(fd, &statbuf);
974 if( rc!=0 ){
975 pFile->lastErrno = errno;
976#ifdef EOVERFLOW
977 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
978#endif
979 return SQLITE_IOERR;
980 }
981
drheb0d74f2009-02-03 15:27:02 +0000982#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +0000983 /* On OS X on an msdos filesystem, the inode number is reported
984 ** incorrectly for zero-size files. See ticket #3260. To work
985 ** around this problem (we consider it a bug in OS X, not SQLite)
986 ** we always increase the file size to 1 by writing a single byte
987 ** prior to accessing the inode number. The one byte written is
988 ** an ASCII 'S' character which also happens to be the first byte
989 ** in the header of every SQLite database. In this way, if there
990 ** is a race condition such that another thread has already populated
991 ** the first page of the database, no damage is done.
992 */
993 if( statbuf.st_size==0 ){
drheb0d74f2009-02-03 15:27:02 +0000994 rc = write(fd, "S", 1);
995 if( rc!=1 ){
996 return SQLITE_IOERR;
997 }
drh6c7d5c52008-11-21 20:32:33 +0000998 rc = fstat(fd, &statbuf);
999 if( rc!=0 ){
1000 pFile->lastErrno = errno;
1001 return SQLITE_IOERR;
1002 }
1003 }
drheb0d74f2009-02-03 15:27:02 +00001004#endif
drh6c7d5c52008-11-21 20:32:33 +00001005
1006 memset(&lockKey, 0, sizeof(lockKey));
1007 lockKey.fid.dev = statbuf.st_dev;
1008#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001009 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001010#else
1011 lockKey.fid.ino = statbuf.st_ino;
1012#endif
drh734c9862008-11-28 15:37:20 +00001013#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +00001014 if( threadsOverrideEachOthersLocks<0 ){
1015 testThreadLockingBehavior(fd);
1016 }
1017 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
1018#endif
1019 fileId = lockKey.fid;
1020 if( ppLock!=0 ){
1021 pLock = lockList;
1022 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
1023 pLock = pLock->pNext;
1024 }
1025 if( pLock==0 ){
1026 pLock = sqlite3_malloc( sizeof(*pLock) );
1027 if( pLock==0 ){
1028 rc = SQLITE_NOMEM;
1029 goto exit_findlockinfo;
1030 }
drh9b5db1d2009-10-07 23:42:25 +00001031 memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
drh6c7d5c52008-11-21 20:32:33 +00001032 pLock->nRef = 1;
1033 pLock->cnt = 0;
1034 pLock->locktype = 0;
1035 pLock->pNext = lockList;
1036 pLock->pPrev = 0;
1037 if( lockList ) lockList->pPrev = pLock;
1038 lockList = pLock;
1039 }else{
1040 pLock->nRef++;
1041 }
1042 *ppLock = pLock;
1043 }
1044 if( ppOpen!=0 ){
1045 pOpen = openList;
1046 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
1047 pOpen = pOpen->pNext;
1048 }
1049 if( pOpen==0 ){
1050 pOpen = sqlite3_malloc( sizeof(*pOpen) );
1051 if( pOpen==0 ){
1052 releaseLockInfo(pLock);
1053 rc = SQLITE_NOMEM;
1054 goto exit_findlockinfo;
1055 }
dane946c392009-08-22 11:39:46 +00001056 memset(pOpen, 0, sizeof(*pOpen));
drh6c7d5c52008-11-21 20:32:33 +00001057 pOpen->fileId = fileId;
1058 pOpen->nRef = 1;
drh6c7d5c52008-11-21 20:32:33 +00001059 pOpen->pNext = openList;
drh6c7d5c52008-11-21 20:32:33 +00001060 if( openList ) openList->pPrev = pOpen;
1061 openList = pOpen;
drh6c7d5c52008-11-21 20:32:33 +00001062 }else{
1063 pOpen->nRef++;
1064 }
1065 *ppOpen = pOpen;
1066 }
1067
1068exit_findlockinfo:
1069 return rc;
1070}
drh6c7d5c52008-11-21 20:32:33 +00001071
drh7708e972008-11-29 00:56:52 +00001072/*
1073** If we are currently in a different thread than the thread that the
1074** unixFile argument belongs to, then transfer ownership of the unixFile
1075** over to the current thread.
1076**
1077** A unixFile is only owned by a thread on systems that use LinuxThreads.
1078**
1079** Ownership transfer is only allowed if the unixFile is currently unlocked.
1080** If the unixFile is locked and an ownership is wrong, then return
1081** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1082*/
1083#if SQLITE_THREADSAFE && defined(__linux__)
1084static int transferOwnership(unixFile *pFile){
1085 int rc;
1086 pthread_t hSelf;
1087 if( threadsOverrideEachOthersLocks ){
1088 /* Ownership transfers not needed on this system */
1089 return SQLITE_OK;
1090 }
1091 hSelf = pthread_self();
1092 if( pthread_equal(pFile->tid, hSelf) ){
1093 /* We are still in the same thread */
1094 OSTRACE1("No-transfer, same thread\n");
1095 return SQLITE_OK;
1096 }
1097 if( pFile->locktype!=NO_LOCK ){
1098 /* We cannot change ownership while we are holding a lock! */
1099 return SQLITE_MISUSE;
1100 }
1101 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1102 pFile->h, pFile->tid, hSelf);
1103 pFile->tid = hSelf;
1104 if (pFile->pLock != NULL) {
1105 releaseLockInfo(pFile->pLock);
1106 rc = findLockInfo(pFile, &pFile->pLock, 0);
1107 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1108 locktypeName(pFile->locktype),
1109 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1110 return rc;
1111 } else {
1112 return SQLITE_OK;
1113 }
1114}
1115#else /* if not SQLITE_THREADSAFE */
1116 /* On single-threaded builds, ownership transfer is a no-op */
1117# define transferOwnership(X) SQLITE_OK
1118#endif /* SQLITE_THREADSAFE */
1119
aswift5b1a2562008-08-22 00:22:35 +00001120
1121/*
danielk197713adf8a2004-06-03 16:08:41 +00001122** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001123** file by this or any other process. If such a lock is held, set *pResOut
1124** to a non-zero value otherwise *pResOut is set to zero. The return value
1125** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001126*/
danielk1977861f7452008-06-05 11:39:11 +00001127static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001128 int rc = SQLITE_OK;
1129 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001130 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001131
danielk1977861f7452008-06-05 11:39:11 +00001132 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1133
drh054889e2005-11-30 03:20:31 +00001134 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001135 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001136
1137 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001138 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001139 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001140 }
1141
drh2ac3ee92004-06-07 16:27:46 +00001142 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001143 */
danielk197709480a92009-02-09 05:32:32 +00001144#ifndef __DJGPP__
aswift5b1a2562008-08-22 00:22:35 +00001145 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001146 struct flock lock;
1147 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001148 lock.l_start = RESERVED_BYTE;
1149 lock.l_len = 1;
1150 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001151 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1152 int tErrno = errno;
1153 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1154 pFile->lastErrno = tErrno;
1155 } else if( lock.l_type!=F_UNLCK ){
1156 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001157 }
1158 }
danielk197709480a92009-02-09 05:32:32 +00001159#endif
danielk197713adf8a2004-06-03 16:08:41 +00001160
drh6c7d5c52008-11-21 20:32:33 +00001161 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00001162 OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001163
aswift5b1a2562008-08-22 00:22:35 +00001164 *pResOut = reserved;
1165 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001166}
1167
1168/*
drh0c2694b2009-09-03 16:23:44 +00001169** Perform a file locking operation on a range of bytes in a file.
1170** The "op" parameter should be one of F_RDLCK, F_WRLCK, or F_UNLCK.
1171** Return 0 on success or -1 for failure. On failure, write the error
1172** code into *pErrcode.
1173**
1174** If the SQLITE_WHOLE_FILE_LOCKING bit is clear, then only lock
1175** the range of bytes on the locking page between SHARED_FIRST and
1176** SHARED_SIZE. If SQLITE_WHOLE_FILE_LOCKING is set, then lock all
1177** bytes from 0 up to but not including PENDING_BYTE, and all bytes
1178** that follow SHARED_FIRST.
1179**
1180** In other words, of SQLITE_WHOLE_FILE_LOCKING if false (the historical
1181** default case) then only lock a small range of bytes from SHARED_FIRST
1182** through SHARED_FIRST+SHARED_SIZE-1. But if SQLITE_WHOLE_FILE_LOCKING is
1183** true then lock every byte in the file except for PENDING_BYTE and
1184** RESERVED_BYTE.
1185**
1186** SQLITE_WHOLE_FILE_LOCKING=true overlaps SQLITE_WHOLE_FILE_LOCKING=false
1187** and so the locking schemes are compatible. One type of lock will
1188** effectively exclude the other type. The reason for using the
1189** SQLITE_WHOLE_FILE_LOCKING=true is that by indicating the full range
1190** of bytes to be read or written, we give hints to NFS to help it
1191** maintain cache coherency. On the other hand, whole file locking
1192** is slower, so we don't want to use it except for NFS.
1193*/
1194static int rangeLock(unixFile *pFile, int op, int *pErrcode){
1195 struct flock lock;
1196 int rc;
1197 lock.l_type = op;
1198 lock.l_start = SHARED_FIRST;
1199 lock.l_whence = SEEK_SET;
1200 if( (pFile->fileFlags & SQLITE_WHOLE_FILE_LOCKING)==0 ){
1201 lock.l_len = SHARED_SIZE;
1202 rc = fcntl(pFile->h, F_SETLK, &lock);
1203 *pErrcode = errno;
1204 }else{
1205 lock.l_len = 0;
1206 rc = fcntl(pFile->h, F_SETLK, &lock);
1207 *pErrcode = errno;
1208 if( NEVER(op==F_UNLCK) || rc!=(-1) ){
1209 lock.l_start = 0;
1210 lock.l_len = PENDING_BYTE;
1211 rc = fcntl(pFile->h, F_SETLK, &lock);
1212 if( ALWAYS(op!=F_UNLCK) && rc==(-1) ){
1213 *pErrcode = errno;
1214 lock.l_type = F_UNLCK;
1215 lock.l_start = SHARED_FIRST;
1216 lock.l_len = 0;
1217 fcntl(pFile->h, F_SETLK, &lock);
1218 }
1219 }
1220 }
1221 return rc;
1222}
1223
1224/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001225** Lock the file with the lock specified by parameter locktype - one
1226** of the following:
1227**
drh2ac3ee92004-06-07 16:27:46 +00001228** (1) SHARED_LOCK
1229** (2) RESERVED_LOCK
1230** (3) PENDING_LOCK
1231** (4) EXCLUSIVE_LOCK
1232**
drhb3e04342004-06-08 00:47:47 +00001233** Sometimes when requesting one lock state, additional lock states
1234** are inserted in between. The locking might fail on one of the later
1235** transitions leaving the lock state different from what it started but
1236** still short of its goal. The following chart shows the allowed
1237** transitions and the inserted intermediate states:
1238**
1239** UNLOCKED -> SHARED
1240** SHARED -> RESERVED
1241** SHARED -> (PENDING) -> EXCLUSIVE
1242** RESERVED -> (PENDING) -> EXCLUSIVE
1243** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001244**
drha6abd042004-06-09 17:37:22 +00001245** This routine will only increase a lock. Use the sqlite3OsUnlock()
1246** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001247*/
danielk197762079062007-08-15 17:08:46 +00001248static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001249 /* The following describes the implementation of the various locks and
1250 ** lock transitions in terms of the POSIX advisory shared and exclusive
1251 ** lock primitives (called read-locks and write-locks below, to avoid
1252 ** confusion with SQLite lock names). The algorithms are complicated
1253 ** slightly in order to be compatible with windows systems simultaneously
1254 ** accessing the same database file, in case that is ever required.
1255 **
1256 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1257 ** byte', each single bytes at well known offsets, and the 'shared byte
1258 ** range', a range of 510 bytes at a well known offset.
1259 **
1260 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1261 ** byte'. If this is successful, a random byte from the 'shared byte
1262 ** range' is read-locked and the lock on the 'pending byte' released.
1263 **
danielk197790ba3bd2004-06-25 08:32:25 +00001264 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1265 ** A RESERVED lock is implemented by grabbing a write-lock on the
1266 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001267 **
1268 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001269 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1270 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1271 ** obtained, but existing SHARED locks are allowed to persist. A process
1272 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1273 ** This property is used by the algorithm for rolling back a journal file
1274 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001275 **
danielk197790ba3bd2004-06-25 08:32:25 +00001276 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1277 ** implemented by obtaining a write-lock on the entire 'shared byte
1278 ** range'. Since all other locks require a read-lock on one of the bytes
1279 ** within this range, this ensures that no other locks are held on the
1280 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001281 **
1282 ** The reason a single byte cannot be used instead of the 'shared byte
1283 ** range' is that some versions of windows do not support read-locks. By
1284 ** locking a random byte from a range, concurrent SHARED locks may exist
1285 ** even if the locking primitive used is always a write-lock.
1286 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001287 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001288 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001289 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001290 struct flock lock;
drh3f022182009-09-09 16:10:50 +00001291 int s = 0;
drh0c2694b2009-09-03 16:23:44 +00001292 int tErrno;
danielk19779a1d0ab2004-06-01 14:09:28 +00001293
drh054889e2005-11-30 03:20:31 +00001294 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001295 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001296 locktypeName(locktype), locktypeName(pFile->locktype),
1297 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001298
1299 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001300 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001301 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001302 */
drh054889e2005-11-30 03:20:31 +00001303 if( pFile->locktype>=locktype ){
drh476bda72009-12-04 14:25:18 +00001304 OSTRACE3("LOCK %d %s ok (already held) (unix)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001305 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001306 return SQLITE_OK;
1307 }
1308
drh0c2694b2009-09-03 16:23:44 +00001309 /* Make sure the locking sequence is correct.
1310 ** (1) We never move from unlocked to anything higher than shared lock.
1311 ** (2) SQLite never explicitly requests a pendig lock.
1312 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001313 */
drh054889e2005-11-30 03:20:31 +00001314 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001315 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001316 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001317
drh054889e2005-11-30 03:20:31 +00001318 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001319 */
drh6c7d5c52008-11-21 20:32:33 +00001320 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001321
drh029b44b2006-01-15 00:13:15 +00001322 /* Make sure the current thread owns the pFile.
1323 */
1324 rc = transferOwnership(pFile);
1325 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001326 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001327 return rc;
1328 }
drh64b1bea2006-01-15 02:30:57 +00001329 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001330
danielk1977ad94b582007-08-20 06:44:22 +00001331 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001332 ** handle that precludes the requested lock, return BUSY.
1333 */
drh054889e2005-11-30 03:20:31 +00001334 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001335 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001336 ){
1337 rc = SQLITE_BUSY;
1338 goto end_lock;
1339 }
1340
1341 /* If a SHARED lock is requested, and some thread using this PID already
1342 ** has a SHARED or RESERVED lock, then increment reference counts and
1343 ** return SQLITE_OK.
1344 */
1345 if( locktype==SHARED_LOCK &&
1346 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1347 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001348 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001349 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001350 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001351 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001352 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001353 goto end_lock;
1354 }
1355
danielk19779a1d0ab2004-06-01 14:09:28 +00001356
drh3cde3bb2004-06-12 02:17:14 +00001357 /* A PENDING lock is needed before acquiring a SHARED lock and before
1358 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1359 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001360 */
drh0c2694b2009-09-03 16:23:44 +00001361 lock.l_len = 1L;
1362 lock.l_whence = SEEK_SET;
drh3cde3bb2004-06-12 02:17:14 +00001363 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001364 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001365 ){
danielk1977489468c2004-06-28 08:25:47 +00001366 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001367 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001368 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001369 if( s==(-1) ){
drh0c2694b2009-09-03 16:23:44 +00001370 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001371 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1372 if( IS_LOCK_ERROR(rc) ){
1373 pFile->lastErrno = tErrno;
1374 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001375 goto end_lock;
1376 }
drh3cde3bb2004-06-12 02:17:14 +00001377 }
1378
1379
1380 /* If control gets to this point, then actually go ahead and make
1381 ** operating system calls for the specified lock.
1382 */
1383 if( locktype==SHARED_LOCK ){
1384 assert( pLock->cnt==0 );
1385 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001386
drh2ac3ee92004-06-07 16:27:46 +00001387 /* Now get the read-lock */
drh0c2694b2009-09-03 16:23:44 +00001388 s = rangeLock(pFile, F_RDLCK, &tErrno);
1389
drh2ac3ee92004-06-07 16:27:46 +00001390 /* Drop the temporary PENDING lock */
1391 lock.l_start = PENDING_BYTE;
1392 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001393 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001394 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001395 if( s != -1 ){
1396 /* This could happen with a network mount */
1397 tErrno = errno;
1398 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1399 if( IS_LOCK_ERROR(rc) ){
1400 pFile->lastErrno = tErrno;
1401 }
1402 goto end_lock;
1403 }
drh2b4b5962005-06-15 17:47:55 +00001404 }
drhe2396a12007-03-29 20:19:58 +00001405 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001406 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1407 if( IS_LOCK_ERROR(rc) ){
1408 pFile->lastErrno = tErrno;
1409 }
drhbbd42a62004-05-22 17:41:58 +00001410 }else{
drh054889e2005-11-30 03:20:31 +00001411 pFile->locktype = SHARED_LOCK;
1412 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001413 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001414 }
drh3cde3bb2004-06-12 02:17:14 +00001415 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1416 /* We are trying for an exclusive lock but another thread in this
1417 ** same process is still holding a shared lock. */
1418 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001419 }else{
drh3cde3bb2004-06-12 02:17:14 +00001420 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001421 ** assumed that there is a SHARED or greater lock on the file
1422 ** already.
1423 */
drh054889e2005-11-30 03:20:31 +00001424 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001425 lock.l_type = F_WRLCK;
1426 switch( locktype ){
1427 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001428 lock.l_start = RESERVED_BYTE;
drh0c2694b2009-09-03 16:23:44 +00001429 s = fcntl(pFile->h, F_SETLK, &lock);
1430 tErrno = errno;
danielk19779a1d0ab2004-06-01 14:09:28 +00001431 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001432 case EXCLUSIVE_LOCK:
drh0c2694b2009-09-03 16:23:44 +00001433 s = rangeLock(pFile, F_WRLCK, &tErrno);
danielk19779a1d0ab2004-06-01 14:09:28 +00001434 break;
1435 default:
1436 assert(0);
1437 }
drhe2396a12007-03-29 20:19:58 +00001438 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001439 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1440 if( IS_LOCK_ERROR(rc) ){
1441 pFile->lastErrno = tErrno;
1442 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001443 }
drhbbd42a62004-05-22 17:41:58 +00001444 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001445
drh8f941bc2009-01-14 23:03:40 +00001446
1447#ifndef NDEBUG
1448 /* Set up the transaction-counter change checking flags when
1449 ** transitioning from a SHARED to a RESERVED lock. The change
1450 ** from SHARED to RESERVED marks the beginning of a normal
1451 ** write operation (not a hot journal rollback).
1452 */
1453 if( rc==SQLITE_OK
1454 && pFile->locktype<=SHARED_LOCK
1455 && locktype==RESERVED_LOCK
1456 ){
1457 pFile->transCntrChng = 0;
1458 pFile->dbUpdate = 0;
1459 pFile->inNormalWrite = 1;
1460 }
1461#endif
1462
1463
danielk1977ecb2a962004-06-02 06:30:16 +00001464 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001465 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001466 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001467 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001468 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001469 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001470 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001471
1472end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001473 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00001474 OSTRACE4("LOCK %d %s %s (unix)\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001475 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001476 return rc;
1477}
1478
1479/*
dane946c392009-08-22 11:39:46 +00001480** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
1481** If all such file descriptors are closed without error, the list is
1482** cleared and SQLITE_OK returned.
dan08da86a2009-08-21 17:18:03 +00001483**
1484** Otherwise, if an error occurs, then successfully closed file descriptor
dane946c392009-08-22 11:39:46 +00001485** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
dan08da86a2009-08-21 17:18:03 +00001486** not deleted and SQLITE_IOERR_CLOSE returned.
1487*/
1488static int closePendingFds(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001489 int rc = SQLITE_OK;
dane946c392009-08-22 11:39:46 +00001490 struct unixOpenCnt *pOpen = pFile->pOpen;
1491 UnixUnusedFd *pError = 0;
1492 UnixUnusedFd *p;
1493 UnixUnusedFd *pNext;
1494 for(p=pOpen->pUnused; p; p=pNext){
1495 pNext = p->pNext;
1496 if( close(p->fd) ){
1497 pFile->lastErrno = errno;
1498 rc = SQLITE_IOERR_CLOSE;
1499 p->pNext = pError;
1500 pError = p;
dane946c392009-08-22 11:39:46 +00001501 }else{
1502 sqlite3_free(p);
dan08da86a2009-08-21 17:18:03 +00001503 }
1504 }
dane946c392009-08-22 11:39:46 +00001505 pOpen->pUnused = pError;
dan08da86a2009-08-21 17:18:03 +00001506 return rc;
1507}
1508
1509/*
1510** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001511** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001512*/
1513static void setPendingFd(unixFile *pFile){
dan08da86a2009-08-21 17:18:03 +00001514 struct unixOpenCnt *pOpen = pFile->pOpen;
dane946c392009-08-22 11:39:46 +00001515 UnixUnusedFd *p = pFile->pUnused;
1516 p->pNext = pOpen->pUnused;
1517 pOpen->pUnused = p;
1518 pFile->h = -1;
1519 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001520}
1521
1522/*
drh054889e2005-11-30 03:20:31 +00001523** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001524** must be either NO_LOCK or SHARED_LOCK.
1525**
1526** If the locking level of the file descriptor is already at or below
1527** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001528*/
danielk197762079062007-08-15 17:08:46 +00001529static int unixUnlock(sqlite3_file *id, int locktype){
drh0c2694b2009-09-03 16:23:44 +00001530 unixFile *pFile = (unixFile*)id; /* The open file */
1531 struct unixLockInfo *pLock; /* Structure describing current lock state */
1532 struct flock lock; /* Information passed into fcntl() */
1533 int rc = SQLITE_OK; /* Return code from this interface */
1534 int h; /* The underlying file descriptor */
1535 int tErrno; /* Error code from system call errors */
drha6abd042004-06-09 17:37:22 +00001536
drh054889e2005-11-30 03:20:31 +00001537 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001538 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001539 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001540
1541 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001542 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001543 return SQLITE_OK;
1544 }
drhf1a221e2006-01-15 17:27:17 +00001545 if( CHECK_THREADID(pFile) ){
1546 return SQLITE_MISUSE;
1547 }
drh6c7d5c52008-11-21 20:32:33 +00001548 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001549 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001550 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001551 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001552 if( pFile->locktype>SHARED_LOCK ){
1553 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001554 SimulateIOErrorBenign(1);
1555 SimulateIOError( h=(-1) )
1556 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001557
1558#ifndef NDEBUG
1559 /* When reducing a lock such that other processes can start
1560 ** reading the database file again, make sure that the
1561 ** transaction counter was updated if any part of the database
1562 ** file changed. If the transaction counter is not updated,
1563 ** other connections to the same file might not realize that
1564 ** the file has changed and hence might not know to flush their
1565 ** cache. The use of a stale cache can lead to database corruption.
1566 */
1567 assert( pFile->inNormalWrite==0
1568 || pFile->dbUpdate==0
1569 || pFile->transCntrChng==1 );
1570 pFile->inNormalWrite = 0;
1571#endif
1572
1573
drh9c105bb2004-10-02 20:38:28 +00001574 if( locktype==SHARED_LOCK ){
drh0c2694b2009-09-03 16:23:44 +00001575 if( rangeLock(pFile, F_RDLCK, &tErrno)==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001576 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1577 if( IS_LOCK_ERROR(rc) ){
1578 pFile->lastErrno = tErrno;
1579 }
danielk197709480a92009-02-09 05:32:32 +00001580 goto end_unlock;
drh9c105bb2004-10-02 20:38:28 +00001581 }
1582 }
drhbbd42a62004-05-22 17:41:58 +00001583 lock.l_type = F_UNLCK;
1584 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001585 lock.l_start = PENDING_BYTE;
1586 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001587 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001588 pLock->locktype = SHARED_LOCK;
1589 }else{
drh0c2694b2009-09-03 16:23:44 +00001590 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001591 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1592 if( IS_LOCK_ERROR(rc) ){
1593 pFile->lastErrno = tErrno;
1594 }
drhcd731cf2009-03-28 23:23:02 +00001595 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001596 }
drhbbd42a62004-05-22 17:41:58 +00001597 }
drha6abd042004-06-09 17:37:22 +00001598 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001599 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001600
drha6abd042004-06-09 17:37:22 +00001601 /* Decrement the shared lock counter. Release the lock using an
1602 ** OS call only when all threads in this same process have released
1603 ** the lock.
1604 */
1605 pLock->cnt--;
1606 if( pLock->cnt==0 ){
1607 lock.l_type = F_UNLCK;
1608 lock.l_whence = SEEK_SET;
1609 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001610 SimulateIOErrorBenign(1);
1611 SimulateIOError( h=(-1) )
1612 SimulateIOErrorBenign(0);
1613 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001614 pLock->locktype = NO_LOCK;
1615 }else{
drh0c2694b2009-09-03 16:23:44 +00001616 tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001617 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001618 if( IS_LOCK_ERROR(rc) ){
1619 pFile->lastErrno = tErrno;
1620 }
drhf48f9ca2009-03-28 23:47:10 +00001621 pLock->locktype = NO_LOCK;
1622 pFile->locktype = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001623 }
drha6abd042004-06-09 17:37:22 +00001624 }
1625
drhbbd42a62004-05-22 17:41:58 +00001626 /* Decrement the count of locks against this same file. When the
1627 ** count reaches zero, close any other file descriptors whose close
1628 ** was deferred because of outstanding locks.
1629 */
danielk197764a54c52009-03-30 07:39:35 +00001630 pOpen = pFile->pOpen;
1631 pOpen->nLock--;
1632 assert( pOpen->nLock>=0 );
dane946c392009-08-22 11:39:46 +00001633 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00001634 int rc2 = closePendingFds(pFile);
1635 if( rc==SQLITE_OK ){
1636 rc = rc2;
drhbbd42a62004-05-22 17:41:58 +00001637 }
drhbbd42a62004-05-22 17:41:58 +00001638 }
1639 }
aswift5b1a2562008-08-22 00:22:35 +00001640
1641end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001642 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001643 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001644 return rc;
drhbbd42a62004-05-22 17:41:58 +00001645}
1646
1647/*
danielk1977e339d652008-06-28 11:23:00 +00001648** This function performs the parts of the "close file" operation
1649** common to all locking schemes. It closes the directory and file
1650** handles, if they are valid, and sets all fields of the unixFile
1651** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001652**
1653** It is *not* necessary to hold the mutex when this routine is called,
1654** even on VxWorks. A mutex will be acquired on VxWorks by the
1655** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001656*/
1657static int closeUnixFile(sqlite3_file *id){
1658 unixFile *pFile = (unixFile*)id;
1659 if( pFile ){
1660 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001661 int err = close(pFile->dirfd);
1662 if( err ){
1663 pFile->lastErrno = errno;
1664 return SQLITE_IOERR_DIR_CLOSE;
1665 }else{
1666 pFile->dirfd=-1;
1667 }
danielk1977e339d652008-06-28 11:23:00 +00001668 }
1669 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001670 int err = close(pFile->h);
1671 if( err ){
1672 pFile->lastErrno = errno;
1673 return SQLITE_IOERR_CLOSE;
1674 }
danielk1977e339d652008-06-28 11:23:00 +00001675 }
drh6c7d5c52008-11-21 20:32:33 +00001676#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001677 if( pFile->pId ){
1678 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001679 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001680 }
drh107886a2008-11-21 22:21:50 +00001681 vxworksReleaseFileId(pFile->pId);
1682 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001683 }
1684#endif
danielk1977e339d652008-06-28 11:23:00 +00001685 OSTRACE2("CLOSE %-3d\n", pFile->h);
1686 OpenCounter(-1);
dane946c392009-08-22 11:39:46 +00001687 sqlite3_free(pFile->pUnused);
danielk1977e339d652008-06-28 11:23:00 +00001688 memset(pFile, 0, sizeof(unixFile));
1689 }
1690 return SQLITE_OK;
1691}
1692
1693/*
danielk1977e3026632004-06-22 11:29:02 +00001694** Close a file.
1695*/
danielk197762079062007-08-15 17:08:46 +00001696static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001697 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001698 if( id ){
1699 unixFile *pFile = (unixFile *)id;
1700 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001701 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001702 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001703 /* If there are outstanding locks, do not actually close the file just
1704 ** yet because that would clear those locks. Instead, add the file
dane946c392009-08-22 11:39:46 +00001705 ** descriptor to pOpen->pUnused list. It will be automatically closed
1706 ** when the last lock is cleared.
danielk1977e339d652008-06-28 11:23:00 +00001707 */
dan08da86a2009-08-21 17:18:03 +00001708 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001709 }
danielk1977e339d652008-06-28 11:23:00 +00001710 releaseLockInfo(pFile->pLock);
1711 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001712 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001713 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001714 }
aswiftaebf4132008-11-21 00:10:35 +00001715 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001716}
1717
drh734c9862008-11-28 15:37:20 +00001718/************** End of the posix advisory lock implementation *****************
1719******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001720
drh734c9862008-11-28 15:37:20 +00001721/******************************************************************************
1722****************************** No-op Locking **********************************
1723**
1724** Of the various locking implementations available, this is by far the
1725** simplest: locking is ignored. No attempt is made to lock the database
1726** file for reading or writing.
1727**
1728** This locking mode is appropriate for use on read-only databases
1729** (ex: databases that are burned into CD-ROM, for example.) It can
1730** also be used if the application employs some external mechanism to
1731** prevent simultaneous access of the same database by two or more
1732** database connections. But there is a serious risk of database
1733** corruption if this locking mode is used in situations where multiple
1734** database connections are accessing the same database file at the same
1735** time and one or more of those connections are writing.
1736*/
drhbfe66312006-10-03 17:40:40 +00001737
drh734c9862008-11-28 15:37:20 +00001738static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1739 UNUSED_PARAMETER(NotUsed);
1740 *pResOut = 0;
1741 return SQLITE_OK;
1742}
drh734c9862008-11-28 15:37:20 +00001743static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1744 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1745 return SQLITE_OK;
1746}
drh734c9862008-11-28 15:37:20 +00001747static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1748 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1749 return SQLITE_OK;
1750}
1751
1752/*
drh9b35ea62008-11-29 02:20:26 +00001753** Close the file.
drh734c9862008-11-28 15:37:20 +00001754*/
1755static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001756 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001757}
1758
1759/******************* End of the no-op lock implementation *********************
1760******************************************************************************/
1761
1762/******************************************************************************
1763************************* Begin dot-file Locking ******************************
1764**
drh0c2694b2009-09-03 16:23:44 +00001765** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001766** files in order to control access to the database. This works on just
1767** about every filesystem imaginable. But there are serious downsides:
1768**
1769** (1) There is zero concurrency. A single reader blocks all other
1770** connections from reading or writing the database.
1771**
1772** (2) An application crash or power loss can leave stale lock files
1773** sitting around that need to be cleared manually.
1774**
1775** Nevertheless, a dotlock is an appropriate locking mode for use if no
1776** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001777**
1778** Dotfile locking works by creating a file in the same directory as the
1779** database and with the same name but with a ".lock" extension added.
1780** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1781** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001782*/
1783
1784/*
1785** The file suffix added to the data base filename in order to create the
1786** lock file.
1787*/
1788#define DOTLOCK_SUFFIX ".lock"
1789
drh7708e972008-11-29 00:56:52 +00001790/*
1791** This routine checks if there is a RESERVED lock held on the specified
1792** file by this or any other process. If such a lock is held, set *pResOut
1793** to a non-zero value otherwise *pResOut is set to zero. The return value
1794** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1795**
1796** In dotfile locking, either a lock exists or it does not. So in this
1797** variation of CheckReservedLock(), *pResOut is set to true if any lock
1798** is held on the file and false if the file is unlocked.
1799*/
drh734c9862008-11-28 15:37:20 +00001800static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1801 int rc = SQLITE_OK;
1802 int reserved = 0;
1803 unixFile *pFile = (unixFile*)id;
1804
1805 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1806
1807 assert( pFile );
1808
1809 /* Check if a thread in this process holds such a lock */
1810 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001811 /* Either this connection or some other connection in the same process
1812 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001813 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001814 }else{
1815 /* The lock is held if and only if the lockfile exists */
1816 const char *zLockFile = (const char*)pFile->lockingContext;
1817 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001818 }
drh476bda72009-12-04 14:25:18 +00001819 OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001820 *pResOut = reserved;
1821 return rc;
1822}
1823
drh7708e972008-11-29 00:56:52 +00001824/*
1825** Lock the file with the lock specified by parameter locktype - one
1826** of the following:
1827**
1828** (1) SHARED_LOCK
1829** (2) RESERVED_LOCK
1830** (3) PENDING_LOCK
1831** (4) EXCLUSIVE_LOCK
1832**
1833** Sometimes when requesting one lock state, additional lock states
1834** are inserted in between. The locking might fail on one of the later
1835** transitions leaving the lock state different from what it started but
1836** still short of its goal. The following chart shows the allowed
1837** transitions and the inserted intermediate states:
1838**
1839** UNLOCKED -> SHARED
1840** SHARED -> RESERVED
1841** SHARED -> (PENDING) -> EXCLUSIVE
1842** RESERVED -> (PENDING) -> EXCLUSIVE
1843** PENDING -> EXCLUSIVE
1844**
1845** This routine will only increase a lock. Use the sqlite3OsUnlock()
1846** routine to lower a locking level.
1847**
1848** With dotfile locking, we really only support state (4): EXCLUSIVE.
1849** But we track the other locking levels internally.
1850*/
drh734c9862008-11-28 15:37:20 +00001851static int dotlockLock(sqlite3_file *id, int locktype) {
1852 unixFile *pFile = (unixFile*)id;
1853 int fd;
1854 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001855 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001856
drh7708e972008-11-29 00:56:52 +00001857
1858 /* If we have any lock, then the lock file already exists. All we have
1859 ** to do is adjust our internal record of the lock level.
1860 */
1861 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001862 pFile->locktype = locktype;
1863#if !OS_VXWORKS
1864 /* Always update the timestamp on the old file */
1865 utimes(zLockFile, NULL);
1866#endif
drh7708e972008-11-29 00:56:52 +00001867 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001868 }
1869
1870 /* grab an exclusive lock */
1871 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1872 if( fd<0 ){
1873 /* failed to open/create the file, someone else may have stolen the lock */
1874 int tErrno = errno;
1875 if( EEXIST == tErrno ){
1876 rc = SQLITE_BUSY;
1877 } else {
1878 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1879 if( IS_LOCK_ERROR(rc) ){
1880 pFile->lastErrno = tErrno;
1881 }
1882 }
drh7708e972008-11-29 00:56:52 +00001883 return rc;
drh734c9862008-11-28 15:37:20 +00001884 }
1885 if( close(fd) ){
1886 pFile->lastErrno = errno;
1887 rc = SQLITE_IOERR_CLOSE;
1888 }
1889
1890 /* got it, set the type and return ok */
1891 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001892 return rc;
1893}
1894
drh7708e972008-11-29 00:56:52 +00001895/*
1896** Lower the locking level on file descriptor pFile to locktype. locktype
1897** must be either NO_LOCK or SHARED_LOCK.
1898**
1899** If the locking level of the file descriptor is already at or below
1900** the requested locking level, this routine is a no-op.
1901**
1902** When the locking level reaches NO_LOCK, delete the lock file.
1903*/
drh734c9862008-11-28 15:37:20 +00001904static int dotlockUnlock(sqlite3_file *id, int locktype) {
1905 unixFile *pFile = (unixFile*)id;
1906 char *zLockFile = (char *)pFile->lockingContext;
1907
1908 assert( pFile );
drh476bda72009-12-04 14:25:18 +00001909 OSTRACE5("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00001910 pFile->locktype, getpid());
1911 assert( locktype<=SHARED_LOCK );
1912
1913 /* no-op if possible */
1914 if( pFile->locktype==locktype ){
1915 return SQLITE_OK;
1916 }
drh7708e972008-11-29 00:56:52 +00001917
1918 /* To downgrade to shared, simply update our internal notion of the
1919 ** lock state. No need to mess with the file on disk.
1920 */
1921 if( locktype==SHARED_LOCK ){
1922 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001923 return SQLITE_OK;
1924 }
1925
drh7708e972008-11-29 00:56:52 +00001926 /* To fully unlock the database, delete the lock file */
1927 assert( locktype==NO_LOCK );
1928 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00001929 int rc = 0;
1930 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00001931 if( ENOENT != tErrno ){
1932 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1933 }
1934 if( IS_LOCK_ERROR(rc) ){
1935 pFile->lastErrno = tErrno;
1936 }
1937 return rc;
1938 }
1939 pFile->locktype = NO_LOCK;
1940 return SQLITE_OK;
1941}
1942
1943/*
drh9b35ea62008-11-29 02:20:26 +00001944** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001945*/
1946static int dotlockClose(sqlite3_file *id) {
1947 int rc;
1948 if( id ){
1949 unixFile *pFile = (unixFile*)id;
1950 dotlockUnlock(id, NO_LOCK);
1951 sqlite3_free(pFile->lockingContext);
1952 }
drh734c9862008-11-28 15:37:20 +00001953 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001954 return rc;
1955}
1956/****************** End of the dot-file lock implementation *******************
1957******************************************************************************/
1958
1959/******************************************************************************
1960************************** Begin flock Locking ********************************
1961**
1962** Use the flock() system call to do file locking.
1963**
drh6b9d6dd2008-12-03 19:34:47 +00001964** flock() locking is like dot-file locking in that the various
1965** fine-grain locking levels supported by SQLite are collapsed into
1966** a single exclusive lock. In other words, SHARED, RESERVED, and
1967** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
1968** still works when you do this, but concurrency is reduced since
1969** only a single process can be reading the database at a time.
1970**
drh734c9862008-11-28 15:37:20 +00001971** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1972** compiling for VXWORKS.
1973*/
1974#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001975
drh6b9d6dd2008-12-03 19:34:47 +00001976/*
1977** This routine checks if there is a RESERVED lock held on the specified
1978** file by this or any other process. If such a lock is held, set *pResOut
1979** to a non-zero value otherwise *pResOut is set to zero. The return value
1980** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1981*/
drh734c9862008-11-28 15:37:20 +00001982static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1983 int rc = SQLITE_OK;
1984 int reserved = 0;
1985 unixFile *pFile = (unixFile*)id;
1986
1987 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1988
1989 assert( pFile );
1990
1991 /* Check if a thread in this process holds such a lock */
1992 if( pFile->locktype>SHARED_LOCK ){
1993 reserved = 1;
1994 }
1995
1996 /* Otherwise see if some other process holds it. */
1997 if( !reserved ){
1998 /* attempt to get the lock */
1999 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
2000 if( !lrc ){
2001 /* got the lock, unlock it */
2002 lrc = flock(pFile->h, LOCK_UN);
2003 if ( lrc ) {
2004 int tErrno = errno;
2005 /* unlock failed with an error */
2006 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2007 if( IS_LOCK_ERROR(lrc) ){
2008 pFile->lastErrno = tErrno;
2009 rc = lrc;
2010 }
2011 }
2012 } else {
2013 int tErrno = errno;
2014 reserved = 1;
2015 /* someone else might have it reserved */
2016 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2017 if( IS_LOCK_ERROR(lrc) ){
2018 pFile->lastErrno = tErrno;
2019 rc = lrc;
2020 }
2021 }
2022 }
drh476bda72009-12-04 14:25:18 +00002023 OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00002024
2025#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2026 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2027 rc = SQLITE_OK;
2028 reserved=1;
2029 }
2030#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2031 *pResOut = reserved;
2032 return rc;
2033}
2034
drh6b9d6dd2008-12-03 19:34:47 +00002035/*
2036** Lock the file with the lock specified by parameter locktype - one
2037** of the following:
2038**
2039** (1) SHARED_LOCK
2040** (2) RESERVED_LOCK
2041** (3) PENDING_LOCK
2042** (4) EXCLUSIVE_LOCK
2043**
2044** Sometimes when requesting one lock state, additional lock states
2045** are inserted in between. The locking might fail on one of the later
2046** transitions leaving the lock state different from what it started but
2047** still short of its goal. The following chart shows the allowed
2048** transitions and the inserted intermediate states:
2049**
2050** UNLOCKED -> SHARED
2051** SHARED -> RESERVED
2052** SHARED -> (PENDING) -> EXCLUSIVE
2053** RESERVED -> (PENDING) -> EXCLUSIVE
2054** PENDING -> EXCLUSIVE
2055**
2056** flock() only really support EXCLUSIVE locks. We track intermediate
2057** lock states in the sqlite3_file structure, but all locks SHARED or
2058** above are really EXCLUSIVE locks and exclude all other processes from
2059** access the file.
2060**
2061** This routine will only increase a lock. Use the sqlite3OsUnlock()
2062** routine to lower a locking level.
2063*/
drh734c9862008-11-28 15:37:20 +00002064static int flockLock(sqlite3_file *id, int locktype) {
2065 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002066 unixFile *pFile = (unixFile*)id;
2067
2068 assert( pFile );
2069
2070 /* if we already have a lock, it is exclusive.
2071 ** Just adjust level and punt on outta here. */
2072 if (pFile->locktype > NO_LOCK) {
2073 pFile->locktype = locktype;
2074 return SQLITE_OK;
2075 }
2076
2077 /* grab an exclusive lock */
2078
2079 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
2080 int tErrno = errno;
2081 /* didn't get, must be busy */
2082 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2083 if( IS_LOCK_ERROR(rc) ){
2084 pFile->lastErrno = tErrno;
2085 }
2086 } else {
2087 /* got it, set the type and return ok */
2088 pFile->locktype = locktype;
2089 }
drh476bda72009-12-04 14:25:18 +00002090 OSTRACE4("LOCK %d %s %s (flock)\n", pFile->h, locktypeName(locktype),
drh734c9862008-11-28 15:37:20 +00002091 rc==SQLITE_OK ? "ok" : "failed");
2092#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2093 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2094 rc = SQLITE_BUSY;
2095 }
2096#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2097 return rc;
2098}
2099
drh6b9d6dd2008-12-03 19:34:47 +00002100
2101/*
2102** Lower the locking level on file descriptor pFile to locktype. locktype
2103** must be either NO_LOCK or SHARED_LOCK.
2104**
2105** If the locking level of the file descriptor is already at or below
2106** the requested locking level, this routine is a no-op.
2107*/
drh734c9862008-11-28 15:37:20 +00002108static int flockUnlock(sqlite3_file *id, int locktype) {
2109 unixFile *pFile = (unixFile*)id;
2110
2111 assert( pFile );
drh476bda72009-12-04 14:25:18 +00002112 OSTRACE5("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00002113 pFile->locktype, getpid());
2114 assert( locktype<=SHARED_LOCK );
2115
2116 /* no-op if possible */
2117 if( pFile->locktype==locktype ){
2118 return SQLITE_OK;
2119 }
2120
2121 /* shared can just be set because we always have an exclusive */
2122 if (locktype==SHARED_LOCK) {
2123 pFile->locktype = locktype;
2124 return SQLITE_OK;
2125 }
2126
2127 /* no, really, unlock. */
2128 int rc = flock(pFile->h, LOCK_UN);
2129 if (rc) {
2130 int r, tErrno = errno;
2131 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2132 if( IS_LOCK_ERROR(r) ){
2133 pFile->lastErrno = tErrno;
2134 }
2135#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2136 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2137 r = SQLITE_BUSY;
2138 }
2139#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2140
2141 return r;
2142 } else {
2143 pFile->locktype = NO_LOCK;
2144 return SQLITE_OK;
2145 }
2146}
2147
2148/*
2149** Close a file.
2150*/
2151static int flockClose(sqlite3_file *id) {
2152 if( id ){
2153 flockUnlock(id, NO_LOCK);
2154 }
2155 return closeUnixFile(id);
2156}
2157
2158#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2159
2160/******************* End of the flock lock implementation *********************
2161******************************************************************************/
2162
2163/******************************************************************************
2164************************ Begin Named Semaphore Locking ************************
2165**
2166** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002167**
2168** Semaphore locking is like dot-lock and flock in that it really only
2169** supports EXCLUSIVE locking. Only a single process can read or write
2170** the database file at a time. This reduces potential concurrency, but
2171** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002172*/
2173#if OS_VXWORKS
2174
drh6b9d6dd2008-12-03 19:34:47 +00002175/*
2176** This routine checks if there is a RESERVED lock held on the specified
2177** file by this or any other process. If such a lock is held, set *pResOut
2178** to a non-zero value otherwise *pResOut is set to zero. The return value
2179** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2180*/
drh734c9862008-11-28 15:37:20 +00002181static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2182 int rc = SQLITE_OK;
2183 int reserved = 0;
2184 unixFile *pFile = (unixFile*)id;
2185
2186 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2187
2188 assert( pFile );
2189
2190 /* Check if a thread in this process holds such a lock */
2191 if( pFile->locktype>SHARED_LOCK ){
2192 reserved = 1;
2193 }
2194
2195 /* Otherwise see if some other process holds it. */
2196 if( !reserved ){
2197 sem_t *pSem = pFile->pOpen->pSem;
2198 struct stat statBuf;
2199
2200 if( sem_trywait(pSem)==-1 ){
2201 int tErrno = errno;
2202 if( EAGAIN != tErrno ){
2203 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2204 pFile->lastErrno = tErrno;
2205 } else {
2206 /* someone else has the lock when we are in NO_LOCK */
2207 reserved = (pFile->locktype < SHARED_LOCK);
2208 }
2209 }else{
2210 /* we could have it if we want it */
2211 sem_post(pSem);
2212 }
2213 }
drh476bda72009-12-04 14:25:18 +00002214 OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00002215
2216 *pResOut = reserved;
2217 return rc;
2218}
2219
drh6b9d6dd2008-12-03 19:34:47 +00002220/*
2221** Lock the file with the lock specified by parameter locktype - one
2222** of the following:
2223**
2224** (1) SHARED_LOCK
2225** (2) RESERVED_LOCK
2226** (3) PENDING_LOCK
2227** (4) EXCLUSIVE_LOCK
2228**
2229** Sometimes when requesting one lock state, additional lock states
2230** are inserted in between. The locking might fail on one of the later
2231** transitions leaving the lock state different from what it started but
2232** still short of its goal. The following chart shows the allowed
2233** transitions and the inserted intermediate states:
2234**
2235** UNLOCKED -> SHARED
2236** SHARED -> RESERVED
2237** SHARED -> (PENDING) -> EXCLUSIVE
2238** RESERVED -> (PENDING) -> EXCLUSIVE
2239** PENDING -> EXCLUSIVE
2240**
2241** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2242** lock states in the sqlite3_file structure, but all locks SHARED or
2243** above are really EXCLUSIVE locks and exclude all other processes from
2244** access the file.
2245**
2246** This routine will only increase a lock. Use the sqlite3OsUnlock()
2247** routine to lower a locking level.
2248*/
drh734c9862008-11-28 15:37:20 +00002249static int semLock(sqlite3_file *id, int locktype) {
2250 unixFile *pFile = (unixFile*)id;
2251 int fd;
2252 sem_t *pSem = pFile->pOpen->pSem;
2253 int rc = SQLITE_OK;
2254
2255 /* if we already have a lock, it is exclusive.
2256 ** Just adjust level and punt on outta here. */
2257 if (pFile->locktype > NO_LOCK) {
2258 pFile->locktype = locktype;
2259 rc = SQLITE_OK;
2260 goto sem_end_lock;
2261 }
2262
2263 /* lock semaphore now but bail out when already locked. */
2264 if( sem_trywait(pSem)==-1 ){
2265 rc = SQLITE_BUSY;
2266 goto sem_end_lock;
2267 }
2268
2269 /* got it, set the type and return ok */
2270 pFile->locktype = locktype;
2271
2272 sem_end_lock:
2273 return rc;
2274}
2275
drh6b9d6dd2008-12-03 19:34:47 +00002276/*
2277** Lower the locking level on file descriptor pFile to locktype. locktype
2278** must be either NO_LOCK or SHARED_LOCK.
2279**
2280** If the locking level of the file descriptor is already at or below
2281** the requested locking level, this routine is a no-op.
2282*/
drh734c9862008-11-28 15:37:20 +00002283static int semUnlock(sqlite3_file *id, int locktype) {
2284 unixFile *pFile = (unixFile*)id;
2285 sem_t *pSem = pFile->pOpen->pSem;
2286
2287 assert( pFile );
2288 assert( pSem );
drh476bda72009-12-04 14:25:18 +00002289 OSTRACE5("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
drh734c9862008-11-28 15:37:20 +00002290 pFile->locktype, getpid());
2291 assert( locktype<=SHARED_LOCK );
2292
2293 /* no-op if possible */
2294 if( pFile->locktype==locktype ){
2295 return SQLITE_OK;
2296 }
2297
2298 /* shared can just be set because we always have an exclusive */
2299 if (locktype==SHARED_LOCK) {
2300 pFile->locktype = locktype;
2301 return SQLITE_OK;
2302 }
2303
2304 /* no, really unlock. */
2305 if ( sem_post(pSem)==-1 ) {
2306 int rc, tErrno = errno;
2307 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2308 if( IS_LOCK_ERROR(rc) ){
2309 pFile->lastErrno = tErrno;
2310 }
2311 return rc;
2312 }
2313 pFile->locktype = NO_LOCK;
2314 return SQLITE_OK;
2315}
2316
2317/*
2318 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002319 */
drh734c9862008-11-28 15:37:20 +00002320static int semClose(sqlite3_file *id) {
2321 if( id ){
2322 unixFile *pFile = (unixFile*)id;
2323 semUnlock(id, NO_LOCK);
2324 assert( pFile );
2325 unixEnterMutex();
2326 releaseLockInfo(pFile->pLock);
2327 releaseOpenCnt(pFile->pOpen);
drh734c9862008-11-28 15:37:20 +00002328 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002329 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002330 }
2331 return SQLITE_OK;
2332}
2333
2334#endif /* OS_VXWORKS */
2335/*
2336** Named semaphore locking is only available on VxWorks.
2337**
2338*************** End of the named semaphore lock implementation ****************
2339******************************************************************************/
2340
2341
2342/******************************************************************************
2343*************************** Begin AFP Locking *********************************
2344**
2345** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2346** on Apple Macintosh computers - both OS9 and OSX.
2347**
2348** Third-party implementations of AFP are available. But this code here
2349** only works on OSX.
2350*/
2351
drhd2cb50b2009-01-09 21:41:17 +00002352#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002353/*
2354** The afpLockingContext structure contains all afp lock specific state
2355*/
drhbfe66312006-10-03 17:40:40 +00002356typedef struct afpLockingContext afpLockingContext;
2357struct afpLockingContext {
aswiftaebf4132008-11-21 00:10:35 +00002358 unsigned long long sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002359 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002360};
2361
2362struct ByteRangeLockPB2
2363{
2364 unsigned long long offset; /* offset to first byte to lock */
2365 unsigned long long length; /* nbr of bytes to lock */
2366 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2367 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2368 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2369 int fd; /* file desc to assoc this lock with */
2370};
2371
drhfd131da2007-08-07 17:13:03 +00002372#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002373
drh6b9d6dd2008-12-03 19:34:47 +00002374/*
2375** This is a utility for setting or clearing a bit-range lock on an
2376** AFP filesystem.
2377**
2378** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2379*/
2380static int afpSetLock(
2381 const char *path, /* Name of the file to be locked or unlocked */
2382 unixFile *pFile, /* Open file descriptor on path */
2383 unsigned long long offset, /* First byte to be locked */
2384 unsigned long long length, /* Number of bytes to lock */
2385 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002386){
drh6b9d6dd2008-12-03 19:34:47 +00002387 struct ByteRangeLockPB2 pb;
2388 int err;
drhbfe66312006-10-03 17:40:40 +00002389
2390 pb.unLockFlag = setLockFlag ? 0 : 1;
2391 pb.startEndFlag = 0;
2392 pb.offset = offset;
2393 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002394 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002395
2396 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002397 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2398 offset, length);
drhbfe66312006-10-03 17:40:40 +00002399 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2400 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002401 int rc;
2402 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002403 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2404 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002405#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2406 rc = SQLITE_BUSY;
2407#else
drh734c9862008-11-28 15:37:20 +00002408 rc = sqliteErrorFromPosixError(tErrno,
2409 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002410#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002411 if( IS_LOCK_ERROR(rc) ){
2412 pFile->lastErrno = tErrno;
2413 }
2414 return rc;
drhbfe66312006-10-03 17:40:40 +00002415 } else {
aswift5b1a2562008-08-22 00:22:35 +00002416 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002417 }
2418}
2419
drh6b9d6dd2008-12-03 19:34:47 +00002420/*
2421** This routine checks if there is a RESERVED lock held on the specified
2422** file by this or any other process. If such a lock is held, set *pResOut
2423** to a non-zero value otherwise *pResOut is set to zero. The return value
2424** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2425*/
danielk1977e339d652008-06-28 11:23:00 +00002426static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002427 int rc = SQLITE_OK;
2428 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002429 unixFile *pFile = (unixFile*)id;
2430
aswift5b1a2562008-08-22 00:22:35 +00002431 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2432
2433 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002434 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2435
2436 /* Check if a thread in this process holds such a lock */
2437 if( pFile->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002438 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002439 }
2440
2441 /* Otherwise see if some other process holds it.
2442 */
aswift5b1a2562008-08-22 00:22:35 +00002443 if( !reserved ){
2444 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002445 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002446 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002447 /* if we succeeded in taking the reserved lock, unlock it to restore
2448 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002449 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002450 } else {
2451 /* if we failed to get the lock then someone else must have it */
2452 reserved = 1;
2453 }
2454 if( IS_LOCK_ERROR(lrc) ){
2455 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002456 }
2457 }
drhbfe66312006-10-03 17:40:40 +00002458
drh476bda72009-12-04 14:25:18 +00002459 OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
aswift5b1a2562008-08-22 00:22:35 +00002460
2461 *pResOut = reserved;
2462 return rc;
drhbfe66312006-10-03 17:40:40 +00002463}
2464
drh6b9d6dd2008-12-03 19:34:47 +00002465/*
2466** Lock the file with the lock specified by parameter locktype - one
2467** of the following:
2468**
2469** (1) SHARED_LOCK
2470** (2) RESERVED_LOCK
2471** (3) PENDING_LOCK
2472** (4) EXCLUSIVE_LOCK
2473**
2474** Sometimes when requesting one lock state, additional lock states
2475** are inserted in between. The locking might fail on one of the later
2476** transitions leaving the lock state different from what it started but
2477** still short of its goal. The following chart shows the allowed
2478** transitions and the inserted intermediate states:
2479**
2480** UNLOCKED -> SHARED
2481** SHARED -> RESERVED
2482** SHARED -> (PENDING) -> EXCLUSIVE
2483** RESERVED -> (PENDING) -> EXCLUSIVE
2484** PENDING -> EXCLUSIVE
2485**
2486** This routine will only increase a lock. Use the sqlite3OsUnlock()
2487** routine to lower a locking level.
2488*/
danielk1977e339d652008-06-28 11:23:00 +00002489static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002490 int rc = SQLITE_OK;
2491 unixFile *pFile = (unixFile*)id;
2492 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002493
2494 assert( pFile );
drh476bda72009-12-04 14:25:18 +00002495 OSTRACE5("LOCK %d %s was %s pid=%d (afp)\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00002496 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
2497
drhbfe66312006-10-03 17:40:40 +00002498 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002499 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002500 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002501 */
drhbfe66312006-10-03 17:40:40 +00002502 if( pFile->locktype>=locktype ){
drh476bda72009-12-04 14:25:18 +00002503 OSTRACE3("LOCK %d %s ok (already held) (afp)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002504 locktypeName(locktype));
2505 return SQLITE_OK;
2506 }
2507
2508 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00002509 */
drhbfe66312006-10-03 17:40:40 +00002510 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2511 assert( locktype!=PENDING_LOCK );
2512 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2513
2514 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002515 */
drh6c7d5c52008-11-21 20:32:33 +00002516 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002517
2518 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002519 */
drhbfe66312006-10-03 17:40:40 +00002520 rc = transferOwnership(pFile);
2521 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002522 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002523 return rc;
2524 }
2525
2526 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002527 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2528 ** be released.
2529 */
drhbfe66312006-10-03 17:40:40 +00002530 if( locktype==SHARED_LOCK
2531 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002532 ){
2533 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002534 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002535 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002536 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002537 goto afp_end_lock;
2538 }
2539 }
2540
2541 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002542 ** operating system calls for the specified lock.
2543 */
drhbfe66312006-10-03 17:40:40 +00002544 if( locktype==SHARED_LOCK ){
drh1d452e12009-11-01 19:26:59 +00002545 int lk, lrc1, lrc2;
2546 int lrc1Errno = 0;
drhbfe66312006-10-03 17:40:40 +00002547
aswift5b1a2562008-08-22 00:22:35 +00002548 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002549 /* note that the quality of the randomness doesn't matter that much */
2550 lk = random();
aswiftaebf4132008-11-21 00:10:35 +00002551 context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002552 lrc1 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002553 SHARED_FIRST+context->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002554 if( IS_LOCK_ERROR(lrc1) ){
2555 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002556 }
aswift5b1a2562008-08-22 00:22:35 +00002557 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002558 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002559
aswift5b1a2562008-08-22 00:22:35 +00002560 if( IS_LOCK_ERROR(lrc1) ) {
2561 pFile->lastErrno = lrc1Errno;
2562 rc = lrc1;
2563 goto afp_end_lock;
2564 } else if( IS_LOCK_ERROR(lrc2) ){
2565 rc = lrc2;
2566 goto afp_end_lock;
2567 } else if( lrc1 != SQLITE_OK ) {
2568 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002569 } else {
2570 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002571 pFile->pOpen->nLock++;
drhbfe66312006-10-03 17:40:40 +00002572 }
2573 }else{
2574 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2575 ** assumed that there is a SHARED or greater lock on the file
2576 ** already.
2577 */
2578 int failed = 0;
2579 assert( 0!=pFile->locktype );
2580 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2581 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002582 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drhbfe66312006-10-03 17:40:40 +00002583 }
2584 if (!failed && locktype == EXCLUSIVE_LOCK) {
2585 /* Acquire an EXCLUSIVE lock */
2586
2587 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002588 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002589 */
drh6b9d6dd2008-12-03 19:34:47 +00002590 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
aswiftaebf4132008-11-21 00:10:35 +00002591 context->sharedByte, 1, 0)) ){
2592 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002593 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002594 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002595 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002596 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
aswiftaebf4132008-11-21 00:10:35 +00002597 SHARED_FIRST + context->sharedByte, 1, 1)) ){
2598 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2599 ** a critical I/O error
2600 */
2601 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2602 SQLITE_IOERR_LOCK;
2603 goto afp_end_lock;
2604 }
2605 }else{
aswift5b1a2562008-08-22 00:22:35 +00002606 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002607 }
2608 }
aswift5b1a2562008-08-22 00:22:35 +00002609 if( failed ){
2610 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002611 }
2612 }
2613
2614 if( rc==SQLITE_OK ){
2615 pFile->locktype = locktype;
2616 }else if( locktype==EXCLUSIVE_LOCK ){
2617 pFile->locktype = PENDING_LOCK;
2618 }
2619
2620afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002621 unixLeaveMutex();
drh476bda72009-12-04 14:25:18 +00002622 OSTRACE4("LOCK %d %s %s (afp)\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002623 rc==SQLITE_OK ? "ok" : "failed");
2624 return rc;
2625}
2626
2627/*
drh339eb0b2008-03-07 15:34:11 +00002628** Lower the locking level on file descriptor pFile to locktype. locktype
2629** must be either NO_LOCK or SHARED_LOCK.
2630**
2631** If the locking level of the file descriptor is already at or below
2632** the requested locking level, this routine is a no-op.
2633*/
danielk1977e339d652008-06-28 11:23:00 +00002634static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002635 int rc = SQLITE_OK;
2636 unixFile *pFile = (unixFile*)id;
aswiftaebf4132008-11-21 00:10:35 +00002637 afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002638
2639 assert( pFile );
drh476bda72009-12-04 14:25:18 +00002640 OSTRACE5("UNLOCK %d %d was %d pid=%d (afp)\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00002641 pFile->locktype, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002642
drhbfe66312006-10-03 17:40:40 +00002643 assert( locktype<=SHARED_LOCK );
2644 if( pFile->locktype<=locktype ){
2645 return SQLITE_OK;
2646 }
2647 if( CHECK_THREADID(pFile) ){
2648 return SQLITE_MISUSE;
2649 }
drh6c7d5c52008-11-21 20:32:33 +00002650 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002651 if( pFile->locktype>SHARED_LOCK ){
aswiftaebf4132008-11-21 00:10:35 +00002652
2653 if( pFile->locktype==EXCLUSIVE_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002654 rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
aswiftaebf4132008-11-21 00:10:35 +00002655 if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
2656 /* only re-establish the shared lock if necessary */
2657 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002658 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
aswiftaebf4132008-11-21 00:10:35 +00002659 }
2660 }
2661 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002662 rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002663 }
2664 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
drh6b9d6dd2008-12-03 19:34:47 +00002665 rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002666 }
2667 }else if( locktype==NO_LOCK ){
2668 /* clear the shared lock */
2669 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
drh6b9d6dd2008-12-03 19:34:47 +00002670 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002671 }
drhbfe66312006-10-03 17:40:40 +00002672
aswiftaebf4132008-11-21 00:10:35 +00002673 if( rc==SQLITE_OK ){
2674 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00002675 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002676 pOpen->nLock--;
2677 assert( pOpen->nLock>=0 );
dan6aa657f2009-08-24 18:57:58 +00002678 if( pOpen->nLock==0 ){
dan08da86a2009-08-21 17:18:03 +00002679 rc = closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002680 }
2681 }
drhbfe66312006-10-03 17:40:40 +00002682 }
drh6c7d5c52008-11-21 20:32:33 +00002683 unixLeaveMutex();
dan08da86a2009-08-21 17:18:03 +00002684 if( rc==SQLITE_OK ){
2685 pFile->locktype = locktype;
2686 }
drhbfe66312006-10-03 17:40:40 +00002687 return rc;
2688}
2689
2690/*
drh339eb0b2008-03-07 15:34:11 +00002691** Close a file & cleanup AFP specific locking context
2692*/
danielk1977e339d652008-06-28 11:23:00 +00002693static int afpClose(sqlite3_file *id) {
2694 if( id ){
2695 unixFile *pFile = (unixFile*)id;
2696 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002697 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002698 if( pFile->pOpen && pFile->pOpen->nLock ){
2699 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002700 ** yet because that would clear those locks. Instead, add the file
2701 ** descriptor to pOpen->aPending. It will be automatically closed when
2702 ** the last lock is cleared.
2703 */
dan08da86a2009-08-21 17:18:03 +00002704 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002705 }
2706 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002707 sqlite3_free(pFile->lockingContext);
aswiftaebf4132008-11-21 00:10:35 +00002708 closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002709 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002710 }
aswiftaebf4132008-11-21 00:10:35 +00002711 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002712}
2713
drhd2cb50b2009-01-09 21:41:17 +00002714#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002715/*
2716** The code above is the AFP lock implementation. The code is specific
2717** to MacOSX and does not work on other unix platforms. No alternative
2718** is available. If you don't compile for a mac, then the "unix-afp"
2719** VFS is not available.
2720**
2721********************* End of the AFP lock implementation **********************
2722******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002723
drh734c9862008-11-28 15:37:20 +00002724
2725/******************************************************************************
2726**************** Non-locking sqlite3_file methods *****************************
2727**
2728** The next division contains implementations for all methods of the
2729** sqlite3_file object other than the locking methods. The locking
2730** methods were defined in divisions above (one locking method per
2731** division). Those methods that are common to all locking modes
2732** are gather together into this division.
2733*/
drhbfe66312006-10-03 17:40:40 +00002734
2735/*
drh734c9862008-11-28 15:37:20 +00002736** Seek to the offset passed as the second argument, then read cnt
2737** bytes into pBuf. Return the number of bytes actually read.
2738**
2739** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2740** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2741** one system to another. Since SQLite does not define USE_PREAD
2742** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2743** See tickets #2741 and #2681.
2744**
2745** To avoid stomping the errno value on a failed read the lastErrno value
2746** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002747*/
drh734c9862008-11-28 15:37:20 +00002748static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2749 int got;
2750 i64 newOffset;
2751 TIMER_START;
2752#if defined(USE_PREAD)
2753 got = pread(id->h, pBuf, cnt, offset);
2754 SimulateIOError( got = -1 );
2755#elif defined(USE_PREAD64)
2756 got = pread64(id->h, pBuf, cnt, offset);
2757 SimulateIOError( got = -1 );
2758#else
2759 newOffset = lseek(id->h, offset, SEEK_SET);
2760 SimulateIOError( newOffset-- );
2761 if( newOffset!=offset ){
2762 if( newOffset == -1 ){
2763 ((unixFile*)id)->lastErrno = errno;
2764 }else{
2765 ((unixFile*)id)->lastErrno = 0;
2766 }
2767 return -1;
2768 }
2769 got = read(id->h, pBuf, cnt);
2770#endif
2771 TIMER_END;
2772 if( got<0 ){
2773 ((unixFile*)id)->lastErrno = errno;
2774 }
2775 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2776 return got;
drhbfe66312006-10-03 17:40:40 +00002777}
2778
2779/*
drh734c9862008-11-28 15:37:20 +00002780** Read data from a file into a buffer. Return SQLITE_OK if all
2781** bytes were read successfully and SQLITE_IOERR if anything goes
2782** wrong.
drh339eb0b2008-03-07 15:34:11 +00002783*/
drh734c9862008-11-28 15:37:20 +00002784static int unixRead(
2785 sqlite3_file *id,
2786 void *pBuf,
2787 int amt,
2788 sqlite3_int64 offset
2789){
dan08da86a2009-08-21 17:18:03 +00002790 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002791 int got;
2792 assert( id );
drh08c6d442009-02-09 17:34:07 +00002793
dan08da86a2009-08-21 17:18:03 +00002794 /* If this is a database file (not a journal, master-journal or temp
2795 ** file), the bytes in the locking range should never be read or written. */
dane946c392009-08-22 11:39:46 +00002796 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002797 || offset>=PENDING_BYTE+512
2798 || offset+amt<=PENDING_BYTE
2799 );
drh08c6d442009-02-09 17:34:07 +00002800
dan08da86a2009-08-21 17:18:03 +00002801 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00002802 if( got==amt ){
2803 return SQLITE_OK;
2804 }else if( got<0 ){
2805 /* lastErrno set by seekAndRead */
2806 return SQLITE_IOERR_READ;
2807 }else{
dan08da86a2009-08-21 17:18:03 +00002808 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002809 /* Unread parts of the buffer must be zero-filled */
2810 memset(&((char*)pBuf)[got], 0, amt-got);
2811 return SQLITE_IOERR_SHORT_READ;
2812 }
2813}
2814
2815/*
2816** Seek to the offset in id->offset then read cnt bytes into pBuf.
2817** Return the number of bytes actually read. Update the offset.
2818**
2819** To avoid stomping the errno value on a failed write the lastErrno value
2820** is set before returning.
2821*/
2822static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2823 int got;
2824 i64 newOffset;
2825 TIMER_START;
2826#if defined(USE_PREAD)
2827 got = pwrite(id->h, pBuf, cnt, offset);
2828#elif defined(USE_PREAD64)
2829 got = pwrite64(id->h, pBuf, cnt, offset);
2830#else
2831 newOffset = lseek(id->h, offset, SEEK_SET);
2832 if( newOffset!=offset ){
2833 if( newOffset == -1 ){
2834 ((unixFile*)id)->lastErrno = errno;
2835 }else{
2836 ((unixFile*)id)->lastErrno = 0;
2837 }
2838 return -1;
2839 }
2840 got = write(id->h, pBuf, cnt);
2841#endif
2842 TIMER_END;
2843 if( got<0 ){
2844 ((unixFile*)id)->lastErrno = errno;
2845 }
2846
2847 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
2848 return got;
2849}
2850
2851
2852/*
2853** Write data from a buffer into a file. Return SQLITE_OK on success
2854** or some other error code on failure.
2855*/
2856static int unixWrite(
2857 sqlite3_file *id,
2858 const void *pBuf,
2859 int amt,
2860 sqlite3_int64 offset
2861){
dan08da86a2009-08-21 17:18:03 +00002862 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002863 int wrote = 0;
2864 assert( id );
2865 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00002866
dan08da86a2009-08-21 17:18:03 +00002867 /* If this is a database file (not a journal, master-journal or temp
2868 ** file), the bytes in the locking range should never be read or written. */
dane946c392009-08-22 11:39:46 +00002869 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002870 || offset>=PENDING_BYTE+512
2871 || offset+amt<=PENDING_BYTE
2872 );
drh08c6d442009-02-09 17:34:07 +00002873
drh8f941bc2009-01-14 23:03:40 +00002874#ifndef NDEBUG
2875 /* If we are doing a normal write to a database file (as opposed to
2876 ** doing a hot-journal rollback or a write to some file other than a
2877 ** normal database file) then record the fact that the database
2878 ** has changed. If the transaction counter is modified, record that
2879 ** fact too.
2880 */
dan08da86a2009-08-21 17:18:03 +00002881 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00002882 pFile->dbUpdate = 1; /* The database has been modified */
2883 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00002884 int rc;
drh8f941bc2009-01-14 23:03:40 +00002885 char oldCntr[4];
2886 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00002887 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00002888 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00002889 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00002890 pFile->transCntrChng = 1; /* The transaction counter has changed */
2891 }
2892 }
2893 }
2894#endif
2895
dan08da86a2009-08-21 17:18:03 +00002896 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00002897 amt -= wrote;
2898 offset += wrote;
2899 pBuf = &((char*)pBuf)[wrote];
2900 }
2901 SimulateIOError(( wrote=(-1), amt=1 ));
2902 SimulateDiskfullError(( wrote=0, amt=1 ));
2903 if( amt>0 ){
2904 if( wrote<0 ){
2905 /* lastErrno set by seekAndWrite */
2906 return SQLITE_IOERR_WRITE;
2907 }else{
dan08da86a2009-08-21 17:18:03 +00002908 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00002909 return SQLITE_FULL;
2910 }
2911 }
2912 return SQLITE_OK;
2913}
2914
2915#ifdef SQLITE_TEST
2916/*
2917** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00002918** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00002919*/
2920int sqlite3_sync_count = 0;
2921int sqlite3_fullsync_count = 0;
2922#endif
2923
2924/*
drh89240432009-03-25 01:06:01 +00002925** We do not trust systems to provide a working fdatasync(). Some do.
2926** Others do no. To be safe, we will stick with the (slower) fsync().
2927** If you know that your system does support fdatasync() correctly,
2928** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00002929*/
drh89240432009-03-25 01:06:01 +00002930#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00002931# define fdatasync fsync
2932#endif
2933
2934/*
2935** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
2936** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
2937** only available on Mac OS X. But that could change.
2938*/
2939#ifdef F_FULLFSYNC
2940# define HAVE_FULLFSYNC 1
2941#else
2942# define HAVE_FULLFSYNC 0
2943#endif
2944
2945
2946/*
2947** The fsync() system call does not work as advertised on many
2948** unix systems. The following procedure is an attempt to make
2949** it work better.
2950**
2951** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
2952** for testing when we want to run through the test suite quickly.
2953** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
2954** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
2955** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00002956**
2957** SQLite sets the dataOnly flag if the size of the file is unchanged.
2958** The idea behind dataOnly is that it should only write the file content
2959** to disk, not the inode. We only set dataOnly if the file size is
2960** unchanged since the file size is part of the inode. However,
2961** Ted Ts'o tells us that fdatasync() will also write the inode if the
2962** file size has changed. The only real difference between fdatasync()
2963** and fsync(), Ted tells us, is that fdatasync() will not flush the
2964** inode if the mtime or owner or other inode attributes have changed.
2965** We only care about the file size, not the other file attributes, so
2966** as far as SQLite is concerned, an fdatasync() is always adequate.
2967** So, we always use fdatasync() if it is available, regardless of
2968** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00002969*/
2970static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00002971 int rc;
drh734c9862008-11-28 15:37:20 +00002972
2973 /* The following "ifdef/elif/else/" block has the same structure as
2974 ** the one below. It is replicated here solely to avoid cluttering
2975 ** up the real code with the UNUSED_PARAMETER() macros.
2976 */
2977#ifdef SQLITE_NO_SYNC
2978 UNUSED_PARAMETER(fd);
2979 UNUSED_PARAMETER(fullSync);
2980 UNUSED_PARAMETER(dataOnly);
2981#elif HAVE_FULLFSYNC
2982 UNUSED_PARAMETER(dataOnly);
2983#else
2984 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00002985 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00002986#endif
2987
2988 /* Record the number of times that we do a normal fsync() and
2989 ** FULLSYNC. This is used during testing to verify that this procedure
2990 ** gets called with the correct arguments.
2991 */
2992#ifdef SQLITE_TEST
2993 if( fullSync ) sqlite3_fullsync_count++;
2994 sqlite3_sync_count++;
2995#endif
2996
2997 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2998 ** no-op
2999 */
3000#ifdef SQLITE_NO_SYNC
3001 rc = SQLITE_OK;
3002#elif HAVE_FULLFSYNC
3003 if( fullSync ){
3004 rc = fcntl(fd, F_FULLFSYNC, 0);
3005 }else{
3006 rc = 1;
3007 }
3008 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003009 ** It shouldn't be possible for fullfsync to fail on the local
3010 ** file system (on OSX), so failure indicates that FULLFSYNC
3011 ** isn't supported for this file system. So, attempt an fsync
3012 ** and (for now) ignore the overhead of a superfluous fcntl call.
3013 ** It'd be better to detect fullfsync support once and avoid
3014 ** the fcntl call every time sync is called.
3015 */
drh734c9862008-11-28 15:37:20 +00003016 if( rc ) rc = fsync(fd);
3017
3018#else
drh0b647ff2009-03-21 14:41:04 +00003019 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003020#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003021 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003022 rc = fsync(fd);
3023 }
drh0b647ff2009-03-21 14:41:04 +00003024#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003025#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3026
3027 if( OS_VXWORKS && rc!= -1 ){
3028 rc = 0;
3029 }
chw97185482008-11-17 08:05:31 +00003030 return rc;
drhbfe66312006-10-03 17:40:40 +00003031}
3032
drh734c9862008-11-28 15:37:20 +00003033/*
3034** Make sure all writes to a particular file are committed to disk.
3035**
3036** If dataOnly==0 then both the file itself and its metadata (file
3037** size, access time, etc) are synced. If dataOnly!=0 then only the
3038** file data is synced.
3039**
3040** Under Unix, also make sure that the directory entry for the file
3041** has been created by fsync-ing the directory that contains the file.
3042** If we do not do this and we encounter a power failure, the directory
3043** entry for the journal might not exist after we reboot. The next
3044** SQLite to access the file will not know that the journal exists (because
3045** the directory entry for the journal was never created) and the transaction
3046** will not roll back - possibly leading to database corruption.
3047*/
3048static int unixSync(sqlite3_file *id, int flags){
3049 int rc;
3050 unixFile *pFile = (unixFile*)id;
3051
3052 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3053 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3054
3055 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3056 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3057 || (flags&0x0F)==SQLITE_SYNC_FULL
3058 );
3059
3060 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3061 ** line is to test that doing so does not cause any problems.
3062 */
3063 SimulateDiskfullError( return SQLITE_FULL );
3064
3065 assert( pFile );
3066 OSTRACE2("SYNC %-3d\n", pFile->h);
3067 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3068 SimulateIOError( rc=1 );
3069 if( rc ){
3070 pFile->lastErrno = errno;
3071 return SQLITE_IOERR_FSYNC;
3072 }
3073 if( pFile->dirfd>=0 ){
3074 int err;
3075 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3076 HAVE_FULLFSYNC, isFullsync);
3077#ifndef SQLITE_DISABLE_DIRSYNC
3078 /* The directory sync is only attempted if full_fsync is
3079 ** turned off or unavailable. If a full_fsync occurred above,
3080 ** then the directory sync is superfluous.
3081 */
3082 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3083 /*
3084 ** We have received multiple reports of fsync() returning
3085 ** errors when applied to directories on certain file systems.
3086 ** A failed directory sync is not a big deal. So it seems
3087 ** better to ignore the error. Ticket #1657
3088 */
3089 /* pFile->lastErrno = errno; */
3090 /* return SQLITE_IOERR; */
3091 }
3092#endif
3093 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3094 if( err==0 ){ /* directory when we are done */
3095 pFile->dirfd = -1;
3096 }else{
3097 pFile->lastErrno = errno;
3098 rc = SQLITE_IOERR_DIR_CLOSE;
3099 }
3100 }
3101 return rc;
3102}
3103
3104/*
3105** Truncate an open file to a specified size
3106*/
3107static int unixTruncate(sqlite3_file *id, i64 nByte){
3108 int rc;
3109 assert( id );
3110 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3111 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3112 if( rc ){
3113 ((unixFile*)id)->lastErrno = errno;
3114 return SQLITE_IOERR_TRUNCATE;
3115 }else{
drh3313b142009-11-06 04:13:18 +00003116#ifndef NDEBUG
3117 /* If we are doing a normal write to a database file (as opposed to
3118 ** doing a hot-journal rollback or a write to some file other than a
3119 ** normal database file) and we truncate the file to zero length,
3120 ** that effectively updates the change counter. This might happen
3121 ** when restoring a database using the backup API from a zero-length
3122 ** source.
3123 */
3124 if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
3125 ((unixFile*)id)->transCntrChng = 1;
3126 }
3127#endif
3128
drh734c9862008-11-28 15:37:20 +00003129 return SQLITE_OK;
3130 }
3131}
3132
3133/*
3134** Determine the current size of a file in bytes
3135*/
3136static int unixFileSize(sqlite3_file *id, i64 *pSize){
3137 int rc;
3138 struct stat buf;
3139 assert( id );
3140 rc = fstat(((unixFile*)id)->h, &buf);
3141 SimulateIOError( rc=1 );
3142 if( rc!=0 ){
3143 ((unixFile*)id)->lastErrno = errno;
3144 return SQLITE_IOERR_FSTAT;
3145 }
3146 *pSize = buf.st_size;
3147
3148 /* When opening a zero-size database, the findLockInfo() procedure
3149 ** writes a single byte into that file in order to work around a bug
3150 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3151 ** layers, we need to report this file size as zero even though it is
3152 ** really 1. Ticket #3260.
3153 */
3154 if( *pSize==1 ) *pSize = 0;
3155
3156
3157 return SQLITE_OK;
3158}
3159
drhd2cb50b2009-01-09 21:41:17 +00003160#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003161/*
3162** Handler for proxy-locking file-control verbs. Defined below in the
3163** proxying locking division.
3164*/
3165static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003166#endif
drh715ff302008-12-03 22:32:44 +00003167
danielk1977ad94b582007-08-20 06:44:22 +00003168
danielk1977e3026632004-06-22 11:29:02 +00003169/*
drh9e33c2c2007-08-31 18:34:59 +00003170** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003171*/
drhcc6bb3e2007-08-31 16:11:35 +00003172static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003173 switch( op ){
3174 case SQLITE_FCNTL_LOCKSTATE: {
3175 *(int*)pArg = ((unixFile*)id)->locktype;
3176 return SQLITE_OK;
3177 }
drh7708e972008-11-29 00:56:52 +00003178 case SQLITE_LAST_ERRNO: {
3179 *(int*)pArg = ((unixFile*)id)->lastErrno;
3180 return SQLITE_OK;
3181 }
drh8f941bc2009-01-14 23:03:40 +00003182#ifndef NDEBUG
3183 /* The pager calls this method to signal that it has done
3184 ** a rollback and that the database is therefore unchanged and
3185 ** it hence it is OK for the transaction change counter to be
3186 ** unchanged.
3187 */
3188 case SQLITE_FCNTL_DB_UNCHANGED: {
3189 ((unixFile*)id)->dbUpdate = 0;
3190 return SQLITE_OK;
3191 }
3192#endif
drhd2cb50b2009-01-09 21:41:17 +00003193#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003194 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003195 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003196 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003197 }
drhd2cb50b2009-01-09 21:41:17 +00003198#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003199 }
drhcc6bb3e2007-08-31 16:11:35 +00003200 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003201}
3202
3203/*
danielk1977a3d4c882007-03-23 10:08:38 +00003204** Return the sector size in bytes of the underlying block device for
3205** the specified file. This is almost always 512 bytes, but may be
3206** larger for some devices.
3207**
3208** SQLite code assumes this function cannot fail. It also assumes that
3209** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003210** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003211** same for both.
3212*/
danielk1977397d65f2008-11-19 11:35:39 +00003213static int unixSectorSize(sqlite3_file *NotUsed){
3214 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003215 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003216}
3217
danielk197790949c22007-08-17 16:50:38 +00003218/*
danielk1977397d65f2008-11-19 11:35:39 +00003219** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003220*/
danielk1977397d65f2008-11-19 11:35:39 +00003221static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3222 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003223 return 0;
3224}
3225
drh734c9862008-11-28 15:37:20 +00003226/*
3227** Here ends the implementation of all sqlite3_file methods.
3228**
3229********************** End sqlite3_file Methods *******************************
3230******************************************************************************/
3231
3232/*
drh6b9d6dd2008-12-03 19:34:47 +00003233** This division contains definitions of sqlite3_io_methods objects that
3234** implement various file locking strategies. It also contains definitions
3235** of "finder" functions. A finder-function is used to locate the appropriate
3236** sqlite3_io_methods object for a particular database file. The pAppData
3237** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3238** the correct finder-function for that VFS.
3239**
3240** Most finder functions return a pointer to a fixed sqlite3_io_methods
3241** object. The only interesting finder-function is autolockIoFinder, which
3242** looks at the filesystem type and tries to guess the best locking
3243** strategy from that.
3244**
drh1875f7a2008-12-08 18:19:17 +00003245** For finder-funtion F, two objects are created:
3246**
3247** (1) The real finder-function named "FImpt()".
3248**
dane946c392009-08-22 11:39:46 +00003249** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00003250**
3251**
3252** A pointer to the F pointer is used as the pAppData value for VFS
3253** objects. We have to do this instead of letting pAppData point
3254** directly at the finder-function since C90 rules prevent a void*
3255** from be cast into a function pointer.
3256**
drh6b9d6dd2008-12-03 19:34:47 +00003257**
drh7708e972008-11-29 00:56:52 +00003258** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003259**
drh7708e972008-11-29 00:56:52 +00003260** * A constant sqlite3_io_methods object call METHOD that has locking
3261** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3262**
3263** * An I/O method finder function called FINDER that returns a pointer
3264** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003265*/
drh7708e972008-11-29 00:56:52 +00003266#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3267static const sqlite3_io_methods METHOD = { \
3268 1, /* iVersion */ \
3269 CLOSE, /* xClose */ \
3270 unixRead, /* xRead */ \
3271 unixWrite, /* xWrite */ \
3272 unixTruncate, /* xTruncate */ \
3273 unixSync, /* xSync */ \
3274 unixFileSize, /* xFileSize */ \
3275 LOCK, /* xLock */ \
3276 UNLOCK, /* xUnlock */ \
3277 CKLOCK, /* xCheckReservedLock */ \
3278 unixFileControl, /* xFileControl */ \
3279 unixSectorSize, /* xSectorSize */ \
3280 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3281}; \
drh0c2694b2009-09-03 16:23:44 +00003282static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3283 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00003284 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00003285} \
drh0c2694b2009-09-03 16:23:44 +00003286static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00003287 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00003288
3289/*
3290** Here are all of the sqlite3_io_methods objects for each of the
3291** locking strategies. Functions that return pointers to these methods
3292** are also created.
3293*/
3294IOMETHODS(
3295 posixIoFinder, /* Finder function name */
3296 posixIoMethods, /* sqlite3_io_methods object name */
3297 unixClose, /* xClose method */
3298 unixLock, /* xLock method */
3299 unixUnlock, /* xUnlock method */
3300 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003301)
drh7708e972008-11-29 00:56:52 +00003302IOMETHODS(
3303 nolockIoFinder, /* Finder function name */
3304 nolockIoMethods, /* sqlite3_io_methods object name */
3305 nolockClose, /* xClose method */
3306 nolockLock, /* xLock method */
3307 nolockUnlock, /* xUnlock method */
3308 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003309)
drh7708e972008-11-29 00:56:52 +00003310IOMETHODS(
3311 dotlockIoFinder, /* Finder function name */
3312 dotlockIoMethods, /* sqlite3_io_methods object name */
3313 dotlockClose, /* xClose method */
3314 dotlockLock, /* xLock method */
3315 dotlockUnlock, /* xUnlock method */
3316 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003317)
drh7708e972008-11-29 00:56:52 +00003318
chw78a13182009-04-07 05:35:03 +00003319#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003320IOMETHODS(
3321 flockIoFinder, /* Finder function name */
3322 flockIoMethods, /* sqlite3_io_methods object name */
3323 flockClose, /* xClose method */
3324 flockLock, /* xLock method */
3325 flockUnlock, /* xUnlock method */
3326 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003327)
drh7708e972008-11-29 00:56:52 +00003328#endif
3329
drh6c7d5c52008-11-21 20:32:33 +00003330#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003331IOMETHODS(
3332 semIoFinder, /* Finder function name */
3333 semIoMethods, /* sqlite3_io_methods object name */
3334 semClose, /* xClose method */
3335 semLock, /* xLock method */
3336 semUnlock, /* xUnlock method */
3337 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003338)
aswiftaebf4132008-11-21 00:10:35 +00003339#endif
drh7708e972008-11-29 00:56:52 +00003340
drhd2cb50b2009-01-09 21:41:17 +00003341#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003342IOMETHODS(
3343 afpIoFinder, /* Finder function name */
3344 afpIoMethods, /* sqlite3_io_methods object name */
3345 afpClose, /* xClose method */
3346 afpLock, /* xLock method */
3347 afpUnlock, /* xUnlock method */
3348 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003349)
drh715ff302008-12-03 22:32:44 +00003350#endif
3351
3352/*
drh0c2694b2009-09-03 16:23:44 +00003353** The "Whole File Locking" finder returns the same set of methods as
3354** the posix locking finder. But it also sets the SQLITE_WHOLE_FILE_LOCKING
3355** flag to force the posix advisory locks to cover the whole file instead
3356** of just a small span of bytes near the 1GiB boundary. Whole File Locking
3357** is useful on NFS-mounted files since it helps NFS to maintain cache
3358** coherency. But it is a detriment to other filesystems since it runs
3359** slower.
3360*/
3361static const sqlite3_io_methods *posixWflIoFinderImpl(const char*z, unixFile*p){
3362 UNUSED_PARAMETER(z);
3363 p->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
3364 return &posixIoMethods;
3365}
3366static const sqlite3_io_methods
3367 *(*const posixWflIoFinder)(const char*,unixFile *p) = posixWflIoFinderImpl;
3368
3369/*
drh715ff302008-12-03 22:32:44 +00003370** The proxy locking method is a "super-method" in the sense that it
3371** opens secondary file descriptors for the conch and lock files and
3372** it uses proxy, dot-file, AFP, and flock() locking methods on those
3373** secondary files. For this reason, the division that implements
3374** proxy locking is located much further down in the file. But we need
3375** to go ahead and define the sqlite3_io_methods and finder function
3376** for proxy locking here. So we forward declare the I/O methods.
3377*/
drhd2cb50b2009-01-09 21:41:17 +00003378#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00003379static int proxyClose(sqlite3_file*);
3380static int proxyLock(sqlite3_file*, int);
3381static int proxyUnlock(sqlite3_file*, int);
3382static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00003383IOMETHODS(
3384 proxyIoFinder, /* Finder function name */
3385 proxyIoMethods, /* sqlite3_io_methods object name */
3386 proxyClose, /* xClose method */
3387 proxyLock, /* xLock method */
3388 proxyUnlock, /* xUnlock method */
3389 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00003390)
aswiftaebf4132008-11-21 00:10:35 +00003391#endif
drh7708e972008-11-29 00:56:52 +00003392
3393
drhd2cb50b2009-01-09 21:41:17 +00003394#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003395/*
drh6b9d6dd2008-12-03 19:34:47 +00003396** This "finder" function attempts to determine the best locking strategy
3397** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00003398** object that implements that strategy.
3399**
3400** This is for MacOSX only.
3401*/
drh1875f7a2008-12-08 18:19:17 +00003402static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00003403 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003404 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00003405){
3406 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00003407 const char *zFilesystem; /* Filesystem type name */
3408 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00003409 } aMap[] = {
3410 { "hfs", &posixIoMethods },
3411 { "ufs", &posixIoMethods },
3412 { "afpfs", &afpIoMethods },
3413#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
3414 { "smbfs", &afpIoMethods },
3415#else
3416 { "smbfs", &flockIoMethods },
3417#endif
3418 { "webdav", &nolockIoMethods },
3419 { 0, 0 }
3420 };
3421 int i;
3422 struct statfs fsInfo;
3423 struct flock lockInfo;
3424
3425 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00003426 /* If filePath==NULL that means we are dealing with a transient file
3427 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00003428 return &nolockIoMethods;
3429 }
3430 if( statfs(filePath, &fsInfo) != -1 ){
3431 if( fsInfo.f_flags & MNT_RDONLY ){
3432 return &nolockIoMethods;
3433 }
3434 for(i=0; aMap[i].zFilesystem; i++){
3435 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3436 return aMap[i].pMethods;
3437 }
3438 }
3439 }
3440
3441 /* Default case. Handles, amongst others, "nfs".
3442 ** Test byte-range lock using fcntl(). If the call succeeds,
3443 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003444 */
drh7708e972008-11-29 00:56:52 +00003445 lockInfo.l_len = 1;
3446 lockInfo.l_start = 0;
3447 lockInfo.l_whence = SEEK_SET;
3448 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003449 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
3450 pNew->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
drh7708e972008-11-29 00:56:52 +00003451 return &posixIoMethods;
3452 }else{
3453 return &dotlockIoMethods;
3454 }
3455}
drh0c2694b2009-09-03 16:23:44 +00003456static const sqlite3_io_methods
3457 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00003458
drhd2cb50b2009-01-09 21:41:17 +00003459#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00003460
chw78a13182009-04-07 05:35:03 +00003461#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
3462/*
3463** This "finder" function attempts to determine the best locking strategy
3464** for the database file "filePath". It then returns the sqlite3_io_methods
3465** object that implements that strategy.
3466**
3467** This is for VXWorks only.
3468*/
3469static const sqlite3_io_methods *autolockIoFinderImpl(
3470 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00003471 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00003472){
3473 struct flock lockInfo;
3474
3475 if( !filePath ){
3476 /* If filePath==NULL that means we are dealing with a transient file
3477 ** that does not need to be locked. */
3478 return &nolockIoMethods;
3479 }
3480
3481 /* Test if fcntl() is supported and use POSIX style locks.
3482 ** Otherwise fall back to the named semaphore method.
3483 */
3484 lockInfo.l_len = 1;
3485 lockInfo.l_start = 0;
3486 lockInfo.l_whence = SEEK_SET;
3487 lockInfo.l_type = F_RDLCK;
drh0c2694b2009-09-03 16:23:44 +00003488 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00003489 return &posixIoMethods;
3490 }else{
3491 return &semIoMethods;
3492 }
3493}
drh0c2694b2009-09-03 16:23:44 +00003494static const sqlite3_io_methods
3495 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00003496
3497#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
3498
drh7708e972008-11-29 00:56:52 +00003499/*
3500** An abstract type for a pointer to a IO method finder function:
3501*/
drh0c2694b2009-09-03 16:23:44 +00003502typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00003503
aswiftaebf4132008-11-21 00:10:35 +00003504
drh734c9862008-11-28 15:37:20 +00003505/****************************************************************************
3506**************************** sqlite3_vfs methods ****************************
3507**
3508** This division contains the implementation of methods on the
3509** sqlite3_vfs object.
3510*/
3511
danielk1977a3d4c882007-03-23 10:08:38 +00003512/*
danielk1977e339d652008-06-28 11:23:00 +00003513** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003514*/
3515static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003516 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003517 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003518 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003519 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003520 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003521 int noLock, /* Omit locking if true */
3522 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003523){
drh7708e972008-11-29 00:56:52 +00003524 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003525 unixFile *pNew = (unixFile *)pId;
3526 int rc = SQLITE_OK;
3527
danielk197717b90b52008-06-06 11:11:25 +00003528 assert( pNew->pLock==NULL );
3529 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003530
dane946c392009-08-22 11:39:46 +00003531 /* Parameter isDelete is only used on vxworks. Express this explicitly
3532 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00003533 */
drh7708e972008-11-29 00:56:52 +00003534 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00003535
drh218c5082008-03-07 00:27:10 +00003536 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003537 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003538 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003539 SET_THREADID(pNew);
drh0c2694b2009-09-03 16:23:44 +00003540 pNew->fileFlags = 0;
drh339eb0b2008-03-07 15:34:11 +00003541
drh6c7d5c52008-11-21 20:32:33 +00003542#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003543 pNew->pId = vxworksFindFileId(zFilename);
3544 if( pNew->pId==0 ){
3545 noLock = 1;
3546 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003547 }
3548#endif
3549
drhda0e7682008-07-30 15:27:54 +00003550 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003551 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003552 }else{
drh0c2694b2009-09-03 16:23:44 +00003553 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00003554#if SQLITE_ENABLE_LOCKING_STYLE
3555 /* Cache zFilename in the locking context (AFP and dotlock override) for
3556 ** proxyLock activation is possible (remote proxy is based on db name)
3557 ** zFilename remains valid until file is closed, to support */
3558 pNew->lockingContext = (void*)zFilename;
3559#endif
drhda0e7682008-07-30 15:27:54 +00003560 }
danielk1977e339d652008-06-28 11:23:00 +00003561
drh7708e972008-11-29 00:56:52 +00003562 if( pLockingStyle == &posixIoMethods ){
3563 unixEnterMutex();
3564 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
dane946c392009-08-22 11:39:46 +00003565 if( rc!=SQLITE_OK ){
3566 /* If an error occured in findLockInfo(), close the file descriptor
3567 ** immediately, before releasing the mutex. findLockInfo() may fail
3568 ** in two scenarios:
3569 **
3570 ** (a) A call to fstat() failed.
3571 ** (b) A malloc failed.
3572 **
3573 ** Scenario (b) may only occur if the process is holding no other
3574 ** file descriptors open on the same file. If there were other file
3575 ** descriptors on this file, then no malloc would be required by
3576 ** findLockInfo(). If this is the case, it is quite safe to close
3577 ** handle h - as it is guaranteed that no posix locks will be released
3578 ** by doing so.
3579 **
3580 ** If scenario (a) caused the error then things are not so safe. The
3581 ** implicit assumption here is that if fstat() fails, things are in
3582 ** such bad shape that dropping a lock or two doesn't matter much.
3583 */
3584 close(h);
3585 h = -1;
3586 }
drh7708e972008-11-29 00:56:52 +00003587 unixLeaveMutex();
3588 }
danielk1977e339d652008-06-28 11:23:00 +00003589
drhd2cb50b2009-01-09 21:41:17 +00003590#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00003591 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00003592 /* AFP locking uses the file path so it needs to be included in
3593 ** the afpLockingContext.
3594 */
3595 afpLockingContext *pCtx;
3596 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3597 if( pCtx==0 ){
3598 rc = SQLITE_NOMEM;
3599 }else{
3600 /* NB: zFilename exists and remains valid until the file is closed
3601 ** according to requirement F11141. So we do not need to make a
3602 ** copy of the filename. */
3603 pCtx->dbPath = zFilename;
3604 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003605 unixEnterMutex();
drh7708e972008-11-29 00:56:52 +00003606 rc = findLockInfo(pNew, NULL, &pNew->pOpen);
3607 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003608 }
drh7708e972008-11-29 00:56:52 +00003609 }
3610#endif
danielk1977e339d652008-06-28 11:23:00 +00003611
drh7708e972008-11-29 00:56:52 +00003612 else if( pLockingStyle == &dotlockIoMethods ){
3613 /* Dotfile locking uses the file path so it needs to be included in
3614 ** the dotlockLockingContext
3615 */
3616 char *zLockFile;
3617 int nFilename;
drhea678832008-12-10 19:26:22 +00003618 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00003619 zLockFile = (char *)sqlite3_malloc(nFilename);
3620 if( zLockFile==0 ){
3621 rc = SQLITE_NOMEM;
3622 }else{
3623 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003624 }
drh7708e972008-11-29 00:56:52 +00003625 pNew->lockingContext = zLockFile;
3626 }
danielk1977e339d652008-06-28 11:23:00 +00003627
drh6c7d5c52008-11-21 20:32:33 +00003628#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003629 else if( pLockingStyle == &semIoMethods ){
3630 /* Named semaphore locking uses the file path so it needs to be
3631 ** included in the semLockingContext
3632 */
3633 unixEnterMutex();
3634 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3635 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3636 char *zSemName = pNew->pOpen->aSemName;
3637 int n;
drh2238dcc2009-08-27 17:56:20 +00003638 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00003639 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00003640 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00003641 if( zSemName[n]=='/' ) zSemName[n] = '_';
3642 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3643 if( pNew->pOpen->pSem == SEM_FAILED ){
3644 rc = SQLITE_NOMEM;
3645 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003646 }
chw97185482008-11-17 08:05:31 +00003647 }
drh7708e972008-11-29 00:56:52 +00003648 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003649 }
drh7708e972008-11-29 00:56:52 +00003650#endif
aswift5b1a2562008-08-22 00:22:35 +00003651
3652 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003653#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003654 if( rc!=SQLITE_OK ){
3655 unlink(zFilename);
3656 isDelete = 0;
3657 }
3658 pNew->isDelete = isDelete;
3659#endif
danielk1977e339d652008-06-28 11:23:00 +00003660 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00003661 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00003662 if( h>=0 ) close(h);
danielk1977e339d652008-06-28 11:23:00 +00003663 }else{
drh7708e972008-11-29 00:56:52 +00003664 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00003665 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00003666 }
danielk1977e339d652008-06-28 11:23:00 +00003667 return rc;
drh054889e2005-11-30 03:20:31 +00003668}
drh9c06c952005-11-26 00:25:00 +00003669
danielk1977ad94b582007-08-20 06:44:22 +00003670/*
3671** Open a file descriptor to the directory containing file zFilename.
3672** If successful, *pFd is set to the opened file descriptor and
3673** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3674** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3675** value.
3676**
3677** If SQLITE_OK is returned, the caller is responsible for closing
3678** the file descriptor *pFd using close().
3679*/
danielk1977fee2d252007-08-18 10:59:19 +00003680static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00003681 int ii;
drh777b17a2007-09-20 10:02:54 +00003682 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00003683 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00003684
drh153c62c2007-08-24 03:51:33 +00003685 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00003686 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00003687 if( ii>0 ){
3688 zDirname[ii] = '\0';
3689 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00003690 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00003691#ifdef FD_CLOEXEC
3692 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3693#endif
3694 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
3695 }
3696 }
danielk1977fee2d252007-08-18 10:59:19 +00003697 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00003698 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00003699}
3700
danielk1977b4b47412007-08-17 15:53:36 +00003701/*
danielk197717b90b52008-06-06 11:11:25 +00003702** Create a temporary file name in zBuf. zBuf must be allocated
3703** by the calling process and must be big enough to hold at least
3704** pVfs->mxPathname bytes.
3705*/
3706static int getTempname(int nBuf, char *zBuf){
3707 static const char *azDirs[] = {
3708 0,
aswiftaebf4132008-11-21 00:10:35 +00003709 0,
danielk197717b90b52008-06-06 11:11:25 +00003710 "/var/tmp",
3711 "/usr/tmp",
3712 "/tmp",
3713 ".",
3714 };
3715 static const unsigned char zChars[] =
3716 "abcdefghijklmnopqrstuvwxyz"
3717 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3718 "0123456789";
drh41022642008-11-21 00:24:42 +00003719 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00003720 struct stat buf;
3721 const char *zDir = ".";
3722
3723 /* It's odd to simulate an io-error here, but really this is just
3724 ** using the io-error infrastructure to test that SQLite handles this
3725 ** function failing.
3726 */
3727 SimulateIOError( return SQLITE_IOERR );
3728
3729 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00003730 if (NULL == azDirs[1]) {
3731 azDirs[1] = getenv("TMPDIR");
3732 }
3733
3734 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00003735 if( azDirs[i]==0 ) continue;
3736 if( stat(azDirs[i], &buf) ) continue;
3737 if( !S_ISDIR(buf.st_mode) ) continue;
3738 if( access(azDirs[i], 07) ) continue;
3739 zDir = azDirs[i];
3740 break;
3741 }
3742
3743 /* Check that the output buffer is large enough for the temporary file
3744 ** name. If it is not, return SQLITE_ERROR.
3745 */
danielk197700e13612008-11-17 19:18:54 +00003746 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00003747 return SQLITE_ERROR;
3748 }
3749
3750 do{
3751 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00003752 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00003753 sqlite3_randomness(15, &zBuf[j]);
3754 for(i=0; i<15; i++, j++){
3755 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3756 }
3757 zBuf[j] = 0;
3758 }while( access(zBuf,0)==0 );
3759 return SQLITE_OK;
3760}
3761
drhd2cb50b2009-01-09 21:41:17 +00003762#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00003763/*
3764** Routine to transform a unixFile into a proxy-locking unixFile.
3765** Implementation in the proxy-lock division, but used by unixOpen()
3766** if SQLITE_PREFER_PROXY_LOCKING is defined.
3767*/
3768static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00003769#endif
drhc66d5b62008-12-03 22:48:32 +00003770
dan08da86a2009-08-21 17:18:03 +00003771/*
3772** Search for an unused file descriptor that was opened on the database
3773** file (not a journal or master-journal file) identified by pathname
3774** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
3775** argument to this function.
3776**
3777** Such a file descriptor may exist if a database connection was closed
3778** but the associated file descriptor could not be closed because some
3779** other file descriptor open on the same file is holding a file-lock.
3780** Refer to comments in the unixClose() function and the lengthy comment
3781** describing "Posix Advisory Locking" at the start of this file for
3782** further details. Also, ticket #4018.
3783**
3784** If a suitable file descriptor is found, then it is returned. If no
3785** such file descriptor is located, -1 is returned.
3786*/
dane946c392009-08-22 11:39:46 +00003787static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
3788 UnixUnusedFd *pUnused = 0;
3789
3790 /* Do not search for an unused file descriptor on vxworks. Not because
3791 ** vxworks would not benefit from the change (it might, we're not sure),
3792 ** but because no way to test it is currently available. It is better
3793 ** not to risk breaking vxworks support for the sake of such an obscure
3794 ** feature. */
3795#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00003796 struct stat sStat; /* Results of stat() call */
3797
3798 /* A stat() call may fail for various reasons. If this happens, it is
3799 ** almost certain that an open() call on the same path will also fail.
3800 ** For this reason, if an error occurs in the stat() call here, it is
3801 ** ignored and -1 is returned. The caller will try to open a new file
3802 ** descriptor on the same path, fail, and return an error to SQLite.
3803 **
3804 ** Even if a subsequent open() call does succeed, the consequences of
3805 ** not searching for a resusable file descriptor are not dire. */
3806 if( 0==stat(zPath, &sStat) ){
drh9061ad12010-01-05 00:14:49 +00003807 struct unixOpenCnt *pOpen;
dan08da86a2009-08-21 17:18:03 +00003808
3809 unixEnterMutex();
drh9061ad12010-01-05 00:14:49 +00003810 pOpen = openList;
3811 while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
3812 || pOpen->fileId.ino!=sStat.st_ino) ){
3813 pOpen = pOpen->pNext;
3814 }
3815 if( pOpen ){
dane946c392009-08-22 11:39:46 +00003816 UnixUnusedFd **pp;
drh9061ad12010-01-05 00:14:49 +00003817 for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00003818 pUnused = *pp;
3819 if( pUnused ){
3820 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00003821 }
3822 }
3823 unixLeaveMutex();
3824 }
dane946c392009-08-22 11:39:46 +00003825#endif /* if !OS_VXWORKS */
3826 return pUnused;
dan08da86a2009-08-21 17:18:03 +00003827}
danielk197717b90b52008-06-06 11:11:25 +00003828
3829/*
danielk1977ad94b582007-08-20 06:44:22 +00003830** Open the file zPath.
3831**
danielk1977b4b47412007-08-17 15:53:36 +00003832** Previously, the SQLite OS layer used three functions in place of this
3833** one:
3834**
3835** sqlite3OsOpenReadWrite();
3836** sqlite3OsOpenReadOnly();
3837** sqlite3OsOpenExclusive();
3838**
3839** These calls correspond to the following combinations of flags:
3840**
3841** ReadWrite() -> (READWRITE | CREATE)
3842** ReadOnly() -> (READONLY)
3843** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
3844**
3845** The old OpenExclusive() accepted a boolean argument - "delFlag". If
3846** true, the file was configured to be automatically deleted when the
3847** file handle closed. To achieve the same effect using this new
3848** interface, add the DELETEONCLOSE flag to those specified above for
3849** OpenExclusive().
3850*/
3851static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00003852 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
3853 const char *zPath, /* Pathname of file to be opened */
3854 sqlite3_file *pFile, /* The file descriptor to be filled in */
3855 int flags, /* Input flags to control the opening */
3856 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00003857){
dan08da86a2009-08-21 17:18:03 +00003858 unixFile *p = (unixFile *)pFile;
3859 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00003860 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00003861 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00003862 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00003863 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00003864 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00003865
3866 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
3867 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
3868 int isCreate = (flags & SQLITE_OPEN_CREATE);
3869 int isReadonly = (flags & SQLITE_OPEN_READONLY);
3870 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
3871
danielk1977fee2d252007-08-18 10:59:19 +00003872 /* If creating a master or main-file journal, this function will open
3873 ** a file-descriptor on the directory too. The first time unixSync()
3874 ** is called the directory file descriptor will be fsync()ed and close()d.
3875 */
3876 int isOpenDirectory = (isCreate &&
3877 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
3878 );
3879
danielk197717b90b52008-06-06 11:11:25 +00003880 /* If argument zPath is a NULL pointer, this function is required to open
3881 ** a temporary file. Use this buffer to store the file name in.
3882 */
3883 char zTmpname[MAX_PATHNAME+1];
3884 const char *zName = zPath;
3885
danielk1977fee2d252007-08-18 10:59:19 +00003886 /* Check the following statements are true:
3887 **
3888 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
3889 ** (b) if CREATE is set, then READWRITE must also be set, and
3890 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00003891 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00003892 */
danielk1977b4b47412007-08-17 15:53:36 +00003893 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00003894 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00003895 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00003896 assert(isDelete==0 || isCreate);
3897
drh33f4e022007-09-03 15:19:34 +00003898 /* The main DB, main journal, and master journal are never automatically
dan08da86a2009-08-21 17:18:03 +00003899 ** deleted. Nor are they ever temporary files. */
3900 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
3901 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
3902 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danielk1977b4b47412007-08-17 15:53:36 +00003903
danielk1977fee2d252007-08-18 10:59:19 +00003904 /* Assert that the upper layer has set one of the "file-type" flags. */
3905 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
3906 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3907 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00003908 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00003909 );
3910
dan08da86a2009-08-21 17:18:03 +00003911 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00003912
dan08da86a2009-08-21 17:18:03 +00003913 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00003914 UnixUnusedFd *pUnused;
3915 pUnused = findReusableFd(zName, flags);
3916 if( pUnused ){
3917 fd = pUnused->fd;
3918 }else{
dan6aa657f2009-08-24 18:57:58 +00003919 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00003920 if( !pUnused ){
3921 return SQLITE_NOMEM;
3922 }
3923 }
3924 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00003925 }else if( !zName ){
3926 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00003927 assert(isDelete && !isOpenDirectory);
3928 rc = getTempname(MAX_PATHNAME+1, zTmpname);
3929 if( rc!=SQLITE_OK ){
3930 return rc;
3931 }
3932 zName = zTmpname;
3933 }
3934
dan08da86a2009-08-21 17:18:03 +00003935 /* Determine the value of the flags parameter passed to POSIX function
3936 ** open(). These must be calculated even if open() is not called, as
3937 ** they may be stored as part of the file handle and used by the
3938 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00003939 if( isReadonly ) openFlags |= O_RDONLY;
3940 if( isReadWrite ) openFlags |= O_RDWR;
3941 if( isCreate ) openFlags |= O_CREAT;
3942 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
3943 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00003944
danielk1977b4b47412007-08-17 15:53:36 +00003945 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00003946 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
3947 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00003948 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
3949 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
3950 /* Failed to open the file for read/write access. Try read-only. */
3951 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00003952 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00003953 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00003954 openFlags |= O_RDONLY;
3955 fd = open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00003956 }
3957 if( fd<0 ){
dane946c392009-08-22 11:39:46 +00003958 rc = SQLITE_CANTOPEN;
3959 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00003960 }
danielk1977b4b47412007-08-17 15:53:36 +00003961 }
dan08da86a2009-08-21 17:18:03 +00003962 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00003963 if( pOutFlags ){
3964 *pOutFlags = flags;
3965 }
3966
dane946c392009-08-22 11:39:46 +00003967 if( p->pUnused ){
3968 p->pUnused->fd = fd;
3969 p->pUnused->flags = flags;
3970 }
3971
danielk1977b4b47412007-08-17 15:53:36 +00003972 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00003973#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003974 zPath = zName;
3975#else
danielk197717b90b52008-06-06 11:11:25 +00003976 unlink(zName);
chw97185482008-11-17 08:05:31 +00003977#endif
danielk1977b4b47412007-08-17 15:53:36 +00003978 }
drh41022642008-11-21 00:24:42 +00003979#if SQLITE_ENABLE_LOCKING_STYLE
3980 else{
dan08da86a2009-08-21 17:18:03 +00003981 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00003982 }
3983#endif
3984
danielk1977fee2d252007-08-18 10:59:19 +00003985 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00003986 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00003987 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00003988 /* It is safe to close fd at this point, because it is guaranteed not
3989 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00003990 ** it would not be safe to close as this would release any locks held
3991 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00003992 assert( eType!=SQLITE_OPEN_MAIN_DB );
3993 close(fd); /* silently leak if fail, already in error */
dane946c392009-08-22 11:39:46 +00003994 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00003995 }
3996 }
danielk1977e339d652008-06-28 11:23:00 +00003997
3998#ifdef FD_CLOEXEC
3999 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4000#endif
4001
drhda0e7682008-07-30 15:27:54 +00004002 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004003
4004#if SQLITE_PREFER_PROXY_LOCKING
dan15edd582009-08-25 05:57:47 +00004005 if( zPath!=NULL && !noLock && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00004006 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4007 int useProxy = 0;
4008
dan08da86a2009-08-21 17:18:03 +00004009 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4010 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00004011 if( envforce!=NULL ){
4012 useProxy = atoi(envforce)>0;
4013 }else{
4014 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00004015 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00004016 /* In theory, the close(fd) call is sub-optimal. If the file opened
4017 ** with fd is a database file, and there are other connections open
4018 ** on that file that are currently holding advisory locks on it,
4019 ** then the call to close() will cancel those locks. In practice,
4020 ** we're assuming that statfs() doesn't fail very often. At least
4021 ** not while other file descriptors opened by the same process on
4022 ** the same file are working. */
4023 p->lastErrno = errno;
4024 if( dirfd>=0 ){
4025 close(dirfd); /* silently leak if fail, in error */
4026 }
aswiftaebf4132008-11-21 00:10:35 +00004027 close(fd); /* silently leak if fail, in error */
dane946c392009-08-22 11:39:46 +00004028 rc = SQLITE_IOERR_ACCESS;
4029 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004030 }
4031 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4032 }
4033 if( useProxy ){
4034 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4035 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00004036 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
aswiftaebf4132008-11-21 00:10:35 +00004037 }
dane946c392009-08-22 11:39:46 +00004038 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00004039 }
4040 }
4041#endif
4042
dane946c392009-08-22 11:39:46 +00004043 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4044open_finished:
4045 if( rc!=SQLITE_OK ){
4046 sqlite3_free(p->pUnused);
4047 }
4048 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004049}
4050
dane946c392009-08-22 11:39:46 +00004051
danielk1977b4b47412007-08-17 15:53:36 +00004052/*
danielk1977fee2d252007-08-18 10:59:19 +00004053** Delete the file at zPath. If the dirSync argument is true, fsync()
4054** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004055*/
drh6b9d6dd2008-12-03 19:34:47 +00004056static int unixDelete(
4057 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4058 const char *zPath, /* Name of file to be deleted */
4059 int dirSync /* If true, fsync() directory after deleting file */
4060){
danielk1977fee2d252007-08-18 10:59:19 +00004061 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004062 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004063 SimulateIOError(return SQLITE_IOERR_DELETE);
4064 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00004065#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004066 if( dirSync ){
4067 int fd;
4068 rc = openDirectory(zPath, &fd);
4069 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004070#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004071 if( fsync(fd)==-1 )
4072#else
4073 if( fsync(fd) )
4074#endif
4075 {
danielk1977fee2d252007-08-18 10:59:19 +00004076 rc = SQLITE_IOERR_DIR_FSYNC;
4077 }
aswiftaebf4132008-11-21 00:10:35 +00004078 if( close(fd)&&!rc ){
4079 rc = SQLITE_IOERR_DIR_CLOSE;
4080 }
danielk1977fee2d252007-08-18 10:59:19 +00004081 }
4082 }
danielk1977d138dd82008-10-15 16:02:48 +00004083#endif
danielk1977fee2d252007-08-18 10:59:19 +00004084 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004085}
4086
danielk197790949c22007-08-17 16:50:38 +00004087/*
4088** Test the existance of or access permissions of file zPath. The
4089** test performed depends on the value of flags:
4090**
4091** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4092** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4093** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4094**
4095** Otherwise return 0.
4096*/
danielk1977861f7452008-06-05 11:39:11 +00004097static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00004098 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
4099 const char *zPath, /* Path of the file to examine */
4100 int flags, /* What do we want to learn about the zPath file? */
4101 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00004102){
rse25c0d1a2007-09-20 08:38:14 +00004103 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004104 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004105 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004106 switch( flags ){
4107 case SQLITE_ACCESS_EXISTS:
4108 amode = F_OK;
4109 break;
4110 case SQLITE_ACCESS_READWRITE:
4111 amode = W_OK|R_OK;
4112 break;
drh50d3f902007-08-27 21:10:36 +00004113 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004114 amode = R_OK;
4115 break;
4116
4117 default:
4118 assert(!"Invalid flags argument");
4119 }
danielk1977861f7452008-06-05 11:39:11 +00004120 *pResOut = (access(zPath, amode)==0);
4121 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004122}
4123
danielk1977b4b47412007-08-17 15:53:36 +00004124
4125/*
4126** Turn a relative pathname into a full pathname. The relative path
4127** is stored as a nul-terminated string in the buffer pointed to by
4128** zPath.
4129**
4130** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4131** (in this case, MAX_PATHNAME bytes). The full-path is written to
4132** this buffer before returning.
4133*/
danielk1977adfb9b02007-09-17 07:02:56 +00004134static int unixFullPathname(
4135 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4136 const char *zPath, /* Possibly relative input path */
4137 int nOut, /* Size of output buffer in bytes */
4138 char *zOut /* Output buffer */
4139){
danielk1977843e65f2007-09-01 16:16:15 +00004140
4141 /* It's odd to simulate an io-error here, but really this is just
4142 ** using the io-error infrastructure to test that SQLite handles this
4143 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00004144 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00004145 */
4146 SimulateIOError( return SQLITE_ERROR );
4147
drh153c62c2007-08-24 03:51:33 +00004148 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004149 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004150
drh3c7f2dc2007-12-06 13:26:20 +00004151 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004152 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004153 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004154 }else{
4155 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004156 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00004157 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00004158 }
drhea678832008-12-10 19:26:22 +00004159 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004160 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004161 }
4162 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004163}
4164
drh0ccebe72005-06-07 22:22:50 +00004165
drh761df872006-12-21 01:29:22 +00004166#ifndef SQLITE_OMIT_LOAD_EXTENSION
4167/*
4168** Interfaces for opening a shared library, finding entry points
4169** within the shared library, and closing the shared library.
4170*/
4171#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004172static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4173 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004174 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4175}
danielk197795c8a542007-09-01 06:51:27 +00004176
4177/*
4178** SQLite calls this function immediately after a call to unixDlSym() or
4179** unixDlOpen() fails (returns a null pointer). If a more detailed error
4180** message is available, it is written to zBufOut. If no error message
4181** is available, zBufOut is left unmodified and SQLite uses a default
4182** error message.
4183*/
danielk1977397d65f2008-11-19 11:35:39 +00004184static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004185 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004186 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004187 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004188 zErr = dlerror();
4189 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004190 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004191 }
drh6c7d5c52008-11-21 20:32:33 +00004192 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004193}
drh1875f7a2008-12-08 18:19:17 +00004194static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
4195 /*
4196 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
4197 ** cast into a pointer to a function. And yet the library dlsym() routine
4198 ** returns a void* which is really a pointer to a function. So how do we
4199 ** use dlsym() with -pedantic-errors?
4200 **
4201 ** Variable x below is defined to be a pointer to a function taking
4202 ** parameters void* and const char* and returning a pointer to a function.
4203 ** We initialize x by assigning it a pointer to the dlsym() function.
4204 ** (That assignment requires a cast.) Then we call the function that
4205 ** x points to.
4206 **
4207 ** This work-around is unlikely to work correctly on any system where
4208 ** you really cannot cast a function pointer into void*. But then, on the
4209 ** other hand, dlsym() will not work on such a system either, so we have
4210 ** not really lost anything.
4211 */
4212 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00004213 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00004214 x = (void(*(*)(void*,const char*))(void))dlsym;
4215 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00004216}
danielk1977397d65f2008-11-19 11:35:39 +00004217static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4218 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004219 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004220}
danielk1977b4b47412007-08-17 15:53:36 +00004221#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4222 #define unixDlOpen 0
4223 #define unixDlError 0
4224 #define unixDlSym 0
4225 #define unixDlClose 0
4226#endif
4227
4228/*
danielk197790949c22007-08-17 16:50:38 +00004229** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004230*/
danielk1977397d65f2008-11-19 11:35:39 +00004231static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4232 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004233 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004234
drhbbd42a62004-05-22 17:41:58 +00004235 /* We have to initialize zBuf to prevent valgrind from reporting
4236 ** errors. The reports issued by valgrind are incorrect - we would
4237 ** prefer that the randomness be increased by making use of the
4238 ** uninitialized space in zBuf - but valgrind errors tend to worry
4239 ** some users. Rather than argue, it seems easier just to initialize
4240 ** the whole array and silence valgrind, even if that means less randomness
4241 ** in the random seed.
4242 **
4243 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004244 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004245 ** tests repeatable.
4246 */
danielk1977b4b47412007-08-17 15:53:36 +00004247 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004248#if !defined(SQLITE_TEST)
4249 {
drh842b8642005-01-21 17:53:17 +00004250 int pid, fd;
4251 fd = open("/dev/urandom", O_RDONLY);
4252 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004253 time_t t;
4254 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004255 memcpy(zBuf, &t, sizeof(t));
4256 pid = getpid();
4257 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004258 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004259 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004260 }else{
drh72cbd072008-10-14 17:58:38 +00004261 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004262 close(fd);
4263 }
drhbbd42a62004-05-22 17:41:58 +00004264 }
4265#endif
drh72cbd072008-10-14 17:58:38 +00004266 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004267}
4268
danielk1977b4b47412007-08-17 15:53:36 +00004269
drhbbd42a62004-05-22 17:41:58 +00004270/*
4271** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004272** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004273** The return value is the number of microseconds of sleep actually
4274** requested from the underlying operating system, a number which
4275** might be greater than or equal to the argument, but not less
4276** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004277*/
danielk1977397d65f2008-11-19 11:35:39 +00004278static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004279#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004280 struct timespec sp;
4281
4282 sp.tv_sec = microseconds / 1000000;
4283 sp.tv_nsec = (microseconds % 1000000) * 1000;
4284 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00004285 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00004286 return microseconds;
4287#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004288 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00004289 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004290 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004291#else
danielk1977b4b47412007-08-17 15:53:36 +00004292 int seconds = (microseconds+999999)/1000000;
4293 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00004294 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00004295 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004296#endif
drh88f474a2006-01-02 20:00:12 +00004297}
4298
4299/*
drh6b9d6dd2008-12-03 19:34:47 +00004300** The following variable, if set to a non-zero value, is interpreted as
4301** the number of seconds since 1970 and is used to set the result of
4302** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00004303*/
4304#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00004305int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00004306#endif
4307
4308/*
4309** Find the current time (in Universal Coordinated Time). Write the
4310** current time and date as a Julian Day number into *prNow and
4311** return 0. Return 1 if the time and date cannot be found.
4312*/
danielk1977397d65f2008-11-19 11:35:39 +00004313static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh0b3bf922009-06-15 20:45:34 +00004314#if defined(SQLITE_OMIT_FLOATING_POINT)
4315 time_t t;
4316 time(&t);
4317 *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
4318#elif defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00004319 time_t t;
4320 time(&t);
4321 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00004322#elif OS_VXWORKS
4323 struct timespec sNow;
4324 clock_gettime(CLOCK_REALTIME, &sNow);
4325 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00004326#else
4327 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00004328 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00004329 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
4330#endif
danielk1977397d65f2008-11-19 11:35:39 +00004331
drhbbd42a62004-05-22 17:41:58 +00004332#ifdef SQLITE_TEST
4333 if( sqlite3_current_time ){
4334 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4335 }
4336#endif
danielk1977397d65f2008-11-19 11:35:39 +00004337 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004338 return 0;
4339}
danielk1977b4b47412007-08-17 15:53:36 +00004340
drh6b9d6dd2008-12-03 19:34:47 +00004341/*
4342** We added the xGetLastError() method with the intention of providing
4343** better low-level error messages when operating-system problems come up
4344** during SQLite operation. But so far, none of that has been implemented
4345** in the core. So this routine is never called. For now, it is merely
4346** a place-holder.
4347*/
danielk1977397d65f2008-11-19 11:35:39 +00004348static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4349 UNUSED_PARAMETER(NotUsed);
4350 UNUSED_PARAMETER(NotUsed2);
4351 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004352 return 0;
4353}
4354
drh153c62c2007-08-24 03:51:33 +00004355/*
drh734c9862008-11-28 15:37:20 +00004356************************ End of sqlite3_vfs methods ***************************
4357******************************************************************************/
4358
drh715ff302008-12-03 22:32:44 +00004359/******************************************************************************
4360************************** Begin Proxy Locking ********************************
4361**
4362** Proxy locking is a "uber-locking-method" in this sense: It uses the
4363** other locking methods on secondary lock files. Proxy locking is a
4364** meta-layer over top of the primitive locking implemented above. For
4365** this reason, the division that implements of proxy locking is deferred
4366** until late in the file (here) after all of the other I/O methods have
4367** been defined - so that the primitive locking methods are available
4368** as services to help with the implementation of proxy locking.
4369**
4370****
4371**
4372** The default locking schemes in SQLite use byte-range locks on the
4373** database file to coordinate safe, concurrent access by multiple readers
4374** and writers [http://sqlite.org/lockingv3.html]. The five file locking
4375** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
4376** as POSIX read & write locks over fixed set of locations (via fsctl),
4377** on AFP and SMB only exclusive byte-range locks are available via fsctl
4378** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
4379** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
4380** address in the shared range is taken for a SHARED lock, the entire
4381** shared range is taken for an EXCLUSIVE lock):
4382**
4383** PENDING_BYTE 0x40000000
4384** RESERVED_BYTE 0x40000001
4385** SHARED_RANGE 0x40000002 -> 0x40000200
4386**
4387** This works well on the local file system, but shows a nearly 100x
4388** slowdown in read performance on AFP because the AFP client disables
4389** the read cache when byte-range locks are present. Enabling the read
4390** cache exposes a cache coherency problem that is present on all OS X
4391** supported network file systems. NFS and AFP both observe the
4392** close-to-open semantics for ensuring cache coherency
4393** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
4394** address the requirements for concurrent database access by multiple
4395** readers and writers
4396** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
4397**
4398** To address the performance and cache coherency issues, proxy file locking
4399** changes the way database access is controlled by limiting access to a
4400** single host at a time and moving file locks off of the database file
4401** and onto a proxy file on the local file system.
4402**
4403**
4404** Using proxy locks
4405** -----------------
4406**
4407** C APIs
4408**
4409** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
4410** <proxy_path> | ":auto:");
4411** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
4412**
4413**
4414** SQL pragmas
4415**
4416** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
4417** PRAGMA [database.]lock_proxy_file
4418**
4419** Specifying ":auto:" means that if there is a conch file with a matching
4420** host ID in it, the proxy path in the conch file will be used, otherwise
4421** a proxy path based on the user's temp dir
4422** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
4423** actual proxy file name is generated from the name and path of the
4424** database file. For example:
4425**
4426** For database path "/Users/me/foo.db"
4427** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
4428**
4429** Once a lock proxy is configured for a database connection, it can not
4430** be removed, however it may be switched to a different proxy path via
4431** the above APIs (assuming the conch file is not being held by another
4432** connection or process).
4433**
4434**
4435** How proxy locking works
4436** -----------------------
4437**
4438** Proxy file locking relies primarily on two new supporting files:
4439**
4440** * conch file to limit access to the database file to a single host
4441** at a time
4442**
4443** * proxy file to act as a proxy for the advisory locks normally
4444** taken on the database
4445**
4446** The conch file - to use a proxy file, sqlite must first "hold the conch"
4447** by taking an sqlite-style shared lock on the conch file, reading the
4448** contents and comparing the host's unique host ID (see below) and lock
4449** proxy path against the values stored in the conch. The conch file is
4450** stored in the same directory as the database file and the file name
4451** is patterned after the database file name as ".<databasename>-conch".
4452** If the conch file does not exist, or it's contents do not match the
4453** host ID and/or proxy path, then the lock is escalated to an exclusive
4454** lock and the conch file contents is updated with the host ID and proxy
4455** path and the lock is downgraded to a shared lock again. If the conch
4456** is held by another process (with a shared lock), the exclusive lock
4457** will fail and SQLITE_BUSY is returned.
4458**
4459** The proxy file - a single-byte file used for all advisory file locks
4460** normally taken on the database file. This allows for safe sharing
4461** of the database file for multiple readers and writers on the same
4462** host (the conch ensures that they all use the same local lock file).
4463**
4464** There is a third file - the host ID file - used as a persistent record
4465** of a unique identifier for the host, a 128-byte unique host id file
4466** in the path defined by the HOSTIDPATH macro (default value is
4467** /Library/Caches/.com.apple.sqliteConchHostId).
4468**
4469** Requesting the lock proxy does not immediately take the conch, it is
4470** only taken when the first request to lock database file is made.
4471** This matches the semantics of the traditional locking behavior, where
4472** opening a connection to a database file does not take a lock on it.
4473** The shared lock and an open file descriptor are maintained until
4474** the connection to the database is closed.
4475**
4476** The proxy file and the lock file are never deleted so they only need
4477** to be created the first time they are used.
4478**
4479** Configuration options
4480** ---------------------
4481**
4482** SQLITE_PREFER_PROXY_LOCKING
4483**
4484** Database files accessed on non-local file systems are
4485** automatically configured for proxy locking, lock files are
4486** named automatically using the same logic as
4487** PRAGMA lock_proxy_file=":auto:"
4488**
4489** SQLITE_PROXY_DEBUG
4490**
4491** Enables the logging of error messages during host id file
4492** retrieval and creation
4493**
4494** HOSTIDPATH
4495**
4496** Overrides the default host ID file path location
4497**
4498** LOCKPROXYDIR
4499**
4500** Overrides the default directory used for lock proxy files that
4501** are named automatically via the ":auto:" setting
4502**
4503** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4504**
4505** Permissions to use when creating a directory for storing the
4506** lock proxy files, only used when LOCKPROXYDIR is not set.
4507**
4508**
4509** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4510** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4511** force proxy locking to be used for every database file opened, and 0
4512** will force automatic proxy locking to be disabled for all database
4513** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4514** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4515*/
4516
4517/*
4518** Proxy locking is only available on MacOSX
4519*/
drhd2cb50b2009-01-09 21:41:17 +00004520#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004521
4522#ifdef SQLITE_TEST
4523/* simulate multiple hosts by creating unique hostid file paths */
4524int sqlite3_hostid_num = 0;
4525#endif
4526
4527/*
4528** The proxyLockingContext has the path and file structures for the remote
4529** and local proxy files in it
4530*/
4531typedef struct proxyLockingContext proxyLockingContext;
4532struct proxyLockingContext {
4533 unixFile *conchFile; /* Open conch file */
4534 char *conchFilePath; /* Name of the conch file */
4535 unixFile *lockProxy; /* Open proxy lock file */
4536 char *lockProxyPath; /* Name of the proxy lock file */
4537 char *dbPath; /* Name of the open file */
4538 int conchHeld; /* True if the conch is currently held */
4539 void *oldLockingContext; /* Original lockingcontext to restore on close */
4540 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4541};
4542
4543/* HOSTIDLEN and CONCHLEN both include space for the string
4544** terminating nul
4545*/
4546#define HOSTIDLEN 128
4547#define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
4548#ifndef HOSTIDPATH
4549# define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
4550#endif
4551
4552/* basically a copy of unixRandomness with different
4553** test behavior built in */
4554static int proxyGenerateHostID(char *pHostID){
4555 int pid, fd, len;
4556 unsigned char *key = (unsigned char *)pHostID;
4557
4558 memset(key, 0, HOSTIDLEN);
4559 len = 0;
4560 fd = open("/dev/urandom", O_RDONLY);
4561 if( fd>=0 ){
4562 len = read(fd, key, HOSTIDLEN);
4563 close(fd); /* silently leak the fd if it fails */
4564 }
4565 if( len < HOSTIDLEN ){
4566 time_t t;
4567 time(&t);
4568 memcpy(key, &t, sizeof(t));
4569 pid = getpid();
4570 memcpy(&key[sizeof(t)], &pid, sizeof(pid));
4571 }
4572
4573#ifdef MAKE_PRETTY_HOSTID
4574 {
4575 int i;
4576 /* filter the bytes into printable ascii characters and NUL terminate */
4577 key[(HOSTIDLEN-1)] = 0x00;
4578 for( i=0; i<(HOSTIDLEN-1); i++ ){
4579 unsigned char pa = key[i]&0x7F;
4580 if( pa<0x20 ){
4581 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
4582 }else if( pa==0x7F ){
4583 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
4584 }
4585 }
4586 }
4587#endif
4588 return SQLITE_OK;
4589}
4590
4591/* writes the host id path to path, path should be an pre-allocated buffer
4592** with enough space for a path
4593*/
4594static void proxyGetHostIDPath(char *path, size_t len){
4595 strlcpy(path, HOSTIDPATH, len);
4596#ifdef SQLITE_TEST
4597 if( sqlite3_hostid_num>0 ){
4598 char suffix[2] = "1";
4599 suffix[0] = suffix[0] + sqlite3_hostid_num;
4600 strlcat(path, suffix, len);
4601 }
4602#endif
4603 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
4604}
4605
4606/* get the host ID from a sqlite hostid file stored in the
4607** user-specific tmp directory, create the ID if it's not there already
4608*/
4609static int proxyGetHostID(char *pHostID, int *pError){
4610 int fd;
4611 char path[MAXPATHLEN];
4612 size_t len;
4613 int rc=SQLITE_OK;
4614
4615 proxyGetHostIDPath(path, MAXPATHLEN);
4616 /* try to create the host ID file, if it already exists read the contents */
4617 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
4618 if( fd<0 ){
4619 int err=errno;
4620
4621 if( err!=EEXIST ){
4622#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4623 fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
4624 path, strerror(err));
4625#endif
4626 return SQLITE_PERM;
4627 }
4628 /* couldn't create the file, read it instead */
4629 fd = open(path, O_RDONLY|O_EXCL);
4630 if( fd<0 ){
4631#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4632 int err = errno;
4633 fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
4634 path, strerror(err));
4635#endif
4636 return SQLITE_PERM;
4637 }
4638 len = pread(fd, pHostID, HOSTIDLEN, 0);
4639 if( len<0 ){
4640 *pError = errno;
4641 rc = SQLITE_IOERR_READ;
4642 }else if( len<HOSTIDLEN ){
4643 *pError = 0;
4644 rc = SQLITE_IOERR_SHORT_READ;
4645 }
4646 close(fd); /* silently leak the fd if it fails */
4647 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
4648 return rc;
4649 }else{
4650 /* we're creating the host ID file (use a random string of bytes) */
4651 proxyGenerateHostID(pHostID);
4652 len = pwrite(fd, pHostID, HOSTIDLEN, 0);
4653 if( len<0 ){
4654 *pError = errno;
4655 rc = SQLITE_IOERR_WRITE;
4656 }else if( len<HOSTIDLEN ){
4657 *pError = 0;
4658 rc = SQLITE_IOERR_WRITE;
4659 }
4660 close(fd); /* silently leak the fd if it fails */
4661 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
4662 return rc;
4663 }
4664}
4665
4666static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4667 int len;
4668 int dbLen;
4669 int i;
4670
4671#ifdef LOCKPROXYDIR
4672 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4673#else
4674# ifdef _CS_DARWIN_USER_TEMP_DIR
4675 {
4676 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
drh9061ad12010-01-05 00:14:49 +00004677 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00004678 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
4679 /* if mkdir fails, handle as lock file creation failure */
drh715ff302008-12-03 22:32:44 +00004680# ifdef SQLITE_DEBUG
danielk197750c55a92009-05-08 11:34:37 +00004681 int err = errno;
drh715ff302008-12-03 22:32:44 +00004682 if( err!=EEXIST ){
4683 fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
4684 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
4685 }
4686# endif
4687 }else{
4688 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
4689 }
4690
4691 }
4692# else
4693 len = strlcpy(lPath, "/tmp/", maxLen);
4694# endif
4695#endif
4696
4697 if( lPath[len-1]!='/' ){
4698 len = strlcat(lPath, "/", maxLen);
4699 }
4700
4701 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00004702 dbLen = (int)strlen(dbPath);
drh715ff302008-12-03 22:32:44 +00004703 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
4704 char c = dbPath[i];
4705 lPath[i+len] = (c=='/')?'_':c;
4706 }
4707 lPath[i+len]='\0';
4708 strlcat(lPath, ":auto:", maxLen);
4709 return SQLITE_OK;
4710}
4711
4712/*
4713** Create a new VFS file descriptor (stored in memory obtained from
4714** sqlite3_malloc) and open the file named "path" in the file descriptor.
4715**
4716** The caller is responsible not only for closing the file descriptor
4717** but also for freeing the memory associated with the file descriptor.
4718*/
4719static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
drh715ff302008-12-03 22:32:44 +00004720 unixFile *pNew;
dan15edd582009-08-25 05:57:47 +00004721 int flags = SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
drh715ff302008-12-03 22:32:44 +00004722 int rc = SQLITE_OK;
4723 sqlite3_vfs dummyVfs;
4724
drh715ff302008-12-03 22:32:44 +00004725 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
dan15edd582009-08-25 05:57:47 +00004726 if( !pNew ){
4727 return SQLITE_NOMEM;
drh715ff302008-12-03 22:32:44 +00004728 }
4729 memset(pNew, 0, sizeof(unixFile));
4730
dan15edd582009-08-25 05:57:47 +00004731 /* Call unixOpen() to open the proxy file. The flags passed to unixOpen()
4732 ** suggest that the file being opened is a "main database". This is
4733 ** necessary as other file types do not necessarily support locking. It
4734 ** is better to use unixOpen() instead of opening the file directly with
4735 ** open(), as unixOpen() sets up the various mechanisms required to
4736 ** make sure a call to close() does not cause the system to discard
4737 ** POSIX locks prematurely.
4738 **
4739 ** It is important that the xOpen member of the VFS object passed to
4740 ** unixOpen() is NULL. This tells unixOpen() may try to open a proxy-file
4741 ** for the proxy-file (creating a potential infinite loop).
4742 */
drh1875f7a2008-12-08 18:19:17 +00004743 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan15edd582009-08-25 05:57:47 +00004744 dummyVfs.xOpen = 0;
4745 rc = unixOpen(&dummyVfs, path, (sqlite3_file *)pNew, flags, &flags);
4746 if( rc==SQLITE_OK && (flags&SQLITE_OPEN_READONLY) ){
4747 pNew->pMethod->xClose((sqlite3_file *)pNew);
4748 rc = SQLITE_CANTOPEN;
drh715ff302008-12-03 22:32:44 +00004749 }
dan15edd582009-08-25 05:57:47 +00004750
4751 if( rc!=SQLITE_OK ){
4752 sqlite3_free(pNew);
4753 pNew = 0;
4754 }
4755
4756 *ppFile = pNew;
drh715ff302008-12-03 22:32:44 +00004757 return rc;
4758}
4759
4760/* takes the conch by taking a shared lock and read the contents conch, if
4761** lockPath is non-NULL, the host ID and lock file path must match. A NULL
4762** lockPath means that the lockPath in the conch file will be used if the
4763** host IDs match, or a new lock path will be generated automatically
4764** and written to the conch file.
4765*/
4766static int proxyTakeConch(unixFile *pFile){
4767 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4768
4769 if( pCtx->conchHeld>0 ){
4770 return SQLITE_OK;
4771 }else{
4772 unixFile *conchFile = pCtx->conchFile;
4773 char testValue[CONCHLEN];
4774 char conchValue[CONCHLEN];
4775 char lockPath[MAXPATHLEN];
4776 char *tLockPath = NULL;
4777 int rc = SQLITE_OK;
4778 int readRc = SQLITE_OK;
4779 int syncPerms = 0;
4780
4781 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
4782 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
4783
4784 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
4785 if( rc==SQLITE_OK ){
4786 int pError = 0;
drh1875f7a2008-12-08 18:19:17 +00004787 memset(testValue, 0, CONCHLEN); /* conch is fixed size */
drh715ff302008-12-03 22:32:44 +00004788 rc = proxyGetHostID(testValue, &pError);
4789 if( (rc&0xff)==SQLITE_IOERR ){
4790 pFile->lastErrno = pError;
4791 }
4792 if( pCtx->lockProxyPath ){
4793 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
4794 }
4795 }
4796 if( rc!=SQLITE_OK ){
4797 goto end_takeconch;
4798 }
4799
4800 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
4801 if( readRc!=SQLITE_IOERR_SHORT_READ ){
4802 if( readRc!=SQLITE_OK ){
4803 if( (rc&0xff)==SQLITE_IOERR ){
4804 pFile->lastErrno = conchFile->lastErrno;
4805 }
4806 rc = readRc;
4807 goto end_takeconch;
4808 }
4809 /* if the conch has data compare the contents */
4810 if( !pCtx->lockProxyPath ){
4811 /* for auto-named local lock file, just check the host ID and we'll
4812 ** use the local lock file path that's already in there */
4813 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
4814 tLockPath = (char *)&conchValue[HOSTIDLEN];
4815 goto end_takeconch;
4816 }
4817 }else{
4818 /* we've got the conch if conchValue matches our path and host ID */
4819 if( !memcmp(testValue, conchValue, CONCHLEN) ){
4820 goto end_takeconch;
4821 }
4822 }
4823 }else{
4824 /* a short read means we're "creating" the conch (even though it could
4825 ** have been user-intervention), if we acquire the exclusive lock,
4826 ** we'll try to match the current on-disk permissions of the database
4827 */
4828 syncPerms = 1;
4829 }
4830
4831 /* either conch was emtpy or didn't match */
4832 if( !pCtx->lockProxyPath ){
4833 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
4834 tLockPath = lockPath;
4835 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
4836 }
4837
4838 /* update conch with host and path (this will fail if other process
4839 ** has a shared lock already) */
4840 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
4841 if( rc==SQLITE_OK ){
4842 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
4843 if( rc==SQLITE_OK && syncPerms ){
4844 struct stat buf;
4845 int err = fstat(pFile->h, &buf);
4846 if( err==0 ){
4847 /* try to match the database file permissions, ignore failure */
4848#ifndef SQLITE_PROXY_DEBUG
4849 fchmod(conchFile->h, buf.st_mode);
4850#else
4851 if( fchmod(conchFile->h, buf.st_mode)!=0 ){
4852 int code = errno;
4853 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
4854 buf.st_mode, code, strerror(code));
4855 } else {
4856 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
4857 }
4858 }else{
4859 int code = errno;
4860 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
4861 err, code, strerror(code));
4862#endif
4863 }
4864 }
4865 }
4866 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
4867
4868end_takeconch:
4869 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
4870 if( rc==SQLITE_OK && pFile->openFlags ){
4871 if( pFile->h>=0 ){
4872#ifdef STRICT_CLOSE_ERROR
4873 if( close(pFile->h) ){
4874 pFile->lastErrno = errno;
4875 return SQLITE_IOERR_CLOSE;
4876 }
4877#else
4878 close(pFile->h); /* silently leak fd if fail */
4879#endif
4880 }
4881 pFile->h = -1;
4882 int fd = open(pCtx->dbPath, pFile->openFlags,
4883 SQLITE_DEFAULT_FILE_PERMISSIONS);
4884 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
4885 if( fd>=0 ){
4886 pFile->h = fd;
4887 }else{
drh1875f7a2008-12-08 18:19:17 +00004888 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
4889 during locking */
drh715ff302008-12-03 22:32:44 +00004890 }
4891 }
4892 if( rc==SQLITE_OK && !pCtx->lockProxy ){
4893 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
drh1875f7a2008-12-08 18:19:17 +00004894 /* ACS: Need to make a copy of path sometimes */
drh715ff302008-12-03 22:32:44 +00004895 rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
4896 }
4897 if( rc==SQLITE_OK ){
4898 pCtx->conchHeld = 1;
4899
4900 if( tLockPath ){
4901 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
4902 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
4903 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
4904 pCtx->lockProxyPath;
4905 }
4906 }
4907 } else {
4908 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4909 }
4910 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
4911 return rc;
4912 }
4913}
4914
4915/*
4916** If pFile holds a lock on a conch file, then release that lock.
4917*/
4918static int proxyReleaseConch(unixFile *pFile){
4919 int rc; /* Subroutine return code */
4920 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
4921 unixFile *conchFile; /* Name of the conch file */
4922
4923 pCtx = (proxyLockingContext *)pFile->lockingContext;
4924 conchFile = pCtx->conchFile;
4925 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
4926 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
4927 getpid());
4928 pCtx->conchHeld = 0;
4929 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4930 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
4931 (rc==SQLITE_OK ? "ok" : "failed"));
4932 return rc;
4933}
4934
4935/*
4936** Given the name of a database file, compute the name of its conch file.
4937** Store the conch filename in memory obtained from sqlite3_malloc().
4938** Make *pConchPath point to the new name. Return SQLITE_OK on success
4939** or SQLITE_NOMEM if unable to obtain memory.
4940**
4941** The caller is responsible for ensuring that the allocated memory
4942** space is eventually freed.
4943**
4944** *pConchPath is set to NULL if a memory allocation error occurs.
4945*/
4946static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
4947 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00004948 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00004949 char *conchPath; /* buffer in which to construct conch name */
4950
4951 /* Allocate space for the conch filename and initialize the name to
4952 ** the name of the original database file. */
4953 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
4954 if( conchPath==0 ){
4955 return SQLITE_NOMEM;
4956 }
4957 memcpy(conchPath, dbPath, len+1);
4958
4959 /* now insert a "." before the last / character */
4960 for( i=(len-1); i>=0; i-- ){
4961 if( conchPath[i]=='/' ){
4962 i++;
4963 break;
4964 }
4965 }
4966 conchPath[i]='.';
4967 while ( i<len ){
4968 conchPath[i+1]=dbPath[i];
4969 i++;
4970 }
4971
4972 /* append the "-conch" suffix to the file */
4973 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00004974 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00004975
4976 return SQLITE_OK;
4977}
4978
4979
4980/* Takes a fully configured proxy locking-style unix file and switches
4981** the local lock file path
4982*/
4983static int switchLockProxyPath(unixFile *pFile, const char *path) {
4984 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4985 char *oldPath = pCtx->lockProxyPath;
4986 int rc = SQLITE_OK;
4987
4988 if( pFile->locktype!=NO_LOCK ){
4989 return SQLITE_BUSY;
4990 }
4991
4992 /* nothing to do if the path is NULL, :auto: or matches the existing path */
4993 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
4994 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
4995 return SQLITE_OK;
4996 }else{
4997 unixFile *lockProxy = pCtx->lockProxy;
4998 pCtx->lockProxy=NULL;
4999 pCtx->conchHeld = 0;
5000 if( lockProxy!=NULL ){
5001 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
5002 if( rc ) return rc;
5003 sqlite3_free(lockProxy);
5004 }
5005 sqlite3_free(oldPath);
5006 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
5007 }
5008
5009 return rc;
5010}
5011
5012/*
5013** pFile is a file that has been opened by a prior xOpen call. dbPath
5014** is a string buffer at least MAXPATHLEN+1 characters in size.
5015**
5016** This routine find the filename associated with pFile and writes it
5017** int dbPath.
5018*/
5019static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00005020#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00005021 if( pFile->pMethod == &afpIoMethods ){
5022 /* afp style keeps a reference to the db path in the filePath field
5023 ** of the struct */
drhea678832008-12-10 19:26:22 +00005024 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh715ff302008-12-03 22:32:44 +00005025 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
5026 }else
5027#endif
5028 if( pFile->pMethod == &dotlockIoMethods ){
5029 /* dot lock style uses the locking context to store the dot lock
5030 ** file path */
5031 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5032 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5033 }else{
5034 /* all other styles use the locking context to store the db file path */
5035 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
5036 strcpy(dbPath, (char *)pFile->lockingContext);
5037 }
5038 return SQLITE_OK;
5039}
5040
5041/*
5042** Takes an already filled in unix file and alters it so all file locking
5043** will be performed on the local proxy lock file. The following fields
5044** are preserved in the locking context so that they can be restored and
5045** the unix structure properly cleaned up at close time:
5046** ->lockingContext
5047** ->pMethod
5048*/
5049static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
5050 proxyLockingContext *pCtx;
5051 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
5052 char *lockPath=NULL;
5053 int rc = SQLITE_OK;
5054
5055 if( pFile->locktype!=NO_LOCK ){
5056 return SQLITE_BUSY;
5057 }
5058 proxyGetDbPathForUnixFile(pFile, dbPath);
5059 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
5060 lockPath=NULL;
5061 }else{
5062 lockPath=(char *)path;
5063 }
5064
5065 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
5066 (lockPath ? lockPath : ":auto:"), getpid());
5067
5068 pCtx = sqlite3_malloc( sizeof(*pCtx) );
5069 if( pCtx==0 ){
5070 return SQLITE_NOMEM;
5071 }
5072 memset(pCtx, 0, sizeof(*pCtx));
5073
5074 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
5075 if( rc==SQLITE_OK ){
5076 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
5077 }
5078 if( rc==SQLITE_OK && lockPath ){
5079 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
5080 }
5081
5082 if( rc==SQLITE_OK ){
5083 /* all memory is allocated, proxys are created and assigned,
5084 ** switch the locking context and pMethod then return.
5085 */
5086 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
5087 pCtx->oldLockingContext = pFile->lockingContext;
5088 pFile->lockingContext = pCtx;
5089 pCtx->pOldMethod = pFile->pMethod;
5090 pFile->pMethod = &proxyIoMethods;
5091 }else{
5092 if( pCtx->conchFile ){
5093 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
5094 if( rc ) return rc;
5095 sqlite3_free(pCtx->conchFile);
5096 }
5097 sqlite3_free(pCtx->conchFilePath);
5098 sqlite3_free(pCtx);
5099 }
5100 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
5101 (rc==SQLITE_OK ? "ok" : "failed"));
5102 return rc;
5103}
5104
5105
5106/*
5107** This routine handles sqlite3_file_control() calls that are specific
5108** to proxy locking.
5109*/
5110static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
5111 switch( op ){
5112 case SQLITE_GET_LOCKPROXYFILE: {
5113 unixFile *pFile = (unixFile*)id;
5114 if( pFile->pMethod == &proxyIoMethods ){
5115 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
5116 proxyTakeConch(pFile);
5117 if( pCtx->lockProxyPath ){
5118 *(const char **)pArg = pCtx->lockProxyPath;
5119 }else{
5120 *(const char **)pArg = ":auto: (not held)";
5121 }
5122 } else {
5123 *(const char **)pArg = NULL;
5124 }
5125 return SQLITE_OK;
5126 }
5127 case SQLITE_SET_LOCKPROXYFILE: {
5128 unixFile *pFile = (unixFile*)id;
5129 int rc = SQLITE_OK;
5130 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
5131 if( pArg==NULL || (const char *)pArg==0 ){
5132 if( isProxyStyle ){
5133 /* turn off proxy locking - not supported */
5134 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
5135 }else{
5136 /* turn off proxy locking - already off - NOOP */
5137 rc = SQLITE_OK;
5138 }
5139 }else{
5140 const char *proxyPath = (const char *)pArg;
5141 if( isProxyStyle ){
5142 proxyLockingContext *pCtx =
5143 (proxyLockingContext*)pFile->lockingContext;
5144 if( !strcmp(pArg, ":auto:")
5145 || (pCtx->lockProxyPath &&
5146 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
5147 ){
5148 rc = SQLITE_OK;
5149 }else{
5150 rc = switchLockProxyPath(pFile, proxyPath);
5151 }
5152 }else{
5153 /* turn on proxy file locking */
5154 rc = proxyTransformUnixFile(pFile, proxyPath);
5155 }
5156 }
5157 return rc;
5158 }
5159 default: {
5160 assert( 0 ); /* The call assures that only valid opcodes are sent */
5161 }
5162 }
5163 /*NOTREACHED*/
5164 return SQLITE_ERROR;
5165}
5166
5167/*
5168** Within this division (the proxying locking implementation) the procedures
5169** above this point are all utilities. The lock-related methods of the
5170** proxy-locking sqlite3_io_method object follow.
5171*/
5172
5173
5174/*
5175** This routine checks if there is a RESERVED lock held on the specified
5176** file by this or any other process. If such a lock is held, set *pResOut
5177** to a non-zero value otherwise *pResOut is set to zero. The return value
5178** is set to SQLITE_OK unless an I/O error occurs during lock checking.
5179*/
5180static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
5181 unixFile *pFile = (unixFile*)id;
5182 int rc = proxyTakeConch(pFile);
5183 if( rc==SQLITE_OK ){
5184 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5185 unixFile *proxy = pCtx->lockProxy;
5186 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
5187 }
5188 return rc;
5189}
5190
5191/*
5192** Lock the file with the lock specified by parameter locktype - one
5193** of the following:
5194**
5195** (1) SHARED_LOCK
5196** (2) RESERVED_LOCK
5197** (3) PENDING_LOCK
5198** (4) EXCLUSIVE_LOCK
5199**
5200** Sometimes when requesting one lock state, additional lock states
5201** are inserted in between. The locking might fail on one of the later
5202** transitions leaving the lock state different from what it started but
5203** still short of its goal. The following chart shows the allowed
5204** transitions and the inserted intermediate states:
5205**
5206** UNLOCKED -> SHARED
5207** SHARED -> RESERVED
5208** SHARED -> (PENDING) -> EXCLUSIVE
5209** RESERVED -> (PENDING) -> EXCLUSIVE
5210** PENDING -> EXCLUSIVE
5211**
5212** This routine will only increase a lock. Use the sqlite3OsUnlock()
5213** routine to lower a locking level.
5214*/
5215static int proxyLock(sqlite3_file *id, int locktype) {
5216 unixFile *pFile = (unixFile*)id;
5217 int rc = proxyTakeConch(pFile);
5218 if( rc==SQLITE_OK ){
5219 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5220 unixFile *proxy = pCtx->lockProxy;
5221 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
5222 pFile->locktype = proxy->locktype;
5223 }
5224 return rc;
5225}
5226
5227
5228/*
5229** Lower the locking level on file descriptor pFile to locktype. locktype
5230** must be either NO_LOCK or SHARED_LOCK.
5231**
5232** If the locking level of the file descriptor is already at or below
5233** the requested locking level, this routine is a no-op.
5234*/
5235static int proxyUnlock(sqlite3_file *id, int locktype) {
5236 unixFile *pFile = (unixFile*)id;
5237 int rc = proxyTakeConch(pFile);
5238 if( rc==SQLITE_OK ){
5239 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5240 unixFile *proxy = pCtx->lockProxy;
5241 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
5242 pFile->locktype = proxy->locktype;
5243 }
5244 return rc;
5245}
5246
5247/*
5248** Close a file that uses proxy locks.
5249*/
5250static int proxyClose(sqlite3_file *id) {
5251 if( id ){
5252 unixFile *pFile = (unixFile*)id;
5253 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5254 unixFile *lockProxy = pCtx->lockProxy;
5255 unixFile *conchFile = pCtx->conchFile;
5256 int rc = SQLITE_OK;
5257
5258 if( lockProxy ){
5259 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
5260 if( rc ) return rc;
5261 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
5262 if( rc ) return rc;
5263 sqlite3_free(lockProxy);
5264 pCtx->lockProxy = 0;
5265 }
5266 if( conchFile ){
5267 if( pCtx->conchHeld ){
5268 rc = proxyReleaseConch(pFile);
5269 if( rc ) return rc;
5270 }
5271 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
5272 if( rc ) return rc;
5273 sqlite3_free(conchFile);
5274 }
5275 sqlite3_free(pCtx->lockProxyPath);
5276 sqlite3_free(pCtx->conchFilePath);
5277 sqlite3_free(pCtx->dbPath);
5278 /* restore the original locking context and pMethod then close it */
5279 pFile->lockingContext = pCtx->oldLockingContext;
5280 pFile->pMethod = pCtx->pOldMethod;
5281 sqlite3_free(pCtx);
5282 return pFile->pMethod->xClose(id);
5283 }
5284 return SQLITE_OK;
5285}
5286
5287
5288
drhd2cb50b2009-01-09 21:41:17 +00005289#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00005290/*
5291** The proxy locking style is intended for use with AFP filesystems.
5292** And since AFP is only supported on MacOSX, the proxy locking is also
5293** restricted to MacOSX.
5294**
5295**
5296******************* End of the proxy lock implementation **********************
5297******************************************************************************/
5298
drh734c9862008-11-28 15:37:20 +00005299/*
danielk1977e339d652008-06-28 11:23:00 +00005300** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00005301**
5302** This routine registers all VFS implementations for unix-like operating
5303** systems. This routine, and the sqlite3_os_end() routine that follows,
5304** should be the only routines in this file that are visible from other
5305** files.
drh6b9d6dd2008-12-03 19:34:47 +00005306**
5307** This routine is called once during SQLite initialization and by a
5308** single thread. The memory allocation and mutex subsystems have not
5309** necessarily been initialized when this routine is called, and so they
5310** should not be used.
drh153c62c2007-08-24 03:51:33 +00005311*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005312int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00005313 /*
5314 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00005315 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
5316 ** to the "finder" function. (pAppData is a pointer to a pointer because
5317 ** silly C90 rules prohibit a void* from being cast to a function pointer
5318 ** and so we have to go through the intermediate pointer to avoid problems
5319 ** when compiling with -pedantic-errors on GCC.)
5320 **
5321 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00005322 ** finder-function. The finder-function returns a pointer to the
5323 ** sqlite_io_methods object that implements the desired locking
5324 ** behaviors. See the division above that contains the IOMETHODS
5325 ** macro for addition information on finder-functions.
5326 **
5327 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
5328 ** object. But the "autolockIoFinder" available on MacOSX does a little
5329 ** more than that; it looks at the filesystem type that hosts the
5330 ** database file and tries to choose an locking method appropriate for
5331 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00005332 */
drh7708e972008-11-29 00:56:52 +00005333 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00005334 1, /* iVersion */ \
5335 sizeof(unixFile), /* szOsFile */ \
5336 MAX_PATHNAME, /* mxPathname */ \
5337 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00005338 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00005339 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00005340 unixOpen, /* xOpen */ \
5341 unixDelete, /* xDelete */ \
5342 unixAccess, /* xAccess */ \
5343 unixFullPathname, /* xFullPathname */ \
5344 unixDlOpen, /* xDlOpen */ \
5345 unixDlError, /* xDlError */ \
5346 unixDlSym, /* xDlSym */ \
5347 unixDlClose, /* xDlClose */ \
5348 unixRandomness, /* xRandomness */ \
5349 unixSleep, /* xSleep */ \
5350 unixCurrentTime, /* xCurrentTime */ \
5351 unixGetLastError /* xGetLastError */ \
5352 }
5353
drh6b9d6dd2008-12-03 19:34:47 +00005354 /*
5355 ** All default VFSes for unix are contained in the following array.
5356 **
5357 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5358 ** by the SQLite core when the VFS is registered. So the following
5359 ** array cannot be const.
5360 */
danielk1977e339d652008-06-28 11:23:00 +00005361 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00005362#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00005363 UNIXVFS("unix", autolockIoFinder ),
5364#else
5365 UNIXVFS("unix", posixIoFinder ),
5366#endif
5367 UNIXVFS("unix-none", nolockIoFinder ),
5368 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh0c2694b2009-09-03 16:23:44 +00005369 UNIXVFS("unix-wfl", posixWflIoFinder ),
drh734c9862008-11-28 15:37:20 +00005370#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005371 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00005372#endif
5373#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005374 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00005375#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005376 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00005377#endif
chw78a13182009-04-07 05:35:03 +00005378#endif
drhd2cb50b2009-01-09 21:41:17 +00005379#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00005380 UNIXVFS("unix-afp", afpIoFinder ),
5381 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00005382#endif
drh153c62c2007-08-24 03:51:33 +00005383 };
drh6b9d6dd2008-12-03 19:34:47 +00005384 unsigned int i; /* Loop counter */
5385
5386 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00005387 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00005388 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00005389 }
danielk1977c0fa4c52008-06-25 17:19:00 +00005390 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00005391}
danielk1977e339d652008-06-28 11:23:00 +00005392
5393/*
drh6b9d6dd2008-12-03 19:34:47 +00005394** Shutdown the operating system interface.
5395**
5396** Some operating systems might need to do some cleanup in this routine,
5397** to release dynamically allocated objects. But not on unix.
5398** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00005399*/
danielk1977c0fa4c52008-06-25 17:19:00 +00005400int sqlite3_os_end(void){
5401 return SQLITE_OK;
5402}
drhdce8bdb2007-08-16 13:01:44 +00005403
danielk197729bafea2008-06-26 10:41:19 +00005404#endif /* SQLITE_OS_UNIX */