blob: 2f99db4609afb8287dec18713f69539bd2a56097 [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**
15** $Id: os_unix.c,v 1.182 2008/05/16 04:51:55 danielk1977 Exp $
drhbbd42a62004-05-22 17:41:58 +000016*/
drhbbd42a62004-05-22 17:41:58 +000017#include "sqliteInt.h"
drheb206252004-10-01 02:00:31 +000018#if 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(){
drh51fc3472007-08-21 13:51:23 +0000370 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
danielk1977b4b47412007-08-17 15:53:36 +0000371}
372static void leaveMutex(){
drh51fc3472007-08-21 13:51:23 +0000373 sqlite3_mutex_leave(sqlite3_mutex_alloc(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;
danielk1977967a4a12007-08-20 14:23:44 +0000808 OSTRACE5("READ %-3d %5d %7lld %d\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;
danielk197762079062007-08-15 17:08:46 +0000856 OSTRACE5("WRITE %-3d %5d %7lld %d\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*/
danielk197762079062007-08-15 17:08:46 +00001073static int unixCheckReservedLock(sqlite3_file *id){
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
drh054889e2005-11-30 03:20:31 +00001077 assert( pFile );
danielk1977b4b47412007-08-17 15:53:36 +00001078 enterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001079
1080 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001081 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001082 r = 1;
1083 }
1084
drh2ac3ee92004-06-07 16:27:46 +00001085 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001086 */
1087 if( !r ){
1088 struct flock lock;
1089 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001090 lock.l_start = RESERVED_BYTE;
1091 lock.l_len = 1;
1092 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001093 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001094 if( lock.l_type!=F_UNLCK ){
1095 r = 1;
1096 }
1097 }
1098
danielk1977b4b47412007-08-17 15:53:36 +00001099 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001100 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001101
1102 return r;
1103}
1104
1105/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001106** Lock the file with the lock specified by parameter locktype - one
1107** of the following:
1108**
drh2ac3ee92004-06-07 16:27:46 +00001109** (1) SHARED_LOCK
1110** (2) RESERVED_LOCK
1111** (3) PENDING_LOCK
1112** (4) EXCLUSIVE_LOCK
1113**
drhb3e04342004-06-08 00:47:47 +00001114** Sometimes when requesting one lock state, additional lock states
1115** are inserted in between. The locking might fail on one of the later
1116** transitions leaving the lock state different from what it started but
1117** still short of its goal. The following chart shows the allowed
1118** transitions and the inserted intermediate states:
1119**
1120** UNLOCKED -> SHARED
1121** SHARED -> RESERVED
1122** SHARED -> (PENDING) -> EXCLUSIVE
1123** RESERVED -> (PENDING) -> EXCLUSIVE
1124** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001125**
drha6abd042004-06-09 17:37:22 +00001126** This routine will only increase a lock. Use the sqlite3OsUnlock()
1127** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001128*/
danielk197762079062007-08-15 17:08:46 +00001129static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001130 /* The following describes the implementation of the various locks and
1131 ** lock transitions in terms of the POSIX advisory shared and exclusive
1132 ** lock primitives (called read-locks and write-locks below, to avoid
1133 ** confusion with SQLite lock names). The algorithms are complicated
1134 ** slightly in order to be compatible with windows systems simultaneously
1135 ** accessing the same database file, in case that is ever required.
1136 **
1137 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1138 ** byte', each single bytes at well known offsets, and the 'shared byte
1139 ** range', a range of 510 bytes at a well known offset.
1140 **
1141 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1142 ** byte'. If this is successful, a random byte from the 'shared byte
1143 ** range' is read-locked and the lock on the 'pending byte' released.
1144 **
danielk197790ba3bd2004-06-25 08:32:25 +00001145 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1146 ** A RESERVED lock is implemented by grabbing a write-lock on the
1147 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001148 **
1149 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001150 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1151 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1152 ** obtained, but existing SHARED locks are allowed to persist. A process
1153 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1154 ** This property is used by the algorithm for rolling back a journal file
1155 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001156 **
danielk197790ba3bd2004-06-25 08:32:25 +00001157 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1158 ** implemented by obtaining a write-lock on the entire 'shared byte
1159 ** range'. Since all other locks require a read-lock on one of the bytes
1160 ** within this range, this ensures that no other locks are held on the
1161 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001162 **
1163 ** The reason a single byte cannot be used instead of the 'shared byte
1164 ** range' is that some versions of windows do not support read-locks. By
1165 ** locking a random byte from a range, concurrent SHARED locks may exist
1166 ** even if the locking primitive used is always a write-lock.
1167 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001168 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001169 unixFile *pFile = (unixFile*)id;
1170 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001171 struct flock lock;
1172 int s;
1173
drh054889e2005-11-30 03:20:31 +00001174 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001175 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001176 locktypeName(locktype), locktypeName(pFile->locktype),
1177 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001178
1179 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001180 ** unixFile, do nothing. Don't use the end_lock: exit path, as
danielk1977b4b47412007-08-17 15:53:36 +00001181 ** enterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001182 */
drh054889e2005-11-30 03:20:31 +00001183 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001184 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001185 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001186 return SQLITE_OK;
1187 }
1188
drhb3e04342004-06-08 00:47:47 +00001189 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001190 */
drh054889e2005-11-30 03:20:31 +00001191 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001192 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001193 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001194
drh054889e2005-11-30 03:20:31 +00001195 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001196 */
danielk1977b4b47412007-08-17 15:53:36 +00001197 enterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001198
drh029b44b2006-01-15 00:13:15 +00001199 /* Make sure the current thread owns the pFile.
1200 */
1201 rc = transferOwnership(pFile);
1202 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001203 leaveMutex();
drh029b44b2006-01-15 00:13:15 +00001204 return rc;
1205 }
drh64b1bea2006-01-15 02:30:57 +00001206 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001207
danielk1977ad94b582007-08-20 06:44:22 +00001208 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001209 ** handle that precludes the requested lock, return BUSY.
1210 */
drh054889e2005-11-30 03:20:31 +00001211 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001212 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001213 ){
1214 rc = SQLITE_BUSY;
1215 goto end_lock;
1216 }
1217
1218 /* If a SHARED lock is requested, and some thread using this PID already
1219 ** has a SHARED or RESERVED lock, then increment reference counts and
1220 ** return SQLITE_OK.
1221 */
1222 if( locktype==SHARED_LOCK &&
1223 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1224 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001225 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001226 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001227 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001228 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001229 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001230 goto end_lock;
1231 }
1232
danielk197713adf8a2004-06-03 16:08:41 +00001233 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001234
danielk19779a1d0ab2004-06-01 14:09:28 +00001235 lock.l_whence = SEEK_SET;
1236
drh3cde3bb2004-06-12 02:17:14 +00001237 /* A PENDING lock is needed before acquiring a SHARED lock and before
1238 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1239 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001240 */
drh3cde3bb2004-06-12 02:17:14 +00001241 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001242 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001243 ){
danielk1977489468c2004-06-28 08:25:47 +00001244 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001245 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001246 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001247 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001248 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1249 goto end_lock;
1250 }
drh3cde3bb2004-06-12 02:17:14 +00001251 }
1252
1253
1254 /* If control gets to this point, then actually go ahead and make
1255 ** operating system calls for the specified lock.
1256 */
1257 if( locktype==SHARED_LOCK ){
1258 assert( pLock->cnt==0 );
1259 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001260
drh2ac3ee92004-06-07 16:27:46 +00001261 /* Now get the read-lock */
1262 lock.l_start = SHARED_FIRST;
1263 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001264 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001265
1266 /* Drop the temporary PENDING lock */
1267 lock.l_start = PENDING_BYTE;
1268 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001269 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001270 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001271 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001272 goto end_lock;
1273 }
drhe2396a12007-03-29 20:19:58 +00001274 if( s==(-1) ){
drhbbd42a62004-05-22 17:41:58 +00001275 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1276 }else{
drh054889e2005-11-30 03:20:31 +00001277 pFile->locktype = SHARED_LOCK;
1278 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001279 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001280 }
drh3cde3bb2004-06-12 02:17:14 +00001281 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1282 /* We are trying for an exclusive lock but another thread in this
1283 ** same process is still holding a shared lock. */
1284 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001285 }else{
drh3cde3bb2004-06-12 02:17:14 +00001286 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001287 ** assumed that there is a SHARED or greater lock on the file
1288 ** already.
1289 */
drh054889e2005-11-30 03:20:31 +00001290 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001291 lock.l_type = F_WRLCK;
1292 switch( locktype ){
1293 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001294 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001295 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001296 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001297 lock.l_start = SHARED_FIRST;
1298 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001299 break;
1300 default:
1301 assert(0);
1302 }
drh054889e2005-11-30 03:20:31 +00001303 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001304 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001305 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1306 }
drhbbd42a62004-05-22 17:41:58 +00001307 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001308
danielk1977ecb2a962004-06-02 06:30:16 +00001309 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001310 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001311 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001312 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001313 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001314 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001315 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001316
1317end_lock:
danielk1977b4b47412007-08-17 15:53:36 +00001318 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001319 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001320 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001321 return rc;
1322}
1323
1324/*
drh054889e2005-11-30 03:20:31 +00001325** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001326** must be either NO_LOCK or SHARED_LOCK.
1327**
1328** If the locking level of the file descriptor is already at or below
1329** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001330*/
danielk197762079062007-08-15 17:08:46 +00001331static int unixUnlock(sqlite3_file *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001332 struct lockInfo *pLock;
1333 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001334 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001335 unixFile *pFile = (unixFile*)id;
drh1aa5af12008-03-07 19:51:14 +00001336 int h;
drha6abd042004-06-09 17:37:22 +00001337
drh054889e2005-11-30 03:20:31 +00001338 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001339 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001340 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001341
1342 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001343 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001344 return SQLITE_OK;
1345 }
drhf1a221e2006-01-15 17:27:17 +00001346 if( CHECK_THREADID(pFile) ){
1347 return SQLITE_MISUSE;
1348 }
danielk1977b4b47412007-08-17 15:53:36 +00001349 enterMutex();
drh1aa5af12008-03-07 19:51:14 +00001350 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001351 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001352 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001353 if( pFile->locktype>SHARED_LOCK ){
1354 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001355 SimulateIOErrorBenign(1);
1356 SimulateIOError( h=(-1) )
1357 SimulateIOErrorBenign(0);
drh9c105bb2004-10-02 20:38:28 +00001358 if( locktype==SHARED_LOCK ){
1359 lock.l_type = F_RDLCK;
1360 lock.l_whence = SEEK_SET;
1361 lock.l_start = SHARED_FIRST;
1362 lock.l_len = SHARED_SIZE;
drh1aa5af12008-03-07 19:51:14 +00001363 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drh4ac285a2006-09-15 07:28:50 +00001364 rc = SQLITE_IOERR_RDLOCK;
drh9c105bb2004-10-02 20:38:28 +00001365 }
1366 }
drhbbd42a62004-05-22 17:41:58 +00001367 lock.l_type = F_UNLCK;
1368 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001369 lock.l_start = PENDING_BYTE;
1370 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001371 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001372 pLock->locktype = SHARED_LOCK;
1373 }else{
drh1aa5af12008-03-07 19:51:14 +00001374 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001375 }
drhbbd42a62004-05-22 17:41:58 +00001376 }
drha6abd042004-06-09 17:37:22 +00001377 if( locktype==NO_LOCK ){
1378 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001379
drha6abd042004-06-09 17:37:22 +00001380 /* Decrement the shared lock counter. Release the lock using an
1381 ** OS call only when all threads in this same process have released
1382 ** the lock.
1383 */
1384 pLock->cnt--;
1385 if( pLock->cnt==0 ){
1386 lock.l_type = F_UNLCK;
1387 lock.l_whence = SEEK_SET;
1388 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001389 SimulateIOErrorBenign(1);
1390 SimulateIOError( h=(-1) )
1391 SimulateIOErrorBenign(0);
1392 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001393 pLock->locktype = NO_LOCK;
1394 }else{
drh1aa5af12008-03-07 19:51:14 +00001395 rc = SQLITE_IOERR_UNLOCK;
1396 pLock->cnt = 1;
drh2b4b5962005-06-15 17:47:55 +00001397 }
drha6abd042004-06-09 17:37:22 +00001398 }
1399
drhbbd42a62004-05-22 17:41:58 +00001400 /* Decrement the count of locks against this same file. When the
1401 ** count reaches zero, close any other file descriptors whose close
1402 ** was deferred because of outstanding locks.
1403 */
drh1aa5af12008-03-07 19:51:14 +00001404 if( rc==SQLITE_OK ){
1405 pOpen = pFile->pOpen;
1406 pOpen->nLock--;
1407 assert( pOpen->nLock>=0 );
1408 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1409 int i;
1410 for(i=0; i<pOpen->nPending; i++){
1411 close(pOpen->aPending[i]);
1412 }
1413 free(pOpen->aPending);
1414 pOpen->nPending = 0;
1415 pOpen->aPending = 0;
drhbbd42a62004-05-22 17:41:58 +00001416 }
drhbbd42a62004-05-22 17:41:58 +00001417 }
1418 }
danielk1977b4b47412007-08-17 15:53:36 +00001419 leaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001420 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001421 return rc;
drhbbd42a62004-05-22 17:41:58 +00001422}
1423
1424/*
danielk1977e3026632004-06-22 11:29:02 +00001425** Close a file.
1426*/
danielk197762079062007-08-15 17:08:46 +00001427static int unixClose(sqlite3_file *id){
1428 unixFile *pFile = (unixFile *)id;
1429 if( !pFile ) return SQLITE_OK;
1430 unixUnlock(id, NO_LOCK);
1431 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1432 pFile->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00001433 enterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001434
danielk197762079062007-08-15 17:08:46 +00001435 if( pFile->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001436 /* If there are outstanding locks, do not actually close the file just
1437 ** yet because that would clear those locks. Instead, add the file
1438 ** descriptor to pOpen->aPending. It will be automatically closed when
1439 ** the last lock is cleared.
1440 */
1441 int *aNew;
danielk197762079062007-08-15 17:08:46 +00001442 struct openCnt *pOpen = pFile->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001443 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001444 if( aNew==0 ){
1445 /* If a malloc fails, just leak the file descriptor */
1446 }else{
1447 pOpen->aPending = aNew;
danielk197762079062007-08-15 17:08:46 +00001448 pOpen->aPending[pOpen->nPending] = pFile->h;
drhad81e872005-08-21 21:45:01 +00001449 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001450 }
1451 }else{
1452 /* There are no outstanding locks so we can close the file immediately */
danielk197762079062007-08-15 17:08:46 +00001453 close(pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001454 }
danielk197762079062007-08-15 17:08:46 +00001455 releaseLockInfo(pFile->pLock);
1456 releaseOpenCnt(pFile->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001457
danielk1977b4b47412007-08-17 15:53:36 +00001458 leaveMutex();
danielk197762079062007-08-15 17:08:46 +00001459 OSTRACE2("CLOSE %-3d\n", pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001460 OpenCounter(-1);
danielk1977b4b47412007-08-17 15:53:36 +00001461 memset(pFile, 0, sizeof(unixFile));
drh02afc862006-01-20 18:10:57 +00001462 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001463}
1464
drhbfe66312006-10-03 17:40:40 +00001465
1466#ifdef SQLITE_ENABLE_LOCKING_STYLE
1467#pragma mark AFP Support
1468
1469/*
1470 ** The afpLockingContext structure contains all afp lock specific state
1471 */
1472typedef struct afpLockingContext afpLockingContext;
1473struct afpLockingContext {
drh1aa5af12008-03-07 19:51:14 +00001474 unsigned long long sharedLockByte;
drh308aa322008-03-07 20:14:38 +00001475 const char *filePath;
drhbfe66312006-10-03 17:40:40 +00001476};
1477
1478struct ByteRangeLockPB2
1479{
1480 unsigned long long offset; /* offset to first byte to lock */
1481 unsigned long long length; /* nbr of bytes to lock */
1482 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
1483 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
1484 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
1485 int fd; /* file desc to assoc this lock with */
1486};
1487
drhfd131da2007-08-07 17:13:03 +00001488#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00001489
danielk1977ad94b582007-08-20 06:44:22 +00001490/*
1491** Return 0 on success, 1 on failure. To match the behavior of the
1492** normal posix file locking (used in unixLock for example), we should
1493** provide 'richer' return codes - specifically to differentiate between
1494** 'file busy' and 'file system error' results.
1495*/
1496static int _AFPFSSetLock(
1497 const char *path,
1498 int fd,
1499 unsigned long long offset,
1500 unsigned long long length,
1501 int setLockFlag
1502){
drhfd131da2007-08-07 17:13:03 +00001503 struct ByteRangeLockPB2 pb;
drhbfe66312006-10-03 17:40:40 +00001504 int err;
1505
1506 pb.unLockFlag = setLockFlag ? 0 : 1;
1507 pb.startEndFlag = 0;
1508 pb.offset = offset;
1509 pb.length = length;
1510 pb.fd = fd;
drh4f0c5872007-03-26 22:05:01 +00001511 OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
drhbfe66312006-10-03 17:40:40 +00001512 (setLockFlag?"ON":"OFF"), fd, offset, length);
1513 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
1514 if ( err==-1 ) {
drh4f0c5872007-03-26 22:05:01 +00001515 OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno,
drhbfe66312006-10-03 17:40:40 +00001516 strerror(errno));
drh3b62b2f2007-06-08 18:27:03 +00001517 return 1; /* error */
drhbfe66312006-10-03 17:40:40 +00001518 } else {
1519 return 0;
1520 }
1521}
1522
1523/*
1524 ** This routine checks if there is a RESERVED lock held on the specified
1525 ** file by this or any other process. If such a lock is held, return
1526 ** non-zero. If the file is unlocked or holds only SHARED locks, then
1527 ** return zero.
1528 */
danielk1977ad94b582007-08-20 06:44:22 +00001529static int afpUnixCheckReservedLock(sqlite3_file *id){
drhbfe66312006-10-03 17:40:40 +00001530 int r = 0;
1531 unixFile *pFile = (unixFile*)id;
1532
1533 assert( pFile );
1534 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1535
1536 /* Check if a thread in this process holds such a lock */
1537 if( pFile->locktype>SHARED_LOCK ){
1538 r = 1;
1539 }
1540
1541 /* Otherwise see if some other process holds it.
1542 */
1543 if ( !r ) {
drh3b62b2f2007-06-08 18:27:03 +00001544 /* lock the byte */
drhbfe66312006-10-03 17:40:40 +00001545 int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1546 if (failed) {
1547 /* if we failed to get the lock then someone else must have it */
1548 r = 1;
1549 } else {
1550 /* if we succeeded in taking the reserved lock, unlock it to restore
1551 ** the original state */
1552 _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
1553 }
1554 }
drh4f0c5872007-03-26 22:05:01 +00001555 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
drhbfe66312006-10-03 17:40:40 +00001556
1557 return r;
1558}
1559
1560/* AFP-style locking following the behavior of unixLock, see the unixLock
1561** function comments for details of lock management. */
drh339eb0b2008-03-07 15:34:11 +00001562static int afpUnixLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00001563 int rc = SQLITE_OK;
1564 unixFile *pFile = (unixFile*)id;
1565 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1566 int gotPendingLock = 0;
1567
1568 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001569 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00001570 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
1571
drhbfe66312006-10-03 17:40:40 +00001572 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00001573 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
1574 ** enterMutex() hasn't been called yet.
1575 */
drhbfe66312006-10-03 17:40:40 +00001576 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001577 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001578 locktypeName(locktype));
1579 return SQLITE_OK;
1580 }
1581
1582 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00001583 */
drhbfe66312006-10-03 17:40:40 +00001584 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
1585 assert( locktype!=PENDING_LOCK );
1586 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1587
1588 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00001589 */
danielk1977b4b47412007-08-17 15:53:36 +00001590 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001591
1592 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00001593 */
drhbfe66312006-10-03 17:40:40 +00001594 rc = transferOwnership(pFile);
1595 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001596 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001597 return rc;
1598 }
1599
1600 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00001601 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1602 ** be released.
1603 */
drhbfe66312006-10-03 17:40:40 +00001604 if( locktype==SHARED_LOCK
1605 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00001606 ){
1607 int failed;
1608 failed = _AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00001609 if (failed) {
1610 rc = SQLITE_BUSY;
1611 goto afp_end_lock;
1612 }
1613 }
1614
1615 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00001616 ** operating system calls for the specified lock.
1617 */
drhbfe66312006-10-03 17:40:40 +00001618 if( locktype==SHARED_LOCK ){
1619 int lk, failed;
1620 int tries = 0;
1621
1622 /* Now get the read-lock */
1623 /* note that the quality of the randomness doesn't matter that much */
1624 lk = random();
1625 context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
1626 failed = _AFPFSSetLock(context->filePath, pFile->h,
1627 SHARED_FIRST+context->sharedLockByte, 1, 1);
1628
1629 /* Drop the temporary PENDING lock */
1630 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
1631 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1632 goto afp_end_lock;
1633 }
1634
1635 if( failed ){
1636 rc = SQLITE_BUSY;
1637 } else {
1638 pFile->locktype = SHARED_LOCK;
1639 }
1640 }else{
1641 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1642 ** assumed that there is a SHARED or greater lock on the file
1643 ** already.
1644 */
1645 int failed = 0;
1646 assert( 0!=pFile->locktype );
1647 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
1648 /* Acquire a RESERVED lock */
1649 failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1650 }
1651 if (!failed && locktype == EXCLUSIVE_LOCK) {
1652 /* Acquire an EXCLUSIVE lock */
1653
1654 /* Remove the shared lock before trying the range. we'll need to
1655 ** reestablish the shared lock if we can't get the afpUnixUnlock
1656 */
1657 if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1658 context->sharedLockByte, 1, 0)) {
1659 /* now attemmpt to get the exclusive lock range */
1660 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1661 SHARED_SIZE, 1);
1662 if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1663 context->sharedLockByte, 1, 1)) {
1664 rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
1665 }
1666 } else {
1667 /* */
1668 rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
1669 }
1670 }
1671 if( failed && rc == SQLITE_OK){
1672 rc = SQLITE_BUSY;
1673 }
1674 }
1675
1676 if( rc==SQLITE_OK ){
1677 pFile->locktype = locktype;
1678 }else if( locktype==EXCLUSIVE_LOCK ){
1679 pFile->locktype = PENDING_LOCK;
1680 }
1681
1682afp_end_lock:
drh339eb0b2008-03-07 15:34:11 +00001683 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001684 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00001685 rc==SQLITE_OK ? "ok" : "failed");
1686 return rc;
1687}
1688
1689/*
drh339eb0b2008-03-07 15:34:11 +00001690** Lower the locking level on file descriptor pFile to locktype. locktype
1691** must be either NO_LOCK or SHARED_LOCK.
1692**
1693** If the locking level of the file descriptor is already at or below
1694** the requested locking level, this routine is a no-op.
1695*/
danielk1977ad94b582007-08-20 06:44:22 +00001696static int afpUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001697 struct flock lock;
1698 int rc = SQLITE_OK;
1699 unixFile *pFile = (unixFile*)id;
1700 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1701
1702 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001703 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00001704 pFile->locktype, getpid());
1705
1706 assert( locktype<=SHARED_LOCK );
1707 if( pFile->locktype<=locktype ){
1708 return SQLITE_OK;
1709 }
1710 if( CHECK_THREADID(pFile) ){
1711 return SQLITE_MISUSE;
1712 }
danielk1977b4b47412007-08-17 15:53:36 +00001713 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001714 if( pFile->locktype>SHARED_LOCK ){
1715 if( locktype==SHARED_LOCK ){
1716 int failed = 0;
1717
1718 /* unlock the exclusive range - then re-establish the shared lock */
1719 if (pFile->locktype==EXCLUSIVE_LOCK) {
1720 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1721 SHARED_SIZE, 0);
1722 if (!failed) {
1723 /* successfully removed the exclusive lock */
1724 if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
1725 context->sharedLockByte, 1, 1)) {
1726 /* failed to re-establish our shared lock */
1727 rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
1728 }
1729 } else {
1730 /* This should never happen - failed to unlock the exclusive range */
1731 rc = SQLITE_IOERR_UNLOCK;
1732 }
1733 }
1734 }
1735 if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
1736 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
1737 /* failed to release the pending lock */
1738 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1739 }
1740 }
1741 if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
1742 if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
1743 /* failed to release the reserved lock */
1744 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1745 }
1746 }
1747 }
1748 if( locktype==NO_LOCK ){
1749 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1750 SHARED_FIRST + context->sharedLockByte, 1, 0);
1751 if (failed) {
1752 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1753 }
1754 }
1755 if (rc == SQLITE_OK)
1756 pFile->locktype = locktype;
danielk1977b4b47412007-08-17 15:53:36 +00001757 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001758 return rc;
1759}
1760
1761/*
drh339eb0b2008-03-07 15:34:11 +00001762** Close a file & cleanup AFP specific locking context
1763*/
danielk1977ad94b582007-08-20 06:44:22 +00001764static int afpUnixClose(sqlite3_file *id) {
drh218c5082008-03-07 00:27:10 +00001765 unixFile *pFile = (unixFile*)id;
danielk1977ad94b582007-08-20 06:44:22 +00001766
1767 if( !pFile ) return SQLITE_OK;
drh218c5082008-03-07 00:27:10 +00001768 afpUnixUnlock(id, NO_LOCK);
drh339eb0b2008-03-07 15:34:11 +00001769 sqlite3_free(pFile->lockingContext);
danielk1977ad94b582007-08-20 06:44:22 +00001770 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1771 pFile->dirfd = -1;
drh1aa5af12008-03-07 19:51:14 +00001772 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001773 close(pFile->h);
drh1aa5af12008-03-07 19:51:14 +00001774 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001775 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001776 OpenCounter(-1);
drh218c5082008-03-07 00:27:10 +00001777 memset(pFile, 0, sizeof(unixFile));
drhbfe66312006-10-03 17:40:40 +00001778 return SQLITE_OK;
1779}
1780
1781
1782#pragma mark flock() style locking
1783
1784/*
drh339eb0b2008-03-07 15:34:11 +00001785** The flockLockingContext is not used
1786*/
drhbfe66312006-10-03 17:40:40 +00001787typedef void flockLockingContext;
1788
drh339eb0b2008-03-07 15:34:11 +00001789static int flockUnixCheckReservedLock(sqlite3_file *id){
drhbfe66312006-10-03 17:40:40 +00001790 unixFile *pFile = (unixFile*)id;
1791
1792 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00001793 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00001794 } else {
drh3b62b2f2007-06-08 18:27:03 +00001795 /* attempt to get the lock */
drhbfe66312006-10-03 17:40:40 +00001796 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1797 if (!rc) {
drh3b62b2f2007-06-08 18:27:03 +00001798 /* got the lock, unlock it */
drhbfe66312006-10-03 17:40:40 +00001799 flock(pFile->h, LOCK_UN);
drh3b62b2f2007-06-08 18:27:03 +00001800 return 0; /* no one has it reserved */
drhbfe66312006-10-03 17:40:40 +00001801 }
drh3b62b2f2007-06-08 18:27:03 +00001802 return 1; /* someone else might have it reserved */
drhbfe66312006-10-03 17:40:40 +00001803 }
1804}
1805
danielk1977ad94b582007-08-20 06:44:22 +00001806static int flockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001807 unixFile *pFile = (unixFile*)id;
1808
drh3b62b2f2007-06-08 18:27:03 +00001809 /* if we already have a lock, it is exclusive.
1810 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00001811 if (pFile->locktype > NO_LOCK) {
1812 pFile->locktype = locktype;
1813 return SQLITE_OK;
1814 }
1815
drh3b62b2f2007-06-08 18:27:03 +00001816 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00001817 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1818 if (rc) {
drh3b62b2f2007-06-08 18:27:03 +00001819 /* didn't get, must be busy */
drhbfe66312006-10-03 17:40:40 +00001820 return SQLITE_BUSY;
1821 } else {
drh3b62b2f2007-06-08 18:27:03 +00001822 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00001823 pFile->locktype = locktype;
1824 return SQLITE_OK;
1825 }
1826}
1827
danielk1977ad94b582007-08-20 06:44:22 +00001828static int flockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001829 unixFile *pFile = (unixFile*)id;
1830
1831 assert( locktype<=SHARED_LOCK );
1832
drh3b62b2f2007-06-08 18:27:03 +00001833 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00001834 if( pFile->locktype==locktype ){
1835 return SQLITE_OK;
1836 }
1837
drh3b62b2f2007-06-08 18:27:03 +00001838 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00001839 if (locktype==SHARED_LOCK) {
1840 pFile->locktype = locktype;
1841 return SQLITE_OK;
1842 }
1843
drh3b62b2f2007-06-08 18:27:03 +00001844 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00001845 int rc = flock(pFile->h, LOCK_UN);
1846 if (rc)
1847 return SQLITE_IOERR_UNLOCK;
1848 else {
1849 pFile->locktype = NO_LOCK;
1850 return SQLITE_OK;
1851 }
1852}
1853
1854/*
drh339eb0b2008-03-07 15:34:11 +00001855** Close a file.
1856*/
drh218c5082008-03-07 00:27:10 +00001857static int flockUnixClose(sqlite3_file *id) {
1858 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00001859
danielk1977ad94b582007-08-20 06:44:22 +00001860 if( !pFile ) return SQLITE_OK;
drh218c5082008-03-07 00:27:10 +00001861 flockUnixUnlock(id, NO_LOCK);
drhbfe66312006-10-03 17:40:40 +00001862
danielk1977ad94b582007-08-20 06:44:22 +00001863 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1864 pFile->dirfd = -1;
drh1aa5af12008-03-07 19:51:14 +00001865
1866 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001867 close(pFile->h);
drh1aa5af12008-03-07 19:51:14 +00001868 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001869 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001870 OpenCounter(-1);
drh218c5082008-03-07 00:27:10 +00001871 memset(pFile, 0, sizeof(unixFile));
drhbfe66312006-10-03 17:40:40 +00001872 return SQLITE_OK;
1873}
1874
1875#pragma mark Old-School .lock file based locking
1876
1877/*
drh339eb0b2008-03-07 15:34:11 +00001878** The dotlockLockingContext structure contains all dotlock (.lock) lock
1879** specific state
1880*/
drhbfe66312006-10-03 17:40:40 +00001881typedef struct dotlockLockingContext dotlockLockingContext;
1882struct dotlockLockingContext {
1883 char *lockPath;
1884};
1885
1886
danielk1977ad94b582007-08-20 06:44:22 +00001887static int dotlockUnixCheckReservedLock(sqlite3_file *id) {
drhbfe66312006-10-03 17:40:40 +00001888 unixFile *pFile = (unixFile*)id;
drh339eb0b2008-03-07 15:34:11 +00001889 dotlockLockingContext *context;
1890
1891 context = (dotlockLockingContext*)pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00001892 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00001893 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00001894 } else {
1895 struct stat statBuf;
drh339eb0b2008-03-07 15:34:11 +00001896 if (lstat(context->lockPath,&statBuf) == 0){
drh3b62b2f2007-06-08 18:27:03 +00001897 /* file exists, someone else has the lock */
drhbfe66312006-10-03 17:40:40 +00001898 return 1;
drh339eb0b2008-03-07 15:34:11 +00001899 }else{
drh3b62b2f2007-06-08 18:27:03 +00001900 /* file does not exist, we could have it if we want it */
drhbfe66312006-10-03 17:40:40 +00001901 return 0;
drh339eb0b2008-03-07 15:34:11 +00001902 }
drhbfe66312006-10-03 17:40:40 +00001903 }
1904}
1905
danielk1977ad94b582007-08-20 06:44:22 +00001906static int dotlockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001907 unixFile *pFile = (unixFile*)id;
drh339eb0b2008-03-07 15:34:11 +00001908 dotlockLockingContext *context;
1909 int fd;
1910
1911 context = (dotlockLockingContext*)pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00001912
drh3b62b2f2007-06-08 18:27:03 +00001913 /* if we already have a lock, it is exclusive.
1914 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00001915 if (pFile->locktype > NO_LOCK) {
1916 pFile->locktype = locktype;
1917
1918 /* Always update the timestamp on the old file */
1919 utimes(context->lockPath,NULL);
1920 return SQLITE_OK;
1921 }
1922
drh3b62b2f2007-06-08 18:27:03 +00001923 /* check to see if lock file already exists */
drhbfe66312006-10-03 17:40:40 +00001924 struct stat statBuf;
1925 if (lstat(context->lockPath,&statBuf) == 0){
drh3b62b2f2007-06-08 18:27:03 +00001926 return SQLITE_BUSY; /* it does, busy */
drhbfe66312006-10-03 17:40:40 +00001927 }
1928
drh3b62b2f2007-06-08 18:27:03 +00001929 /* grab an exclusive lock */
drh339eb0b2008-03-07 15:34:11 +00001930 fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
1931 if( fd<0 ){
drh3b62b2f2007-06-08 18:27:03 +00001932 /* failed to open/create the file, someone else may have stolen the lock */
drhbfe66312006-10-03 17:40:40 +00001933 return SQLITE_BUSY;
1934 }
1935 close(fd);
1936
drh3b62b2f2007-06-08 18:27:03 +00001937 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00001938 pFile->locktype = locktype;
1939 return SQLITE_OK;
1940}
1941
danielk1977ad94b582007-08-20 06:44:22 +00001942static int dotlockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001943 unixFile *pFile = (unixFile*)id;
drh339eb0b2008-03-07 15:34:11 +00001944 dotlockLockingContext *context;
1945
1946 context = (dotlockLockingContext*)pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00001947
1948 assert( locktype<=SHARED_LOCK );
1949
drh3b62b2f2007-06-08 18:27:03 +00001950 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00001951 if( pFile->locktype==locktype ){
1952 return SQLITE_OK;
1953 }
1954
drh3b62b2f2007-06-08 18:27:03 +00001955 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00001956 if (locktype==SHARED_LOCK) {
1957 pFile->locktype = locktype;
1958 return SQLITE_OK;
1959 }
1960
drh3b62b2f2007-06-08 18:27:03 +00001961 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00001962 unlink(context->lockPath);
1963 pFile->locktype = NO_LOCK;
1964 return SQLITE_OK;
1965}
1966
1967/*
1968 ** Close a file.
1969 */
danielk1977ad94b582007-08-20 06:44:22 +00001970static int dotlockUnixClose(sqlite3_file *id) {
1971 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00001972
danielk1977ad94b582007-08-20 06:44:22 +00001973 if( !pFile ) return SQLITE_OK;
drh218c5082008-03-07 00:27:10 +00001974 dotlockUnixUnlock(id, NO_LOCK);
drh339eb0b2008-03-07 15:34:11 +00001975 sqlite3_free(pFile->lockingContext);
danielk1977ad94b582007-08-20 06:44:22 +00001976 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1977 pFile->dirfd = -1;
drh1aa5af12008-03-07 19:51:14 +00001978 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001979 close(pFile->h);
drh1aa5af12008-03-07 19:51:14 +00001980 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00001981 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001982 OpenCounter(-1);
drh218c5082008-03-07 00:27:10 +00001983 memset(pFile, 0, sizeof(unixFile));
drhbfe66312006-10-03 17:40:40 +00001984 return SQLITE_OK;
1985}
1986
1987
1988#pragma mark No locking
1989
1990/*
drh339eb0b2008-03-07 15:34:11 +00001991** The nolockLockingContext is void
1992*/
drhbfe66312006-10-03 17:40:40 +00001993typedef void nolockLockingContext;
1994
danielk1977ad94b582007-08-20 06:44:22 +00001995static int nolockUnixCheckReservedLock(sqlite3_file *id) {
drhbfe66312006-10-03 17:40:40 +00001996 return 0;
1997}
1998
danielk1977ad94b582007-08-20 06:44:22 +00001999static int nolockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002000 return SQLITE_OK;
2001}
2002
danielk1977ad94b582007-08-20 06:44:22 +00002003static int nolockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002004 return SQLITE_OK;
2005}
2006
2007/*
drh339eb0b2008-03-07 15:34:11 +00002008** Close a file.
2009*/
danielk1977ad94b582007-08-20 06:44:22 +00002010static int nolockUnixClose(sqlite3_file *id) {
2011 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00002012
danielk1977ad94b582007-08-20 06:44:22 +00002013 if( !pFile ) return SQLITE_OK;
2014 if( pFile->dirfd>=0 ) close(pFile->dirfd);
2015 pFile->dirfd = -1;
drh1aa5af12008-03-07 19:51:14 +00002016 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00002017 close(pFile->h);
drh1aa5af12008-03-07 19:51:14 +00002018 leaveMutex();
danielk1977ad94b582007-08-20 06:44:22 +00002019 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00002020 OpenCounter(-1);
drh218c5082008-03-07 00:27:10 +00002021 memset(pFile, 0, sizeof(unixFile));
drhbfe66312006-10-03 17:40:40 +00002022 return SQLITE_OK;
2023}
2024
2025#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2026
danielk1977ad94b582007-08-20 06:44:22 +00002027
danielk1977e3026632004-06-22 11:29:02 +00002028/*
drh9e33c2c2007-08-31 18:34:59 +00002029** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00002030*/
drhcc6bb3e2007-08-31 16:11:35 +00002031static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00002032 switch( op ){
2033 case SQLITE_FCNTL_LOCKSTATE: {
2034 *(int*)pArg = ((unixFile*)id)->locktype;
2035 return SQLITE_OK;
2036 }
2037 }
drhcc6bb3e2007-08-31 16:11:35 +00002038 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00002039}
2040
2041/*
danielk1977a3d4c882007-03-23 10:08:38 +00002042** Return the sector size in bytes of the underlying block device for
2043** the specified file. This is almost always 512 bytes, but may be
2044** larger for some devices.
2045**
2046** SQLite code assumes this function cannot fail. It also assumes that
2047** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00002048** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00002049** same for both.
2050*/
danielk197762079062007-08-15 17:08:46 +00002051static int unixSectorSize(sqlite3_file *id){
drh3ceeb752007-03-29 18:19:52 +00002052 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00002053}
2054
danielk197790949c22007-08-17 16:50:38 +00002055/*
2056** Return the device characteristics for the file. This is always 0.
2057*/
danielk197762079062007-08-15 17:08:46 +00002058static int unixDeviceCharacteristics(sqlite3_file *id){
2059 return 0;
2060}
2061
danielk1977a3d4c882007-03-23 10:08:38 +00002062/*
danielk1977ad94b582007-08-20 06:44:22 +00002063** This vector defines all the methods that can operate on an sqlite3_file
drh054889e2005-11-30 03:20:31 +00002064** for unix.
drh9c06c952005-11-26 00:25:00 +00002065*/
danielk197762079062007-08-15 17:08:46 +00002066static const sqlite3_io_methods sqlite3UnixIoMethod = {
2067 1, /* iVersion */
drh9c06c952005-11-26 00:25:00 +00002068 unixClose,
2069 unixRead,
2070 unixWrite,
drh9c06c952005-11-26 00:25:00 +00002071 unixTruncate,
drh054889e2005-11-30 03:20:31 +00002072 unixSync,
drh054889e2005-11-30 03:20:31 +00002073 unixFileSize,
2074 unixLock,
2075 unixUnlock,
drh054889e2005-11-30 03:20:31 +00002076 unixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002077 unixFileControl,
danielk1977a3d4c882007-03-23 10:08:38 +00002078 unixSectorSize,
danielk197762079062007-08-15 17:08:46 +00002079 unixDeviceCharacteristics
drh9c06c952005-11-26 00:25:00 +00002080};
2081
drhbfe66312006-10-03 17:40:40 +00002082#ifdef SQLITE_ENABLE_LOCKING_STYLE
drh054889e2005-11-30 03:20:31 +00002083/*
danielk1977ad94b582007-08-20 06:44:22 +00002084** This vector defines all the methods that can operate on an sqlite3_file
2085** for unix with AFP style file locking.
2086*/
2087static const sqlite3_io_methods sqlite3AFPLockingUnixIoMethod = {
2088 1, /* iVersion */
drh218c5082008-03-07 00:27:10 +00002089 afpUnixClose,
drhbfe66312006-10-03 17:40:40 +00002090 unixRead,
2091 unixWrite,
drhbfe66312006-10-03 17:40:40 +00002092 unixTruncate,
2093 unixSync,
danielk1977ad94b582007-08-20 06:44:22 +00002094 unixFileSize,
2095 afpUnixLock,
2096 afpUnixUnlock,
2097 afpUnixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002098 unixFileControl,
danielk1977ad94b582007-08-20 06:44:22 +00002099 unixSectorSize,
2100 unixDeviceCharacteristics
2101};
2102
2103/*
2104** This vector defines all the methods that can operate on an sqlite3_file
2105** for unix with flock() style file locking.
2106*/
2107static const sqlite3_io_methods sqlite3FlockLockingUnixIoMethod = {
2108 1, /* iVersion */
2109 flockUnixClose,
2110 unixRead,
2111 unixWrite,
2112 unixTruncate,
2113 unixSync,
2114 unixFileSize,
2115 flockUnixLock,
2116 flockUnixUnlock,
2117 flockUnixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002118 unixFileControl,
danielk1977ad94b582007-08-20 06:44:22 +00002119 unixSectorSize,
2120 unixDeviceCharacteristics
2121};
2122
2123/*
2124** This vector defines all the methods that can operate on an sqlite3_file
2125** for unix with dotlock style file locking.
2126*/
2127static const sqlite3_io_methods sqlite3DotlockLockingUnixIoMethod = {
2128 1, /* iVersion */
2129 dotlockUnixClose,
2130 unixRead,
2131 unixWrite,
2132 unixTruncate,
2133 unixSync,
2134 unixFileSize,
2135 dotlockUnixLock,
2136 dotlockUnixUnlock,
2137 dotlockUnixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002138 unixFileControl,
danielk1977ad94b582007-08-20 06:44:22 +00002139 unixSectorSize,
2140 unixDeviceCharacteristics
2141};
2142
2143/*
2144** This vector defines all the methods that can operate on an sqlite3_file
drh339eb0b2008-03-07 15:34:11 +00002145** for unix with nolock style file locking.
danielk1977ad94b582007-08-20 06:44:22 +00002146*/
2147static const sqlite3_io_methods sqlite3NolockLockingUnixIoMethod = {
2148 1, /* iVersion */
2149 nolockUnixClose,
2150 unixRead,
2151 unixWrite,
2152 unixTruncate,
2153 unixSync,
drhbfe66312006-10-03 17:40:40 +00002154 unixFileSize,
2155 nolockUnixLock,
2156 nolockUnixUnlock,
drhbfe66312006-10-03 17:40:40 +00002157 nolockUnixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002158 unixFileControl,
danielk1977a3d4c882007-03-23 10:08:38 +00002159 unixSectorSize,
danielk1977ad94b582007-08-20 06:44:22 +00002160 unixDeviceCharacteristics
drhbfe66312006-10-03 17:40:40 +00002161};
2162
2163#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2164
2165/*
2166** Allocate memory for a new unixFile and initialize that unixFile.
2167** Write a pointer to the new unixFile into *pId.
2168** If we run out of memory, close the file and return an error.
drh054889e2005-11-30 03:20:31 +00002169*/
drhbfe66312006-10-03 17:40:40 +00002170#ifdef SQLITE_ENABLE_LOCKING_STYLE
2171/*
danielk1977ad94b582007-08-20 06:44:22 +00002172** When locking extensions are enabled, the filepath and locking style
2173** are needed to determine the unixFile pMethod to use for locking operations.
2174** The locking-style specific lockingContext data structure is created
2175** and assigned here also.
2176*/
2177static int fillInUnixFile(
drhbfe66312006-10-03 17:40:40 +00002178 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00002179 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00002180 sqlite3_file *pId, /* Write to the unixFile structure here */
2181 const char *zFilename /* Name of the file being opened */
drhbfe66312006-10-03 17:40:40 +00002182){
aswift108bc322006-10-11 17:19:46 +00002183 sqlite3LockingStyle lockingStyle;
danielk1977ad94b582007-08-20 06:44:22 +00002184 unixFile *pNew = (unixFile *)pId;
drhbfe66312006-10-03 17:40:40 +00002185 int rc;
2186
drh218c5082008-03-07 00:27:10 +00002187#ifdef FD_CLOEXEC
2188 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
2189#endif
2190
aswift448aa6f2006-11-11 01:31:58 +00002191 lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
drh339eb0b2008-03-07 15:34:11 +00002192 if ( lockingStyle==posixLockingStyle ){
danielk1977b4b47412007-08-17 15:53:36 +00002193 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00002194 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
danielk1977b4b47412007-08-17 15:53:36 +00002195 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002196 if( rc ){
drh218c5082008-03-07 00:27:10 +00002197 if( dirfd>=0 ) close(dirfd);
drhbfe66312006-10-03 17:40:40 +00002198 close(h);
drh65594042008-05-05 16:56:34 +00002199 return rc;
drhbfe66312006-10-03 17:40:40 +00002200 }
2201 } else {
drh3b62b2f2007-06-08 18:27:03 +00002202 /* pLock and pOpen are only used for posix advisory locking */
danielk1977ad94b582007-08-20 06:44:22 +00002203 pNew->pLock = NULL;
2204 pNew->pOpen = NULL;
drhbfe66312006-10-03 17:40:40 +00002205 }
drh218c5082008-03-07 00:27:10 +00002206
2207 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00002208 pNew->dirfd = -1;
2209 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00002210 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00002211 SET_THREADID(pNew);
drh218c5082008-03-07 00:27:10 +00002212
2213 switch(lockingStyle) {
2214 case afpLockingStyle: {
2215 /* afp locking uses the file path so it needs to be included in
2216 ** the afpLockingContext */
drh339eb0b2008-03-07 15:34:11 +00002217 afpLockingContext *context;
drh218c5082008-03-07 00:27:10 +00002218 pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
drh339eb0b2008-03-07 15:34:11 +00002219 pNew->lockingContext = context = sqlite3_malloc( sizeof(*context) );
2220 if( context==0 ){
2221 close(h);
2222 if( dirfd>=0 ) close(dirfd);
2223 return SQLITE_NOMEM;
2224 }
2225
2226 /* NB: zFilename exists and remains valid until the file is closed
2227 ** according to requirement F11141. So we do not need to make a
2228 ** copy of the filename. */
2229 context->filePath = zFilename;
drh218c5082008-03-07 00:27:10 +00002230 srandomdev();
2231 break;
drhbfe66312006-10-03 17:40:40 +00002232 }
drh218c5082008-03-07 00:27:10 +00002233 case flockLockingStyle:
2234 /* flock locking doesn't need additional lockingContext information */
2235 pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
2236 break;
2237 case dotlockLockingStyle: {
2238 /* dotlock locking uses the file path so it needs to be included in
drh339eb0b2008-03-07 15:34:11 +00002239 ** the dotlockLockingContext */
2240 dotlockLockingContext *context;
drh218c5082008-03-07 00:27:10 +00002241 int nFilename;
drh339eb0b2008-03-07 15:34:11 +00002242 nFilename = strlen(zFilename);
drh218c5082008-03-07 00:27:10 +00002243 pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
drh339eb0b2008-03-07 15:34:11 +00002244 pNew->lockingContext = context =
2245 sqlite3_malloc( sizeof(*context) + nFilename + 6 );
2246 if( context==0 ){
2247 close(h);
2248 if( dirfd>=0 ) close(dirfd);
2249 return SQLITE_NOMEM;
2250 }
2251 context->lockPath = (char*)&context[1];
2252 sqlite3_snprintf(nFilename, context->lockPath,
2253 "%s.lock", zFilename);
drh218c5082008-03-07 00:27:10 +00002254 break;
2255 }
2256 case posixLockingStyle:
2257 /* posix locking doesn't need additional lockingContext information */
2258 pNew->pMethod = &sqlite3UnixIoMethod;
2259 break;
2260 case noLockingStyle:
2261 case unsupportedLockingStyle:
2262 default:
2263 pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
drhbfe66312006-10-03 17:40:40 +00002264 }
drh218c5082008-03-07 00:27:10 +00002265 OpenCounter(+1);
2266 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002267}
2268#else /* SQLITE_ENABLE_LOCKING_STYLE */
danielk1977b4b47412007-08-17 15:53:36 +00002269static int fillInUnixFile(
drhbfe66312006-10-03 17:40:40 +00002270 int h, /* Open file descriptor on file being opened */
danielk1977fee2d252007-08-18 10:59:19 +00002271 int dirfd,
danielk1977b4b47412007-08-17 15:53:36 +00002272 sqlite3_file *pId, /* Write to the unixFile structure here */
2273 const char *zFilename /* Name of the file being opened */
drhbfe66312006-10-03 17:40:40 +00002274){
danielk1977b4b47412007-08-17 15:53:36 +00002275 unixFile *pNew = (unixFile *)pId;
drhbfe66312006-10-03 17:40:40 +00002276 int rc;
2277
drhe78669b2007-06-29 12:04:26 +00002278#ifdef FD_CLOEXEC
2279 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
2280#endif
danielk1977b4b47412007-08-17 15:53:36 +00002281
2282 enterMutex();
2283 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
2284 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002285 if( rc ){
danielk19777c055b92007-10-30 17:28:51 +00002286 if( dirfd>=0 ) close(dirfd);
drhbfe66312006-10-03 17:40:40 +00002287 close(h);
drh65594042008-05-05 16:56:34 +00002288 return rc;
drhbfe66312006-10-03 17:40:40 +00002289 }
danielk1977b4b47412007-08-17 15:53:36 +00002290
drh4f0c5872007-03-26 22:05:01 +00002291 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977b4b47412007-08-17 15:53:36 +00002292 pNew->dirfd = -1;
2293 pNew->h = h;
danielk1977fee2d252007-08-18 10:59:19 +00002294 pNew->dirfd = dirfd;
danielk1977b4b47412007-08-17 15:53:36 +00002295 SET_THREADID(pNew);
2296
2297 pNew->pMethod = &sqlite3UnixIoMethod;
2298 OpenCounter(+1);
2299 return SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00002300}
drhbfe66312006-10-03 17:40:40 +00002301#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9c06c952005-11-26 00:25:00 +00002302
danielk1977ad94b582007-08-20 06:44:22 +00002303/*
2304** Open a file descriptor to the directory containing file zFilename.
2305** If successful, *pFd is set to the opened file descriptor and
2306** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
2307** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
2308** value.
2309**
2310** If SQLITE_OK is returned, the caller is responsible for closing
2311** the file descriptor *pFd using close().
2312*/
danielk1977fee2d252007-08-18 10:59:19 +00002313static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00002314 int ii;
drh777b17a2007-09-20 10:02:54 +00002315 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00002316 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00002317
drh153c62c2007-08-24 03:51:33 +00002318 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
danielk1977fee2d252007-08-18 10:59:19 +00002319 for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
2320 if( ii>0 ){
2321 zDirname[ii] = '\0';
2322 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00002323 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00002324#ifdef FD_CLOEXEC
2325 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
2326#endif
2327 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
2328 }
2329 }
danielk1977fee2d252007-08-18 10:59:19 +00002330 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00002331 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00002332}
2333
danielk1977b4b47412007-08-17 15:53:36 +00002334/*
danielk1977ad94b582007-08-20 06:44:22 +00002335** Open the file zPath.
2336**
danielk1977b4b47412007-08-17 15:53:36 +00002337** Previously, the SQLite OS layer used three functions in place of this
2338** one:
2339**
2340** sqlite3OsOpenReadWrite();
2341** sqlite3OsOpenReadOnly();
2342** sqlite3OsOpenExclusive();
2343**
2344** These calls correspond to the following combinations of flags:
2345**
2346** ReadWrite() -> (READWRITE | CREATE)
2347** ReadOnly() -> (READONLY)
2348** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
2349**
2350** The old OpenExclusive() accepted a boolean argument - "delFlag". If
2351** true, the file was configured to be automatically deleted when the
2352** file handle closed. To achieve the same effect using this new
2353** interface, add the DELETEONCLOSE flag to those specified above for
2354** OpenExclusive().
2355*/
2356static int unixOpen(
drh153c62c2007-08-24 03:51:33 +00002357 sqlite3_vfs *pVfs,
danielk1977b4b47412007-08-17 15:53:36 +00002358 const char *zPath,
2359 sqlite3_file *pFile,
2360 int flags,
2361 int *pOutFlags
2362){
danielk1977fee2d252007-08-18 10:59:19 +00002363 int fd = 0; /* File descriptor returned by open() */
2364 int dirfd = -1; /* Directory file descriptor */
2365 int oflags = 0; /* Flags to pass to open() */
2366 int eType = flags&0xFFFFFF00; /* Type of file to open */
danielk1977b4b47412007-08-17 15:53:36 +00002367
2368 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
2369 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
2370 int isCreate = (flags & SQLITE_OPEN_CREATE);
2371 int isReadonly = (flags & SQLITE_OPEN_READONLY);
2372 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
2373
danielk1977fee2d252007-08-18 10:59:19 +00002374 /* If creating a master or main-file journal, this function will open
2375 ** a file-descriptor on the directory too. The first time unixSync()
2376 ** is called the directory file descriptor will be fsync()ed and close()d.
2377 */
2378 int isOpenDirectory = (isCreate &&
2379 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
2380 );
2381
2382 /* Check the following statements are true:
2383 **
2384 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
2385 ** (b) if CREATE is set, then READWRITE must also be set, and
2386 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00002387 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00002388 */
danielk1977b4b47412007-08-17 15:53:36 +00002389 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00002390 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00002391 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00002392 assert(isDelete==0 || isCreate);
2393
2394
2395 /* The main DB, main journal, and master journal are never automatically
2396 ** deleted
2397 */
2398 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
2399 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
2400 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00002401
danielk1977fee2d252007-08-18 10:59:19 +00002402 /* Assert that the upper layer has set one of the "file-type" flags. */
2403 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
2404 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
2405 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00002406 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00002407 );
2408
danielk1977b4b47412007-08-17 15:53:36 +00002409 if( isReadonly ) oflags |= O_RDONLY;
2410 if( isReadWrite ) oflags |= O_RDWR;
2411 if( isCreate ) oflags |= O_CREAT;
2412 if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
2413 oflags |= (O_LARGEFILE|O_BINARY);
2414
2415 memset(pFile, 0, sizeof(unixFile));
2416 fd = open(zPath, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
danielk19772f2d8c72007-08-30 16:13:33 +00002417 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00002418 /* Failed to open the file for read/write access. Try read-only. */
2419 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
2420 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00002421 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00002422 }
2423 if( fd<0 ){
2424 return SQLITE_CANTOPEN;
2425 }
2426 if( isDelete ){
2427 unlink(zPath);
2428 }
2429 if( pOutFlags ){
2430 *pOutFlags = flags;
2431 }
2432
2433 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00002434 if( isOpenDirectory ){
2435 int rc = openDirectory(zPath, &dirfd);
2436 if( rc!=SQLITE_OK ){
2437 close(fd);
2438 return rc;
2439 }
2440 }
2441 return fillInUnixFile(fd, dirfd, pFile, zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002442}
2443
2444/*
danielk1977fee2d252007-08-18 10:59:19 +00002445** Delete the file at zPath. If the dirSync argument is true, fsync()
2446** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00002447*/
drh153c62c2007-08-24 03:51:33 +00002448static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
danielk1977fee2d252007-08-18 10:59:19 +00002449 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00002450 SimulateIOError(return SQLITE_IOERR_DELETE);
2451 unlink(zPath);
danielk1977fee2d252007-08-18 10:59:19 +00002452 if( dirSync ){
2453 int fd;
2454 rc = openDirectory(zPath, &fd);
2455 if( rc==SQLITE_OK ){
2456 if( fsync(fd) ){
2457 rc = SQLITE_IOERR_DIR_FSYNC;
2458 }
2459 close(fd);
2460 }
2461 }
2462 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00002463}
2464
danielk197790949c22007-08-17 16:50:38 +00002465/*
2466** Test the existance of or access permissions of file zPath. The
2467** test performed depends on the value of flags:
2468**
2469** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
2470** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
2471** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
2472**
2473** Otherwise return 0.
2474*/
drh153c62c2007-08-24 03:51:33 +00002475static int unixAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
rse25c0d1a2007-09-20 08:38:14 +00002476 int amode = 0;
danielk1977b4b47412007-08-17 15:53:36 +00002477 switch( flags ){
2478 case SQLITE_ACCESS_EXISTS:
2479 amode = F_OK;
2480 break;
2481 case SQLITE_ACCESS_READWRITE:
2482 amode = W_OK|R_OK;
2483 break;
drh50d3f902007-08-27 21:10:36 +00002484 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00002485 amode = R_OK;
2486 break;
2487
2488 default:
2489 assert(!"Invalid flags argument");
2490 }
2491 return (access(zPath, amode)==0);
2492}
2493
2494/*
drh153c62c2007-08-24 03:51:33 +00002495** Create a temporary file name in zBuf. zBuf must be allocated
2496** by the calling process and must be big enough to hold at least
2497** pVfs->mxPathname bytes.
danielk1977b4b47412007-08-17 15:53:36 +00002498*/
danielk1977adfb9b02007-09-17 07:02:56 +00002499static int unixGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
danielk1977b4b47412007-08-17 15:53:36 +00002500 static const char *azDirs[] = {
2501 0,
2502 "/var/tmp",
2503 "/usr/tmp",
2504 "/tmp",
2505 ".",
2506 };
2507 static const unsigned char zChars[] =
2508 "abcdefghijklmnopqrstuvwxyz"
2509 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2510 "0123456789";
2511 int i, j;
2512 struct stat buf;
2513 const char *zDir = ".";
danielk1977843e65f2007-09-01 16:16:15 +00002514
2515 /* It's odd to simulate an io-error here, but really this is just
2516 ** using the io-error infrastructure to test that SQLite handles this
2517 ** function failing.
2518 */
2519 SimulateIOError( return SQLITE_ERROR );
2520
danielk1977b4b47412007-08-17 15:53:36 +00002521 azDirs[0] = sqlite3_temp_directory;
2522 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
2523 if( azDirs[i]==0 ) continue;
2524 if( stat(azDirs[i], &buf) ) continue;
2525 if( !S_ISDIR(buf.st_mode) ) continue;
2526 if( access(azDirs[i], 07) ) continue;
2527 zDir = azDirs[i];
2528 break;
2529 }
danielk1977f96d8ae2008-04-30 08:56:10 +00002530
2531 /* Check that the output buffer is large enough for the temporary file
2532 ** name. If it is not, return SQLITE_ERROR.
2533 */
2534 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
drh3c7f2dc2007-12-06 13:26:20 +00002535 return SQLITE_ERROR;
2536 }
danielk1977f96d8ae2008-04-30 08:56:10 +00002537
danielk1977b4b47412007-08-17 15:53:36 +00002538 do{
drh153c62c2007-08-24 03:51:33 +00002539 assert( pVfs->mxPathname==MAX_PATHNAME );
drh3c7f2dc2007-12-06 13:26:20 +00002540 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
danielk1977b4b47412007-08-17 15:53:36 +00002541 j = strlen(zBuf);
drh2fa18682008-03-19 14:15:34 +00002542 sqlite3_randomness(15, &zBuf[j]);
danielk1977b4b47412007-08-17 15:53:36 +00002543 for(i=0; i<15; i++, j++){
2544 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
2545 }
2546 zBuf[j] = 0;
2547 }while( access(zBuf,0)==0 );
2548 return SQLITE_OK;
2549}
2550
2551
2552/*
2553** Turn a relative pathname into a full pathname. The relative path
2554** is stored as a nul-terminated string in the buffer pointed to by
2555** zPath.
2556**
2557** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
2558** (in this case, MAX_PATHNAME bytes). The full-path is written to
2559** this buffer before returning.
2560*/
danielk1977adfb9b02007-09-17 07:02:56 +00002561static int unixFullPathname(
2562 sqlite3_vfs *pVfs, /* Pointer to vfs object */
2563 const char *zPath, /* Possibly relative input path */
2564 int nOut, /* Size of output buffer in bytes */
2565 char *zOut /* Output buffer */
2566){
danielk1977843e65f2007-09-01 16:16:15 +00002567
2568 /* It's odd to simulate an io-error here, but really this is just
2569 ** using the io-error infrastructure to test that SQLite handles this
2570 ** function failing. This function could fail if, for example, the
2571 ** current working directly has been unlinked.
2572 */
2573 SimulateIOError( return SQLITE_ERROR );
2574
drh153c62c2007-08-24 03:51:33 +00002575 assert( pVfs->mxPathname==MAX_PATHNAME );
drh3c7f2dc2007-12-06 13:26:20 +00002576 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00002577 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00002578 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002579 }else{
2580 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00002581 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00002582 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00002583 }
2584 nCwd = strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00002585 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002586 }
2587 return SQLITE_OK;
2588
2589#if 0
2590 /*
2591 ** Remove "/./" path elements and convert "/A/./" path elements
2592 ** to just "/".
2593 */
2594 if( zFull ){
2595 int i, j;
2596 for(i=j=0; zFull[i]; i++){
2597 if( zFull[i]=='/' ){
2598 if( zFull[i+1]=='/' ) continue;
2599 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
2600 i += 1;
2601 continue;
2602 }
2603 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
2604 while( j>0 && zFull[j-1]!='/' ){ j--; }
2605 i += 3;
2606 continue;
2607 }
2608 }
2609 zFull[j++] = zFull[i];
2610 }
2611 zFull[j] = 0;
2612 }
2613#endif
2614}
2615
drh0ccebe72005-06-07 22:22:50 +00002616
drh761df872006-12-21 01:29:22 +00002617#ifndef SQLITE_OMIT_LOAD_EXTENSION
2618/*
2619** Interfaces for opening a shared library, finding entry points
2620** within the shared library, and closing the shared library.
2621*/
2622#include <dlfcn.h>
drh153c62c2007-08-24 03:51:33 +00002623static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
drh761df872006-12-21 01:29:22 +00002624 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
2625}
danielk197795c8a542007-09-01 06:51:27 +00002626
2627/*
2628** SQLite calls this function immediately after a call to unixDlSym() or
2629** unixDlOpen() fails (returns a null pointer). If a more detailed error
2630** message is available, it is written to zBufOut. If no error message
2631** is available, zBufOut is left unmodified and SQLite uses a default
2632** error message.
2633*/
drh153c62c2007-08-24 03:51:33 +00002634static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00002635 char *zErr;
2636 enterMutex();
2637 zErr = dlerror();
2638 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00002639 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00002640 }
2641 leaveMutex();
2642}
drh46c99e02007-08-27 23:26:59 +00002643static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
drh761df872006-12-21 01:29:22 +00002644 return dlsym(pHandle, zSymbol);
2645}
drh46c99e02007-08-27 23:26:59 +00002646static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
danielk1977b4b47412007-08-17 15:53:36 +00002647 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00002648}
danielk1977b4b47412007-08-17 15:53:36 +00002649#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
2650 #define unixDlOpen 0
2651 #define unixDlError 0
2652 #define unixDlSym 0
2653 #define unixDlClose 0
2654#endif
2655
2656/*
danielk197790949c22007-08-17 16:50:38 +00002657** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00002658*/
drh153c62c2007-08-24 03:51:33 +00002659static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
danielk197790949c22007-08-17 16:50:38 +00002660
2661 assert(nBuf>=(sizeof(time_t)+sizeof(int)));
2662
drhbbd42a62004-05-22 17:41:58 +00002663 /* We have to initialize zBuf to prevent valgrind from reporting
2664 ** errors. The reports issued by valgrind are incorrect - we would
2665 ** prefer that the randomness be increased by making use of the
2666 ** uninitialized space in zBuf - but valgrind errors tend to worry
2667 ** some users. Rather than argue, it seems easier just to initialize
2668 ** the whole array and silence valgrind, even if that means less randomness
2669 ** in the random seed.
2670 **
2671 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00002672 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00002673 ** tests repeatable.
2674 */
danielk1977b4b47412007-08-17 15:53:36 +00002675 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00002676#if !defined(SQLITE_TEST)
2677 {
drh842b8642005-01-21 17:53:17 +00002678 int pid, fd;
2679 fd = open("/dev/urandom", O_RDONLY);
2680 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00002681 time_t t;
2682 time(&t);
danielk197790949c22007-08-17 16:50:38 +00002683 memcpy(zBuf, &t, sizeof(t));
2684 pid = getpid();
2685 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
drh842b8642005-01-21 17:53:17 +00002686 }else{
danielk1977b4b47412007-08-17 15:53:36 +00002687 read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00002688 close(fd);
2689 }
drhbbd42a62004-05-22 17:41:58 +00002690 }
2691#endif
2692 return SQLITE_OK;
2693}
2694
danielk1977b4b47412007-08-17 15:53:36 +00002695
drhbbd42a62004-05-22 17:41:58 +00002696/*
2697** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00002698** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00002699** The return value is the number of microseconds of sleep actually
2700** requested from the underlying operating system, a number which
2701** might be greater than or equal to the argument, but not less
2702** than the argument.
drhbbd42a62004-05-22 17:41:58 +00002703*/
drh153c62c2007-08-24 03:51:33 +00002704static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
drhbbd42a62004-05-22 17:41:58 +00002705#if defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00002706 usleep(microseconds);
2707 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00002708#else
danielk1977b4b47412007-08-17 15:53:36 +00002709 int seconds = (microseconds+999999)/1000000;
2710 sleep(seconds);
drh4a50aac2007-08-23 02:47:53 +00002711 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00002712#endif
drh88f474a2006-01-02 20:00:12 +00002713}
2714
2715/*
drhbbd42a62004-05-22 17:41:58 +00002716** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00002717** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00002718*/
2719#ifdef SQLITE_TEST
2720int sqlite3_current_time = 0;
2721#endif
2722
2723/*
2724** Find the current time (in Universal Coordinated Time). Write the
2725** current time and date as a Julian Day number into *prNow and
2726** return 0. Return 1 if the time and date cannot be found.
2727*/
drh153c62c2007-08-24 03:51:33 +00002728static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
drh19e2d372005-08-29 23:00:03 +00002729#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00002730 time_t t;
2731 time(&t);
2732 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00002733#else
2734 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00002735 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00002736 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
2737#endif
drhbbd42a62004-05-22 17:41:58 +00002738#ifdef SQLITE_TEST
2739 if( sqlite3_current_time ){
2740 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
2741 }
2742#endif
2743 return 0;
2744}
danielk1977b4b47412007-08-17 15:53:36 +00002745
drh153c62c2007-08-24 03:51:33 +00002746/*
2747** Return a pointer to the sqlite3DefaultVfs structure. We use
2748** a function rather than give the structure global scope because
2749** some compilers (MSVC) do not allow forward declarations of
2750** initialized structures.
2751*/
2752sqlite3_vfs *sqlite3OsDefaultVfs(void){
2753 static sqlite3_vfs unixVfs = {
2754 1, /* iVersion */
2755 sizeof(unixFile), /* szOsFile */
2756 MAX_PATHNAME, /* mxPathname */
drh153c62c2007-08-24 03:51:33 +00002757 0, /* pNext */
2758 "unix", /* zName */
2759 0, /* pAppData */
2760
2761 unixOpen, /* xOpen */
2762 unixDelete, /* xDelete */
2763 unixAccess, /* xAccess */
danielk197776ee37f2007-09-17 06:06:39 +00002764 unixGetTempname, /* xGetTempName */
drh153c62c2007-08-24 03:51:33 +00002765 unixFullPathname, /* xFullPathname */
2766 unixDlOpen, /* xDlOpen */
2767 unixDlError, /* xDlError */
2768 unixDlSym, /* xDlSym */
2769 unixDlClose, /* xDlClose */
2770 unixRandomness, /* xRandomness */
2771 unixSleep, /* xSleep */
2772 unixCurrentTime /* xCurrentTime */
2773 };
2774
2775 return &unixVfs;
2776}
drhdce8bdb2007-08-16 13:01:44 +00002777
drhbbd42a62004-05-22 17:41:58 +00002778#endif /* OS_UNIX */