blob: 91418914ce53e1808883b03ba1dcd19cfd38c291 [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 {
85 IoMethod 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
drh66560ad2006-01-06 14:32:19 +0000102/*
103** Provide the ability to override some OS-layer functions during
104** testing. This is used to simulate OS crashes to verify that
105** commits are atomic even in the event of an OS crash.
106*/
107#ifdef SQLITE_CRASH_TEST
108 extern int sqlite3CrashTestEnable;
109 extern int sqlite3CrashOpenReadWrite(const char*, OsFile**, int*);
110 extern int sqlite3CrashOpenExclusive(const char*, OsFile**, int);
111 extern int sqlite3CrashOpenReadOnly(const char*, OsFile**, int);
112# define CRASH_TEST_OVERRIDE(X,A,B,C) \
113 if(sqlite3CrashTestEnable){ return X(A,B,C); }
114#else
115# define CRASH_TEST_OVERRIDE(X,A,B,C) /* no-op */
116#endif
117
drh0ccebe72005-06-07 22:22:50 +0000118
119/*
drh198bf392006-01-06 21:52:49 +0000120** Include code that is common to all os_*.c files
121*/
122#include "os_common.h"
123
124/*
drh0ccebe72005-06-07 22:22:50 +0000125** Do not include any of the File I/O interface procedures if the
drhf1a221e2006-01-15 17:27:17 +0000126** SQLITE_OMIT_DISKIO macro is defined (indicating that the database
drh0ccebe72005-06-07 22:22:50 +0000127** will be in-memory only)
128*/
129#ifndef SQLITE_OMIT_DISKIO
130
131
132/*
133** Define various macros that are missing from some systems.
134*/
drhbbd42a62004-05-22 17:41:58 +0000135#ifndef O_LARGEFILE
136# define O_LARGEFILE 0
137#endif
138#ifdef SQLITE_DISABLE_LFS
139# undef O_LARGEFILE
140# define O_LARGEFILE 0
141#endif
142#ifndef O_NOFOLLOW
143# define O_NOFOLLOW 0
144#endif
145#ifndef O_BINARY
146# define O_BINARY 0
147#endif
148
149/*
150** The DJGPP compiler environment looks mostly like Unix, but it
151** lacks the fcntl() system call. So redefine fcntl() to be something
152** that always succeeds. This means that locking does not occur under
danielk197726c5d792005-11-25 09:01:23 +0000153** DJGPP. But it's DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000154*/
155#ifdef __DJGPP__
156# define fcntl(A,B,C) 0
157#endif
158
159/*
drh2b4b5962005-06-15 17:47:55 +0000160** The threadid macro resolves to the thread-id or to 0. Used for
161** testing and debugging only.
162*/
163#ifdef SQLITE_UNIX_THREADS
164#define threadid pthread_self()
165#else
166#define threadid 0
167#endif
168
169/*
170** Set or check the OsFile.tid field. This field is set when an OsFile
171** is first opened. All subsequent uses of the OsFile verify that the
172** same thread is operating on the OsFile. Some operating systems do
173** not allow locks to be overridden by other threads and that restriction
174** means that sqlite3* database handles cannot be moved from one thread
175** to another. This logic makes sure a user does not try to do that
176** by mistake.
drhf1a221e2006-01-15 17:27:17 +0000177**
178** Version 3.3.1 (2006-01-15): OsFiles can be moved from one thread to
179** another as long as we are running on a system that supports threads
180** overriding each others locks (which now the most common behavior)
181** or if no locks are held. But the OsFile.pLock field needs to be
182** recomputed because its key includes the thread-id. See the
183** transferOwnership() function below for additional information
drh2b4b5962005-06-15 17:47:55 +0000184*/
drh029b44b2006-01-15 00:13:15 +0000185#if defined(SQLITE_UNIX_THREADS)
drh9cbe6352005-11-29 03:13:21 +0000186# define SET_THREADID(X) (X)->tid = pthread_self()
drh029b44b2006-01-15 00:13:15 +0000187# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
188 !pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000189#else
190# define SET_THREADID(X)
191# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000192#endif
193
drhbbd42a62004-05-22 17:41:58 +0000194/*
195** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
196** section 6.5.2.2 lines 483 through 490 specify that when a process
197** sets or clears a lock, that operation overrides any prior locks set
198** by the same process. It does not explicitly say so, but this implies
199** that it overrides locks set by the same process using a different
200** file descriptor. Consider this test case:
201**
202** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
203** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
204**
205** Suppose ./file1 and ./file2 are really the same file (because
206** one is a hard or symbolic link to the other) then if you set
207** an exclusive lock on fd1, then try to get an exclusive lock
208** on fd2, it works. I would have expected the second lock to
209** fail since there was already a lock on the file due to fd1.
210** But not so. Since both locks came from the same process, the
211** second overrides the first, even though they were on different
212** file descriptors opened on different file names.
213**
214** Bummer. If you ask me, this is broken. Badly broken. It means
215** that we cannot use POSIX locks to synchronize file access among
216** competing threads of the same process. POSIX locks will work fine
217** to synchronize access for threads in separate processes, but not
218** threads within the same process.
219**
220** To work around the problem, SQLite has to manage file locks internally
221** on its own. Whenever a new database is opened, we have to find the
222** specific inode of the database file (the inode is determined by the
223** st_dev and st_ino fields of the stat structure that fstat() fills in)
224** and check for locks already existing on that inode. When locks are
225** created or removed, we have to look at our own internal record of the
226** locks to see if another thread has previously set a lock on that same
227** inode.
228**
229** The OsFile structure for POSIX is no longer just an integer file
230** descriptor. It is now a structure that holds the integer file
231** descriptor and a pointer to a structure that describes the internal
232** locks on the corresponding inode. There is one locking structure
233** per inode, so if the same inode is opened twice, both OsFile structures
234** point to the same locking structure. The locking structure keeps
235** a reference count (so we will know when to delete it) and a "cnt"
236** field that tells us its internal lock status. cnt==0 means the
237** file is unlocked. cnt==-1 means the file has an exclusive lock.
238** cnt>0 means there are cnt shared locks on the file.
239**
240** Any attempt to lock or unlock a file first checks the locking
241** structure. The fcntl() system call is only invoked to set a
242** POSIX lock if the internal lock structure transitions between
243** a locked and an unlocked state.
244**
245** 2004-Jan-11:
246** More recent discoveries about POSIX advisory locks. (The more
247** I discover, the more I realize the a POSIX advisory locks are
248** an abomination.)
249**
250** If you close a file descriptor that points to a file that has locks,
251** all locks on that file that are owned by the current process are
252** released. To work around this problem, each OsFile structure contains
253** a pointer to an openCnt structure. There is one openCnt structure
254** per open inode, which means that multiple OsFiles can point to a single
255** openCnt. When an attempt is made to close an OsFile, if there are
256** other OsFiles open on the same inode that are holding locks, the call
257** to close() the file descriptor is deferred until all of the locks clear.
258** The openCnt structure keeps a list of file descriptors that need to
259** be closed and that list is walked (and cleared) when the last lock
260** clears.
261**
262** First, under Linux threads, because each thread has a separate
263** process ID, lock operations in one thread do not override locks
264** to the same file in other threads. Linux threads behave like
265** separate processes in this respect. But, if you close a file
266** descriptor in linux threads, all locks are cleared, even locks
267** on other threads and even though the other threads have different
268** process IDs. Linux threads is inconsistent in this respect.
269** (I'm beginning to think that linux threads is an abomination too.)
270** The consequence of this all is that the hash table for the lockInfo
271** structure has to include the process id as part of its key because
272** locks in different threads are treated as distinct. But the
273** openCnt structure should not include the process id in its
274** key because close() clears lock on all threads, not just the current
275** thread. Were it not for this goofiness in linux threads, we could
276** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000277**
278** 2004-Jun-28:
279** On some versions of linux, threads can override each others locks.
280** On others not. Sometimes you can change the behavior on the same
281** system by setting the LD_ASSUME_KERNEL environment variable. The
282** POSIX standard is silent as to which behavior is correct, as far
283** as I can tell, so other versions of unix might show the same
284** inconsistency. There is no little doubt in my mind that posix
285** advisory locks and linux threads are profoundly broken.
286**
287** To work around the inconsistencies, we have to test at runtime
288** whether or not threads can override each others locks. This test
289** is run once, the first time any lock is attempted. A static
290** variable is set to record the results of this test for future
291** use.
drhbbd42a62004-05-22 17:41:58 +0000292*/
293
294/*
295** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000296** to locate a particular lockInfo structure given its inode.
297**
298** If threads cannot override each others locks, then we set the
299** lockKey.tid field to the thread ID. If threads can override
drhf1a221e2006-01-15 17:27:17 +0000300** each others locks then tid is always set to zero. tid is omitted
301** if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000302*/
303struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000304 dev_t dev; /* Device number */
305 ino_t ino; /* Inode number */
306#ifdef SQLITE_UNIX_THREADS
drhd9cb6ac2005-10-20 07:28:17 +0000307 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000308#endif
drhbbd42a62004-05-22 17:41:58 +0000309};
310
311/*
312** An instance of the following structure is allocated for each open
313** inode on each thread with a different process ID. (Threads have
314** different process IDs on linux, but not on most other unixes.)
315**
316** A single inode can have multiple file descriptors, so each OsFile
317** structure contains a pointer to an instance of this object and this
318** object keeps a count of the number of OsFiles pointing to it.
319*/
320struct lockInfo {
321 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000322 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000323 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000324 int nRef; /* Number of pointers to this structure */
325};
326
327/*
328** An instance of the following structure serves as the key used
329** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000330** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000331*/
332struct openKey {
333 dev_t dev; /* Device number */
334 ino_t ino; /* Inode number */
335};
336
337/*
338** An instance of the following structure is allocated for each open
339** inode. This structure keeps track of the number of locks on that
340** inode. If a close is attempted against an inode that is holding
341** locks, the close is deferred until all locks clear by adding the
342** file descriptor to be closed to the pending list.
343*/
344struct openCnt {
345 struct openKey key; /* The lookup key */
346 int nRef; /* Number of pointers to this structure */
347 int nLock; /* Number of outstanding locks */
348 int nPending; /* Number of pending close() operations */
349 int *aPending; /* Malloced space holding fd's awaiting a close() */
350};
351
352/*
drhf1a221e2006-01-15 17:27:17 +0000353** These hash tables map inodes and file descriptors (really, lockKey and
354** openKey structures) into lockInfo and openCnt structures. Access to
355** these hash tables must be protected by a mutex.
drhbbd42a62004-05-22 17:41:58 +0000356*/
danielk1977750b03e2006-02-14 10:48:39 +0000357static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0,
358 sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
359static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0,
360 sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
drh5fdae772004-06-29 03:29:00 +0000361
drhbfe66312006-10-03 17:40:40 +0000362#ifdef SQLITE_ENABLE_LOCKING_STYLE
363/*
364** The locking styles are associated with the different file locking
365** capabilities supported by different file systems.
366**
367** POSIX locking style fully supports shared and exclusive byte-range locks
368** ADP locking only supports exclusive byte-range locks
369** FLOCK only supports a single file-global exclusive lock
370** DOTLOCK isn't a true locking style, it refers to the use of a special
371** file named the same as the database file with a '.lock' extension, this
372** can be used on file systems that do not offer any reliable file locking
373** NO locking means that no locking will be attempted, this is only used for
374** read-only file systems currently
375** UNSUPPORTED means that no locking will be attempted, this is only used for
376** file systems that are known to be unsupported
377*/
378typedef enum {
drhfd131da2007-08-07 17:13:03 +0000379 posixLockingStyle = 0, /* standard posix-advisory locks */
380 afpLockingStyle, /* use afp locks */
381 flockLockingStyle, /* use flock() */
382 dotlockLockingStyle, /* use <file>.lock files */
383 noLockingStyle, /* useful for read-only file system */
384 unsupportedLockingStyle /* indicates unsupported file system */
drhbfe66312006-10-03 17:40:40 +0000385} sqlite3LockingStyle;
386#endif /* SQLITE_ENABLE_LOCKING_STYLE */
387
drh5fdae772004-06-29 03:29:00 +0000388#ifdef SQLITE_UNIX_THREADS
389/*
390** This variable records whether or not threads can override each others
391** locks.
392**
393** 0: No. Threads cannot override each others locks.
394** 1: Yes. Threads can override each others locks.
395** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000396**
drh5062d3a2006-01-31 23:03:35 +0000397** On some systems, we know at compile-time if threads can override each
398** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
399** will be set appropriately. On other systems, we have to check at
400** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
401** undefined.
402**
drhf1a221e2006-01-15 17:27:17 +0000403** This variable normally has file scope only. But during testing, we make
404** it a global so that the test code can change its value in order to verify
405** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000406*/
drh5062d3a2006-01-31 23:03:35 +0000407#ifndef SQLITE_THREAD_OVERRIDE_LOCK
408# define SQLITE_THREAD_OVERRIDE_LOCK -1
409#endif
drh029b44b2006-01-15 00:13:15 +0000410#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000411int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000412#else
drh5062d3a2006-01-31 23:03:35 +0000413static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000414#endif
drh5fdae772004-06-29 03:29:00 +0000415
416/*
417** This structure holds information passed into individual test
418** threads by the testThreadLockingBehavior() routine.
419*/
420struct threadTestData {
421 int fd; /* File to be locked */
422 struct flock lock; /* The locking operation */
423 int result; /* Result of the locking operation */
424};
425
drh2b4b5962005-06-15 17:47:55 +0000426#ifdef SQLITE_LOCK_TRACE
427/*
428** Print out information about all locking operations.
429**
430** This routine is used for troubleshooting locks on multithreaded
431** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
432** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000433** turned off.
drh2b4b5962005-06-15 17:47:55 +0000434*/
435static int lockTrace(int fd, int op, struct flock *p){
436 char *zOpName, *zType;
437 int s;
438 int savedErrno;
439 if( op==F_GETLK ){
440 zOpName = "GETLK";
441 }else if( op==F_SETLK ){
442 zOpName = "SETLK";
443 }else{
444 s = fcntl(fd, op, p);
445 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
446 return s;
447 }
448 if( p->l_type==F_RDLCK ){
449 zType = "RDLCK";
450 }else if( p->l_type==F_WRLCK ){
451 zType = "WRLCK";
452 }else if( p->l_type==F_UNLCK ){
453 zType = "UNLCK";
454 }else{
455 assert( 0 );
456 }
457 assert( p->l_whence==SEEK_SET );
458 s = fcntl(fd, op, p);
459 savedErrno = errno;
460 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
461 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
462 (int)p->l_pid, s);
drhe2396a12007-03-29 20:19:58 +0000463 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
drh2b4b5962005-06-15 17:47:55 +0000464 struct flock l2;
465 l2 = *p;
466 fcntl(fd, F_GETLK, &l2);
467 if( l2.l_type==F_RDLCK ){
468 zType = "RDLCK";
469 }else if( l2.l_type==F_WRLCK ){
470 zType = "WRLCK";
471 }else if( l2.l_type==F_UNLCK ){
472 zType = "UNLCK";
473 }else{
474 assert( 0 );
475 }
476 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
477 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
478 }
479 errno = savedErrno;
480 return s;
481}
482#define fcntl lockTrace
483#endif /* SQLITE_LOCK_TRACE */
484
drh5fdae772004-06-29 03:29:00 +0000485/*
486** The testThreadLockingBehavior() routine launches two separate
487** threads on this routine. This routine attempts to lock a file
488** descriptor then returns. The success or failure of that attempt
489** allows the testThreadLockingBehavior() procedure to determine
490** whether or not threads can override each others locks.
491*/
492static void *threadLockingTest(void *pArg){
493 struct threadTestData *pData = (struct threadTestData*)pArg;
494 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
495 return pArg;
496}
497
498/*
499** This procedure attempts to determine whether or not threads
500** can override each others locks then sets the
501** threadsOverrideEachOthersLocks variable appropriately.
502*/
danielk19774d5238f2006-01-27 06:32:00 +0000503static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000504 int fd;
505 struct threadTestData d[2];
506 pthread_t t[2];
507
508 fd = dup(fd_orig);
509 if( fd<0 ) return;
510 memset(d, 0, sizeof(d));
511 d[0].fd = fd;
512 d[0].lock.l_type = F_RDLCK;
513 d[0].lock.l_len = 1;
514 d[0].lock.l_start = 0;
515 d[0].lock.l_whence = SEEK_SET;
516 d[1] = d[0];
517 d[1].lock.l_type = F_WRLCK;
518 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
519 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
520 pthread_join(t[0], 0);
521 pthread_join(t[1], 0);
522 close(fd);
523 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
524}
525#endif /* SQLITE_UNIX_THREADS */
526
drhbbd42a62004-05-22 17:41:58 +0000527/*
528** Release a lockInfo structure previously allocated by findLockInfo().
529*/
530static void releaseLockInfo(struct lockInfo *pLock){
drh757b04e2006-01-18 17:25:45 +0000531 assert( sqlite3OsInMutex(1) );
drhbfe66312006-10-03 17:40:40 +0000532 if (pLock == NULL)
533 return;
drhbbd42a62004-05-22 17:41:58 +0000534 pLock->nRef--;
535 if( pLock->nRef==0 ){
536 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
danielk1977750b03e2006-02-14 10:48:39 +0000537 sqlite3ThreadSafeFree(pLock);
drhbbd42a62004-05-22 17:41:58 +0000538 }
539}
540
541/*
542** Release a openCnt structure previously allocated by findLockInfo().
543*/
544static void releaseOpenCnt(struct openCnt *pOpen){
drh757b04e2006-01-18 17:25:45 +0000545 assert( sqlite3OsInMutex(1) );
drhbfe66312006-10-03 17:40:40 +0000546 if (pOpen == NULL)
547 return;
drhbbd42a62004-05-22 17:41:58 +0000548 pOpen->nRef--;
549 if( pOpen->nRef==0 ){
550 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
drh64b1bea2006-01-15 02:30:57 +0000551 free(pOpen->aPending);
danielk1977750b03e2006-02-14 10:48:39 +0000552 sqlite3ThreadSafeFree(pOpen);
drhbbd42a62004-05-22 17:41:58 +0000553 }
554}
555
drhbfe66312006-10-03 17:40:40 +0000556#ifdef SQLITE_ENABLE_LOCKING_STYLE
557/*
558** Tests a byte-range locking query to see if byte range locks are
559** supported, if not we fall back to dotlockLockingStyle.
560*/
561static sqlite3LockingStyle sqlite3TestLockingStyle(const char *filePath,
562 int fd) {
563 /* test byte-range lock using fcntl */
564 struct flock lockInfo;
565
566 lockInfo.l_len = 1;
567 lockInfo.l_start = 0;
568 lockInfo.l_whence = SEEK_SET;
569 lockInfo.l_type = F_RDLCK;
570
aswiftae0943b2007-01-31 23:37:07 +0000571 if (fcntl(fd, F_GETLK, &lockInfo) != -1) {
drhbfe66312006-10-03 17:40:40 +0000572 return posixLockingStyle;
573 }
574
575 /* testing for flock can give false positives. So if if the above test
576 ** fails, then we fall back to using dot-lock style locking.
577 */
578 return dotlockLockingStyle;
579}
580
581/*
582** Examines the f_fstypename entry in the statfs structure as returned by
583** stat() for the file system hosting the database file, assigns the
584** appropriate locking style based on it's value. These values and
585** assignments are based on Darwin/OSX behavior and have not been tested on
586** other systems.
587*/
588static sqlite3LockingStyle sqlite3DetectLockingStyle(const char *filePath,
589 int fd) {
590
591#ifdef SQLITE_FIXED_LOCKING_STYLE
592 return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
593#else
594 struct statfs fsInfo;
595
596 if (statfs(filePath, &fsInfo) == -1)
597 return sqlite3TestLockingStyle(filePath, fd);
598
599 if (fsInfo.f_flags & MNT_RDONLY)
600 return noLockingStyle;
601
602 if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
603 (!strcmp(fsInfo.f_fstypename, "ufs")) )
drhfd131da2007-08-07 17:13:03 +0000604 return posixLockingStyle;
drhbfe66312006-10-03 17:40:40 +0000605
606 if(!strcmp(fsInfo.f_fstypename, "afpfs"))
607 return afpLockingStyle;
608
609 if(!strcmp(fsInfo.f_fstypename, "nfs"))
610 return sqlite3TestLockingStyle(filePath, fd);
611
612 if(!strcmp(fsInfo.f_fstypename, "smbfs"))
613 return flockLockingStyle;
614
615 if(!strcmp(fsInfo.f_fstypename, "msdos"))
616 return dotlockLockingStyle;
617
618 if(!strcmp(fsInfo.f_fstypename, "webdav"))
619 return unsupportedLockingStyle;
620
621 return sqlite3TestLockingStyle(filePath, fd);
drh3b62b2f2007-06-08 18:27:03 +0000622#endif /* SQLITE_FIXED_LOCKING_STYLE */
drhbfe66312006-10-03 17:40:40 +0000623}
624
625#endif /* SQLITE_ENABLE_LOCKING_STYLE */
626
drhbbd42a62004-05-22 17:41:58 +0000627/*
628** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000629** describes that file descriptor. Create new ones if necessary. The
630** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000631**
632** Return the number of errors.
633*/
drh38f82712004-06-18 17:10:16 +0000634static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000635 int fd, /* The file descriptor used in the key */
636 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000637 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000638){
639 int rc;
640 struct lockKey key1;
641 struct openKey key2;
642 struct stat statbuf;
643 struct lockInfo *pLock;
644 struct openCnt *pOpen;
645 rc = fstat(fd, &statbuf);
646 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000647
drh757b04e2006-01-18 17:25:45 +0000648 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000649 memset(&key1, 0, sizeof(key1));
650 key1.dev = statbuf.st_dev;
651 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000652#ifdef SQLITE_UNIX_THREADS
653 if( threadsOverrideEachOthersLocks<0 ){
654 testThreadLockingBehavior(fd);
655 }
656 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
657#endif
drhbbd42a62004-05-22 17:41:58 +0000658 memset(&key2, 0, sizeof(key2));
659 key2.dev = statbuf.st_dev;
660 key2.ino = statbuf.st_ino;
661 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
662 if( pLock==0 ){
663 struct lockInfo *pOld;
danielk1977750b03e2006-02-14 10:48:39 +0000664 pLock = sqlite3ThreadSafeMalloc( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000665 if( pLock==0 ){
666 rc = 1;
667 goto exit_findlockinfo;
668 }
drhbbd42a62004-05-22 17:41:58 +0000669 pLock->key = key1;
670 pLock->nRef = 1;
671 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000672 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000673 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
674 if( pOld!=0 ){
675 assert( pOld==pLock );
danielk1977750b03e2006-02-14 10:48:39 +0000676 sqlite3ThreadSafeFree(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000677 rc = 1;
678 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000679 }
680 }else{
681 pLock->nRef++;
682 }
683 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000684 if( ppOpen!=0 ){
685 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
drhbbd42a62004-05-22 17:41:58 +0000686 if( pOpen==0 ){
drh029b44b2006-01-15 00:13:15 +0000687 struct openCnt *pOld;
danielk1977750b03e2006-02-14 10:48:39 +0000688 pOpen = sqlite3ThreadSafeMalloc( sizeof(*pOpen) );
drh029b44b2006-01-15 00:13:15 +0000689 if( pOpen==0 ){
690 releaseLockInfo(pLock);
691 rc = 1;
692 goto exit_findlockinfo;
693 }
694 pOpen->key = key2;
695 pOpen->nRef = 1;
696 pOpen->nLock = 0;
697 pOpen->nPending = 0;
698 pOpen->aPending = 0;
699 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
700 if( pOld!=0 ){
701 assert( pOld==pOpen );
danielk1977750b03e2006-02-14 10:48:39 +0000702 sqlite3ThreadSafeFree(pOpen);
drh029b44b2006-01-15 00:13:15 +0000703 releaseLockInfo(pLock);
704 rc = 1;
705 goto exit_findlockinfo;
706 }
707 }else{
708 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000709 }
drh029b44b2006-01-15 00:13:15 +0000710 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000711 }
danielk1977441b09a2006-01-05 13:48:29 +0000712
713exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000714 return rc;
drhbbd42a62004-05-22 17:41:58 +0000715}
716
drh64b1bea2006-01-15 02:30:57 +0000717#ifdef SQLITE_DEBUG
718/*
719** Helper function for printing out trace information from debugging
720** binaries. This returns the string represetation of the supplied
721** integer lock-type.
722*/
723static const char *locktypeName(int locktype){
724 switch( locktype ){
725 case NO_LOCK: return "NONE";
726 case SHARED_LOCK: return "SHARED";
727 case RESERVED_LOCK: return "RESERVED";
728 case PENDING_LOCK: return "PENDING";
729 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
730 }
731 return "ERROR";
732}
733#endif
734
drhbbd42a62004-05-22 17:41:58 +0000735/*
drh029b44b2006-01-15 00:13:15 +0000736** If we are currently in a different thread than the thread that the
737** unixFile argument belongs to, then transfer ownership of the unixFile
738** over to the current thread.
739**
740** A unixFile is only owned by a thread on systems where one thread is
741** unable to override locks created by a different thread. RedHat9 is
742** an example of such a system.
743**
744** Ownership transfer is only allowed if the unixFile is currently unlocked.
745** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000746** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000747*/
748#ifdef SQLITE_UNIX_THREADS
749static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000750 int rc;
drh029b44b2006-01-15 00:13:15 +0000751 pthread_t hSelf;
752 if( threadsOverrideEachOthersLocks ){
753 /* Ownership transfers not needed on this system */
754 return SQLITE_OK;
755 }
756 hSelf = pthread_self();
757 if( pthread_equal(pFile->tid, hSelf) ){
758 /* We are still in the same thread */
drh4f0c5872007-03-26 22:05:01 +0000759 OSTRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000760 return SQLITE_OK;
761 }
762 if( pFile->locktype!=NO_LOCK ){
763 /* We cannot change ownership while we are holding a lock! */
764 return SQLITE_MISUSE;
765 }
drh4f0c5872007-03-26 22:05:01 +0000766 OSTRACE4("Transfer ownership of %d from %d to %d\n",
767 pFile->h, pFile->tid, hSelf);
drh029b44b2006-01-15 00:13:15 +0000768 pFile->tid = hSelf;
drhbfe66312006-10-03 17:40:40 +0000769 if (pFile->pLock != NULL) {
770 releaseLockInfo(pFile->pLock);
771 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
drh4f0c5872007-03-26 22:05:01 +0000772 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +0000773 locktypeName(pFile->locktype),
774 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
775 return rc;
776 } else {
777 return SQLITE_OK;
778 }
drh029b44b2006-01-15 00:13:15 +0000779}
780#else
drhf1a221e2006-01-15 17:27:17 +0000781 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +0000782# define transferOwnership(X) SQLITE_OK
783#endif
784
785/*
drhbbd42a62004-05-22 17:41:58 +0000786** Delete the named file
787*/
drh66560ad2006-01-06 14:32:19 +0000788int sqlite3UnixDelete(const char *zFilename){
danielk1977979f38e2007-03-27 16:19:51 +0000789 SimulateIOError(return SQLITE_IOERR_DELETE);
drhbbd42a62004-05-22 17:41:58 +0000790 unlink(zFilename);
791 return SQLITE_OK;
792}
793
794/*
795** Return TRUE if the named file exists.
796*/
drh66560ad2006-01-06 14:32:19 +0000797int sqlite3UnixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000798 return access(zFilename, 0)==0;
799}
800
drh054889e2005-11-30 03:20:31 +0000801/* Forward declaration */
drhbfe66312006-10-03 17:40:40 +0000802static int allocateUnixFile(
803 int h, /* File descriptor of the open file */
804 OsFile **pId, /* Write the real file descriptor here */
805 const char *zFilename, /* Name of the file being opened */
806 int delFlag /* If true, make sure the file deletes on close */
807);
drh9cbe6352005-11-29 03:13:21 +0000808
809/*
drhbbd42a62004-05-22 17:41:58 +0000810** Attempt to open a file for both reading and writing. If that
811** fails, try opening it read-only. If the file does not exist,
812** try to create it.
813**
814** On success, a handle for the open file is written to *id
815** and *pReadonly is set to 0 if the file was opened for reading and
816** writing or 1 if the file was opened read-only. The function returns
817** SQLITE_OK.
818**
819** On failure, the function returns SQLITE_CANTOPEN and leaves
820** *id and *pReadonly unchanged.
821*/
drh66560ad2006-01-06 14:32:19 +0000822int sqlite3UnixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000823 const char *zFilename,
drh9cbe6352005-11-29 03:13:21 +0000824 OsFile **pId,
drhbbd42a62004-05-22 17:41:58 +0000825 int *pReadonly
826){
drhbfe66312006-10-03 17:40:40 +0000827 int h;
828
drh66560ad2006-01-06 14:32:19 +0000829 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
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 }
drhbfe66312006-10-03 17:40:40 +0000847 return allocateUnixFile(h, pId, zFilename, 0);
drhbbd42a62004-05-22 17:41:58 +0000848}
849
850
851/*
852** Attempt to open a new file for exclusive access by this process.
853** The file will be opened for both reading and writing. To avoid
854** a potential security problem, we do not allow the file to have
855** previously existed. Nor do we allow the file to be a symbolic
856** link.
857**
858** If delFlag is true, then make arrangements to automatically delete
859** the file when it is closed.
860**
861** On success, write the file handle into *id and return SQLITE_OK.
862**
863** On failure, return SQLITE_CANTOPEN.
864*/
drh66560ad2006-01-06 14:32:19 +0000865int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
drhbfe66312006-10-03 17:40:40 +0000866 int h;
drh9cbe6352005-11-29 03:13:21 +0000867
drh66560ad2006-01-06 14:32:19 +0000868 CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
drh9cbe6352005-11-29 03:13:21 +0000869 assert( 0==*pId );
drhbfe66312006-10-03 17:40:40 +0000870 h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000871 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
drh3f56e6e2007-03-15 01:16:47 +0000872 delFlag ? 0600 : SQLITE_DEFAULT_FILE_PERMISSIONS);
drhbfe66312006-10-03 17:40:40 +0000873 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000874 return SQLITE_CANTOPEN;
875 }
drhbfe66312006-10-03 17:40:40 +0000876 return allocateUnixFile(h, pId, zFilename, delFlag);
drhbbd42a62004-05-22 17:41:58 +0000877}
878
879/*
880** Attempt to open a new file for read-only access.
881**
882** On success, write the file handle into *id and return SQLITE_OK.
883**
884** On failure, return SQLITE_CANTOPEN.
885*/
drh66560ad2006-01-06 14:32:19 +0000886int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
drhbfe66312006-10-03 17:40:40 +0000887 int h;
888
drh66560ad2006-01-06 14:32:19 +0000889 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
drh9cbe6352005-11-29 03:13:21 +0000890 assert( 0==*pId );
drhbfe66312006-10-03 17:40:40 +0000891 h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
892 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000893 return SQLITE_CANTOPEN;
894 }
drhbfe66312006-10-03 17:40:40 +0000895 return allocateUnixFile(h, pId, zFilename, 0);
drhbbd42a62004-05-22 17:41:58 +0000896}
897
898/*
899** Attempt to open a file descriptor for the directory that contains a
900** file. This file descriptor can be used to fsync() the directory
901** in order to make sure the creation of a new file is actually written
902** to disk.
903**
904** This routine is only meaningful for Unix. It is a no-op under
905** windows since windows does not support hard links.
906**
drhbfe66312006-10-03 17:40:40 +0000907** If FULL_FSYNC is enabled, this function is not longer useful,
908** a FULL_FSYNC sync applies to all pending disk operations.
909**
drh9cbe6352005-11-29 03:13:21 +0000910** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000911** updated with the new directory file descriptor and SQLITE_OK is
912** returned.
913**
914** On failure, the function returns SQLITE_CANTOPEN and leaves
915** *id unchanged.
916*/
drh9c06c952005-11-26 00:25:00 +0000917static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000918 OsFile *id,
919 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000920){
drhe78669b2007-06-29 12:04:26 +0000921 int h;
drh054889e2005-11-30 03:20:31 +0000922 unixFile *pFile = (unixFile*)id;
drhbb5f18d2007-04-06 18:23:17 +0000923 assert( pFile!=0 );
drh054889e2005-11-30 03:20:31 +0000924 SET_THREADID(pFile);
925 assert( pFile->dirfd<0 );
drhe78669b2007-06-29 12:04:26 +0000926 pFile->dirfd = h = open(zDirname, O_RDONLY|O_BINARY, 0);
927 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000928 return SQLITE_CANTOPEN;
929 }
drhe78669b2007-06-29 12:04:26 +0000930#ifdef FD_CLOEXEC
931 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
932#endif
933 OSTRACE3("OPENDIR %-3d %s\n", h, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000934 return SQLITE_OK;
935}
936
937/*
938** Create a temporary file name in zBuf. zBuf must be big enough to
939** hold at least SQLITE_TEMPNAME_SIZE characters.
940*/
drh66560ad2006-01-06 14:32:19 +0000941int sqlite3UnixTempFileName(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +0000942 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000943 0,
drhbbd42a62004-05-22 17:41:58 +0000944 "/var/tmp",
945 "/usr/tmp",
946 "/tmp",
947 ".",
948 };
drh57196282004-10-06 15:41:16 +0000949 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000950 "abcdefghijklmnopqrstuvwxyz"
951 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
952 "0123456789";
953 int i, j;
954 struct stat buf;
955 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000956 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000957 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000958 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000959 if( stat(azDirs[i], &buf) ) continue;
960 if( !S_ISDIR(buf.st_mode) ) continue;
961 if( access(azDirs[i], 07) ) continue;
962 zDir = azDirs[i];
963 break;
964 }
965 do{
drh5bb3eb92007-05-04 13:15:55 +0000966 sqlite3_snprintf(SQLITE_TEMPNAME_SIZE, zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
drhbbd42a62004-05-22 17:41:58 +0000967 j = strlen(zBuf);
968 sqlite3Randomness(15, &zBuf[j]);
969 for(i=0; i<15; i++, j++){
970 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
971 }
972 zBuf[j] = 0;
973 }while( access(zBuf,0)==0 );
974 return SQLITE_OK;
975}
976
977/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000978** Check that a given pathname is a directory and is writable
979**
980*/
drh66560ad2006-01-06 14:32:19 +0000981int sqlite3UnixIsDirWritable(char *zBuf){
drh9c06c952005-11-26 00:25:00 +0000982#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000983 struct stat buf;
984 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000985 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000986 if( stat(zBuf, &buf) ) return 0;
987 if( !S_ISDIR(buf.st_mode) ) return 0;
988 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000989#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000990 return 1;
991}
992
993/*
drhb912b282006-03-23 22:42:20 +0000994** Seek to the offset in id->offset then read cnt bytes into pBuf.
995** Return the number of bytes actually read. Update the offset.
996*/
997static int seekAndRead(unixFile *id, void *pBuf, int cnt){
998 int got;
drh8ebf6702007-02-06 11:11:08 +0000999 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +00001000 TIMER_START;
drh8350a212007-03-22 15:22:06 +00001001#if defined(USE_PREAD)
drhb912b282006-03-23 22:42:20 +00001002 got = pread(id->h, pBuf, cnt, id->offset);
drhbb5f18d2007-04-06 18:23:17 +00001003 SimulateIOError( got = -1 );
drh8350a212007-03-22 15:22:06 +00001004#elif defined(USE_PREAD64)
1005 got = pread64(id->h, pBuf, cnt, id->offset);
drhbb5f18d2007-04-06 18:23:17 +00001006 SimulateIOError( got = -1 );
drhb912b282006-03-23 22:42:20 +00001007#else
drh8ebf6702007-02-06 11:11:08 +00001008 newOffset = lseek(id->h, id->offset, SEEK_SET);
drhbb5f18d2007-04-06 18:23:17 +00001009 SimulateIOError( newOffset-- );
drh8ebf6702007-02-06 11:11:08 +00001010 if( newOffset!=id->offset ){
1011 return -1;
1012 }
drhb912b282006-03-23 22:42:20 +00001013 got = read(id->h, pBuf, cnt);
1014#endif
drh15d00c42007-02-27 02:01:14 +00001015 TIMER_END;
drh4f0c5872007-03-26 22:05:01 +00001016 OSTRACE5("READ %-3d %5d %7lld %d\n", id->h, got, id->offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +00001017 if( got>0 ){
1018 id->offset += got;
1019 }
1020 return got;
1021}
1022
1023/*
drhbbd42a62004-05-22 17:41:58 +00001024** Read data from a file into a buffer. Return SQLITE_OK if all
1025** bytes were read successfully and SQLITE_IOERR if anything goes
1026** wrong.
1027*/
drh9c06c952005-11-26 00:25:00 +00001028static int unixRead(OsFile *id, void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +00001029 int got;
drh9cbe6352005-11-29 03:13:21 +00001030 assert( id );
drhb912b282006-03-23 22:42:20 +00001031 got = seekAndRead((unixFile*)id, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +00001032 if( got==amt ){
1033 return SQLITE_OK;
drh4ac285a2006-09-15 07:28:50 +00001034 }else if( got<0 ){
1035 return SQLITE_IOERR_READ;
drhbbd42a62004-05-22 17:41:58 +00001036 }else{
drhbafda092007-01-03 23:36:22 +00001037 memset(&((char*)pBuf)[got], 0, amt-got);
drh4ac285a2006-09-15 07:28:50 +00001038 return SQLITE_IOERR_SHORT_READ;
drhbbd42a62004-05-22 17:41:58 +00001039 }
1040}
1041
1042/*
drhb912b282006-03-23 22:42:20 +00001043** Seek to the offset in id->offset then read cnt bytes into pBuf.
1044** Return the number of bytes actually read. Update the offset.
1045*/
1046static int seekAndWrite(unixFile *id, const void *pBuf, int cnt){
1047 int got;
drh8ebf6702007-02-06 11:11:08 +00001048 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +00001049 TIMER_START;
drh8350a212007-03-22 15:22:06 +00001050#if defined(USE_PREAD)
drhb912b282006-03-23 22:42:20 +00001051 got = pwrite(id->h, pBuf, cnt, id->offset);
drh8350a212007-03-22 15:22:06 +00001052#elif defined(USE_PREAD64)
1053 got = pwrite64(id->h, pBuf, cnt, id->offset);
drhb912b282006-03-23 22:42:20 +00001054#else
drh8ebf6702007-02-06 11:11:08 +00001055 newOffset = lseek(id->h, id->offset, SEEK_SET);
1056 if( newOffset!=id->offset ){
1057 return -1;
1058 }
drhb912b282006-03-23 22:42:20 +00001059 got = write(id->h, pBuf, cnt);
1060#endif
drh15d00c42007-02-27 02:01:14 +00001061 TIMER_END;
drh4f0c5872007-03-26 22:05:01 +00001062 OSTRACE5("WRITE %-3d %5d %7lld %d\n", id->h, got, id->offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +00001063 if( got>0 ){
1064 id->offset += got;
1065 }
1066 return got;
1067}
1068
1069
1070/*
drhbbd42a62004-05-22 17:41:58 +00001071** Write data from a buffer into a file. Return SQLITE_OK on success
1072** or some other error code on failure.
1073*/
drh9c06c952005-11-26 00:25:00 +00001074static int unixWrite(OsFile *id, const void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +00001075 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +00001076 assert( id );
drh4c7f9412005-02-03 00:29:47 +00001077 assert( amt>0 );
drhb912b282006-03-23 22:42:20 +00001078 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +00001079 amt -= wrote;
1080 pBuf = &((char*)pBuf)[wrote];
1081 }
drh59685932006-09-14 13:47:11 +00001082 SimulateIOError(( wrote=(-1), amt=1 ));
1083 SimulateDiskfullError(( wrote=0, amt=1 ));
drhbbd42a62004-05-22 17:41:58 +00001084 if( amt>0 ){
drh59685932006-09-14 13:47:11 +00001085 if( wrote<0 ){
drh4ac285a2006-09-15 07:28:50 +00001086 return SQLITE_IOERR_WRITE;
drh59685932006-09-14 13:47:11 +00001087 }else{
1088 return SQLITE_FULL;
1089 }
drhbbd42a62004-05-22 17:41:58 +00001090 }
1091 return SQLITE_OK;
1092}
1093
1094/*
1095** Move the read/write pointer in a file.
1096*/
drh9c06c952005-11-26 00:25:00 +00001097static int unixSeek(OsFile *id, i64 offset){
drh9cbe6352005-11-29 03:13:21 +00001098 assert( id );
drhb4746b92005-09-09 01:32:06 +00001099#ifdef SQLITE_TEST
drh59685932006-09-14 13:47:11 +00001100 if( offset ) SimulateDiskfullError(return SQLITE_FULL);
drhb4746b92005-09-09 01:32:06 +00001101#endif
drhb912b282006-03-23 22:42:20 +00001102 ((unixFile*)id)->offset = offset;
drhbbd42a62004-05-22 17:41:58 +00001103 return SQLITE_OK;
1104}
1105
drhb851b2c2005-03-10 14:11:12 +00001106#ifdef SQLITE_TEST
1107/*
1108** Count the number of fullsyncs and normal syncs. This is used to test
1109** that syncs and fullsyncs are occuring at the right times.
1110*/
1111int sqlite3_sync_count = 0;
1112int sqlite3_fullsync_count = 0;
1113#endif
1114
drhf2f23912005-10-05 10:29:36 +00001115/*
1116** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
1117** Otherwise use fsync() in its place.
1118*/
1119#ifndef HAVE_FDATASYNC
1120# define fdatasync fsync
1121#endif
1122
drhac530b12006-02-11 01:25:50 +00001123/*
1124** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
1125** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
1126** only available on Mac OS X. But that could change.
1127*/
1128#ifdef F_FULLFSYNC
1129# define HAVE_FULLFSYNC 1
1130#else
1131# define HAVE_FULLFSYNC 0
1132#endif
1133
drhb851b2c2005-03-10 14:11:12 +00001134
drhbbd42a62004-05-22 17:41:58 +00001135/*
drhdd809b02004-07-17 21:44:57 +00001136** The fsync() system call does not work as advertised on many
1137** unix systems. The following procedure is an attempt to make
1138** it work better.
drh1398ad32005-01-19 23:24:50 +00001139**
1140** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
1141** for testing when we want to run through the test suite quickly.
1142** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
1143** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
1144** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +00001145*/
drheb796a72005-09-08 12:38:41 +00001146static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +00001147 int rc;
drhb851b2c2005-03-10 14:11:12 +00001148
1149 /* Record the number of times that we do a normal fsync() and
1150 ** FULLSYNC. This is used during testing to verify that this procedure
1151 ** gets called with the correct arguments.
1152 */
1153#ifdef SQLITE_TEST
1154 if( fullSync ) sqlite3_fullsync_count++;
1155 sqlite3_sync_count++;
1156#endif
1157
1158 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
1159 ** no-op
1160 */
1161#ifdef SQLITE_NO_SYNC
1162 rc = SQLITE_OK;
1163#else
1164
drhac530b12006-02-11 01:25:50 +00001165#if HAVE_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +00001166 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +00001167 rc = fcntl(fd, F_FULLFSYNC, 0);
aswiftae0943b2007-01-31 23:37:07 +00001168 }else{
1169 rc = 1;
1170 }
1171 /* If the FULLFSYNC failed, fall back to attempting an fsync().
1172 * It shouldn't be possible for fullfsync to fail on the local
1173 * file system (on OSX), so failure indicates that FULLFSYNC
1174 * isn't supported for this file system. So, attempt an fsync
1175 * and (for now) ignore the overhead of a superfluous fcntl call.
1176 * It'd be better to detect fullfsync support once and avoid
1177 * the fcntl call every time sync is called.
1178 */
1179 if( rc ) rc = fsync(fd);
1180
1181#else
drheb796a72005-09-08 12:38:41 +00001182 if( dataOnly ){
1183 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +00001184 }else{
drheb796a72005-09-08 12:38:41 +00001185 rc = fsync(fd);
1186 }
aswiftae0943b2007-01-31 23:37:07 +00001187#endif /* HAVE_FULLFSYNC */
drhb851b2c2005-03-10 14:11:12 +00001188#endif /* defined(SQLITE_NO_SYNC) */
1189
drhdd809b02004-07-17 21:44:57 +00001190 return rc;
1191}
1192
1193/*
drhbbd42a62004-05-22 17:41:58 +00001194** Make sure all writes to a particular file are committed to disk.
1195**
drheb796a72005-09-08 12:38:41 +00001196** If dataOnly==0 then both the file itself and its metadata (file
1197** size, access time, etc) are synced. If dataOnly!=0 then only the
1198** file data is synced.
1199**
drhbbd42a62004-05-22 17:41:58 +00001200** Under Unix, also make sure that the directory entry for the file
1201** has been created by fsync-ing the directory that contains the file.
1202** If we do not do this and we encounter a power failure, the directory
1203** entry for the journal might not exist after we reboot. The next
1204** SQLite to access the file will not know that the journal exists (because
1205** the directory entry for the journal was never created) and the transaction
1206** will not roll back - possibly leading to database corruption.
1207*/
drh9c06c952005-11-26 00:25:00 +00001208static int unixSync(OsFile *id, int dataOnly){
drh59685932006-09-14 13:47:11 +00001209 int rc;
drh054889e2005-11-30 03:20:31 +00001210 unixFile *pFile = (unixFile*)id;
1211 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001212 OSTRACE2("SYNC %-3d\n", pFile->h);
drh59685932006-09-14 13:47:11 +00001213 rc = full_fsync(pFile->h, pFile->fullSync, dataOnly);
1214 SimulateIOError( rc=1 );
1215 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001216 return SQLITE_IOERR_FSYNC;
drhbbd42a62004-05-22 17:41:58 +00001217 }
drh054889e2005-11-30 03:20:31 +00001218 if( pFile->dirfd>=0 ){
drh4f0c5872007-03-26 22:05:01 +00001219 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
drhac530b12006-02-11 01:25:50 +00001220 HAVE_FULLFSYNC, pFile->fullSync);
danielk1977d7c03f72005-11-25 10:38:22 +00001221#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001222 /* The directory sync is only attempted if full_fsync is
1223 ** turned off or unavailable. If a full_fsync occurred above,
1224 ** then the directory sync is superfluous.
1225 */
1226 if( (!HAVE_FULLFSYNC || !pFile->fullSync) && full_fsync(pFile->dirfd,0,0) ){
1227 /*
1228 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001229 ** errors when applied to directories on certain file systems.
1230 ** A failed directory sync is not a big deal. So it seems
1231 ** better to ignore the error. Ticket #1657
1232 */
1233 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001234 }
danielk1977d7c03f72005-11-25 10:38:22 +00001235#endif
drh054889e2005-11-30 03:20:31 +00001236 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1237 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001238 }
drha2854222004-06-17 19:04:17 +00001239 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001240}
1241
1242/*
danielk1977962398d2004-06-14 09:35:16 +00001243** Sync the directory zDirname. This is a no-op on operating systems other
1244** than UNIX.
drhb851b2c2005-03-10 14:11:12 +00001245**
1246** This is used to make sure the master journal file has truely been deleted
1247** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +00001248** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +00001249*/
drh66560ad2006-01-06 14:32:19 +00001250int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +00001251#ifdef SQLITE_DISABLE_DIRSYNC
1252 return SQLITE_OK;
1253#else
danielk1977962398d2004-06-14 09:35:16 +00001254 int fd;
1255 int r;
drh8e855772005-05-17 11:25:31 +00001256 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh4f0c5872007-03-26 22:05:01 +00001257 OSTRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001258 if( fd<0 ){
1259 return SQLITE_CANTOPEN;
1260 }
1261 r = fsync(fd);
1262 close(fd);
drh59685932006-09-14 13:47:11 +00001263 SimulateIOError( r=1 );
1264 if( r ){
drh4ac285a2006-09-15 07:28:50 +00001265 return SQLITE_IOERR_DIR_FSYNC;
drh59685932006-09-14 13:47:11 +00001266 }else{
1267 return SQLITE_OK;
1268 }
danielk1977d7c03f72005-11-25 10:38:22 +00001269#endif
danielk1977962398d2004-06-14 09:35:16 +00001270}
1271
1272/*
drhbbd42a62004-05-22 17:41:58 +00001273** Truncate an open file to a specified size
1274*/
drh9c06c952005-11-26 00:25:00 +00001275static int unixTruncate(OsFile *id, i64 nByte){
drh59685932006-09-14 13:47:11 +00001276 int rc;
drh9cbe6352005-11-29 03:13:21 +00001277 assert( id );
drh63fff5f2007-06-19 10:50:38 +00001278 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
drh59685932006-09-14 13:47:11 +00001279 SimulateIOError( rc=1 );
1280 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001281 return SQLITE_IOERR_TRUNCATE;
drh59685932006-09-14 13:47:11 +00001282 }else{
1283 return SQLITE_OK;
1284 }
drhbbd42a62004-05-22 17:41:58 +00001285}
1286
1287/*
1288** Determine the current size of a file in bytes
1289*/
drh9c06c952005-11-26 00:25:00 +00001290static int unixFileSize(OsFile *id, i64 *pSize){
drh59685932006-09-14 13:47:11 +00001291 int rc;
drhbbd42a62004-05-22 17:41:58 +00001292 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001293 assert( id );
drh59685932006-09-14 13:47:11 +00001294 rc = fstat(((unixFile*)id)->h, &buf);
1295 SimulateIOError( rc=1 );
1296 if( rc!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001297 return SQLITE_IOERR_FSTAT;
drhbbd42a62004-05-22 17:41:58 +00001298 }
1299 *pSize = buf.st_size;
1300 return SQLITE_OK;
1301}
1302
danielk19779a1d0ab2004-06-01 14:09:28 +00001303/*
danielk197713adf8a2004-06-03 16:08:41 +00001304** This routine checks if there is a RESERVED lock held on the specified
1305** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001306** non-zero. If the file is unlocked or holds only SHARED locks, then
1307** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001308*/
drh9c06c952005-11-26 00:25:00 +00001309static int unixCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +00001310 int r = 0;
drh054889e2005-11-30 03:20:31 +00001311 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001312
drh054889e2005-11-30 03:20:31 +00001313 assert( pFile );
drh66560ad2006-01-06 14:32:19 +00001314 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001315
1316 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001317 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001318 r = 1;
1319 }
1320
drh2ac3ee92004-06-07 16:27:46 +00001321 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001322 */
1323 if( !r ){
1324 struct flock lock;
1325 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001326 lock.l_start = RESERVED_BYTE;
1327 lock.l_len = 1;
1328 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001329 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001330 if( lock.l_type!=F_UNLCK ){
1331 r = 1;
1332 }
1333 }
1334
drh66560ad2006-01-06 14:32:19 +00001335 sqlite3OsLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001336 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001337
1338 return r;
1339}
1340
1341/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001342** Lock the file with the lock specified by parameter locktype - one
1343** of the following:
1344**
drh2ac3ee92004-06-07 16:27:46 +00001345** (1) SHARED_LOCK
1346** (2) RESERVED_LOCK
1347** (3) PENDING_LOCK
1348** (4) EXCLUSIVE_LOCK
1349**
drhb3e04342004-06-08 00:47:47 +00001350** Sometimes when requesting one lock state, additional lock states
1351** are inserted in between. The locking might fail on one of the later
1352** transitions leaving the lock state different from what it started but
1353** still short of its goal. The following chart shows the allowed
1354** transitions and the inserted intermediate states:
1355**
1356** UNLOCKED -> SHARED
1357** SHARED -> RESERVED
1358** SHARED -> (PENDING) -> EXCLUSIVE
1359** RESERVED -> (PENDING) -> EXCLUSIVE
1360** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001361**
drha6abd042004-06-09 17:37:22 +00001362** This routine will only increase a lock. Use the sqlite3OsUnlock()
1363** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001364*/
drh9c06c952005-11-26 00:25:00 +00001365static int unixLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001366 /* The following describes the implementation of the various locks and
1367 ** lock transitions in terms of the POSIX advisory shared and exclusive
1368 ** lock primitives (called read-locks and write-locks below, to avoid
1369 ** confusion with SQLite lock names). The algorithms are complicated
1370 ** slightly in order to be compatible with windows systems simultaneously
1371 ** accessing the same database file, in case that is ever required.
1372 **
1373 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1374 ** byte', each single bytes at well known offsets, and the 'shared byte
1375 ** range', a range of 510 bytes at a well known offset.
1376 **
1377 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1378 ** byte'. If this is successful, a random byte from the 'shared byte
1379 ** range' is read-locked and the lock on the 'pending byte' released.
1380 **
danielk197790ba3bd2004-06-25 08:32:25 +00001381 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1382 ** A RESERVED lock is implemented by grabbing a write-lock on the
1383 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001384 **
1385 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001386 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1387 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1388 ** obtained, but existing SHARED locks are allowed to persist. A process
1389 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1390 ** This property is used by the algorithm for rolling back a journal file
1391 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001392 **
danielk197790ba3bd2004-06-25 08:32:25 +00001393 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1394 ** implemented by obtaining a write-lock on the entire 'shared byte
1395 ** range'. Since all other locks require a read-lock on one of the bytes
1396 ** within this range, this ensures that no other locks are held on the
1397 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001398 **
1399 ** The reason a single byte cannot be used instead of the 'shared byte
1400 ** range' is that some versions of windows do not support read-locks. By
1401 ** locking a random byte from a range, concurrent SHARED locks may exist
1402 ** even if the locking primitive used is always a write-lock.
1403 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001404 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001405 unixFile *pFile = (unixFile*)id;
1406 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001407 struct flock lock;
1408 int s;
1409
drh054889e2005-11-30 03:20:31 +00001410 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001411 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001412 locktypeName(locktype), locktypeName(pFile->locktype),
1413 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001414
1415 /* If there is already a lock of this type or more restrictive on the
1416 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh66560ad2006-01-06 14:32:19 +00001417 ** sqlite3OsEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001418 */
drh054889e2005-11-30 03:20:31 +00001419 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001420 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001421 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001422 return SQLITE_OK;
1423 }
1424
drhb3e04342004-06-08 00:47:47 +00001425 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001426 */
drh054889e2005-11-30 03:20:31 +00001427 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001428 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001429 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001430
drh054889e2005-11-30 03:20:31 +00001431 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001432 */
drh66560ad2006-01-06 14:32:19 +00001433 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001434
drh029b44b2006-01-15 00:13:15 +00001435 /* Make sure the current thread owns the pFile.
1436 */
1437 rc = transferOwnership(pFile);
1438 if( rc!=SQLITE_OK ){
1439 sqlite3OsLeaveMutex();
1440 return rc;
1441 }
drh64b1bea2006-01-15 02:30:57 +00001442 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001443
danielk19779a1d0ab2004-06-01 14:09:28 +00001444 /* If some thread using this PID has a lock via a different OsFile*
1445 ** handle that precludes the requested lock, return BUSY.
1446 */
drh054889e2005-11-30 03:20:31 +00001447 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001448 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001449 ){
1450 rc = SQLITE_BUSY;
1451 goto end_lock;
1452 }
1453
1454 /* If a SHARED lock is requested, and some thread using this PID already
1455 ** has a SHARED or RESERVED lock, then increment reference counts and
1456 ** return SQLITE_OK.
1457 */
1458 if( locktype==SHARED_LOCK &&
1459 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1460 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001461 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001462 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001463 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001464 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001465 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001466 goto end_lock;
1467 }
1468
danielk197713adf8a2004-06-03 16:08:41 +00001469 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001470
danielk19779a1d0ab2004-06-01 14:09:28 +00001471 lock.l_whence = SEEK_SET;
1472
drh3cde3bb2004-06-12 02:17:14 +00001473 /* A PENDING lock is needed before acquiring a SHARED lock and before
1474 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1475 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001476 */
drh3cde3bb2004-06-12 02:17:14 +00001477 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001478 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001479 ){
danielk1977489468c2004-06-28 08:25:47 +00001480 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001481 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001482 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001483 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001484 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1485 goto end_lock;
1486 }
drh3cde3bb2004-06-12 02:17:14 +00001487 }
1488
1489
1490 /* If control gets to this point, then actually go ahead and make
1491 ** operating system calls for the specified lock.
1492 */
1493 if( locktype==SHARED_LOCK ){
1494 assert( pLock->cnt==0 );
1495 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001496
drh2ac3ee92004-06-07 16:27:46 +00001497 /* Now get the read-lock */
1498 lock.l_start = SHARED_FIRST;
1499 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001500 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001501
1502 /* Drop the temporary PENDING lock */
1503 lock.l_start = PENDING_BYTE;
1504 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001505 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001506 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001507 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001508 goto end_lock;
1509 }
drhe2396a12007-03-29 20:19:58 +00001510 if( s==(-1) ){
drhbbd42a62004-05-22 17:41:58 +00001511 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1512 }else{
drh054889e2005-11-30 03:20:31 +00001513 pFile->locktype = SHARED_LOCK;
1514 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001515 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001516 }
drh3cde3bb2004-06-12 02:17:14 +00001517 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1518 /* We are trying for an exclusive lock but another thread in this
1519 ** same process is still holding a shared lock. */
1520 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001521 }else{
drh3cde3bb2004-06-12 02:17:14 +00001522 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001523 ** assumed that there is a SHARED or greater lock on the file
1524 ** already.
1525 */
drh054889e2005-11-30 03:20:31 +00001526 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001527 lock.l_type = F_WRLCK;
1528 switch( locktype ){
1529 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001530 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001531 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001532 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001533 lock.l_start = SHARED_FIRST;
1534 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001535 break;
1536 default:
1537 assert(0);
1538 }
drh054889e2005-11-30 03:20:31 +00001539 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001540 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001541 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1542 }
drhbbd42a62004-05-22 17:41:58 +00001543 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001544
danielk1977ecb2a962004-06-02 06:30:16 +00001545 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001546 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001547 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001548 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001549 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001550 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001551 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001552
1553end_lock:
drh66560ad2006-01-06 14:32:19 +00001554 sqlite3OsLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001555 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001556 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001557 return rc;
1558}
1559
1560/*
drh054889e2005-11-30 03:20:31 +00001561** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001562** must be either NO_LOCK or SHARED_LOCK.
1563**
1564** If the locking level of the file descriptor is already at or below
1565** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001566*/
drh9c06c952005-11-26 00:25:00 +00001567static int unixUnlock(OsFile *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001568 struct lockInfo *pLock;
1569 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001570 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001571 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001572
drh054889e2005-11-30 03:20:31 +00001573 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001574 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001575 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001576
1577 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001578 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001579 return SQLITE_OK;
1580 }
drhf1a221e2006-01-15 17:27:17 +00001581 if( CHECK_THREADID(pFile) ){
1582 return SQLITE_MISUSE;
1583 }
drh66560ad2006-01-06 14:32:19 +00001584 sqlite3OsEnterMutex();
drh054889e2005-11-30 03:20:31 +00001585 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001586 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001587 if( pFile->locktype>SHARED_LOCK ){
1588 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001589 if( locktype==SHARED_LOCK ){
1590 lock.l_type = F_RDLCK;
1591 lock.l_whence = SEEK_SET;
1592 lock.l_start = SHARED_FIRST;
1593 lock.l_len = SHARED_SIZE;
drhe2396a12007-03-29 20:19:58 +00001594 if( fcntl(pFile->h, F_SETLK, &lock)==(-1) ){
drh9c105bb2004-10-02 20:38:28 +00001595 /* This should never happen */
drh4ac285a2006-09-15 07:28:50 +00001596 rc = SQLITE_IOERR_RDLOCK;
drh9c105bb2004-10-02 20:38:28 +00001597 }
1598 }
drhbbd42a62004-05-22 17:41:58 +00001599 lock.l_type = F_UNLCK;
1600 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001601 lock.l_start = PENDING_BYTE;
1602 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drhe2396a12007-03-29 20:19:58 +00001603 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001604 pLock->locktype = SHARED_LOCK;
1605 }else{
drh4ac285a2006-09-15 07:28:50 +00001606 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001607 }
drhbbd42a62004-05-22 17:41:58 +00001608 }
drha6abd042004-06-09 17:37:22 +00001609 if( locktype==NO_LOCK ){
1610 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001611
drha6abd042004-06-09 17:37:22 +00001612 /* Decrement the shared lock counter. Release the lock using an
1613 ** OS call only when all threads in this same process have released
1614 ** the lock.
1615 */
1616 pLock->cnt--;
1617 if( pLock->cnt==0 ){
1618 lock.l_type = F_UNLCK;
1619 lock.l_whence = SEEK_SET;
1620 lock.l_start = lock.l_len = 0L;
drhe2396a12007-03-29 20:19:58 +00001621 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001622 pLock->locktype = NO_LOCK;
1623 }else{
drh4ac285a2006-09-15 07:28:50 +00001624 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001625 }
drha6abd042004-06-09 17:37:22 +00001626 }
1627
drhbbd42a62004-05-22 17:41:58 +00001628 /* Decrement the count of locks against this same file. When the
1629 ** count reaches zero, close any other file descriptors whose close
1630 ** was deferred because of outstanding locks.
1631 */
drh054889e2005-11-30 03:20:31 +00001632 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001633 pOpen->nLock--;
1634 assert( pOpen->nLock>=0 );
1635 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1636 int i;
1637 for(i=0; i<pOpen->nPending; i++){
1638 close(pOpen->aPending[i]);
1639 }
drh64b1bea2006-01-15 02:30:57 +00001640 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001641 pOpen->nPending = 0;
1642 pOpen->aPending = 0;
1643 }
1644 }
drh66560ad2006-01-06 14:32:19 +00001645 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001646 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001647 return rc;
drhbbd42a62004-05-22 17:41:58 +00001648}
1649
1650/*
danielk1977e3026632004-06-22 11:29:02 +00001651** Close a file.
1652*/
drh9cbe6352005-11-29 03:13:21 +00001653static int unixClose(OsFile **pId){
drh054889e2005-11-30 03:20:31 +00001654 unixFile *id = (unixFile*)*pId;
drh029b44b2006-01-15 00:13:15 +00001655
drh9cbe6352005-11-29 03:13:21 +00001656 if( !id ) return SQLITE_OK;
drh38322302006-01-15 02:43:16 +00001657 unixUnlock(*pId, NO_LOCK);
danielk1977e3026632004-06-22 11:29:02 +00001658 if( id->dirfd>=0 ) close(id->dirfd);
1659 id->dirfd = -1;
drh66560ad2006-01-06 14:32:19 +00001660 sqlite3OsEnterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001661
drh38322302006-01-15 02:43:16 +00001662 if( id->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001663 /* If there are outstanding locks, do not actually close the file just
1664 ** yet because that would clear those locks. Instead, add the file
1665 ** descriptor to pOpen->aPending. It will be automatically closed when
1666 ** the last lock is cleared.
1667 */
1668 int *aNew;
1669 struct openCnt *pOpen = id->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001670 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001671 if( aNew==0 ){
1672 /* If a malloc fails, just leak the file descriptor */
1673 }else{
1674 pOpen->aPending = aNew;
drhad81e872005-08-21 21:45:01 +00001675 pOpen->aPending[pOpen->nPending] = id->h;
1676 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001677 }
1678 }else{
1679 /* There are no outstanding locks so we can close the file immediately */
1680 close(id->h);
1681 }
1682 releaseLockInfo(id->pLock);
1683 releaseOpenCnt(id->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001684
drh66560ad2006-01-06 14:32:19 +00001685 sqlite3OsLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001686 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00001687 OSTRACE2("CLOSE %-3d\n", id->h);
danielk1977e3026632004-06-22 11:29:02 +00001688 OpenCounter(-1);
danielk1977750b03e2006-02-14 10:48:39 +00001689 sqlite3ThreadSafeFree(id);
drh9cbe6352005-11-29 03:13:21 +00001690 *pId = 0;
drh02afc862006-01-20 18:10:57 +00001691 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001692}
1693
drhbfe66312006-10-03 17:40:40 +00001694
1695#ifdef SQLITE_ENABLE_LOCKING_STYLE
1696#pragma mark AFP Support
1697
1698/*
1699 ** The afpLockingContext structure contains all afp lock specific state
1700 */
1701typedef struct afpLockingContext afpLockingContext;
1702struct afpLockingContext {
1703 unsigned long long sharedLockByte;
1704 char *filePath;
1705};
1706
1707struct ByteRangeLockPB2
1708{
1709 unsigned long long offset; /* offset to first byte to lock */
1710 unsigned long long length; /* nbr of bytes to lock */
1711 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
1712 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
1713 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
1714 int fd; /* file desc to assoc this lock with */
1715};
1716
drhfd131da2007-08-07 17:13:03 +00001717#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00001718
1719/* return 0 on success, 1 on failure. To match the behavior of the
1720 normal posix file locking (used in unixLock for example), we should
1721 provide 'richer' return codes - specifically to differentiate between
1722 'file busy' and 'file system error' results */
1723static int _AFPFSSetLock(const char *path, int fd, unsigned long long offset,
1724 unsigned long long length, int setLockFlag)
1725{
drhfd131da2007-08-07 17:13:03 +00001726 struct ByteRangeLockPB2 pb;
drhbfe66312006-10-03 17:40:40 +00001727 int err;
1728
1729 pb.unLockFlag = setLockFlag ? 0 : 1;
1730 pb.startEndFlag = 0;
1731 pb.offset = offset;
1732 pb.length = length;
1733 pb.fd = fd;
drh4f0c5872007-03-26 22:05:01 +00001734 OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
drhbfe66312006-10-03 17:40:40 +00001735 (setLockFlag?"ON":"OFF"), fd, offset, length);
1736 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
1737 if ( err==-1 ) {
drh4f0c5872007-03-26 22:05:01 +00001738 OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno,
drhbfe66312006-10-03 17:40:40 +00001739 strerror(errno));
drh3b62b2f2007-06-08 18:27:03 +00001740 return 1; /* error */
drhbfe66312006-10-03 17:40:40 +00001741 } else {
1742 return 0;
1743 }
1744}
1745
1746/*
1747 ** This routine checks if there is a RESERVED lock held on the specified
1748 ** file by this or any other process. If such a lock is held, return
1749 ** non-zero. If the file is unlocked or holds only SHARED locks, then
1750 ** return zero.
1751 */
1752static int afpUnixCheckReservedLock(OsFile *id){
1753 int r = 0;
1754 unixFile *pFile = (unixFile*)id;
1755
1756 assert( pFile );
1757 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1758
1759 /* Check if a thread in this process holds such a lock */
1760 if( pFile->locktype>SHARED_LOCK ){
1761 r = 1;
1762 }
1763
1764 /* Otherwise see if some other process holds it.
1765 */
1766 if ( !r ) {
drh3b62b2f2007-06-08 18:27:03 +00001767 /* lock the byte */
drhbfe66312006-10-03 17:40:40 +00001768 int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1769 if (failed) {
1770 /* if we failed to get the lock then someone else must have it */
1771 r = 1;
1772 } else {
1773 /* if we succeeded in taking the reserved lock, unlock it to restore
1774 ** the original state */
1775 _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
1776 }
1777 }
drh4f0c5872007-03-26 22:05:01 +00001778 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
drhbfe66312006-10-03 17:40:40 +00001779
1780 return r;
1781}
1782
1783/* AFP-style locking following the behavior of unixLock, see the unixLock
1784** function comments for details of lock management. */
1785static int afpUnixLock(OsFile *id, int locktype)
1786{
1787 int rc = SQLITE_OK;
1788 unixFile *pFile = (unixFile*)id;
1789 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1790 int gotPendingLock = 0;
1791
1792 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001793 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001794 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
1795 /* If there is already a lock of this type or more restrictive on the
1796 ** OsFile, do nothing. Don't use the afp_end_lock: exit path, as
1797 ** sqlite3OsEnterMutex() hasn't been called yet.
1798 */
1799 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001800 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001801 locktypeName(locktype));
1802 return SQLITE_OK;
1803 }
1804
1805 /* Make sure the locking sequence is correct
1806 */
1807 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
1808 assert( locktype!=PENDING_LOCK );
1809 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1810
1811 /* This mutex is needed because pFile->pLock is shared across threads
1812 */
1813 sqlite3OsEnterMutex();
1814
1815 /* Make sure the current thread owns the pFile.
1816 */
1817 rc = transferOwnership(pFile);
1818 if( rc!=SQLITE_OK ){
1819 sqlite3OsLeaveMutex();
1820 return rc;
1821 }
1822
1823 /* A PENDING lock is needed before acquiring a SHARED lock and before
1824 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1825 ** be released.
1826 */
1827 if( locktype==SHARED_LOCK
1828 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
1829 ){
1830 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1831 PENDING_BYTE, 1, 1);
1832 if (failed) {
1833 rc = SQLITE_BUSY;
1834 goto afp_end_lock;
1835 }
1836 }
1837
1838 /* If control gets to this point, then actually go ahead and make
1839 ** operating system calls for the specified lock.
1840 */
1841 if( locktype==SHARED_LOCK ){
1842 int lk, failed;
1843 int tries = 0;
1844
1845 /* Now get the read-lock */
1846 /* note that the quality of the randomness doesn't matter that much */
1847 lk = random();
1848 context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
1849 failed = _AFPFSSetLock(context->filePath, pFile->h,
1850 SHARED_FIRST+context->sharedLockByte, 1, 1);
1851
1852 /* Drop the temporary PENDING lock */
1853 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
1854 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1855 goto afp_end_lock;
1856 }
1857
1858 if( failed ){
1859 rc = SQLITE_BUSY;
1860 } else {
1861 pFile->locktype = SHARED_LOCK;
1862 }
1863 }else{
1864 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1865 ** assumed that there is a SHARED or greater lock on the file
1866 ** already.
1867 */
1868 int failed = 0;
1869 assert( 0!=pFile->locktype );
1870 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
1871 /* Acquire a RESERVED lock */
1872 failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1873 }
1874 if (!failed && locktype == EXCLUSIVE_LOCK) {
1875 /* Acquire an EXCLUSIVE lock */
1876
1877 /* Remove the shared lock before trying the range. we'll need to
1878 ** reestablish the shared lock if we can't get the afpUnixUnlock
1879 */
1880 if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1881 context->sharedLockByte, 1, 0)) {
1882 /* now attemmpt to get the exclusive lock range */
1883 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1884 SHARED_SIZE, 1);
1885 if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1886 context->sharedLockByte, 1, 1)) {
1887 rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
1888 }
1889 } else {
1890 /* */
1891 rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
1892 }
1893 }
1894 if( failed && rc == SQLITE_OK){
1895 rc = SQLITE_BUSY;
1896 }
1897 }
1898
1899 if( rc==SQLITE_OK ){
1900 pFile->locktype = locktype;
1901 }else if( locktype==EXCLUSIVE_LOCK ){
1902 pFile->locktype = PENDING_LOCK;
1903 }
1904
1905afp_end_lock:
1906 sqlite3OsLeaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001907 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00001908 rc==SQLITE_OK ? "ok" : "failed");
1909 return rc;
1910}
1911
1912/*
1913 ** Lower the locking level on file descriptor pFile to locktype. locktype
1914 ** must be either NO_LOCK or SHARED_LOCK.
1915 **
1916 ** If the locking level of the file descriptor is already at or below
1917 ** the requested locking level, this routine is a no-op.
1918 */
1919static int afpUnixUnlock(OsFile *id, int locktype) {
1920 struct flock lock;
1921 int rc = SQLITE_OK;
1922 unixFile *pFile = (unixFile*)id;
1923 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1924
1925 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001926 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00001927 pFile->locktype, getpid());
1928
1929 assert( locktype<=SHARED_LOCK );
1930 if( pFile->locktype<=locktype ){
1931 return SQLITE_OK;
1932 }
1933 if( CHECK_THREADID(pFile) ){
1934 return SQLITE_MISUSE;
1935 }
1936 sqlite3OsEnterMutex();
1937 if( pFile->locktype>SHARED_LOCK ){
1938 if( locktype==SHARED_LOCK ){
1939 int failed = 0;
1940
1941 /* unlock the exclusive range - then re-establish the shared lock */
1942 if (pFile->locktype==EXCLUSIVE_LOCK) {
1943 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1944 SHARED_SIZE, 0);
1945 if (!failed) {
1946 /* successfully removed the exclusive lock */
1947 if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
1948 context->sharedLockByte, 1, 1)) {
1949 /* failed to re-establish our shared lock */
1950 rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
1951 }
1952 } else {
1953 /* This should never happen - failed to unlock the exclusive range */
1954 rc = SQLITE_IOERR_UNLOCK;
1955 }
1956 }
1957 }
1958 if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
1959 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
1960 /* failed to release the pending lock */
1961 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1962 }
1963 }
1964 if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
1965 if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
1966 /* failed to release the reserved lock */
1967 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1968 }
1969 }
1970 }
1971 if( locktype==NO_LOCK ){
1972 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1973 SHARED_FIRST + context->sharedLockByte, 1, 0);
1974 if (failed) {
1975 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1976 }
1977 }
1978 if (rc == SQLITE_OK)
1979 pFile->locktype = locktype;
1980 sqlite3OsLeaveMutex();
1981 return rc;
1982}
1983
1984/*
1985 ** Close a file & cleanup AFP specific locking context
1986 */
1987static int afpUnixClose(OsFile **pId) {
1988 unixFile *id = (unixFile*)*pId;
1989
1990 if( !id ) return SQLITE_OK;
1991 afpUnixUnlock(*pId, NO_LOCK);
1992 /* free the AFP locking structure */
1993 if (id->lockingContext != NULL) {
1994 if (((afpLockingContext *)id->lockingContext)->filePath != NULL)
1995 sqlite3ThreadSafeFree(((afpLockingContext*)id->lockingContext)->filePath);
1996 sqlite3ThreadSafeFree(id->lockingContext);
1997 }
1998
1999 if( id->dirfd>=0 ) close(id->dirfd);
2000 id->dirfd = -1;
2001 close(id->h);
2002 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00002003 OSTRACE2("CLOSE %-3d\n", id->h);
drhbfe66312006-10-03 17:40:40 +00002004 OpenCounter(-1);
2005 sqlite3ThreadSafeFree(id);
2006 *pId = 0;
2007 return SQLITE_OK;
2008}
2009
2010
2011#pragma mark flock() style locking
2012
2013/*
2014 ** The flockLockingContext is not used
2015 */
2016typedef void flockLockingContext;
2017
2018static int flockUnixCheckReservedLock(OsFile *id) {
2019 unixFile *pFile = (unixFile*)id;
2020
2021 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00002022 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00002023 } else {
drh3b62b2f2007-06-08 18:27:03 +00002024 /* attempt to get the lock */
drhbfe66312006-10-03 17:40:40 +00002025 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
2026 if (!rc) {
drh3b62b2f2007-06-08 18:27:03 +00002027 /* got the lock, unlock it */
drhbfe66312006-10-03 17:40:40 +00002028 flock(pFile->h, LOCK_UN);
drh3b62b2f2007-06-08 18:27:03 +00002029 return 0; /* no one has it reserved */
drhbfe66312006-10-03 17:40:40 +00002030 }
drh3b62b2f2007-06-08 18:27:03 +00002031 return 1; /* someone else might have it reserved */
drhbfe66312006-10-03 17:40:40 +00002032 }
2033}
2034
2035static int flockUnixLock(OsFile *id, int locktype) {
2036 unixFile *pFile = (unixFile*)id;
2037
drh3b62b2f2007-06-08 18:27:03 +00002038 /* if we already have a lock, it is exclusive.
2039 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00002040 if (pFile->locktype > NO_LOCK) {
2041 pFile->locktype = locktype;
2042 return SQLITE_OK;
2043 }
2044
drh3b62b2f2007-06-08 18:27:03 +00002045 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00002046 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
2047 if (rc) {
drh3b62b2f2007-06-08 18:27:03 +00002048 /* didn't get, must be busy */
drhbfe66312006-10-03 17:40:40 +00002049 return SQLITE_BUSY;
2050 } else {
drh3b62b2f2007-06-08 18:27:03 +00002051 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00002052 pFile->locktype = locktype;
2053 return SQLITE_OK;
2054 }
2055}
2056
2057static int flockUnixUnlock(OsFile *id, int locktype) {
2058 unixFile *pFile = (unixFile*)id;
2059
2060 assert( locktype<=SHARED_LOCK );
2061
drh3b62b2f2007-06-08 18:27:03 +00002062 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00002063 if( pFile->locktype==locktype ){
2064 return SQLITE_OK;
2065 }
2066
drh3b62b2f2007-06-08 18:27:03 +00002067 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00002068 if (locktype==SHARED_LOCK) {
2069 pFile->locktype = locktype;
2070 return SQLITE_OK;
2071 }
2072
drh3b62b2f2007-06-08 18:27:03 +00002073 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00002074 int rc = flock(pFile->h, LOCK_UN);
2075 if (rc)
2076 return SQLITE_IOERR_UNLOCK;
2077 else {
2078 pFile->locktype = NO_LOCK;
2079 return SQLITE_OK;
2080 }
2081}
2082
2083/*
2084 ** Close a file.
2085 */
2086static int flockUnixClose(OsFile **pId) {
2087 unixFile *id = (unixFile*)*pId;
2088
2089 if( !id ) return SQLITE_OK;
2090 flockUnixUnlock(*pId, NO_LOCK);
2091
2092 if( id->dirfd>=0 ) close(id->dirfd);
2093 id->dirfd = -1;
2094 sqlite3OsEnterMutex();
2095
2096 close(id->h);
2097 sqlite3OsLeaveMutex();
2098 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00002099 OSTRACE2("CLOSE %-3d\n", id->h);
drhbfe66312006-10-03 17:40:40 +00002100 OpenCounter(-1);
2101 sqlite3ThreadSafeFree(id);
2102 *pId = 0;
2103 return SQLITE_OK;
2104}
2105
2106#pragma mark Old-School .lock file based locking
2107
2108/*
2109 ** The dotlockLockingContext structure contains all dotlock (.lock) lock
2110 ** specific state
2111 */
2112typedef struct dotlockLockingContext dotlockLockingContext;
2113struct dotlockLockingContext {
2114 char *lockPath;
2115};
2116
2117
2118static int dotlockUnixCheckReservedLock(OsFile *id) {
2119 unixFile *pFile = (unixFile*)id;
2120 dotlockLockingContext *context =
2121 (dotlockLockingContext *) pFile->lockingContext;
2122
2123 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00002124 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00002125 } else {
2126 struct stat statBuf;
2127 if (lstat(context->lockPath,&statBuf) == 0)
drh3b62b2f2007-06-08 18:27:03 +00002128 /* file exists, someone else has the lock */
drhbfe66312006-10-03 17:40:40 +00002129 return 1;
2130 else
drh3b62b2f2007-06-08 18:27:03 +00002131 /* file does not exist, we could have it if we want it */
drhbfe66312006-10-03 17:40:40 +00002132 return 0;
2133 }
2134}
2135
2136static int dotlockUnixLock(OsFile *id, int locktype) {
2137 unixFile *pFile = (unixFile*)id;
2138 dotlockLockingContext *context =
2139 (dotlockLockingContext *) pFile->lockingContext;
2140
drh3b62b2f2007-06-08 18:27:03 +00002141 /* if we already have a lock, it is exclusive.
2142 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00002143 if (pFile->locktype > NO_LOCK) {
2144 pFile->locktype = locktype;
2145
2146 /* Always update the timestamp on the old file */
2147 utimes(context->lockPath,NULL);
2148 return SQLITE_OK;
2149 }
2150
drh3b62b2f2007-06-08 18:27:03 +00002151 /* check to see if lock file already exists */
drhbfe66312006-10-03 17:40:40 +00002152 struct stat statBuf;
2153 if (lstat(context->lockPath,&statBuf) == 0){
drh3b62b2f2007-06-08 18:27:03 +00002154 return SQLITE_BUSY; /* it does, busy */
drhbfe66312006-10-03 17:40:40 +00002155 }
2156
drh3b62b2f2007-06-08 18:27:03 +00002157 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00002158 int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
2159 if (fd < 0) {
drh3b62b2f2007-06-08 18:27:03 +00002160 /* failed to open/create the file, someone else may have stolen the lock */
drhbfe66312006-10-03 17:40:40 +00002161 return SQLITE_BUSY;
2162 }
2163 close(fd);
2164
drh3b62b2f2007-06-08 18:27:03 +00002165 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00002166 pFile->locktype = locktype;
2167 return SQLITE_OK;
2168}
2169
2170static int dotlockUnixUnlock(OsFile *id, int locktype) {
2171 unixFile *pFile = (unixFile*)id;
2172 dotlockLockingContext *context =
2173 (dotlockLockingContext *) pFile->lockingContext;
2174
2175 assert( locktype<=SHARED_LOCK );
2176
drh3b62b2f2007-06-08 18:27:03 +00002177 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00002178 if( pFile->locktype==locktype ){
2179 return SQLITE_OK;
2180 }
2181
drh3b62b2f2007-06-08 18:27:03 +00002182 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00002183 if (locktype==SHARED_LOCK) {
2184 pFile->locktype = locktype;
2185 return SQLITE_OK;
2186 }
2187
drh3b62b2f2007-06-08 18:27:03 +00002188 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00002189 unlink(context->lockPath);
2190 pFile->locktype = NO_LOCK;
2191 return SQLITE_OK;
2192}
2193
2194/*
2195 ** Close a file.
2196 */
2197static int dotlockUnixClose(OsFile **pId) {
2198 unixFile *id = (unixFile*)*pId;
2199
2200 if( !id ) return SQLITE_OK;
2201 dotlockUnixUnlock(*pId, NO_LOCK);
2202 /* free the dotlock locking structure */
2203 if (id->lockingContext != NULL) {
2204 if (((dotlockLockingContext *)id->lockingContext)->lockPath != NULL)
2205 sqlite3ThreadSafeFree( ( (dotlockLockingContext *)
2206 id->lockingContext)->lockPath);
2207 sqlite3ThreadSafeFree(id->lockingContext);
2208 }
2209
2210 if( id->dirfd>=0 ) close(id->dirfd);
2211 id->dirfd = -1;
2212 sqlite3OsEnterMutex();
2213
2214 close(id->h);
2215
2216 sqlite3OsLeaveMutex();
2217 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00002218 OSTRACE2("CLOSE %-3d\n", id->h);
drhbfe66312006-10-03 17:40:40 +00002219 OpenCounter(-1);
2220 sqlite3ThreadSafeFree(id);
2221 *pId = 0;
2222 return SQLITE_OK;
2223}
2224
2225
2226#pragma mark No locking
2227
2228/*
2229 ** The nolockLockingContext is void
2230 */
2231typedef void nolockLockingContext;
2232
2233static int nolockUnixCheckReservedLock(OsFile *id) {
2234 return 0;
2235}
2236
2237static int nolockUnixLock(OsFile *id, int locktype) {
2238 return SQLITE_OK;
2239}
2240
2241static int nolockUnixUnlock(OsFile *id, int locktype) {
2242 return SQLITE_OK;
2243}
2244
2245/*
2246 ** Close a file.
2247 */
2248static int nolockUnixClose(OsFile **pId) {
2249 unixFile *id = (unixFile*)*pId;
2250
2251 if( !id ) return SQLITE_OK;
2252 if( id->dirfd>=0 ) close(id->dirfd);
2253 id->dirfd = -1;
2254 sqlite3OsEnterMutex();
2255
2256 close(id->h);
2257
2258 sqlite3OsLeaveMutex();
2259 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00002260 OSTRACE2("CLOSE %-3d\n", id->h);
drhbfe66312006-10-03 17:40:40 +00002261 OpenCounter(-1);
2262 sqlite3ThreadSafeFree(id);
2263 *pId = 0;
2264 return SQLITE_OK;
2265}
2266
2267#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2268
danielk1977e3026632004-06-22 11:29:02 +00002269/*
drh0ccebe72005-06-07 22:22:50 +00002270** Turn a relative pathname into a full pathname. Return a pointer
2271** to the full pathname stored in space obtained from sqliteMalloc().
2272** The calling function is responsible for freeing this space once it
2273** is no longer needed.
2274*/
drh66560ad2006-01-06 14:32:19 +00002275char *sqlite3UnixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00002276 char *zFull = 0;
2277 if( zRelative[0]=='/' ){
2278 sqlite3SetString(&zFull, zRelative, (char*)0);
2279 }else{
drh79158e12005-09-06 21:40:45 +00002280 char *zBuf = sqliteMalloc(5000);
2281 if( zBuf==0 ){
2282 return 0;
2283 }
drh0ccebe72005-06-07 22:22:50 +00002284 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00002285 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00002286 (char*)0);
drh79158e12005-09-06 21:40:45 +00002287 sqliteFree(zBuf);
drh0ccebe72005-06-07 22:22:50 +00002288 }
drh4eb9a972006-02-13 18:42:21 +00002289
2290#if 0
drh89ea9312006-02-13 17:03:47 +00002291 /*
2292 ** Remove "/./" path elements and convert "/A/./" path elements
2293 ** to just "/".
2294 */
2295 if( zFull ){
drh4eb9a972006-02-13 18:42:21 +00002296 int i, j;
drh89ea9312006-02-13 17:03:47 +00002297 for(i=j=0; zFull[i]; i++){
2298 if( zFull[i]=='/' ){
2299 if( zFull[i+1]=='/' ) continue;
2300 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
2301 i += 1;
2302 continue;
2303 }
2304 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
2305 while( j>0 && zFull[j-1]!='/' ){ j--; }
2306 i += 3;
2307 continue;
2308 }
2309 }
2310 zFull[j++] = zFull[i];
2311 }
2312 zFull[j] = 0;
2313 }
drh4eb9a972006-02-13 18:42:21 +00002314#endif
2315
drh0ccebe72005-06-07 22:22:50 +00002316 return zFull;
2317}
2318
drh18839212005-11-26 03:43:23 +00002319/*
drh9cbe6352005-11-29 03:13:21 +00002320** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00002321*/
drh9cbe6352005-11-29 03:13:21 +00002322static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00002323 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00002324}
2325
2326/*
2327** Return the underlying file handle for an OsFile
2328*/
2329static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00002330 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00002331}
2332
2333/*
2334** Return an integer that indices the type of lock currently held
2335** by this handle. (Used for testing and analysis only.)
2336*/
2337static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00002338 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00002339}
drh0ccebe72005-06-07 22:22:50 +00002340
drh9c06c952005-11-26 00:25:00 +00002341/*
danielk1977a3d4c882007-03-23 10:08:38 +00002342** Return the sector size in bytes of the underlying block device for
2343** the specified file. This is almost always 512 bytes, but may be
2344** larger for some devices.
2345**
2346** SQLite code assumes this function cannot fail. It also assumes that
2347** if two files are created in the same file-system directory (i.e.
2348** a database and it's journal file) that the sector size will be the
2349** same for both.
2350*/
2351static int unixSectorSize(OsFile *id){
drh3ceeb752007-03-29 18:19:52 +00002352 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00002353}
2354
2355/*
drh054889e2005-11-30 03:20:31 +00002356** This vector defines all the methods that can operate on an OsFile
2357** for unix.
drh9c06c952005-11-26 00:25:00 +00002358*/
drh054889e2005-11-30 03:20:31 +00002359static const IoMethod sqlite3UnixIoMethod = {
drh9c06c952005-11-26 00:25:00 +00002360 unixClose,
drh054889e2005-11-30 03:20:31 +00002361 unixOpenDirectory,
drh9c06c952005-11-26 00:25:00 +00002362 unixRead,
2363 unixWrite,
2364 unixSeek,
drh9c06c952005-11-26 00:25:00 +00002365 unixTruncate,
drh054889e2005-11-30 03:20:31 +00002366 unixSync,
drh9cbe6352005-11-29 03:13:21 +00002367 unixSetFullSync,
2368 unixFileHandle,
drh054889e2005-11-30 03:20:31 +00002369 unixFileSize,
2370 unixLock,
2371 unixUnlock,
drh9cbe6352005-11-29 03:13:21 +00002372 unixLockState,
drh054889e2005-11-30 03:20:31 +00002373 unixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002374 unixSectorSize,
drh9c06c952005-11-26 00:25:00 +00002375};
2376
drhbfe66312006-10-03 17:40:40 +00002377#ifdef SQLITE_ENABLE_LOCKING_STYLE
drh054889e2005-11-30 03:20:31 +00002378/*
drhbfe66312006-10-03 17:40:40 +00002379 ** This vector defines all the methods that can operate on an OsFile
2380 ** for unix with AFP style file locking.
2381 */
2382static const IoMethod sqlite3AFPLockingUnixIoMethod = {
2383 afpUnixClose,
2384 unixOpenDirectory,
2385 unixRead,
2386 unixWrite,
2387 unixSeek,
2388 unixTruncate,
2389 unixSync,
2390 unixSetFullSync,
2391 unixFileHandle,
2392 unixFileSize,
2393 afpUnixLock,
2394 afpUnixUnlock,
2395 unixLockState,
2396 afpUnixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002397 unixSectorSize,
drhbfe66312006-10-03 17:40:40 +00002398};
2399
2400/*
2401 ** This vector defines all the methods that can operate on an OsFile
2402 ** for unix with flock() style file locking.
2403 */
2404static const IoMethod sqlite3FlockLockingUnixIoMethod = {
2405 flockUnixClose,
2406 unixOpenDirectory,
2407 unixRead,
2408 unixWrite,
2409 unixSeek,
2410 unixTruncate,
2411 unixSync,
2412 unixSetFullSync,
2413 unixFileHandle,
2414 unixFileSize,
2415 flockUnixLock,
2416 flockUnixUnlock,
2417 unixLockState,
2418 flockUnixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002419 unixSectorSize,
drhbfe66312006-10-03 17:40:40 +00002420};
2421
2422/*
2423 ** This vector defines all the methods that can operate on an OsFile
2424 ** for unix with dotlock style file locking.
2425 */
2426static const IoMethod sqlite3DotlockLockingUnixIoMethod = {
2427 dotlockUnixClose,
2428 unixOpenDirectory,
2429 unixRead,
2430 unixWrite,
2431 unixSeek,
2432 unixTruncate,
2433 unixSync,
2434 unixSetFullSync,
2435 unixFileHandle,
2436 unixFileSize,
2437 dotlockUnixLock,
2438 dotlockUnixUnlock,
2439 unixLockState,
2440 dotlockUnixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002441 unixSectorSize,
drhbfe66312006-10-03 17:40:40 +00002442};
2443
2444/*
2445 ** This vector defines all the methods that can operate on an OsFile
2446 ** for unix with dotlock style file locking.
2447 */
2448static const IoMethod sqlite3NolockLockingUnixIoMethod = {
2449 nolockUnixClose,
2450 unixOpenDirectory,
2451 unixRead,
2452 unixWrite,
2453 unixSeek,
2454 unixTruncate,
2455 unixSync,
2456 unixSetFullSync,
2457 unixFileHandle,
2458 unixFileSize,
2459 nolockUnixLock,
2460 nolockUnixUnlock,
2461 unixLockState,
2462 nolockUnixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002463 unixSectorSize,
drhbfe66312006-10-03 17:40:40 +00002464};
2465
2466#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2467
2468/*
2469** Allocate memory for a new unixFile and initialize that unixFile.
2470** Write a pointer to the new unixFile into *pId.
2471** If we run out of memory, close the file and return an error.
drh054889e2005-11-30 03:20:31 +00002472*/
drhbfe66312006-10-03 17:40:40 +00002473#ifdef SQLITE_ENABLE_LOCKING_STYLE
2474/*
2475 ** When locking extensions are enabled, the filepath and locking style
2476 ** are needed to determine the unixFile pMethod to use for locking operations.
2477 ** The locking-style specific lockingContext data structure is created
2478 ** and assigned here also.
2479 */
2480static int allocateUnixFile(
2481 int h, /* Open file descriptor of file being opened */
2482 OsFile **pId, /* Write completed initialization here */
2483 const char *zFilename, /* Name of the file being opened */
2484 int delFlag /* Delete-on-or-before-close flag */
2485){
aswift108bc322006-10-11 17:19:46 +00002486 sqlite3LockingStyle lockingStyle;
drh054889e2005-11-30 03:20:31 +00002487 unixFile *pNew;
drhbfe66312006-10-03 17:40:40 +00002488 unixFile f;
2489 int rc;
2490
drh61fc5952007-04-01 23:49:51 +00002491 memset(&f, 0, sizeof(f));
aswift448aa6f2006-11-11 01:31:58 +00002492 lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
drhbfe66312006-10-03 17:40:40 +00002493 if ( lockingStyle == posixLockingStyle ) {
2494 sqlite3OsEnterMutex();
2495 rc = findLockInfo(h, &f.pLock, &f.pOpen);
2496 sqlite3OsLeaveMutex();
2497 if( rc ){
2498 close(h);
2499 unlink(zFilename);
2500 return SQLITE_NOMEM;
2501 }
2502 } else {
drh3b62b2f2007-06-08 18:27:03 +00002503 /* pLock and pOpen are only used for posix advisory locking */
drhbfe66312006-10-03 17:40:40 +00002504 f.pLock = NULL;
2505 f.pOpen = NULL;
2506 }
2507 if( delFlag ){
2508 unlink(zFilename);
2509 }
2510 f.dirfd = -1;
drhbfe66312006-10-03 17:40:40 +00002511 f.h = h;
2512 SET_THREADID(&f);
danielk1977750b03e2006-02-14 10:48:39 +00002513 pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
drh054889e2005-11-30 03:20:31 +00002514 if( pNew==0 ){
drhbfe66312006-10-03 17:40:40 +00002515 close(h);
drh029b44b2006-01-15 00:13:15 +00002516 sqlite3OsEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002517 releaseLockInfo(f.pLock);
2518 releaseOpenCnt(f.pOpen);
drh029b44b2006-01-15 00:13:15 +00002519 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00002520 *pId = 0;
2521 return SQLITE_NOMEM;
2522 }else{
drhbfe66312006-10-03 17:40:40 +00002523 *pNew = f;
aswift108bc322006-10-11 17:19:46 +00002524 switch(lockingStyle) {
drh5bb3eb92007-05-04 13:15:55 +00002525 case afpLockingStyle: {
drhbfe66312006-10-03 17:40:40 +00002526 /* afp locking uses the file path so it needs to be included in
2527 ** the afpLockingContext */
drh5bb3eb92007-05-04 13:15:55 +00002528 int nFilename;
drhbfe66312006-10-03 17:40:40 +00002529 pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
2530 pNew->lockingContext =
2531 sqlite3ThreadSafeMalloc(sizeof(afpLockingContext));
drh5bb3eb92007-05-04 13:15:55 +00002532 nFilename = strlen(zFilename)+1;
drhbfe66312006-10-03 17:40:40 +00002533 ((afpLockingContext *)pNew->lockingContext)->filePath =
drh5bb3eb92007-05-04 13:15:55 +00002534 sqlite3ThreadSafeMalloc(nFilename);
2535 memcpy(((afpLockingContext *)pNew->lockingContext)->filePath,
2536 zFilename, nFilename);
drhbfe66312006-10-03 17:40:40 +00002537 srandomdev();
2538 break;
drh5bb3eb92007-05-04 13:15:55 +00002539 }
drhbfe66312006-10-03 17:40:40 +00002540 case flockLockingStyle:
2541 /* flock locking doesn't need additional lockingContext information */
2542 pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
2543 break;
drh5bb3eb92007-05-04 13:15:55 +00002544 case dotlockLockingStyle: {
drhbfe66312006-10-03 17:40:40 +00002545 /* dotlock locking uses the file path so it needs to be included in
2546 ** the dotlockLockingContext */
drh5bb3eb92007-05-04 13:15:55 +00002547 int nFilename;
drhbfe66312006-10-03 17:40:40 +00002548 pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
2549 pNew->lockingContext = sqlite3ThreadSafeMalloc(
2550 sizeof(dotlockLockingContext));
drh5bb3eb92007-05-04 13:15:55 +00002551 nFilename = strlen(zFilename) + 6;
drhbfe66312006-10-03 17:40:40 +00002552 ((dotlockLockingContext *)pNew->lockingContext)->lockPath =
drh5bb3eb92007-05-04 13:15:55 +00002553 sqlite3ThreadSafeMalloc( nFilename );
2554 sqlite3_snprintf(nFilename,
2555 ((dotlockLockingContext *)pNew->lockingContext)->lockPath,
drhbfe66312006-10-03 17:40:40 +00002556 "%s.lock", zFilename);
2557 break;
drh5bb3eb92007-05-04 13:15:55 +00002558 }
drhbfe66312006-10-03 17:40:40 +00002559 case posixLockingStyle:
2560 /* posix locking doesn't need additional lockingContext information */
2561 pNew->pMethod = &sqlite3UnixIoMethod;
2562 break;
2563 case noLockingStyle:
2564 case unsupportedLockingStyle:
2565 default:
2566 pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
2567 }
2568 *pId = (OsFile*)pNew;
2569 OpenCounter(+1);
2570 return SQLITE_OK;
2571 }
2572}
2573#else /* SQLITE_ENABLE_LOCKING_STYLE */
2574static int allocateUnixFile(
2575 int h, /* Open file descriptor on file being opened */
2576 OsFile **pId, /* Write the resul unixFile structure here */
2577 const char *zFilename, /* Name of the file being opened */
2578 int delFlag /* If true, delete the file on or before closing */
2579){
2580 unixFile *pNew;
2581 unixFile f;
2582 int rc;
2583
drhe78669b2007-06-29 12:04:26 +00002584#ifdef FD_CLOEXEC
2585 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
2586#endif
drh61fc5952007-04-01 23:49:51 +00002587 memset(&f, 0, sizeof(f));
drhbfe66312006-10-03 17:40:40 +00002588 sqlite3OsEnterMutex();
2589 rc = findLockInfo(h, &f.pLock, &f.pOpen);
2590 sqlite3OsLeaveMutex();
2591 if( delFlag ){
2592 unlink(zFilename);
2593 }
2594 if( rc ){
2595 close(h);
2596 return SQLITE_NOMEM;
2597 }
drh4f0c5872007-03-26 22:05:01 +00002598 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
drhbfe66312006-10-03 17:40:40 +00002599 f.dirfd = -1;
drhbfe66312006-10-03 17:40:40 +00002600 f.h = h;
2601 SET_THREADID(&f);
2602 pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
2603 if( pNew==0 ){
2604 close(h);
2605 sqlite3OsEnterMutex();
2606 releaseLockInfo(f.pLock);
2607 releaseOpenCnt(f.pOpen);
2608 sqlite3OsLeaveMutex();
2609 *pId = 0;
2610 return SQLITE_NOMEM;
2611 }else{
2612 *pNew = f;
drh054889e2005-11-30 03:20:31 +00002613 pNew->pMethod = &sqlite3UnixIoMethod;
2614 *pId = (OsFile*)pNew;
2615 OpenCounter(+1);
2616 return SQLITE_OK;
2617 }
2618}
drhbfe66312006-10-03 17:40:40 +00002619#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9c06c952005-11-26 00:25:00 +00002620
drh0ccebe72005-06-07 22:22:50 +00002621#endif /* SQLITE_OMIT_DISKIO */
2622/***************************************************************************
2623** Everything above deals with file I/O. Everything that follows deals
2624** with other miscellanous aspects of the operating system interface
2625****************************************************************************/
2626
2627
drh761df872006-12-21 01:29:22 +00002628#ifndef SQLITE_OMIT_LOAD_EXTENSION
2629/*
2630** Interfaces for opening a shared library, finding entry points
2631** within the shared library, and closing the shared library.
2632*/
2633#include <dlfcn.h>
2634void *sqlite3UnixDlopen(const char *zFilename){
2635 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
2636}
2637void *sqlite3UnixDlsym(void *pHandle, const char *zSymbol){
2638 return dlsym(pHandle, zSymbol);
2639}
2640int sqlite3UnixDlclose(void *pHandle){
2641 return dlclose(pHandle);
2642}
2643#endif /* SQLITE_OMIT_LOAD_EXTENSION */
2644
drh0ccebe72005-06-07 22:22:50 +00002645/*
drhbbd42a62004-05-22 17:41:58 +00002646** Get information to seed the random number generator. The seed
2647** is written into the buffer zBuf[256]. The calling function must
2648** supply a sufficiently large buffer.
2649*/
drh66560ad2006-01-06 14:32:19 +00002650int sqlite3UnixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00002651 /* We have to initialize zBuf to prevent valgrind from reporting
2652 ** errors. The reports issued by valgrind are incorrect - we would
2653 ** prefer that the randomness be increased by making use of the
2654 ** uninitialized space in zBuf - but valgrind errors tend to worry
2655 ** some users. Rather than argue, it seems easier just to initialize
2656 ** the whole array and silence valgrind, even if that means less randomness
2657 ** in the random seed.
2658 **
2659 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00002660 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00002661 ** tests repeatable.
2662 */
2663 memset(zBuf, 0, 256);
2664#if !defined(SQLITE_TEST)
2665 {
drh842b8642005-01-21 17:53:17 +00002666 int pid, fd;
2667 fd = open("/dev/urandom", O_RDONLY);
2668 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00002669 time_t t;
2670 time(&t);
2671 memcpy(zBuf, &t, sizeof(t));
drh842b8642005-01-21 17:53:17 +00002672 pid = getpid();
2673 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
2674 }else{
2675 read(fd, zBuf, 256);
2676 close(fd);
2677 }
drhbbd42a62004-05-22 17:41:58 +00002678 }
2679#endif
2680 return SQLITE_OK;
2681}
2682
2683/*
2684** Sleep for a little while. Return the amount of time slept.
drhf1a221e2006-01-15 17:27:17 +00002685** The argument is the number of milliseconds we want to sleep.
drhbbd42a62004-05-22 17:41:58 +00002686*/
drh66560ad2006-01-06 14:32:19 +00002687int sqlite3UnixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00002688#if defined(HAVE_USLEEP) && HAVE_USLEEP
2689 usleep(ms*1000);
2690 return ms;
2691#else
2692 sleep((ms+999)/1000);
2693 return 1000*((ms+999)/1000);
2694#endif
2695}
2696
2697/*
drh5c111232006-02-10 04:33:12 +00002698** Static variables used for thread synchronization.
2699**
2700** inMutex the nesting depth of the recursive mutex. The thread
2701** holding mutexMain can read this variable at any time.
2702** But is must hold mutexAux to change this variable. Other
drh6a3d6702006-02-10 13:11:32 +00002703** threads must hold mutexAux to read the variable and can
2704** never write.
drh5c111232006-02-10 04:33:12 +00002705**
2706** mutexOwner The thread id of the thread holding mutexMain. Same
2707** access rules as for inMutex.
2708**
drh6a3d6702006-02-10 13:11:32 +00002709** mutexOwnerValid True if the value in mutexOwner is valid. The same
2710** access rules apply as for inMutex.
drh5c111232006-02-10 04:33:12 +00002711**
2712** mutexMain The main mutex. Hold this mutex in order to get exclusive
2713** access to SQLite data structures.
2714**
2715** mutexAux An auxiliary mutex needed to access variables defined above.
2716**
drh6a3d6702006-02-10 13:11:32 +00002717** Mutexes are always acquired in this order: mutexMain mutexAux. It
2718** is not necessary to acquire mutexMain in order to get mutexAux - just
2719** do not attempt to acquire them in the reverse order: mutexAux mutexMain.
2720** Either get the mutexes with mutexMain first or get mutexAux only.
2721**
2722** When running on a platform where the three variables inMutex, mutexOwner,
2723** and mutexOwnerValid can be set atomically, the mutexAux is not required.
2724** On many systems, all three are 32-bit integers and writing to a 32-bit
2725** integer is atomic. I think. But there are no guarantees. So it seems
2726** safer to protect them using mutexAux.
drhbbd42a62004-05-22 17:41:58 +00002727*/
2728static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00002729#ifdef SQLITE_UNIX_THREADS
drh6a3d6702006-02-10 13:11:32 +00002730static pthread_t mutexOwner; /* Thread holding mutexMain */
drh5c111232006-02-10 04:33:12 +00002731static int mutexOwnerValid = 0; /* True if mutexOwner is valid */
2732static pthread_mutex_t mutexMain = PTHREAD_MUTEX_INITIALIZER; /* The mutex */
2733static pthread_mutex_t mutexAux = PTHREAD_MUTEX_INITIALIZER; /* Aux mutex */
drh79069752004-05-22 21:30:40 +00002734#endif
drhbbd42a62004-05-22 17:41:58 +00002735
2736/*
2737** The following pair of routine implement mutual exclusion for
2738** multi-threaded processes. Only a single thread is allowed to
2739** executed code that is surrounded by EnterMutex() and LeaveMutex().
2740**
2741** SQLite uses only a single Mutex. There is not much critical
2742** code and what little there is executes quickly and without blocking.
drhf1a221e2006-01-15 17:27:17 +00002743**
drh757b04e2006-01-18 17:25:45 +00002744** As of version 3.3.2, this mutex must be recursive.
drhbbd42a62004-05-22 17:41:58 +00002745*/
drh66560ad2006-01-06 14:32:19 +00002746void sqlite3UnixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00002747#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00002748 pthread_mutex_lock(&mutexAux);
2749 if( !mutexOwnerValid || !pthread_equal(mutexOwner, pthread_self()) ){
2750 pthread_mutex_unlock(&mutexAux);
2751 pthread_mutex_lock(&mutexMain);
2752 assert( inMutex==0 );
2753 assert( !mutexOwnerValid );
2754 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00002755 mutexOwner = pthread_self();
drh5c111232006-02-10 04:33:12 +00002756 mutexOwnerValid = 1;
drha3fad6f2006-01-18 14:06:37 +00002757 }
drha3fad6f2006-01-18 14:06:37 +00002758 inMutex++;
drh5c111232006-02-10 04:33:12 +00002759 pthread_mutex_unlock(&mutexAux);
2760#else
drhe9565a62006-02-11 02:03:52 +00002761 inMutex++;
drh5c111232006-02-10 04:33:12 +00002762#endif
drhbbd42a62004-05-22 17:41:58 +00002763}
drh66560ad2006-01-06 14:32:19 +00002764void sqlite3UnixLeaveMutex(){
drha3fad6f2006-01-18 14:06:37 +00002765 assert( inMutex>0 );
drhbbd42a62004-05-22 17:41:58 +00002766#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00002767 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00002768 inMutex--;
drh5c111232006-02-10 04:33:12 +00002769 assert( pthread_equal(mutexOwner, pthread_self()) );
drha3fad6f2006-01-18 14:06:37 +00002770 if( inMutex==0 ){
drh5c111232006-02-10 04:33:12 +00002771 assert( mutexOwnerValid );
2772 mutexOwnerValid = 0;
2773 pthread_mutex_unlock(&mutexMain);
drha3fad6f2006-01-18 14:06:37 +00002774 }
drh5c111232006-02-10 04:33:12 +00002775 pthread_mutex_unlock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00002776#else
2777 inMutex--;
drhbbd42a62004-05-22 17:41:58 +00002778#endif
2779}
2780
2781/*
drh757b04e2006-01-18 17:25:45 +00002782** Return TRUE if the mutex is currently held.
2783**
drh5c111232006-02-10 04:33:12 +00002784** If the thisThrd parameter is true, return true only if the
drh757b04e2006-01-18 17:25:45 +00002785** calling thread holds the mutex. If the parameter is false, return
2786** true if any thread holds the mutex.
drh88f474a2006-01-02 20:00:12 +00002787*/
drh5c111232006-02-10 04:33:12 +00002788int sqlite3UnixInMutex(int thisThrd){
drha3fad6f2006-01-18 14:06:37 +00002789#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00002790 int rc;
2791 pthread_mutex_lock(&mutexAux);
2792 rc = inMutex>0 && (thisThrd==0 || pthread_equal(mutexOwner,pthread_self()));
2793 pthread_mutex_unlock(&mutexAux);
2794 return rc;
drha3fad6f2006-01-18 14:06:37 +00002795#else
drh757b04e2006-01-18 17:25:45 +00002796 return inMutex>0;
drha3fad6f2006-01-18 14:06:37 +00002797#endif
drh88f474a2006-01-02 20:00:12 +00002798}
2799
2800/*
drhb4bc7052006-01-11 23:40:33 +00002801** Remember the number of thread-specific-data blocks allocated.
2802** Use this to verify that we are not leaking thread-specific-data.
2803** Ticket #1601
2804*/
2805#ifdef SQLITE_TEST
2806int sqlite3_tsd_count = 0;
2807# ifdef SQLITE_UNIX_THREADS
2808 static pthread_mutex_t tsd_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
2809# define TSD_COUNTER(N) \
2810 pthread_mutex_lock(&tsd_counter_mutex); \
2811 sqlite3_tsd_count += N; \
2812 pthread_mutex_unlock(&tsd_counter_mutex);
2813# else
2814# define TSD_COUNTER(N) sqlite3_tsd_count += N
2815# endif
2816#else
2817# define TSD_COUNTER(N) /* no-op */
2818#endif
2819
drhb4bc7052006-01-11 23:40:33 +00002820/*
drhf1a221e2006-01-15 17:27:17 +00002821** If called with allocateFlag>0, then return a pointer to thread
drh6f7adc82006-01-11 21:41:20 +00002822** specific data for the current thread. Allocate and zero the
drhf1a221e2006-01-15 17:27:17 +00002823** thread-specific data if it does not already exist.
danielk197713a68c32005-12-15 10:11:30 +00002824**
drh6f7adc82006-01-11 21:41:20 +00002825** If called with allocateFlag==0, then check the current thread
drh70ff98a2006-01-12 01:25:18 +00002826** specific data. Return it if it exists. If it does not exist,
2827** then return NULL.
2828**
2829** If called with allocateFlag<0, check to see if the thread specific
2830** data is allocated and is all zero. If it is then deallocate it.
drh6f7adc82006-01-11 21:41:20 +00002831** Return a pointer to the thread specific data or NULL if it is
drh70ff98a2006-01-12 01:25:18 +00002832** unallocated or gets deallocated.
danielk197713a68c32005-12-15 10:11:30 +00002833*/
drh6f7adc82006-01-11 21:41:20 +00002834ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
danielk19774d5238f2006-01-27 06:32:00 +00002835 static const ThreadData zeroData = {0}; /* Initializer to silence warnings
2836 ** from broken compilers */
danielk197713a68c32005-12-15 10:11:30 +00002837#ifdef SQLITE_UNIX_THREADS
2838 static pthread_key_t key;
2839 static int keyInit = 0;
drh6f7adc82006-01-11 21:41:20 +00002840 ThreadData *pTsd;
danielk197713a68c32005-12-15 10:11:30 +00002841
2842 if( !keyInit ){
drh66560ad2006-01-06 14:32:19 +00002843 sqlite3OsEnterMutex();
danielk197713a68c32005-12-15 10:11:30 +00002844 if( !keyInit ){
2845 int rc;
drh6f7adc82006-01-11 21:41:20 +00002846 rc = pthread_key_create(&key, 0);
danielk197713a68c32005-12-15 10:11:30 +00002847 if( rc ){
drh8c0ca7d2006-01-07 04:06:54 +00002848 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00002849 return 0;
2850 }
2851 keyInit = 1;
2852 }
drh66560ad2006-01-06 14:32:19 +00002853 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00002854 }
2855
drh3fbb0b12006-01-06 00:36:00 +00002856 pTsd = pthread_getspecific(key);
drh70ff98a2006-01-12 01:25:18 +00002857 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00002858 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00002859 if( !sqlite3TestMallocFail() ){
2860 pTsd = sqlite3OsMalloc(sizeof(zeroData));
2861 }
2862#ifdef SQLITE_MEMDEBUG
2863 sqlite3_isFail = 0;
2864#endif
drh6f7adc82006-01-11 21:41:20 +00002865 if( pTsd ){
2866 *pTsd = zeroData;
2867 pthread_setspecific(key, pTsd);
drhb4bc7052006-01-11 23:40:33 +00002868 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00002869 }
danielk197713a68c32005-12-15 10:11:30 +00002870 }
drh70ff98a2006-01-12 01:25:18 +00002871 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00002872 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00002873 sqlite3OsFree(pTsd);
2874 pthread_setspecific(key, 0);
drhb4bc7052006-01-11 23:40:33 +00002875 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00002876 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00002877 }
2878 return pTsd;
2879#else
drh6f7adc82006-01-11 21:41:20 +00002880 static ThreadData *pTsd = 0;
drh70ff98a2006-01-12 01:25:18 +00002881 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00002882 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00002883 if( !sqlite3TestMallocFail() ){
2884 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
2885 }
2886#ifdef SQLITE_MEMDEBUG
2887 sqlite3_isFail = 0;
2888#endif
drh6f7adc82006-01-11 21:41:20 +00002889 if( pTsd ){
2890 *pTsd = zeroData;
drhb4bc7052006-01-11 23:40:33 +00002891 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00002892 }
drh3fbb0b12006-01-06 00:36:00 +00002893 }
drh70ff98a2006-01-12 01:25:18 +00002894 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00002895 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00002896 sqlite3OsFree(pTsd);
drhb4bc7052006-01-11 23:40:33 +00002897 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00002898 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00002899 }
drh3fbb0b12006-01-06 00:36:00 +00002900 return pTsd;
danielk197713a68c32005-12-15 10:11:30 +00002901#endif
2902}
2903
2904/*
drhbbd42a62004-05-22 17:41:58 +00002905** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00002906** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00002907*/
2908#ifdef SQLITE_TEST
2909int sqlite3_current_time = 0;
2910#endif
2911
2912/*
2913** Find the current time (in Universal Coordinated Time). Write the
2914** current time and date as a Julian Day number into *prNow and
2915** return 0. Return 1 if the time and date cannot be found.
2916*/
drh66560ad2006-01-06 14:32:19 +00002917int sqlite3UnixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00002918#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00002919 time_t t;
2920 time(&t);
2921 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00002922#else
2923 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00002924 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00002925 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
2926#endif
drhbbd42a62004-05-22 17:41:58 +00002927#ifdef SQLITE_TEST
2928 if( sqlite3_current_time ){
2929 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
2930 }
2931#endif
2932 return 0;
2933}
2934
drhbbd42a62004-05-22 17:41:58 +00002935#endif /* OS_UNIX */