blob: b16369cef05e48657564579d5efc5356e5cb9710 [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**
27** The current set of divisions is as follows:
28**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
31** * Various locking primitive implementations:
32** + 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)
38** + for proxy locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000039** * sqlite3_file methods not associated with locking.
40** * Definitions of sqlite3_io_methods objects for all locking
41** methods plus "finder" functions for each locking method.
42** * VFS method implementations.
43** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drh734c9862008-11-28 15:37:20 +000045**
drh9b35ea62008-11-29 02:20:26 +000046** $Id: os_unix.c,v 1.224 2008/11/29 02:20:27 drh Exp $
drhbbd42a62004-05-22 17:41:58 +000047*/
drhbbd42a62004-05-22 17:41:58 +000048#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000049#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000050
danielk1977e339d652008-06-28 11:23:00 +000051/*
drh734c9862008-11-28 15:37:20 +000052** This module implements the following locking styles:
danielk1977e339d652008-06-28 11:23:00 +000053**
drh734c9862008-11-28 15:37:20 +000054** 1. POSIX locking (the default),
55** 2. No locking,
56** 3. Dot-file locking,
57** 4. flock() locking,
58** 5. AFP locking (OSX only),
59** 6. Named POSIX semaphores (VXWorks only),
60** 7. proxy locking. (OSX only)
61**
62** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
63** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
64** selection of the appropriate locking style based on the filesystem
65** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000066*/
drh40bbb0a2008-09-23 10:23:26 +000067#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
68# if defined(__DARWIN__)
69# define SQLITE_ENABLE_LOCKING_STYLE 1
70# else
71# define SQLITE_ENABLE_LOCKING_STYLE 0
72# endif
73#endif
drhbfe66312006-10-03 17:40:40 +000074
drh9cbe6352005-11-29 03:13:21 +000075/*
drh6c7d5c52008-11-21 20:32:33 +000076** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000077** vxworks, or 0 otherwise.
78*/
drh6c7d5c52008-11-21 20:32:33 +000079#ifndef OS_VXWORKS
80# if defined(__RTP__) || defined(_WRS_KERNEL)
81# define OS_VXWORKS 1
82# else
83# define OS_VXWORKS 0
84# endif
danielk1977397d65f2008-11-19 11:35:39 +000085#endif
86
87/*
drh9cbe6352005-11-29 03:13:21 +000088** These #defines should enable >2GB file support on Posix if the
89** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000090** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000091**
92** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
93** on the compiler command line. This is necessary if you are compiling
94** on a recent machine (ex: RedHat 7.2) but you want your code to work
95** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
96** without this option, LFS is enable. But LFS does not exist in the kernel
97** in RedHat 6.0, so the code won't work. Hence, for maximum binary
98** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000099**
100** The previous paragraph was written in 2005. (This paragraph is written
101** on 2008-11-28.) These days, all Linux kernels support large files, so
102** you should probably leave LFS enabled. But some embedded platforms might
103** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000104*/
105#ifndef SQLITE_DISABLE_LFS
106# define _LARGE_FILE 1
107# ifndef _FILE_OFFSET_BITS
108# define _FILE_OFFSET_BITS 64
109# endif
110# define _LARGEFILE_SOURCE 1
111#endif
drhbbd42a62004-05-22 17:41:58 +0000112
drh9cbe6352005-11-29 03:13:21 +0000113/*
114** standard include files.
115*/
116#include <sys/types.h>
117#include <sys/stat.h>
118#include <fcntl.h>
119#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000120#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000121#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000122#include <errno.h>
danielk1977e339d652008-06-28 11:23:00 +0000123
drh40bbb0a2008-09-23 10:23:26 +0000124#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000125# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000126# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <semaphore.h>
128# include <limits.h>
129# else
drh9b35ea62008-11-29 02:20:26 +0000130# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000131# include <sys/param.h>
132# include <sys/mount.h>
133# endif
drhbfe66312006-10-03 17:40:40 +0000134#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000135
136/*
drhf1a221e2006-01-15 17:27:17 +0000137** If we are to be thread-safe, include the pthreads header and define
138** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000139*/
drhd677b3d2007-08-20 22:48:41 +0000140#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000141# include <pthread.h>
142# define SQLITE_UNIX_THREADS 1
143#endif
144
145/*
146** Default permissions when creating a new file
147*/
148#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
149# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
150#endif
151
danielk1977b4b47412007-08-17 15:53:36 +0000152/*
aswiftaebf4132008-11-21 00:10:35 +0000153 ** Default permissions when creating auto proxy dir
154 */
155#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
156# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
157#endif
158
159/*
danielk1977b4b47412007-08-17 15:53:36 +0000160** Maximum supported path-length.
161*/
162#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000163
drh734c9862008-11-28 15:37:20 +0000164/*
drh734c9862008-11-28 15:37:20 +0000165** Only set the lastErrno if the error code is a real error and not
166** a normal expected return code of SQLITE_BUSY or SQLITE_OK
167*/
168#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
169
drh9cbe6352005-11-29 03:13:21 +0000170
171/*
drh9b35ea62008-11-29 02:20:26 +0000172** The unixFile structure is subclass of sqlite3_file specific to the unix
173** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000174*/
drh054889e2005-11-30 03:20:31 +0000175typedef struct unixFile unixFile;
176struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000177 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh6c7d5c52008-11-21 20:32:33 +0000178 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */
179 struct unixLockInfo *pLock; /* Info about locks on this inode */
180 int h; /* The file descriptor */
181 int dirfd; /* File descriptor for the directory */
182 unsigned char locktype; /* The type of lock held on this fd */
183 int lastErrno; /* The unix errno from the last I/O error */
drh6c7d5c52008-11-21 20:32:33 +0000184 void *lockingContext; /* Locking style specific state */
drh734c9862008-11-28 15:37:20 +0000185 int openFlags; /* The flags specified at open */
186#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000187 pthread_t tid; /* The thread that "owns" this unixFile */
188#endif
189#if OS_VXWORKS
190 int isDelete; /* Delete on close if true */
drh107886a2008-11-21 22:21:50 +0000191 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000192#endif
danielk1977967a4a12007-08-20 14:23:44 +0000193#ifdef SQLITE_TEST
194 /* In test mode, increase the size of this structure a bit so that
195 ** it is larger than the struct CrashFile defined in test6.c.
196 */
197 char aPadding[32];
198#endif
drh9cbe6352005-11-29 03:13:21 +0000199};
200
drh0ccebe72005-06-07 22:22:50 +0000201/*
drh198bf392006-01-06 21:52:49 +0000202** Include code that is common to all os_*.c files
203*/
204#include "os_common.h"
205
206/*
drh0ccebe72005-06-07 22:22:50 +0000207** Define various macros that are missing from some systems.
208*/
drhbbd42a62004-05-22 17:41:58 +0000209#ifndef O_LARGEFILE
210# define O_LARGEFILE 0
211#endif
212#ifdef SQLITE_DISABLE_LFS
213# undef O_LARGEFILE
214# define O_LARGEFILE 0
215#endif
216#ifndef O_NOFOLLOW
217# define O_NOFOLLOW 0
218#endif
219#ifndef O_BINARY
220# define O_BINARY 0
221#endif
222
223/*
224** The DJGPP compiler environment looks mostly like Unix, but it
225** lacks the fcntl() system call. So redefine fcntl() to be something
226** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000227** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000228*/
229#ifdef __DJGPP__
230# define fcntl(A,B,C) 0
231#endif
232
233/*
drh2b4b5962005-06-15 17:47:55 +0000234** The threadid macro resolves to the thread-id or to 0. Used for
235** testing and debugging only.
236*/
drhd677b3d2007-08-20 22:48:41 +0000237#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000238#define threadid pthread_self()
239#else
240#define threadid 0
241#endif
242
danielk197713adf8a2004-06-03 16:08:41 +0000243
drh107886a2008-11-21 22:21:50 +0000244/*
245** Helper functions to obtain and relinquish the global mutex.
246*/
247static void unixEnterMutex(void){
248 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
249}
250static void unixLeaveMutex(void){
251 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
252}
253
drh734c9862008-11-28 15:37:20 +0000254
255#ifdef SQLITE_DEBUG
256/*
257** Helper function for printing out trace information from debugging
258** binaries. This returns the string represetation of the supplied
259** integer lock-type.
260*/
261static const char *locktypeName(int locktype){
262 switch( locktype ){
263 case NO_LOCK: return "NONE";
264 case SHARED_LOCK: return "SHARED";
265 case RESERVED_LOCK: return "RESERVED";
266 case PENDING_LOCK: return "PENDING";
267 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
268 }
269 return "ERROR";
270}
271#endif
272
273#ifdef SQLITE_LOCK_TRACE
274/*
275** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000276**
drh734c9862008-11-28 15:37:20 +0000277** This routine is used for troubleshooting locks on multithreaded
278** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
279** command-line option on the compiler. This code is normally
280** turned off.
281*/
282static int lockTrace(int fd, int op, struct flock *p){
283 char *zOpName, *zType;
284 int s;
285 int savedErrno;
286 if( op==F_GETLK ){
287 zOpName = "GETLK";
288 }else if( op==F_SETLK ){
289 zOpName = "SETLK";
290 }else{
291 s = fcntl(fd, op, p);
292 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
293 return s;
294 }
295 if( p->l_type==F_RDLCK ){
296 zType = "RDLCK";
297 }else if( p->l_type==F_WRLCK ){
298 zType = "WRLCK";
299 }else if( p->l_type==F_UNLCK ){
300 zType = "UNLCK";
301 }else{
302 assert( 0 );
303 }
304 assert( p->l_whence==SEEK_SET );
305 s = fcntl(fd, op, p);
306 savedErrno = errno;
307 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
308 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
309 (int)p->l_pid, s);
310 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
311 struct flock l2;
312 l2 = *p;
313 fcntl(fd, F_GETLK, &l2);
314 if( l2.l_type==F_RDLCK ){
315 zType = "RDLCK";
316 }else if( l2.l_type==F_WRLCK ){
317 zType = "WRLCK";
318 }else if( l2.l_type==F_UNLCK ){
319 zType = "UNLCK";
320 }else{
321 assert( 0 );
322 }
323 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
324 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
325 }
326 errno = savedErrno;
327 return s;
328}
329#define fcntl lockTrace
330#endif /* SQLITE_LOCK_TRACE */
331
332
333
334/*
335** This routine translates a standard POSIX errno code into something
336** useful to the clients of the sqlite3 functions. Specifically, it is
337** intended to translate a variety of "try again" errors into SQLITE_BUSY
338** and a variety of "please close the file descriptor NOW" errors into
339** SQLITE_IOERR
340**
341** Errors during initialization of locks, or file system support for locks,
342** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
343*/
344static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
345 switch (posixError) {
346 case 0:
347 return SQLITE_OK;
348
349 case EAGAIN:
350 case ETIMEDOUT:
351 case EBUSY:
352 case EINTR:
353 case ENOLCK:
354 /* random NFS retry error, unless during file system support
355 * introspection, in which it actually means what it says */
356 return SQLITE_BUSY;
357
358 case EACCES:
359 /* EACCES is like EAGAIN during locking operations, but not any other time*/
360 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
361 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
362 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
363 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
364 return SQLITE_BUSY;
365 }
366 /* else fall through */
367 case EPERM:
368 return SQLITE_PERM;
369
370 case EDEADLK:
371 return SQLITE_IOERR_BLOCKED;
372
373#if EOPNOTSUPP!=ENOTSUP
374 case EOPNOTSUPP:
375 /* something went terribly awry, unless during file system support
376 * introspection, in which it actually means what it says */
377#endif
378#ifdef ENOTSUP
379 case ENOTSUP:
380 /* invalid fd, unless during file system support introspection, in which
381 * it actually means what it says */
382#endif
383 case EIO:
384 case EBADF:
385 case EINVAL:
386 case ENOTCONN:
387 case ENODEV:
388 case ENXIO:
389 case ENOENT:
390 case ESTALE:
391 case ENOSYS:
392 /* these should force the client to close the file and reconnect */
393
394 default:
395 return sqliteIOErr;
396 }
397}
398
399
400
401/******************************************************************************
402****************** Begin Unique File ID Utility Used By VxWorks ***************
403**
404** On most versions of unix, we can get a unique ID for a file by concatenating
405** the device number and the inode number. But this does not work on VxWorks.
406** On VxWorks, a unique file id must be based on the canonical filename.
407**
408** A pointer to an instance of the following structure can be used as a
409** unique file ID in VxWorks. Each instance of this structure contains
410** a copy of the canonical filename. There is also a reference count.
411** The structure is reclaimed when the number of pointers to it drops to
412** zero.
413**
414** There are never very many files open at one time and lookups are not
415** a performance-critical path, so it is sufficient to put these
416** structures on a linked list.
417*/
418struct vxworksFileId {
419 struct vxworksFileId *pNext; /* Next in a list of them all */
420 int nRef; /* Number of references to this one */
421 int nName; /* Length of the zCanonicalName[] string */
422 char *zCanonicalName; /* Canonical filename */
423};
424
425#if OS_VXWORKS
426/*
drh9b35ea62008-11-29 02:20:26 +0000427** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000428** variable:
429*/
430static struct vxworksFileId *vxworksFileList = 0;
431
432/*
433** Simplify a filename into its canonical form
434** by making the following changes:
435**
436** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000437** * convert /./ into just /
438** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000439**
440** Changes are made in-place. Return the new name length.
441**
442** The original filename is in z[0..n-1]. Return the number of
443** characters in the simplified name.
444*/
445static int vxworksSimplifyName(char *z, int n){
446 int i, j;
447 while( n>1 && z[n-1]=='/' ){ n--; }
448 for(i=j=0; i<n; i++){
449 if( z[i]=='/' ){
450 if( z[i+1]=='/' ) continue;
451 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
452 i += 1;
453 continue;
454 }
455 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
456 while( j>0 && z[j-1]!='/' ){ j--; }
457 if( j>0 ){ j--; }
458 i += 2;
459 continue;
460 }
461 }
462 z[j++] = z[i];
463 }
464 z[j] = 0;
465 return j;
466}
467
468/*
469** Find a unique file ID for the given absolute pathname. Return
470** a pointer to the vxworksFileId object. This pointer is the unique
471** file ID.
472**
473** The nRef field of the vxworksFileId object is incremented before
474** the object is returned. A new vxworksFileId object is created
475** and added to the global list if necessary.
476**
477** If a memory allocation error occurs, return NULL.
478*/
479static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
480 struct vxworksFileId *pNew; /* search key and new file ID */
481 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
482 int n; /* Length of zAbsoluteName string */
483
484 assert( zAbsoluteName[0]=='/' );
485 n = strlen(zAbsoluteName);
486 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
487 if( pNew==0 ) return 0;
488 pNew->zCanonicalName = (char*)&pNew[1];
489 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
490 n = vxworksSimplifyName(pNew->zCanonicalName, n);
491
492 /* Search for an existing entry that matching the canonical name.
493 ** If found, increment the reference count and return a pointer to
494 ** the existing file ID.
495 */
496 unixEnterMutex();
497 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
498 if( pCandidate->nName==n
499 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
500 ){
501 sqlite3_free(pNew);
502 pCandidate->nRef++;
503 unixLeaveMutex();
504 return pCandidate;
505 }
506 }
507
508 /* No match was found. We will make a new file ID */
509 pNew->nRef = 1;
510 pNew->nName = n;
511 pNew->pNext = vxworksFileList;
512 vxworksFileList = pNew;
513 unixLeaveMutex();
514 return pNew;
515}
516
517/*
518** Decrement the reference count on a vxworksFileId object. Free
519** the object when the reference count reaches zero.
520*/
521static void vxworksReleaseFileId(struct vxworksFileId *pId){
522 unixEnterMutex();
523 assert( pId->nRef>0 );
524 pId->nRef--;
525 if( pId->nRef==0 ){
526 struct vxworksFileId **pp;
527 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
528 assert( *pp==pId );
529 *pp = pId->pNext;
530 sqlite3_free(pId);
531 }
532 unixLeaveMutex();
533}
534#endif /* OS_VXWORKS */
535/*************** End of Unique File ID Utility Used By VxWorks ****************
536******************************************************************************/
537
538
539/******************************************************************************
540*************************** Posix Advisory Locking ****************************
541**
drh9b35ea62008-11-29 02:20:26 +0000542** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000543** section 6.5.2.2 lines 483 through 490 specify that when a process
544** sets or clears a lock, that operation overrides any prior locks set
545** by the same process. It does not explicitly say so, but this implies
546** that it overrides locks set by the same process using a different
547** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000548**
549** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000550** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
551**
552** Suppose ./file1 and ./file2 are really the same file (because
553** one is a hard or symbolic link to the other) then if you set
554** an exclusive lock on fd1, then try to get an exclusive lock
555** on fd2, it works. I would have expected the second lock to
556** fail since there was already a lock on the file due to fd1.
557** But not so. Since both locks came from the same process, the
558** second overrides the first, even though they were on different
559** file descriptors opened on different file names.
560**
drh734c9862008-11-28 15:37:20 +0000561** This means that we cannot use POSIX locks to synchronize file access
562** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000563** to synchronize access for threads in separate processes, but not
564** threads within the same process.
565**
566** To work around the problem, SQLite has to manage file locks internally
567** on its own. Whenever a new database is opened, we have to find the
568** specific inode of the database file (the inode is determined by the
569** st_dev and st_ino fields of the stat structure that fstat() fills in)
570** and check for locks already existing on that inode. When locks are
571** created or removed, we have to look at our own internal record of the
572** locks to see if another thread has previously set a lock on that same
573** inode.
574**
drh9b35ea62008-11-29 02:20:26 +0000575** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
576** For VxWorks, we have to use the alternative unique ID system based on
577** canonical filename and implemented in the previous division.)
578**
danielk1977ad94b582007-08-20 06:44:22 +0000579** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000580** descriptor. It is now a structure that holds the integer file
581** descriptor and a pointer to a structure that describes the internal
582** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000583** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000584** point to the same locking structure. The locking structure keeps
585** a reference count (so we will know when to delete it) and a "cnt"
586** field that tells us its internal lock status. cnt==0 means the
587** file is unlocked. cnt==-1 means the file has an exclusive lock.
588** cnt>0 means there are cnt shared locks on the file.
589**
590** Any attempt to lock or unlock a file first checks the locking
591** structure. The fcntl() system call is only invoked to set a
592** POSIX lock if the internal lock structure transitions between
593** a locked and an unlocked state.
594**
drh734c9862008-11-28 15:37:20 +0000595** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000596**
597** If you close a file descriptor that points to a file that has locks,
598** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000599** released. To work around this problem, each unixFile structure contains
drh6c7d5c52008-11-21 20:32:33 +0000600** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000601** per open inode, which means that multiple unixFile can point to a single
drh6c7d5c52008-11-21 20:32:33 +0000602** unixOpenCnt. When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000603** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000604** to close() the file descriptor is deferred until all of the locks clear.
drh6c7d5c52008-11-21 20:32:33 +0000605** The unixOpenCnt structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000606** be closed and that list is walked (and cleared) when the last lock
607** clears.
608**
drh9b35ea62008-11-29 02:20:26 +0000609** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000610**
drh9b35ea62008-11-29 02:20:26 +0000611** Many older versions of linux use the LinuxThreads library which is
612** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000613** A cannot be modified or overridden by a different thread B.
614** Only thread A can modify the lock. Locking behavior is correct
615** if the appliation uses the newer Native Posix Thread Library (NPTL)
616** on linux - with NPTL a lock created by thread A can override locks
617** in thread B. But there is no way to know at compile-time which
618** threading library is being used. So there is no way to know at
619** compile-time whether or not thread A can override locks on thread B.
620** We have to do a run-time check to discover the behavior of the
621** current process.
drh5fdae772004-06-29 03:29:00 +0000622**
drh734c9862008-11-28 15:37:20 +0000623** On systems where thread A is unable to modify locks created by
624** thread B, we have to keep track of which thread created each
drh9b35ea62008-11-29 02:20:26 +0000625** lock. Hence there is an extra field in the key to the unixLockInfo
drh734c9862008-11-28 15:37:20 +0000626** structure to record this information. And on those systems it
627** is illegal to begin a transaction in one thread and finish it
628** in another. For this latter restriction, there is no work-around.
629** It is a limitation of LinuxThreads.
drhbbd42a62004-05-22 17:41:58 +0000630*/
631
632/*
drh6c7d5c52008-11-21 20:32:33 +0000633** Set or check the unixFile.tid field. This field is set when an unixFile
634** is first opened. All subsequent uses of the unixFile verify that the
635** same thread is operating on the unixFile. Some operating systems do
636** not allow locks to be overridden by other threads and that restriction
637** means that sqlite3* database handles cannot be moved from one thread
drh734c9862008-11-28 15:37:20 +0000638** to another while locks are held.
drh6c7d5c52008-11-21 20:32:33 +0000639**
640** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
641** another as long as we are running on a system that supports threads
drh734c9862008-11-28 15:37:20 +0000642** overriding each others locks (which is now the most common behavior)
drh6c7d5c52008-11-21 20:32:33 +0000643** or if no locks are held. But the unixFile.pLock field needs to be
644** recomputed because its key includes the thread-id. See the
645** transferOwnership() function below for additional information
646*/
drh734c9862008-11-28 15:37:20 +0000647#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000648# define SET_THREADID(X) (X)->tid = pthread_self()
649# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
650 !pthread_equal((X)->tid, pthread_self()))
651#else
652# define SET_THREADID(X)
653# define CHECK_THREADID(X) 0
654#endif
655
656/*
drhbbd42a62004-05-22 17:41:58 +0000657** An instance of the following structure serves as the key used
drh6c7d5c52008-11-21 20:32:33 +0000658** to locate a particular unixOpenCnt structure given its inode. This
659** is the same as the unixLockKey except that the thread ID is omitted.
660*/
661struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000662 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000663#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000664 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000665#else
drh107886a2008-11-21 22:21:50 +0000666 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000667#endif
668};
669
670/*
671** An instance of the following structure serves as the key used
672** to locate a particular unixLockInfo structure given its inode.
drh5fdae772004-06-29 03:29:00 +0000673**
drh734c9862008-11-28 15:37:20 +0000674** If threads cannot override each others locks (LinuxThreads), then we
675** set the unixLockKey.tid field to the thread ID. If threads can override
676** each others locks (Posix and NPTL) then tid is always set to zero.
677** tid is omitted if we compile without threading support or on an OS
678** other than linux.
drhbbd42a62004-05-22 17:41:58 +0000679*/
drh6c7d5c52008-11-21 20:32:33 +0000680struct unixLockKey {
681 struct unixFileId fid; /* Unique identifier for the file */
drh734c9862008-11-28 15:37:20 +0000682#if SQLITE_THREADSAFE && defined(__linux__)
683 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
drh5fdae772004-06-29 03:29:00 +0000684#endif
drhbbd42a62004-05-22 17:41:58 +0000685};
686
687/*
688** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000689** inode. Or, on LinuxThreads, there is one of these structures for
690** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000691**
danielk1977ad94b582007-08-20 06:44:22 +0000692** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000693** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000694** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000695*/
drh6c7d5c52008-11-21 20:32:33 +0000696struct unixLockInfo {
drh734c9862008-11-28 15:37:20 +0000697 struct unixLockKey lockKey; /* The lookup key */
698 int cnt; /* Number of SHARED locks held */
699 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
700 int nRef; /* Number of pointers to this structure */
701 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */
702 struct unixLockInfo *pPrev; /* .... doubly linked */
drhbbd42a62004-05-22 17:41:58 +0000703};
704
705/*
706** An instance of the following structure is allocated for each open
707** inode. This structure keeps track of the number of locks on that
708** inode. If a close is attempted against an inode that is holding
709** locks, the close is deferred until all locks clear by adding the
710** file descriptor to be closed to the pending list.
drh9b35ea62008-11-29 02:20:26 +0000711**
712** TODO: Consider changing this so that there is only a single file
713** descriptor for each open file, even when it is opened multiple times.
714** The close() system call would only occur when the last database
715** using the file closes.
drhbbd42a62004-05-22 17:41:58 +0000716*/
drh6c7d5c52008-11-21 20:32:33 +0000717struct unixOpenCnt {
718 struct unixFileId fileId; /* The lookup key */
719 int nRef; /* Number of pointers to this structure */
720 int nLock; /* Number of outstanding locks */
721 int nPending; /* Number of pending close() operations */
722 int *aPending; /* Malloced space holding fd's awaiting a close() */
723#if OS_VXWORKS
724 sem_t *pSem; /* Named POSIX semaphore */
chw97185482008-11-17 08:05:31 +0000725 char aSemName[MAX_PATHNAME+1]; /* Name of that semaphore */
726#endif
drh6c7d5c52008-11-21 20:32:33 +0000727 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000728};
729
drhda0e7682008-07-30 15:27:54 +0000730/*
drh9b35ea62008-11-29 02:20:26 +0000731** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash
732** tables. But the number of objects is rarely more than a dozen and
drhda0e7682008-07-30 15:27:54 +0000733** never exceeds a few thousand. And lookup is not on a critical
drh6c7d5c52008-11-21 20:32:33 +0000734** path so a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000735*/
drh6c7d5c52008-11-21 20:32:33 +0000736static struct unixLockInfo *lockList = 0;
737static struct unixOpenCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000738
drh5fdae772004-06-29 03:29:00 +0000739/*
drh9b35ea62008-11-29 02:20:26 +0000740** This variable remembers whether or not threads can override each others
drh5fdae772004-06-29 03:29:00 +0000741** locks.
742**
drh9b35ea62008-11-29 02:20:26 +0000743** 0: No. Threads cannot override each others locks. (LinuxThreads)
744** 1: Yes. Threads can override each others locks. (Posix & NLPT)
drh5fdae772004-06-29 03:29:00 +0000745** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000746**
drh5062d3a2006-01-31 23:03:35 +0000747** On some systems, we know at compile-time if threads can override each
748** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
749** will be set appropriately. On other systems, we have to check at
750** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
751** undefined.
752**
drhf1a221e2006-01-15 17:27:17 +0000753** This variable normally has file scope only. But during testing, we make
754** it a global so that the test code can change its value in order to verify
755** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000756*/
drh5062d3a2006-01-31 23:03:35 +0000757#ifndef SQLITE_THREAD_OVERRIDE_LOCK
758# define SQLITE_THREAD_OVERRIDE_LOCK -1
759#endif
drh029b44b2006-01-15 00:13:15 +0000760#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000761int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000762#else
drh5062d3a2006-01-31 23:03:35 +0000763static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000764#endif
drh5fdae772004-06-29 03:29:00 +0000765
766/*
767** This structure holds information passed into individual test
768** threads by the testThreadLockingBehavior() routine.
769*/
770struct threadTestData {
771 int fd; /* File to be locked */
772 struct flock lock; /* The locking operation */
773 int result; /* Result of the locking operation */
774};
775
drh6c7d5c52008-11-21 20:32:33 +0000776#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000777/*
danielk197741a6a612008-11-11 18:34:35 +0000778** This function is used as the main routine for a thread launched by
779** testThreadLockingBehavior(). It tests whether the shared-lock obtained
780** by the main thread in testThreadLockingBehavior() conflicts with a
781** hypothetical write-lock obtained by this thread on the same file.
782**
783** The write-lock is not actually acquired, as this is not possible if
784** the file is open in read-only mode (see ticket #3472).
785*/
drh5fdae772004-06-29 03:29:00 +0000786static void *threadLockingTest(void *pArg){
787 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000788 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000789 return pArg;
790}
drh6c7d5c52008-11-21 20:32:33 +0000791#endif /* SQLITE_THREADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000792
drh6c7d5c52008-11-21 20:32:33 +0000793
794#if SQLITE_THREADSAFE && defined(__linux__)
drh5fdae772004-06-29 03:29:00 +0000795/*
796** This procedure attempts to determine whether or not threads
797** can override each others locks then sets the
798** threadsOverrideEachOthersLocks variable appropriately.
799*/
danielk19774d5238f2006-01-27 06:32:00 +0000800static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000801 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000802 int rc;
803 struct threadTestData d;
804 struct flock l;
805 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000806
807 fd = dup(fd_orig);
808 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000809 memset(&l, 0, sizeof(l));
810 l.l_type = F_RDLCK;
811 l.l_len = 1;
812 l.l_start = 0;
813 l.l_whence = SEEK_SET;
814 rc = fcntl(fd_orig, F_SETLK, &l);
815 if( rc!=0 ) return;
816 memset(&d, 0, sizeof(d));
817 d.fd = fd;
818 d.lock = l;
819 d.lock.l_type = F_WRLCK;
820 pthread_create(&t, 0, threadLockingTest, &d);
821 pthread_join(t, 0);
drh5fdae772004-06-29 03:29:00 +0000822 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000823 if( d.result!=0 ) return;
824 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000825}
drh734c9862008-11-28 15:37:20 +0000826#elif SQLITE_THREADSAFE
danielk197741a6a612008-11-11 18:34:35 +0000827/*
828** On anything other than linux, assume threads override each others locks.
829*/
830static void testThreadLockingBehavior(int fd_orig){
drh6c7d5c52008-11-21 20:32:33 +0000831 UNUSED_PARAMETER(fd_orig);
danielk197741a6a612008-11-11 18:34:35 +0000832 threadsOverrideEachOthersLocks = 1;
833}
drh6c7d5c52008-11-21 20:32:33 +0000834#endif /* SQLITE_THERADSAFE && defined(__linux__) */
drh5fdae772004-06-29 03:29:00 +0000835
drhbbd42a62004-05-22 17:41:58 +0000836/*
drh6c7d5c52008-11-21 20:32:33 +0000837** Release a unixLockInfo structure previously allocated by findLockInfo().
838*/
839static void releaseLockInfo(struct unixLockInfo *pLock){
danielk1977e339d652008-06-28 11:23:00 +0000840 if( pLock ){
841 pLock->nRef--;
842 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000843 if( pLock->pPrev ){
844 assert( pLock->pPrev->pNext==pLock );
845 pLock->pPrev->pNext = pLock->pNext;
846 }else{
847 assert( lockList==pLock );
848 lockList = pLock->pNext;
849 }
850 if( pLock->pNext ){
851 assert( pLock->pNext->pPrev==pLock );
852 pLock->pNext->pPrev = pLock->pPrev;
853 }
danielk1977e339d652008-06-28 11:23:00 +0000854 sqlite3_free(pLock);
855 }
drhbbd42a62004-05-22 17:41:58 +0000856 }
857}
858
859/*
drh6c7d5c52008-11-21 20:32:33 +0000860** Release a unixOpenCnt structure previously allocated by findLockInfo().
drhbbd42a62004-05-22 17:41:58 +0000861*/
drh6c7d5c52008-11-21 20:32:33 +0000862static void releaseOpenCnt(struct unixOpenCnt *pOpen){
danielk1977e339d652008-06-28 11:23:00 +0000863 if( pOpen ){
864 pOpen->nRef--;
865 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000866 if( pOpen->pPrev ){
867 assert( pOpen->pPrev->pNext==pOpen );
868 pOpen->pPrev->pNext = pOpen->pNext;
869 }else{
870 assert( openList==pOpen );
871 openList = pOpen->pNext;
872 }
873 if( pOpen->pNext ){
874 assert( pOpen->pNext->pPrev==pOpen );
875 pOpen->pNext->pPrev = pOpen->pPrev;
876 }
877 sqlite3_free(pOpen->aPending);
danielk1977e339d652008-06-28 11:23:00 +0000878 sqlite3_free(pOpen);
879 }
drhbbd42a62004-05-22 17:41:58 +0000880 }
881}
882
drh6c7d5c52008-11-21 20:32:33 +0000883/*
884** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
885** describes that file descriptor. Create new ones if necessary. The
886** return values might be uninitialized if an error occurs.
887**
888** Return an appropriate error code.
889*/
890static int findLockInfo(
891 unixFile *pFile, /* Unix file with file desc used in the key */
892 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */
893 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
894){
895 int rc; /* System call return code */
896 int fd; /* The file descriptor for pFile */
897 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */
898 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
899 struct stat statbuf; /* Low-level file information */
900 struct unixLockInfo *pLock; /* Candidate unixLockInfo object */
901 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
902
903 /* Get low-level information about the file that we can used to
904 ** create a unique name for the file.
905 */
906 fd = pFile->h;
907 rc = fstat(fd, &statbuf);
908 if( rc!=0 ){
909 pFile->lastErrno = errno;
910#ifdef EOVERFLOW
911 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
912#endif
913 return SQLITE_IOERR;
914 }
915
916 /* On OS X on an msdos filesystem, the inode number is reported
917 ** incorrectly for zero-size files. See ticket #3260. To work
918 ** around this problem (we consider it a bug in OS X, not SQLite)
919 ** we always increase the file size to 1 by writing a single byte
920 ** prior to accessing the inode number. The one byte written is
921 ** an ASCII 'S' character which also happens to be the first byte
922 ** in the header of every SQLite database. In this way, if there
923 ** is a race condition such that another thread has already populated
924 ** the first page of the database, no damage is done.
925 */
926 if( statbuf.st_size==0 ){
927 write(fd, "S", 1);
928 rc = fstat(fd, &statbuf);
929 if( rc!=0 ){
930 pFile->lastErrno = errno;
931 return SQLITE_IOERR;
932 }
933 }
934
935 memset(&lockKey, 0, sizeof(lockKey));
936 lockKey.fid.dev = statbuf.st_dev;
937#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000938 lockKey.fid.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +0000939#else
940 lockKey.fid.ino = statbuf.st_ino;
941#endif
drh734c9862008-11-28 15:37:20 +0000942#if SQLITE_THREADSAFE && defined(__linux__)
drh6c7d5c52008-11-21 20:32:33 +0000943 if( threadsOverrideEachOthersLocks<0 ){
944 testThreadLockingBehavior(fd);
945 }
946 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
947#endif
948 fileId = lockKey.fid;
949 if( ppLock!=0 ){
950 pLock = lockList;
951 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
952 pLock = pLock->pNext;
953 }
954 if( pLock==0 ){
955 pLock = sqlite3_malloc( sizeof(*pLock) );
956 if( pLock==0 ){
957 rc = SQLITE_NOMEM;
958 goto exit_findlockinfo;
959 }
960 pLock->lockKey = lockKey;
961 pLock->nRef = 1;
962 pLock->cnt = 0;
963 pLock->locktype = 0;
964 pLock->pNext = lockList;
965 pLock->pPrev = 0;
966 if( lockList ) lockList->pPrev = pLock;
967 lockList = pLock;
968 }else{
969 pLock->nRef++;
970 }
971 *ppLock = pLock;
972 }
973 if( ppOpen!=0 ){
974 pOpen = openList;
975 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
976 pOpen = pOpen->pNext;
977 }
978 if( pOpen==0 ){
979 pOpen = sqlite3_malloc( sizeof(*pOpen) );
980 if( pOpen==0 ){
981 releaseLockInfo(pLock);
982 rc = SQLITE_NOMEM;
983 goto exit_findlockinfo;
984 }
985 pOpen->fileId = fileId;
986 pOpen->nRef = 1;
987 pOpen->nLock = 0;
988 pOpen->nPending = 0;
989 pOpen->aPending = 0;
990 pOpen->pNext = openList;
991 pOpen->pPrev = 0;
992 if( openList ) openList->pPrev = pOpen;
993 openList = pOpen;
994#if OS_VXWORKS
995 pOpen->pSem = NULL;
996 pOpen->aSemName[0] = '\0';
997#endif
998 }else{
999 pOpen->nRef++;
1000 }
1001 *ppOpen = pOpen;
1002 }
1003
1004exit_findlockinfo:
1005 return rc;
1006}
drh6c7d5c52008-11-21 20:32:33 +00001007
drh7708e972008-11-29 00:56:52 +00001008/*
1009** If we are currently in a different thread than the thread that the
1010** unixFile argument belongs to, then transfer ownership of the unixFile
1011** over to the current thread.
1012**
1013** A unixFile is only owned by a thread on systems that use LinuxThreads.
1014**
1015** Ownership transfer is only allowed if the unixFile is currently unlocked.
1016** If the unixFile is locked and an ownership is wrong, then return
1017** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1018*/
1019#if SQLITE_THREADSAFE && defined(__linux__)
1020static int transferOwnership(unixFile *pFile){
1021 int rc;
1022 pthread_t hSelf;
1023 if( threadsOverrideEachOthersLocks ){
1024 /* Ownership transfers not needed on this system */
1025 return SQLITE_OK;
1026 }
1027 hSelf = pthread_self();
1028 if( pthread_equal(pFile->tid, hSelf) ){
1029 /* We are still in the same thread */
1030 OSTRACE1("No-transfer, same thread\n");
1031 return SQLITE_OK;
1032 }
1033 if( pFile->locktype!=NO_LOCK ){
1034 /* We cannot change ownership while we are holding a lock! */
1035 return SQLITE_MISUSE;
1036 }
1037 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1038 pFile->h, pFile->tid, hSelf);
1039 pFile->tid = hSelf;
1040 if (pFile->pLock != NULL) {
1041 releaseLockInfo(pFile->pLock);
1042 rc = findLockInfo(pFile, &pFile->pLock, 0);
1043 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1044 locktypeName(pFile->locktype),
1045 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1046 return rc;
1047 } else {
1048 return SQLITE_OK;
1049 }
1050}
1051#else /* if not SQLITE_THREADSAFE */
1052 /* On single-threaded builds, ownership transfer is a no-op */
1053# define transferOwnership(X) SQLITE_OK
1054#endif /* SQLITE_THREADSAFE */
1055
aswift5b1a2562008-08-22 00:22:35 +00001056
1057/*
danielk197713adf8a2004-06-03 16:08:41 +00001058** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001059** file by this or any other process. If such a lock is held, set *pResOut
1060** to a non-zero value otherwise *pResOut is set to zero. The return value
1061** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001062*/
danielk1977861f7452008-06-05 11:39:11 +00001063static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001064 int rc = SQLITE_OK;
1065 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001066 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001067
danielk1977861f7452008-06-05 11:39:11 +00001068 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1069
drh054889e2005-11-30 03:20:31 +00001070 assert( pFile );
drh6c7d5c52008-11-21 20:32:33 +00001071 unixEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001072
1073 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001074 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001075 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001076 }
1077
drh2ac3ee92004-06-07 16:27:46 +00001078 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001079 */
aswift5b1a2562008-08-22 00:22:35 +00001080 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001081 struct flock lock;
1082 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001083 lock.l_start = RESERVED_BYTE;
1084 lock.l_len = 1;
1085 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001086 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1087 int tErrno = errno;
1088 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1089 pFile->lastErrno = tErrno;
1090 } else if( lock.l_type!=F_UNLCK ){
1091 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001092 }
1093 }
1094
drh6c7d5c52008-11-21 20:32:33 +00001095 unixLeaveMutex();
aswift5b1a2562008-08-22 00:22:35 +00001096 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001097
aswift5b1a2562008-08-22 00:22:35 +00001098 *pResOut = reserved;
1099 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001100}
1101
1102/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001103** Lock the file with the lock specified by parameter locktype - one
1104** of the following:
1105**
drh2ac3ee92004-06-07 16:27:46 +00001106** (1) SHARED_LOCK
1107** (2) RESERVED_LOCK
1108** (3) PENDING_LOCK
1109** (4) EXCLUSIVE_LOCK
1110**
drhb3e04342004-06-08 00:47:47 +00001111** Sometimes when requesting one lock state, additional lock states
1112** are inserted in between. The locking might fail on one of the later
1113** transitions leaving the lock state different from what it started but
1114** still short of its goal. The following chart shows the allowed
1115** transitions and the inserted intermediate states:
1116**
1117** UNLOCKED -> SHARED
1118** SHARED -> RESERVED
1119** SHARED -> (PENDING) -> EXCLUSIVE
1120** RESERVED -> (PENDING) -> EXCLUSIVE
1121** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001122**
drha6abd042004-06-09 17:37:22 +00001123** This routine will only increase a lock. Use the sqlite3OsUnlock()
1124** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001125*/
danielk197762079062007-08-15 17:08:46 +00001126static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001127 /* The following describes the implementation of the various locks and
1128 ** lock transitions in terms of the POSIX advisory shared and exclusive
1129 ** lock primitives (called read-locks and write-locks below, to avoid
1130 ** confusion with SQLite lock names). The algorithms are complicated
1131 ** slightly in order to be compatible with windows systems simultaneously
1132 ** accessing the same database file, in case that is ever required.
1133 **
1134 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1135 ** byte', each single bytes at well known offsets, and the 'shared byte
1136 ** range', a range of 510 bytes at a well known offset.
1137 **
1138 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1139 ** byte'. If this is successful, a random byte from the 'shared byte
1140 ** range' is read-locked and the lock on the 'pending byte' released.
1141 **
danielk197790ba3bd2004-06-25 08:32:25 +00001142 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1143 ** A RESERVED lock is implemented by grabbing a write-lock on the
1144 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001145 **
1146 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001147 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1148 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1149 ** obtained, but existing SHARED locks are allowed to persist. A process
1150 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1151 ** This property is used by the algorithm for rolling back a journal file
1152 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001153 **
danielk197790ba3bd2004-06-25 08:32:25 +00001154 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1155 ** implemented by obtaining a write-lock on the entire 'shared byte
1156 ** range'. Since all other locks require a read-lock on one of the bytes
1157 ** within this range, this ensures that no other locks are held on the
1158 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001159 **
1160 ** The reason a single byte cannot be used instead of the 'shared byte
1161 ** range' is that some versions of windows do not support read-locks. By
1162 ** locking a random byte from a range, concurrent SHARED locks may exist
1163 ** even if the locking primitive used is always a write-lock.
1164 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001165 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001166 unixFile *pFile = (unixFile*)id;
drh6c7d5c52008-11-21 20:32:33 +00001167 struct unixLockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001168 struct flock lock;
1169 int s;
1170
drh054889e2005-11-30 03:20:31 +00001171 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001172 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001173 locktypeName(locktype), locktypeName(pFile->locktype),
1174 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001175
1176 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001177 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001178 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001179 */
drh054889e2005-11-30 03:20:31 +00001180 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001181 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001182 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001183 return SQLITE_OK;
1184 }
1185
drhb3e04342004-06-08 00:47:47 +00001186 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001187 */
drh054889e2005-11-30 03:20:31 +00001188 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001189 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001190 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001191
drh054889e2005-11-30 03:20:31 +00001192 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001193 */
drh6c7d5c52008-11-21 20:32:33 +00001194 unixEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001195
drh029b44b2006-01-15 00:13:15 +00001196 /* Make sure the current thread owns the pFile.
1197 */
1198 rc = transferOwnership(pFile);
1199 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00001200 unixLeaveMutex();
drh029b44b2006-01-15 00:13:15 +00001201 return rc;
1202 }
drh64b1bea2006-01-15 02:30:57 +00001203 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001204
danielk1977ad94b582007-08-20 06:44:22 +00001205 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001206 ** handle that precludes the requested lock, return BUSY.
1207 */
drh054889e2005-11-30 03:20:31 +00001208 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001209 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001210 ){
1211 rc = SQLITE_BUSY;
1212 goto end_lock;
1213 }
1214
1215 /* If a SHARED lock is requested, and some thread using this PID already
1216 ** has a SHARED or RESERVED lock, then increment reference counts and
1217 ** return SQLITE_OK.
1218 */
1219 if( locktype==SHARED_LOCK &&
1220 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1221 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001222 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001223 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001224 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001225 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001226 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001227 goto end_lock;
1228 }
1229
danielk197713adf8a2004-06-03 16:08:41 +00001230 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001231
danielk19779a1d0ab2004-06-01 14:09:28 +00001232 lock.l_whence = SEEK_SET;
1233
drh3cde3bb2004-06-12 02:17:14 +00001234 /* A PENDING lock is needed before acquiring a SHARED lock and before
1235 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1236 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001237 */
drh3cde3bb2004-06-12 02:17:14 +00001238 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001239 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001240 ){
danielk1977489468c2004-06-28 08:25:47 +00001241 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001242 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001243 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001244 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001245 int tErrno = errno;
1246 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1247 if( IS_LOCK_ERROR(rc) ){
1248 pFile->lastErrno = tErrno;
1249 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001250 goto end_lock;
1251 }
drh3cde3bb2004-06-12 02:17:14 +00001252 }
1253
1254
1255 /* If control gets to this point, then actually go ahead and make
1256 ** operating system calls for the specified lock.
1257 */
1258 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001259 int tErrno = 0;
drh3cde3bb2004-06-12 02:17:14 +00001260 assert( pLock->cnt==0 );
1261 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001262
drh2ac3ee92004-06-07 16:27:46 +00001263 /* Now get the read-lock */
1264 lock.l_start = SHARED_FIRST;
1265 lock.l_len = SHARED_SIZE;
aswift5b1a2562008-08-22 00:22:35 +00001266 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1267 tErrno = errno;
1268 }
drh2ac3ee92004-06-07 16:27:46 +00001269 /* Drop the temporary PENDING lock */
1270 lock.l_start = PENDING_BYTE;
1271 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001272 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001273 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001274 if( s != -1 ){
1275 /* This could happen with a network mount */
1276 tErrno = errno;
1277 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1278 if( IS_LOCK_ERROR(rc) ){
1279 pFile->lastErrno = tErrno;
1280 }
1281 goto end_lock;
1282 }
drh2b4b5962005-06-15 17:47:55 +00001283 }
drhe2396a12007-03-29 20:19:58 +00001284 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001285 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1286 if( IS_LOCK_ERROR(rc) ){
1287 pFile->lastErrno = tErrno;
1288 }
drhbbd42a62004-05-22 17:41:58 +00001289 }else{
drh054889e2005-11-30 03:20:31 +00001290 pFile->locktype = SHARED_LOCK;
1291 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001292 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001293 }
drh3cde3bb2004-06-12 02:17:14 +00001294 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1295 /* We are trying for an exclusive lock but another thread in this
1296 ** same process is still holding a shared lock. */
1297 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001298 }else{
drh3cde3bb2004-06-12 02:17:14 +00001299 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001300 ** assumed that there is a SHARED or greater lock on the file
1301 ** already.
1302 */
drh054889e2005-11-30 03:20:31 +00001303 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001304 lock.l_type = F_WRLCK;
1305 switch( locktype ){
1306 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001307 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001308 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001309 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001310 lock.l_start = SHARED_FIRST;
1311 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001312 break;
1313 default:
1314 assert(0);
1315 }
drh054889e2005-11-30 03:20:31 +00001316 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001317 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001318 int tErrno = errno;
1319 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1320 if( IS_LOCK_ERROR(rc) ){
1321 pFile->lastErrno = tErrno;
1322 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001323 }
drhbbd42a62004-05-22 17:41:58 +00001324 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001325
danielk1977ecb2a962004-06-02 06:30:16 +00001326 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001327 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001328 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001329 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001330 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001331 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001332 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001333
1334end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001335 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001336 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001337 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001338 return rc;
1339}
1340
1341/*
drh054889e2005-11-30 03:20:31 +00001342** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001343** must be either NO_LOCK or SHARED_LOCK.
1344**
1345** If the locking level of the file descriptor is already at or below
1346** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001347*/
danielk197762079062007-08-15 17:08:46 +00001348static int unixUnlock(sqlite3_file *id, int locktype){
drh6c7d5c52008-11-21 20:32:33 +00001349 struct unixLockInfo *pLock;
drha6abd042004-06-09 17:37:22 +00001350 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001351 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001352 unixFile *pFile = (unixFile*)id;
drh1aa5af12008-03-07 19:51:14 +00001353 int h;
drha6abd042004-06-09 17:37:22 +00001354
drh054889e2005-11-30 03:20:31 +00001355 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001356 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001357 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001358
1359 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001360 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001361 return SQLITE_OK;
1362 }
drhf1a221e2006-01-15 17:27:17 +00001363 if( CHECK_THREADID(pFile) ){
1364 return SQLITE_MISUSE;
1365 }
drh6c7d5c52008-11-21 20:32:33 +00001366 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001367 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001368 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001369 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001370 if( pFile->locktype>SHARED_LOCK ){
1371 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001372 SimulateIOErrorBenign(1);
1373 SimulateIOError( h=(-1) )
1374 SimulateIOErrorBenign(0);
drh9c105bb2004-10-02 20:38:28 +00001375 if( locktype==SHARED_LOCK ){
1376 lock.l_type = F_RDLCK;
1377 lock.l_whence = SEEK_SET;
1378 lock.l_start = SHARED_FIRST;
1379 lock.l_len = SHARED_SIZE;
drh1aa5af12008-03-07 19:51:14 +00001380 if( fcntl(h, F_SETLK, &lock)==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001381 int tErrno = errno;
1382 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1383 if( IS_LOCK_ERROR(rc) ){
1384 pFile->lastErrno = tErrno;
1385 }
1386 goto end_unlock;
drh9c105bb2004-10-02 20:38:28 +00001387 }
1388 }
drhbbd42a62004-05-22 17:41:58 +00001389 lock.l_type = F_UNLCK;
1390 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001391 lock.l_start = PENDING_BYTE;
1392 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001393 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001394 pLock->locktype = SHARED_LOCK;
1395 }else{
aswift5b1a2562008-08-22 00:22:35 +00001396 int tErrno = errno;
1397 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1398 if( IS_LOCK_ERROR(rc) ){
1399 pFile->lastErrno = tErrno;
1400 }
1401 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001402 }
drhbbd42a62004-05-22 17:41:58 +00001403 }
drha6abd042004-06-09 17:37:22 +00001404 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00001405 struct unixOpenCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001406
drha6abd042004-06-09 17:37:22 +00001407 /* Decrement the shared lock counter. Release the lock using an
1408 ** OS call only when all threads in this same process have released
1409 ** the lock.
1410 */
1411 pLock->cnt--;
1412 if( pLock->cnt==0 ){
1413 lock.l_type = F_UNLCK;
1414 lock.l_whence = SEEK_SET;
1415 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001416 SimulateIOErrorBenign(1);
1417 SimulateIOError( h=(-1) )
1418 SimulateIOErrorBenign(0);
1419 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001420 pLock->locktype = NO_LOCK;
1421 }else{
aswift5b1a2562008-08-22 00:22:35 +00001422 int tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001423 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001424 if( IS_LOCK_ERROR(rc) ){
1425 pFile->lastErrno = tErrno;
1426 }
drh1aa5af12008-03-07 19:51:14 +00001427 pLock->cnt = 1;
aswift5b1a2562008-08-22 00:22:35 +00001428 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001429 }
drha6abd042004-06-09 17:37:22 +00001430 }
1431
drhbbd42a62004-05-22 17:41:58 +00001432 /* Decrement the count of locks against this same file. When the
1433 ** count reaches zero, close any other file descriptors whose close
1434 ** was deferred because of outstanding locks.
1435 */
drh1aa5af12008-03-07 19:51:14 +00001436 if( rc==SQLITE_OK ){
1437 pOpen = pFile->pOpen;
1438 pOpen->nLock--;
1439 assert( pOpen->nLock>=0 );
1440 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1441 int i;
1442 for(i=0; i<pOpen->nPending; i++){
aswiftaebf4132008-11-21 00:10:35 +00001443 /* close pending fds, but if closing fails don't free the array
1444 ** assign -1 to the successfully closed descriptors and record the
1445 ** error. The next attempt to unlock will try again. */
1446 if( pOpen->aPending[i] < 0 ) continue;
1447 if( close(pOpen->aPending[i]) ){
1448 pFile->lastErrno = errno;
1449 rc = SQLITE_IOERR_CLOSE;
1450 }else{
1451 pOpen->aPending[i] = -1;
1452 }
drh1aa5af12008-03-07 19:51:14 +00001453 }
aswiftaebf4132008-11-21 00:10:35 +00001454 if( rc==SQLITE_OK ){
1455 sqlite3_free(pOpen->aPending);
1456 pOpen->nPending = 0;
1457 pOpen->aPending = 0;
1458 }
drhbbd42a62004-05-22 17:41:58 +00001459 }
drhbbd42a62004-05-22 17:41:58 +00001460 }
1461 }
aswift5b1a2562008-08-22 00:22:35 +00001462
1463end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001464 unixLeaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001465 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001466 return rc;
drhbbd42a62004-05-22 17:41:58 +00001467}
1468
1469/*
danielk1977e339d652008-06-28 11:23:00 +00001470** This function performs the parts of the "close file" operation
1471** common to all locking schemes. It closes the directory and file
1472** handles, if they are valid, and sets all fields of the unixFile
1473** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001474**
1475** It is *not* necessary to hold the mutex when this routine is called,
1476** even on VxWorks. A mutex will be acquired on VxWorks by the
1477** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001478*/
1479static int closeUnixFile(sqlite3_file *id){
1480 unixFile *pFile = (unixFile*)id;
1481 if( pFile ){
1482 if( pFile->dirfd>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001483 int err = close(pFile->dirfd);
1484 if( err ){
1485 pFile->lastErrno = errno;
1486 return SQLITE_IOERR_DIR_CLOSE;
1487 }else{
1488 pFile->dirfd=-1;
1489 }
danielk1977e339d652008-06-28 11:23:00 +00001490 }
1491 if( pFile->h>=0 ){
aswiftaebf4132008-11-21 00:10:35 +00001492 int err = close(pFile->h);
1493 if( err ){
1494 pFile->lastErrno = errno;
1495 return SQLITE_IOERR_CLOSE;
1496 }
danielk1977e339d652008-06-28 11:23:00 +00001497 }
drh6c7d5c52008-11-21 20:32:33 +00001498#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001499 if( pFile->pId ){
1500 if( pFile->isDelete ){
drh9b35ea62008-11-29 02:20:26 +00001501 unlink(pFile->pId->zCanonicalName);
chw97185482008-11-17 08:05:31 +00001502 }
drh107886a2008-11-21 22:21:50 +00001503 vxworksReleaseFileId(pFile->pId);
1504 pFile->pId = 0;
chw97185482008-11-17 08:05:31 +00001505 }
1506#endif
danielk1977e339d652008-06-28 11:23:00 +00001507 OSTRACE2("CLOSE %-3d\n", pFile->h);
1508 OpenCounter(-1);
1509 memset(pFile, 0, sizeof(unixFile));
1510 }
1511 return SQLITE_OK;
1512}
1513
1514/*
danielk1977e3026632004-06-22 11:29:02 +00001515** Close a file.
1516*/
danielk197762079062007-08-15 17:08:46 +00001517static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001518 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00001519 if( id ){
1520 unixFile *pFile = (unixFile *)id;
1521 unixUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00001522 unixEnterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001523 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001524 /* If there are outstanding locks, do not actually close the file just
1525 ** yet because that would clear those locks. Instead, add the file
1526 ** descriptor to pOpen->aPending. It will be automatically closed when
1527 ** the last lock is cleared.
1528 */
1529 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00001530 struct unixOpenCnt *pOpen = pFile->pOpen;
drhda0e7682008-07-30 15:27:54 +00001531 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e339d652008-06-28 11:23:00 +00001532 if( aNew==0 ){
1533 /* If a malloc fails, just leak the file descriptor */
1534 }else{
1535 pOpen->aPending = aNew;
1536 pOpen->aPending[pOpen->nPending] = pFile->h;
1537 pOpen->nPending++;
1538 pFile->h = -1;
1539 }
danielk1977e3026632004-06-22 11:29:02 +00001540 }
danielk1977e339d652008-06-28 11:23:00 +00001541 releaseLockInfo(pFile->pLock);
1542 releaseOpenCnt(pFile->pOpen);
aswiftaebf4132008-11-21 00:10:35 +00001543 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00001544 unixLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001545 }
aswiftaebf4132008-11-21 00:10:35 +00001546 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001547}
1548
drh734c9862008-11-28 15:37:20 +00001549/************** End of the posix advisory lock implementation *****************
1550******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001551
drh734c9862008-11-28 15:37:20 +00001552/******************************************************************************
1553****************************** No-op Locking **********************************
1554**
1555** Of the various locking implementations available, this is by far the
1556** simplest: locking is ignored. No attempt is made to lock the database
1557** file for reading or writing.
1558**
1559** This locking mode is appropriate for use on read-only databases
1560** (ex: databases that are burned into CD-ROM, for example.) It can
1561** also be used if the application employs some external mechanism to
1562** prevent simultaneous access of the same database by two or more
1563** database connections. But there is a serious risk of database
1564** corruption if this locking mode is used in situations where multiple
1565** database connections are accessing the same database file at the same
1566** time and one or more of those connections are writing.
1567*/
drhbfe66312006-10-03 17:40:40 +00001568
drh734c9862008-11-28 15:37:20 +00001569static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1570 UNUSED_PARAMETER(NotUsed);
1571 *pResOut = 0;
1572 return SQLITE_OK;
1573}
drh734c9862008-11-28 15:37:20 +00001574static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1575 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1576 return SQLITE_OK;
1577}
drh734c9862008-11-28 15:37:20 +00001578static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1579 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1580 return SQLITE_OK;
1581}
1582
1583/*
drh9b35ea62008-11-29 02:20:26 +00001584** Close the file.
drh734c9862008-11-28 15:37:20 +00001585*/
1586static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001587 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001588}
1589
1590/******************* End of the no-op lock implementation *********************
1591******************************************************************************/
1592
1593/******************************************************************************
1594************************* Begin dot-file Locking ******************************
1595**
1596** The dotfile locking implementation uses the existing of separate lock
1597** files in order to control access to the database. This works on just
1598** about every filesystem imaginable. But there are serious downsides:
1599**
1600** (1) There is zero concurrency. A single reader blocks all other
1601** connections from reading or writing the database.
1602**
1603** (2) An application crash or power loss can leave stale lock files
1604** sitting around that need to be cleared manually.
1605**
1606** Nevertheless, a dotlock is an appropriate locking mode for use if no
1607** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001608**
1609** Dotfile locking works by creating a file in the same directory as the
1610** database and with the same name but with a ".lock" extension added.
1611** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1612** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001613*/
1614
1615/*
1616** The file suffix added to the data base filename in order to create the
1617** lock file.
1618*/
1619#define DOTLOCK_SUFFIX ".lock"
1620
drh7708e972008-11-29 00:56:52 +00001621/*
1622** This routine checks if there is a RESERVED lock held on the specified
1623** file by this or any other process. If such a lock is held, set *pResOut
1624** to a non-zero value otherwise *pResOut is set to zero. The return value
1625** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1626**
1627** In dotfile locking, either a lock exists or it does not. So in this
1628** variation of CheckReservedLock(), *pResOut is set to true if any lock
1629** is held on the file and false if the file is unlocked.
1630*/
drh734c9862008-11-28 15:37:20 +00001631static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1632 int rc = SQLITE_OK;
1633 int reserved = 0;
1634 unixFile *pFile = (unixFile*)id;
1635
1636 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1637
1638 assert( pFile );
1639
1640 /* Check if a thread in this process holds such a lock */
1641 if( pFile->locktype>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001642 /* Either this connection or some other connection in the same process
1643 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001644 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001645 }else{
1646 /* The lock is held if and only if the lockfile exists */
1647 const char *zLockFile = (const char*)pFile->lockingContext;
1648 reserved = access(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001649 }
1650 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
drh734c9862008-11-28 15:37:20 +00001651 *pResOut = reserved;
1652 return rc;
1653}
1654
drh7708e972008-11-29 00:56:52 +00001655/*
1656** Lock the file with the lock specified by parameter locktype - one
1657** of the following:
1658**
1659** (1) SHARED_LOCK
1660** (2) RESERVED_LOCK
1661** (3) PENDING_LOCK
1662** (4) EXCLUSIVE_LOCK
1663**
1664** Sometimes when requesting one lock state, additional lock states
1665** are inserted in between. The locking might fail on one of the later
1666** transitions leaving the lock state different from what it started but
1667** still short of its goal. The following chart shows the allowed
1668** transitions and the inserted intermediate states:
1669**
1670** UNLOCKED -> SHARED
1671** SHARED -> RESERVED
1672** SHARED -> (PENDING) -> EXCLUSIVE
1673** RESERVED -> (PENDING) -> EXCLUSIVE
1674** PENDING -> EXCLUSIVE
1675**
1676** This routine will only increase a lock. Use the sqlite3OsUnlock()
1677** routine to lower a locking level.
1678**
1679** With dotfile locking, we really only support state (4): EXCLUSIVE.
1680** But we track the other locking levels internally.
1681*/
drh734c9862008-11-28 15:37:20 +00001682static int dotlockLock(sqlite3_file *id, int locktype) {
1683 unixFile *pFile = (unixFile*)id;
1684 int fd;
1685 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001686 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001687
drh7708e972008-11-29 00:56:52 +00001688
1689 /* If we have any lock, then the lock file already exists. All we have
1690 ** to do is adjust our internal record of the lock level.
1691 */
1692 if( pFile->locktype > NO_LOCK ){
drh734c9862008-11-28 15:37:20 +00001693 pFile->locktype = locktype;
1694#if !OS_VXWORKS
1695 /* Always update the timestamp on the old file */
1696 utimes(zLockFile, NULL);
1697#endif
drh7708e972008-11-29 00:56:52 +00001698 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001699 }
1700
1701 /* grab an exclusive lock */
1702 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1703 if( fd<0 ){
1704 /* failed to open/create the file, someone else may have stolen the lock */
1705 int tErrno = errno;
1706 if( EEXIST == tErrno ){
1707 rc = SQLITE_BUSY;
1708 } else {
1709 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1710 if( IS_LOCK_ERROR(rc) ){
1711 pFile->lastErrno = tErrno;
1712 }
1713 }
drh7708e972008-11-29 00:56:52 +00001714 return rc;
drh734c9862008-11-28 15:37:20 +00001715 }
1716 if( close(fd) ){
1717 pFile->lastErrno = errno;
1718 rc = SQLITE_IOERR_CLOSE;
1719 }
1720
1721 /* got it, set the type and return ok */
1722 pFile->locktype = locktype;
drh734c9862008-11-28 15:37:20 +00001723 return rc;
1724}
1725
drh7708e972008-11-29 00:56:52 +00001726/*
1727** Lower the locking level on file descriptor pFile to locktype. locktype
1728** must be either NO_LOCK or SHARED_LOCK.
1729**
1730** If the locking level of the file descriptor is already at or below
1731** the requested locking level, this routine is a no-op.
1732**
1733** When the locking level reaches NO_LOCK, delete the lock file.
1734*/
drh734c9862008-11-28 15:37:20 +00001735static int dotlockUnlock(sqlite3_file *id, int locktype) {
1736 unixFile *pFile = (unixFile*)id;
1737 char *zLockFile = (char *)pFile->lockingContext;
1738
1739 assert( pFile );
1740 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1741 pFile->locktype, getpid());
1742 assert( locktype<=SHARED_LOCK );
1743
1744 /* no-op if possible */
1745 if( pFile->locktype==locktype ){
1746 return SQLITE_OK;
1747 }
drh7708e972008-11-29 00:56:52 +00001748
1749 /* To downgrade to shared, simply update our internal notion of the
1750 ** lock state. No need to mess with the file on disk.
1751 */
1752 if( locktype==SHARED_LOCK ){
1753 pFile->locktype = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00001754 return SQLITE_OK;
1755 }
1756
drh7708e972008-11-29 00:56:52 +00001757 /* To fully unlock the database, delete the lock file */
1758 assert( locktype==NO_LOCK );
1759 if( unlink(zLockFile) ){
drh734c9862008-11-28 15:37:20 +00001760 int rc, tErrno = errno;
1761 if( ENOENT != tErrno ){
1762 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1763 }
1764 if( IS_LOCK_ERROR(rc) ){
1765 pFile->lastErrno = tErrno;
1766 }
1767 return rc;
1768 }
1769 pFile->locktype = NO_LOCK;
1770 return SQLITE_OK;
1771}
1772
1773/*
drh9b35ea62008-11-29 02:20:26 +00001774** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00001775*/
1776static int dotlockClose(sqlite3_file *id) {
1777 int rc;
1778 if( id ){
1779 unixFile *pFile = (unixFile*)id;
1780 dotlockUnlock(id, NO_LOCK);
1781 sqlite3_free(pFile->lockingContext);
1782 }
drh734c9862008-11-28 15:37:20 +00001783 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001784 return rc;
1785}
1786/****************** End of the dot-file lock implementation *******************
1787******************************************************************************/
1788
1789/******************************************************************************
1790************************** Begin flock Locking ********************************
1791**
1792** Use the flock() system call to do file locking.
1793**
1794** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
1795** compiling for VXWORKS.
1796*/
1797#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00001798
1799/* flock-style reserved lock checking following the behavior of
1800 ** unixCheckReservedLock, see the unixCheckReservedLock function comments */
1801static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1802 int rc = SQLITE_OK;
1803 int reserved = 0;
1804 unixFile *pFile = (unixFile*)id;
1805
1806 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1807
1808 assert( pFile );
1809
1810 /* Check if a thread in this process holds such a lock */
1811 if( pFile->locktype>SHARED_LOCK ){
1812 reserved = 1;
1813 }
1814
1815 /* Otherwise see if some other process holds it. */
1816 if( !reserved ){
1817 /* attempt to get the lock */
1818 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
1819 if( !lrc ){
1820 /* got the lock, unlock it */
1821 lrc = flock(pFile->h, LOCK_UN);
1822 if ( lrc ) {
1823 int tErrno = errno;
1824 /* unlock failed with an error */
1825 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1826 if( IS_LOCK_ERROR(lrc) ){
1827 pFile->lastErrno = tErrno;
1828 rc = lrc;
1829 }
1830 }
1831 } else {
1832 int tErrno = errno;
1833 reserved = 1;
1834 /* someone else might have it reserved */
1835 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1836 if( IS_LOCK_ERROR(lrc) ){
1837 pFile->lastErrno = tErrno;
1838 rc = lrc;
1839 }
1840 }
1841 }
1842 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
1843
1844#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1845 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1846 rc = SQLITE_OK;
1847 reserved=1;
1848 }
1849#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1850 *pResOut = reserved;
1851 return rc;
1852}
1853
1854static int flockLock(sqlite3_file *id, int locktype) {
1855 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001856 unixFile *pFile = (unixFile*)id;
1857
1858 assert( pFile );
1859
1860 /* if we already have a lock, it is exclusive.
1861 ** Just adjust level and punt on outta here. */
1862 if (pFile->locktype > NO_LOCK) {
1863 pFile->locktype = locktype;
1864 return SQLITE_OK;
1865 }
1866
1867 /* grab an exclusive lock */
1868
1869 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
1870 int tErrno = errno;
1871 /* didn't get, must be busy */
1872 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1873 if( IS_LOCK_ERROR(rc) ){
1874 pFile->lastErrno = tErrno;
1875 }
1876 } else {
1877 /* got it, set the type and return ok */
1878 pFile->locktype = locktype;
1879 }
1880 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
1881 rc==SQLITE_OK ? "ok" : "failed");
1882#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1883 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
1884 rc = SQLITE_BUSY;
1885 }
1886#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1887 return rc;
1888}
1889
1890static int flockUnlock(sqlite3_file *id, int locktype) {
1891 unixFile *pFile = (unixFile*)id;
1892
1893 assert( pFile );
1894 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1895 pFile->locktype, getpid());
1896 assert( locktype<=SHARED_LOCK );
1897
1898 /* no-op if possible */
1899 if( pFile->locktype==locktype ){
1900 return SQLITE_OK;
1901 }
1902
1903 /* shared can just be set because we always have an exclusive */
1904 if (locktype==SHARED_LOCK) {
1905 pFile->locktype = locktype;
1906 return SQLITE_OK;
1907 }
1908
1909 /* no, really, unlock. */
1910 int rc = flock(pFile->h, LOCK_UN);
1911 if (rc) {
1912 int r, tErrno = errno;
1913 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1914 if( IS_LOCK_ERROR(r) ){
1915 pFile->lastErrno = tErrno;
1916 }
1917#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
1918 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
1919 r = SQLITE_BUSY;
1920 }
1921#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
1922
1923 return r;
1924 } else {
1925 pFile->locktype = NO_LOCK;
1926 return SQLITE_OK;
1927 }
1928}
1929
1930/*
1931** Close a file.
1932*/
1933static int flockClose(sqlite3_file *id) {
1934 if( id ){
1935 flockUnlock(id, NO_LOCK);
1936 }
1937 return closeUnixFile(id);
1938}
1939
1940#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
1941
1942/******************* End of the flock lock implementation *********************
1943******************************************************************************/
1944
1945/******************************************************************************
1946************************ Begin Named Semaphore Locking ************************
1947**
1948** Named semaphore locking is only supported on VxWorks.
1949*/
1950#if OS_VXWORKS
1951
1952/* Namedsem-style reserved lock checking following the behavior of
1953** unixCheckReservedLock, see the unixCheckReservedLock function comments */
1954static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
1955 int rc = SQLITE_OK;
1956 int reserved = 0;
1957 unixFile *pFile = (unixFile*)id;
1958
1959 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1960
1961 assert( pFile );
1962
1963 /* Check if a thread in this process holds such a lock */
1964 if( pFile->locktype>SHARED_LOCK ){
1965 reserved = 1;
1966 }
1967
1968 /* Otherwise see if some other process holds it. */
1969 if( !reserved ){
1970 sem_t *pSem = pFile->pOpen->pSem;
1971 struct stat statBuf;
1972
1973 if( sem_trywait(pSem)==-1 ){
1974 int tErrno = errno;
1975 if( EAGAIN != tErrno ){
1976 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1977 pFile->lastErrno = tErrno;
1978 } else {
1979 /* someone else has the lock when we are in NO_LOCK */
1980 reserved = (pFile->locktype < SHARED_LOCK);
1981 }
1982 }else{
1983 /* we could have it if we want it */
1984 sem_post(pSem);
1985 }
1986 }
1987 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
1988
1989 *pResOut = reserved;
1990 return rc;
1991}
1992
1993static int semLock(sqlite3_file *id, int locktype) {
1994 unixFile *pFile = (unixFile*)id;
1995 int fd;
1996 sem_t *pSem = pFile->pOpen->pSem;
1997 int rc = SQLITE_OK;
1998
1999 /* if we already have a lock, it is exclusive.
2000 ** Just adjust level and punt on outta here. */
2001 if (pFile->locktype > NO_LOCK) {
2002 pFile->locktype = locktype;
2003 rc = SQLITE_OK;
2004 goto sem_end_lock;
2005 }
2006
2007 /* lock semaphore now but bail out when already locked. */
2008 if( sem_trywait(pSem)==-1 ){
2009 rc = SQLITE_BUSY;
2010 goto sem_end_lock;
2011 }
2012
2013 /* got it, set the type and return ok */
2014 pFile->locktype = locktype;
2015
2016 sem_end_lock:
2017 return rc;
2018}
2019
2020static int semUnlock(sqlite3_file *id, int locktype) {
2021 unixFile *pFile = (unixFile*)id;
2022 sem_t *pSem = pFile->pOpen->pSem;
2023
2024 assert( pFile );
2025 assert( pSem );
2026 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2027 pFile->locktype, getpid());
2028 assert( locktype<=SHARED_LOCK );
2029
2030 /* no-op if possible */
2031 if( pFile->locktype==locktype ){
2032 return SQLITE_OK;
2033 }
2034
2035 /* shared can just be set because we always have an exclusive */
2036 if (locktype==SHARED_LOCK) {
2037 pFile->locktype = locktype;
2038 return SQLITE_OK;
2039 }
2040
2041 /* no, really unlock. */
2042 if ( sem_post(pSem)==-1 ) {
2043 int rc, tErrno = errno;
2044 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2045 if( IS_LOCK_ERROR(rc) ){
2046 pFile->lastErrno = tErrno;
2047 }
2048 return rc;
2049 }
2050 pFile->locktype = NO_LOCK;
2051 return SQLITE_OK;
2052}
2053
2054/*
2055 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002056 */
drh734c9862008-11-28 15:37:20 +00002057static int semClose(sqlite3_file *id) {
2058 if( id ){
2059 unixFile *pFile = (unixFile*)id;
2060 semUnlock(id, NO_LOCK);
2061 assert( pFile );
2062 unixEnterMutex();
2063 releaseLockInfo(pFile->pLock);
2064 releaseOpenCnt(pFile->pOpen);
2065 closeUnixFile(id);
2066 unixLeaveMutex();
2067 }
2068 return SQLITE_OK;
2069}
2070
2071#endif /* OS_VXWORKS */
2072/*
2073** Named semaphore locking is only available on VxWorks.
2074**
2075*************** End of the named semaphore lock implementation ****************
2076******************************************************************************/
2077
2078
2079/******************************************************************************
2080*************************** Begin AFP Locking *********************************
2081**
2082** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2083** on Apple Macintosh computers - both OS9 and OSX.
2084**
2085** Third-party implementations of AFP are available. But this code here
2086** only works on OSX.
2087*/
2088
2089#if defined(__DARWIN__) && SQLITE_ENABLE_LOCKING_STYLE
2090/*
2091** The afpLockingContext structure contains all afp lock specific state
2092*/
drhbfe66312006-10-03 17:40:40 +00002093typedef struct afpLockingContext afpLockingContext;
2094struct afpLockingContext {
aswiftaebf4132008-11-21 00:10:35 +00002095 unsigned long long sharedByte;
2096 const char *dbPath;
drhbfe66312006-10-03 17:40:40 +00002097};
2098
2099struct ByteRangeLockPB2
2100{
2101 unsigned long long offset; /* offset to first byte to lock */
2102 unsigned long long length; /* nbr of bytes to lock */
2103 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2104 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2105 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2106 int fd; /* file desc to assoc this lock with */
2107};
2108
drhfd131da2007-08-07 17:13:03 +00002109#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002110
danielk1977ad94b582007-08-20 06:44:22 +00002111/*
aswift5b1a2562008-08-22 00:22:35 +00002112 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2113 */
danielk1977ad94b582007-08-20 06:44:22 +00002114static int _AFPFSSetLock(
2115 const char *path,
aswift5b1a2562008-08-22 00:22:35 +00002116 unixFile *pFile,
danielk1977ad94b582007-08-20 06:44:22 +00002117 unsigned long long offset,
2118 unsigned long long length,
2119 int setLockFlag
2120){
drhfd131da2007-08-07 17:13:03 +00002121 struct ByteRangeLockPB2 pb;
drhbfe66312006-10-03 17:40:40 +00002122 int err;
2123
2124 pb.unLockFlag = setLockFlag ? 0 : 1;
2125 pb.startEndFlag = 0;
2126 pb.offset = offset;
2127 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002128 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002129 //SimulateIOErrorBenign(1);
2130 //SimulateIOError( pb.fd=(-1) )
2131 //SimulateIOErrorBenign(0);
2132
2133 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002134 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2135 offset, length);
drhbfe66312006-10-03 17:40:40 +00002136 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2137 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002138 int rc;
2139 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002140 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2141 path, tErrno, strerror(tErrno));
aswiftaebf4132008-11-21 00:10:35 +00002142#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2143 rc = SQLITE_BUSY;
2144#else
drh734c9862008-11-28 15:37:20 +00002145 rc = sqliteErrorFromPosixError(tErrno,
2146 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002147#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002148 if( IS_LOCK_ERROR(rc) ){
2149 pFile->lastErrno = tErrno;
2150 }
2151 return rc;
drhbfe66312006-10-03 17:40:40 +00002152 } else {
aswift5b1a2562008-08-22 00:22:35 +00002153 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002154 }
2155}
2156
aswift5b1a2562008-08-22 00:22:35 +00002157/* AFP-style reserved lock checking following the behavior of
2158** unixCheckReservedLock, see the unixCheckReservedLock function comments */
danielk1977e339d652008-06-28 11:23:00 +00002159static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002160 int rc = SQLITE_OK;
2161 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002162 unixFile *pFile = (unixFile*)id;
2163
aswift5b1a2562008-08-22 00:22:35 +00002164 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2165
2166 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002167 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2168
2169 /* Check if a thread in this process holds such a lock */
2170 if( pFile->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002171 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002172 }
2173
2174 /* Otherwise see if some other process holds it.
2175 */
aswift5b1a2562008-08-22 00:22:35 +00002176 if( !reserved ){
2177 /* lock the RESERVED byte */
aswiftaebf4132008-11-21 00:10:35 +00002178 int lrc = _AFPFSSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002179 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002180 /* if we succeeded in taking the reserved lock, unlock it to restore
2181 ** the original state */
aswiftaebf4132008-11-21 00:10:35 +00002182 lrc = _AFPFSSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002183 } else {
2184 /* if we failed to get the lock then someone else must have it */
2185 reserved = 1;
2186 }
2187 if( IS_LOCK_ERROR(lrc) ){
2188 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002189 }
2190 }
drhbfe66312006-10-03 17:40:40 +00002191
aswift5b1a2562008-08-22 00:22:35 +00002192 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2193
2194 *pResOut = reserved;
2195 return rc;
drhbfe66312006-10-03 17:40:40 +00002196}
2197
2198/* AFP-style locking following the behavior of unixLock, see the unixLock
2199** function comments for details of lock management. */
danielk1977e339d652008-06-28 11:23:00 +00002200static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00002201 int rc = SQLITE_OK;
2202 unixFile *pFile = (unixFile*)id;
2203 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002204
2205 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002206 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00002207 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
2208
drhbfe66312006-10-03 17:40:40 +00002209 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002210 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002211 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002212 */
drhbfe66312006-10-03 17:40:40 +00002213 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00002214 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002215 locktypeName(locktype));
2216 return SQLITE_OK;
2217 }
2218
2219 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00002220 */
drhbfe66312006-10-03 17:40:40 +00002221 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2222 assert( locktype!=PENDING_LOCK );
2223 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2224
2225 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002226 */
drh6c7d5c52008-11-21 20:32:33 +00002227 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002228
2229 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002230 */
drhbfe66312006-10-03 17:40:40 +00002231 rc = transferOwnership(pFile);
2232 if( rc!=SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00002233 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00002234 return rc;
2235 }
2236
2237 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002238 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2239 ** be released.
2240 */
drhbfe66312006-10-03 17:40:40 +00002241 if( locktype==SHARED_LOCK
2242 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002243 ){
2244 int failed;
aswiftaebf4132008-11-21 00:10:35 +00002245 failed = _AFPFSSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002246 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002247 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002248 goto afp_end_lock;
2249 }
2250 }
2251
2252 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002253 ** operating system calls for the specified lock.
2254 */
drhbfe66312006-10-03 17:40:40 +00002255 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002256 int lk, lrc1, lrc2, lrc1Errno;
drhbfe66312006-10-03 17:40:40 +00002257
aswift5b1a2562008-08-22 00:22:35 +00002258 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002259 /* note that the quality of the randomness doesn't matter that much */
2260 lk = random();
aswiftaebf4132008-11-21 00:10:35 +00002261 context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
2262 lrc1 = _AFPFSSetLock(context->dbPath, pFile,
2263 SHARED_FIRST+context->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002264 if( IS_LOCK_ERROR(lrc1) ){
2265 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002266 }
aswift5b1a2562008-08-22 00:22:35 +00002267 /* Drop the temporary PENDING lock */
aswiftaebf4132008-11-21 00:10:35 +00002268 lrc2 = _AFPFSSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002269
aswift5b1a2562008-08-22 00:22:35 +00002270 if( IS_LOCK_ERROR(lrc1) ) {
2271 pFile->lastErrno = lrc1Errno;
2272 rc = lrc1;
2273 goto afp_end_lock;
2274 } else if( IS_LOCK_ERROR(lrc2) ){
2275 rc = lrc2;
2276 goto afp_end_lock;
2277 } else if( lrc1 != SQLITE_OK ) {
2278 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002279 } else {
2280 pFile->locktype = SHARED_LOCK;
aswiftaebf4132008-11-21 00:10:35 +00002281 pFile->pOpen->nLock++;
drhbfe66312006-10-03 17:40:40 +00002282 }
2283 }else{
2284 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2285 ** assumed that there is a SHARED or greater lock on the file
2286 ** already.
2287 */
2288 int failed = 0;
2289 assert( 0!=pFile->locktype );
2290 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2291 /* Acquire a RESERVED lock */
aswiftaebf4132008-11-21 00:10:35 +00002292 failed = _AFPFSSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drhbfe66312006-10-03 17:40:40 +00002293 }
2294 if (!failed && locktype == EXCLUSIVE_LOCK) {
2295 /* Acquire an EXCLUSIVE lock */
2296
2297 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002298 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002299 */
aswiftaebf4132008-11-21 00:10:35 +00002300 if( !(failed = _AFPFSSetLock(context->dbPath, pFile, SHARED_FIRST +
2301 context->sharedByte, 1, 0)) ){
2302 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002303 /* now attemmpt to get the exclusive lock range */
aswiftaebf4132008-11-21 00:10:35 +00002304 failed = _AFPFSSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002305 SHARED_SIZE, 1);
aswiftaebf4132008-11-21 00:10:35 +00002306 if( failed && (failed2 = _AFPFSSetLock(context->dbPath, pFile,
2307 SHARED_FIRST + context->sharedByte, 1, 1)) ){
2308 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2309 ** a critical I/O error
2310 */
2311 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2312 SQLITE_IOERR_LOCK;
2313 goto afp_end_lock;
2314 }
2315 }else{
aswift5b1a2562008-08-22 00:22:35 +00002316 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002317 }
2318 }
aswift5b1a2562008-08-22 00:22:35 +00002319 if( failed ){
2320 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002321 }
2322 }
2323
2324 if( rc==SQLITE_OK ){
2325 pFile->locktype = locktype;
2326 }else if( locktype==EXCLUSIVE_LOCK ){
2327 pFile->locktype = PENDING_LOCK;
2328 }
2329
2330afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002331 unixLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00002332 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002333 rc==SQLITE_OK ? "ok" : "failed");
2334 return rc;
2335}
2336
2337/*
drh339eb0b2008-03-07 15:34:11 +00002338** Lower the locking level on file descriptor pFile to locktype. locktype
2339** must be either NO_LOCK or SHARED_LOCK.
2340**
2341** If the locking level of the file descriptor is already at or below
2342** the requested locking level, this routine is a no-op.
2343*/
danielk1977e339d652008-06-28 11:23:00 +00002344static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002345 int rc = SQLITE_OK;
2346 unixFile *pFile = (unixFile*)id;
aswiftaebf4132008-11-21 00:10:35 +00002347 afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002348
2349 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002350 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00002351 pFile->locktype, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002352
drhbfe66312006-10-03 17:40:40 +00002353 assert( locktype<=SHARED_LOCK );
2354 if( pFile->locktype<=locktype ){
2355 return SQLITE_OK;
2356 }
2357 if( CHECK_THREADID(pFile) ){
2358 return SQLITE_MISUSE;
2359 }
drh6c7d5c52008-11-21 20:32:33 +00002360 unixEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002361 if( pFile->locktype>SHARED_LOCK ){
aswiftaebf4132008-11-21 00:10:35 +00002362
2363 if( pFile->locktype==EXCLUSIVE_LOCK ){
2364 rc = _AFPFSSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
2365 if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
2366 /* only re-establish the shared lock if necessary */
2367 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
2368 rc = _AFPFSSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
2369 }
2370 }
2371 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
2372 rc = _AFPFSSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
2373 }
2374 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
2375 rc = _AFPFSSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
2376 }
2377 }else if( locktype==NO_LOCK ){
2378 /* clear the shared lock */
2379 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
2380 rc = _AFPFSSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
2381 }
drhbfe66312006-10-03 17:40:40 +00002382
aswiftaebf4132008-11-21 00:10:35 +00002383 if( rc==SQLITE_OK ){
2384 if( locktype==NO_LOCK ){
drh6c7d5c52008-11-21 20:32:33 +00002385 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002386 pOpen->nLock--;
2387 assert( pOpen->nLock>=0 );
2388 if( pOpen->nLock==0 && pOpen->nPending>0 ){
2389 int i;
2390 for(i=0; i<pOpen->nPending; i++){
2391 if( pOpen->aPending[i] < 0 ) continue;
2392 if( close(pOpen->aPending[i]) ){
2393 pFile->lastErrno = errno;
2394 rc = SQLITE_IOERR_CLOSE;
2395 }else{
2396 pOpen->aPending[i] = -1;
drhbfe66312006-10-03 17:40:40 +00002397 }
aswiftaebf4132008-11-21 00:10:35 +00002398 }
2399 if( rc==SQLITE_OK ){
2400 sqlite3_free(pOpen->aPending);
2401 pOpen->nPending = 0;
2402 pOpen->aPending = 0;
2403 }
drhbfe66312006-10-03 17:40:40 +00002404 }
2405 }
drhbfe66312006-10-03 17:40:40 +00002406 }
aswiftaebf4132008-11-21 00:10:35 +00002407end_afpunlock:
drh6c7d5c52008-11-21 20:32:33 +00002408 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002409 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002410 return rc;
2411}
2412
2413/*
drh339eb0b2008-03-07 15:34:11 +00002414** Close a file & cleanup AFP specific locking context
2415*/
danielk1977e339d652008-06-28 11:23:00 +00002416static int afpClose(sqlite3_file *id) {
2417 if( id ){
2418 unixFile *pFile = (unixFile*)id;
2419 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002420 unixEnterMutex();
aswiftaebf4132008-11-21 00:10:35 +00002421 if( pFile->pOpen && pFile->pOpen->nLock ){
2422 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002423 ** yet because that would clear those locks. Instead, add the file
2424 ** descriptor to pOpen->aPending. It will be automatically closed when
2425 ** the last lock is cleared.
2426 */
aswiftaebf4132008-11-21 00:10:35 +00002427 int *aNew;
drh6c7d5c52008-11-21 20:32:33 +00002428 struct unixOpenCnt *pOpen = pFile->pOpen;
aswiftaebf4132008-11-21 00:10:35 +00002429 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
2430 if( aNew==0 ){
2431 /* If a malloc fails, just leak the file descriptor */
2432 }else{
2433 pOpen->aPending = aNew;
2434 pOpen->aPending[pOpen->nPending] = pFile->h;
2435 pOpen->nPending++;
2436 pFile->h = -1;
2437 }
2438 }
2439 releaseOpenCnt(pFile->pOpen);
danielk1977e339d652008-06-28 11:23:00 +00002440 sqlite3_free(pFile->lockingContext);
aswiftaebf4132008-11-21 00:10:35 +00002441 closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002442 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002443 }
aswiftaebf4132008-11-21 00:10:35 +00002444 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002445}
2446
drh734c9862008-11-28 15:37:20 +00002447#endif /* defined(__DARWIN__) && SQLITE_ENABLE_LOCKING_STYLE */
2448/*
2449** The code above is the AFP lock implementation. The code is specific
2450** to MacOSX and does not work on other unix platforms. No alternative
2451** is available. If you don't compile for a mac, then the "unix-afp"
2452** VFS is not available.
2453**
2454********************* End of the AFP lock implementation **********************
2455******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002456
drh734c9862008-11-28 15:37:20 +00002457/******************************************************************************
2458************************** Begin Proxy Locking ********************************
2459**
2460**
2461** The default locking schemes in SQLite use byte-range locks on the
2462** database file to coordinate safe, concurrent access by multiple readers
2463** and writers [http://sqlite.org/lockingv3.html]. The five file locking
2464** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
2465** as POSIX read & write locks over fixed set of locations (via fsctl),
2466** on AFP and SMB only exclusive byte-range locks are available via fsctl
2467** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
2468** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
2469** address in the shared range is taken for a SHARED lock, the entire
2470** shared range is taken for an EXCLUSIVE lock):
2471**
2472** PENDING_BYTE 0x40000000
2473** RESERVED_BYTE 0x40000001
2474** SHARED_RANGE 0x40000002 -> 0x40000200
2475**
2476** This works well on the local file system, but shows a nearly 100x
2477** slowdown in read performance on AFP because the AFP client disables
2478** the read cache when byte-range locks are present. Enabling the read
2479** cache exposes a cache coherency problem that is present on all OS X
2480** supported network file systems. NFS and AFP both observe the
2481** close-to-open semantics for ensuring cache coherency
2482** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
2483** address the requirements for concurrent database access by multiple
2484** readers and writers
2485** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
2486**
2487** To address the performance and cache coherency issues, proxy file locking
2488** changes the way database access is controlled by limiting access to a
2489** single host at a time and moving file locks off of the database file
2490** and onto a proxy file on the local file system.
2491**
2492**
2493** Using proxy locks
2494** -----------------
2495**
2496** C APIs
2497**
2498** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
2499** <proxy_path> | ":auto:");
2500** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
2501**
2502**
2503** SQL pragmas
2504**
2505** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
2506** PRAGMA [database.]lock_proxy_file
2507**
2508** Specifying ":auto:" means that if there is a conch file with a matching
2509** host ID in it, the proxy path in the conch file will be used, otherwise
2510** a proxy path based on the user's temp dir
2511** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
2512** actual proxy file name is generated from the name and path of the
2513** database file. For example:
2514**
2515** For database path "/Users/me/foo.db"
2516** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
2517**
2518** Once a lock proxy is configured for a database connection, it can not
2519** be removed, however it may be switched to a different proxy path via
2520** the above APIs (assuming the conch file is not being held by another
2521** connection or process).
2522**
2523**
2524** How proxy locking works
2525** -----------------------
2526**
2527** Proxy file locking relies primarily on two new supporting files:
2528**
2529** * conch file to limit access to the database file to a single host
2530** at a time
2531**
2532** * proxy file to act as a proxy for the advisory locks normally
2533** taken on the database
2534**
2535** The conch file - to use a proxy file, sqlite must first "hold the conch"
2536** by taking an sqlite-style shared lock on the conch file, reading the
2537** contents and comparing the host's unique host ID (see below) and lock
2538** proxy path against the values stored in the conch. The conch file is
2539** stored in the same directory as the database file and the file name
2540** is patterned after the database file name as ".<databasename>-conch".
2541** If the conch file does not exist, or it's contents do not match the
2542** host ID and/or proxy path, then the lock is escalated to an exclusive
2543** lock and the conch file contents is updated with the host ID and proxy
2544** path and the lock is downgraded to a shared lock again. If the conch
2545** is held by another process (with a shared lock), the exclusive lock
2546** will fail and SQLITE_BUSY is returned.
2547**
2548** The proxy file - a single-byte file used for all advisory file locks
2549** normally taken on the database file. This allows for safe sharing
2550** of the database file for multiple readers and writers on the same
2551** host (the conch ensures that they all use the same local lock file).
2552**
2553** There is a third file - the host ID file - used as a persistent record
2554** of a unique identifier for the host, a 128-byte unique host id file
2555** in the path defined by the HOSTIDPATH macro (default value is
2556** /Library/Caches/.com.apple.sqliteConchHostId).
2557**
2558** Requesting the lock proxy does not immediately take the conch, it is
2559** only taken when the first request to lock database file is made.
2560** This matches the semantics of the traditional locking behavior, where
2561** opening a connection to a database file does not take a lock on it.
2562** The shared lock and an open file descriptor are maintained until
2563** the connection to the database is closed.
2564**
2565** The proxy file and the lock file are never deleted so they only need
2566** to be created the first time they are used.
2567**
2568** Configuration options
2569** ---------------------
2570**
2571** SQLITE_PREFER_PROXY_LOCKING
2572**
2573** Database files accessed on non-local file systems are
2574** automatically configured for proxy locking, lock files are
2575** named automatically using the same logic as
2576** PRAGMA lock_proxy_file=":auto:"
2577**
2578** SQLITE_PROXY_DEBUG
2579**
2580** Enables the logging of error messages during host id file
2581** retrieval and creation
2582**
2583** HOSTIDPATH
2584**
2585** Overrides the default host ID file path location
2586**
2587** LOCKPROXYDIR
2588**
2589** Overrides the default directory used for lock proxy files that
2590** are named automatically via the ":auto:" setting
2591**
2592** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
2593**
2594** Permissions to use when creating a directory for storing the
2595** lock proxy files, only used when LOCKPROXYDIR is not set.
2596**
2597**
2598** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
2599** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
2600** force proxy locking to be used for every database file opened, and 0
2601** will force automatic proxy locking to be disabled for all database
2602** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
2603** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
2604*/
drhbfe66312006-10-03 17:40:40 +00002605
2606/*
drh734c9862008-11-28 15:37:20 +00002607** Proxy locking is only available on MacOSX
drh339eb0b2008-03-07 15:34:11 +00002608*/
drh734c9862008-11-28 15:37:20 +00002609#if defined(__DARWIN__) && SQLITE_ENABLE_LOCKING_STYLE
drhbfe66312006-10-03 17:40:40 +00002610
danielk1977861f7452008-06-05 11:39:11 +00002611
drh734c9862008-11-28 15:37:20 +00002612static int getDbPathForUnixFile(unixFile *pFile, char *dbPath);
2613static int getLockPath(const char *dbPath, char *lPath, size_t maxLen);
drh734c9862008-11-28 15:37:20 +00002614static int createProxyUnixFile(const char *path, unixFile **ppFile);
2615static int fillInUnixFile(sqlite3_vfs *pVfs, int h, int dirfd, sqlite3_file *pId, const char *zFilename, int noLock, int isDelete);
2616static int takeConch(unixFile *pFile);
2617static int releaseConch(unixFile *pFile);
2618static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf);
drhbfe66312006-10-03 17:40:40 +00002619
drh339eb0b2008-03-07 15:34:11 +00002620
drh734c9862008-11-28 15:37:20 +00002621#ifdef SQLITE_TEST
2622/* simulate multiple hosts by creating unique hostid file paths */
2623int sqlite3_hostid_num = 0;
chw97185482008-11-17 08:05:31 +00002624#endif
drhbfe66312006-10-03 17:40:40 +00002625
2626/*
drh734c9862008-11-28 15:37:20 +00002627** The proxyLockingContext has the path and file structures for the remote
2628** and local proxy files in it
2629*/
2630typedef struct proxyLockingContext proxyLockingContext;
2631struct proxyLockingContext {
2632 unixFile *conchFile;
2633 char *conchFilePath;
2634 unixFile *lockProxy;
2635 char *lockProxyPath;
2636 char *dbPath;
2637 int conchHeld;
2638 void *oldLockingContext; /* preserve the original locking context for close */
2639 sqlite3_io_methods const *pOldMethod; /* ditto pMethod */
2640};
drhbfe66312006-10-03 17:40:40 +00002641
aswiftaebf4132008-11-21 00:10:35 +00002642
2643static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
2644 unixFile *pFile = (unixFile*)id;
2645 int rc = takeConch(pFile);
2646 if( rc==SQLITE_OK ){
2647 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
2648 unixFile *proxy = pCtx->lockProxy;
2649 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
2650 }
2651 return rc;
2652}
2653
2654static int proxyLock(sqlite3_file *id, int locktype) {
2655 unixFile *pFile = (unixFile*)id;
2656 int rc = takeConch(pFile);
2657 if( rc==SQLITE_OK ){
2658 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
2659 unixFile *proxy = pCtx->lockProxy;
2660 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
2661 pFile->locktype = proxy->locktype;
2662 }
2663 return rc;
2664}
2665
2666static int proxyUnlock(sqlite3_file *id, int locktype) {
2667 unixFile *pFile = (unixFile*)id;
2668 int rc = takeConch(pFile);
2669 if( rc==SQLITE_OK ){
2670 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
2671 unixFile *proxy = pCtx->lockProxy;
2672 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
2673 pFile->locktype = proxy->locktype;
2674 }
2675 return rc;
2676}
2677
2678/*
2679 ** Close a file.
2680 */
2681static int proxyClose(sqlite3_file *id) {
2682 if( id ){
2683 unixFile *pFile = (unixFile*)id;
2684 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
2685 unixFile *lockProxy = pCtx->lockProxy;
2686 unixFile *conchFile = pCtx->conchFile;
2687 int rc = SQLITE_OK;
2688
2689 if( lockProxy ){
2690 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
2691 if( rc ) return rc;
2692 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
2693 if( rc ) return rc;
2694 sqlite3_free(lockProxy);
2695 }
2696 if( conchFile ){
2697 if( pCtx->conchHeld ){
2698 rc = releaseConch(pFile);
2699 if( rc ) return rc;
2700 }
2701 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
2702 if( rc ) return rc;
2703 sqlite3_free(conchFile);
2704 }
2705 sqlite3_free(pCtx->lockProxyPath);
2706 sqlite3_free(pCtx->conchFilePath);
2707 sqlite3_free(pCtx->dbPath);
2708 /* restore the original locking context and pMethod then close it */
2709 pFile->lockingContext = pCtx->oldLockingContext;
2710 pFile->pMethod = pCtx->pOldMethod;
2711 sqlite3_free(pCtx);
2712 return pFile->pMethod->xClose(id);
2713 }
2714 return SQLITE_OK;
2715}
2716
2717/* HOSTIDLEN and CONCHLEN both include space for the string
2718** terminating nul
2719*/
2720#define HOSTIDLEN 128
2721#define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
2722#ifndef HOSTIDPATH
2723# define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
2724#endif
2725
2726/* basically a copy of unixRandomness with different
2727** test behavior built in */
2728static int genHostID(char *pHostID){
2729 int pid, fd, i, len;
2730 unsigned char *key = (unsigned char *)pHostID;
2731
2732 memset(key, 0, HOSTIDLEN);
2733 len = 0;
2734 fd = open("/dev/urandom", O_RDONLY);
2735 if( fd>=0 ){
2736 len = read(fd, key, HOSTIDLEN);
2737 close(fd); /* silently leak the fd if it fails */
2738 }
2739 if( len < HOSTIDLEN ){
2740 time_t t;
2741 time(&t);
2742 memcpy(key, &t, sizeof(t));
2743 pid = getpid();
2744 memcpy(&key[sizeof(t)], &pid, sizeof(pid));
2745 }
2746
2747#ifdef MAKE_PRETTY_HOSTID
2748 /* filter the bytes into printable ascii characters and NUL terminate */
2749 key[(HOSTIDLEN-1)] = 0x00;
2750 for( i=0; i<(HOSTIDLEN-1); i++ ){
2751 unsigned char pa = key[i]&0x7F;
2752 if( pa<0x20 ){
2753 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
2754 }else if( pa==0x7F ){
2755 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
2756 }
2757 }
2758#endif
2759 return SQLITE_OK;
2760}
2761
aswiftaebf4132008-11-21 00:10:35 +00002762/* writes the host id path to path, path should be an pre-allocated buffer
2763** with enough space for a path */
2764static int getHostIDPath(char *path, size_t len){
2765 strlcpy(path, HOSTIDPATH, len);
2766#ifdef SQLITE_TEST
2767 if( sqlite3_hostid_num>0 ){
2768 char suffix[2] = "1";
2769 suffix[0] = suffix[0] + sqlite3_hostid_num;
2770 strlcat(path, suffix, len);
2771 }
2772#endif
2773 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
2774}
2775
2776/* get the host ID from a sqlite hostid file stored in the
2777** user-specific tmp directory, create the ID if it's not there already
2778*/
2779static int getHostID(char *pHostID, int *pError){
2780 int fd;
2781 char path[MAXPATHLEN];
2782 size_t len;
2783 int rc=SQLITE_OK;
2784
2785 getHostIDPath(path, MAXPATHLEN);
2786 /* try to create the host ID file, if it already exists read the contents */
2787 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
2788 if( fd<0 ){
2789 int err=errno;
2790
2791 if( err!=EEXIST ){
2792#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
drh734c9862008-11-28 15:37:20 +00002793 fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
2794 path, strerror(err));
aswiftaebf4132008-11-21 00:10:35 +00002795#endif
2796 return SQLITE_PERM;
2797 }
2798 /* couldn't create the file, read it instead */
2799 fd = open(path, O_RDONLY|O_EXCL);
2800 if( fd<0 ){
2801 int err = errno;
2802#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
drh734c9862008-11-28 15:37:20 +00002803 fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
2804 path, strerror(err));
aswiftaebf4132008-11-21 00:10:35 +00002805#endif
2806 return SQLITE_PERM;
2807 }
2808 len = pread(fd, pHostID, HOSTIDLEN, 0);
drh734c9862008-11-28 15:37:20 +00002809 if( len<0 ){
2810 *pError = errno;
2811 rc = SQLITE_IOERR_READ;
2812 }else if( len<HOSTIDLEN ){
2813 *pError = 0;
2814 rc = SQLITE_IOERR_SHORT_READ;
2815 }
aswiftaebf4132008-11-21 00:10:35 +00002816 close(fd); /* silently leak the fd if it fails */
2817 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
2818 return rc;
2819 }else{
2820 int i;
2821 /* we're creating the host ID file (use a random string of bytes) */
2822 genHostID(pHostID);
2823 len = pwrite(fd, pHostID, HOSTIDLEN, 0);
drh734c9862008-11-28 15:37:20 +00002824 if( len<0 ){
2825 *pError = errno;
2826 rc = SQLITE_IOERR_WRITE;
2827 }else if( len<HOSTIDLEN ){
2828 *pError = 0;
2829 rc = SQLITE_IOERR_WRITE;
2830 }
aswiftaebf4132008-11-21 00:10:35 +00002831 close(fd); /* silently leak the fd if it fails */
2832 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
2833 return rc;
2834 }
2835}
2836
2837/* takes the conch by taking a shared lock and read the contents conch, if
2838** lockPath is non-NULL, the host ID and lock file path must match. A NULL
2839** lockPath means that the lockPath in the conch file will be used if the
2840** host IDs match, or a new lock path will be generated automatically
2841** and written to the conch file.
2842*/
2843static int takeConch(unixFile *pFile){
2844 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
2845
2846 if( pCtx->conchHeld>0 ){
2847 return SQLITE_OK;
2848 }else{
2849 unixFile *conchFile = pCtx->conchFile;
2850 char testValue[CONCHLEN];
2851 char conchValue[CONCHLEN];
2852 char lockPath[MAXPATHLEN];
2853 char *tLockPath = NULL;
2854 int rc = SQLITE_OK;
2855 int readRc = SQLITE_OK;
2856 int syncPerms = 0;
2857
2858 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h,
2859 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
2860
2861 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
2862 if( rc==SQLITE_OK ){
2863 int pError = 0;
2864 memset(testValue, 0, CONCHLEN); // conch is fixed size
2865 rc = getHostID(testValue, &pError);
2866 if( rc&SQLITE_IOERR==SQLITE_IOERR ){
2867 pFile->lastErrno = pError;
2868 }
2869 if( pCtx->lockProxyPath ){
2870 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
2871 }
2872 }
2873 if( rc!=SQLITE_OK ){
2874 goto end_takeconch;
2875 }
2876
2877 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
2878 if( readRc!=SQLITE_IOERR_SHORT_READ ){
2879 int match = 0;
2880 if( readRc!=SQLITE_OK ){
drh734c9862008-11-28 15:37:20 +00002881 if( rc&SQLITE_IOERR==SQLITE_IOERR ){
2882 pFile->lastErrno = conchFile->lastErrno;
2883 }
aswiftaebf4132008-11-21 00:10:35 +00002884 rc = readRc;
2885 goto end_takeconch;
2886 }
2887 /* if the conch has data compare the contents */
2888 if( !pCtx->lockProxyPath ){
2889 /* for auto-named local lock file, just check the host ID and we'll
2890 ** use the local lock file path that's already in there */
2891 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
2892 tLockPath = (char *)&conchValue[HOSTIDLEN];
2893 goto end_takeconch;
2894 }
2895 }else{
2896 /* we've got the conch if conchValue matches our path and host ID */
2897 if( !memcmp(testValue, conchValue, CONCHLEN) ){
2898 goto end_takeconch;
2899 }
2900 }
2901 }else{
2902 /* a short read means we're "creating" the conch (even though it could
2903 ** have been user-intervention), if we acquire the exclusive lock,
2904 ** we'll try to match the current on-disk permissions of the database
2905 */
2906 syncPerms = 1;
2907 }
2908
2909 /* either conch was emtpy or didn't match */
2910 if( !pCtx->lockProxyPath ){
2911 getLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
2912 tLockPath = lockPath;
2913 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
2914 }
2915
2916 /* update conch with host and path (this will fail if other process
2917 ** has a shared lock already) */
2918 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
2919 if( rc==SQLITE_OK ){
2920 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
2921 if( rc==SQLITE_OK && syncPerms ){
2922 struct stat buf;
2923 int err = fstat(pFile->h, &buf);
2924 if( err==0 ){
2925 mode_t mode = buf.st_mode & 0100666;
2926 /* try to match the database file permissions, ignore failure */
2927#ifndef SQLITE_PROXY_DEBUG
2928 fchmod(conchFile->h, buf.st_mode);
2929#else
2930 if( fchmod(conchFile->h, buf.st_mode)!=0 ){
2931 int code = errno;
drh734c9862008-11-28 15:37:20 +00002932 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
2933 buf.st_mode, code, strerror(code));
aswiftaebf4132008-11-21 00:10:35 +00002934 } else {
2935 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
2936 }
2937 }else{
2938 int code = errno;
drh734c9862008-11-28 15:37:20 +00002939 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
2940 err, code, strerror(code));
aswiftaebf4132008-11-21 00:10:35 +00002941#endif
2942 }
2943 }
2944 }
2945 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
2946
2947end_takeconch:
2948 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h);
drh734c9862008-11-28 15:37:20 +00002949 if( rc==SQLITE_OK && pFile->openFlags ){
aswiftaebf4132008-11-21 00:10:35 +00002950 if( pFile->h>=0 ){
2951#ifdef STRICT_CLOSE_ERROR
2952 if( close(pFile->h) ){
2953 pFile->lastErrno = errno;
2954 return SQLITE_IOERR_CLOSE;
2955 }
2956#else
2957 close(pFile->h); /* silently leak fd if fail */
2958#endif
2959 }
2960 pFile->h = -1;
drh734c9862008-11-28 15:37:20 +00002961 int fd = open(pCtx->dbPath, pFile->openFlags,
2962 SQLITE_DEFAULT_FILE_PERMISSIONS);
aswiftaebf4132008-11-21 00:10:35 +00002963 OSTRACE2("TRANSPROXY: OPEN %d\n", fd);
2964 if( fd>=0 ){
2965 pFile->h = fd;
2966 }else{
2967 rc=SQLITE_CANTOPEN; // SQLITE_BUSY? takeConch called during locking
2968 }
2969 }
2970 if( rc==SQLITE_OK && !pCtx->lockProxy ){
2971 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
2972 // ACS: Need to make a copy of path sometimes
2973 rc = createProxyUnixFile(path, &pCtx->lockProxy);
2974 }
2975 if( rc==SQLITE_OK ){
2976 pCtx->conchHeld = 1;
2977
2978 if( tLockPath ){
2979 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
drh7708e972008-11-29 00:56:52 +00002980 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
drh734c9862008-11-28 15:37:20 +00002981 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
2982 pCtx->lockProxyPath;
aswiftaebf4132008-11-21 00:10:35 +00002983 }
2984 }
2985 } else {
2986 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
2987 }
drh734c9862008-11-28 15:37:20 +00002988 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
aswiftaebf4132008-11-21 00:10:35 +00002989 return rc;
2990 }
2991}
2992
2993static int releaseConch(unixFile *pFile){
2994 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
2995 int rc;
2996 unixFile *conchFile = pCtx->conchFile;
2997
2998 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
2999 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
3000 getpid());
3001 pCtx->conchHeld = 0;
3002 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
3003 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h,
3004 (rc==SQLITE_OK ? "ok" : "failed"));
3005 return rc;
3006}
3007
3008static int getConchPathFromDBPath(char *dbPath, char **pConchPath){
3009 int i;
3010 int len = strlen(dbPath);
3011 char *conchPath;
3012
3013 conchPath = (char *)sqlite3_malloc(len + 8);
3014 if( conchPath==0 ){
3015 return SQLITE_NOMEM;
3016 }
3017 strlcpy(conchPath, dbPath, len+1);
3018
3019 /* now insert a "." before the last / character */
3020 for( i=(len-1); i>=0; i-- ){
3021 if( conchPath[i]=='/' ){
3022 i++;
3023 break;
3024 }
3025 }
3026 conchPath[i]='.';
3027 while ( i<len ){
3028 conchPath[i+1]=dbPath[i];
3029 i++;
3030 }
3031 conchPath[i+1]='\0';
3032 strlcat(conchPath, "-conch", len + 8);
3033 *pConchPath = conchPath;
3034 return SQLITE_OK;
3035}
3036
drh734c9862008-11-28 15:37:20 +00003037
aswiftaebf4132008-11-21 00:10:35 +00003038static int getLockPath(const char *dbPath, char *lPath, size_t maxLen){
3039 int len;
3040 int dbLen;
3041 int i;
3042
3043#ifdef LOCKPROXYDIR
3044 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
3045#else
3046# ifdef _CS_DARWIN_USER_TEMP_DIR
3047 {
3048 char utdir[MAXPATHLEN];
3049
3050 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
3051 len = strlcat(lPath, "sqliteplocks", maxLen);
3052 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
3053 /* if mkdir fails, handle as lock file creation failure */
3054 int err = errno;
3055# ifdef SQLITE_DEBUG
3056 if( err!=EEXIST ){
3057 fprintf(stderr, "getLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
3058 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
3059 }
3060# endif
3061 }else{
3062 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
3063 }
3064
3065 }
3066# else
3067 len = strlcpy(lPath, "/tmp/", maxLen);
3068# endif
3069#endif
3070
3071 if( lPath[len-1]!='/' ){
3072 len = strlcat(lPath, "/", maxLen);
3073 }
3074
3075 /* transform the db path to a unique cache name */
3076 dbLen = strlen(dbPath);
3077 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
3078 char c = dbPath[i];
3079 lPath[i+len] = (c=='/')?'_':c;
3080 }
3081 lPath[i+len]='\0';
3082 strlcat(lPath, ":auto:", maxLen);
3083 return SQLITE_OK;
3084}
3085
3086/* Takes a fully configured proxy locking-style unix file and switches
3087** the local lock file path
3088*/
3089static int switchLockProxyPath(unixFile *pFile, const char *path) {
3090 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
3091 char *oldPath = pCtx->lockProxyPath;
3092 int taken = 0;
3093 int rc = SQLITE_OK;
3094
3095 if( pFile->locktype!=NO_LOCK ){
3096 return SQLITE_BUSY;
3097 }
3098
3099 /* nothing to do if the path is NULL, :auto: or matches the existing path */
3100 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
3101 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
3102 return SQLITE_OK;
3103 }else{
3104 unixFile *lockProxy = pCtx->lockProxy;
3105 pCtx->lockProxy=NULL;
3106 pCtx->conchHeld = 0;
3107 if( lockProxy!=NULL ){
3108 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
3109 if( rc ) return rc;
3110 sqlite3_free(lockProxy);
3111 }
3112 sqlite3_free(oldPath);
3113 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
3114 }
3115
3116 return rc;
3117}
3118
3119/*
3120** Takes an already filled in unix file and alters it so all file locking
3121** will be performed on the local proxy lock file. The following fields
3122** are preserved in the locking context so that they can be restored and
3123** the unix structure properly cleaned up at close time:
3124** ->lockingContext
3125** ->pMethod
3126*/
3127static int transformUnixFileForLockProxy(unixFile *pFile, const char *path) {
3128 proxyLockingContext *pCtx;
3129 char dbPath[MAXPATHLEN];
3130 char *lockPath=NULL;
3131 int rc = SQLITE_OK;
3132
3133 if( pFile->locktype!=NO_LOCK ){
3134 return SQLITE_BUSY;
3135 }
3136 getDbPathForUnixFile(pFile, dbPath);
3137 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
3138 lockPath=NULL;
3139 }else{
3140 lockPath=(char *)path;
3141 }
3142
3143 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h,
3144 (lockPath ? lockPath : ":auto:"), getpid());
3145
3146 pCtx = sqlite3_malloc( sizeof(*pCtx) );
3147 if( pCtx==0 ){
3148 return SQLITE_NOMEM;
3149 }
3150 memset(pCtx, 0, sizeof(*pCtx));
3151
3152 rc = getConchPathFromDBPath(dbPath, &pCtx->conchFilePath);
3153 if( rc==SQLITE_OK ){
3154 rc = createProxyUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
3155 }
3156 if( rc==SQLITE_OK && lockPath ){
3157 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
3158 }
3159
3160end_transform_file:
3161 if( rc==SQLITE_OK ){
3162 /* all memory is allocated, proxys are created and assigned,
3163 ** switch the locking context and pMethod then return.
3164 */
3165 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
3166 pCtx->oldLockingContext = pFile->lockingContext;
3167 pFile->lockingContext = pCtx;
3168 pCtx->pOldMethod = pFile->pMethod;
drh7708e972008-11-29 00:56:52 +00003169 pFile->pMethod = &proxyIoMethods;
aswiftaebf4132008-11-21 00:10:35 +00003170 }else{
3171 if( pCtx->conchFile ){
3172 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
3173 if( rc ) return rc;
3174 sqlite3_free(pCtx->conchFile);
3175 }
3176 sqlite3_free(pCtx->conchFilePath);
3177 sqlite3_free(pCtx);
3178 }
3179 OSTRACE3("TRANSPROXY %d %s\n", pFile->h,
3180 (rc==SQLITE_OK ? "ok" : "failed"));
3181 return rc;
3182}
3183
3184static int createProxyUnixFile(const char *path, unixFile **ppFile) {
3185 int fd;
3186 int dirfd = -1;
3187 unixFile *pNew;
3188 int rc = SQLITE_OK;
3189
3190 fd = open(path, O_RDWR | O_CREAT, SQLITE_DEFAULT_FILE_PERMISSIONS);
3191 if( fd<0 ){
3192 return SQLITE_CANTOPEN;
3193 }
3194
3195 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
3196 if( pNew==NULL ){
3197 rc = SQLITE_NOMEM;
3198 goto end_create_proxy;
3199 }
3200 memset(pNew, 0, sizeof(unixFile));
3201
3202 rc = fillInUnixFile(NULL, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
3203 if( rc==SQLITE_OK ){
3204 *ppFile = pNew;
3205 return SQLITE_OK;
3206 }
3207end_create_proxy:
3208 close(fd); /* silently leak fd if error, we're already in error */
3209 sqlite3_free(pNew);
3210 return rc;
3211}
3212
3213
drh734c9862008-11-28 15:37:20 +00003214#endif /* defined(__DARWIN__) && SQLITE_ENABLE_LOCKING_STYLE */
3215/*
3216** The proxy locking style is intended for use with AFP filesystems.
3217** And since AFP is only supported on MacOSX, the proxy locking is also
3218** restricted to MacOSX.
3219**
3220**
3221******************* End of the proxy lock implementation **********************
3222******************************************************************************/
3223
3224
3225/******************************************************************************
3226**************** Non-locking sqlite3_file methods *****************************
3227**
3228** The next division contains implementations for all methods of the
3229** sqlite3_file object other than the locking methods. The locking
3230** methods were defined in divisions above (one locking method per
3231** division). Those methods that are common to all locking modes
3232** are gather together into this division.
3233*/
drhbfe66312006-10-03 17:40:40 +00003234
3235/*
drh734c9862008-11-28 15:37:20 +00003236** Seek to the offset passed as the second argument, then read cnt
3237** bytes into pBuf. Return the number of bytes actually read.
3238**
3239** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3240** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3241** one system to another. Since SQLite does not define USE_PREAD
3242** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3243** See tickets #2741 and #2681.
3244**
3245** To avoid stomping the errno value on a failed read the lastErrno value
3246** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003247*/
drh734c9862008-11-28 15:37:20 +00003248static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3249 int got;
3250 i64 newOffset;
3251 TIMER_START;
3252#if defined(USE_PREAD)
3253 got = pread(id->h, pBuf, cnt, offset);
3254 SimulateIOError( got = -1 );
3255#elif defined(USE_PREAD64)
3256 got = pread64(id->h, pBuf, cnt, offset);
3257 SimulateIOError( got = -1 );
3258#else
3259 newOffset = lseek(id->h, offset, SEEK_SET);
3260 SimulateIOError( newOffset-- );
3261 if( newOffset!=offset ){
3262 if( newOffset == -1 ){
3263 ((unixFile*)id)->lastErrno = errno;
3264 }else{
3265 ((unixFile*)id)->lastErrno = 0;
3266 }
3267 return -1;
3268 }
3269 got = read(id->h, pBuf, cnt);
3270#endif
3271 TIMER_END;
3272 if( got<0 ){
3273 ((unixFile*)id)->lastErrno = errno;
3274 }
3275 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
3276 return got;
drhbfe66312006-10-03 17:40:40 +00003277}
3278
3279/*
drh734c9862008-11-28 15:37:20 +00003280** Read data from a file into a buffer. Return SQLITE_OK if all
3281** bytes were read successfully and SQLITE_IOERR if anything goes
3282** wrong.
drh339eb0b2008-03-07 15:34:11 +00003283*/
drh734c9862008-11-28 15:37:20 +00003284static int unixRead(
3285 sqlite3_file *id,
3286 void *pBuf,
3287 int amt,
3288 sqlite3_int64 offset
3289){
3290 int got;
3291 assert( id );
3292 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
3293 if( got==amt ){
3294 return SQLITE_OK;
3295 }else if( got<0 ){
3296 /* lastErrno set by seekAndRead */
3297 return SQLITE_IOERR_READ;
3298 }else{
3299 ((unixFile*)id)->lastErrno = 0; /* not a system error */
3300 /* Unread parts of the buffer must be zero-filled */
3301 memset(&((char*)pBuf)[got], 0, amt-got);
3302 return SQLITE_IOERR_SHORT_READ;
3303 }
3304}
3305
3306/*
3307** Seek to the offset in id->offset then read cnt bytes into pBuf.
3308** Return the number of bytes actually read. Update the offset.
3309**
3310** To avoid stomping the errno value on a failed write the lastErrno value
3311** is set before returning.
3312*/
3313static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3314 int got;
3315 i64 newOffset;
3316 TIMER_START;
3317#if defined(USE_PREAD)
3318 got = pwrite(id->h, pBuf, cnt, offset);
3319#elif defined(USE_PREAD64)
3320 got = pwrite64(id->h, pBuf, cnt, offset);
3321#else
3322 newOffset = lseek(id->h, offset, SEEK_SET);
3323 if( newOffset!=offset ){
3324 if( newOffset == -1 ){
3325 ((unixFile*)id)->lastErrno = errno;
3326 }else{
3327 ((unixFile*)id)->lastErrno = 0;
3328 }
3329 return -1;
3330 }
3331 got = write(id->h, pBuf, cnt);
3332#endif
3333 TIMER_END;
3334 if( got<0 ){
3335 ((unixFile*)id)->lastErrno = errno;
3336 }
3337
3338 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
3339 return got;
3340}
3341
3342
3343/*
3344** Write data from a buffer into a file. Return SQLITE_OK on success
3345** or some other error code on failure.
3346*/
3347static int unixWrite(
3348 sqlite3_file *id,
3349 const void *pBuf,
3350 int amt,
3351 sqlite3_int64 offset
3352){
3353 int wrote = 0;
3354 assert( id );
3355 assert( amt>0 );
3356 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
3357 amt -= wrote;
3358 offset += wrote;
3359 pBuf = &((char*)pBuf)[wrote];
3360 }
3361 SimulateIOError(( wrote=(-1), amt=1 ));
3362 SimulateDiskfullError(( wrote=0, amt=1 ));
3363 if( amt>0 ){
3364 if( wrote<0 ){
3365 /* lastErrno set by seekAndWrite */
3366 return SQLITE_IOERR_WRITE;
3367 }else{
3368 ((unixFile*)id)->lastErrno = 0; /* not a system error */
3369 return SQLITE_FULL;
3370 }
3371 }
3372 return SQLITE_OK;
3373}
3374
3375#ifdef SQLITE_TEST
3376/*
3377** Count the number of fullsyncs and normal syncs. This is used to test
3378** that syncs and fullsyncs are occuring at the right times.
3379*/
3380int sqlite3_sync_count = 0;
3381int sqlite3_fullsync_count = 0;
3382#endif
3383
3384/*
3385** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
3386** Otherwise use fsync() in its place.
3387*/
3388#ifndef HAVE_FDATASYNC
3389# define fdatasync fsync
3390#endif
3391
3392/*
3393** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3394** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3395** only available on Mac OS X. But that could change.
3396*/
3397#ifdef F_FULLFSYNC
3398# define HAVE_FULLFSYNC 1
3399#else
3400# define HAVE_FULLFSYNC 0
3401#endif
3402
3403
3404/*
3405** The fsync() system call does not work as advertised on many
3406** unix systems. The following procedure is an attempt to make
3407** it work better.
3408**
3409** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3410** for testing when we want to run through the test suite quickly.
3411** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3412** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3413** or power failure will likely corrupt the database file.
3414*/
3415static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003416 int rc;
drh734c9862008-11-28 15:37:20 +00003417
3418 /* The following "ifdef/elif/else/" block has the same structure as
3419 ** the one below. It is replicated here solely to avoid cluttering
3420 ** up the real code with the UNUSED_PARAMETER() macros.
3421 */
3422#ifdef SQLITE_NO_SYNC
3423 UNUSED_PARAMETER(fd);
3424 UNUSED_PARAMETER(fullSync);
3425 UNUSED_PARAMETER(dataOnly);
3426#elif HAVE_FULLFSYNC
3427 UNUSED_PARAMETER(dataOnly);
3428#else
3429 UNUSED_PARAMETER(fullSync);
3430#endif
3431
3432 /* Record the number of times that we do a normal fsync() and
3433 ** FULLSYNC. This is used during testing to verify that this procedure
3434 ** gets called with the correct arguments.
3435 */
3436#ifdef SQLITE_TEST
3437 if( fullSync ) sqlite3_fullsync_count++;
3438 sqlite3_sync_count++;
3439#endif
3440
3441 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3442 ** no-op
3443 */
3444#ifdef SQLITE_NO_SYNC
3445 rc = SQLITE_OK;
3446#elif HAVE_FULLFSYNC
3447 if( fullSync ){
3448 rc = fcntl(fd, F_FULLFSYNC, 0);
3449 }else{
3450 rc = 1;
3451 }
3452 /* If the FULLFSYNC failed, fall back to attempting an fsync().
3453 * It shouldn't be possible for fullfsync to fail on the local
3454 * file system (on OSX), so failure indicates that FULLFSYNC
3455 * isn't supported for this file system. So, attempt an fsync
3456 * and (for now) ignore the overhead of a superfluous fcntl call.
3457 * It'd be better to detect fullfsync support once and avoid
3458 * the fcntl call every time sync is called.
3459 */
3460 if( rc ) rc = fsync(fd);
3461
3462#else
3463 if( dataOnly ){
3464 rc = fdatasync(fd);
3465 if( OS_VXWORKS && rc==-1 && errno==ENOTSUP ){
3466 rc = fsync(fd);
3467 }
3468 }else{
3469 rc = fsync(fd);
3470 }
3471#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3472
3473 if( OS_VXWORKS && rc!= -1 ){
3474 rc = 0;
3475 }
chw97185482008-11-17 08:05:31 +00003476 return rc;
drhbfe66312006-10-03 17:40:40 +00003477}
3478
drh734c9862008-11-28 15:37:20 +00003479/*
3480** Make sure all writes to a particular file are committed to disk.
3481**
3482** If dataOnly==0 then both the file itself and its metadata (file
3483** size, access time, etc) are synced. If dataOnly!=0 then only the
3484** file data is synced.
3485**
3486** Under Unix, also make sure that the directory entry for the file
3487** has been created by fsync-ing the directory that contains the file.
3488** If we do not do this and we encounter a power failure, the directory
3489** entry for the journal might not exist after we reboot. The next
3490** SQLite to access the file will not know that the journal exists (because
3491** the directory entry for the journal was never created) and the transaction
3492** will not roll back - possibly leading to database corruption.
3493*/
3494static int unixSync(sqlite3_file *id, int flags){
3495 int rc;
3496 unixFile *pFile = (unixFile*)id;
3497
3498 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3499 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3500
3501 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3502 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3503 || (flags&0x0F)==SQLITE_SYNC_FULL
3504 );
3505
3506 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3507 ** line is to test that doing so does not cause any problems.
3508 */
3509 SimulateDiskfullError( return SQLITE_FULL );
3510
3511 assert( pFile );
3512 OSTRACE2("SYNC %-3d\n", pFile->h);
3513 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3514 SimulateIOError( rc=1 );
3515 if( rc ){
3516 pFile->lastErrno = errno;
3517 return SQLITE_IOERR_FSYNC;
3518 }
3519 if( pFile->dirfd>=0 ){
3520 int err;
3521 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3522 HAVE_FULLFSYNC, isFullsync);
3523#ifndef SQLITE_DISABLE_DIRSYNC
3524 /* The directory sync is only attempted if full_fsync is
3525 ** turned off or unavailable. If a full_fsync occurred above,
3526 ** then the directory sync is superfluous.
3527 */
3528 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3529 /*
3530 ** We have received multiple reports of fsync() returning
3531 ** errors when applied to directories on certain file systems.
3532 ** A failed directory sync is not a big deal. So it seems
3533 ** better to ignore the error. Ticket #1657
3534 */
3535 /* pFile->lastErrno = errno; */
3536 /* return SQLITE_IOERR; */
3537 }
3538#endif
3539 err = close(pFile->dirfd); /* Only need to sync once, so close the */
3540 if( err==0 ){ /* directory when we are done */
3541 pFile->dirfd = -1;
3542 }else{
3543 pFile->lastErrno = errno;
3544 rc = SQLITE_IOERR_DIR_CLOSE;
3545 }
3546 }
3547 return rc;
3548}
3549
3550/*
3551** Truncate an open file to a specified size
3552*/
3553static int unixTruncate(sqlite3_file *id, i64 nByte){
3554 int rc;
3555 assert( id );
3556 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3557 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
3558 if( rc ){
3559 ((unixFile*)id)->lastErrno = errno;
3560 return SQLITE_IOERR_TRUNCATE;
3561 }else{
3562 return SQLITE_OK;
3563 }
3564}
3565
3566/*
3567** Determine the current size of a file in bytes
3568*/
3569static int unixFileSize(sqlite3_file *id, i64 *pSize){
3570 int rc;
3571 struct stat buf;
3572 assert( id );
3573 rc = fstat(((unixFile*)id)->h, &buf);
3574 SimulateIOError( rc=1 );
3575 if( rc!=0 ){
3576 ((unixFile*)id)->lastErrno = errno;
3577 return SQLITE_IOERR_FSTAT;
3578 }
3579 *pSize = buf.st_size;
3580
3581 /* When opening a zero-size database, the findLockInfo() procedure
3582 ** writes a single byte into that file in order to work around a bug
3583 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3584 ** layers, we need to report this file size as zero even though it is
3585 ** really 1. Ticket #3260.
3586 */
3587 if( *pSize==1 ) *pSize = 0;
3588
3589
3590 return SQLITE_OK;
3591}
3592
danielk1977ad94b582007-08-20 06:44:22 +00003593
danielk1977e3026632004-06-22 11:29:02 +00003594/*
drh9e33c2c2007-08-31 18:34:59 +00003595** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003596*/
drhcc6bb3e2007-08-31 16:11:35 +00003597static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003598 switch( op ){
3599 case SQLITE_FCNTL_LOCKSTATE: {
3600 *(int*)pArg = ((unixFile*)id)->locktype;
3601 return SQLITE_OK;
3602 }
drh7708e972008-11-29 00:56:52 +00003603 case SQLITE_LAST_ERRNO: {
3604 *(int*)pArg = ((unixFile*)id)->lastErrno;
3605 return SQLITE_OK;
3606 }
3607#if SQLITE_ENABLE_LOCKING_STYLE && defined(__DARWIN__)
aswiftaebf4132008-11-21 00:10:35 +00003608 case SQLITE_GET_LOCKPROXYFILE: {
aswiftaebf4132008-11-21 00:10:35 +00003609 unixFile *pFile = (unixFile*)id;
drh7708e972008-11-29 00:56:52 +00003610 if( pFile->pMethod == &proxyIoMethods ){
aswiftaebf4132008-11-21 00:10:35 +00003611 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
3612 takeConch(pFile);
3613 if( pCtx->lockProxyPath ){
3614 *(const char **)pArg = pCtx->lockProxyPath;
3615 }else{
3616 *(const char **)pArg = ":auto: (not held)";
3617 }
3618 } else {
3619 *(const char **)pArg = NULL;
3620 }
aswiftaebf4132008-11-21 00:10:35 +00003621 return SQLITE_OK;
3622 }
3623 case SQLITE_SET_LOCKPROXYFILE: {
aswiftaebf4132008-11-21 00:10:35 +00003624 unixFile *pFile = (unixFile*)id;
3625 int rc = SQLITE_OK;
drh7708e972008-11-29 00:56:52 +00003626 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
aswiftaebf4132008-11-21 00:10:35 +00003627 if( pArg==NULL || (const char *)pArg==0 ){
3628 if( isProxyStyle ){
drh7708e972008-11-29 00:56:52 +00003629 /* turn off proxy locking - not supported */
aswiftaebf4132008-11-21 00:10:35 +00003630 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
3631 }else{
drh7708e972008-11-29 00:56:52 +00003632 /* turn off proxy locking - already off - NOOP */
aswiftaebf4132008-11-21 00:10:35 +00003633 rc = SQLITE_OK;
3634 }
3635 }else{
3636 const char *proxyPath = (const char *)pArg;
3637 if( isProxyStyle ){
3638 proxyLockingContext *pCtx =
3639 (proxyLockingContext*)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00003640 if( !strcmp(pArg, ":auto:")
3641 || (pCtx->lockProxyPath &&
3642 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
3643 ){
aswiftaebf4132008-11-21 00:10:35 +00003644 rc = SQLITE_OK;
3645 }else{
3646 rc = switchLockProxyPath(pFile, proxyPath);
3647 }
3648 }else{
drh7708e972008-11-29 00:56:52 +00003649 /* turn on proxy file locking */
aswiftaebf4132008-11-21 00:10:35 +00003650 rc = transformUnixFileForLockProxy(pFile, proxyPath);
3651 }
3652 }
3653 return rc;
drh7708e972008-11-29 00:56:52 +00003654 }
aswiftaebf4132008-11-21 00:10:35 +00003655#endif
drh9e33c2c2007-08-31 18:34:59 +00003656 }
drhcc6bb3e2007-08-31 16:11:35 +00003657 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00003658}
3659
3660/*
danielk1977a3d4c882007-03-23 10:08:38 +00003661** Return the sector size in bytes of the underlying block device for
3662** the specified file. This is almost always 512 bytes, but may be
3663** larger for some devices.
3664**
3665** SQLite code assumes this function cannot fail. It also assumes that
3666** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003667** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003668** same for both.
3669*/
danielk1977397d65f2008-11-19 11:35:39 +00003670static int unixSectorSize(sqlite3_file *NotUsed){
3671 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003672 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003673}
3674
danielk197790949c22007-08-17 16:50:38 +00003675/*
danielk1977397d65f2008-11-19 11:35:39 +00003676** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003677*/
danielk1977397d65f2008-11-19 11:35:39 +00003678static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3679 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003680 return 0;
3681}
3682
drh734c9862008-11-28 15:37:20 +00003683/*
3684** Here ends the implementation of all sqlite3_file methods.
3685**
3686********************** End sqlite3_file Methods *******************************
3687******************************************************************************/
3688
3689/*
drh7708e972008-11-29 00:56:52 +00003690** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00003691**
drh7708e972008-11-29 00:56:52 +00003692** * A constant sqlite3_io_methods object call METHOD that has locking
3693** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3694**
3695** * An I/O method finder function called FINDER that returns a pointer
3696** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00003697*/
drh7708e972008-11-29 00:56:52 +00003698#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \
3699static const sqlite3_io_methods METHOD = { \
3700 1, /* iVersion */ \
3701 CLOSE, /* xClose */ \
3702 unixRead, /* xRead */ \
3703 unixWrite, /* xWrite */ \
3704 unixTruncate, /* xTruncate */ \
3705 unixSync, /* xSync */ \
3706 unixFileSize, /* xFileSize */ \
3707 LOCK, /* xLock */ \
3708 UNLOCK, /* xUnlock */ \
3709 CKLOCK, /* xCheckReservedLock */ \
3710 unixFileControl, /* xFileControl */ \
3711 unixSectorSize, /* xSectorSize */ \
3712 unixDeviceCharacteristics /* xDeviceCapabilities */ \
3713}; \
3714static const sqlite3_io_methods *FINDER(const char *z, int h){ \
3715 UNUSED_PARAMETER(z); UNUSED_PARAMETER(h); \
3716 return &METHOD; \
aswiftaebf4132008-11-21 00:10:35 +00003717}
drh7708e972008-11-29 00:56:52 +00003718
3719/*
3720** Here are all of the sqlite3_io_methods objects for each of the
3721** locking strategies. Functions that return pointers to these methods
3722** are also created.
3723*/
3724IOMETHODS(
3725 posixIoFinder, /* Finder function name */
3726 posixIoMethods, /* sqlite3_io_methods object name */
3727 unixClose, /* xClose method */
3728 unixLock, /* xLock method */
3729 unixUnlock, /* xUnlock method */
3730 unixCheckReservedLock /* xCheckReservedLock method */
3731);
3732IOMETHODS(
3733 nolockIoFinder, /* Finder function name */
3734 nolockIoMethods, /* sqlite3_io_methods object name */
3735 nolockClose, /* xClose method */
3736 nolockLock, /* xLock method */
3737 nolockUnlock, /* xUnlock method */
3738 nolockCheckReservedLock /* xCheckReservedLock method */
3739);
3740IOMETHODS(
3741 dotlockIoFinder, /* Finder function name */
3742 dotlockIoMethods, /* sqlite3_io_methods object name */
3743 dotlockClose, /* xClose method */
3744 dotlockLock, /* xLock method */
3745 dotlockUnlock, /* xUnlock method */
3746 dotlockCheckReservedLock /* xCheckReservedLock method */
3747);
3748
3749#if SQLITE_ENABLE_LOCKING_STYLE
3750IOMETHODS(
3751 flockIoFinder, /* Finder function name */
3752 flockIoMethods, /* sqlite3_io_methods object name */
3753 flockClose, /* xClose method */
3754 flockLock, /* xLock method */
3755 flockUnlock, /* xUnlock method */
3756 flockCheckReservedLock /* xCheckReservedLock method */
3757);
3758#endif
3759
drh6c7d5c52008-11-21 20:32:33 +00003760#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003761IOMETHODS(
3762 semIoFinder, /* Finder function name */
3763 semIoMethods, /* sqlite3_io_methods object name */
3764 semClose, /* xClose method */
3765 semLock, /* xLock method */
3766 semUnlock, /* xUnlock method */
3767 semCheckReservedLock /* xCheckReservedLock method */
3768);
aswiftaebf4132008-11-21 00:10:35 +00003769#endif
drh7708e972008-11-29 00:56:52 +00003770
drh734c9862008-11-28 15:37:20 +00003771#if defined(__DARWIN__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003772IOMETHODS(
3773 afpIoFinder, /* Finder function name */
3774 afpIoMethods, /* sqlite3_io_methods object name */
3775 afpClose, /* xClose method */
3776 afpLock, /* xLock method */
3777 afpUnlock, /* xUnlock method */
3778 afpCheckReservedLock /* xCheckReservedLock method */
3779);
3780IOMETHODS(
3781 proxyIoFinder, /* Finder function name */
3782 proxyIoMethods, /* sqlite3_io_methods object name */
3783 proxyClose, /* xClose method */
3784 proxyLock, /* xLock method */
3785 proxyUnlock, /* xUnlock method */
3786 proxyCheckReservedLock /* xCheckReservedLock method */
3787);
aswiftaebf4132008-11-21 00:10:35 +00003788#endif
drh7708e972008-11-29 00:56:52 +00003789
3790
3791#if defined(__DARWIN__) && SQLITE_ENABLE_LOCKING_STYLE
3792/*
3793** This procedure attempts to determine the best locking strategy for
3794** the given database file. It then returns the sqlite3_io_methods
3795** object that implements that strategy.
3796**
3797** This is for MacOSX only.
3798*/
3799static const sqlite3_io_methods *autolockIoFinder(
3800 const char *filePath, /* name of the database file */
3801 int fd /* file descriptor open on the database file */
3802){
3803 static const struct Mapping {
3804 const char *zFilesystem;
3805 const sqlite3_io_methods *pMethods;
3806 } aMap[] = {
3807 { "hfs", &posixIoMethods },
3808 { "ufs", &posixIoMethods },
3809 { "afpfs", &afpIoMethods },
3810#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
3811 { "smbfs", &afpIoMethods },
3812#else
3813 { "smbfs", &flockIoMethods },
3814#endif
3815 { "webdav", &nolockIoMethods },
3816 { 0, 0 }
3817 };
3818 int i;
3819 struct statfs fsInfo;
3820 struct flock lockInfo;
3821
3822 if( !filePath ){
3823 return &nolockIoMethods;
3824 }
3825 if( statfs(filePath, &fsInfo) != -1 ){
3826 if( fsInfo.f_flags & MNT_RDONLY ){
3827 return &nolockIoMethods;
3828 }
3829 for(i=0; aMap[i].zFilesystem; i++){
3830 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
3831 return aMap[i].pMethods;
3832 }
3833 }
3834 }
3835
3836 /* Default case. Handles, amongst others, "nfs".
3837 ** Test byte-range lock using fcntl(). If the call succeeds,
3838 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00003839 */
drh7708e972008-11-29 00:56:52 +00003840 lockInfo.l_len = 1;
3841 lockInfo.l_start = 0;
3842 lockInfo.l_whence = SEEK_SET;
3843 lockInfo.l_type = F_RDLCK;
3844 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
3845 return &posixIoMethods;
3846 }else{
3847 return &dotlockIoMethods;
3848 }
3849}
3850#endif /* defined(__DARWIN__) && SQLITE_ENABLE_LOCKING_STYLE */
3851
3852/*
3853** An abstract type for a pointer to a IO method finder function:
3854*/
3855typedef const sqlite3_io_methods *(*finder_type)(const char*,int);
3856
aswiftaebf4132008-11-21 00:10:35 +00003857
drh734c9862008-11-28 15:37:20 +00003858/****************************************************************************
3859**************************** sqlite3_vfs methods ****************************
3860**
3861** This division contains the implementation of methods on the
3862** sqlite3_vfs object.
3863*/
3864
danielk1977a3d4c882007-03-23 10:08:38 +00003865/*
danielk1977e339d652008-06-28 11:23:00 +00003866** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00003867*/
3868static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00003869 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00003870 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00003871 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00003872 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00003873 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00003874 int noLock, /* Omit locking if true */
3875 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00003876){
drh7708e972008-11-29 00:56:52 +00003877 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00003878 unixFile *pNew = (unixFile *)pId;
3879 int rc = SQLITE_OK;
3880
danielk197717b90b52008-06-06 11:11:25 +00003881 assert( pNew->pLock==NULL );
3882 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00003883
danielk1977a03396a2008-11-19 14:35:46 +00003884 /* Parameter isDelete is only used on vxworks. Parameter pVfs is only
3885 ** used if ENABLE_LOCKING_STYLE is defined. Express this explicitly
3886 ** here to prevent compiler warnings about unused parameters.
3887 */
drh7708e972008-11-29 00:56:52 +00003888#if !OS_VXWORKS
3889 UNUSED_PARAMETER(isDelete);
3890#endif
3891#if !SQLITE_ENABLE_LOCKING_STYLE
3892 UNUSED_PARAMETER(pVfs);
3893#endif
3894#if !OS_VXWORKS && !SQLITE_ENABLE_LOCKING_STYLE
3895 UNUSED_PARAMETER(zFilename);
3896#endif
danielk1977a03396a2008-11-19 14:35:46 +00003897
drh218c5082008-03-07 00:27:10 +00003898 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00003899 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00003900 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00003901 SET_THREADID(pNew);
drh339eb0b2008-03-07 15:34:11 +00003902
drh6c7d5c52008-11-21 20:32:33 +00003903#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00003904 pNew->pId = vxworksFindFileId(zFilename);
3905 if( pNew->pId==0 ){
3906 noLock = 1;
3907 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00003908 }
3909#endif
3910
drhda0e7682008-07-30 15:27:54 +00003911 if( noLock ){
drh7708e972008-11-29 00:56:52 +00003912 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00003913 }else{
drh7708e972008-11-29 00:56:52 +00003914 pLockingStyle = (*(finder_type)pVfs->pAppData)(zFilename, h);
aswiftaebf4132008-11-21 00:10:35 +00003915#if SQLITE_ENABLE_LOCKING_STYLE
3916 /* Cache zFilename in the locking context (AFP and dotlock override) for
3917 ** proxyLock activation is possible (remote proxy is based on db name)
3918 ** zFilename remains valid until file is closed, to support */
3919 pNew->lockingContext = (void*)zFilename;
3920#endif
drhda0e7682008-07-30 15:27:54 +00003921 }
danielk1977e339d652008-06-28 11:23:00 +00003922
drh7708e972008-11-29 00:56:52 +00003923 if( pLockingStyle == &posixIoMethods ){
3924 unixEnterMutex();
3925 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3926 unixLeaveMutex();
3927 }
danielk1977e339d652008-06-28 11:23:00 +00003928
drh7708e972008-11-29 00:56:52 +00003929#if SQLITE_ENABLE_LOCKING_STYLE && defined(__DARWIN__)
3930 else if( pLockingStyle == &apfIoMethods ){
3931 /* AFP locking uses the file path so it needs to be included in
3932 ** the afpLockingContext.
3933 */
3934 afpLockingContext *pCtx;
3935 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3936 if( pCtx==0 ){
3937 rc = SQLITE_NOMEM;
3938 }else{
3939 /* NB: zFilename exists and remains valid until the file is closed
3940 ** according to requirement F11141. So we do not need to make a
3941 ** copy of the filename. */
3942 pCtx->dbPath = zFilename;
3943 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00003944 unixEnterMutex();
drh7708e972008-11-29 00:56:52 +00003945 rc = findLockInfo(pNew, NULL, &pNew->pOpen);
3946 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00003947 }
drh7708e972008-11-29 00:56:52 +00003948 }
3949#endif
danielk1977e339d652008-06-28 11:23:00 +00003950
drh40bbb0a2008-09-23 10:23:26 +00003951#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00003952 else if( pLockingStyle == &dotlockIoMethods ){
3953 /* Dotfile locking uses the file path so it needs to be included in
3954 ** the dotlockLockingContext
3955 */
3956 char *zLockFile;
3957 int nFilename;
3958 nFilename = strlen(zFilename) + 6;
3959 zLockFile = (char *)sqlite3_malloc(nFilename);
3960 if( zLockFile==0 ){
3961 rc = SQLITE_NOMEM;
3962 }else{
3963 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00003964 }
drh7708e972008-11-29 00:56:52 +00003965 pNew->lockingContext = zLockFile;
3966 }
chw97185482008-11-17 08:05:31 +00003967#endif
danielk1977e339d652008-06-28 11:23:00 +00003968
drh6c7d5c52008-11-21 20:32:33 +00003969#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00003970 else if( pLockingStyle == &semIoMethods ){
3971 /* Named semaphore locking uses the file path so it needs to be
3972 ** included in the semLockingContext
3973 */
3974 unixEnterMutex();
3975 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
3976 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
3977 char *zSemName = pNew->pOpen->aSemName;
3978 int n;
3979 sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem",
3980 pNew->pId->zCanonicalName);
3981 for( n=0; zSemName[n]; n++ )
3982 if( zSemName[n]=='/' ) zSemName[n] = '_';
3983 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3984 if( pNew->pOpen->pSem == SEM_FAILED ){
3985 rc = SQLITE_NOMEM;
3986 pNew->pOpen->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00003987 }
chw97185482008-11-17 08:05:31 +00003988 }
drh7708e972008-11-29 00:56:52 +00003989 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003990 }
drh7708e972008-11-29 00:56:52 +00003991#endif
aswift5b1a2562008-08-22 00:22:35 +00003992
3993 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00003994#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00003995 if( rc!=SQLITE_OK ){
3996 unlink(zFilename);
3997 isDelete = 0;
3998 }
3999 pNew->isDelete = isDelete;
4000#endif
danielk1977e339d652008-06-28 11:23:00 +00004001 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00004002 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
drhbfe66312006-10-03 17:40:40 +00004003 close(h);
danielk1977e339d652008-06-28 11:23:00 +00004004 }else{
drh7708e972008-11-29 00:56:52 +00004005 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004006 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004007 }
danielk1977e339d652008-06-28 11:23:00 +00004008 return rc;
drh054889e2005-11-30 03:20:31 +00004009}
drh9c06c952005-11-26 00:25:00 +00004010
aswiftaebf4132008-11-21 00:10:35 +00004011#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00004012static int getDbPathForUnixFile(unixFile *pFile, char *dbPath){
drh7708e972008-11-29 00:56:52 +00004013#if defined(__DARWIN__)
4014 if( pFile->pMethod == &afpIoMethods ){
drh734c9862008-11-28 15:37:20 +00004015 /* afp style keeps a reference to the db path in the filePath field
4016 ** of the struct */
drh7708e972008-11-29 00:56:52 +00004017 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
4018 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath)
4019 }else
4020#endif
4021 if( pFile->pMethod == &dotlockIoMethods ){
drh734c9862008-11-28 15:37:20 +00004022 /* dot lock style uses the locking context to store the dot lock
4023 ** file path */
aswiftaebf4132008-11-21 00:10:35 +00004024 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
drh7708e972008-11-29 00:56:52 +00004025 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
4026 }else{
4027 /* all other styles use the locking context to store the db file path */
4028 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
4029 strcpy(dbPath, (char *)pFile->lockingContext);
aswiftaebf4132008-11-21 00:10:35 +00004030 }
aswiftaebf4132008-11-21 00:10:35 +00004031 return SQLITE_OK;
4032}
4033#endif
4034
danielk1977ad94b582007-08-20 06:44:22 +00004035/*
4036** Open a file descriptor to the directory containing file zFilename.
4037** If successful, *pFd is set to the opened file descriptor and
4038** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4039** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4040** value.
4041**
4042** If SQLITE_OK is returned, the caller is responsible for closing
4043** the file descriptor *pFd using close().
4044*/
danielk1977fee2d252007-08-18 10:59:19 +00004045static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004046 int ii;
drh777b17a2007-09-20 10:02:54 +00004047 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004048 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004049
drh153c62c2007-08-24 03:51:33 +00004050 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
danielk1977fee2d252007-08-18 10:59:19 +00004051 for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
4052 if( ii>0 ){
4053 zDirname[ii] = '\0';
4054 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004055 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004056#ifdef FD_CLOEXEC
4057 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4058#endif
4059 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
4060 }
4061 }
danielk1977fee2d252007-08-18 10:59:19 +00004062 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00004063 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00004064}
4065
danielk1977b4b47412007-08-17 15:53:36 +00004066/*
danielk197717b90b52008-06-06 11:11:25 +00004067** Create a temporary file name in zBuf. zBuf must be allocated
4068** by the calling process and must be big enough to hold at least
4069** pVfs->mxPathname bytes.
4070*/
4071static int getTempname(int nBuf, char *zBuf){
4072 static const char *azDirs[] = {
4073 0,
aswiftaebf4132008-11-21 00:10:35 +00004074 0,
danielk197717b90b52008-06-06 11:11:25 +00004075 "/var/tmp",
4076 "/usr/tmp",
4077 "/tmp",
4078 ".",
4079 };
4080 static const unsigned char zChars[] =
4081 "abcdefghijklmnopqrstuvwxyz"
4082 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4083 "0123456789";
drh41022642008-11-21 00:24:42 +00004084 unsigned int i, j;
danielk197717b90b52008-06-06 11:11:25 +00004085 struct stat buf;
4086 const char *zDir = ".";
4087
4088 /* It's odd to simulate an io-error here, but really this is just
4089 ** using the io-error infrastructure to test that SQLite handles this
4090 ** function failing.
4091 */
4092 SimulateIOError( return SQLITE_IOERR );
4093
4094 azDirs[0] = sqlite3_temp_directory;
aswiftaebf4132008-11-21 00:10:35 +00004095 if (NULL == azDirs[1]) {
4096 azDirs[1] = getenv("TMPDIR");
4097 }
4098
4099 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
danielk197717b90b52008-06-06 11:11:25 +00004100 if( azDirs[i]==0 ) continue;
4101 if( stat(azDirs[i], &buf) ) continue;
4102 if( !S_ISDIR(buf.st_mode) ) continue;
4103 if( access(azDirs[i], 07) ) continue;
4104 zDir = azDirs[i];
4105 break;
4106 }
4107
4108 /* Check that the output buffer is large enough for the temporary file
4109 ** name. If it is not, return SQLITE_ERROR.
4110 */
danielk197700e13612008-11-17 19:18:54 +00004111 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004112 return SQLITE_ERROR;
4113 }
4114
4115 do{
4116 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
4117 j = strlen(zBuf);
4118 sqlite3_randomness(15, &zBuf[j]);
4119 for(i=0; i<15; i++, j++){
4120 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4121 }
4122 zBuf[j] = 0;
4123 }while( access(zBuf,0)==0 );
4124 return SQLITE_OK;
4125}
4126
4127
4128/*
danielk1977ad94b582007-08-20 06:44:22 +00004129** Open the file zPath.
4130**
danielk1977b4b47412007-08-17 15:53:36 +00004131** Previously, the SQLite OS layer used three functions in place of this
4132** one:
4133**
4134** sqlite3OsOpenReadWrite();
4135** sqlite3OsOpenReadOnly();
4136** sqlite3OsOpenExclusive();
4137**
4138** These calls correspond to the following combinations of flags:
4139**
4140** ReadWrite() -> (READWRITE | CREATE)
4141** ReadOnly() -> (READONLY)
4142** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4143**
4144** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4145** true, the file was configured to be automatically deleted when the
4146** file handle closed. To achieve the same effect using this new
4147** interface, add the DELETEONCLOSE flag to those specified above for
4148** OpenExclusive().
4149*/
4150static int unixOpen(
drh153c62c2007-08-24 03:51:33 +00004151 sqlite3_vfs *pVfs,
danielk1977b4b47412007-08-17 15:53:36 +00004152 const char *zPath,
4153 sqlite3_file *pFile,
4154 int flags,
4155 int *pOutFlags
4156){
danielk1977fee2d252007-08-18 10:59:19 +00004157 int fd = 0; /* File descriptor returned by open() */
4158 int dirfd = -1; /* Directory file descriptor */
drh734c9862008-11-28 15:37:20 +00004159 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004160 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004161 int noLock; /* True to omit locking primitives */
aswiftaebf4132008-11-21 00:10:35 +00004162 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004163
4164 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4165 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4166 int isCreate = (flags & SQLITE_OPEN_CREATE);
4167 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4168 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
4169
danielk1977fee2d252007-08-18 10:59:19 +00004170 /* If creating a master or main-file journal, this function will open
4171 ** a file-descriptor on the directory too. The first time unixSync()
4172 ** is called the directory file descriptor will be fsync()ed and close()d.
4173 */
4174 int isOpenDirectory = (isCreate &&
4175 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
4176 );
4177
danielk197717b90b52008-06-06 11:11:25 +00004178 /* If argument zPath is a NULL pointer, this function is required to open
4179 ** a temporary file. Use this buffer to store the file name in.
4180 */
4181 char zTmpname[MAX_PATHNAME+1];
4182 const char *zName = zPath;
4183
danielk1977fee2d252007-08-18 10:59:19 +00004184 /* Check the following statements are true:
4185 **
4186 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4187 ** (b) if CREATE is set, then READWRITE must also be set, and
4188 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004189 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004190 */
danielk1977b4b47412007-08-17 15:53:36 +00004191 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004192 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004193 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004194 assert(isDelete==0 || isCreate);
4195
drh33f4e022007-09-03 15:19:34 +00004196 /* The main DB, main journal, and master journal are never automatically
4197 ** deleted
4198 */
4199 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
4200 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
4201 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00004202
danielk1977fee2d252007-08-18 10:59:19 +00004203 /* Assert that the upper layer has set one of the "file-type" flags. */
4204 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4205 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4206 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00004207 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00004208 );
4209
danielk1977e339d652008-06-28 11:23:00 +00004210 memset(pFile, 0, sizeof(unixFile));
4211
danielk197717b90b52008-06-06 11:11:25 +00004212 if( !zName ){
danielk197717b90b52008-06-06 11:11:25 +00004213 assert(isDelete && !isOpenDirectory);
4214 rc = getTempname(MAX_PATHNAME+1, zTmpname);
4215 if( rc!=SQLITE_OK ){
4216 return rc;
4217 }
4218 zName = zTmpname;
4219 }
4220
drh734c9862008-11-28 15:37:20 +00004221 if( isReadonly ) openFlags |= O_RDONLY;
4222 if( isReadWrite ) openFlags |= O_RDWR;
4223 if( isCreate ) openFlags |= O_CREAT;
4224 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4225 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004226
drh734c9862008-11-28 15:37:20 +00004227 fd = open(zName, openFlags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
4228 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags);
danielk19772f2d8c72007-08-30 16:13:33 +00004229 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00004230 /* Failed to open the file for read/write access. Try read-only. */
4231 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
4232 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00004233 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00004234 }
4235 if( fd<0 ){
4236 return SQLITE_CANTOPEN;
4237 }
4238 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00004239#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004240 zPath = zName;
4241#else
danielk197717b90b52008-06-06 11:11:25 +00004242 unlink(zName);
chw97185482008-11-17 08:05:31 +00004243#endif
danielk1977b4b47412007-08-17 15:53:36 +00004244 }
drh41022642008-11-21 00:24:42 +00004245#if SQLITE_ENABLE_LOCKING_STYLE
4246 else{
drh734c9862008-11-28 15:37:20 +00004247 ((unixFile*)pFile)->openFlags = openFlags;
drh41022642008-11-21 00:24:42 +00004248 }
4249#endif
danielk1977b4b47412007-08-17 15:53:36 +00004250 if( pOutFlags ){
4251 *pOutFlags = flags;
4252 }
4253
4254 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00004255 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00004256 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00004257 if( rc!=SQLITE_OK ){
aswiftaebf4132008-11-21 00:10:35 +00004258 close(fd); /* silently leak if fail, already in error */
danielk1977fee2d252007-08-18 10:59:19 +00004259 return rc;
4260 }
4261 }
danielk1977e339d652008-06-28 11:23:00 +00004262
4263#ifdef FD_CLOEXEC
4264 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
4265#endif
4266
drhda0e7682008-07-30 15:27:54 +00004267 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00004268
4269#if SQLITE_PREFER_PROXY_LOCKING
4270 if( zPath!=NULL && !noLock ){
4271 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4272 int useProxy = 0;
4273
4274 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy,
drh7708e972008-11-29 00:56:52 +00004275 ** 0 means never use proxy, NULL means use proxy for non-local files only
4276 */
aswiftaebf4132008-11-21 00:10:35 +00004277 if( envforce!=NULL ){
4278 useProxy = atoi(envforce)>0;
4279 }else{
4280 struct statfs fsInfo;
4281
4282 if( statfs(zPath, &fsInfo) == -1 ){
4283 ((unixFile*)pFile)->lastErrno = errno;
4284 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4285 close(fd); /* silently leak if fail, in error */
4286 return SQLITE_IOERR_ACCESS;
4287 }
4288 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4289 }
4290 if( useProxy ){
4291 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4292 if( rc==SQLITE_OK ){
4293 rc = transformUnixFileForLockProxy((unixFile*)pFile, ":auto:");
4294 }
4295 return rc;
4296 }
4297 }
4298#endif
4299
chw97185482008-11-17 08:05:31 +00004300 return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
danielk1977b4b47412007-08-17 15:53:36 +00004301}
4302
4303/*
danielk1977fee2d252007-08-18 10:59:19 +00004304** Delete the file at zPath. If the dirSync argument is true, fsync()
4305** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00004306*/
danielk1977397d65f2008-11-19 11:35:39 +00004307static int unixDelete(sqlite3_vfs *NotUsed, const char *zPath, int dirSync){
danielk1977fee2d252007-08-18 10:59:19 +00004308 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00004309 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004310 SimulateIOError(return SQLITE_IOERR_DELETE);
4311 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00004312#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00004313 if( dirSync ){
4314 int fd;
4315 rc = openDirectory(zPath, &fd);
4316 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00004317#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004318 if( fsync(fd)==-1 )
4319#else
4320 if( fsync(fd) )
4321#endif
4322 {
danielk1977fee2d252007-08-18 10:59:19 +00004323 rc = SQLITE_IOERR_DIR_FSYNC;
4324 }
aswiftaebf4132008-11-21 00:10:35 +00004325 if( close(fd)&&!rc ){
4326 rc = SQLITE_IOERR_DIR_CLOSE;
4327 }
danielk1977fee2d252007-08-18 10:59:19 +00004328 }
4329 }
danielk1977d138dd82008-10-15 16:02:48 +00004330#endif
danielk1977fee2d252007-08-18 10:59:19 +00004331 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00004332}
4333
danielk197790949c22007-08-17 16:50:38 +00004334/*
4335** Test the existance of or access permissions of file zPath. The
4336** test performed depends on the value of flags:
4337**
4338** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
4339** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
4340** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
4341**
4342** Otherwise return 0.
4343*/
danielk1977861f7452008-06-05 11:39:11 +00004344static int unixAccess(
danielk1977397d65f2008-11-19 11:35:39 +00004345 sqlite3_vfs *NotUsed,
danielk1977861f7452008-06-05 11:39:11 +00004346 const char *zPath,
4347 int flags,
4348 int *pResOut
4349){
rse25c0d1a2007-09-20 08:38:14 +00004350 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00004351 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00004352 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00004353 switch( flags ){
4354 case SQLITE_ACCESS_EXISTS:
4355 amode = F_OK;
4356 break;
4357 case SQLITE_ACCESS_READWRITE:
4358 amode = W_OK|R_OK;
4359 break;
drh50d3f902007-08-27 21:10:36 +00004360 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00004361 amode = R_OK;
4362 break;
4363
4364 default:
4365 assert(!"Invalid flags argument");
4366 }
danielk1977861f7452008-06-05 11:39:11 +00004367 *pResOut = (access(zPath, amode)==0);
4368 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004369}
4370
danielk1977b4b47412007-08-17 15:53:36 +00004371
4372/*
4373** Turn a relative pathname into a full pathname. The relative path
4374** is stored as a nul-terminated string in the buffer pointed to by
4375** zPath.
4376**
4377** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
4378** (in this case, MAX_PATHNAME bytes). The full-path is written to
4379** this buffer before returning.
4380*/
danielk1977adfb9b02007-09-17 07:02:56 +00004381static int unixFullPathname(
4382 sqlite3_vfs *pVfs, /* Pointer to vfs object */
4383 const char *zPath, /* Possibly relative input path */
4384 int nOut, /* Size of output buffer in bytes */
4385 char *zOut /* Output buffer */
4386){
danielk1977843e65f2007-09-01 16:16:15 +00004387
4388 /* It's odd to simulate an io-error here, but really this is just
4389 ** using the io-error infrastructure to test that SQLite handles this
4390 ** function failing. This function could fail if, for example, the
4391 ** current working directly has been unlinked.
4392 */
4393 SimulateIOError( return SQLITE_ERROR );
4394
drh153c62c2007-08-24 03:51:33 +00004395 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00004396 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00004397
drh3c7f2dc2007-12-06 13:26:20 +00004398 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00004399 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00004400 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004401 }else{
4402 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00004403 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00004404 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00004405 }
4406 nCwd = strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00004407 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00004408 }
4409 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00004410}
4411
drh0ccebe72005-06-07 22:22:50 +00004412
drh761df872006-12-21 01:29:22 +00004413#ifndef SQLITE_OMIT_LOAD_EXTENSION
4414/*
4415** Interfaces for opening a shared library, finding entry points
4416** within the shared library, and closing the shared library.
4417*/
4418#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00004419static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
4420 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004421 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
4422}
danielk197795c8a542007-09-01 06:51:27 +00004423
4424/*
4425** SQLite calls this function immediately after a call to unixDlSym() or
4426** unixDlOpen() fails (returns a null pointer). If a more detailed error
4427** message is available, it is written to zBufOut. If no error message
4428** is available, zBufOut is left unmodified and SQLite uses a default
4429** error message.
4430*/
danielk1977397d65f2008-11-19 11:35:39 +00004431static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00004432 char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00004433 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00004434 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004435 zErr = dlerror();
4436 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00004437 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00004438 }
drh6c7d5c52008-11-21 20:32:33 +00004439 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00004440}
danielk1977397d65f2008-11-19 11:35:39 +00004441static void *unixDlSym(sqlite3_vfs *NotUsed, void *pHandle, const char*zSymbol){
4442 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00004443 return dlsym(pHandle, zSymbol);
4444}
danielk1977397d65f2008-11-19 11:35:39 +00004445static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
4446 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00004447 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00004448}
danielk1977b4b47412007-08-17 15:53:36 +00004449#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4450 #define unixDlOpen 0
4451 #define unixDlError 0
4452 #define unixDlSym 0
4453 #define unixDlClose 0
4454#endif
4455
4456/*
danielk197790949c22007-08-17 16:50:38 +00004457** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00004458*/
danielk1977397d65f2008-11-19 11:35:39 +00004459static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
4460 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00004461 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00004462
drhbbd42a62004-05-22 17:41:58 +00004463 /* We have to initialize zBuf to prevent valgrind from reporting
4464 ** errors. The reports issued by valgrind are incorrect - we would
4465 ** prefer that the randomness be increased by making use of the
4466 ** uninitialized space in zBuf - but valgrind errors tend to worry
4467 ** some users. Rather than argue, it seems easier just to initialize
4468 ** the whole array and silence valgrind, even if that means less randomness
4469 ** in the random seed.
4470 **
4471 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00004472 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00004473 ** tests repeatable.
4474 */
danielk1977b4b47412007-08-17 15:53:36 +00004475 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00004476#if !defined(SQLITE_TEST)
4477 {
drh842b8642005-01-21 17:53:17 +00004478 int pid, fd;
4479 fd = open("/dev/urandom", O_RDONLY);
4480 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00004481 time_t t;
4482 time(&t);
danielk197790949c22007-08-17 16:50:38 +00004483 memcpy(zBuf, &t, sizeof(t));
4484 pid = getpid();
4485 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00004486 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00004487 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00004488 }else{
drh72cbd072008-10-14 17:58:38 +00004489 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00004490 close(fd);
4491 }
drhbbd42a62004-05-22 17:41:58 +00004492 }
4493#endif
drh72cbd072008-10-14 17:58:38 +00004494 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00004495}
4496
danielk1977b4b47412007-08-17 15:53:36 +00004497
drhbbd42a62004-05-22 17:41:58 +00004498/*
4499** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00004500** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00004501** The return value is the number of microseconds of sleep actually
4502** requested from the underlying operating system, a number which
4503** might be greater than or equal to the argument, but not less
4504** than the argument.
drhbbd42a62004-05-22 17:41:58 +00004505*/
danielk1977397d65f2008-11-19 11:35:39 +00004506static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00004507#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004508 struct timespec sp;
4509
4510 sp.tv_sec = microseconds / 1000000;
4511 sp.tv_nsec = (microseconds % 1000000) * 1000;
4512 nanosleep(&sp, NULL);
danielk1977397d65f2008-11-19 11:35:39 +00004513 return microseconds;
4514#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00004515 usleep(microseconds);
4516 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00004517#else
danielk1977b4b47412007-08-17 15:53:36 +00004518 int seconds = (microseconds+999999)/1000000;
4519 sleep(seconds);
drh4a50aac2007-08-23 02:47:53 +00004520 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00004521#endif
danielk1977397d65f2008-11-19 11:35:39 +00004522 UNUSED_PARAMETER(NotUsed);
drh88f474a2006-01-02 20:00:12 +00004523}
4524
4525/*
drhbbd42a62004-05-22 17:41:58 +00004526** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00004527** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00004528*/
4529#ifdef SQLITE_TEST
4530int sqlite3_current_time = 0;
4531#endif
4532
4533/*
4534** Find the current time (in Universal Coordinated Time). Write the
4535** current time and date as a Julian Day number into *prNow and
4536** return 0. Return 1 if the time and date cannot be found.
4537*/
danielk1977397d65f2008-11-19 11:35:39 +00004538static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drh6c7d5c52008-11-21 20:32:33 +00004539#if defined(NO_GETTOD)
drhbbd42a62004-05-22 17:41:58 +00004540 time_t t;
4541 time(&t);
4542 *prNow = t/86400.0 + 2440587.5;
drh6c7d5c52008-11-21 20:32:33 +00004543#elif OS_VXWORKS
4544 struct timespec sNow;
4545 clock_gettime(CLOCK_REALTIME, &sNow);
4546 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
drh19e2d372005-08-29 23:00:03 +00004547#else
4548 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00004549 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00004550 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
4551#endif
danielk1977397d65f2008-11-19 11:35:39 +00004552
drhbbd42a62004-05-22 17:41:58 +00004553#ifdef SQLITE_TEST
4554 if( sqlite3_current_time ){
4555 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
4556 }
4557#endif
danielk1977397d65f2008-11-19 11:35:39 +00004558 UNUSED_PARAMETER(NotUsed);
drhbbd42a62004-05-22 17:41:58 +00004559 return 0;
4560}
danielk1977b4b47412007-08-17 15:53:36 +00004561
danielk1977397d65f2008-11-19 11:35:39 +00004562static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4563 UNUSED_PARAMETER(NotUsed);
4564 UNUSED_PARAMETER(NotUsed2);
4565 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00004566 return 0;
4567}
4568
drh153c62c2007-08-24 03:51:33 +00004569/*
drh734c9862008-11-28 15:37:20 +00004570************************ End of sqlite3_vfs methods ***************************
4571******************************************************************************/
4572
4573/*
danielk1977e339d652008-06-28 11:23:00 +00004574** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00004575**
4576** This routine registers all VFS implementations for unix-like operating
4577** systems. This routine, and the sqlite3_os_end() routine that follows,
4578** should be the only routines in this file that are visible from other
4579** files.
drh153c62c2007-08-24 03:51:33 +00004580*/
danielk1977c0fa4c52008-06-25 17:19:00 +00004581int sqlite3_os_init(void){
danielk1977e339d652008-06-28 11:23:00 +00004582 /* Macro to define the static contents of an sqlite3_vfs structure for
4583 ** the unix backend. The two parameters are the values to use for
4584 ** the sqlite3_vfs.zName and sqlite3_vfs.pAppData fields, respectively.
4585 **
4586 */
drh7708e972008-11-29 00:56:52 +00004587 #define UNIXVFS(VFSNAME, FINDER) { \
danielk1977e339d652008-06-28 11:23:00 +00004588 1, /* iVersion */ \
4589 sizeof(unixFile), /* szOsFile */ \
4590 MAX_PATHNAME, /* mxPathname */ \
4591 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00004592 VFSNAME, /* zName */ \
4593 (void*)FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00004594 unixOpen, /* xOpen */ \
4595 unixDelete, /* xDelete */ \
4596 unixAccess, /* xAccess */ \
4597 unixFullPathname, /* xFullPathname */ \
4598 unixDlOpen, /* xDlOpen */ \
4599 unixDlError, /* xDlError */ \
4600 unixDlSym, /* xDlSym */ \
4601 unixDlClose, /* xDlClose */ \
4602 unixRandomness, /* xRandomness */ \
4603 unixSleep, /* xSleep */ \
4604 unixCurrentTime, /* xCurrentTime */ \
4605 unixGetLastError /* xGetLastError */ \
4606 }
4607
drh7708e972008-11-29 00:56:52 +00004608 unsigned int i;
danielk1977e339d652008-06-28 11:23:00 +00004609 static sqlite3_vfs aVfs[] = {
drh7708e972008-11-29 00:56:52 +00004610#if SQLITE_ENABLE_LOCKING_STYLE && defined(__DARWIN__)
4611 UNIXVFS("unix", autolockIoFinder ),
4612#else
4613 UNIXVFS("unix", posixIoFinder ),
4614#endif
4615 UNIXVFS("unix-none", nolockIoFinder ),
4616 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drh734c9862008-11-28 15:37:20 +00004617#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004618 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00004619#endif
4620#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004621 UNIXVFS("unix-posix", posixIoFinder ),
4622 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00004623#endif
4624#if SQLITE_ENABLE_LOCKING_STYLE && defined(__DARWIN__)
drh7708e972008-11-29 00:56:52 +00004625 UNIXVFS("unix-afp", afpIoFinder ),
4626 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00004627#endif
drh153c62c2007-08-24 03:51:33 +00004628 };
danielk1977e339d652008-06-28 11:23:00 +00004629 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00004630 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00004631 }
danielk1977c0fa4c52008-06-25 17:19:00 +00004632 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00004633}
danielk1977e339d652008-06-28 11:23:00 +00004634
4635/*
4636** Shutdown the operating system interface. This is a no-op for unix.
4637*/
danielk1977c0fa4c52008-06-25 17:19:00 +00004638int sqlite3_os_end(void){
4639 return SQLITE_OK;
4640}
drhdce8bdb2007-08-16 13:01:44 +00004641
danielk197729bafea2008-06-26 10:41:19 +00004642#endif /* SQLITE_OS_UNIX */