blob: fa03d33f4dfd3934bd1246a780b8bad0c7b3b7be [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**
13** This file contains code that is specific to Unix systems.
danielk1977822a5162008-05-16 04:51:54 +000014**
danielk197729bafea2008-06-26 10:41:19 +000015** $Id: os_unix.c,v 1.190 2008/06/26 10:41:19 danielk1977 Exp $
drhbbd42a62004-05-22 17:41:58 +000016*/
drhbbd42a62004-05-22 17:41:58 +000017#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000018#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000019
drhbfe66312006-10-03 17:40:40 +000020/* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
21
drh9cbe6352005-11-29 03:13:21 +000022/*
23** These #defines should enable >2GB file support on Posix if the
24** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000025** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000026**
27** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
28** on the compiler command line. This is necessary if you are compiling
29** on a recent machine (ex: RedHat 7.2) but you want your code to work
30** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
31** without this option, LFS is enable. But LFS does not exist in the kernel
32** in RedHat 6.0, so the code won't work. Hence, for maximum binary
33** portability you should omit LFS.
drh9cbe6352005-11-29 03:13:21 +000034*/
35#ifndef SQLITE_DISABLE_LFS
36# define _LARGE_FILE 1
37# ifndef _FILE_OFFSET_BITS
38# define _FILE_OFFSET_BITS 64
39# endif
40# define _LARGEFILE_SOURCE 1
41#endif
drhbbd42a62004-05-22 17:41:58 +000042
drh9cbe6352005-11-29 03:13:21 +000043/*
44** standard include files.
45*/
46#include <sys/types.h>
47#include <sys/stat.h>
48#include <fcntl.h>
49#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000050#include <time.h>
drh19e2d372005-08-29 23:00:03 +000051#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000052#include <errno.h>
drhbfe66312006-10-03 17:40:40 +000053#ifdef SQLITE_ENABLE_LOCKING_STYLE
54#include <sys/ioctl.h>
55#include <sys/param.h>
56#include <sys/mount.h>
57#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000058
59/*
drhf1a221e2006-01-15 17:27:17 +000060** If we are to be thread-safe, include the pthreads header and define
61** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +000062*/
drhd677b3d2007-08-20 22:48:41 +000063#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +000064# include <pthread.h>
65# define SQLITE_UNIX_THREADS 1
66#endif
67
68/*
69** Default permissions when creating a new file
70*/
71#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
72# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
73#endif
74
danielk1977b4b47412007-08-17 15:53:36 +000075/*
76** Maximum supported path-length.
77*/
78#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +000079
80
81/*
danielk1977ad94b582007-08-20 06:44:22 +000082** The unixFile structure is subclass of sqlite3_file specific for the unix
drh054889e2005-11-30 03:20:31 +000083** protability layer.
drh9cbe6352005-11-29 03:13:21 +000084*/
drh054889e2005-11-30 03:20:31 +000085typedef struct unixFile unixFile;
86struct unixFile {
danielk197762079062007-08-15 17:08:46 +000087 sqlite3_io_methods const *pMethod; /* Always the first entry */
danielk1977967a4a12007-08-20 14:23:44 +000088#ifdef SQLITE_TEST
89 /* In test mode, increase the size of this structure a bit so that
90 ** it is larger than the struct CrashFile defined in test6.c.
91 */
92 char aPadding[32];
93#endif
drh9cbe6352005-11-29 03:13:21 +000094 struct openCnt *pOpen; /* Info about all open fd's on this inode */
95 struct lockInfo *pLock; /* Info about locks on this inode */
drhbfe66312006-10-03 17:40:40 +000096#ifdef SQLITE_ENABLE_LOCKING_STYLE
97 void *lockingContext; /* Locking style specific state */
98#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000099 int h; /* The file descriptor */
100 unsigned char locktype; /* The type of lock held on this fd */
drh9cbe6352005-11-29 03:13:21 +0000101 int dirfd; /* File descriptor for the directory */
drhd677b3d2007-08-20 22:48:41 +0000102#if SQLITE_THREADSAFE
danielk1977ad94b582007-08-20 06:44:22 +0000103 pthread_t tid; /* The thread that "owns" this unixFile */
drh9cbe6352005-11-29 03:13:21 +0000104#endif
105};
106
drh0ccebe72005-06-07 22:22:50 +0000107/*
drh198bf392006-01-06 21:52:49 +0000108** Include code that is common to all os_*.c files
109*/
110#include "os_common.h"
111
112/*
drh0ccebe72005-06-07 22:22:50 +0000113** Define various macros that are missing from some systems.
114*/
drhbbd42a62004-05-22 17:41:58 +0000115#ifndef O_LARGEFILE
116# define O_LARGEFILE 0
117#endif
118#ifdef SQLITE_DISABLE_LFS
119# undef O_LARGEFILE
120# define O_LARGEFILE 0
121#endif
122#ifndef O_NOFOLLOW
123# define O_NOFOLLOW 0
124#endif
125#ifndef O_BINARY
126# define O_BINARY 0
127#endif
128
129/*
130** The DJGPP compiler environment looks mostly like Unix, but it
131** lacks the fcntl() system call. So redefine fcntl() to be something
132** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000133** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000134*/
135#ifdef __DJGPP__
136# define fcntl(A,B,C) 0
137#endif
138
139/*
drh2b4b5962005-06-15 17:47:55 +0000140** The threadid macro resolves to the thread-id or to 0. Used for
141** testing and debugging only.
142*/
drhd677b3d2007-08-20 22:48:41 +0000143#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000144#define threadid pthread_self()
145#else
146#define threadid 0
147#endif
148
149/*
danielk1977ad94b582007-08-20 06:44:22 +0000150** Set or check the unixFile.tid field. This field is set when an unixFile
151** is first opened. All subsequent uses of the unixFile verify that the
152** same thread is operating on the unixFile. Some operating systems do
drh2b4b5962005-06-15 17:47:55 +0000153** not allow locks to be overridden by other threads and that restriction
154** means that sqlite3* database handles cannot be moved from one thread
155** to another. This logic makes sure a user does not try to do that
156** by mistake.
drhf1a221e2006-01-15 17:27:17 +0000157**
danielk1977ad94b582007-08-20 06:44:22 +0000158** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
drhf1a221e2006-01-15 17:27:17 +0000159** another as long as we are running on a system that supports threads
160** overriding each others locks (which now the most common behavior)
danielk1977ad94b582007-08-20 06:44:22 +0000161** or if no locks are held. But the unixFile.pLock field needs to be
drhf1a221e2006-01-15 17:27:17 +0000162** recomputed because its key includes the thread-id. See the
163** transferOwnership() function below for additional information
drh2b4b5962005-06-15 17:47:55 +0000164*/
drhd677b3d2007-08-20 22:48:41 +0000165#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000166# define SET_THREADID(X) (X)->tid = pthread_self()
drh029b44b2006-01-15 00:13:15 +0000167# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
168 !pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000169#else
170# define SET_THREADID(X)
171# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000172#endif
173
drhbbd42a62004-05-22 17:41:58 +0000174/*
175** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
176** section 6.5.2.2 lines 483 through 490 specify that when a process
177** sets or clears a lock, that operation overrides any prior locks set
178** by the same process. It does not explicitly say so, but this implies
179** that it overrides locks set by the same process using a different
180** file descriptor. Consider this test case:
181**
182** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
183** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
184**
185** Suppose ./file1 and ./file2 are really the same file (because
186** one is a hard or symbolic link to the other) then if you set
187** an exclusive lock on fd1, then try to get an exclusive lock
188** on fd2, it works. I would have expected the second lock to
189** fail since there was already a lock on the file due to fd1.
190** But not so. Since both locks came from the same process, the
191** second overrides the first, even though they were on different
192** file descriptors opened on different file names.
193**
194** Bummer. If you ask me, this is broken. Badly broken. It means
195** that we cannot use POSIX locks to synchronize file access among
196** competing threads of the same process. POSIX locks will work fine
197** to synchronize access for threads in separate processes, but not
198** threads within the same process.
199**
200** To work around the problem, SQLite has to manage file locks internally
201** on its own. Whenever a new database is opened, we have to find the
202** specific inode of the database file (the inode is determined by the
203** st_dev and st_ino fields of the stat structure that fstat() fills in)
204** and check for locks already existing on that inode. When locks are
205** created or removed, we have to look at our own internal record of the
206** locks to see if another thread has previously set a lock on that same
207** inode.
208**
danielk1977ad94b582007-08-20 06:44:22 +0000209** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000210** descriptor. It is now a structure that holds the integer file
211** descriptor and a pointer to a structure that describes the internal
212** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000213** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000214** point to the same locking structure. The locking structure keeps
215** a reference count (so we will know when to delete it) and a "cnt"
216** field that tells us its internal lock status. cnt==0 means the
217** file is unlocked. cnt==-1 means the file has an exclusive lock.
218** cnt>0 means there are cnt shared locks on the file.
219**
220** Any attempt to lock or unlock a file first checks the locking
221** structure. The fcntl() system call is only invoked to set a
222** POSIX lock if the internal lock structure transitions between
223** a locked and an unlocked state.
224**
225** 2004-Jan-11:
226** More recent discoveries about POSIX advisory locks. (The more
227** I discover, the more I realize the a POSIX advisory locks are
228** an abomination.)
229**
230** If you close a file descriptor that points to a file that has locks,
231** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000232** released. To work around this problem, each unixFile structure contains
drhbbd42a62004-05-22 17:41:58 +0000233** a pointer to an openCnt structure. There is one openCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000234** per open inode, which means that multiple unixFile can point to a single
235** openCnt. When an attempt is made to close an unixFile, if there are
236** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000237** to close() the file descriptor is deferred until all of the locks clear.
238** The openCnt structure keeps a list of file descriptors that need to
239** be closed and that list is walked (and cleared) when the last lock
240** clears.
241**
242** First, under Linux threads, because each thread has a separate
243** process ID, lock operations in one thread do not override locks
244** to the same file in other threads. Linux threads behave like
245** separate processes in this respect. But, if you close a file
246** descriptor in linux threads, all locks are cleared, even locks
247** on other threads and even though the other threads have different
248** process IDs. Linux threads is inconsistent in this respect.
249** (I'm beginning to think that linux threads is an abomination too.)
250** The consequence of this all is that the hash table for the lockInfo
251** structure has to include the process id as part of its key because
252** locks in different threads are treated as distinct. But the
253** openCnt structure should not include the process id in its
254** key because close() clears lock on all threads, not just the current
255** thread. Were it not for this goofiness in linux threads, we could
256** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000257**
258** 2004-Jun-28:
259** On some versions of linux, threads can override each others locks.
260** On others not. Sometimes you can change the behavior on the same
261** system by setting the LD_ASSUME_KERNEL environment variable. The
262** POSIX standard is silent as to which behavior is correct, as far
263** as I can tell, so other versions of unix might show the same
264** inconsistency. There is no little doubt in my mind that posix
265** advisory locks and linux threads are profoundly broken.
266**
267** To work around the inconsistencies, we have to test at runtime
268** whether or not threads can override each others locks. This test
269** is run once, the first time any lock is attempted. A static
270** variable is set to record the results of this test for future
271** use.
drhbbd42a62004-05-22 17:41:58 +0000272*/
273
274/*
275** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000276** to locate a particular lockInfo structure given its inode.
277**
278** If threads cannot override each others locks, then we set the
279** lockKey.tid field to the thread ID. If threads can override
drhf1a221e2006-01-15 17:27:17 +0000280** each others locks then tid is always set to zero. tid is omitted
281** if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000282*/
283struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000284 dev_t dev; /* Device number */
285 ino_t ino; /* Inode number */
drhd677b3d2007-08-20 22:48:41 +0000286#if SQLITE_THREADSAFE
drhd9cb6ac2005-10-20 07:28:17 +0000287 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000288#endif
drhbbd42a62004-05-22 17:41:58 +0000289};
290
291/*
292** An instance of the following structure is allocated for each open
293** inode on each thread with a different process ID. (Threads have
294** different process IDs on linux, but not on most other unixes.)
295**
danielk1977ad94b582007-08-20 06:44:22 +0000296** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000297** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000298** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000299*/
300struct lockInfo {
301 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000302 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000303 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000304 int nRef; /* Number of pointers to this structure */
305};
306
307/*
308** An instance of the following structure serves as the key used
309** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000310** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000311*/
312struct openKey {
313 dev_t dev; /* Device number */
314 ino_t ino; /* Inode number */
315};
316
317/*
318** An instance of the following structure is allocated for each open
319** inode. This structure keeps track of the number of locks on that
320** inode. If a close is attempted against an inode that is holding
321** locks, the close is deferred until all locks clear by adding the
322** file descriptor to be closed to the pending list.
323*/
324struct openCnt {
325 struct openKey key; /* The lookup key */
326 int nRef; /* Number of pointers to this structure */
327 int nLock; /* Number of outstanding locks */
328 int nPending; /* Number of pending close() operations */
329 int *aPending; /* Malloced space holding fd's awaiting a close() */
330};
331
332/*
drhf1a221e2006-01-15 17:27:17 +0000333** These hash tables map inodes and file descriptors (really, lockKey and
334** openKey structures) into lockInfo and openCnt structures. Access to
335** these hash tables must be protected by a mutex.
drhbbd42a62004-05-22 17:41:58 +0000336*/
drh17435752007-08-16 04:30:38 +0000337static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
338static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
drh5fdae772004-06-29 03:29:00 +0000339
drhbfe66312006-10-03 17:40:40 +0000340#ifdef SQLITE_ENABLE_LOCKING_STYLE
341/*
342** The locking styles are associated with the different file locking
343** capabilities supported by different file systems.
344**
345** POSIX locking style fully supports shared and exclusive byte-range locks
346** ADP locking only supports exclusive byte-range locks
347** FLOCK only supports a single file-global exclusive lock
348** DOTLOCK isn't a true locking style, it refers to the use of a special
349** file named the same as the database file with a '.lock' extension, this
350** can be used on file systems that do not offer any reliable file locking
351** NO locking means that no locking will be attempted, this is only used for
352** read-only file systems currently
353** UNSUPPORTED means that no locking will be attempted, this is only used for
354** file systems that are known to be unsupported
355*/
356typedef enum {
drh339eb0b2008-03-07 15:34:11 +0000357 posixLockingStyle = 0, /* standard posix-advisory locks */
358 afpLockingStyle, /* use afp locks */
359 flockLockingStyle, /* use flock() */
360 dotlockLockingStyle, /* use <file>.lock files */
361 noLockingStyle, /* useful for read-only file system */
362 unsupportedLockingStyle /* indicates unsupported file system */
drhbfe66312006-10-03 17:40:40 +0000363} sqlite3LockingStyle;
364#endif /* SQLITE_ENABLE_LOCKING_STYLE */
365
danielk1977ad94b582007-08-20 06:44:22 +0000366/*
367** Helper functions to obtain and relinquish the global mutex.
368*/
danielk1977b4b47412007-08-17 15:53:36 +0000369static void enterMutex(){
danielk197759f8c082008-06-18 17:09:10 +0000370 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
danielk1977b4b47412007-08-17 15:53:36 +0000371}
372static void leaveMutex(){
danielk197759f8c082008-06-18 17:09:10 +0000373 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
danielk1977b4b47412007-08-17 15:53:36 +0000374}
375
drhd677b3d2007-08-20 22:48:41 +0000376#if SQLITE_THREADSAFE
drh5fdae772004-06-29 03:29:00 +0000377/*
378** This variable records whether or not threads can override each others
379** locks.
380**
381** 0: No. Threads cannot override each others locks.
382** 1: Yes. Threads can override each others locks.
383** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000384**
drh5062d3a2006-01-31 23:03:35 +0000385** On some systems, we know at compile-time if threads can override each
386** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
387** will be set appropriately. On other systems, we have to check at
388** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
389** undefined.
390**
drhf1a221e2006-01-15 17:27:17 +0000391** This variable normally has file scope only. But during testing, we make
392** it a global so that the test code can change its value in order to verify
393** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000394*/
drh5062d3a2006-01-31 23:03:35 +0000395#ifndef SQLITE_THREAD_OVERRIDE_LOCK
396# define SQLITE_THREAD_OVERRIDE_LOCK -1
397#endif
drh029b44b2006-01-15 00:13:15 +0000398#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000399int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000400#else
drh5062d3a2006-01-31 23:03:35 +0000401static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000402#endif
drh5fdae772004-06-29 03:29:00 +0000403
404/*
405** This structure holds information passed into individual test
406** threads by the testThreadLockingBehavior() routine.
407*/
408struct threadTestData {
409 int fd; /* File to be locked */
410 struct flock lock; /* The locking operation */
411 int result; /* Result of the locking operation */
412};
413
drh2b4b5962005-06-15 17:47:55 +0000414#ifdef SQLITE_LOCK_TRACE
415/*
416** Print out information about all locking operations.
417**
418** This routine is used for troubleshooting locks on multithreaded
419** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
420** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000421** turned off.
drh2b4b5962005-06-15 17:47:55 +0000422*/
423static int lockTrace(int fd, int op, struct flock *p){
424 char *zOpName, *zType;
425 int s;
426 int savedErrno;
427 if( op==F_GETLK ){
428 zOpName = "GETLK";
429 }else if( op==F_SETLK ){
430 zOpName = "SETLK";
431 }else{
432 s = fcntl(fd, op, p);
433 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
434 return s;
435 }
436 if( p->l_type==F_RDLCK ){
437 zType = "RDLCK";
438 }else if( p->l_type==F_WRLCK ){
439 zType = "WRLCK";
440 }else if( p->l_type==F_UNLCK ){
441 zType = "UNLCK";
442 }else{
443 assert( 0 );
444 }
445 assert( p->l_whence==SEEK_SET );
446 s = fcntl(fd, op, p);
447 savedErrno = errno;
448 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
449 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
450 (int)p->l_pid, s);
drhe2396a12007-03-29 20:19:58 +0000451 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
drh2b4b5962005-06-15 17:47:55 +0000452 struct flock l2;
453 l2 = *p;
454 fcntl(fd, F_GETLK, &l2);
455 if( l2.l_type==F_RDLCK ){
456 zType = "RDLCK";
457 }else if( l2.l_type==F_WRLCK ){
458 zType = "WRLCK";
459 }else if( l2.l_type==F_UNLCK ){
460 zType = "UNLCK";
461 }else{
462 assert( 0 );
463 }
464 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
465 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
466 }
467 errno = savedErrno;
468 return s;
469}
470#define fcntl lockTrace
471#endif /* SQLITE_LOCK_TRACE */
472
drh5fdae772004-06-29 03:29:00 +0000473/*
474** The testThreadLockingBehavior() routine launches two separate
475** threads on this routine. This routine attempts to lock a file
476** descriptor then returns. The success or failure of that attempt
477** allows the testThreadLockingBehavior() procedure to determine
478** whether or not threads can override each others locks.
479*/
480static void *threadLockingTest(void *pArg){
481 struct threadTestData *pData = (struct threadTestData*)pArg;
482 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
483 return pArg;
484}
485
486/*
487** This procedure attempts to determine whether or not threads
488** can override each others locks then sets the
489** threadsOverrideEachOthersLocks variable appropriately.
490*/
danielk19774d5238f2006-01-27 06:32:00 +0000491static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000492 int fd;
493 struct threadTestData d[2];
494 pthread_t t[2];
495
496 fd = dup(fd_orig);
497 if( fd<0 ) return;
498 memset(d, 0, sizeof(d));
499 d[0].fd = fd;
500 d[0].lock.l_type = F_RDLCK;
501 d[0].lock.l_len = 1;
502 d[0].lock.l_start = 0;
503 d[0].lock.l_whence = SEEK_SET;
504 d[1] = d[0];
505 d[1].lock.l_type = F_WRLCK;
506 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
507 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
508 pthread_join(t[0], 0);
509 pthread_join(t[1], 0);
510 close(fd);
511 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
512}
drhd677b3d2007-08-20 22:48:41 +0000513#endif /* SQLITE_THREADSAFE */
drh5fdae772004-06-29 03:29:00 +0000514
drhbbd42a62004-05-22 17:41:58 +0000515/*
516** Release a lockInfo structure previously allocated by findLockInfo().
517*/
518static void releaseLockInfo(struct lockInfo *pLock){
drhbfe66312006-10-03 17:40:40 +0000519 if (pLock == NULL)
520 return;
drhbbd42a62004-05-22 17:41:58 +0000521 pLock->nRef--;
522 if( pLock->nRef==0 ){
523 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
drh17435752007-08-16 04:30:38 +0000524 sqlite3_free(pLock);
drhbbd42a62004-05-22 17:41:58 +0000525 }
526}
527
528/*
529** Release a openCnt structure previously allocated by findLockInfo().
530*/
531static void releaseOpenCnt(struct openCnt *pOpen){
drhbfe66312006-10-03 17:40:40 +0000532 if (pOpen == NULL)
533 return;
drhbbd42a62004-05-22 17:41:58 +0000534 pOpen->nRef--;
535 if( pOpen->nRef==0 ){
536 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
drh64b1bea2006-01-15 02:30:57 +0000537 free(pOpen->aPending);
drh17435752007-08-16 04:30:38 +0000538 sqlite3_free(pOpen);
drhbbd42a62004-05-22 17:41:58 +0000539 }
540}
541
drhbfe66312006-10-03 17:40:40 +0000542#ifdef SQLITE_ENABLE_LOCKING_STYLE
543/*
544** Tests a byte-range locking query to see if byte range locks are
545** supported, if not we fall back to dotlockLockingStyle.
546*/
danielk1977ad94b582007-08-20 06:44:22 +0000547static sqlite3LockingStyle sqlite3TestLockingStyle(
548 const char *filePath,
549 int fd
550){
drhbfe66312006-10-03 17:40:40 +0000551 /* test byte-range lock using fcntl */
552 struct flock lockInfo;
553
554 lockInfo.l_len = 1;
555 lockInfo.l_start = 0;
556 lockInfo.l_whence = SEEK_SET;
557 lockInfo.l_type = F_RDLCK;
558
danielk1977ad94b582007-08-20 06:44:22 +0000559 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
drhbfe66312006-10-03 17:40:40 +0000560 return posixLockingStyle;
561 }
562
563 /* testing for flock can give false positives. So if if the above test
564 ** fails, then we fall back to using dot-lock style locking.
565 */
566 return dotlockLockingStyle;
567}
568
569/*
570** Examines the f_fstypename entry in the statfs structure as returned by
571** stat() for the file system hosting the database file, assigns the
drh85b623f2007-12-13 21:54:09 +0000572** appropriate locking style based on its value. These values and
drhbfe66312006-10-03 17:40:40 +0000573** assignments are based on Darwin/OSX behavior and have not been tested on
574** other systems.
575*/
danielk1977ad94b582007-08-20 06:44:22 +0000576static sqlite3LockingStyle sqlite3DetectLockingStyle(
577 const char *filePath,
578 int fd
579){
drhbfe66312006-10-03 17:40:40 +0000580
581#ifdef SQLITE_FIXED_LOCKING_STYLE
582 return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
583#else
584 struct statfs fsInfo;
585
drh339eb0b2008-03-07 15:34:11 +0000586 if( statfs(filePath, &fsInfo) == -1 ){
drhbfe66312006-10-03 17:40:40 +0000587 return sqlite3TestLockingStyle(filePath, fd);
drh339eb0b2008-03-07 15:34:11 +0000588 }
589 if( fsInfo.f_flags & MNT_RDONLY ){
drhbfe66312006-10-03 17:40:40 +0000590 return noLockingStyle;
drh339eb0b2008-03-07 15:34:11 +0000591 }
592 if( strcmp(fsInfo.f_fstypename, "hfs")==0 ||
593 strcmp(fsInfo.f_fstypename, "ufs")==0 ){
594 return posixLockingStyle;
595 }
596 if( strcmp(fsInfo.f_fstypename, "afpfs")==0 ){
drhbfe66312006-10-03 17:40:40 +0000597 return afpLockingStyle;
drh339eb0b2008-03-07 15:34:11 +0000598 }
599 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
drhbfe66312006-10-03 17:40:40 +0000600 return sqlite3TestLockingStyle(filePath, fd);
drh339eb0b2008-03-07 15:34:11 +0000601 }
602 if( strcmp(fsInfo.f_fstypename, "smbfs")==0 ){
drhbfe66312006-10-03 17:40:40 +0000603 return flockLockingStyle;
drh339eb0b2008-03-07 15:34:11 +0000604 }
605 if( strcmp(fsInfo.f_fstypename, "msdos")==0 ){
drhbfe66312006-10-03 17:40:40 +0000606 return dotlockLockingStyle;
drh339eb0b2008-03-07 15:34:11 +0000607 }
608 if( strcmp(fsInfo.f_fstypename, "webdav")==0 ){
drhbfe66312006-10-03 17:40:40 +0000609 return unsupportedLockingStyle;
drh339eb0b2008-03-07 15:34:11 +0000610 }
drhbfe66312006-10-03 17:40:40 +0000611 return sqlite3TestLockingStyle(filePath, fd);
drh3b62b2f2007-06-08 18:27:03 +0000612#endif /* SQLITE_FIXED_LOCKING_STYLE */
drhbfe66312006-10-03 17:40:40 +0000613}
614
615#endif /* SQLITE_ENABLE_LOCKING_STYLE */
616
drhbbd42a62004-05-22 17:41:58 +0000617/*
618** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000619** describes that file descriptor. Create new ones if necessary. The
620** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000621**
drh65594042008-05-05 16:56:34 +0000622** Return an appropriate error code.
drhbbd42a62004-05-22 17:41:58 +0000623*/
drh38f82712004-06-18 17:10:16 +0000624static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000625 int fd, /* The file descriptor used in the key */
626 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000627 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000628){
629 int rc;
630 struct lockKey key1;
631 struct openKey key2;
632 struct stat statbuf;
633 struct lockInfo *pLock;
634 struct openCnt *pOpen;
635 rc = fstat(fd, &statbuf);
drh65594042008-05-05 16:56:34 +0000636 if( rc!=0 ){
637#ifdef EOVERFLOW
638 if( errno==EOVERFLOW ) return SQLITE_NOLFS;
639#endif
640 return SQLITE_IOERR;
641 }
danielk1977441b09a2006-01-05 13:48:29 +0000642
drhbbd42a62004-05-22 17:41:58 +0000643 memset(&key1, 0, sizeof(key1));
644 key1.dev = statbuf.st_dev;
645 key1.ino = statbuf.st_ino;
drhd677b3d2007-08-20 22:48:41 +0000646#if SQLITE_THREADSAFE
drh5fdae772004-06-29 03:29:00 +0000647 if( threadsOverrideEachOthersLocks<0 ){
648 testThreadLockingBehavior(fd);
649 }
650 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
651#endif
drhbbd42a62004-05-22 17:41:58 +0000652 memset(&key2, 0, sizeof(key2));
653 key2.dev = statbuf.st_dev;
654 key2.ino = statbuf.st_ino;
655 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
656 if( pLock==0 ){
657 struct lockInfo *pOld;
drh17435752007-08-16 04:30:38 +0000658 pLock = sqlite3_malloc( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000659 if( pLock==0 ){
drh65594042008-05-05 16:56:34 +0000660 rc = SQLITE_NOMEM;
danielk1977441b09a2006-01-05 13:48:29 +0000661 goto exit_findlockinfo;
662 }
drhbbd42a62004-05-22 17:41:58 +0000663 pLock->key = key1;
664 pLock->nRef = 1;
665 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000666 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000667 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
668 if( pOld!=0 ){
669 assert( pOld==pLock );
drh17435752007-08-16 04:30:38 +0000670 sqlite3_free(pLock);
drh65594042008-05-05 16:56:34 +0000671 rc = SQLITE_NOMEM;
danielk1977441b09a2006-01-05 13:48:29 +0000672 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000673 }
674 }else{
675 pLock->nRef++;
676 }
677 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000678 if( ppOpen!=0 ){
679 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
drhbbd42a62004-05-22 17:41:58 +0000680 if( pOpen==0 ){
drh029b44b2006-01-15 00:13:15 +0000681 struct openCnt *pOld;
drh17435752007-08-16 04:30:38 +0000682 pOpen = sqlite3_malloc( sizeof(*pOpen) );
drh029b44b2006-01-15 00:13:15 +0000683 if( pOpen==0 ){
684 releaseLockInfo(pLock);
drh65594042008-05-05 16:56:34 +0000685 rc = SQLITE_NOMEM;
drh029b44b2006-01-15 00:13:15 +0000686 goto exit_findlockinfo;
687 }
688 pOpen->key = key2;
689 pOpen->nRef = 1;
690 pOpen->nLock = 0;
691 pOpen->nPending = 0;
692 pOpen->aPending = 0;
693 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
694 if( pOld!=0 ){
695 assert( pOld==pOpen );
drh17435752007-08-16 04:30:38 +0000696 sqlite3_free(pOpen);
drh029b44b2006-01-15 00:13:15 +0000697 releaseLockInfo(pLock);
drh65594042008-05-05 16:56:34 +0000698 rc = SQLITE_NOMEM;
drh029b44b2006-01-15 00:13:15 +0000699 goto exit_findlockinfo;
700 }
701 }else{
702 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000703 }
drh029b44b2006-01-15 00:13:15 +0000704 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000705 }
danielk1977441b09a2006-01-05 13:48:29 +0000706
707exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000708 return rc;
drhbbd42a62004-05-22 17:41:58 +0000709}
710
drh64b1bea2006-01-15 02:30:57 +0000711#ifdef SQLITE_DEBUG
712/*
713** Helper function for printing out trace information from debugging
714** binaries. This returns the string represetation of the supplied
715** integer lock-type.
716*/
717static const char *locktypeName(int locktype){
718 switch( locktype ){
719 case NO_LOCK: return "NONE";
720 case SHARED_LOCK: return "SHARED";
721 case RESERVED_LOCK: return "RESERVED";
722 case PENDING_LOCK: return "PENDING";
723 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
724 }
725 return "ERROR";
726}
727#endif
728
drhbbd42a62004-05-22 17:41:58 +0000729/*
drh029b44b2006-01-15 00:13:15 +0000730** If we are currently in a different thread than the thread that the
731** unixFile argument belongs to, then transfer ownership of the unixFile
732** over to the current thread.
733**
734** A unixFile is only owned by a thread on systems where one thread is
735** unable to override locks created by a different thread. RedHat9 is
736** an example of such a system.
737**
738** Ownership transfer is only allowed if the unixFile is currently unlocked.
739** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000740** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000741*/
drhd677b3d2007-08-20 22:48:41 +0000742#if SQLITE_THREADSAFE
drh029b44b2006-01-15 00:13:15 +0000743static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000744 int rc;
drh029b44b2006-01-15 00:13:15 +0000745 pthread_t hSelf;
746 if( threadsOverrideEachOthersLocks ){
747 /* Ownership transfers not needed on this system */
748 return SQLITE_OK;
749 }
750 hSelf = pthread_self();
751 if( pthread_equal(pFile->tid, hSelf) ){
752 /* We are still in the same thread */
drh4f0c5872007-03-26 22:05:01 +0000753 OSTRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000754 return SQLITE_OK;
755 }
756 if( pFile->locktype!=NO_LOCK ){
757 /* We cannot change ownership while we are holding a lock! */
758 return SQLITE_MISUSE;
759 }
drh4f0c5872007-03-26 22:05:01 +0000760 OSTRACE4("Transfer ownership of %d from %d to %d\n",
761 pFile->h, pFile->tid, hSelf);
drh029b44b2006-01-15 00:13:15 +0000762 pFile->tid = hSelf;
drhbfe66312006-10-03 17:40:40 +0000763 if (pFile->pLock != NULL) {
764 releaseLockInfo(pFile->pLock);
765 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
drh4f0c5872007-03-26 22:05:01 +0000766 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +0000767 locktypeName(pFile->locktype),
768 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
769 return rc;
770 } else {
771 return SQLITE_OK;
772 }
drh029b44b2006-01-15 00:13:15 +0000773}
774#else
drhf1a221e2006-01-15 17:27:17 +0000775 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +0000776# define transferOwnership(X) SQLITE_OK
777#endif
778
779/*
danielk19772a6bdf62007-08-20 16:07:00 +0000780** Seek to the offset passed as the second argument, then read cnt
781** bytes into pBuf. Return the number of bytes actually read.
drh9e0ebbf2007-10-23 15:59:18 +0000782**
783** NB: If you define USE_PREAD or USE_PREAD64, then it might also
784** be necessary to define _XOPEN_SOURCE to be 500. This varies from
785** one system to another. Since SQLite does not define USE_PREAD
786** any any form by default, we will not attempt to define _XOPEN_SOURCE.
787** See tickets #2741 and #2681.
drhb912b282006-03-23 22:42:20 +0000788*/
danielk197762079062007-08-15 17:08:46 +0000789static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +0000790 int got;
drh8ebf6702007-02-06 11:11:08 +0000791 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +0000792 TIMER_START;
drh8350a212007-03-22 15:22:06 +0000793#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +0000794 got = pread(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +0000795 SimulateIOError( got = -1 );
drh8350a212007-03-22 15:22:06 +0000796#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +0000797 got = pread64(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +0000798 SimulateIOError( got = -1 );
drhb912b282006-03-23 22:42:20 +0000799#else
danielk197762079062007-08-15 17:08:46 +0000800 newOffset = lseek(id->h, offset, SEEK_SET);
drhbb5f18d2007-04-06 18:23:17 +0000801 SimulateIOError( newOffset-- );
danielk197762079062007-08-15 17:08:46 +0000802 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +0000803 return -1;
804 }
drhb912b282006-03-23 22:42:20 +0000805 got = read(id->h, pBuf, cnt);
806#endif
drh15d00c42007-02-27 02:01:14 +0000807 TIMER_END;
shane9bcbdad2008-05-29 20:22:37 +0000808 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +0000809 return got;
810}
811
812/*
drhbbd42a62004-05-22 17:41:58 +0000813** Read data from a file into a buffer. Return SQLITE_OK if all
814** bytes were read successfully and SQLITE_IOERR if anything goes
815** wrong.
816*/
danielk197762079062007-08-15 17:08:46 +0000817static int unixRead(
818 sqlite3_file *id,
819 void *pBuf,
820 int amt,
821 sqlite3_int64 offset
822){
drhbbd42a62004-05-22 17:41:58 +0000823 int got;
drh9cbe6352005-11-29 03:13:21 +0000824 assert( id );
danielk197762079062007-08-15 17:08:46 +0000825 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000826 if( got==amt ){
827 return SQLITE_OK;
drh4ac285a2006-09-15 07:28:50 +0000828 }else if( got<0 ){
829 return SQLITE_IOERR_READ;
drhbbd42a62004-05-22 17:41:58 +0000830 }else{
drhbafda092007-01-03 23:36:22 +0000831 memset(&((char*)pBuf)[got], 0, amt-got);
drh4ac285a2006-09-15 07:28:50 +0000832 return SQLITE_IOERR_SHORT_READ;
drhbbd42a62004-05-22 17:41:58 +0000833 }
834}
835
836/*
drhb912b282006-03-23 22:42:20 +0000837** Seek to the offset in id->offset then read cnt bytes into pBuf.
838** Return the number of bytes actually read. Update the offset.
839*/
danielk197762079062007-08-15 17:08:46 +0000840static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +0000841 int got;
drh8ebf6702007-02-06 11:11:08 +0000842 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +0000843 TIMER_START;
drh8350a212007-03-22 15:22:06 +0000844#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +0000845 got = pwrite(id->h, pBuf, cnt, offset);
drh8350a212007-03-22 15:22:06 +0000846#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +0000847 got = pwrite64(id->h, pBuf, cnt, offset);
drhb912b282006-03-23 22:42:20 +0000848#else
danielk197762079062007-08-15 17:08:46 +0000849 newOffset = lseek(id->h, offset, SEEK_SET);
850 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +0000851 return -1;
852 }
drhb912b282006-03-23 22:42:20 +0000853 got = write(id->h, pBuf, cnt);
854#endif
drh15d00c42007-02-27 02:01:14 +0000855 TIMER_END;
shane9bcbdad2008-05-29 20:22:37 +0000856 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +0000857 return got;
858}
859
860
861/*
drhbbd42a62004-05-22 17:41:58 +0000862** Write data from a buffer into a file. Return SQLITE_OK on success
863** or some other error code on failure.
864*/
danielk197762079062007-08-15 17:08:46 +0000865static int unixWrite(
866 sqlite3_file *id,
867 const void *pBuf,
868 int amt,
869 sqlite3_int64 offset
870){
drhbbd42a62004-05-22 17:41:58 +0000871 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000872 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000873 assert( amt>0 );
danielk197762079062007-08-15 17:08:46 +0000874 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000875 amt -= wrote;
danielk197762079062007-08-15 17:08:46 +0000876 offset += wrote;
drhbbd42a62004-05-22 17:41:58 +0000877 pBuf = &((char*)pBuf)[wrote];
878 }
drh59685932006-09-14 13:47:11 +0000879 SimulateIOError(( wrote=(-1), amt=1 ));
880 SimulateDiskfullError(( wrote=0, amt=1 ));
drhbbd42a62004-05-22 17:41:58 +0000881 if( amt>0 ){
drh59685932006-09-14 13:47:11 +0000882 if( wrote<0 ){
drh4ac285a2006-09-15 07:28:50 +0000883 return SQLITE_IOERR_WRITE;
drh59685932006-09-14 13:47:11 +0000884 }else{
885 return SQLITE_FULL;
886 }
drhbbd42a62004-05-22 17:41:58 +0000887 }
888 return SQLITE_OK;
889}
890
drhb851b2c2005-03-10 14:11:12 +0000891#ifdef SQLITE_TEST
892/*
893** Count the number of fullsyncs and normal syncs. This is used to test
894** that syncs and fullsyncs are occuring at the right times.
895*/
896int sqlite3_sync_count = 0;
897int sqlite3_fullsync_count = 0;
898#endif
899
drhf2f23912005-10-05 10:29:36 +0000900/*
901** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
902** Otherwise use fsync() in its place.
903*/
904#ifndef HAVE_FDATASYNC
905# define fdatasync fsync
906#endif
907
drhac530b12006-02-11 01:25:50 +0000908/*
909** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
910** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
911** only available on Mac OS X. But that could change.
912*/
913#ifdef F_FULLFSYNC
914# define HAVE_FULLFSYNC 1
915#else
916# define HAVE_FULLFSYNC 0
917#endif
918
drhb851b2c2005-03-10 14:11:12 +0000919
drhbbd42a62004-05-22 17:41:58 +0000920/*
drhdd809b02004-07-17 21:44:57 +0000921** The fsync() system call does not work as advertised on many
922** unix systems. The following procedure is an attempt to make
923** it work better.
drh1398ad32005-01-19 23:24:50 +0000924**
925** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
926** for testing when we want to run through the test suite quickly.
927** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
928** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
929** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000930*/
drheb796a72005-09-08 12:38:41 +0000931static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +0000932 int rc;
drhb851b2c2005-03-10 14:11:12 +0000933
934 /* Record the number of times that we do a normal fsync() and
935 ** FULLSYNC. This is used during testing to verify that this procedure
936 ** gets called with the correct arguments.
937 */
938#ifdef SQLITE_TEST
939 if( fullSync ) sqlite3_fullsync_count++;
940 sqlite3_sync_count++;
941#endif
942
943 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
944 ** no-op
945 */
946#ifdef SQLITE_NO_SYNC
947 rc = SQLITE_OK;
948#else
949
drhac530b12006-02-11 01:25:50 +0000950#if HAVE_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +0000951 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +0000952 rc = fcntl(fd, F_FULLFSYNC, 0);
aswiftae0943b2007-01-31 23:37:07 +0000953 }else{
954 rc = 1;
955 }
956 /* If the FULLFSYNC failed, fall back to attempting an fsync().
957 * It shouldn't be possible for fullfsync to fail on the local
958 * file system (on OSX), so failure indicates that FULLFSYNC
959 * isn't supported for this file system. So, attempt an fsync
960 * and (for now) ignore the overhead of a superfluous fcntl call.
961 * It'd be better to detect fullfsync support once and avoid
962 * the fcntl call every time sync is called.
963 */
964 if( rc ) rc = fsync(fd);
965
966#else
drheb796a72005-09-08 12:38:41 +0000967 if( dataOnly ){
968 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +0000969 }else{
drheb796a72005-09-08 12:38:41 +0000970 rc = fsync(fd);
971 }
aswiftae0943b2007-01-31 23:37:07 +0000972#endif /* HAVE_FULLFSYNC */
drhb851b2c2005-03-10 14:11:12 +0000973#endif /* defined(SQLITE_NO_SYNC) */
974
drhdd809b02004-07-17 21:44:57 +0000975 return rc;
976}
977
978/*
drhbbd42a62004-05-22 17:41:58 +0000979** Make sure all writes to a particular file are committed to disk.
980**
drheb796a72005-09-08 12:38:41 +0000981** If dataOnly==0 then both the file itself and its metadata (file
982** size, access time, etc) are synced. If dataOnly!=0 then only the
983** file data is synced.
984**
drhbbd42a62004-05-22 17:41:58 +0000985** Under Unix, also make sure that the directory entry for the file
986** has been created by fsync-ing the directory that contains the file.
987** If we do not do this and we encounter a power failure, the directory
988** entry for the journal might not exist after we reboot. The next
989** SQLite to access the file will not know that the journal exists (because
990** the directory entry for the journal was never created) and the transaction
991** will not roll back - possibly leading to database corruption.
992*/
danielk197790949c22007-08-17 16:50:38 +0000993static int unixSync(sqlite3_file *id, int flags){
drh59685932006-09-14 13:47:11 +0000994 int rc;
drh054889e2005-11-30 03:20:31 +0000995 unixFile *pFile = (unixFile*)id;
danielk197790949c22007-08-17 16:50:38 +0000996
danielk1977f036aef2007-08-20 05:36:51 +0000997 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
998 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
999
danielk1977c16d4632007-08-30 14:49:58 +00001000 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
danielk1977f036aef2007-08-20 05:36:51 +00001001 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
1002 || (flags&0x0F)==SQLITE_SYNC_FULL
danielk1977f036aef2007-08-20 05:36:51 +00001003 );
danielk197790949c22007-08-17 16:50:38 +00001004
drh054889e2005-11-30 03:20:31 +00001005 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001006 OSTRACE2("SYNC %-3d\n", pFile->h);
danielk197790949c22007-08-17 16:50:38 +00001007 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
drh59685932006-09-14 13:47:11 +00001008 SimulateIOError( rc=1 );
1009 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001010 return SQLITE_IOERR_FSYNC;
drhbbd42a62004-05-22 17:41:58 +00001011 }
drh054889e2005-11-30 03:20:31 +00001012 if( pFile->dirfd>=0 ){
drh4f0c5872007-03-26 22:05:01 +00001013 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
danielk197790949c22007-08-17 16:50:38 +00001014 HAVE_FULLFSYNC, isFullsync);
danielk1977d7c03f72005-11-25 10:38:22 +00001015#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001016 /* The directory sync is only attempted if full_fsync is
1017 ** turned off or unavailable. If a full_fsync occurred above,
1018 ** then the directory sync is superfluous.
1019 */
danielk197790949c22007-08-17 16:50:38 +00001020 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
drhac530b12006-02-11 01:25:50 +00001021 /*
1022 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001023 ** errors when applied to directories on certain file systems.
1024 ** A failed directory sync is not a big deal. So it seems
1025 ** better to ignore the error. Ticket #1657
1026 */
1027 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001028 }
danielk1977d7c03f72005-11-25 10:38:22 +00001029#endif
drh054889e2005-11-30 03:20:31 +00001030 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1031 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001032 }
drha2854222004-06-17 19:04:17 +00001033 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001034}
1035
1036/*
1037** Truncate an open file to a specified size
1038*/
danielk197762079062007-08-15 17:08:46 +00001039static int unixTruncate(sqlite3_file *id, i64 nByte){
drh59685932006-09-14 13:47:11 +00001040 int rc;
drh9cbe6352005-11-29 03:13:21 +00001041 assert( id );
drh93aed5a2008-01-16 17:46:38 +00001042 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
drh63fff5f2007-06-19 10:50:38 +00001043 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
drh59685932006-09-14 13:47:11 +00001044 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001045 return SQLITE_IOERR_TRUNCATE;
drh59685932006-09-14 13:47:11 +00001046 }else{
1047 return SQLITE_OK;
1048 }
drhbbd42a62004-05-22 17:41:58 +00001049}
1050
1051/*
1052** Determine the current size of a file in bytes
1053*/
danielk197762079062007-08-15 17:08:46 +00001054static int unixFileSize(sqlite3_file *id, i64 *pSize){
drh59685932006-09-14 13:47:11 +00001055 int rc;
drhbbd42a62004-05-22 17:41:58 +00001056 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001057 assert( id );
drh59685932006-09-14 13:47:11 +00001058 rc = fstat(((unixFile*)id)->h, &buf);
1059 SimulateIOError( rc=1 );
1060 if( rc!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001061 return SQLITE_IOERR_FSTAT;
drhbbd42a62004-05-22 17:41:58 +00001062 }
1063 *pSize = buf.st_size;
1064 return SQLITE_OK;
1065}
1066
danielk19779a1d0ab2004-06-01 14:09:28 +00001067/*
danielk197713adf8a2004-06-03 16:08:41 +00001068** This routine checks if there is a RESERVED lock held on the specified
1069** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001070** non-zero. If the file is unlocked or holds only SHARED locks, then
1071** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001072*/
danielk1977861f7452008-06-05 11:39:11 +00001073static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
danielk197713adf8a2004-06-03 16:08:41 +00001074 int r = 0;
drh054889e2005-11-30 03:20:31 +00001075 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001076
danielk1977861f7452008-06-05 11:39:11 +00001077 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1078
drh054889e2005-11-30 03:20:31 +00001079 assert( pFile );
danielk1977b4b47412007-08-17 15:53:36 +00001080 enterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001081
1082 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001083 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001084 r = 1;
1085 }
1086
drh2ac3ee92004-06-07 16:27:46 +00001087 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001088 */
1089 if( !r ){
1090 struct flock lock;
1091 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001092 lock.l_start = RESERVED_BYTE;
1093 lock.l_len = 1;
1094 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001095 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001096 if( lock.l_type!=F_UNLCK ){
1097 r = 1;
1098 }
1099 }
1100
danielk1977b4b47412007-08-17 15:53:36 +00001101 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001102 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001103
danielk1977861f7452008-06-05 11:39:11 +00001104 *pResOut = r;
1105 return SQLITE_OK;
danielk197713adf8a2004-06-03 16:08:41 +00001106}
1107
1108/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001109** Lock the file with the lock specified by parameter locktype - one
1110** of the following:
1111**
drh2ac3ee92004-06-07 16:27:46 +00001112** (1) SHARED_LOCK
1113** (2) RESERVED_LOCK
1114** (3) PENDING_LOCK
1115** (4) EXCLUSIVE_LOCK
1116**
drhb3e04342004-06-08 00:47:47 +00001117** Sometimes when requesting one lock state, additional lock states
1118** are inserted in between. The locking might fail on one of the later
1119** transitions leaving the lock state different from what it started but
1120** still short of its goal. The following chart shows the allowed
1121** transitions and the inserted intermediate states:
1122**
1123** UNLOCKED -> SHARED
1124** SHARED -> RESERVED
1125** SHARED -> (PENDING) -> EXCLUSIVE
1126** RESERVED -> (PENDING) -> EXCLUSIVE
1127** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001128**
drha6abd042004-06-09 17:37:22 +00001129** This routine will only increase a lock. Use the sqlite3OsUnlock()
1130** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001131*/
danielk197762079062007-08-15 17:08:46 +00001132static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001133 /* The following describes the implementation of the various locks and
1134 ** lock transitions in terms of the POSIX advisory shared and exclusive
1135 ** lock primitives (called read-locks and write-locks below, to avoid
1136 ** confusion with SQLite lock names). The algorithms are complicated
1137 ** slightly in order to be compatible with windows systems simultaneously
1138 ** accessing the same database file, in case that is ever required.
1139 **
1140 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1141 ** byte', each single bytes at well known offsets, and the 'shared byte
1142 ** range', a range of 510 bytes at a well known offset.
1143 **
1144 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1145 ** byte'. If this is successful, a random byte from the 'shared byte
1146 ** range' is read-locked and the lock on the 'pending byte' released.
1147 **
danielk197790ba3bd2004-06-25 08:32:25 +00001148 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1149 ** A RESERVED lock is implemented by grabbing a write-lock on the
1150 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001151 **
1152 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001153 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1154 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1155 ** obtained, but existing SHARED locks are allowed to persist. A process
1156 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1157 ** This property is used by the algorithm for rolling back a journal file
1158 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001159 **
danielk197790ba3bd2004-06-25 08:32:25 +00001160 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1161 ** implemented by obtaining a write-lock on the entire 'shared byte
1162 ** range'. Since all other locks require a read-lock on one of the bytes
1163 ** within this range, this ensures that no other locks are held on the
1164 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001165 **
1166 ** The reason a single byte cannot be used instead of the 'shared byte
1167 ** range' is that some versions of windows do not support read-locks. By
1168 ** locking a random byte from a range, concurrent SHARED locks may exist
1169 ** even if the locking primitive used is always a write-lock.
1170 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001171 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001172 unixFile *pFile = (unixFile*)id;
1173 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001174 struct flock lock;
1175 int s;
1176
drh054889e2005-11-30 03:20:31 +00001177 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001178 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001179 locktypeName(locktype), locktypeName(pFile->locktype),
1180 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001181
1182 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001183 ** unixFile, do nothing. Don't use the end_lock: exit path, as
danielk1977b4b47412007-08-17 15:53:36 +00001184 ** enterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001185 */
drh054889e2005-11-30 03:20:31 +00001186 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001187 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001188 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001189 return SQLITE_OK;
1190 }
1191
drhb3e04342004-06-08 00:47:47 +00001192 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001193 */
drh054889e2005-11-30 03:20:31 +00001194 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001195 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001196 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001197
drh054889e2005-11-30 03:20:31 +00001198 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001199 */
danielk1977b4b47412007-08-17 15:53:36 +00001200 enterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001201
drh029b44b2006-01-15 00:13:15 +00001202 /* Make sure the current thread owns the pFile.
1203 */
1204 rc = transferOwnership(pFile);
1205 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001206 leaveMutex();
drh029b44b2006-01-15 00:13:15 +00001207 return rc;
1208 }
drh64b1bea2006-01-15 02:30:57 +00001209 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001210
danielk1977ad94b582007-08-20 06:44:22 +00001211 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001212 ** handle that precludes the requested lock, return BUSY.
1213 */
drh054889e2005-11-30 03:20:31 +00001214 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001215 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001216 ){
1217 rc = SQLITE_BUSY;
1218 goto end_lock;
1219 }
1220
1221 /* If a SHARED lock is requested, and some thread using this PID already
1222 ** has a SHARED or RESERVED lock, then increment reference counts and
1223 ** return SQLITE_OK.
1224 */
1225 if( locktype==SHARED_LOCK &&
1226 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1227 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001228 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001229 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001230 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001231 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001232 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001233 goto end_lock;
1234 }
1235
danielk197713adf8a2004-06-03 16:08:41 +00001236 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001237
danielk19779a1d0ab2004-06-01 14:09:28 +00001238 lock.l_whence = SEEK_SET;
1239
drh3cde3bb2004-06-12 02:17:14 +00001240 /* A PENDING lock is needed before acquiring a SHARED lock and before
1241 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1242 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001243 */
drh3cde3bb2004-06-12 02:17:14 +00001244 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001245 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001246 ){
danielk1977489468c2004-06-28 08:25:47 +00001247 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001248 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001249 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001250 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001251 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1252 goto end_lock;
1253 }
drh3cde3bb2004-06-12 02:17:14 +00001254 }
1255
1256
1257 /* If control gets to this point, then actually go ahead and make
1258 ** operating system calls for the specified lock.
1259 */
1260 if( locktype==SHARED_LOCK ){
1261 assert( pLock->cnt==0 );
1262 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001263
drh2ac3ee92004-06-07 16:27:46 +00001264 /* Now get the read-lock */
1265 lock.l_start = SHARED_FIRST;
1266 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001267 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001268
1269 /* 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 ){
drh4ac285a2006-09-15 07:28:50 +00001274 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001275 goto end_lock;
1276 }
drhe2396a12007-03-29 20:19:58 +00001277 if( s==(-1) ){
drhbbd42a62004-05-22 17:41:58 +00001278 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1279 }else{
drh054889e2005-11-30 03:20:31 +00001280 pFile->locktype = SHARED_LOCK;
1281 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001282 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001283 }
drh3cde3bb2004-06-12 02:17:14 +00001284 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1285 /* We are trying for an exclusive lock but another thread in this
1286 ** same process is still holding a shared lock. */
1287 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001288 }else{
drh3cde3bb2004-06-12 02:17:14 +00001289 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001290 ** assumed that there is a SHARED or greater lock on the file
1291 ** already.
1292 */
drh054889e2005-11-30 03:20:31 +00001293 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001294 lock.l_type = F_WRLCK;
1295 switch( locktype ){
1296 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001297 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001298 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001299 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001300 lock.l_start = SHARED_FIRST;
1301 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001302 break;
1303 default:
1304 assert(0);
1305 }
drh054889e2005-11-30 03:20:31 +00001306 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001307 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001308 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1309 }
drhbbd42a62004-05-22 17:41:58 +00001310 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001311
danielk1977ecb2a962004-06-02 06:30:16 +00001312 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001313 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001314 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001315 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001316 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001317 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001318 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001319
1320end_lock:
danielk1977b4b47412007-08-17 15:53:36 +00001321 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001322 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001323 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001324 return rc;
1325}
1326
1327/*
drh054889e2005-11-30 03:20:31 +00001328** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001329** must be either NO_LOCK or SHARED_LOCK.
1330**
1331** If the locking level of the file descriptor is already at or below
1332** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001333*/
danielk197762079062007-08-15 17:08:46 +00001334static int unixUnlock(sqlite3_file *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001335 struct lockInfo *pLock;
1336 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001337 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001338 unixFile *pFile = (unixFile*)id;
drh1aa5af12008-03-07 19:51:14 +00001339 int h;
drha6abd042004-06-09 17:37:22 +00001340
drh054889e2005-11-30 03:20:31 +00001341 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001342 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001343 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001344
1345 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001346 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001347 return SQLITE_OK;
1348 }
drhf1a221e2006-01-15 17:27:17 +00001349 if( CHECK_THREADID(pFile) ){
1350 return SQLITE_MISUSE;
1351 }
danielk1977b4b47412007-08-17 15:53:36 +00001352 enterMutex();
drh1aa5af12008-03-07 19:51:14 +00001353 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001354 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001355 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001356 if( pFile->locktype>SHARED_LOCK ){
1357 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001358 SimulateIOErrorBenign(1);
1359 SimulateIOError( h=(-1) )
1360 SimulateIOErrorBenign(0);
drh9c105bb2004-10-02 20:38:28 +00001361 if( locktype==SHARED_LOCK ){
1362 lock.l_type = F_RDLCK;
1363 lock.l_whence = SEEK_SET;
1364 lock.l_start = SHARED_FIRST;
1365 lock.l_len = SHARED_SIZE;
drh1aa5af12008-03-07 19:51:14 +00001366 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drh4ac285a2006-09-15 07:28:50 +00001367 rc = SQLITE_IOERR_RDLOCK;
drh9c105bb2004-10-02 20:38:28 +00001368 }
1369 }
drhbbd42a62004-05-22 17:41:58 +00001370 lock.l_type = F_UNLCK;
1371 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001372 lock.l_start = PENDING_BYTE;
1373 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001374 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001375 pLock->locktype = SHARED_LOCK;
1376 }else{
drh1aa5af12008-03-07 19:51:14 +00001377 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001378 }
drhbbd42a62004-05-22 17:41:58 +00001379 }
drha6abd042004-06-09 17:37:22 +00001380 if( locktype==NO_LOCK ){
1381 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001382
drha6abd042004-06-09 17:37:22 +00001383 /* Decrement the shared lock counter. Release the lock using an
1384 ** OS call only when all threads in this same process have released
1385 ** the lock.
1386 */
1387 pLock->cnt--;
1388 if( pLock->cnt==0 ){
1389 lock.l_type = F_UNLCK;
1390 lock.l_whence = SEEK_SET;
1391 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001392 SimulateIOErrorBenign(1);
1393 SimulateIOError( h=(-1) )
1394 SimulateIOErrorBenign(0);
1395 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001396 pLock->locktype = NO_LOCK;
1397 }else{
drh1aa5af12008-03-07 19:51:14 +00001398 rc = SQLITE_IOERR_UNLOCK;
1399 pLock->cnt = 1;
drh2b4b5962005-06-15 17:47:55 +00001400 }
drha6abd042004-06-09 17:37:22 +00001401 }
1402
drhbbd42a62004-05-22 17:41:58 +00001403 /* Decrement the count of locks against this same file. When the
1404 ** count reaches zero, close any other file descriptors whose close
1405 ** was deferred because of outstanding locks.
1406 */
drh1aa5af12008-03-07 19:51:14 +00001407 if( rc==SQLITE_OK ){
1408 pOpen = pFile->pOpen;
1409 pOpen->nLock--;
1410 assert( pOpen->nLock>=0 );
1411 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1412 int i;
1413 for(i=0; i<pOpen->nPending; i++){
1414 close(pOpen->aPending[i]);
1415 }
1416 free(pOpen->aPending);
1417 pOpen->nPending = 0;
1418 pOpen->aPending = 0;
drhbbd42a62004-05-22 17:41:58 +00001419 }
drhbbd42a62004-05-22 17:41:58 +00001420 }
1421 }
danielk1977b4b47412007-08-17 15:53:36 +00001422 leaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001423 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001424 return rc;
drhbbd42a62004-05-22 17:41:58 +00001425}
1426
1427/*
danielk1977e3026632004-06-22 11:29:02 +00001428** Close a file.
1429*/
danielk197762079062007-08-15 17:08:46 +00001430static int unixClose(sqlite3_file *id){
1431 unixFile *pFile = (unixFile *)id;
1432 if( !pFile ) return SQLITE_OK;
1433 unixUnlock(id, NO_LOCK);
1434 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1435 pFile->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00001436 enterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001437
danielk197762079062007-08-15 17:08:46 +00001438 if( pFile->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001439 /* If there are outstanding locks, do not actually close the file just
1440 ** yet because that would clear those locks. Instead, add the file
1441 ** descriptor to pOpen->aPending. It will be automatically closed when
1442 ** the last lock is cleared.
1443 */
1444 int *aNew;
danielk197762079062007-08-15 17:08:46 +00001445 struct openCnt *pOpen = pFile->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001446 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001447 if( aNew==0 ){
1448 /* If a malloc fails, just leak the file descriptor */
1449 }else{
1450 pOpen->aPending = aNew;
danielk197762079062007-08-15 17:08:46 +00001451 pOpen->aPending[pOpen->nPending] = pFile->h;
drhad81e872005-08-21 21:45:01 +00001452 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001453 }
1454 }else{
1455 /* There are no outstanding locks so we can close the file immediately */
danielk197762079062007-08-15 17:08:46 +00001456 close(pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001457 }
danielk197762079062007-08-15 17:08:46 +00001458 releaseLockInfo(pFile->pLock);
1459 releaseOpenCnt(pFile->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001460
danielk1977b4b47412007-08-17 15:53:36 +00001461 leaveMutex();
danielk197762079062007-08-15 17:08:46 +00001462 OSTRACE2("CLOSE %-3d\n", pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001463 OpenCounter(-1);
danielk1977b4b47412007-08-17 15:53:36 +00001464 memset(pFile, 0, sizeof(unixFile));
drh02afc862006-01-20 18:10:57 +00001465 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001466}
1467
drhbfe66312006-10-03 17:40:40 +00001468
1469#ifdef SQLITE_ENABLE_LOCKING_STYLE
1470#pragma mark AFP Support
1471
1472/*
1473 ** The afpLockingContext structure contains all afp lock specific state
1474 */
1475typedef struct afpLockingContext afpLockingContext;
1476struct afpLockingContext {
drh1aa5af12008-03-07 19:51:14 +00001477 unsigned long long sharedLockByte;
drh308aa322008-03-07 20:14:38 +00001478 const char *filePath;
drhbfe66312006-10-03 17:40:40 +00001479};
1480
1481struct ByteRangeLockPB2
1482{
1483 unsigned long long offset; /* offset to first byte to lock */
1484 unsigned long long length; /* nbr of bytes to lock */
1485 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
1486 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
1487 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
1488 int fd; /* file desc to assoc this lock with */
1489};
1490
drhfd131da2007-08-07 17:13:03 +00001491#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00001492
danielk1977ad94b582007-08-20 06:44:22 +00001493/*
1494** Return 0 on success, 1 on failure. To match the behavior of the
1495** normal posix file locking (used in unixLock for example), we should
1496** provide 'richer' return codes - specifically to differentiate between
1497** 'file busy' and 'file system error' results.
1498*/
1499static int _AFPFSSetLock(
1500 const char *path,
1501 int fd,
1502 unsigned long long offset,
1503 unsigned long long length,
1504 int setLockFlag
1505){
drhfd131da2007-08-07 17:13:03 +00001506 struct ByteRangeLockPB2 pb;
drhbfe66312006-10-03 17:40:40 +00001507 int err;
1508
1509 pb.unLockFlag = setLockFlag ? 0 : 1;
1510 pb.startEndFlag = 0;
1511 pb.offset = offset;
1512 pb.length = length;
1513 pb.fd = fd;
drh4f0c5872007-03-26 22:05:01 +00001514 OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
drhbfe66312006-10-03 17:40:40 +00001515 (setLockFlag?"ON":"OFF"), fd, offset, length);
1516 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
1517 if ( err==-1 ) {
drh4f0c5872007-03-26 22:05:01 +00001518 OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno,
drhbfe66312006-10-03 17:40:40 +00001519 strerror(errno));
drh3b62b2f2007-06-08 18:27:03 +00001520 return 1; /* error */
drhbfe66312006-10-03 17:40:40 +00001521 } else {
1522 return 0;
1523 }
1524}
1525
1526/*
1527 ** This routine checks if there is a RESERVED lock held on the specified
1528 ** file by this or any other process. If such a lock is held, return
1529 ** non-zero. If the file is unlocked or holds only SHARED locks, then
1530 ** return zero.
1531 */
danielk1977861f7452008-06-05 11:39:11 +00001532static int afpUnixCheckReservedLock(sqlite3_file *id, int *pResOut){
drhbfe66312006-10-03 17:40:40 +00001533 int r = 0;
1534 unixFile *pFile = (unixFile*)id;
1535
1536 assert( pFile );
1537 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1538
1539 /* Check if a thread in this process holds such a lock */
1540 if( pFile->locktype>SHARED_LOCK ){
1541 r = 1;
1542 }
1543
1544 /* Otherwise see if some other process holds it.
1545 */
1546 if ( !r ) {
drh3b62b2f2007-06-08 18:27:03 +00001547 /* lock the byte */
drhbfe66312006-10-03 17:40:40 +00001548 int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1549 if (failed) {
1550 /* if we failed to get the lock then someone else must have it */
1551 r = 1;
1552 } else {
1553 /* if we succeeded in taking the reserved lock, unlock it to restore
1554 ** the original state */
1555 _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
1556 }
1557 }
drh4f0c5872007-03-26 22:05:01 +00001558 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
drhbfe66312006-10-03 17:40:40 +00001559
danielk1977861f7452008-06-05 11:39:11 +00001560 *pResOut = r;
1561 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001562}
1563
1564/* AFP-style locking following the behavior of unixLock, see the unixLock
1565** function comments for details of lock management. */
drh339eb0b2008-03-07 15:34:11 +00001566static int afpUnixLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00001567 int rc = SQLITE_OK;
1568 unixFile *pFile = (unixFile*)id;
1569 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1570 int gotPendingLock = 0;
1571
1572 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001573 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00001574 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
1575
drhbfe66312006-10-03 17:40:40 +00001576 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00001577 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
1578 ** enterMutex() hasn't been called yet.
1579 */
drhbfe66312006-10-03 17:40:40 +00001580 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001581 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001582 locktypeName(locktype));
1583 return SQLITE_OK;
1584 }
1585
1586 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00001587 */
drhbfe66312006-10-03 17:40:40 +00001588 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
1589 assert( locktype!=PENDING_LOCK );
1590 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1591
1592 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00001593 */
danielk1977b4b47412007-08-17 15:53:36 +00001594 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001595
1596 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00001597 */
drhbfe66312006-10-03 17:40:40 +00001598 rc = transferOwnership(pFile);
1599 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001600 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001601 return rc;
1602 }
1603
1604 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00001605 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1606 ** be released.
1607 */
drhbfe66312006-10-03 17:40:40 +00001608 if( locktype==SHARED_LOCK
1609 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00001610 ){
1611 int failed;
1612 failed = _AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00001613 if (failed) {
1614 rc = SQLITE_BUSY;
1615 goto afp_end_lock;
1616 }
1617 }
1618
1619 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00001620 ** operating system calls for the specified lock.
1621 */
drhbfe66312006-10-03 17:40:40 +00001622 if( locktype==SHARED_LOCK ){
1623 int lk, failed;
1624 int tries = 0;
1625
1626 /* Now get the read-lock */
1627 /* note that the quality of the randomness doesn't matter that much */
1628 lk = random();
1629 context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
1630 failed = _AFPFSSetLock(context->filePath, pFile->h,
1631 SHARED_FIRST+context->sharedLockByte, 1, 1);
1632
1633 /* Drop the temporary PENDING lock */
1634 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
1635 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1636 goto afp_end_lock;
1637 }
1638
1639 if( failed ){
1640 rc = SQLITE_BUSY;
1641 } else {
1642 pFile->locktype = SHARED_LOCK;
1643 }
1644 }else{
1645 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1646 ** assumed that there is a SHARED or greater lock on the file
1647 ** already.
1648 */
1649 int failed = 0;
1650 assert( 0!=pFile->locktype );
1651 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
1652 /* Acquire a RESERVED lock */
1653 failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1654 }
1655 if (!failed && locktype == EXCLUSIVE_LOCK) {
1656 /* Acquire an EXCLUSIVE lock */
1657
1658 /* Remove the shared lock before trying the range. we'll need to
1659 ** reestablish the shared lock if we can't get the afpUnixUnlock
1660 */
1661 if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1662 context->sharedLockByte, 1, 0)) {
1663 /* now attemmpt to get the exclusive lock range */
1664 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1665 SHARED_SIZE, 1);
1666 if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1667 context->sharedLockByte, 1, 1)) {
1668 rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
1669 }
1670 } else {
1671 /* */
1672 rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
1673 }
1674 }
1675 if( failed && rc == SQLITE_OK){
1676 rc = SQLITE_BUSY;
1677 }
1678 }
1679
1680 if( rc==SQLITE_OK ){
1681 pFile->locktype = locktype;
1682 }else if( locktype==EXCLUSIVE_LOCK ){
1683 pFile->locktype = PENDING_LOCK;
1684 }
1685
1686afp_end_lock:
drh339eb0b2008-03-07 15:34:11 +00001687 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001688 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00001689 rc==SQLITE_OK ? "ok" : "failed");
1690 return rc;
1691}
1692
1693/*
drh339eb0b2008-03-07 15:34:11 +00001694** Lower the locking level on file descriptor pFile to locktype. locktype
1695** must be either NO_LOCK or SHARED_LOCK.
1696**
1697** If the locking level of the file descriptor is already at or below
1698** the requested locking level, this routine is a no-op.
1699*/
danielk1977ad94b582007-08-20 06:44:22 +00001700static int afpUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001701 struct flock lock;
1702 int rc = SQLITE_OK;
1703 unixFile *pFile = (unixFile*)id;
1704 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1705
1706 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001707 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00001708 pFile->locktype, getpid());
1709
1710 assert( locktype<=SHARED_LOCK );
1711 if( pFile->locktype<=locktype ){
1712 return SQLITE_OK;
1713 }
1714 if( CHECK_THREADID(pFile) ){
1715 return SQLITE_MISUSE;
1716 }
danielk1977b4b47412007-08-17 15:53:36 +00001717 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001718 if( pFile->locktype>SHARED_LOCK ){
1719 if( locktype==SHARED_LOCK ){
1720 int failed = 0;
1721
1722 /* unlock the exclusive range - then re-establish the shared lock */
1723 if (pFile->locktype==EXCLUSIVE_LOCK) {
1724 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1725 SHARED_SIZE, 0);
1726 if (!failed) {
1727 /* successfully removed the exclusive lock */
1728 if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
1729 context->sharedLockByte, 1, 1)) {
1730 /* failed to re-establish our shared lock */
1731 rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
1732 }
1733 } else {
1734 /* This should never happen - failed to unlock the exclusive range */
1735 rc = SQLITE_IOERR_UNLOCK;
1736 }
1737 }
1738 }
1739 if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
1740 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
1741 /* failed to release the pending lock */
1742 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1743 }
1744 }
1745 if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
1746 if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
1747 /* failed to release the reserved lock */
1748 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1749 }
1750 }
1751 }
1752 if( locktype==NO_LOCK ){
1753 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1754 SHARED_FIRST + context->sharedLockByte, 1, 0);
1755 if (failed) {
1756 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1757 }
1758 }
1759 if (rc == SQLITE_OK)
1760 pFile->locktype = locktype;
danielk1977b4b47412007-08-17 15:53:36 +00001761 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001762 return rc;
1763}
1764
1765/*
drh339eb0b2008-03-07 15:34:11 +00001766** Close a file & cleanup AFP specific locking context
1767*/
danielk1977ad94b582007-08-20 06:44:22 +00001768static int afpUnixClose(sqlite3_file *id) {
drh218c5082008-03-07 00:27:10 +00001769 unixFile *pFile = (unixFile*)id;
danielk1977ad94b582007-08-20 06:44:22 +00001770
1771 if( !pFile ) return SQLITE_OK;
drh218c5082008-03-07 00:27:10 +00001772 afpUnixUnlock(id, NO_LOCK);
drh339eb0b2008-03-07 15:34:11 +00001773 sqlite3_free(pFile->lockingContext);
danielk1977ad94b582007-08-20 06:44:22 +00001774 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1775 pFile->dirfd = -1;
drh1aa5af12008-03-07 19:51:14 +00001776 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001777 close(pFile->h);
drh1aa5af12008-03-07 19:51:14 +00001778 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001779 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001780 OpenCounter(-1);
drh218c5082008-03-07 00:27:10 +00001781 memset(pFile, 0, sizeof(unixFile));
drhbfe66312006-10-03 17:40:40 +00001782 return SQLITE_OK;
1783}
1784
1785
1786#pragma mark flock() style locking
1787
1788/*
drh339eb0b2008-03-07 15:34:11 +00001789** The flockLockingContext is not used
1790*/
drhbfe66312006-10-03 17:40:40 +00001791typedef void flockLockingContext;
1792
danielk1977861f7452008-06-05 11:39:11 +00001793static int flockUnixCheckReservedLock(sqlite3_file *id, int *pResOut){
1794 int r = 1;
drhbfe66312006-10-03 17:40:40 +00001795 unixFile *pFile = (unixFile*)id;
1796
danielk1977861f7452008-06-05 11:39:11 +00001797 if (pFile->locktype != RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00001798 /* attempt to get the lock */
drhbfe66312006-10-03 17:40:40 +00001799 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1800 if (!rc) {
drh3b62b2f2007-06-08 18:27:03 +00001801 /* got the lock, unlock it */
drhbfe66312006-10-03 17:40:40 +00001802 flock(pFile->h, LOCK_UN);
danielk1977861f7452008-06-05 11:39:11 +00001803 r = 0; /* no one has it reserved */
drhbfe66312006-10-03 17:40:40 +00001804 }
drhbfe66312006-10-03 17:40:40 +00001805 }
danielk1977861f7452008-06-05 11:39:11 +00001806
1807 *pResOut = r;
1808 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001809}
1810
danielk1977ad94b582007-08-20 06:44:22 +00001811static int flockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001812 unixFile *pFile = (unixFile*)id;
1813
drh3b62b2f2007-06-08 18:27:03 +00001814 /* if we already have a lock, it is exclusive.
1815 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00001816 if (pFile->locktype > NO_LOCK) {
1817 pFile->locktype = locktype;
1818 return SQLITE_OK;
1819 }
1820
drh3b62b2f2007-06-08 18:27:03 +00001821 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00001822 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1823 if (rc) {
drh3b62b2f2007-06-08 18:27:03 +00001824 /* didn't get, must be busy */
drhbfe66312006-10-03 17:40:40 +00001825 return SQLITE_BUSY;
1826 } else {
drh3b62b2f2007-06-08 18:27:03 +00001827 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00001828 pFile->locktype = locktype;
1829 return SQLITE_OK;
1830 }
1831}
1832
danielk1977ad94b582007-08-20 06:44:22 +00001833static int flockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001834 unixFile *pFile = (unixFile*)id;
1835
1836 assert( locktype<=SHARED_LOCK );
1837
drh3b62b2f2007-06-08 18:27:03 +00001838 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00001839 if( pFile->locktype==locktype ){
1840 return SQLITE_OK;
1841 }
1842
drh3b62b2f2007-06-08 18:27:03 +00001843 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00001844 if (locktype==SHARED_LOCK) {
1845 pFile->locktype = locktype;
1846 return SQLITE_OK;
1847 }
1848
drh3b62b2f2007-06-08 18:27:03 +00001849 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00001850 int rc = flock(pFile->h, LOCK_UN);
1851 if (rc)
1852 return SQLITE_IOERR_UNLOCK;
1853 else {
1854 pFile->locktype = NO_LOCK;
1855 return SQLITE_OK;
1856 }
1857}
1858
1859/*
drh339eb0b2008-03-07 15:34:11 +00001860** Close a file.
1861*/
drh218c5082008-03-07 00:27:10 +00001862static int flockUnixClose(sqlite3_file *id) {
1863 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00001864
danielk1977ad94b582007-08-20 06:44:22 +00001865 if( !pFile ) return SQLITE_OK;
drh218c5082008-03-07 00:27:10 +00001866 flockUnixUnlock(id, NO_LOCK);
drhbfe66312006-10-03 17:40:40 +00001867
danielk1977ad94b582007-08-20 06:44:22 +00001868 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1869 pFile->dirfd = -1;
drh1aa5af12008-03-07 19:51:14 +00001870
1871 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001872 close(pFile->h);
drh1aa5af12008-03-07 19:51:14 +00001873 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001874 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001875 OpenCounter(-1);
drh218c5082008-03-07 00:27:10 +00001876 memset(pFile, 0, sizeof(unixFile));
drhbfe66312006-10-03 17:40:40 +00001877 return SQLITE_OK;
1878}
1879
1880#pragma mark Old-School .lock file based locking
1881
1882/*
drh339eb0b2008-03-07 15:34:11 +00001883** The dotlockLockingContext structure contains all dotlock (.lock) lock
1884** specific state
1885*/
drhbfe66312006-10-03 17:40:40 +00001886typedef struct dotlockLockingContext dotlockLockingContext;
1887struct dotlockLockingContext {
1888 char *lockPath;
1889};
1890
1891
danielk1977861f7452008-06-05 11:39:11 +00001892static int dotlockUnixCheckReservedLock(sqlite3_file *id, int *pResOut) {
1893 int r = 1;
drhbfe66312006-10-03 17:40:40 +00001894 unixFile *pFile = (unixFile*)id;
drh339eb0b2008-03-07 15:34:11 +00001895 dotlockLockingContext *context;
1896
1897 context = (dotlockLockingContext*)pFile->lockingContext;
danielk1977861f7452008-06-05 11:39:11 +00001898 if (pFile->locktype != RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00001899 struct stat statBuf;
danielk1977861f7452008-06-05 11:39:11 +00001900 if (lstat(context->lockPath,&statBuf) != 0){
drh3b62b2f2007-06-08 18:27:03 +00001901 /* file does not exist, we could have it if we want it */
danielk1977861f7452008-06-05 11:39:11 +00001902 r = 0;
drh339eb0b2008-03-07 15:34:11 +00001903 }
drhbfe66312006-10-03 17:40:40 +00001904 }
danielk1977861f7452008-06-05 11:39:11 +00001905
1906 *pResOut = r;
1907 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001908}
1909
danielk1977ad94b582007-08-20 06:44:22 +00001910static int dotlockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001911 unixFile *pFile = (unixFile*)id;
drh339eb0b2008-03-07 15:34:11 +00001912 dotlockLockingContext *context;
1913 int fd;
1914
1915 context = (dotlockLockingContext*)pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00001916
drh3b62b2f2007-06-08 18:27:03 +00001917 /* if we already have a lock, it is exclusive.
1918 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00001919 if (pFile->locktype > NO_LOCK) {
1920 pFile->locktype = locktype;
1921
1922 /* Always update the timestamp on the old file */
1923 utimes(context->lockPath,NULL);
1924 return SQLITE_OK;
1925 }
1926
drh3b62b2f2007-06-08 18:27:03 +00001927 /* check to see if lock file already exists */
drhbfe66312006-10-03 17:40:40 +00001928 struct stat statBuf;
1929 if (lstat(context->lockPath,&statBuf) == 0){
drh3b62b2f2007-06-08 18:27:03 +00001930 return SQLITE_BUSY; /* it does, busy */
drhbfe66312006-10-03 17:40:40 +00001931 }
1932
drh3b62b2f2007-06-08 18:27:03 +00001933 /* grab an exclusive lock */
drh339eb0b2008-03-07 15:34:11 +00001934 fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
1935 if( fd<0 ){
drh3b62b2f2007-06-08 18:27:03 +00001936 /* failed to open/create the file, someone else may have stolen the lock */
drhbfe66312006-10-03 17:40:40 +00001937 return SQLITE_BUSY;
1938 }
1939 close(fd);
1940
drh3b62b2f2007-06-08 18:27:03 +00001941 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00001942 pFile->locktype = locktype;
1943 return SQLITE_OK;
1944}
1945
danielk1977ad94b582007-08-20 06:44:22 +00001946static int dotlockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001947 unixFile *pFile = (unixFile*)id;
drh339eb0b2008-03-07 15:34:11 +00001948 dotlockLockingContext *context;
1949
1950 context = (dotlockLockingContext*)pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00001951
1952 assert( locktype<=SHARED_LOCK );
1953
drh3b62b2f2007-06-08 18:27:03 +00001954 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00001955 if( pFile->locktype==locktype ){
1956 return SQLITE_OK;
1957 }
1958
drh3b62b2f2007-06-08 18:27:03 +00001959 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00001960 if (locktype==SHARED_LOCK) {
1961 pFile->locktype = locktype;
1962 return SQLITE_OK;
1963 }
1964
drh3b62b2f2007-06-08 18:27:03 +00001965 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00001966 unlink(context->lockPath);
1967 pFile->locktype = NO_LOCK;
1968 return SQLITE_OK;
1969}
1970
1971/*
1972 ** Close a file.
1973 */
danielk1977ad94b582007-08-20 06:44:22 +00001974static int dotlockUnixClose(sqlite3_file *id) {
1975 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00001976
danielk1977ad94b582007-08-20 06:44:22 +00001977 if( !pFile ) return SQLITE_OK;
drh218c5082008-03-07 00:27:10 +00001978 dotlockUnixUnlock(id, NO_LOCK);
drh339eb0b2008-03-07 15:34:11 +00001979 sqlite3_free(pFile->lockingContext);
danielk1977ad94b582007-08-20 06:44:22 +00001980 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1981 pFile->dirfd = -1;
drh1aa5af12008-03-07 19:51:14 +00001982 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001983 close(pFile->h);
drh1aa5af12008-03-07 19:51:14 +00001984 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001985 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001986 OpenCounter(-1);
drh218c5082008-03-07 00:27:10 +00001987 memset(pFile, 0, sizeof(unixFile));
drhbfe66312006-10-03 17:40:40 +00001988 return SQLITE_OK;
1989}
1990
1991
1992#pragma mark No locking
1993
1994/*
drh339eb0b2008-03-07 15:34:11 +00001995** The nolockLockingContext is void
1996*/
drhbfe66312006-10-03 17:40:40 +00001997typedef void nolockLockingContext;
1998
danielk1977861f7452008-06-05 11:39:11 +00001999static int nolockUnixCheckReservedLock(sqlite3_file *id, int *pResOut) {
2000 *pResOut = 0;
2001 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002002}
2003
danielk1977ad94b582007-08-20 06:44:22 +00002004static int nolockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002005 return SQLITE_OK;
2006}
2007
danielk1977ad94b582007-08-20 06:44:22 +00002008static int nolockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002009 return SQLITE_OK;
2010}
2011
2012/*
drh339eb0b2008-03-07 15:34:11 +00002013** Close a file.
2014*/
danielk1977ad94b582007-08-20 06:44:22 +00002015static int nolockUnixClose(sqlite3_file *id) {
2016 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00002017
danielk1977ad94b582007-08-20 06:44:22 +00002018 if( !pFile ) return SQLITE_OK;
2019 if( pFile->dirfd>=0 ) close(pFile->dirfd);
2020 pFile->dirfd = -1;
drh1aa5af12008-03-07 19:51:14 +00002021 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00002022 close(pFile->h);
drh1aa5af12008-03-07 19:51:14 +00002023 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00002024 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00002025 OpenCounter(-1);
drh218c5082008-03-07 00:27:10 +00002026 memset(pFile, 0, sizeof(unixFile));
drhbfe66312006-10-03 17:40:40 +00002027 return SQLITE_OK;
2028}
2029
2030#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2031
danielk1977ad94b582007-08-20 06:44:22 +00002032
danielk1977e3026632004-06-22 11:29:02 +00002033/*
drh9e33c2c2007-08-31 18:34:59 +00002034** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00002035*/
drhcc6bb3e2007-08-31 16:11:35 +00002036static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00002037 switch( op ){
2038 case SQLITE_FCNTL_LOCKSTATE: {
2039 *(int*)pArg = ((unixFile*)id)->locktype;
2040 return SQLITE_OK;
2041 }
2042 }
drhcc6bb3e2007-08-31 16:11:35 +00002043 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00002044}
2045
2046/*
danielk1977a3d4c882007-03-23 10:08:38 +00002047** Return the sector size in bytes of the underlying block device for
2048** the specified file. This is almost always 512 bytes, but may be
2049** larger for some devices.
2050**
2051** SQLite code assumes this function cannot fail. It also assumes that
2052** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00002053** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00002054** same for both.
2055*/
danielk197762079062007-08-15 17:08:46 +00002056static int unixSectorSize(sqlite3_file *id){
drh3ceeb752007-03-29 18:19:52 +00002057 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00002058}
2059
danielk197790949c22007-08-17 16:50:38 +00002060/*
2061** Return the device characteristics for the file. This is always 0.
2062*/
danielk197762079062007-08-15 17:08:46 +00002063static int unixDeviceCharacteristics(sqlite3_file *id){
2064 return 0;
2065}
2066
danielk1977a3d4c882007-03-23 10:08:38 +00002067/*
danielk1977ad94b582007-08-20 06:44:22 +00002068** This vector defines all the methods that can operate on an sqlite3_file
drh054889e2005-11-30 03:20:31 +00002069** for unix.
drh9c06c952005-11-26 00:25:00 +00002070*/
danielk197762079062007-08-15 17:08:46 +00002071static const sqlite3_io_methods sqlite3UnixIoMethod = {
2072 1, /* iVersion */
drh9c06c952005-11-26 00:25:00 +00002073 unixClose,
2074 unixRead,
2075 unixWrite,
drh9c06c952005-11-26 00:25:00 +00002076 unixTruncate,
drh054889e2005-11-30 03:20:31 +00002077 unixSync,
drh054889e2005-11-30 03:20:31 +00002078 unixFileSize,
2079 unixLock,
2080 unixUnlock,
drh054889e2005-11-30 03:20:31 +00002081 unixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002082 unixFileControl,
danielk1977a3d4c882007-03-23 10:08:38 +00002083 unixSectorSize,
danielk197762079062007-08-15 17:08:46 +00002084 unixDeviceCharacteristics
drh9c06c952005-11-26 00:25:00 +00002085};
2086
drhbfe66312006-10-03 17:40:40 +00002087#ifdef SQLITE_ENABLE_LOCKING_STYLE
drh054889e2005-11-30 03:20:31 +00002088/*
danielk1977ad94b582007-08-20 06:44:22 +00002089** This vector defines all the methods that can operate on an sqlite3_file
2090** for unix with AFP style file locking.
2091*/
2092static const sqlite3_io_methods sqlite3AFPLockingUnixIoMethod = {
2093 1, /* iVersion */
drh218c5082008-03-07 00:27:10 +00002094 afpUnixClose,
drhbfe66312006-10-03 17:40:40 +00002095 unixRead,
2096 unixWrite,
drhbfe66312006-10-03 17:40:40 +00002097 unixTruncate,
2098 unixSync,
danielk1977ad94b582007-08-20 06:44:22 +00002099 unixFileSize,
2100 afpUnixLock,
2101 afpUnixUnlock,
2102 afpUnixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002103 unixFileControl,
danielk1977ad94b582007-08-20 06:44:22 +00002104 unixSectorSize,
2105 unixDeviceCharacteristics
2106};
2107
2108/*
2109** This vector defines all the methods that can operate on an sqlite3_file
2110** for unix with flock() style file locking.
2111*/
2112static const sqlite3_io_methods sqlite3FlockLockingUnixIoMethod = {
2113 1, /* iVersion */
2114 flockUnixClose,
2115 unixRead,
2116 unixWrite,
2117 unixTruncate,
2118 unixSync,
2119 unixFileSize,
2120 flockUnixLock,
2121 flockUnixUnlock,
2122 flockUnixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002123 unixFileControl,
danielk1977ad94b582007-08-20 06:44:22 +00002124 unixSectorSize,
2125 unixDeviceCharacteristics
2126};
2127
2128/*
2129** This vector defines all the methods that can operate on an sqlite3_file
2130** for unix with dotlock style file locking.
2131*/
2132static const sqlite3_io_methods sqlite3DotlockLockingUnixIoMethod = {
2133 1, /* iVersion */
2134 dotlockUnixClose,
2135 unixRead,
2136 unixWrite,
2137 unixTruncate,
2138 unixSync,
2139 unixFileSize,
2140 dotlockUnixLock,
2141 dotlockUnixUnlock,
2142 dotlockUnixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002143 unixFileControl,
danielk1977ad94b582007-08-20 06:44:22 +00002144 unixSectorSize,
2145 unixDeviceCharacteristics
2146};
2147
2148/*
2149** This vector defines all the methods that can operate on an sqlite3_file
drh339eb0b2008-03-07 15:34:11 +00002150** for unix with nolock style file locking.
danielk1977ad94b582007-08-20 06:44:22 +00002151*/
2152static const sqlite3_io_methods sqlite3NolockLockingUnixIoMethod = {
2153 1, /* iVersion */
2154 nolockUnixClose,
2155 unixRead,
2156 unixWrite,
2157 unixTruncate,
2158 unixSync,
drhbfe66312006-10-03 17:40:40 +00002159 unixFileSize,
2160 nolockUnixLock,
2161 nolockUnixUnlock,
drhbfe66312006-10-03 17:40:40 +00002162 nolockUnixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002163 unixFileControl,
danielk1977a3d4c882007-03-23 10:08:38 +00002164 unixSectorSize,
danielk1977ad94b582007-08-20 06:44:22 +00002165 unixDeviceCharacteristics
drhbfe66312006-10-03 17:40:40 +00002166};
2167
2168#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2169
2170/*
2171** Allocate memory for a new unixFile and initialize that unixFile.
2172** Write a pointer to the new unixFile into *pId.
2173** If we run out of memory, close the file and return an error.
drh054889e2005-11-30 03:20:31 +00002174*/
drhbfe66312006-10-03 17:40:40 +00002175#ifdef SQLITE_ENABLE_LOCKING_STYLE
2176/*
danielk1977ad94b582007-08-20 06:44:22 +00002177** When locking extensions are enabled, the filepath and locking style
2178** are needed to determine the unixFile pMethod to use for locking operations.
2179** The locking-style specific lockingContext data structure is created
2180** and assigned here also.
2181*/
2182static int fillInUnixFile(
drhbfe66312006-10-03 17:40:40 +00002183 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00002184 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00002185 sqlite3_file *pId, /* Write to the unixFile structure here */
2186 const char *zFilename /* Name of the file being opened */
drhbfe66312006-10-03 17:40:40 +00002187){
danielk197717b90b52008-06-06 11:11:25 +00002188 sqlite3LockingStyle lockingStyle = noLockingStyle;
danielk1977ad94b582007-08-20 06:44:22 +00002189 unixFile *pNew = (unixFile *)pId;
drhbfe66312006-10-03 17:40:40 +00002190 int rc;
2191
drh218c5082008-03-07 00:27:10 +00002192#ifdef FD_CLOEXEC
2193 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
2194#endif
2195
danielk197717b90b52008-06-06 11:11:25 +00002196 assert( pNew->pLock==NULL );
2197 assert( pNew->pOpen==NULL );
2198 if( zFilename ){
2199 /* If zFilename is NULL then this is a temporary file. Temporary files
2200 ** are never locked or unlocked, so noLockingStyle is used for these.
2201 ** The locking style used by other files is determined by
2202 ** sqlite3DetectLockingStyle().
2203 */
2204 lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
2205 if ( lockingStyle==posixLockingStyle ){
2206 enterMutex();
2207 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
2208 leaveMutex();
2209 if( rc ){
2210 if( dirfd>=0 ) close(dirfd);
2211 close(h);
2212 return rc;
2213 }
drhbfe66312006-10-03 17:40:40 +00002214 }
drhbfe66312006-10-03 17:40:40 +00002215 }
drh218c5082008-03-07 00:27:10 +00002216
2217 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00002218 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00002219 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00002220 SET_THREADID(pNew);
drh218c5082008-03-07 00:27:10 +00002221
2222 switch(lockingStyle) {
2223 case afpLockingStyle: {
2224 /* afp locking uses the file path so it needs to be included in
2225 ** the afpLockingContext */
drh339eb0b2008-03-07 15:34:11 +00002226 afpLockingContext *context;
drh218c5082008-03-07 00:27:10 +00002227 pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
drh339eb0b2008-03-07 15:34:11 +00002228 pNew->lockingContext = context = sqlite3_malloc( sizeof(*context) );
2229 if( context==0 ){
2230 close(h);
2231 if( dirfd>=0 ) close(dirfd);
2232 return SQLITE_NOMEM;
2233 }
2234
2235 /* NB: zFilename exists and remains valid until the file is closed
2236 ** according to requirement F11141. So we do not need to make a
2237 ** copy of the filename. */
2238 context->filePath = zFilename;
drh218c5082008-03-07 00:27:10 +00002239 srandomdev();
2240 break;
drhbfe66312006-10-03 17:40:40 +00002241 }
drh218c5082008-03-07 00:27:10 +00002242 case flockLockingStyle:
2243 /* flock locking doesn't need additional lockingContext information */
2244 pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
2245 break;
2246 case dotlockLockingStyle: {
2247 /* dotlock locking uses the file path so it needs to be included in
drh339eb0b2008-03-07 15:34:11 +00002248 ** the dotlockLockingContext */
2249 dotlockLockingContext *context;
drh218c5082008-03-07 00:27:10 +00002250 int nFilename;
drh339eb0b2008-03-07 15:34:11 +00002251 nFilename = strlen(zFilename);
drh218c5082008-03-07 00:27:10 +00002252 pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
drh339eb0b2008-03-07 15:34:11 +00002253 pNew->lockingContext = context =
2254 sqlite3_malloc( sizeof(*context) + nFilename + 6 );
2255 if( context==0 ){
2256 close(h);
2257 if( dirfd>=0 ) close(dirfd);
2258 return SQLITE_NOMEM;
2259 }
2260 context->lockPath = (char*)&context[1];
2261 sqlite3_snprintf(nFilename, context->lockPath,
2262 "%s.lock", zFilename);
drh218c5082008-03-07 00:27:10 +00002263 break;
2264 }
2265 case posixLockingStyle:
2266 /* posix locking doesn't need additional lockingContext information */
2267 pNew->pMethod = &sqlite3UnixIoMethod;
2268 break;
2269 case noLockingStyle:
2270 case unsupportedLockingStyle:
2271 default:
2272 pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
drhbfe66312006-10-03 17:40:40 +00002273 }
drh218c5082008-03-07 00:27:10 +00002274 OpenCounter(+1);
2275 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002276}
2277#else /* SQLITE_ENABLE_LOCKING_STYLE */
danielk1977b4b47412007-08-17 15:53:36 +00002278static int fillInUnixFile(
drhbfe66312006-10-03 17:40:40 +00002279 int h, /* Open file descriptor on file being opened */
danielk1977fee2d252007-08-18 10:59:19 +00002280 int dirfd,
danielk1977b4b47412007-08-17 15:53:36 +00002281 sqlite3_file *pId, /* Write to the unixFile structure here */
2282 const char *zFilename /* Name of the file being opened */
drhbfe66312006-10-03 17:40:40 +00002283){
danielk1977b4b47412007-08-17 15:53:36 +00002284 unixFile *pNew = (unixFile *)pId;
drhbfe66312006-10-03 17:40:40 +00002285 int rc;
2286
drhe78669b2007-06-29 12:04:26 +00002287#ifdef FD_CLOEXEC
2288 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
2289#endif
danielk1977b4b47412007-08-17 15:53:36 +00002290
2291 enterMutex();
2292 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
2293 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002294 if( rc ){
danielk19777c055b92007-10-30 17:28:51 +00002295 if( dirfd>=0 ) close(dirfd);
drhbfe66312006-10-03 17:40:40 +00002296 close(h);
drh65594042008-05-05 16:56:34 +00002297 return rc;
drhbfe66312006-10-03 17:40:40 +00002298 }
danielk1977b4b47412007-08-17 15:53:36 +00002299
drh4f0c5872007-03-26 22:05:01 +00002300 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977b4b47412007-08-17 15:53:36 +00002301 pNew->dirfd = -1;
2302 pNew->h = h;
danielk1977fee2d252007-08-18 10:59:19 +00002303 pNew->dirfd = dirfd;
danielk1977b4b47412007-08-17 15:53:36 +00002304 SET_THREADID(pNew);
2305
2306 pNew->pMethod = &sqlite3UnixIoMethod;
2307 OpenCounter(+1);
2308 return SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00002309}
drhbfe66312006-10-03 17:40:40 +00002310#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9c06c952005-11-26 00:25:00 +00002311
danielk1977ad94b582007-08-20 06:44:22 +00002312/*
2313** Open a file descriptor to the directory containing file zFilename.
2314** If successful, *pFd is set to the opened file descriptor and
2315** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
2316** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
2317** value.
2318**
2319** If SQLITE_OK is returned, the caller is responsible for closing
2320** the file descriptor *pFd using close().
2321*/
danielk1977fee2d252007-08-18 10:59:19 +00002322static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00002323 int ii;
drh777b17a2007-09-20 10:02:54 +00002324 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00002325 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00002326
drh153c62c2007-08-24 03:51:33 +00002327 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
danielk1977fee2d252007-08-18 10:59:19 +00002328 for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
2329 if( ii>0 ){
2330 zDirname[ii] = '\0';
2331 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00002332 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00002333#ifdef FD_CLOEXEC
2334 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
2335#endif
2336 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
2337 }
2338 }
danielk1977fee2d252007-08-18 10:59:19 +00002339 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00002340 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00002341}
2342
danielk1977b4b47412007-08-17 15:53:36 +00002343/*
danielk197717b90b52008-06-06 11:11:25 +00002344** Create a temporary file name in zBuf. zBuf must be allocated
2345** by the calling process and must be big enough to hold at least
2346** pVfs->mxPathname bytes.
2347*/
2348static int getTempname(int nBuf, char *zBuf){
2349 static const char *azDirs[] = {
2350 0,
2351 "/var/tmp",
2352 "/usr/tmp",
2353 "/tmp",
2354 ".",
2355 };
2356 static const unsigned char zChars[] =
2357 "abcdefghijklmnopqrstuvwxyz"
2358 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2359 "0123456789";
2360 int i, j;
2361 struct stat buf;
2362 const char *zDir = ".";
2363
2364 /* It's odd to simulate an io-error here, but really this is just
2365 ** using the io-error infrastructure to test that SQLite handles this
2366 ** function failing.
2367 */
2368 SimulateIOError( return SQLITE_IOERR );
2369
2370 azDirs[0] = sqlite3_temp_directory;
2371 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
2372 if( azDirs[i]==0 ) continue;
2373 if( stat(azDirs[i], &buf) ) continue;
2374 if( !S_ISDIR(buf.st_mode) ) continue;
2375 if( access(azDirs[i], 07) ) continue;
2376 zDir = azDirs[i];
2377 break;
2378 }
2379
2380 /* Check that the output buffer is large enough for the temporary file
2381 ** name. If it is not, return SQLITE_ERROR.
2382 */
2383 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
2384 return SQLITE_ERROR;
2385 }
2386
2387 do{
2388 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
2389 j = strlen(zBuf);
2390 sqlite3_randomness(15, &zBuf[j]);
2391 for(i=0; i<15; i++, j++){
2392 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
2393 }
2394 zBuf[j] = 0;
2395 }while( access(zBuf,0)==0 );
2396 return SQLITE_OK;
2397}
2398
2399
2400/*
danielk1977ad94b582007-08-20 06:44:22 +00002401** Open the file zPath.
2402**
danielk1977b4b47412007-08-17 15:53:36 +00002403** Previously, the SQLite OS layer used three functions in place of this
2404** one:
2405**
2406** sqlite3OsOpenReadWrite();
2407** sqlite3OsOpenReadOnly();
2408** sqlite3OsOpenExclusive();
2409**
2410** These calls correspond to the following combinations of flags:
2411**
2412** ReadWrite() -> (READWRITE | CREATE)
2413** ReadOnly() -> (READONLY)
2414** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
2415**
2416** The old OpenExclusive() accepted a boolean argument - "delFlag". If
2417** true, the file was configured to be automatically deleted when the
2418** file handle closed. To achieve the same effect using this new
2419** interface, add the DELETEONCLOSE flag to those specified above for
2420** OpenExclusive().
2421*/
2422static int unixOpen(
drh153c62c2007-08-24 03:51:33 +00002423 sqlite3_vfs *pVfs,
danielk1977b4b47412007-08-17 15:53:36 +00002424 const char *zPath,
2425 sqlite3_file *pFile,
2426 int flags,
2427 int *pOutFlags
2428){
danielk1977fee2d252007-08-18 10:59:19 +00002429 int fd = 0; /* File descriptor returned by open() */
2430 int dirfd = -1; /* Directory file descriptor */
2431 int oflags = 0; /* Flags to pass to open() */
2432 int eType = flags&0xFFFFFF00; /* Type of file to open */
danielk1977b4b47412007-08-17 15:53:36 +00002433
2434 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
2435 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
2436 int isCreate = (flags & SQLITE_OPEN_CREATE);
2437 int isReadonly = (flags & SQLITE_OPEN_READONLY);
2438 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
2439
danielk1977fee2d252007-08-18 10:59:19 +00002440 /* If creating a master or main-file journal, this function will open
2441 ** a file-descriptor on the directory too. The first time unixSync()
2442 ** is called the directory file descriptor will be fsync()ed and close()d.
2443 */
2444 int isOpenDirectory = (isCreate &&
2445 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
2446 );
2447
danielk197717b90b52008-06-06 11:11:25 +00002448 /* If argument zPath is a NULL pointer, this function is required to open
2449 ** a temporary file. Use this buffer to store the file name in.
2450 */
2451 char zTmpname[MAX_PATHNAME+1];
2452 const char *zName = zPath;
2453
danielk1977fee2d252007-08-18 10:59:19 +00002454 /* Check the following statements are true:
2455 **
2456 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
2457 ** (b) if CREATE is set, then READWRITE must also be set, and
2458 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00002459 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00002460 */
danielk1977b4b47412007-08-17 15:53:36 +00002461 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00002462 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00002463 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00002464 assert(isDelete==0 || isCreate);
2465
2466
2467 /* The main DB, main journal, and master journal are never automatically
2468 ** deleted
2469 */
2470 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
2471 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
2472 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00002473
danielk1977fee2d252007-08-18 10:59:19 +00002474 /* Assert that the upper layer has set one of the "file-type" flags. */
2475 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
2476 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
2477 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00002478 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00002479 );
2480
danielk197717b90b52008-06-06 11:11:25 +00002481 if( !zName ){
2482 int rc;
2483 assert(isDelete && !isOpenDirectory);
2484 rc = getTempname(MAX_PATHNAME+1, zTmpname);
2485 if( rc!=SQLITE_OK ){
2486 return rc;
2487 }
2488 zName = zTmpname;
2489 }
2490
danielk1977b4b47412007-08-17 15:53:36 +00002491 if( isReadonly ) oflags |= O_RDONLY;
2492 if( isReadWrite ) oflags |= O_RDWR;
2493 if( isCreate ) oflags |= O_CREAT;
2494 if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
2495 oflags |= (O_LARGEFILE|O_BINARY);
2496
2497 memset(pFile, 0, sizeof(unixFile));
danielk197717b90b52008-06-06 11:11:25 +00002498 fd = open(zName, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
danielk19772f2d8c72007-08-30 16:13:33 +00002499 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00002500 /* Failed to open the file for read/write access. Try read-only. */
2501 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
2502 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00002503 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00002504 }
2505 if( fd<0 ){
2506 return SQLITE_CANTOPEN;
2507 }
2508 if( isDelete ){
danielk197717b90b52008-06-06 11:11:25 +00002509 unlink(zName);
danielk1977b4b47412007-08-17 15:53:36 +00002510 }
2511 if( pOutFlags ){
2512 *pOutFlags = flags;
2513 }
2514
2515 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00002516 if( isOpenDirectory ){
2517 int rc = openDirectory(zPath, &dirfd);
2518 if( rc!=SQLITE_OK ){
2519 close(fd);
2520 return rc;
2521 }
2522 }
2523 return fillInUnixFile(fd, dirfd, pFile, zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002524}
2525
2526/*
danielk1977fee2d252007-08-18 10:59:19 +00002527** Delete the file at zPath. If the dirSync argument is true, fsync()
2528** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00002529*/
drh153c62c2007-08-24 03:51:33 +00002530static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
danielk1977fee2d252007-08-18 10:59:19 +00002531 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00002532 SimulateIOError(return SQLITE_IOERR_DELETE);
2533 unlink(zPath);
danielk1977fee2d252007-08-18 10:59:19 +00002534 if( dirSync ){
2535 int fd;
2536 rc = openDirectory(zPath, &fd);
2537 if( rc==SQLITE_OK ){
2538 if( fsync(fd) ){
2539 rc = SQLITE_IOERR_DIR_FSYNC;
2540 }
2541 close(fd);
2542 }
2543 }
2544 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00002545}
2546
danielk197790949c22007-08-17 16:50:38 +00002547/*
2548** Test the existance of or access permissions of file zPath. The
2549** test performed depends on the value of flags:
2550**
2551** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
2552** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
2553** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
2554**
2555** Otherwise return 0.
2556*/
danielk1977861f7452008-06-05 11:39:11 +00002557static int unixAccess(
2558 sqlite3_vfs *pVfs,
2559 const char *zPath,
2560 int flags,
2561 int *pResOut
2562){
rse25c0d1a2007-09-20 08:38:14 +00002563 int amode = 0;
danielk1977861f7452008-06-05 11:39:11 +00002564 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00002565 switch( flags ){
2566 case SQLITE_ACCESS_EXISTS:
2567 amode = F_OK;
2568 break;
2569 case SQLITE_ACCESS_READWRITE:
2570 amode = W_OK|R_OK;
2571 break;
drh50d3f902007-08-27 21:10:36 +00002572 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00002573 amode = R_OK;
2574 break;
2575
2576 default:
2577 assert(!"Invalid flags argument");
2578 }
danielk1977861f7452008-06-05 11:39:11 +00002579 *pResOut = (access(zPath, amode)==0);
2580 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00002581}
2582
danielk1977b4b47412007-08-17 15:53:36 +00002583
2584/*
2585** Turn a relative pathname into a full pathname. The relative path
2586** is stored as a nul-terminated string in the buffer pointed to by
2587** zPath.
2588**
2589** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
2590** (in this case, MAX_PATHNAME bytes). The full-path is written to
2591** this buffer before returning.
2592*/
danielk1977adfb9b02007-09-17 07:02:56 +00002593static int unixFullPathname(
2594 sqlite3_vfs *pVfs, /* Pointer to vfs object */
2595 const char *zPath, /* Possibly relative input path */
2596 int nOut, /* Size of output buffer in bytes */
2597 char *zOut /* Output buffer */
2598){
danielk1977843e65f2007-09-01 16:16:15 +00002599
2600 /* It's odd to simulate an io-error here, but really this is just
2601 ** using the io-error infrastructure to test that SQLite handles this
2602 ** function failing. This function could fail if, for example, the
2603 ** current working directly has been unlinked.
2604 */
2605 SimulateIOError( return SQLITE_ERROR );
2606
drh153c62c2007-08-24 03:51:33 +00002607 assert( pVfs->mxPathname==MAX_PATHNAME );
drh3c7f2dc2007-12-06 13:26:20 +00002608 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00002609 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00002610 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002611 }else{
2612 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00002613 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00002614 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00002615 }
2616 nCwd = strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00002617 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002618 }
2619 return SQLITE_OK;
2620
2621#if 0
2622 /*
2623 ** Remove "/./" path elements and convert "/A/./" path elements
2624 ** to just "/".
2625 */
2626 if( zFull ){
2627 int i, j;
2628 for(i=j=0; zFull[i]; i++){
2629 if( zFull[i]=='/' ){
2630 if( zFull[i+1]=='/' ) continue;
2631 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
2632 i += 1;
2633 continue;
2634 }
2635 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
2636 while( j>0 && zFull[j-1]!='/' ){ j--; }
2637 i += 3;
2638 continue;
2639 }
2640 }
2641 zFull[j++] = zFull[i];
2642 }
2643 zFull[j] = 0;
2644 }
2645#endif
2646}
2647
drh0ccebe72005-06-07 22:22:50 +00002648
drh761df872006-12-21 01:29:22 +00002649#ifndef SQLITE_OMIT_LOAD_EXTENSION
2650/*
2651** Interfaces for opening a shared library, finding entry points
2652** within the shared library, and closing the shared library.
2653*/
2654#include <dlfcn.h>
drh153c62c2007-08-24 03:51:33 +00002655static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
drh761df872006-12-21 01:29:22 +00002656 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
2657}
danielk197795c8a542007-09-01 06:51:27 +00002658
2659/*
2660** SQLite calls this function immediately after a call to unixDlSym() or
2661** unixDlOpen() fails (returns a null pointer). If a more detailed error
2662** message is available, it is written to zBufOut. If no error message
2663** is available, zBufOut is left unmodified and SQLite uses a default
2664** error message.
2665*/
drh153c62c2007-08-24 03:51:33 +00002666static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00002667 char *zErr;
2668 enterMutex();
2669 zErr = dlerror();
2670 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00002671 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00002672 }
2673 leaveMutex();
2674}
drh46c99e02007-08-27 23:26:59 +00002675static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
drh761df872006-12-21 01:29:22 +00002676 return dlsym(pHandle, zSymbol);
2677}
drh46c99e02007-08-27 23:26:59 +00002678static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
danielk1977b4b47412007-08-17 15:53:36 +00002679 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00002680}
danielk1977b4b47412007-08-17 15:53:36 +00002681#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
2682 #define unixDlOpen 0
2683 #define unixDlError 0
2684 #define unixDlSym 0
2685 #define unixDlClose 0
2686#endif
2687
2688/*
danielk197790949c22007-08-17 16:50:38 +00002689** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00002690*/
drh153c62c2007-08-24 03:51:33 +00002691static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
danielk197790949c22007-08-17 16:50:38 +00002692
2693 assert(nBuf>=(sizeof(time_t)+sizeof(int)));
2694
drhbbd42a62004-05-22 17:41:58 +00002695 /* We have to initialize zBuf to prevent valgrind from reporting
2696 ** errors. The reports issued by valgrind are incorrect - we would
2697 ** prefer that the randomness be increased by making use of the
2698 ** uninitialized space in zBuf - but valgrind errors tend to worry
2699 ** some users. Rather than argue, it seems easier just to initialize
2700 ** the whole array and silence valgrind, even if that means less randomness
2701 ** in the random seed.
2702 **
2703 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00002704 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00002705 ** tests repeatable.
2706 */
danielk1977b4b47412007-08-17 15:53:36 +00002707 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00002708#if !defined(SQLITE_TEST)
2709 {
drh842b8642005-01-21 17:53:17 +00002710 int pid, fd;
2711 fd = open("/dev/urandom", O_RDONLY);
2712 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00002713 time_t t;
2714 time(&t);
danielk197790949c22007-08-17 16:50:38 +00002715 memcpy(zBuf, &t, sizeof(t));
2716 pid = getpid();
2717 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
drh842b8642005-01-21 17:53:17 +00002718 }else{
danielk1977b4b47412007-08-17 15:53:36 +00002719 read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00002720 close(fd);
2721 }
drhbbd42a62004-05-22 17:41:58 +00002722 }
2723#endif
2724 return SQLITE_OK;
2725}
2726
danielk1977b4b47412007-08-17 15:53:36 +00002727
drhbbd42a62004-05-22 17:41:58 +00002728/*
2729** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00002730** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00002731** The return value is the number of microseconds of sleep actually
2732** requested from the underlying operating system, a number which
2733** might be greater than or equal to the argument, but not less
2734** than the argument.
drhbbd42a62004-05-22 17:41:58 +00002735*/
drh153c62c2007-08-24 03:51:33 +00002736static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
drhbbd42a62004-05-22 17:41:58 +00002737#if defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00002738 usleep(microseconds);
2739 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00002740#else
danielk1977b4b47412007-08-17 15:53:36 +00002741 int seconds = (microseconds+999999)/1000000;
2742 sleep(seconds);
drh4a50aac2007-08-23 02:47:53 +00002743 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00002744#endif
drh88f474a2006-01-02 20:00:12 +00002745}
2746
2747/*
drhbbd42a62004-05-22 17:41:58 +00002748** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00002749** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00002750*/
2751#ifdef SQLITE_TEST
2752int sqlite3_current_time = 0;
2753#endif
2754
2755/*
2756** Find the current time (in Universal Coordinated Time). Write the
2757** current time and date as a Julian Day number into *prNow and
2758** return 0. Return 1 if the time and date cannot be found.
2759*/
drh153c62c2007-08-24 03:51:33 +00002760static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
drh19e2d372005-08-29 23:00:03 +00002761#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00002762 time_t t;
2763 time(&t);
2764 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00002765#else
2766 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00002767 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00002768 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
2769#endif
drhbbd42a62004-05-22 17:41:58 +00002770#ifdef SQLITE_TEST
2771 if( sqlite3_current_time ){
2772 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
2773 }
2774#endif
2775 return 0;
2776}
danielk1977b4b47412007-08-17 15:53:36 +00002777
danielk1977bcb97fe2008-06-06 15:49:29 +00002778static int unixGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
2779 return 0;
2780}
2781
drh153c62c2007-08-24 03:51:33 +00002782/*
danielk1977c0fa4c52008-06-25 17:19:00 +00002783** Initialize and deinitialize the operating system interface.
drh153c62c2007-08-24 03:51:33 +00002784*/
danielk1977c0fa4c52008-06-25 17:19:00 +00002785int sqlite3_os_init(void){
drh153c62c2007-08-24 03:51:33 +00002786 static sqlite3_vfs unixVfs = {
2787 1, /* iVersion */
2788 sizeof(unixFile), /* szOsFile */
2789 MAX_PATHNAME, /* mxPathname */
drh153c62c2007-08-24 03:51:33 +00002790 0, /* pNext */
2791 "unix", /* zName */
2792 0, /* pAppData */
2793
2794 unixOpen, /* xOpen */
2795 unixDelete, /* xDelete */
2796 unixAccess, /* xAccess */
drh153c62c2007-08-24 03:51:33 +00002797 unixFullPathname, /* xFullPathname */
2798 unixDlOpen, /* xDlOpen */
2799 unixDlError, /* xDlError */
2800 unixDlSym, /* xDlSym */
2801 unixDlClose, /* xDlClose */
2802 unixRandomness, /* xRandomness */
2803 unixSleep, /* xSleep */
danielk1977bcb97fe2008-06-06 15:49:29 +00002804 unixCurrentTime, /* xCurrentTime */
2805 unixGetLastError /* xGetLastError */
drh153c62c2007-08-24 03:51:33 +00002806 };
danielk1977c0fa4c52008-06-25 17:19:00 +00002807 sqlite3_vfs_register(&unixVfs, 1);
2808 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00002809}
danielk1977c0fa4c52008-06-25 17:19:00 +00002810int sqlite3_os_end(void){
2811 return SQLITE_OK;
2812}
drhdce8bdb2007-08-16 13:01:44 +00002813
danielk197729bafea2008-06-26 10:41:19 +00002814#endif /* SQLITE_OS_UNIX */