blob: 71f4bafdd879768be5b3f7a436ef8c4585e4147f [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.
14*/
drhbbd42a62004-05-22 17:41:58 +000015#include "sqliteInt.h"
drheb206252004-10-01 02:00:31 +000016#include "os.h"
17#if OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000018
drhbfe66312006-10-03 17:40:40 +000019/* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
20
drh9cbe6352005-11-29 03:13:21 +000021/*
22** These #defines should enable >2GB file support on Posix if the
23** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000024** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000025**
26** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
27** on the compiler command line. This is necessary if you are compiling
28** on a recent machine (ex: RedHat 7.2) but you want your code to work
29** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
30** without this option, LFS is enable. But LFS does not exist in the kernel
31** in RedHat 6.0, so the code won't work. Hence, for maximum binary
32** portability you should omit LFS.
drh9cbe6352005-11-29 03:13:21 +000033*/
34#ifndef SQLITE_DISABLE_LFS
35# define _LARGE_FILE 1
36# ifndef _FILE_OFFSET_BITS
37# define _FILE_OFFSET_BITS 64
38# endif
39# define _LARGEFILE_SOURCE 1
40#endif
drhbbd42a62004-05-22 17:41:58 +000041
drh9cbe6352005-11-29 03:13:21 +000042/*
43** standard include files.
44*/
45#include <sys/types.h>
46#include <sys/stat.h>
47#include <fcntl.h>
48#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000049#include <time.h>
drh19e2d372005-08-29 23:00:03 +000050#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000051#include <errno.h>
drhbfe66312006-10-03 17:40:40 +000052#ifdef SQLITE_ENABLE_LOCKING_STYLE
53#include <sys/ioctl.h>
54#include <sys/param.h>
55#include <sys/mount.h>
56#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000057
58/*
drhf1a221e2006-01-15 17:27:17 +000059** If we are to be thread-safe, include the pthreads header and define
60** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +000061*/
drh2c547df2007-04-01 18:46:19 +000062#ifndef THREADSAFE
63# define THREADSAFE 1
64#endif
65#if THREADSAFE
drh9cbe6352005-11-29 03:13:21 +000066# include <pthread.h>
67# define SQLITE_UNIX_THREADS 1
68#endif
69
70/*
71** Default permissions when creating a new file
72*/
73#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
74# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
75#endif
76
77
78
79/*
drh054889e2005-11-30 03:20:31 +000080** The unixFile structure is subclass of OsFile specific for the unix
81** protability layer.
drh9cbe6352005-11-29 03:13:21 +000082*/
drh054889e2005-11-30 03:20:31 +000083typedef struct unixFile unixFile;
84struct unixFile {
danielk197762079062007-08-15 17:08:46 +000085 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh9cbe6352005-11-29 03:13:21 +000086 struct openCnt *pOpen; /* Info about all open fd's on this inode */
87 struct lockInfo *pLock; /* Info about locks on this inode */
drhbfe66312006-10-03 17:40:40 +000088#ifdef SQLITE_ENABLE_LOCKING_STYLE
89 void *lockingContext; /* Locking style specific state */
90#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000091 int h; /* The file descriptor */
92 unsigned char locktype; /* The type of lock held on this fd */
93 unsigned char isOpen; /* True if needs to be closed */
94 unsigned char fullSync; /* Use F_FULLSYNC if available */
95 int dirfd; /* File descriptor for the directory */
drhb912b282006-03-23 22:42:20 +000096 i64 offset; /* Seek offset */
drh9cbe6352005-11-29 03:13:21 +000097#ifdef SQLITE_UNIX_THREADS
drhf1a221e2006-01-15 17:27:17 +000098 pthread_t tid; /* The thread that "owns" this OsFile */
drh9cbe6352005-11-29 03:13:21 +000099#endif
100};
101
danielk197762079062007-08-15 17:08:46 +0000102
drh66560ad2006-01-06 14:32:19 +0000103/*
104** Provide the ability to override some OS-layer functions during
105** testing. This is used to simulate OS crashes to verify that
106** commits are atomic even in the event of an OS crash.
107*/
108#ifdef SQLITE_CRASH_TEST
109 extern int sqlite3CrashTestEnable;
danielk197762079062007-08-15 17:08:46 +0000110 int sqlite3CrashFileWrap(sqlite3_file *, const char *, sqlite3_file **);
111 static int CRASH_TEST_OVERRIDE(const char *zFile, sqlite3_file **pId, int rc){
112 if( rc==SQLITE_OK && sqlite3CrashTestEnable ){
113 rc = sqlite3CrashFileWrap(*pId, zFile, pId);
114 }
115 return rc;
116 }
drh66560ad2006-01-06 14:32:19 +0000117#else
danielk197762079062007-08-15 17:08:46 +0000118# define CRASH_TEST_OVERRIDE(A,B,C) C
drh66560ad2006-01-06 14:32:19 +0000119#endif
120
drh0ccebe72005-06-07 22:22:50 +0000121
122/*
drh198bf392006-01-06 21:52:49 +0000123** Include code that is common to all os_*.c files
124*/
125#include "os_common.h"
126
127/*
drh0ccebe72005-06-07 22:22:50 +0000128** Do not include any of the File I/O interface procedures if the
drhf1a221e2006-01-15 17:27:17 +0000129** SQLITE_OMIT_DISKIO macro is defined (indicating that the database
drh0ccebe72005-06-07 22:22:50 +0000130** will be in-memory only)
131*/
132#ifndef SQLITE_OMIT_DISKIO
133
134
135/*
136** Define various macros that are missing from some systems.
137*/
drhbbd42a62004-05-22 17:41:58 +0000138#ifndef O_LARGEFILE
139# define O_LARGEFILE 0
140#endif
141#ifdef SQLITE_DISABLE_LFS
142# undef O_LARGEFILE
143# define O_LARGEFILE 0
144#endif
145#ifndef O_NOFOLLOW
146# define O_NOFOLLOW 0
147#endif
148#ifndef O_BINARY
149# define O_BINARY 0
150#endif
151
152/*
153** The DJGPP compiler environment looks mostly like Unix, but it
154** lacks the fcntl() system call. So redefine fcntl() to be something
155** that always succeeds. This means that locking does not occur under
danielk197726c5d792005-11-25 09:01:23 +0000156** DJGPP. But it's DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000157*/
158#ifdef __DJGPP__
159# define fcntl(A,B,C) 0
160#endif
161
162/*
drh2b4b5962005-06-15 17:47:55 +0000163** The threadid macro resolves to the thread-id or to 0. Used for
164** testing and debugging only.
165*/
166#ifdef SQLITE_UNIX_THREADS
167#define threadid pthread_self()
168#else
169#define threadid 0
170#endif
171
172/*
173** Set or check the OsFile.tid field. This field is set when an OsFile
174** is first opened. All subsequent uses of the OsFile verify that the
175** same thread is operating on the OsFile. Some operating systems do
176** not allow locks to be overridden by other threads and that restriction
177** means that sqlite3* database handles cannot be moved from one thread
178** to another. This logic makes sure a user does not try to do that
179** by mistake.
drhf1a221e2006-01-15 17:27:17 +0000180**
181** Version 3.3.1 (2006-01-15): OsFiles can be moved from one thread to
182** another as long as we are running on a system that supports threads
183** overriding each others locks (which now the most common behavior)
184** or if no locks are held. But the OsFile.pLock field needs to be
185** recomputed because its key includes the thread-id. See the
186** transferOwnership() function below for additional information
drh2b4b5962005-06-15 17:47:55 +0000187*/
drh029b44b2006-01-15 00:13:15 +0000188#if defined(SQLITE_UNIX_THREADS)
drh9cbe6352005-11-29 03:13:21 +0000189# define SET_THREADID(X) (X)->tid = pthread_self()
drh029b44b2006-01-15 00:13:15 +0000190# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
191 !pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000192#else
193# define SET_THREADID(X)
194# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000195#endif
196
drhbbd42a62004-05-22 17:41:58 +0000197/*
198** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
199** section 6.5.2.2 lines 483 through 490 specify that when a process
200** sets or clears a lock, that operation overrides any prior locks set
201** by the same process. It does not explicitly say so, but this implies
202** that it overrides locks set by the same process using a different
203** file descriptor. Consider this test case:
204**
205** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
206** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
207**
208** Suppose ./file1 and ./file2 are really the same file (because
209** one is a hard or symbolic link to the other) then if you set
210** an exclusive lock on fd1, then try to get an exclusive lock
211** on fd2, it works. I would have expected the second lock to
212** fail since there was already a lock on the file due to fd1.
213** But not so. Since both locks came from the same process, the
214** second overrides the first, even though they were on different
215** file descriptors opened on different file names.
216**
217** Bummer. If you ask me, this is broken. Badly broken. It means
218** that we cannot use POSIX locks to synchronize file access among
219** competing threads of the same process. POSIX locks will work fine
220** to synchronize access for threads in separate processes, but not
221** threads within the same process.
222**
223** To work around the problem, SQLite has to manage file locks internally
224** on its own. Whenever a new database is opened, we have to find the
225** specific inode of the database file (the inode is determined by the
226** st_dev and st_ino fields of the stat structure that fstat() fills in)
227** and check for locks already existing on that inode. When locks are
228** created or removed, we have to look at our own internal record of the
229** locks to see if another thread has previously set a lock on that same
230** inode.
231**
232** The OsFile structure for POSIX is no longer just an integer file
233** descriptor. It is now a structure that holds the integer file
234** descriptor and a pointer to a structure that describes the internal
235** locks on the corresponding inode. There is one locking structure
236** per inode, so if the same inode is opened twice, both OsFile structures
237** point to the same locking structure. The locking structure keeps
238** a reference count (so we will know when to delete it) and a "cnt"
239** field that tells us its internal lock status. cnt==0 means the
240** file is unlocked. cnt==-1 means the file has an exclusive lock.
241** cnt>0 means there are cnt shared locks on the file.
242**
243** Any attempt to lock or unlock a file first checks the locking
244** structure. The fcntl() system call is only invoked to set a
245** POSIX lock if the internal lock structure transitions between
246** a locked and an unlocked state.
247**
248** 2004-Jan-11:
249** More recent discoveries about POSIX advisory locks. (The more
250** I discover, the more I realize the a POSIX advisory locks are
251** an abomination.)
252**
253** If you close a file descriptor that points to a file that has locks,
254** all locks on that file that are owned by the current process are
255** released. To work around this problem, each OsFile structure contains
256** a pointer to an openCnt structure. There is one openCnt structure
257** per open inode, which means that multiple OsFiles can point to a single
258** openCnt. When an attempt is made to close an OsFile, if there are
259** other OsFiles open on the same inode that are holding locks, the call
260** to close() the file descriptor is deferred until all of the locks clear.
261** The openCnt structure keeps a list of file descriptors that need to
262** be closed and that list is walked (and cleared) when the last lock
263** clears.
264**
265** First, under Linux threads, because each thread has a separate
266** process ID, lock operations in one thread do not override locks
267** to the same file in other threads. Linux threads behave like
268** separate processes in this respect. But, if you close a file
269** descriptor in linux threads, all locks are cleared, even locks
270** on other threads and even though the other threads have different
271** process IDs. Linux threads is inconsistent in this respect.
272** (I'm beginning to think that linux threads is an abomination too.)
273** The consequence of this all is that the hash table for the lockInfo
274** structure has to include the process id as part of its key because
275** locks in different threads are treated as distinct. But the
276** openCnt structure should not include the process id in its
277** key because close() clears lock on all threads, not just the current
278** thread. Were it not for this goofiness in linux threads, we could
279** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000280**
281** 2004-Jun-28:
282** On some versions of linux, threads can override each others locks.
283** On others not. Sometimes you can change the behavior on the same
284** system by setting the LD_ASSUME_KERNEL environment variable. The
285** POSIX standard is silent as to which behavior is correct, as far
286** as I can tell, so other versions of unix might show the same
287** inconsistency. There is no little doubt in my mind that posix
288** advisory locks and linux threads are profoundly broken.
289**
290** To work around the inconsistencies, we have to test at runtime
291** whether or not threads can override each others locks. This test
292** is run once, the first time any lock is attempted. A static
293** variable is set to record the results of this test for future
294** use.
drhbbd42a62004-05-22 17:41:58 +0000295*/
296
297/*
298** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000299** to locate a particular lockInfo structure given its inode.
300**
301** If threads cannot override each others locks, then we set the
302** lockKey.tid field to the thread ID. If threads can override
drhf1a221e2006-01-15 17:27:17 +0000303** each others locks then tid is always set to zero. tid is omitted
304** if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000305*/
306struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000307 dev_t dev; /* Device number */
308 ino_t ino; /* Inode number */
309#ifdef SQLITE_UNIX_THREADS
drhd9cb6ac2005-10-20 07:28:17 +0000310 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000311#endif
drhbbd42a62004-05-22 17:41:58 +0000312};
313
314/*
315** An instance of the following structure is allocated for each open
316** inode on each thread with a different process ID. (Threads have
317** different process IDs on linux, but not on most other unixes.)
318**
319** A single inode can have multiple file descriptors, so each OsFile
320** structure contains a pointer to an instance of this object and this
321** object keeps a count of the number of OsFiles pointing to it.
322*/
323struct lockInfo {
324 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000325 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000326 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000327 int nRef; /* Number of pointers to this structure */
328};
329
330/*
331** An instance of the following structure serves as the key used
332** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000333** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000334*/
335struct openKey {
336 dev_t dev; /* Device number */
337 ino_t ino; /* Inode number */
338};
339
340/*
341** An instance of the following structure is allocated for each open
342** inode. This structure keeps track of the number of locks on that
343** inode. If a close is attempted against an inode that is holding
344** locks, the close is deferred until all locks clear by adding the
345** file descriptor to be closed to the pending list.
346*/
347struct openCnt {
348 struct openKey key; /* The lookup key */
349 int nRef; /* Number of pointers to this structure */
350 int nLock; /* Number of outstanding locks */
351 int nPending; /* Number of pending close() operations */
352 int *aPending; /* Malloced space holding fd's awaiting a close() */
353};
354
355/*
drhf1a221e2006-01-15 17:27:17 +0000356** These hash tables map inodes and file descriptors (really, lockKey and
357** openKey structures) into lockInfo and openCnt structures. Access to
358** these hash tables must be protected by a mutex.
drhbbd42a62004-05-22 17:41:58 +0000359*/
drh17435752007-08-16 04:30:38 +0000360static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
361static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
drh5fdae772004-06-29 03:29:00 +0000362
drhbfe66312006-10-03 17:40:40 +0000363#ifdef SQLITE_ENABLE_LOCKING_STYLE
364/*
365** The locking styles are associated with the different file locking
366** capabilities supported by different file systems.
367**
368** POSIX locking style fully supports shared and exclusive byte-range locks
369** ADP locking only supports exclusive byte-range locks
370** FLOCK only supports a single file-global exclusive lock
371** DOTLOCK isn't a true locking style, it refers to the use of a special
372** file named the same as the database file with a '.lock' extension, this
373** can be used on file systems that do not offer any reliable file locking
374** NO locking means that no locking will be attempted, this is only used for
375** read-only file systems currently
376** UNSUPPORTED means that no locking will be attempted, this is only used for
377** file systems that are known to be unsupported
378*/
379typedef enum {
drhfd131da2007-08-07 17:13:03 +0000380 posixLockingStyle = 0, /* standard posix-advisory locks */
381 afpLockingStyle, /* use afp locks */
382 flockLockingStyle, /* use flock() */
383 dotlockLockingStyle, /* use <file>.lock files */
384 noLockingStyle, /* useful for read-only file system */
385 unsupportedLockingStyle /* indicates unsupported file system */
drhbfe66312006-10-03 17:40:40 +0000386} sqlite3LockingStyle;
387#endif /* SQLITE_ENABLE_LOCKING_STYLE */
388
drh5fdae772004-06-29 03:29:00 +0000389#ifdef SQLITE_UNIX_THREADS
390/*
391** This variable records whether or not threads can override each others
392** locks.
393**
394** 0: No. Threads cannot override each others locks.
395** 1: Yes. Threads can override each others locks.
396** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000397**
drh5062d3a2006-01-31 23:03:35 +0000398** On some systems, we know at compile-time if threads can override each
399** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
400** will be set appropriately. On other systems, we have to check at
401** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
402** undefined.
403**
drhf1a221e2006-01-15 17:27:17 +0000404** This variable normally has file scope only. But during testing, we make
405** it a global so that the test code can change its value in order to verify
406** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000407*/
drh5062d3a2006-01-31 23:03:35 +0000408#ifndef SQLITE_THREAD_OVERRIDE_LOCK
409# define SQLITE_THREAD_OVERRIDE_LOCK -1
410#endif
drh029b44b2006-01-15 00:13:15 +0000411#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000412int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000413#else
drh5062d3a2006-01-31 23:03:35 +0000414static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000415#endif
drh5fdae772004-06-29 03:29:00 +0000416
417/*
418** This structure holds information passed into individual test
419** threads by the testThreadLockingBehavior() routine.
420*/
421struct threadTestData {
422 int fd; /* File to be locked */
423 struct flock lock; /* The locking operation */
424 int result; /* Result of the locking operation */
425};
426
drh2b4b5962005-06-15 17:47:55 +0000427#ifdef SQLITE_LOCK_TRACE
428/*
429** Print out information about all locking operations.
430**
431** This routine is used for troubleshooting locks on multithreaded
432** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
433** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000434** turned off.
drh2b4b5962005-06-15 17:47:55 +0000435*/
436static int lockTrace(int fd, int op, struct flock *p){
437 char *zOpName, *zType;
438 int s;
439 int savedErrno;
440 if( op==F_GETLK ){
441 zOpName = "GETLK";
442 }else if( op==F_SETLK ){
443 zOpName = "SETLK";
444 }else{
445 s = fcntl(fd, op, p);
446 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
447 return s;
448 }
449 if( p->l_type==F_RDLCK ){
450 zType = "RDLCK";
451 }else if( p->l_type==F_WRLCK ){
452 zType = "WRLCK";
453 }else if( p->l_type==F_UNLCK ){
454 zType = "UNLCK";
455 }else{
456 assert( 0 );
457 }
458 assert( p->l_whence==SEEK_SET );
459 s = fcntl(fd, op, p);
460 savedErrno = errno;
461 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
462 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
463 (int)p->l_pid, s);
drhe2396a12007-03-29 20:19:58 +0000464 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
drh2b4b5962005-06-15 17:47:55 +0000465 struct flock l2;
466 l2 = *p;
467 fcntl(fd, F_GETLK, &l2);
468 if( l2.l_type==F_RDLCK ){
469 zType = "RDLCK";
470 }else if( l2.l_type==F_WRLCK ){
471 zType = "WRLCK";
472 }else if( l2.l_type==F_UNLCK ){
473 zType = "UNLCK";
474 }else{
475 assert( 0 );
476 }
477 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
478 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
479 }
480 errno = savedErrno;
481 return s;
482}
483#define fcntl lockTrace
484#endif /* SQLITE_LOCK_TRACE */
485
drh5fdae772004-06-29 03:29:00 +0000486/*
487** The testThreadLockingBehavior() routine launches two separate
488** threads on this routine. This routine attempts to lock a file
489** descriptor then returns. The success or failure of that attempt
490** allows the testThreadLockingBehavior() procedure to determine
491** whether or not threads can override each others locks.
492*/
493static void *threadLockingTest(void *pArg){
494 struct threadTestData *pData = (struct threadTestData*)pArg;
495 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
496 return pArg;
497}
498
499/*
500** This procedure attempts to determine whether or not threads
501** can override each others locks then sets the
502** threadsOverrideEachOthersLocks variable appropriately.
503*/
danielk19774d5238f2006-01-27 06:32:00 +0000504static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000505 int fd;
506 struct threadTestData d[2];
507 pthread_t t[2];
508
509 fd = dup(fd_orig);
510 if( fd<0 ) return;
511 memset(d, 0, sizeof(d));
512 d[0].fd = fd;
513 d[0].lock.l_type = F_RDLCK;
514 d[0].lock.l_len = 1;
515 d[0].lock.l_start = 0;
516 d[0].lock.l_whence = SEEK_SET;
517 d[1] = d[0];
518 d[1].lock.l_type = F_WRLCK;
519 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
520 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
521 pthread_join(t[0], 0);
522 pthread_join(t[1], 0);
523 close(fd);
524 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
525}
526#endif /* SQLITE_UNIX_THREADS */
527
drhbbd42a62004-05-22 17:41:58 +0000528/*
529** Release a lockInfo structure previously allocated by findLockInfo().
530*/
531static void releaseLockInfo(struct lockInfo *pLock){
drh757b04e2006-01-18 17:25:45 +0000532 assert( sqlite3OsInMutex(1) );
drhbfe66312006-10-03 17:40:40 +0000533 if (pLock == NULL)
534 return;
drhbbd42a62004-05-22 17:41:58 +0000535 pLock->nRef--;
536 if( pLock->nRef==0 ){
537 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
drh17435752007-08-16 04:30:38 +0000538 sqlite3_free(pLock);
drhbbd42a62004-05-22 17:41:58 +0000539 }
540}
541
542/*
543** Release a openCnt structure previously allocated by findLockInfo().
544*/
545static void releaseOpenCnt(struct openCnt *pOpen){
drh757b04e2006-01-18 17:25:45 +0000546 assert( sqlite3OsInMutex(1) );
drhbfe66312006-10-03 17:40:40 +0000547 if (pOpen == NULL)
548 return;
drhbbd42a62004-05-22 17:41:58 +0000549 pOpen->nRef--;
550 if( pOpen->nRef==0 ){
551 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
drh64b1bea2006-01-15 02:30:57 +0000552 free(pOpen->aPending);
drh17435752007-08-16 04:30:38 +0000553 sqlite3_free(pOpen);
drhbbd42a62004-05-22 17:41:58 +0000554 }
555}
556
drhbfe66312006-10-03 17:40:40 +0000557#ifdef SQLITE_ENABLE_LOCKING_STYLE
558/*
559** Tests a byte-range locking query to see if byte range locks are
560** supported, if not we fall back to dotlockLockingStyle.
561*/
562static sqlite3LockingStyle sqlite3TestLockingStyle(const char *filePath,
563 int fd) {
564 /* test byte-range lock using fcntl */
565 struct flock lockInfo;
566
567 lockInfo.l_len = 1;
568 lockInfo.l_start = 0;
569 lockInfo.l_whence = SEEK_SET;
570 lockInfo.l_type = F_RDLCK;
571
aswiftae0943b2007-01-31 23:37:07 +0000572 if (fcntl(fd, F_GETLK, &lockInfo) != -1) {
drhbfe66312006-10-03 17:40:40 +0000573 return posixLockingStyle;
574 }
575
576 /* testing for flock can give false positives. So if if the above test
577 ** fails, then we fall back to using dot-lock style locking.
578 */
579 return dotlockLockingStyle;
580}
581
582/*
583** Examines the f_fstypename entry in the statfs structure as returned by
584** stat() for the file system hosting the database file, assigns the
585** appropriate locking style based on it's value. These values and
586** assignments are based on Darwin/OSX behavior and have not been tested on
587** other systems.
588*/
589static sqlite3LockingStyle sqlite3DetectLockingStyle(const char *filePath,
590 int fd) {
591
592#ifdef SQLITE_FIXED_LOCKING_STYLE
593 return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
594#else
595 struct statfs fsInfo;
596
597 if (statfs(filePath, &fsInfo) == -1)
598 return sqlite3TestLockingStyle(filePath, fd);
599
600 if (fsInfo.f_flags & MNT_RDONLY)
601 return noLockingStyle;
602
603 if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
604 (!strcmp(fsInfo.f_fstypename, "ufs")) )
drhfd131da2007-08-07 17:13:03 +0000605 return posixLockingStyle;
drhbfe66312006-10-03 17:40:40 +0000606
607 if(!strcmp(fsInfo.f_fstypename, "afpfs"))
608 return afpLockingStyle;
609
610 if(!strcmp(fsInfo.f_fstypename, "nfs"))
611 return sqlite3TestLockingStyle(filePath, fd);
612
613 if(!strcmp(fsInfo.f_fstypename, "smbfs"))
614 return flockLockingStyle;
615
616 if(!strcmp(fsInfo.f_fstypename, "msdos"))
617 return dotlockLockingStyle;
618
619 if(!strcmp(fsInfo.f_fstypename, "webdav"))
620 return unsupportedLockingStyle;
621
622 return sqlite3TestLockingStyle(filePath, fd);
drh3b62b2f2007-06-08 18:27:03 +0000623#endif /* SQLITE_FIXED_LOCKING_STYLE */
drhbfe66312006-10-03 17:40:40 +0000624}
625
626#endif /* SQLITE_ENABLE_LOCKING_STYLE */
627
drhbbd42a62004-05-22 17:41:58 +0000628/*
629** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000630** describes that file descriptor. Create new ones if necessary. The
631** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000632**
633** Return the number of errors.
634*/
drh38f82712004-06-18 17:10:16 +0000635static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000636 int fd, /* The file descriptor used in the key */
637 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000638 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000639){
640 int rc;
641 struct lockKey key1;
642 struct openKey key2;
643 struct stat statbuf;
644 struct lockInfo *pLock;
645 struct openCnt *pOpen;
646 rc = fstat(fd, &statbuf);
647 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000648
drh757b04e2006-01-18 17:25:45 +0000649 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000650 memset(&key1, 0, sizeof(key1));
651 key1.dev = statbuf.st_dev;
652 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000653#ifdef SQLITE_UNIX_THREADS
654 if( threadsOverrideEachOthersLocks<0 ){
655 testThreadLockingBehavior(fd);
656 }
657 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
658#endif
drhbbd42a62004-05-22 17:41:58 +0000659 memset(&key2, 0, sizeof(key2));
660 key2.dev = statbuf.st_dev;
661 key2.ino = statbuf.st_ino;
662 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
663 if( pLock==0 ){
664 struct lockInfo *pOld;
drh17435752007-08-16 04:30:38 +0000665 pLock = sqlite3_malloc( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000666 if( pLock==0 ){
667 rc = 1;
668 goto exit_findlockinfo;
669 }
drhbbd42a62004-05-22 17:41:58 +0000670 pLock->key = key1;
671 pLock->nRef = 1;
672 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000673 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000674 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
675 if( pOld!=0 ){
676 assert( pOld==pLock );
drh17435752007-08-16 04:30:38 +0000677 sqlite3_free(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000678 rc = 1;
679 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000680 }
681 }else{
682 pLock->nRef++;
683 }
684 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000685 if( ppOpen!=0 ){
686 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
drhbbd42a62004-05-22 17:41:58 +0000687 if( pOpen==0 ){
drh029b44b2006-01-15 00:13:15 +0000688 struct openCnt *pOld;
drh17435752007-08-16 04:30:38 +0000689 pOpen = sqlite3_malloc( sizeof(*pOpen) );
drh029b44b2006-01-15 00:13:15 +0000690 if( pOpen==0 ){
691 releaseLockInfo(pLock);
692 rc = 1;
693 goto exit_findlockinfo;
694 }
695 pOpen->key = key2;
696 pOpen->nRef = 1;
697 pOpen->nLock = 0;
698 pOpen->nPending = 0;
699 pOpen->aPending = 0;
700 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
701 if( pOld!=0 ){
702 assert( pOld==pOpen );
drh17435752007-08-16 04:30:38 +0000703 sqlite3_free(pOpen);
drh029b44b2006-01-15 00:13:15 +0000704 releaseLockInfo(pLock);
705 rc = 1;
706 goto exit_findlockinfo;
707 }
708 }else{
709 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000710 }
drh029b44b2006-01-15 00:13:15 +0000711 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000712 }
danielk1977441b09a2006-01-05 13:48:29 +0000713
714exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000715 return rc;
drhbbd42a62004-05-22 17:41:58 +0000716}
717
drh64b1bea2006-01-15 02:30:57 +0000718#ifdef SQLITE_DEBUG
719/*
720** Helper function for printing out trace information from debugging
721** binaries. This returns the string represetation of the supplied
722** integer lock-type.
723*/
724static const char *locktypeName(int locktype){
725 switch( locktype ){
726 case NO_LOCK: return "NONE";
727 case SHARED_LOCK: return "SHARED";
728 case RESERVED_LOCK: return "RESERVED";
729 case PENDING_LOCK: return "PENDING";
730 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
731 }
732 return "ERROR";
733}
734#endif
735
drhbbd42a62004-05-22 17:41:58 +0000736/*
drh029b44b2006-01-15 00:13:15 +0000737** If we are currently in a different thread than the thread that the
738** unixFile argument belongs to, then transfer ownership of the unixFile
739** over to the current thread.
740**
741** A unixFile is only owned by a thread on systems where one thread is
742** unable to override locks created by a different thread. RedHat9 is
743** an example of such a system.
744**
745** Ownership transfer is only allowed if the unixFile is currently unlocked.
746** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000747** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000748*/
749#ifdef SQLITE_UNIX_THREADS
750static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000751 int rc;
drh029b44b2006-01-15 00:13:15 +0000752 pthread_t hSelf;
753 if( threadsOverrideEachOthersLocks ){
754 /* Ownership transfers not needed on this system */
755 return SQLITE_OK;
756 }
757 hSelf = pthread_self();
758 if( pthread_equal(pFile->tid, hSelf) ){
759 /* We are still in the same thread */
drh4f0c5872007-03-26 22:05:01 +0000760 OSTRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000761 return SQLITE_OK;
762 }
763 if( pFile->locktype!=NO_LOCK ){
764 /* We cannot change ownership while we are holding a lock! */
765 return SQLITE_MISUSE;
766 }
drh4f0c5872007-03-26 22:05:01 +0000767 OSTRACE4("Transfer ownership of %d from %d to %d\n",
768 pFile->h, pFile->tid, hSelf);
drh029b44b2006-01-15 00:13:15 +0000769 pFile->tid = hSelf;
drhbfe66312006-10-03 17:40:40 +0000770 if (pFile->pLock != NULL) {
771 releaseLockInfo(pFile->pLock);
772 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
drh4f0c5872007-03-26 22:05:01 +0000773 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +0000774 locktypeName(pFile->locktype),
775 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
776 return rc;
777 } else {
778 return SQLITE_OK;
779 }
drh029b44b2006-01-15 00:13:15 +0000780}
781#else
drhf1a221e2006-01-15 17:27:17 +0000782 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +0000783# define transferOwnership(X) SQLITE_OK
784#endif
785
786/*
drhbbd42a62004-05-22 17:41:58 +0000787** Delete the named file
788*/
drh66560ad2006-01-06 14:32:19 +0000789int sqlite3UnixDelete(const char *zFilename){
danielk1977979f38e2007-03-27 16:19:51 +0000790 SimulateIOError(return SQLITE_IOERR_DELETE);
drhbbd42a62004-05-22 17:41:58 +0000791 unlink(zFilename);
792 return SQLITE_OK;
793}
794
795/*
796** Return TRUE if the named file exists.
797*/
drh66560ad2006-01-06 14:32:19 +0000798int sqlite3UnixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000799 return access(zFilename, 0)==0;
800}
801
drh054889e2005-11-30 03:20:31 +0000802/* Forward declaration */
drhbfe66312006-10-03 17:40:40 +0000803static int allocateUnixFile(
804 int h, /* File descriptor of the open file */
danielk197762079062007-08-15 17:08:46 +0000805 sqlite3_file **pId, /* Write the real file descriptor here */
drhbfe66312006-10-03 17:40:40 +0000806 const char *zFilename, /* Name of the file being opened */
807 int delFlag /* If true, make sure the file deletes on close */
808);
drh9cbe6352005-11-29 03:13:21 +0000809
810/*
drhbbd42a62004-05-22 17:41:58 +0000811** Attempt to open a file for both reading and writing. If that
812** fails, try opening it read-only. If the file does not exist,
813** try to create it.
814**
815** On success, a handle for the open file is written to *id
816** and *pReadonly is set to 0 if the file was opened for reading and
817** writing or 1 if the file was opened read-only. The function returns
818** SQLITE_OK.
819**
820** On failure, the function returns SQLITE_CANTOPEN and leaves
821** *id and *pReadonly unchanged.
822*/
drh66560ad2006-01-06 14:32:19 +0000823int sqlite3UnixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000824 const char *zFilename,
danielk197762079062007-08-15 17:08:46 +0000825 sqlite3_file **pId,
drhbbd42a62004-05-22 17:41:58 +0000826 int *pReadonly
827){
drhbfe66312006-10-03 17:40:40 +0000828 int h;
829
drh9cbe6352005-11-29 03:13:21 +0000830 assert( 0==*pId );
drhbfe66312006-10-03 17:40:40 +0000831 h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
832 SQLITE_DEFAULT_FILE_PERMISSIONS);
833 if( h<0 ){
drh6458e392004-07-20 01:14:13 +0000834#ifdef EISDIR
835 if( errno==EISDIR ){
836 return SQLITE_CANTOPEN;
837 }
838#endif
drhbfe66312006-10-03 17:40:40 +0000839 h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
840 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000841 return SQLITE_CANTOPEN;
842 }
843 *pReadonly = 1;
844 }else{
845 *pReadonly = 0;
846 }
danielk197762079062007-08-15 17:08:46 +0000847
848 return CRASH_TEST_OVERRIDE(
849 zFilename, pId, allocateUnixFile(h, pId, zFilename, 0)
850 );
drhbbd42a62004-05-22 17:41:58 +0000851}
852
853
854/*
855** Attempt to open a new file for exclusive access by this process.
856** The file will be opened for both reading and writing. To avoid
857** a potential security problem, we do not allow the file to have
858** previously existed. Nor do we allow the file to be a symbolic
859** link.
860**
861** If delFlag is true, then make arrangements to automatically delete
862** the file when it is closed.
863**
864** On success, write the file handle into *id and return SQLITE_OK.
865**
866** On failure, return SQLITE_CANTOPEN.
867*/
danielk197762079062007-08-15 17:08:46 +0000868int sqlite3UnixOpenExclusive(
869 const char *zFilename,
870 sqlite3_file **pId,
871 int delFlag
872){
drhbfe66312006-10-03 17:40:40 +0000873 int h;
drh9cbe6352005-11-29 03:13:21 +0000874
875 assert( 0==*pId );
drhbfe66312006-10-03 17:40:40 +0000876 h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000877 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
drh3f56e6e2007-03-15 01:16:47 +0000878 delFlag ? 0600 : SQLITE_DEFAULT_FILE_PERMISSIONS);
drhbfe66312006-10-03 17:40:40 +0000879 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000880 return SQLITE_CANTOPEN;
881 }
danielk197762079062007-08-15 17:08:46 +0000882 return CRASH_TEST_OVERRIDE(
883 zFilename, pId, allocateUnixFile(h, pId, zFilename, delFlag)
884 );
drhbbd42a62004-05-22 17:41:58 +0000885}
886
887/*
888** Attempt to open a new file for read-only access.
889**
890** On success, write the file handle into *id and return SQLITE_OK.
891**
892** On failure, return SQLITE_CANTOPEN.
893*/
danielk197762079062007-08-15 17:08:46 +0000894int sqlite3UnixOpenReadOnly(const char *zFilename, sqlite3_file **pId){
drhbfe66312006-10-03 17:40:40 +0000895 int h;
896
drh9cbe6352005-11-29 03:13:21 +0000897 assert( 0==*pId );
drhbfe66312006-10-03 17:40:40 +0000898 h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
899 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000900 return SQLITE_CANTOPEN;
901 }
danielk197762079062007-08-15 17:08:46 +0000902 return CRASH_TEST_OVERRIDE(
903 zFilename, pId, allocateUnixFile(h, pId, zFilename, 0)
904 );
drhbbd42a62004-05-22 17:41:58 +0000905}
906
907/*
908** Attempt to open a file descriptor for the directory that contains a
909** file. This file descriptor can be used to fsync() the directory
910** in order to make sure the creation of a new file is actually written
911** to disk.
912**
913** This routine is only meaningful for Unix. It is a no-op under
914** windows since windows does not support hard links.
915**
drhbfe66312006-10-03 17:40:40 +0000916** If FULL_FSYNC is enabled, this function is not longer useful,
917** a FULL_FSYNC sync applies to all pending disk operations.
918**
drh9cbe6352005-11-29 03:13:21 +0000919** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000920** updated with the new directory file descriptor and SQLITE_OK is
921** returned.
922**
923** On failure, the function returns SQLITE_CANTOPEN and leaves
924** *id unchanged.
925*/
drh9c06c952005-11-26 00:25:00 +0000926static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000927 OsFile *id,
928 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000929){
drhe78669b2007-06-29 12:04:26 +0000930 int h;
drh054889e2005-11-30 03:20:31 +0000931 unixFile *pFile = (unixFile*)id;
drhbb5f18d2007-04-06 18:23:17 +0000932 assert( pFile!=0 );
drh054889e2005-11-30 03:20:31 +0000933 SET_THREADID(pFile);
934 assert( pFile->dirfd<0 );
drhe78669b2007-06-29 12:04:26 +0000935 pFile->dirfd = h = open(zDirname, O_RDONLY|O_BINARY, 0);
936 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000937 return SQLITE_CANTOPEN;
938 }
drhe78669b2007-06-29 12:04:26 +0000939#ifdef FD_CLOEXEC
940 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
941#endif
942 OSTRACE3("OPENDIR %-3d %s\n", h, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000943 return SQLITE_OK;
944}
945
946/*
947** Create a temporary file name in zBuf. zBuf must be big enough to
948** hold at least SQLITE_TEMPNAME_SIZE characters.
949*/
drh66560ad2006-01-06 14:32:19 +0000950int sqlite3UnixTempFileName(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +0000951 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000952 0,
drhbbd42a62004-05-22 17:41:58 +0000953 "/var/tmp",
954 "/usr/tmp",
955 "/tmp",
956 ".",
957 };
drh57196282004-10-06 15:41:16 +0000958 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000959 "abcdefghijklmnopqrstuvwxyz"
960 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
961 "0123456789";
962 int i, j;
963 struct stat buf;
964 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000965 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000966 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000967 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000968 if( stat(azDirs[i], &buf) ) continue;
969 if( !S_ISDIR(buf.st_mode) ) continue;
970 if( access(azDirs[i], 07) ) continue;
971 zDir = azDirs[i];
972 break;
973 }
974 do{
drh5bb3eb92007-05-04 13:15:55 +0000975 sqlite3_snprintf(SQLITE_TEMPNAME_SIZE, zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
drhbbd42a62004-05-22 17:41:58 +0000976 j = strlen(zBuf);
977 sqlite3Randomness(15, &zBuf[j]);
978 for(i=0; i<15; i++, j++){
979 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
980 }
981 zBuf[j] = 0;
982 }while( access(zBuf,0)==0 );
983 return SQLITE_OK;
984}
985
986/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000987** Check that a given pathname is a directory and is writable
988**
989*/
drh66560ad2006-01-06 14:32:19 +0000990int sqlite3UnixIsDirWritable(char *zBuf){
drh9c06c952005-11-26 00:25:00 +0000991#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000992 struct stat buf;
993 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000994 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000995 if( stat(zBuf, &buf) ) return 0;
996 if( !S_ISDIR(buf.st_mode) ) return 0;
997 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000998#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000999 return 1;
1000}
1001
1002/*
drhb912b282006-03-23 22:42:20 +00001003** Seek to the offset in id->offset then read cnt bytes into pBuf.
1004** Return the number of bytes actually read. Update the offset.
1005*/
danielk197762079062007-08-15 17:08:46 +00001006static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +00001007 int got;
drh8ebf6702007-02-06 11:11:08 +00001008 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +00001009 TIMER_START;
drh8350a212007-03-22 15:22:06 +00001010#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +00001011 got = pread(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +00001012 SimulateIOError( got = -1 );
drh8350a212007-03-22 15:22:06 +00001013#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +00001014 got = pread64(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +00001015 SimulateIOError( got = -1 );
drhb912b282006-03-23 22:42:20 +00001016#else
danielk197762079062007-08-15 17:08:46 +00001017 newOffset = lseek(id->h, offset, SEEK_SET);
drhbb5f18d2007-04-06 18:23:17 +00001018 SimulateIOError( newOffset-- );
danielk197762079062007-08-15 17:08:46 +00001019 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +00001020 return -1;
1021 }
drhb912b282006-03-23 22:42:20 +00001022 got = read(id->h, pBuf, cnt);
1023#endif
drh15d00c42007-02-27 02:01:14 +00001024 TIMER_END;
drh4f0c5872007-03-26 22:05:01 +00001025 OSTRACE5("READ %-3d %5d %7lld %d\n", id->h, got, id->offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +00001026 return got;
1027}
1028
1029/*
drhbbd42a62004-05-22 17:41:58 +00001030** Read data from a file into a buffer. Return SQLITE_OK if all
1031** bytes were read successfully and SQLITE_IOERR if anything goes
1032** wrong.
1033*/
danielk197762079062007-08-15 17:08:46 +00001034static int unixRead(
1035 sqlite3_file *id,
1036 void *pBuf,
1037 int amt,
1038 sqlite3_int64 offset
1039){
drhbbd42a62004-05-22 17:41:58 +00001040 int got;
drh9cbe6352005-11-29 03:13:21 +00001041 assert( id );
danielk197762079062007-08-15 17:08:46 +00001042 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +00001043 if( got==amt ){
1044 return SQLITE_OK;
drh4ac285a2006-09-15 07:28:50 +00001045 }else if( got<0 ){
1046 return SQLITE_IOERR_READ;
drhbbd42a62004-05-22 17:41:58 +00001047 }else{
drhbafda092007-01-03 23:36:22 +00001048 memset(&((char*)pBuf)[got], 0, amt-got);
drh4ac285a2006-09-15 07:28:50 +00001049 return SQLITE_IOERR_SHORT_READ;
drhbbd42a62004-05-22 17:41:58 +00001050 }
1051}
1052
1053/*
drhb912b282006-03-23 22:42:20 +00001054** Seek to the offset in id->offset then read cnt bytes into pBuf.
1055** Return the number of bytes actually read. Update the offset.
1056*/
danielk197762079062007-08-15 17:08:46 +00001057static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +00001058 int got;
drh8ebf6702007-02-06 11:11:08 +00001059 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +00001060 TIMER_START;
drh8350a212007-03-22 15:22:06 +00001061#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +00001062 got = pwrite(id->h, pBuf, cnt, offset);
drh8350a212007-03-22 15:22:06 +00001063#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +00001064 got = pwrite64(id->h, pBuf, cnt, offset);
drhb912b282006-03-23 22:42:20 +00001065#else
danielk197762079062007-08-15 17:08:46 +00001066 newOffset = lseek(id->h, offset, SEEK_SET);
1067 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +00001068 return -1;
1069 }
drhb912b282006-03-23 22:42:20 +00001070 got = write(id->h, pBuf, cnt);
1071#endif
drh15d00c42007-02-27 02:01:14 +00001072 TIMER_END;
danielk197762079062007-08-15 17:08:46 +00001073 OSTRACE5("WRITE %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +00001074 return got;
1075}
1076
1077
1078/*
drhbbd42a62004-05-22 17:41:58 +00001079** Write data from a buffer into a file. Return SQLITE_OK on success
1080** or some other error code on failure.
1081*/
danielk197762079062007-08-15 17:08:46 +00001082static int unixWrite(
1083 sqlite3_file *id,
1084 const void *pBuf,
1085 int amt,
1086 sqlite3_int64 offset
1087){
drhbbd42a62004-05-22 17:41:58 +00001088 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +00001089 assert( id );
drh4c7f9412005-02-03 00:29:47 +00001090 assert( amt>0 );
danielk197762079062007-08-15 17:08:46 +00001091 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +00001092 amt -= wrote;
danielk197762079062007-08-15 17:08:46 +00001093 offset += wrote;
drhbbd42a62004-05-22 17:41:58 +00001094 pBuf = &((char*)pBuf)[wrote];
1095 }
drh59685932006-09-14 13:47:11 +00001096 SimulateIOError(( wrote=(-1), amt=1 ));
1097 SimulateDiskfullError(( wrote=0, amt=1 ));
drhbbd42a62004-05-22 17:41:58 +00001098 if( amt>0 ){
drh59685932006-09-14 13:47:11 +00001099 if( wrote<0 ){
drh4ac285a2006-09-15 07:28:50 +00001100 return SQLITE_IOERR_WRITE;
drh59685932006-09-14 13:47:11 +00001101 }else{
1102 return SQLITE_FULL;
1103 }
drhbbd42a62004-05-22 17:41:58 +00001104 }
1105 return SQLITE_OK;
1106}
1107
1108/*
1109** Move the read/write pointer in a file.
1110*/
drh9c06c952005-11-26 00:25:00 +00001111static int unixSeek(OsFile *id, i64 offset){
drh9cbe6352005-11-29 03:13:21 +00001112 assert( id );
drhb4746b92005-09-09 01:32:06 +00001113#ifdef SQLITE_TEST
drh59685932006-09-14 13:47:11 +00001114 if( offset ) SimulateDiskfullError(return SQLITE_FULL);
drhb4746b92005-09-09 01:32:06 +00001115#endif
drhb912b282006-03-23 22:42:20 +00001116 ((unixFile*)id)->offset = offset;
drhbbd42a62004-05-22 17:41:58 +00001117 return SQLITE_OK;
1118}
1119
drhb851b2c2005-03-10 14:11:12 +00001120#ifdef SQLITE_TEST
1121/*
1122** Count the number of fullsyncs and normal syncs. This is used to test
1123** that syncs and fullsyncs are occuring at the right times.
1124*/
1125int sqlite3_sync_count = 0;
1126int sqlite3_fullsync_count = 0;
1127#endif
1128
drhf2f23912005-10-05 10:29:36 +00001129/*
1130** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
1131** Otherwise use fsync() in its place.
1132*/
1133#ifndef HAVE_FDATASYNC
1134# define fdatasync fsync
1135#endif
1136
drhac530b12006-02-11 01:25:50 +00001137/*
1138** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
1139** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
1140** only available on Mac OS X. But that could change.
1141*/
1142#ifdef F_FULLFSYNC
1143# define HAVE_FULLFSYNC 1
1144#else
1145# define HAVE_FULLFSYNC 0
1146#endif
1147
drhb851b2c2005-03-10 14:11:12 +00001148
drhbbd42a62004-05-22 17:41:58 +00001149/*
drhdd809b02004-07-17 21:44:57 +00001150** The fsync() system call does not work as advertised on many
1151** unix systems. The following procedure is an attempt to make
1152** it work better.
drh1398ad32005-01-19 23:24:50 +00001153**
1154** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
1155** for testing when we want to run through the test suite quickly.
1156** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
1157** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
1158** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +00001159*/
drheb796a72005-09-08 12:38:41 +00001160static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +00001161 int rc;
drhb851b2c2005-03-10 14:11:12 +00001162
1163 /* Record the number of times that we do a normal fsync() and
1164 ** FULLSYNC. This is used during testing to verify that this procedure
1165 ** gets called with the correct arguments.
1166 */
1167#ifdef SQLITE_TEST
1168 if( fullSync ) sqlite3_fullsync_count++;
1169 sqlite3_sync_count++;
1170#endif
1171
1172 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
1173 ** no-op
1174 */
1175#ifdef SQLITE_NO_SYNC
1176 rc = SQLITE_OK;
1177#else
1178
drhac530b12006-02-11 01:25:50 +00001179#if HAVE_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +00001180 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +00001181 rc = fcntl(fd, F_FULLFSYNC, 0);
aswiftae0943b2007-01-31 23:37:07 +00001182 }else{
1183 rc = 1;
1184 }
1185 /* If the FULLFSYNC failed, fall back to attempting an fsync().
1186 * It shouldn't be possible for fullfsync to fail on the local
1187 * file system (on OSX), so failure indicates that FULLFSYNC
1188 * isn't supported for this file system. So, attempt an fsync
1189 * and (for now) ignore the overhead of a superfluous fcntl call.
1190 * It'd be better to detect fullfsync support once and avoid
1191 * the fcntl call every time sync is called.
1192 */
1193 if( rc ) rc = fsync(fd);
1194
1195#else
drheb796a72005-09-08 12:38:41 +00001196 if( dataOnly ){
1197 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +00001198 }else{
drheb796a72005-09-08 12:38:41 +00001199 rc = fsync(fd);
1200 }
aswiftae0943b2007-01-31 23:37:07 +00001201#endif /* HAVE_FULLFSYNC */
drhb851b2c2005-03-10 14:11:12 +00001202#endif /* defined(SQLITE_NO_SYNC) */
1203
drhdd809b02004-07-17 21:44:57 +00001204 return rc;
1205}
1206
1207/*
drhbbd42a62004-05-22 17:41:58 +00001208** Make sure all writes to a particular file are committed to disk.
1209**
drheb796a72005-09-08 12:38:41 +00001210** If dataOnly==0 then both the file itself and its metadata (file
1211** size, access time, etc) are synced. If dataOnly!=0 then only the
1212** file data is synced.
1213**
drhbbd42a62004-05-22 17:41:58 +00001214** Under Unix, also make sure that the directory entry for the file
1215** has been created by fsync-ing the directory that contains the file.
1216** If we do not do this and we encounter a power failure, the directory
1217** entry for the journal might not exist after we reboot. The next
1218** SQLite to access the file will not know that the journal exists (because
1219** the directory entry for the journal was never created) and the transaction
1220** will not roll back - possibly leading to database corruption.
1221*/
danielk197762079062007-08-15 17:08:46 +00001222static int unixSync(sqlite3_file *id, int dataOnly){
drh59685932006-09-14 13:47:11 +00001223 int rc;
drh054889e2005-11-30 03:20:31 +00001224 unixFile *pFile = (unixFile*)id;
1225 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001226 OSTRACE2("SYNC %-3d\n", pFile->h);
drh59685932006-09-14 13:47:11 +00001227 rc = full_fsync(pFile->h, pFile->fullSync, dataOnly);
1228 SimulateIOError( rc=1 );
1229 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001230 return SQLITE_IOERR_FSYNC;
drhbbd42a62004-05-22 17:41:58 +00001231 }
drh054889e2005-11-30 03:20:31 +00001232 if( pFile->dirfd>=0 ){
drh4f0c5872007-03-26 22:05:01 +00001233 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
drhac530b12006-02-11 01:25:50 +00001234 HAVE_FULLFSYNC, pFile->fullSync);
danielk1977d7c03f72005-11-25 10:38:22 +00001235#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001236 /* The directory sync is only attempted if full_fsync is
1237 ** turned off or unavailable. If a full_fsync occurred above,
1238 ** then the directory sync is superfluous.
1239 */
1240 if( (!HAVE_FULLFSYNC || !pFile->fullSync) && full_fsync(pFile->dirfd,0,0) ){
1241 /*
1242 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001243 ** errors when applied to directories on certain file systems.
1244 ** A failed directory sync is not a big deal. So it seems
1245 ** better to ignore the error. Ticket #1657
1246 */
1247 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001248 }
danielk1977d7c03f72005-11-25 10:38:22 +00001249#endif
drh054889e2005-11-30 03:20:31 +00001250 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1251 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001252 }
drha2854222004-06-17 19:04:17 +00001253 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001254}
1255
1256/*
danielk1977962398d2004-06-14 09:35:16 +00001257** Sync the directory zDirname. This is a no-op on operating systems other
1258** than UNIX.
drhb851b2c2005-03-10 14:11:12 +00001259**
1260** This is used to make sure the master journal file has truely been deleted
1261** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +00001262** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +00001263*/
drh66560ad2006-01-06 14:32:19 +00001264int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +00001265#ifdef SQLITE_DISABLE_DIRSYNC
1266 return SQLITE_OK;
1267#else
danielk1977962398d2004-06-14 09:35:16 +00001268 int fd;
1269 int r;
drh8e855772005-05-17 11:25:31 +00001270 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh4f0c5872007-03-26 22:05:01 +00001271 OSTRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001272 if( fd<0 ){
1273 return SQLITE_CANTOPEN;
1274 }
1275 r = fsync(fd);
1276 close(fd);
drh59685932006-09-14 13:47:11 +00001277 SimulateIOError( r=1 );
1278 if( r ){
drh4ac285a2006-09-15 07:28:50 +00001279 return SQLITE_IOERR_DIR_FSYNC;
drh59685932006-09-14 13:47:11 +00001280 }else{
1281 return SQLITE_OK;
1282 }
danielk1977d7c03f72005-11-25 10:38:22 +00001283#endif
danielk1977962398d2004-06-14 09:35:16 +00001284}
1285
1286/*
drhbbd42a62004-05-22 17:41:58 +00001287** Truncate an open file to a specified size
1288*/
danielk197762079062007-08-15 17:08:46 +00001289static int unixTruncate(sqlite3_file *id, i64 nByte){
drh59685932006-09-14 13:47:11 +00001290 int rc;
drh9cbe6352005-11-29 03:13:21 +00001291 assert( id );
drh63fff5f2007-06-19 10:50:38 +00001292 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
drh59685932006-09-14 13:47:11 +00001293 SimulateIOError( rc=1 );
1294 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001295 return SQLITE_IOERR_TRUNCATE;
drh59685932006-09-14 13:47:11 +00001296 }else{
1297 return SQLITE_OK;
1298 }
drhbbd42a62004-05-22 17:41:58 +00001299}
1300
1301/*
1302** Determine the current size of a file in bytes
1303*/
danielk197762079062007-08-15 17:08:46 +00001304static int unixFileSize(sqlite3_file *id, i64 *pSize){
drh59685932006-09-14 13:47:11 +00001305 int rc;
drhbbd42a62004-05-22 17:41:58 +00001306 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001307 assert( id );
drh59685932006-09-14 13:47:11 +00001308 rc = fstat(((unixFile*)id)->h, &buf);
1309 SimulateIOError( rc=1 );
1310 if( rc!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001311 return SQLITE_IOERR_FSTAT;
drhbbd42a62004-05-22 17:41:58 +00001312 }
1313 *pSize = buf.st_size;
1314 return SQLITE_OK;
1315}
1316
danielk19779a1d0ab2004-06-01 14:09:28 +00001317/*
danielk197713adf8a2004-06-03 16:08:41 +00001318** This routine checks if there is a RESERVED lock held on the specified
1319** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001320** non-zero. If the file is unlocked or holds only SHARED locks, then
1321** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001322*/
danielk197762079062007-08-15 17:08:46 +00001323static int unixCheckReservedLock(sqlite3_file *id){
danielk197713adf8a2004-06-03 16:08:41 +00001324 int r = 0;
drh054889e2005-11-30 03:20:31 +00001325 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001326
drh054889e2005-11-30 03:20:31 +00001327 assert( pFile );
drh66560ad2006-01-06 14:32:19 +00001328 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001329
1330 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001331 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001332 r = 1;
1333 }
1334
drh2ac3ee92004-06-07 16:27:46 +00001335 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001336 */
1337 if( !r ){
1338 struct flock lock;
1339 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001340 lock.l_start = RESERVED_BYTE;
1341 lock.l_len = 1;
1342 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001343 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001344 if( lock.l_type!=F_UNLCK ){
1345 r = 1;
1346 }
1347 }
1348
drh66560ad2006-01-06 14:32:19 +00001349 sqlite3OsLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001350 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001351
1352 return r;
1353}
1354
1355/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001356** Lock the file with the lock specified by parameter locktype - one
1357** of the following:
1358**
drh2ac3ee92004-06-07 16:27:46 +00001359** (1) SHARED_LOCK
1360** (2) RESERVED_LOCK
1361** (3) PENDING_LOCK
1362** (4) EXCLUSIVE_LOCK
1363**
drhb3e04342004-06-08 00:47:47 +00001364** Sometimes when requesting one lock state, additional lock states
1365** are inserted in between. The locking might fail on one of the later
1366** transitions leaving the lock state different from what it started but
1367** still short of its goal. The following chart shows the allowed
1368** transitions and the inserted intermediate states:
1369**
1370** UNLOCKED -> SHARED
1371** SHARED -> RESERVED
1372** SHARED -> (PENDING) -> EXCLUSIVE
1373** RESERVED -> (PENDING) -> EXCLUSIVE
1374** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001375**
drha6abd042004-06-09 17:37:22 +00001376** This routine will only increase a lock. Use the sqlite3OsUnlock()
1377** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001378*/
danielk197762079062007-08-15 17:08:46 +00001379static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001380 /* The following describes the implementation of the various locks and
1381 ** lock transitions in terms of the POSIX advisory shared and exclusive
1382 ** lock primitives (called read-locks and write-locks below, to avoid
1383 ** confusion with SQLite lock names). The algorithms are complicated
1384 ** slightly in order to be compatible with windows systems simultaneously
1385 ** accessing the same database file, in case that is ever required.
1386 **
1387 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1388 ** byte', each single bytes at well known offsets, and the 'shared byte
1389 ** range', a range of 510 bytes at a well known offset.
1390 **
1391 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1392 ** byte'. If this is successful, a random byte from the 'shared byte
1393 ** range' is read-locked and the lock on the 'pending byte' released.
1394 **
danielk197790ba3bd2004-06-25 08:32:25 +00001395 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1396 ** A RESERVED lock is implemented by grabbing a write-lock on the
1397 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001398 **
1399 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001400 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1401 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1402 ** obtained, but existing SHARED locks are allowed to persist. A process
1403 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1404 ** This property is used by the algorithm for rolling back a journal file
1405 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001406 **
danielk197790ba3bd2004-06-25 08:32:25 +00001407 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1408 ** implemented by obtaining a write-lock on the entire 'shared byte
1409 ** range'. Since all other locks require a read-lock on one of the bytes
1410 ** within this range, this ensures that no other locks are held on the
1411 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001412 **
1413 ** The reason a single byte cannot be used instead of the 'shared byte
1414 ** range' is that some versions of windows do not support read-locks. By
1415 ** locking a random byte from a range, concurrent SHARED locks may exist
1416 ** even if the locking primitive used is always a write-lock.
1417 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001418 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001419 unixFile *pFile = (unixFile*)id;
1420 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001421 struct flock lock;
1422 int s;
1423
drh054889e2005-11-30 03:20:31 +00001424 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001425 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001426 locktypeName(locktype), locktypeName(pFile->locktype),
1427 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001428
1429 /* If there is already a lock of this type or more restrictive on the
1430 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh66560ad2006-01-06 14:32:19 +00001431 ** sqlite3OsEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001432 */
drh054889e2005-11-30 03:20:31 +00001433 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001434 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001435 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001436 return SQLITE_OK;
1437 }
1438
drhb3e04342004-06-08 00:47:47 +00001439 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001440 */
drh054889e2005-11-30 03:20:31 +00001441 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001442 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001443 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001444
drh054889e2005-11-30 03:20:31 +00001445 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001446 */
drh66560ad2006-01-06 14:32:19 +00001447 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001448
drh029b44b2006-01-15 00:13:15 +00001449 /* Make sure the current thread owns the pFile.
1450 */
1451 rc = transferOwnership(pFile);
1452 if( rc!=SQLITE_OK ){
1453 sqlite3OsLeaveMutex();
1454 return rc;
1455 }
drh64b1bea2006-01-15 02:30:57 +00001456 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001457
danielk19779a1d0ab2004-06-01 14:09:28 +00001458 /* If some thread using this PID has a lock via a different OsFile*
1459 ** handle that precludes the requested lock, return BUSY.
1460 */
drh054889e2005-11-30 03:20:31 +00001461 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001462 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001463 ){
1464 rc = SQLITE_BUSY;
1465 goto end_lock;
1466 }
1467
1468 /* If a SHARED lock is requested, and some thread using this PID already
1469 ** has a SHARED or RESERVED lock, then increment reference counts and
1470 ** return SQLITE_OK.
1471 */
1472 if( locktype==SHARED_LOCK &&
1473 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1474 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001475 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001476 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001477 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001478 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001479 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001480 goto end_lock;
1481 }
1482
danielk197713adf8a2004-06-03 16:08:41 +00001483 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001484
danielk19779a1d0ab2004-06-01 14:09:28 +00001485 lock.l_whence = SEEK_SET;
1486
drh3cde3bb2004-06-12 02:17:14 +00001487 /* A PENDING lock is needed before acquiring a SHARED lock and before
1488 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1489 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001490 */
drh3cde3bb2004-06-12 02:17:14 +00001491 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001492 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001493 ){
danielk1977489468c2004-06-28 08:25:47 +00001494 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001495 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001496 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001497 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001498 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1499 goto end_lock;
1500 }
drh3cde3bb2004-06-12 02:17:14 +00001501 }
1502
1503
1504 /* If control gets to this point, then actually go ahead and make
1505 ** operating system calls for the specified lock.
1506 */
1507 if( locktype==SHARED_LOCK ){
1508 assert( pLock->cnt==0 );
1509 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001510
drh2ac3ee92004-06-07 16:27:46 +00001511 /* Now get the read-lock */
1512 lock.l_start = SHARED_FIRST;
1513 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001514 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001515
1516 /* Drop the temporary PENDING lock */
1517 lock.l_start = PENDING_BYTE;
1518 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001519 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001520 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001521 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001522 goto end_lock;
1523 }
drhe2396a12007-03-29 20:19:58 +00001524 if( s==(-1) ){
drhbbd42a62004-05-22 17:41:58 +00001525 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1526 }else{
drh054889e2005-11-30 03:20:31 +00001527 pFile->locktype = SHARED_LOCK;
1528 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001529 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001530 }
drh3cde3bb2004-06-12 02:17:14 +00001531 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1532 /* We are trying for an exclusive lock but another thread in this
1533 ** same process is still holding a shared lock. */
1534 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001535 }else{
drh3cde3bb2004-06-12 02:17:14 +00001536 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001537 ** assumed that there is a SHARED or greater lock on the file
1538 ** already.
1539 */
drh054889e2005-11-30 03:20:31 +00001540 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001541 lock.l_type = F_WRLCK;
1542 switch( locktype ){
1543 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001544 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001545 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001546 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001547 lock.l_start = SHARED_FIRST;
1548 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001549 break;
1550 default:
1551 assert(0);
1552 }
drh054889e2005-11-30 03:20:31 +00001553 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001554 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001555 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1556 }
drhbbd42a62004-05-22 17:41:58 +00001557 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001558
danielk1977ecb2a962004-06-02 06:30:16 +00001559 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001560 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001561 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001562 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001563 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001564 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001565 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001566
1567end_lock:
drh66560ad2006-01-06 14:32:19 +00001568 sqlite3OsLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001569 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001570 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001571 return rc;
1572}
1573
1574/*
drh054889e2005-11-30 03:20:31 +00001575** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001576** must be either NO_LOCK or SHARED_LOCK.
1577**
1578** If the locking level of the file descriptor is already at or below
1579** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001580*/
danielk197762079062007-08-15 17:08:46 +00001581static int unixUnlock(sqlite3_file *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001582 struct lockInfo *pLock;
1583 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001584 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001585 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001586
drh054889e2005-11-30 03:20:31 +00001587 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001588 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001589 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001590
1591 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001592 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001593 return SQLITE_OK;
1594 }
drhf1a221e2006-01-15 17:27:17 +00001595 if( CHECK_THREADID(pFile) ){
1596 return SQLITE_MISUSE;
1597 }
drh66560ad2006-01-06 14:32:19 +00001598 sqlite3OsEnterMutex();
drh054889e2005-11-30 03:20:31 +00001599 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001600 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001601 if( pFile->locktype>SHARED_LOCK ){
1602 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001603 if( locktype==SHARED_LOCK ){
1604 lock.l_type = F_RDLCK;
1605 lock.l_whence = SEEK_SET;
1606 lock.l_start = SHARED_FIRST;
1607 lock.l_len = SHARED_SIZE;
drhe2396a12007-03-29 20:19:58 +00001608 if( fcntl(pFile->h, F_SETLK, &lock)==(-1) ){
drh9c105bb2004-10-02 20:38:28 +00001609 /* This should never happen */
drh4ac285a2006-09-15 07:28:50 +00001610 rc = SQLITE_IOERR_RDLOCK;
drh9c105bb2004-10-02 20:38:28 +00001611 }
1612 }
drhbbd42a62004-05-22 17:41:58 +00001613 lock.l_type = F_UNLCK;
1614 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001615 lock.l_start = PENDING_BYTE;
1616 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drhe2396a12007-03-29 20:19:58 +00001617 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001618 pLock->locktype = SHARED_LOCK;
1619 }else{
drh4ac285a2006-09-15 07:28:50 +00001620 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001621 }
drhbbd42a62004-05-22 17:41:58 +00001622 }
drha6abd042004-06-09 17:37:22 +00001623 if( locktype==NO_LOCK ){
1624 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001625
drha6abd042004-06-09 17:37:22 +00001626 /* Decrement the shared lock counter. Release the lock using an
1627 ** OS call only when all threads in this same process have released
1628 ** the lock.
1629 */
1630 pLock->cnt--;
1631 if( pLock->cnt==0 ){
1632 lock.l_type = F_UNLCK;
1633 lock.l_whence = SEEK_SET;
1634 lock.l_start = lock.l_len = 0L;
drhe2396a12007-03-29 20:19:58 +00001635 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001636 pLock->locktype = NO_LOCK;
1637 }else{
drh4ac285a2006-09-15 07:28:50 +00001638 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001639 }
drha6abd042004-06-09 17:37:22 +00001640 }
1641
drhbbd42a62004-05-22 17:41:58 +00001642 /* Decrement the count of locks against this same file. When the
1643 ** count reaches zero, close any other file descriptors whose close
1644 ** was deferred because of outstanding locks.
1645 */
drh054889e2005-11-30 03:20:31 +00001646 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001647 pOpen->nLock--;
1648 assert( pOpen->nLock>=0 );
1649 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1650 int i;
1651 for(i=0; i<pOpen->nPending; i++){
1652 close(pOpen->aPending[i]);
1653 }
drh64b1bea2006-01-15 02:30:57 +00001654 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001655 pOpen->nPending = 0;
1656 pOpen->aPending = 0;
1657 }
1658 }
drh66560ad2006-01-06 14:32:19 +00001659 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001660 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001661 return rc;
drhbbd42a62004-05-22 17:41:58 +00001662}
1663
1664/*
danielk1977e3026632004-06-22 11:29:02 +00001665** Close a file.
1666*/
danielk197762079062007-08-15 17:08:46 +00001667static int unixClose(sqlite3_file *id){
1668 unixFile *pFile = (unixFile *)id;
1669 if( !pFile ) return SQLITE_OK;
1670 unixUnlock(id, NO_LOCK);
1671 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1672 pFile->dirfd = -1;
drh66560ad2006-01-06 14:32:19 +00001673 sqlite3OsEnterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001674
danielk197762079062007-08-15 17:08:46 +00001675 if( pFile->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001676 /* If there are outstanding locks, do not actually close the file just
1677 ** yet because that would clear those locks. Instead, add the file
1678 ** descriptor to pOpen->aPending. It will be automatically closed when
1679 ** the last lock is cleared.
1680 */
1681 int *aNew;
danielk197762079062007-08-15 17:08:46 +00001682 struct openCnt *pOpen = pFile->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001683 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001684 if( aNew==0 ){
1685 /* If a malloc fails, just leak the file descriptor */
1686 }else{
1687 pOpen->aPending = aNew;
danielk197762079062007-08-15 17:08:46 +00001688 pOpen->aPending[pOpen->nPending] = pFile->h;
drhad81e872005-08-21 21:45:01 +00001689 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001690 }
1691 }else{
1692 /* There are no outstanding locks so we can close the file immediately */
danielk197762079062007-08-15 17:08:46 +00001693 close(pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001694 }
danielk197762079062007-08-15 17:08:46 +00001695 releaseLockInfo(pFile->pLock);
1696 releaseOpenCnt(pFile->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001697
drh66560ad2006-01-06 14:32:19 +00001698 sqlite3OsLeaveMutex();
danielk197762079062007-08-15 17:08:46 +00001699 pFile->isOpen = 0;
1700 OSTRACE2("CLOSE %-3d\n", pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001701 OpenCounter(-1);
drh17435752007-08-16 04:30:38 +00001702 sqlite3_free(id);
drh02afc862006-01-20 18:10:57 +00001703 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001704}
1705
drhbfe66312006-10-03 17:40:40 +00001706
1707#ifdef SQLITE_ENABLE_LOCKING_STYLE
1708#pragma mark AFP Support
1709
1710/*
1711 ** The afpLockingContext structure contains all afp lock specific state
1712 */
1713typedef struct afpLockingContext afpLockingContext;
1714struct afpLockingContext {
1715 unsigned long long sharedLockByte;
1716 char *filePath;
1717};
1718
1719struct ByteRangeLockPB2
1720{
1721 unsigned long long offset; /* offset to first byte to lock */
1722 unsigned long long length; /* nbr of bytes to lock */
1723 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
1724 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
1725 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
1726 int fd; /* file desc to assoc this lock with */
1727};
1728
drhfd131da2007-08-07 17:13:03 +00001729#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00001730
1731/* return 0 on success, 1 on failure. To match the behavior of the
1732 normal posix file locking (used in unixLock for example), we should
1733 provide 'richer' return codes - specifically to differentiate between
1734 'file busy' and 'file system error' results */
1735static int _AFPFSSetLock(const char *path, int fd, unsigned long long offset,
1736 unsigned long long length, int setLockFlag)
1737{
drhfd131da2007-08-07 17:13:03 +00001738 struct ByteRangeLockPB2 pb;
drhbfe66312006-10-03 17:40:40 +00001739 int err;
1740
1741 pb.unLockFlag = setLockFlag ? 0 : 1;
1742 pb.startEndFlag = 0;
1743 pb.offset = offset;
1744 pb.length = length;
1745 pb.fd = fd;
drh4f0c5872007-03-26 22:05:01 +00001746 OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
drhbfe66312006-10-03 17:40:40 +00001747 (setLockFlag?"ON":"OFF"), fd, offset, length);
1748 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
1749 if ( err==-1 ) {
drh4f0c5872007-03-26 22:05:01 +00001750 OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno,
drhbfe66312006-10-03 17:40:40 +00001751 strerror(errno));
drh3b62b2f2007-06-08 18:27:03 +00001752 return 1; /* error */
drhbfe66312006-10-03 17:40:40 +00001753 } else {
1754 return 0;
1755 }
1756}
1757
1758/*
1759 ** This routine checks if there is a RESERVED lock held on the specified
1760 ** file by this or any other process. If such a lock is held, return
1761 ** non-zero. If the file is unlocked or holds only SHARED locks, then
1762 ** return zero.
1763 */
1764static int afpUnixCheckReservedLock(OsFile *id){
1765 int r = 0;
1766 unixFile *pFile = (unixFile*)id;
1767
1768 assert( pFile );
1769 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1770
1771 /* Check if a thread in this process holds such a lock */
1772 if( pFile->locktype>SHARED_LOCK ){
1773 r = 1;
1774 }
1775
1776 /* Otherwise see if some other process holds it.
1777 */
1778 if ( !r ) {
drh3b62b2f2007-06-08 18:27:03 +00001779 /* lock the byte */
drhbfe66312006-10-03 17:40:40 +00001780 int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1781 if (failed) {
1782 /* if we failed to get the lock then someone else must have it */
1783 r = 1;
1784 } else {
1785 /* if we succeeded in taking the reserved lock, unlock it to restore
1786 ** the original state */
1787 _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
1788 }
1789 }
drh4f0c5872007-03-26 22:05:01 +00001790 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
drhbfe66312006-10-03 17:40:40 +00001791
1792 return r;
1793}
1794
1795/* AFP-style locking following the behavior of unixLock, see the unixLock
1796** function comments for details of lock management. */
1797static int afpUnixLock(OsFile *id, int locktype)
1798{
1799 int rc = SQLITE_OK;
1800 unixFile *pFile = (unixFile*)id;
1801 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1802 int gotPendingLock = 0;
1803
1804 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001805 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001806 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
1807 /* If there is already a lock of this type or more restrictive on the
1808 ** OsFile, do nothing. Don't use the afp_end_lock: exit path, as
1809 ** sqlite3OsEnterMutex() hasn't been called yet.
1810 */
1811 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001812 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001813 locktypeName(locktype));
1814 return SQLITE_OK;
1815 }
1816
1817 /* Make sure the locking sequence is correct
1818 */
1819 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
1820 assert( locktype!=PENDING_LOCK );
1821 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1822
1823 /* This mutex is needed because pFile->pLock is shared across threads
1824 */
1825 sqlite3OsEnterMutex();
1826
1827 /* Make sure the current thread owns the pFile.
1828 */
1829 rc = transferOwnership(pFile);
1830 if( rc!=SQLITE_OK ){
1831 sqlite3OsLeaveMutex();
1832 return rc;
1833 }
1834
1835 /* A PENDING lock is needed before acquiring a SHARED lock and before
1836 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1837 ** be released.
1838 */
1839 if( locktype==SHARED_LOCK
1840 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
1841 ){
1842 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1843 PENDING_BYTE, 1, 1);
1844 if (failed) {
1845 rc = SQLITE_BUSY;
1846 goto afp_end_lock;
1847 }
1848 }
1849
1850 /* If control gets to this point, then actually go ahead and make
1851 ** operating system calls for the specified lock.
1852 */
1853 if( locktype==SHARED_LOCK ){
1854 int lk, failed;
1855 int tries = 0;
1856
1857 /* Now get the read-lock */
1858 /* note that the quality of the randomness doesn't matter that much */
1859 lk = random();
1860 context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
1861 failed = _AFPFSSetLock(context->filePath, pFile->h,
1862 SHARED_FIRST+context->sharedLockByte, 1, 1);
1863
1864 /* Drop the temporary PENDING lock */
1865 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
1866 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1867 goto afp_end_lock;
1868 }
1869
1870 if( failed ){
1871 rc = SQLITE_BUSY;
1872 } else {
1873 pFile->locktype = SHARED_LOCK;
1874 }
1875 }else{
1876 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1877 ** assumed that there is a SHARED or greater lock on the file
1878 ** already.
1879 */
1880 int failed = 0;
1881 assert( 0!=pFile->locktype );
1882 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
1883 /* Acquire a RESERVED lock */
1884 failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1885 }
1886 if (!failed && locktype == EXCLUSIVE_LOCK) {
1887 /* Acquire an EXCLUSIVE lock */
1888
1889 /* Remove the shared lock before trying the range. we'll need to
1890 ** reestablish the shared lock if we can't get the afpUnixUnlock
1891 */
1892 if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1893 context->sharedLockByte, 1, 0)) {
1894 /* now attemmpt to get the exclusive lock range */
1895 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1896 SHARED_SIZE, 1);
1897 if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1898 context->sharedLockByte, 1, 1)) {
1899 rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
1900 }
1901 } else {
1902 /* */
1903 rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
1904 }
1905 }
1906 if( failed && rc == SQLITE_OK){
1907 rc = SQLITE_BUSY;
1908 }
1909 }
1910
1911 if( rc==SQLITE_OK ){
1912 pFile->locktype = locktype;
1913 }else if( locktype==EXCLUSIVE_LOCK ){
1914 pFile->locktype = PENDING_LOCK;
1915 }
1916
1917afp_end_lock:
1918 sqlite3OsLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001919 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00001920 rc==SQLITE_OK ? "ok" : "failed");
1921 return rc;
1922}
1923
1924/*
1925 ** Lower the locking level on file descriptor pFile to locktype. locktype
1926 ** must be either NO_LOCK or SHARED_LOCK.
1927 **
1928 ** If the locking level of the file descriptor is already at or below
1929 ** the requested locking level, this routine is a no-op.
1930 */
1931static int afpUnixUnlock(OsFile *id, int locktype) {
1932 struct flock lock;
1933 int rc = SQLITE_OK;
1934 unixFile *pFile = (unixFile*)id;
1935 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1936
1937 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001938 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00001939 pFile->locktype, getpid());
1940
1941 assert( locktype<=SHARED_LOCK );
1942 if( pFile->locktype<=locktype ){
1943 return SQLITE_OK;
1944 }
1945 if( CHECK_THREADID(pFile) ){
1946 return SQLITE_MISUSE;
1947 }
1948 sqlite3OsEnterMutex();
1949 if( pFile->locktype>SHARED_LOCK ){
1950 if( locktype==SHARED_LOCK ){
1951 int failed = 0;
1952
1953 /* unlock the exclusive range - then re-establish the shared lock */
1954 if (pFile->locktype==EXCLUSIVE_LOCK) {
1955 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1956 SHARED_SIZE, 0);
1957 if (!failed) {
1958 /* successfully removed the exclusive lock */
1959 if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
1960 context->sharedLockByte, 1, 1)) {
1961 /* failed to re-establish our shared lock */
1962 rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
1963 }
1964 } else {
1965 /* This should never happen - failed to unlock the exclusive range */
1966 rc = SQLITE_IOERR_UNLOCK;
1967 }
1968 }
1969 }
1970 if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
1971 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
1972 /* failed to release the pending lock */
1973 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1974 }
1975 }
1976 if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
1977 if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
1978 /* failed to release the reserved lock */
1979 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1980 }
1981 }
1982 }
1983 if( locktype==NO_LOCK ){
1984 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1985 SHARED_FIRST + context->sharedLockByte, 1, 0);
1986 if (failed) {
1987 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1988 }
1989 }
1990 if (rc == SQLITE_OK)
1991 pFile->locktype = locktype;
1992 sqlite3OsLeaveMutex();
1993 return rc;
1994}
1995
1996/*
1997 ** Close a file & cleanup AFP specific locking context
1998 */
1999static int afpUnixClose(OsFile **pId) {
2000 unixFile *id = (unixFile*)*pId;
2001
2002 if( !id ) return SQLITE_OK;
2003 afpUnixUnlock(*pId, NO_LOCK);
2004 /* free the AFP locking structure */
2005 if (id->lockingContext != NULL) {
2006 if (((afpLockingContext *)id->lockingContext)->filePath != NULL)
drh17435752007-08-16 04:30:38 +00002007 sqlite3_free(((afpLockingContext*)id->lockingContext)->filePath);
2008 sqlite3_free(id->lockingContext);
drhbfe66312006-10-03 17:40:40 +00002009 }
2010
2011 if( id->dirfd>=0 ) close(id->dirfd);
2012 id->dirfd = -1;
2013 close(id->h);
2014 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00002015 OSTRACE2("CLOSE %-3d\n", id->h);
drhbfe66312006-10-03 17:40:40 +00002016 OpenCounter(-1);
drh17435752007-08-16 04:30:38 +00002017 sqlite3_free(id);
drhbfe66312006-10-03 17:40:40 +00002018 *pId = 0;
2019 return SQLITE_OK;
2020}
2021
2022
2023#pragma mark flock() style locking
2024
2025/*
2026 ** The flockLockingContext is not used
2027 */
2028typedef void flockLockingContext;
2029
2030static int flockUnixCheckReservedLock(OsFile *id) {
2031 unixFile *pFile = (unixFile*)id;
2032
2033 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00002034 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00002035 } else {
drh3b62b2f2007-06-08 18:27:03 +00002036 /* attempt to get the lock */
drhbfe66312006-10-03 17:40:40 +00002037 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
2038 if (!rc) {
drh3b62b2f2007-06-08 18:27:03 +00002039 /* got the lock, unlock it */
drhbfe66312006-10-03 17:40:40 +00002040 flock(pFile->h, LOCK_UN);
drh3b62b2f2007-06-08 18:27:03 +00002041 return 0; /* no one has it reserved */
drhbfe66312006-10-03 17:40:40 +00002042 }
drh3b62b2f2007-06-08 18:27:03 +00002043 return 1; /* someone else might have it reserved */
drhbfe66312006-10-03 17:40:40 +00002044 }
2045}
2046
2047static int flockUnixLock(OsFile *id, int locktype) {
2048 unixFile *pFile = (unixFile*)id;
2049
drh3b62b2f2007-06-08 18:27:03 +00002050 /* if we already have a lock, it is exclusive.
2051 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00002052 if (pFile->locktype > NO_LOCK) {
2053 pFile->locktype = locktype;
2054 return SQLITE_OK;
2055 }
2056
drh3b62b2f2007-06-08 18:27:03 +00002057 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00002058 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
2059 if (rc) {
drh3b62b2f2007-06-08 18:27:03 +00002060 /* didn't get, must be busy */
drhbfe66312006-10-03 17:40:40 +00002061 return SQLITE_BUSY;
2062 } else {
drh3b62b2f2007-06-08 18:27:03 +00002063 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00002064 pFile->locktype = locktype;
2065 return SQLITE_OK;
2066 }
2067}
2068
2069static int flockUnixUnlock(OsFile *id, int locktype) {
2070 unixFile *pFile = (unixFile*)id;
2071
2072 assert( locktype<=SHARED_LOCK );
2073
drh3b62b2f2007-06-08 18:27:03 +00002074 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00002075 if( pFile->locktype==locktype ){
2076 return SQLITE_OK;
2077 }
2078
drh3b62b2f2007-06-08 18:27:03 +00002079 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00002080 if (locktype==SHARED_LOCK) {
2081 pFile->locktype = locktype;
2082 return SQLITE_OK;
2083 }
2084
drh3b62b2f2007-06-08 18:27:03 +00002085 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00002086 int rc = flock(pFile->h, LOCK_UN);
2087 if (rc)
2088 return SQLITE_IOERR_UNLOCK;
2089 else {
2090 pFile->locktype = NO_LOCK;
2091 return SQLITE_OK;
2092 }
2093}
2094
2095/*
2096 ** Close a file.
2097 */
2098static int flockUnixClose(OsFile **pId) {
2099 unixFile *id = (unixFile*)*pId;
2100
2101 if( !id ) return SQLITE_OK;
2102 flockUnixUnlock(*pId, NO_LOCK);
2103
2104 if( id->dirfd>=0 ) close(id->dirfd);
2105 id->dirfd = -1;
2106 sqlite3OsEnterMutex();
2107
2108 close(id->h);
2109 sqlite3OsLeaveMutex();
2110 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00002111 OSTRACE2("CLOSE %-3d\n", id->h);
drhbfe66312006-10-03 17:40:40 +00002112 OpenCounter(-1);
drh17435752007-08-16 04:30:38 +00002113 sqlite3_free(id);
drhbfe66312006-10-03 17:40:40 +00002114 *pId = 0;
2115 return SQLITE_OK;
2116}
2117
2118#pragma mark Old-School .lock file based locking
2119
2120/*
2121 ** The dotlockLockingContext structure contains all dotlock (.lock) lock
2122 ** specific state
2123 */
2124typedef struct dotlockLockingContext dotlockLockingContext;
2125struct dotlockLockingContext {
2126 char *lockPath;
2127};
2128
2129
2130static int dotlockUnixCheckReservedLock(OsFile *id) {
2131 unixFile *pFile = (unixFile*)id;
2132 dotlockLockingContext *context =
2133 (dotlockLockingContext *) pFile->lockingContext;
2134
2135 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00002136 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00002137 } else {
2138 struct stat statBuf;
2139 if (lstat(context->lockPath,&statBuf) == 0)
drh3b62b2f2007-06-08 18:27:03 +00002140 /* file exists, someone else has the lock */
drhbfe66312006-10-03 17:40:40 +00002141 return 1;
2142 else
drh3b62b2f2007-06-08 18:27:03 +00002143 /* file does not exist, we could have it if we want it */
drhbfe66312006-10-03 17:40:40 +00002144 return 0;
2145 }
2146}
2147
2148static int dotlockUnixLock(OsFile *id, int locktype) {
2149 unixFile *pFile = (unixFile*)id;
2150 dotlockLockingContext *context =
2151 (dotlockLockingContext *) pFile->lockingContext;
2152
drh3b62b2f2007-06-08 18:27:03 +00002153 /* if we already have a lock, it is exclusive.
2154 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00002155 if (pFile->locktype > NO_LOCK) {
2156 pFile->locktype = locktype;
2157
2158 /* Always update the timestamp on the old file */
2159 utimes(context->lockPath,NULL);
2160 return SQLITE_OK;
2161 }
2162
drh3b62b2f2007-06-08 18:27:03 +00002163 /* check to see if lock file already exists */
drhbfe66312006-10-03 17:40:40 +00002164 struct stat statBuf;
2165 if (lstat(context->lockPath,&statBuf) == 0){
drh3b62b2f2007-06-08 18:27:03 +00002166 return SQLITE_BUSY; /* it does, busy */
drhbfe66312006-10-03 17:40:40 +00002167 }
2168
drh3b62b2f2007-06-08 18:27:03 +00002169 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00002170 int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
2171 if (fd < 0) {
drh3b62b2f2007-06-08 18:27:03 +00002172 /* failed to open/create the file, someone else may have stolen the lock */
drhbfe66312006-10-03 17:40:40 +00002173 return SQLITE_BUSY;
2174 }
2175 close(fd);
2176
drh3b62b2f2007-06-08 18:27:03 +00002177 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00002178 pFile->locktype = locktype;
2179 return SQLITE_OK;
2180}
2181
2182static int dotlockUnixUnlock(OsFile *id, int locktype) {
2183 unixFile *pFile = (unixFile*)id;
2184 dotlockLockingContext *context =
2185 (dotlockLockingContext *) pFile->lockingContext;
2186
2187 assert( locktype<=SHARED_LOCK );
2188
drh3b62b2f2007-06-08 18:27:03 +00002189 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00002190 if( pFile->locktype==locktype ){
2191 return SQLITE_OK;
2192 }
2193
drh3b62b2f2007-06-08 18:27:03 +00002194 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00002195 if (locktype==SHARED_LOCK) {
2196 pFile->locktype = locktype;
2197 return SQLITE_OK;
2198 }
2199
drh3b62b2f2007-06-08 18:27:03 +00002200 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00002201 unlink(context->lockPath);
2202 pFile->locktype = NO_LOCK;
2203 return SQLITE_OK;
2204}
2205
2206/*
2207 ** Close a file.
2208 */
2209static int dotlockUnixClose(OsFile **pId) {
2210 unixFile *id = (unixFile*)*pId;
2211
2212 if( !id ) return SQLITE_OK;
2213 dotlockUnixUnlock(*pId, NO_LOCK);
2214 /* free the dotlock locking structure */
2215 if (id->lockingContext != NULL) {
2216 if (((dotlockLockingContext *)id->lockingContext)->lockPath != NULL)
drh17435752007-08-16 04:30:38 +00002217 sqlite3_free( ( (dotlockLockingContext *)
drhbfe66312006-10-03 17:40:40 +00002218 id->lockingContext)->lockPath);
drh17435752007-08-16 04:30:38 +00002219 sqlite3_free(id->lockingContext);
drhbfe66312006-10-03 17:40:40 +00002220 }
2221
2222 if( id->dirfd>=0 ) close(id->dirfd);
2223 id->dirfd = -1;
2224 sqlite3OsEnterMutex();
2225
2226 close(id->h);
2227
2228 sqlite3OsLeaveMutex();
2229 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00002230 OSTRACE2("CLOSE %-3d\n", id->h);
drhbfe66312006-10-03 17:40:40 +00002231 OpenCounter(-1);
drh17435752007-08-16 04:30:38 +00002232 sqlite3_free(id);
drhbfe66312006-10-03 17:40:40 +00002233 *pId = 0;
2234 return SQLITE_OK;
2235}
2236
2237
2238#pragma mark No locking
2239
2240/*
2241 ** The nolockLockingContext is void
2242 */
2243typedef void nolockLockingContext;
2244
2245static int nolockUnixCheckReservedLock(OsFile *id) {
2246 return 0;
2247}
2248
2249static int nolockUnixLock(OsFile *id, int locktype) {
2250 return SQLITE_OK;
2251}
2252
2253static int nolockUnixUnlock(OsFile *id, int locktype) {
2254 return SQLITE_OK;
2255}
2256
2257/*
2258 ** Close a file.
2259 */
2260static int nolockUnixClose(OsFile **pId) {
2261 unixFile *id = (unixFile*)*pId;
2262
2263 if( !id ) return SQLITE_OK;
2264 if( id->dirfd>=0 ) close(id->dirfd);
2265 id->dirfd = -1;
2266 sqlite3OsEnterMutex();
2267
2268 close(id->h);
2269
2270 sqlite3OsLeaveMutex();
2271 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00002272 OSTRACE2("CLOSE %-3d\n", id->h);
drhbfe66312006-10-03 17:40:40 +00002273 OpenCounter(-1);
drh17435752007-08-16 04:30:38 +00002274 sqlite3_free(id);
drhbfe66312006-10-03 17:40:40 +00002275 *pId = 0;
2276 return SQLITE_OK;
2277}
2278
2279#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2280
danielk1977e3026632004-06-22 11:29:02 +00002281/*
drh0ccebe72005-06-07 22:22:50 +00002282** Turn a relative pathname into a full pathname. Return a pointer
2283** to the full pathname stored in space obtained from sqliteMalloc().
2284** The calling function is responsible for freeing this space once it
2285** is no longer needed.
2286*/
drh66560ad2006-01-06 14:32:19 +00002287char *sqlite3UnixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00002288 char *zFull = 0;
2289 if( zRelative[0]=='/' ){
2290 sqlite3SetString(&zFull, zRelative, (char*)0);
2291 }else{
drh17435752007-08-16 04:30:38 +00002292 char *zBuf = sqlite3_malloc(5000);
drh79158e12005-09-06 21:40:45 +00002293 if( zBuf==0 ){
2294 return 0;
2295 }
drh0ccebe72005-06-07 22:22:50 +00002296 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00002297 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00002298 (char*)0);
danielk19771e536952007-08-16 10:09:01 +00002299 sqlite3_free(zBuf);
drh0ccebe72005-06-07 22:22:50 +00002300 }
drh4eb9a972006-02-13 18:42:21 +00002301
2302#if 0
drh89ea9312006-02-13 17:03:47 +00002303 /*
2304 ** Remove "/./" path elements and convert "/A/./" path elements
2305 ** to just "/".
2306 */
2307 if( zFull ){
drh4eb9a972006-02-13 18:42:21 +00002308 int i, j;
drh89ea9312006-02-13 17:03:47 +00002309 for(i=j=0; zFull[i]; i++){
2310 if( zFull[i]=='/' ){
2311 if( zFull[i+1]=='/' ) continue;
2312 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
2313 i += 1;
2314 continue;
2315 }
2316 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
2317 while( j>0 && zFull[j-1]!='/' ){ j--; }
2318 i += 3;
2319 continue;
2320 }
2321 }
2322 zFull[j++] = zFull[i];
2323 }
2324 zFull[j] = 0;
2325 }
drh4eb9a972006-02-13 18:42:21 +00002326#endif
2327
drh0ccebe72005-06-07 22:22:50 +00002328 return zFull;
2329}
2330
drh18839212005-11-26 03:43:23 +00002331/*
drh9cbe6352005-11-29 03:13:21 +00002332** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00002333*/
drh9cbe6352005-11-29 03:13:21 +00002334static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00002335 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00002336}
2337
2338/*
2339** Return the underlying file handle for an OsFile
2340*/
2341static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00002342 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00002343}
2344
2345/*
2346** Return an integer that indices the type of lock currently held
2347** by this handle. (Used for testing and analysis only.)
2348*/
2349static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00002350 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00002351}
drh0ccebe72005-06-07 22:22:50 +00002352
drh9c06c952005-11-26 00:25:00 +00002353/*
danielk1977a3d4c882007-03-23 10:08:38 +00002354** Return the sector size in bytes of the underlying block device for
2355** the specified file. This is almost always 512 bytes, but may be
2356** larger for some devices.
2357**
2358** SQLite code assumes this function cannot fail. It also assumes that
2359** if two files are created in the same file-system directory (i.e.
2360** a database and it's journal file) that the sector size will be the
2361** same for both.
2362*/
danielk197762079062007-08-15 17:08:46 +00002363static int unixSectorSize(sqlite3_file *id){
drh3ceeb752007-03-29 18:19:52 +00002364 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00002365}
2366
danielk197762079062007-08-15 17:08:46 +00002367static int unixDeviceCharacteristics(sqlite3_file *id){
2368 return 0;
2369}
2370
2371static int unixBreakLock(sqlite3_file *id){
2372 assert(!"TODO: unixBreakLock()");
2373 return 0;
2374}
2375
danielk1977a3d4c882007-03-23 10:08:38 +00002376/*
drh054889e2005-11-30 03:20:31 +00002377** This vector defines all the methods that can operate on an OsFile
2378** for unix.
drh9c06c952005-11-26 00:25:00 +00002379*/
danielk197762079062007-08-15 17:08:46 +00002380static const sqlite3_io_methods sqlite3UnixIoMethod = {
2381 1, /* iVersion */
drh9c06c952005-11-26 00:25:00 +00002382 unixClose,
2383 unixRead,
2384 unixWrite,
drh9c06c952005-11-26 00:25:00 +00002385 unixTruncate,
drh054889e2005-11-30 03:20:31 +00002386 unixSync,
drh054889e2005-11-30 03:20:31 +00002387 unixFileSize,
2388 unixLock,
2389 unixUnlock,
drh054889e2005-11-30 03:20:31 +00002390 unixCheckReservedLock,
danielk197762079062007-08-15 17:08:46 +00002391 unixBreakLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002392 unixSectorSize,
danielk197762079062007-08-15 17:08:46 +00002393 unixDeviceCharacteristics
drh9c06c952005-11-26 00:25:00 +00002394};
2395
drhbfe66312006-10-03 17:40:40 +00002396#ifdef SQLITE_ENABLE_LOCKING_STYLE
drh054889e2005-11-30 03:20:31 +00002397/*
drhbfe66312006-10-03 17:40:40 +00002398 ** This vector defines all the methods that can operate on an OsFile
2399 ** for unix with AFP style file locking.
2400 */
2401static const IoMethod sqlite3AFPLockingUnixIoMethod = {
2402 afpUnixClose,
2403 unixOpenDirectory,
2404 unixRead,
2405 unixWrite,
2406 unixSeek,
2407 unixTruncate,
2408 unixSync,
2409 unixSetFullSync,
2410 unixFileHandle,
2411 unixFileSize,
2412 afpUnixLock,
2413 afpUnixUnlock,
2414 unixLockState,
2415 afpUnixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002416 unixSectorSize,
drhbfe66312006-10-03 17:40:40 +00002417};
2418
2419/*
2420 ** This vector defines all the methods that can operate on an OsFile
2421 ** for unix with flock() style file locking.
2422 */
2423static const IoMethod sqlite3FlockLockingUnixIoMethod = {
2424 flockUnixClose,
2425 unixOpenDirectory,
2426 unixRead,
2427 unixWrite,
2428 unixSeek,
2429 unixTruncate,
2430 unixSync,
2431 unixSetFullSync,
2432 unixFileHandle,
2433 unixFileSize,
2434 flockUnixLock,
2435 flockUnixUnlock,
2436 unixLockState,
2437 flockUnixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002438 unixSectorSize,
drhbfe66312006-10-03 17:40:40 +00002439};
2440
2441/*
2442 ** This vector defines all the methods that can operate on an OsFile
2443 ** for unix with dotlock style file locking.
2444 */
2445static const IoMethod sqlite3DotlockLockingUnixIoMethod = {
2446 dotlockUnixClose,
2447 unixOpenDirectory,
2448 unixRead,
2449 unixWrite,
2450 unixSeek,
2451 unixTruncate,
2452 unixSync,
2453 unixSetFullSync,
2454 unixFileHandle,
2455 unixFileSize,
2456 dotlockUnixLock,
2457 dotlockUnixUnlock,
2458 unixLockState,
2459 dotlockUnixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002460 unixSectorSize,
drhbfe66312006-10-03 17:40:40 +00002461};
2462
2463/*
2464 ** This vector defines all the methods that can operate on an OsFile
2465 ** for unix with dotlock style file locking.
2466 */
2467static const IoMethod sqlite3NolockLockingUnixIoMethod = {
2468 nolockUnixClose,
2469 unixOpenDirectory,
2470 unixRead,
2471 unixWrite,
2472 unixSeek,
2473 unixTruncate,
2474 unixSync,
2475 unixSetFullSync,
2476 unixFileHandle,
2477 unixFileSize,
2478 nolockUnixLock,
2479 nolockUnixUnlock,
2480 unixLockState,
2481 nolockUnixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002482 unixSectorSize,
drhbfe66312006-10-03 17:40:40 +00002483};
2484
2485#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2486
2487/*
2488** Allocate memory for a new unixFile and initialize that unixFile.
2489** Write a pointer to the new unixFile into *pId.
2490** If we run out of memory, close the file and return an error.
drh054889e2005-11-30 03:20:31 +00002491*/
drhbfe66312006-10-03 17:40:40 +00002492#ifdef SQLITE_ENABLE_LOCKING_STYLE
2493/*
2494 ** When locking extensions are enabled, the filepath and locking style
2495 ** are needed to determine the unixFile pMethod to use for locking operations.
2496 ** The locking-style specific lockingContext data structure is created
2497 ** and assigned here also.
2498 */
2499static int allocateUnixFile(
2500 int h, /* Open file descriptor of file being opened */
2501 OsFile **pId, /* Write completed initialization here */
2502 const char *zFilename, /* Name of the file being opened */
2503 int delFlag /* Delete-on-or-before-close flag */
2504){
aswift108bc322006-10-11 17:19:46 +00002505 sqlite3LockingStyle lockingStyle;
drh054889e2005-11-30 03:20:31 +00002506 unixFile *pNew;
drhbfe66312006-10-03 17:40:40 +00002507 unixFile f;
2508 int rc;
2509
drh61fc5952007-04-01 23:49:51 +00002510 memset(&f, 0, sizeof(f));
aswift448aa6f2006-11-11 01:31:58 +00002511 lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
drhbfe66312006-10-03 17:40:40 +00002512 if ( lockingStyle == posixLockingStyle ) {
2513 sqlite3OsEnterMutex();
2514 rc = findLockInfo(h, &f.pLock, &f.pOpen);
2515 sqlite3OsLeaveMutex();
2516 if( rc ){
2517 close(h);
2518 unlink(zFilename);
2519 return SQLITE_NOMEM;
2520 }
2521 } else {
drh3b62b2f2007-06-08 18:27:03 +00002522 /* pLock and pOpen are only used for posix advisory locking */
drhbfe66312006-10-03 17:40:40 +00002523 f.pLock = NULL;
2524 f.pOpen = NULL;
2525 }
2526 if( delFlag ){
2527 unlink(zFilename);
2528 }
2529 f.dirfd = -1;
drhbfe66312006-10-03 17:40:40 +00002530 f.h = h;
2531 SET_THREADID(&f);
drh17435752007-08-16 04:30:38 +00002532 pNew = sqlite3_malloc( sizeof(unixFile) );
drh054889e2005-11-30 03:20:31 +00002533 if( pNew==0 ){
drhbfe66312006-10-03 17:40:40 +00002534 close(h);
drh029b44b2006-01-15 00:13:15 +00002535 sqlite3OsEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002536 releaseLockInfo(f.pLock);
2537 releaseOpenCnt(f.pOpen);
drh029b44b2006-01-15 00:13:15 +00002538 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00002539 *pId = 0;
2540 return SQLITE_NOMEM;
2541 }else{
drhbfe66312006-10-03 17:40:40 +00002542 *pNew = f;
aswift108bc322006-10-11 17:19:46 +00002543 switch(lockingStyle) {
drh5bb3eb92007-05-04 13:15:55 +00002544 case afpLockingStyle: {
drhbfe66312006-10-03 17:40:40 +00002545 /* afp locking uses the file path so it needs to be included in
2546 ** the afpLockingContext */
drh5bb3eb92007-05-04 13:15:55 +00002547 int nFilename;
drhbfe66312006-10-03 17:40:40 +00002548 pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
2549 pNew->lockingContext =
drh17435752007-08-16 04:30:38 +00002550 sqlite3_malloc(sizeof(afpLockingContext));
drh5bb3eb92007-05-04 13:15:55 +00002551 nFilename = strlen(zFilename)+1;
drhbfe66312006-10-03 17:40:40 +00002552 ((afpLockingContext *)pNew->lockingContext)->filePath =
drh17435752007-08-16 04:30:38 +00002553 sqlite3_malloc(nFilename);
drh5bb3eb92007-05-04 13:15:55 +00002554 memcpy(((afpLockingContext *)pNew->lockingContext)->filePath,
2555 zFilename, nFilename);
drhbfe66312006-10-03 17:40:40 +00002556 srandomdev();
2557 break;
drh5bb3eb92007-05-04 13:15:55 +00002558 }
drhbfe66312006-10-03 17:40:40 +00002559 case flockLockingStyle:
2560 /* flock locking doesn't need additional lockingContext information */
2561 pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
2562 break;
drh5bb3eb92007-05-04 13:15:55 +00002563 case dotlockLockingStyle: {
drhbfe66312006-10-03 17:40:40 +00002564 /* dotlock locking uses the file path so it needs to be included in
2565 ** the dotlockLockingContext */
drh5bb3eb92007-05-04 13:15:55 +00002566 int nFilename;
drhbfe66312006-10-03 17:40:40 +00002567 pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
drh17435752007-08-16 04:30:38 +00002568 pNew->lockingContext = sqlite3_malloc(
drhbfe66312006-10-03 17:40:40 +00002569 sizeof(dotlockLockingContext));
drh5bb3eb92007-05-04 13:15:55 +00002570 nFilename = strlen(zFilename) + 6;
drhbfe66312006-10-03 17:40:40 +00002571 ((dotlockLockingContext *)pNew->lockingContext)->lockPath =
drh17435752007-08-16 04:30:38 +00002572 sqlite3_malloc( nFilename );
drh5bb3eb92007-05-04 13:15:55 +00002573 sqlite3_snprintf(nFilename,
2574 ((dotlockLockingContext *)pNew->lockingContext)->lockPath,
drhbfe66312006-10-03 17:40:40 +00002575 "%s.lock", zFilename);
2576 break;
drh5bb3eb92007-05-04 13:15:55 +00002577 }
drhbfe66312006-10-03 17:40:40 +00002578 case posixLockingStyle:
2579 /* posix locking doesn't need additional lockingContext information */
2580 pNew->pMethod = &sqlite3UnixIoMethod;
2581 break;
2582 case noLockingStyle:
2583 case unsupportedLockingStyle:
2584 default:
2585 pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
2586 }
2587 *pId = (OsFile*)pNew;
2588 OpenCounter(+1);
2589 return SQLITE_OK;
2590 }
2591}
2592#else /* SQLITE_ENABLE_LOCKING_STYLE */
2593static int allocateUnixFile(
2594 int h, /* Open file descriptor on file being opened */
danielk197762079062007-08-15 17:08:46 +00002595 sqlite3_file **pId, /* Write the resul unixFile structure here */
drhbfe66312006-10-03 17:40:40 +00002596 const char *zFilename, /* Name of the file being opened */
2597 int delFlag /* If true, delete the file on or before closing */
2598){
2599 unixFile *pNew;
2600 unixFile f;
2601 int rc;
2602
drhe78669b2007-06-29 12:04:26 +00002603#ifdef FD_CLOEXEC
2604 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
2605#endif
drh61fc5952007-04-01 23:49:51 +00002606 memset(&f, 0, sizeof(f));
drhbfe66312006-10-03 17:40:40 +00002607 sqlite3OsEnterMutex();
2608 rc = findLockInfo(h, &f.pLock, &f.pOpen);
2609 sqlite3OsLeaveMutex();
2610 if( delFlag ){
2611 unlink(zFilename);
2612 }
2613 if( rc ){
2614 close(h);
2615 return SQLITE_NOMEM;
2616 }
drh4f0c5872007-03-26 22:05:01 +00002617 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
drhbfe66312006-10-03 17:40:40 +00002618 f.dirfd = -1;
drhbfe66312006-10-03 17:40:40 +00002619 f.h = h;
2620 SET_THREADID(&f);
drh17435752007-08-16 04:30:38 +00002621 pNew = sqlite3_malloc( sizeof(unixFile) );
drhbfe66312006-10-03 17:40:40 +00002622 if( pNew==0 ){
2623 close(h);
2624 sqlite3OsEnterMutex();
2625 releaseLockInfo(f.pLock);
2626 releaseOpenCnt(f.pOpen);
2627 sqlite3OsLeaveMutex();
2628 *pId = 0;
2629 return SQLITE_NOMEM;
2630 }else{
2631 *pNew = f;
drh054889e2005-11-30 03:20:31 +00002632 pNew->pMethod = &sqlite3UnixIoMethod;
danielk197762079062007-08-15 17:08:46 +00002633 *pId = (sqlite3_file*)pNew;
drh054889e2005-11-30 03:20:31 +00002634 OpenCounter(+1);
2635 return SQLITE_OK;
2636 }
2637}
drhbfe66312006-10-03 17:40:40 +00002638#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9c06c952005-11-26 00:25:00 +00002639
drh0ccebe72005-06-07 22:22:50 +00002640#endif /* SQLITE_OMIT_DISKIO */
2641/***************************************************************************
2642** Everything above deals with file I/O. Everything that follows deals
2643** with other miscellanous aspects of the operating system interface
2644****************************************************************************/
2645
2646
drh761df872006-12-21 01:29:22 +00002647#ifndef SQLITE_OMIT_LOAD_EXTENSION
2648/*
2649** Interfaces for opening a shared library, finding entry points
2650** within the shared library, and closing the shared library.
2651*/
2652#include <dlfcn.h>
2653void *sqlite3UnixDlopen(const char *zFilename){
2654 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
2655}
2656void *sqlite3UnixDlsym(void *pHandle, const char *zSymbol){
2657 return dlsym(pHandle, zSymbol);
2658}
2659int sqlite3UnixDlclose(void *pHandle){
2660 return dlclose(pHandle);
2661}
2662#endif /* SQLITE_OMIT_LOAD_EXTENSION */
2663
drh0ccebe72005-06-07 22:22:50 +00002664/*
drhbbd42a62004-05-22 17:41:58 +00002665** Get information to seed the random number generator. The seed
2666** is written into the buffer zBuf[256]. The calling function must
2667** supply a sufficiently large buffer.
2668*/
drh66560ad2006-01-06 14:32:19 +00002669int sqlite3UnixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00002670 /* We have to initialize zBuf to prevent valgrind from reporting
2671 ** errors. The reports issued by valgrind are incorrect - we would
2672 ** prefer that the randomness be increased by making use of the
2673 ** uninitialized space in zBuf - but valgrind errors tend to worry
2674 ** some users. Rather than argue, it seems easier just to initialize
2675 ** the whole array and silence valgrind, even if that means less randomness
2676 ** in the random seed.
2677 **
2678 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00002679 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00002680 ** tests repeatable.
2681 */
2682 memset(zBuf, 0, 256);
2683#if !defined(SQLITE_TEST)
2684 {
drh842b8642005-01-21 17:53:17 +00002685 int pid, fd;
2686 fd = open("/dev/urandom", O_RDONLY);
2687 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00002688 time_t t;
2689 time(&t);
2690 memcpy(zBuf, &t, sizeof(t));
drh842b8642005-01-21 17:53:17 +00002691 pid = getpid();
2692 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
2693 }else{
2694 read(fd, zBuf, 256);
2695 close(fd);
2696 }
drhbbd42a62004-05-22 17:41:58 +00002697 }
2698#endif
2699 return SQLITE_OK;
2700}
2701
2702/*
2703** Sleep for a little while. Return the amount of time slept.
drhf1a221e2006-01-15 17:27:17 +00002704** The argument is the number of milliseconds we want to sleep.
drhbbd42a62004-05-22 17:41:58 +00002705*/
drh66560ad2006-01-06 14:32:19 +00002706int sqlite3UnixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00002707#if defined(HAVE_USLEEP) && HAVE_USLEEP
2708 usleep(ms*1000);
2709 return ms;
2710#else
2711 sleep((ms+999)/1000);
2712 return 1000*((ms+999)/1000);
2713#endif
2714}
2715
2716/*
drh5c111232006-02-10 04:33:12 +00002717** Static variables used for thread synchronization.
2718**
2719** inMutex the nesting depth of the recursive mutex. The thread
2720** holding mutexMain can read this variable at any time.
2721** But is must hold mutexAux to change this variable. Other
drh6a3d6702006-02-10 13:11:32 +00002722** threads must hold mutexAux to read the variable and can
2723** never write.
drh5c111232006-02-10 04:33:12 +00002724**
2725** mutexOwner The thread id of the thread holding mutexMain. Same
2726** access rules as for inMutex.
2727**
drh6a3d6702006-02-10 13:11:32 +00002728** mutexOwnerValid True if the value in mutexOwner is valid. The same
2729** access rules apply as for inMutex.
drh5c111232006-02-10 04:33:12 +00002730**
2731** mutexMain The main mutex. Hold this mutex in order to get exclusive
2732** access to SQLite data structures.
2733**
2734** mutexAux An auxiliary mutex needed to access variables defined above.
2735**
drh6a3d6702006-02-10 13:11:32 +00002736** Mutexes are always acquired in this order: mutexMain mutexAux. It
2737** is not necessary to acquire mutexMain in order to get mutexAux - just
2738** do not attempt to acquire them in the reverse order: mutexAux mutexMain.
2739** Either get the mutexes with mutexMain first or get mutexAux only.
2740**
2741** When running on a platform where the three variables inMutex, mutexOwner,
2742** and mutexOwnerValid can be set atomically, the mutexAux is not required.
2743** On many systems, all three are 32-bit integers and writing to a 32-bit
2744** integer is atomic. I think. But there are no guarantees. So it seems
2745** safer to protect them using mutexAux.
drhbbd42a62004-05-22 17:41:58 +00002746*/
2747static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00002748#ifdef SQLITE_UNIX_THREADS
drh6a3d6702006-02-10 13:11:32 +00002749static pthread_t mutexOwner; /* Thread holding mutexMain */
drh5c111232006-02-10 04:33:12 +00002750static int mutexOwnerValid = 0; /* True if mutexOwner is valid */
2751static pthread_mutex_t mutexMain = PTHREAD_MUTEX_INITIALIZER; /* The mutex */
2752static pthread_mutex_t mutexAux = PTHREAD_MUTEX_INITIALIZER; /* Aux mutex */
drh79069752004-05-22 21:30:40 +00002753#endif
drhbbd42a62004-05-22 17:41:58 +00002754
2755/*
2756** The following pair of routine implement mutual exclusion for
2757** multi-threaded processes. Only a single thread is allowed to
2758** executed code that is surrounded by EnterMutex() and LeaveMutex().
2759**
2760** SQLite uses only a single Mutex. There is not much critical
2761** code and what little there is executes quickly and without blocking.
drhf1a221e2006-01-15 17:27:17 +00002762**
drh757b04e2006-01-18 17:25:45 +00002763** As of version 3.3.2, this mutex must be recursive.
drhbbd42a62004-05-22 17:41:58 +00002764*/
drh66560ad2006-01-06 14:32:19 +00002765void sqlite3UnixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00002766#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00002767 pthread_mutex_lock(&mutexAux);
2768 if( !mutexOwnerValid || !pthread_equal(mutexOwner, pthread_self()) ){
2769 pthread_mutex_unlock(&mutexAux);
2770 pthread_mutex_lock(&mutexMain);
2771 assert( inMutex==0 );
2772 assert( !mutexOwnerValid );
2773 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00002774 mutexOwner = pthread_self();
drh5c111232006-02-10 04:33:12 +00002775 mutexOwnerValid = 1;
drha3fad6f2006-01-18 14:06:37 +00002776 }
drha3fad6f2006-01-18 14:06:37 +00002777 inMutex++;
drh5c111232006-02-10 04:33:12 +00002778 pthread_mutex_unlock(&mutexAux);
2779#else
drhe9565a62006-02-11 02:03:52 +00002780 inMutex++;
drh5c111232006-02-10 04:33:12 +00002781#endif
drhbbd42a62004-05-22 17:41:58 +00002782}
drh66560ad2006-01-06 14:32:19 +00002783void sqlite3UnixLeaveMutex(){
drha3fad6f2006-01-18 14:06:37 +00002784 assert( inMutex>0 );
drhbbd42a62004-05-22 17:41:58 +00002785#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00002786 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00002787 inMutex--;
drh5c111232006-02-10 04:33:12 +00002788 assert( pthread_equal(mutexOwner, pthread_self()) );
drha3fad6f2006-01-18 14:06:37 +00002789 if( inMutex==0 ){
drh5c111232006-02-10 04:33:12 +00002790 assert( mutexOwnerValid );
2791 mutexOwnerValid = 0;
2792 pthread_mutex_unlock(&mutexMain);
drha3fad6f2006-01-18 14:06:37 +00002793 }
drh5c111232006-02-10 04:33:12 +00002794 pthread_mutex_unlock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00002795#else
2796 inMutex--;
drhbbd42a62004-05-22 17:41:58 +00002797#endif
2798}
2799
2800/*
drh757b04e2006-01-18 17:25:45 +00002801** Return TRUE if the mutex is currently held.
2802**
drh5c111232006-02-10 04:33:12 +00002803** If the thisThrd parameter is true, return true only if the
drh757b04e2006-01-18 17:25:45 +00002804** calling thread holds the mutex. If the parameter is false, return
2805** true if any thread holds the mutex.
drh88f474a2006-01-02 20:00:12 +00002806*/
drh5c111232006-02-10 04:33:12 +00002807int sqlite3UnixInMutex(int thisThrd){
drha3fad6f2006-01-18 14:06:37 +00002808#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00002809 int rc;
2810 pthread_mutex_lock(&mutexAux);
2811 rc = inMutex>0 && (thisThrd==0 || pthread_equal(mutexOwner,pthread_self()));
2812 pthread_mutex_unlock(&mutexAux);
2813 return rc;
drha3fad6f2006-01-18 14:06:37 +00002814#else
drh757b04e2006-01-18 17:25:45 +00002815 return inMutex>0;
drha3fad6f2006-01-18 14:06:37 +00002816#endif
drh88f474a2006-01-02 20:00:12 +00002817}
2818
2819/*
drhbbd42a62004-05-22 17:41:58 +00002820** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00002821** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00002822*/
2823#ifdef SQLITE_TEST
2824int sqlite3_current_time = 0;
2825#endif
2826
2827/*
2828** Find the current time (in Universal Coordinated Time). Write the
2829** current time and date as a Julian Day number into *prNow and
2830** return 0. Return 1 if the time and date cannot be found.
2831*/
drh66560ad2006-01-06 14:32:19 +00002832int sqlite3UnixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00002833#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00002834 time_t t;
2835 time(&t);
2836 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00002837#else
2838 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00002839 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00002840 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
2841#endif
drhbbd42a62004-05-22 17:41:58 +00002842#ifdef SQLITE_TEST
2843 if( sqlite3_current_time ){
2844 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
2845 }
2846#endif
2847 return 0;
2848}
drhdce8bdb2007-08-16 13:01:44 +00002849
drhbbd42a62004-05-22 17:41:58 +00002850#endif /* OS_UNIX */