blob: dfbb9338cf0ada8ed5a5f89cc43efb7723785d1f [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*/
62#if defined(THREADSAFE) && THREADSAFE
63# include <pthread.h>
64# define SQLITE_UNIX_THREADS 1
65#endif
66
67/*
68** Default permissions when creating a new file
69*/
70#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
71# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
72#endif
73
74
75
76/*
drh054889e2005-11-30 03:20:31 +000077** The unixFile structure is subclass of OsFile specific for the unix
78** protability layer.
drh9cbe6352005-11-29 03:13:21 +000079*/
drh054889e2005-11-30 03:20:31 +000080typedef struct unixFile unixFile;
81struct unixFile {
82 IoMethod const *pMethod; /* Always the first entry */
drh9cbe6352005-11-29 03:13:21 +000083 struct openCnt *pOpen; /* Info about all open fd's on this inode */
84 struct lockInfo *pLock; /* Info about locks on this inode */
drhbfe66312006-10-03 17:40:40 +000085#ifdef SQLITE_ENABLE_LOCKING_STYLE
86 void *lockingContext; /* Locking style specific state */
87#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000088 int h; /* The file descriptor */
89 unsigned char locktype; /* The type of lock held on this fd */
90 unsigned char isOpen; /* True if needs to be closed */
91 unsigned char fullSync; /* Use F_FULLSYNC if available */
92 int dirfd; /* File descriptor for the directory */
drhb912b282006-03-23 22:42:20 +000093 i64 offset; /* Seek offset */
drh9cbe6352005-11-29 03:13:21 +000094#ifdef SQLITE_UNIX_THREADS
drhf1a221e2006-01-15 17:27:17 +000095 pthread_t tid; /* The thread that "owns" this OsFile */
drh9cbe6352005-11-29 03:13:21 +000096#endif
97};
98
drh66560ad2006-01-06 14:32:19 +000099/*
100** Provide the ability to override some OS-layer functions during
101** testing. This is used to simulate OS crashes to verify that
102** commits are atomic even in the event of an OS crash.
103*/
104#ifdef SQLITE_CRASH_TEST
105 extern int sqlite3CrashTestEnable;
106 extern int sqlite3CrashOpenReadWrite(const char*, OsFile**, int*);
107 extern int sqlite3CrashOpenExclusive(const char*, OsFile**, int);
108 extern int sqlite3CrashOpenReadOnly(const char*, OsFile**, int);
109# define CRASH_TEST_OVERRIDE(X,A,B,C) \
110 if(sqlite3CrashTestEnable){ return X(A,B,C); }
111#else
112# define CRASH_TEST_OVERRIDE(X,A,B,C) /* no-op */
113#endif
114
drh0ccebe72005-06-07 22:22:50 +0000115
116/*
drh198bf392006-01-06 21:52:49 +0000117** Include code that is common to all os_*.c files
118*/
119#include "os_common.h"
120
121/*
drh0ccebe72005-06-07 22:22:50 +0000122** Do not include any of the File I/O interface procedures if the
drhf1a221e2006-01-15 17:27:17 +0000123** SQLITE_OMIT_DISKIO macro is defined (indicating that the database
drh0ccebe72005-06-07 22:22:50 +0000124** will be in-memory only)
125*/
126#ifndef SQLITE_OMIT_DISKIO
127
128
129/*
130** Define various macros that are missing from some systems.
131*/
drhbbd42a62004-05-22 17:41:58 +0000132#ifndef O_LARGEFILE
133# define O_LARGEFILE 0
134#endif
135#ifdef SQLITE_DISABLE_LFS
136# undef O_LARGEFILE
137# define O_LARGEFILE 0
138#endif
139#ifndef O_NOFOLLOW
140# define O_NOFOLLOW 0
141#endif
142#ifndef O_BINARY
143# define O_BINARY 0
144#endif
145
146/*
147** The DJGPP compiler environment looks mostly like Unix, but it
148** lacks the fcntl() system call. So redefine fcntl() to be something
149** that always succeeds. This means that locking does not occur under
danielk197726c5d792005-11-25 09:01:23 +0000150** DJGPP. But it's DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000151*/
152#ifdef __DJGPP__
153# define fcntl(A,B,C) 0
154#endif
155
156/*
drh2b4b5962005-06-15 17:47:55 +0000157** The threadid macro resolves to the thread-id or to 0. Used for
158** testing and debugging only.
159*/
160#ifdef SQLITE_UNIX_THREADS
161#define threadid pthread_self()
162#else
163#define threadid 0
164#endif
165
166/*
167** Set or check the OsFile.tid field. This field is set when an OsFile
168** is first opened. All subsequent uses of the OsFile verify that the
169** same thread is operating on the OsFile. Some operating systems do
170** not allow locks to be overridden by other threads and that restriction
171** means that sqlite3* database handles cannot be moved from one thread
172** to another. This logic makes sure a user does not try to do that
173** by mistake.
drhf1a221e2006-01-15 17:27:17 +0000174**
175** Version 3.3.1 (2006-01-15): OsFiles can be moved from one thread to
176** another as long as we are running on a system that supports threads
177** overriding each others locks (which now the most common behavior)
178** or if no locks are held. But the OsFile.pLock field needs to be
179** recomputed because its key includes the thread-id. See the
180** transferOwnership() function below for additional information
drh2b4b5962005-06-15 17:47:55 +0000181*/
drh029b44b2006-01-15 00:13:15 +0000182#if defined(SQLITE_UNIX_THREADS)
drh9cbe6352005-11-29 03:13:21 +0000183# define SET_THREADID(X) (X)->tid = pthread_self()
drh029b44b2006-01-15 00:13:15 +0000184# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
185 !pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000186#else
187# define SET_THREADID(X)
188# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000189#endif
190
drhbbd42a62004-05-22 17:41:58 +0000191/*
192** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
193** section 6.5.2.2 lines 483 through 490 specify that when a process
194** sets or clears a lock, that operation overrides any prior locks set
195** by the same process. It does not explicitly say so, but this implies
196** that it overrides locks set by the same process using a different
197** file descriptor. Consider this test case:
198**
199** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
200** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
201**
202** Suppose ./file1 and ./file2 are really the same file (because
203** one is a hard or symbolic link to the other) then if you set
204** an exclusive lock on fd1, then try to get an exclusive lock
205** on fd2, it works. I would have expected the second lock to
206** fail since there was already a lock on the file due to fd1.
207** But not so. Since both locks came from the same process, the
208** second overrides the first, even though they were on different
209** file descriptors opened on different file names.
210**
211** Bummer. If you ask me, this is broken. Badly broken. It means
212** that we cannot use POSIX locks to synchronize file access among
213** competing threads of the same process. POSIX locks will work fine
214** to synchronize access for threads in separate processes, but not
215** threads within the same process.
216**
217** To work around the problem, SQLite has to manage file locks internally
218** on its own. Whenever a new database is opened, we have to find the
219** specific inode of the database file (the inode is determined by the
220** st_dev and st_ino fields of the stat structure that fstat() fills in)
221** and check for locks already existing on that inode. When locks are
222** created or removed, we have to look at our own internal record of the
223** locks to see if another thread has previously set a lock on that same
224** inode.
225**
226** The OsFile structure for POSIX is no longer just an integer file
227** descriptor. It is now a structure that holds the integer file
228** descriptor and a pointer to a structure that describes the internal
229** locks on the corresponding inode. There is one locking structure
230** per inode, so if the same inode is opened twice, both OsFile structures
231** point to the same locking structure. The locking structure keeps
232** a reference count (so we will know when to delete it) and a "cnt"
233** field that tells us its internal lock status. cnt==0 means the
234** file is unlocked. cnt==-1 means the file has an exclusive lock.
235** cnt>0 means there are cnt shared locks on the file.
236**
237** Any attempt to lock or unlock a file first checks the locking
238** structure. The fcntl() system call is only invoked to set a
239** POSIX lock if the internal lock structure transitions between
240** a locked and an unlocked state.
241**
242** 2004-Jan-11:
243** More recent discoveries about POSIX advisory locks. (The more
244** I discover, the more I realize the a POSIX advisory locks are
245** an abomination.)
246**
247** If you close a file descriptor that points to a file that has locks,
248** all locks on that file that are owned by the current process are
249** released. To work around this problem, each OsFile structure contains
250** a pointer to an openCnt structure. There is one openCnt structure
251** per open inode, which means that multiple OsFiles can point to a single
252** openCnt. When an attempt is made to close an OsFile, if there are
253** other OsFiles open on the same inode that are holding locks, the call
254** to close() the file descriptor is deferred until all of the locks clear.
255** The openCnt structure keeps a list of file descriptors that need to
256** be closed and that list is walked (and cleared) when the last lock
257** clears.
258**
259** First, under Linux threads, because each thread has a separate
260** process ID, lock operations in one thread do not override locks
261** to the same file in other threads. Linux threads behave like
262** separate processes in this respect. But, if you close a file
263** descriptor in linux threads, all locks are cleared, even locks
264** on other threads and even though the other threads have different
265** process IDs. Linux threads is inconsistent in this respect.
266** (I'm beginning to think that linux threads is an abomination too.)
267** The consequence of this all is that the hash table for the lockInfo
268** structure has to include the process id as part of its key because
269** locks in different threads are treated as distinct. But the
270** openCnt structure should not include the process id in its
271** key because close() clears lock on all threads, not just the current
272** thread. Were it not for this goofiness in linux threads, we could
273** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000274**
275** 2004-Jun-28:
276** On some versions of linux, threads can override each others locks.
277** On others not. Sometimes you can change the behavior on the same
278** system by setting the LD_ASSUME_KERNEL environment variable. The
279** POSIX standard is silent as to which behavior is correct, as far
280** as I can tell, so other versions of unix might show the same
281** inconsistency. There is no little doubt in my mind that posix
282** advisory locks and linux threads are profoundly broken.
283**
284** To work around the inconsistencies, we have to test at runtime
285** whether or not threads can override each others locks. This test
286** is run once, the first time any lock is attempted. A static
287** variable is set to record the results of this test for future
288** use.
drhbbd42a62004-05-22 17:41:58 +0000289*/
290
291/*
292** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000293** to locate a particular lockInfo structure given its inode.
294**
295** If threads cannot override each others locks, then we set the
296** lockKey.tid field to the thread ID. If threads can override
drhf1a221e2006-01-15 17:27:17 +0000297** each others locks then tid is always set to zero. tid is omitted
298** if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000299*/
300struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000301 dev_t dev; /* Device number */
302 ino_t ino; /* Inode number */
303#ifdef SQLITE_UNIX_THREADS
drhd9cb6ac2005-10-20 07:28:17 +0000304 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000305#endif
drhbbd42a62004-05-22 17:41:58 +0000306};
307
308/*
309** An instance of the following structure is allocated for each open
310** inode on each thread with a different process ID. (Threads have
311** different process IDs on linux, but not on most other unixes.)
312**
313** A single inode can have multiple file descriptors, so each OsFile
314** structure contains a pointer to an instance of this object and this
315** object keeps a count of the number of OsFiles pointing to it.
316*/
317struct lockInfo {
318 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000319 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000320 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000321 int nRef; /* Number of pointers to this structure */
322};
323
324/*
325** An instance of the following structure serves as the key used
326** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000327** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000328*/
329struct openKey {
330 dev_t dev; /* Device number */
331 ino_t ino; /* Inode number */
332};
333
334/*
335** An instance of the following structure is allocated for each open
336** inode. This structure keeps track of the number of locks on that
337** inode. If a close is attempted against an inode that is holding
338** locks, the close is deferred until all locks clear by adding the
339** file descriptor to be closed to the pending list.
340*/
341struct openCnt {
342 struct openKey key; /* The lookup key */
343 int nRef; /* Number of pointers to this structure */
344 int nLock; /* Number of outstanding locks */
345 int nPending; /* Number of pending close() operations */
346 int *aPending; /* Malloced space holding fd's awaiting a close() */
347};
348
349/*
drhf1a221e2006-01-15 17:27:17 +0000350** These hash tables map inodes and file descriptors (really, lockKey and
351** openKey structures) into lockInfo and openCnt structures. Access to
352** these hash tables must be protected by a mutex.
drhbbd42a62004-05-22 17:41:58 +0000353*/
danielk1977750b03e2006-02-14 10:48:39 +0000354static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0,
355 sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
356static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0,
357 sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
drh5fdae772004-06-29 03:29:00 +0000358
drhbfe66312006-10-03 17:40:40 +0000359#ifdef SQLITE_ENABLE_LOCKING_STYLE
360/*
361** The locking styles are associated with the different file locking
362** capabilities supported by different file systems.
363**
364** POSIX locking style fully supports shared and exclusive byte-range locks
365** ADP locking only supports exclusive byte-range locks
366** FLOCK only supports a single file-global exclusive lock
367** DOTLOCK isn't a true locking style, it refers to the use of a special
368** file named the same as the database file with a '.lock' extension, this
369** can be used on file systems that do not offer any reliable file locking
370** NO locking means that no locking will be attempted, this is only used for
371** read-only file systems currently
372** UNSUPPORTED means that no locking will be attempted, this is only used for
373** file systems that are known to be unsupported
374*/
375typedef enum {
376 posixLockingStyle = 0, /* standard posix-advisory locks */
377 afpLockingStyle, /* use afp locks */
378 flockLockingStyle, /* use flock() */
379 dotlockLockingStyle, /* use <file>.lock files */
380 noLockingStyle, /* useful for read-only file system */
381 unsupportedLockingStyle /* indicates unsupported file system */
382} sqlite3LockingStyle;
383#endif /* SQLITE_ENABLE_LOCKING_STYLE */
384
drh5fdae772004-06-29 03:29:00 +0000385#ifdef SQLITE_UNIX_THREADS
386/*
387** This variable records whether or not threads can override each others
388** locks.
389**
390** 0: No. Threads cannot override each others locks.
391** 1: Yes. Threads can override each others locks.
392** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000393**
drh5062d3a2006-01-31 23:03:35 +0000394** On some systems, we know at compile-time if threads can override each
395** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
396** will be set appropriately. On other systems, we have to check at
397** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
398** undefined.
399**
drhf1a221e2006-01-15 17:27:17 +0000400** This variable normally has file scope only. But during testing, we make
401** it a global so that the test code can change its value in order to verify
402** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000403*/
drh5062d3a2006-01-31 23:03:35 +0000404#ifndef SQLITE_THREAD_OVERRIDE_LOCK
405# define SQLITE_THREAD_OVERRIDE_LOCK -1
406#endif
drh029b44b2006-01-15 00:13:15 +0000407#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000408int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000409#else
drh5062d3a2006-01-31 23:03:35 +0000410static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000411#endif
drh5fdae772004-06-29 03:29:00 +0000412
413/*
414** This structure holds information passed into individual test
415** threads by the testThreadLockingBehavior() routine.
416*/
417struct threadTestData {
418 int fd; /* File to be locked */
419 struct flock lock; /* The locking operation */
420 int result; /* Result of the locking operation */
421};
422
drh2b4b5962005-06-15 17:47:55 +0000423#ifdef SQLITE_LOCK_TRACE
424/*
425** Print out information about all locking operations.
426**
427** This routine is used for troubleshooting locks on multithreaded
428** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
429** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000430** turned off.
drh2b4b5962005-06-15 17:47:55 +0000431*/
432static int lockTrace(int fd, int op, struct flock *p){
433 char *zOpName, *zType;
434 int s;
435 int savedErrno;
436 if( op==F_GETLK ){
437 zOpName = "GETLK";
438 }else if( op==F_SETLK ){
439 zOpName = "SETLK";
440 }else{
441 s = fcntl(fd, op, p);
442 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
443 return s;
444 }
445 if( p->l_type==F_RDLCK ){
446 zType = "RDLCK";
447 }else if( p->l_type==F_WRLCK ){
448 zType = "WRLCK";
449 }else if( p->l_type==F_UNLCK ){
450 zType = "UNLCK";
451 }else{
452 assert( 0 );
453 }
454 assert( p->l_whence==SEEK_SET );
455 s = fcntl(fd, op, p);
456 savedErrno = errno;
457 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
458 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
459 (int)p->l_pid, s);
460 if( s && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
461 struct flock l2;
462 l2 = *p;
463 fcntl(fd, F_GETLK, &l2);
464 if( l2.l_type==F_RDLCK ){
465 zType = "RDLCK";
466 }else if( l2.l_type==F_WRLCK ){
467 zType = "WRLCK";
468 }else if( l2.l_type==F_UNLCK ){
469 zType = "UNLCK";
470 }else{
471 assert( 0 );
472 }
473 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
474 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
475 }
476 errno = savedErrno;
477 return s;
478}
479#define fcntl lockTrace
480#endif /* SQLITE_LOCK_TRACE */
481
drh5fdae772004-06-29 03:29:00 +0000482/*
483** The testThreadLockingBehavior() routine launches two separate
484** threads on this routine. This routine attempts to lock a file
485** descriptor then returns. The success or failure of that attempt
486** allows the testThreadLockingBehavior() procedure to determine
487** whether or not threads can override each others locks.
488*/
489static void *threadLockingTest(void *pArg){
490 struct threadTestData *pData = (struct threadTestData*)pArg;
491 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
492 return pArg;
493}
494
495/*
496** This procedure attempts to determine whether or not threads
497** can override each others locks then sets the
498** threadsOverrideEachOthersLocks variable appropriately.
499*/
danielk19774d5238f2006-01-27 06:32:00 +0000500static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000501 int fd;
502 struct threadTestData d[2];
503 pthread_t t[2];
504
505 fd = dup(fd_orig);
506 if( fd<0 ) return;
507 memset(d, 0, sizeof(d));
508 d[0].fd = fd;
509 d[0].lock.l_type = F_RDLCK;
510 d[0].lock.l_len = 1;
511 d[0].lock.l_start = 0;
512 d[0].lock.l_whence = SEEK_SET;
513 d[1] = d[0];
514 d[1].lock.l_type = F_WRLCK;
515 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
516 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
517 pthread_join(t[0], 0);
518 pthread_join(t[1], 0);
519 close(fd);
520 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
521}
522#endif /* SQLITE_UNIX_THREADS */
523
drhbbd42a62004-05-22 17:41:58 +0000524/*
525** Release a lockInfo structure previously allocated by findLockInfo().
526*/
527static void releaseLockInfo(struct lockInfo *pLock){
drh757b04e2006-01-18 17:25:45 +0000528 assert( sqlite3OsInMutex(1) );
drhbfe66312006-10-03 17:40:40 +0000529 if (pLock == NULL)
530 return;
drhbbd42a62004-05-22 17:41:58 +0000531 pLock->nRef--;
532 if( pLock->nRef==0 ){
533 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
danielk1977750b03e2006-02-14 10:48:39 +0000534 sqlite3ThreadSafeFree(pLock);
drhbbd42a62004-05-22 17:41:58 +0000535 }
536}
537
538/*
539** Release a openCnt structure previously allocated by findLockInfo().
540*/
541static void releaseOpenCnt(struct openCnt *pOpen){
drh757b04e2006-01-18 17:25:45 +0000542 assert( sqlite3OsInMutex(1) );
drhbfe66312006-10-03 17:40:40 +0000543 if (pOpen == NULL)
544 return;
drhbbd42a62004-05-22 17:41:58 +0000545 pOpen->nRef--;
546 if( pOpen->nRef==0 ){
547 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
drh64b1bea2006-01-15 02:30:57 +0000548 free(pOpen->aPending);
danielk1977750b03e2006-02-14 10:48:39 +0000549 sqlite3ThreadSafeFree(pOpen);
drhbbd42a62004-05-22 17:41:58 +0000550 }
551}
552
drhbfe66312006-10-03 17:40:40 +0000553#ifdef SQLITE_ENABLE_LOCKING_STYLE
554/*
555** Tests a byte-range locking query to see if byte range locks are
556** supported, if not we fall back to dotlockLockingStyle.
557*/
558static sqlite3LockingStyle sqlite3TestLockingStyle(const char *filePath,
559 int fd) {
560 /* test byte-range lock using fcntl */
561 struct flock lockInfo;
562
563 lockInfo.l_len = 1;
564 lockInfo.l_start = 0;
565 lockInfo.l_whence = SEEK_SET;
566 lockInfo.l_type = F_RDLCK;
567
aswiftae0943b2007-01-31 23:37:07 +0000568 if (fcntl(fd, F_GETLK, &lockInfo) != -1) {
drhbfe66312006-10-03 17:40:40 +0000569 return posixLockingStyle;
570 }
571
572 /* testing for flock can give false positives. So if if the above test
573 ** fails, then we fall back to using dot-lock style locking.
574 */
575 return dotlockLockingStyle;
576}
577
578/*
579** Examines the f_fstypename entry in the statfs structure as returned by
580** stat() for the file system hosting the database file, assigns the
581** appropriate locking style based on it's value. These values and
582** assignments are based on Darwin/OSX behavior and have not been tested on
583** other systems.
584*/
585static sqlite3LockingStyle sqlite3DetectLockingStyle(const char *filePath,
586 int fd) {
587
588#ifdef SQLITE_FIXED_LOCKING_STYLE
589 return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
590#else
591 struct statfs fsInfo;
592
593 if (statfs(filePath, &fsInfo) == -1)
594 return sqlite3TestLockingStyle(filePath, fd);
595
596 if (fsInfo.f_flags & MNT_RDONLY)
597 return noLockingStyle;
598
599 if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
600 (!strcmp(fsInfo.f_fstypename, "ufs")) )
601 return posixLockingStyle;
602
603 if(!strcmp(fsInfo.f_fstypename, "afpfs"))
604 return afpLockingStyle;
605
606 if(!strcmp(fsInfo.f_fstypename, "nfs"))
607 return sqlite3TestLockingStyle(filePath, fd);
608
609 if(!strcmp(fsInfo.f_fstypename, "smbfs"))
610 return flockLockingStyle;
611
612 if(!strcmp(fsInfo.f_fstypename, "msdos"))
613 return dotlockLockingStyle;
614
615 if(!strcmp(fsInfo.f_fstypename, "webdav"))
616 return unsupportedLockingStyle;
617
618 return sqlite3TestLockingStyle(filePath, fd);
619#endif // SQLITE_FIXED_LOCKING_STYLE
620}
621
622#endif /* SQLITE_ENABLE_LOCKING_STYLE */
623
drhbbd42a62004-05-22 17:41:58 +0000624/*
625** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000626** describes that file descriptor. Create new ones if necessary. The
627** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000628**
629** Return the number of errors.
630*/
drh38f82712004-06-18 17:10:16 +0000631static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000632 int fd, /* The file descriptor used in the key */
633 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000634 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000635){
636 int rc;
637 struct lockKey key1;
638 struct openKey key2;
639 struct stat statbuf;
640 struct lockInfo *pLock;
641 struct openCnt *pOpen;
642 rc = fstat(fd, &statbuf);
643 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000644
drh757b04e2006-01-18 17:25:45 +0000645 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000646 memset(&key1, 0, sizeof(key1));
647 key1.dev = statbuf.st_dev;
648 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000649#ifdef SQLITE_UNIX_THREADS
650 if( threadsOverrideEachOthersLocks<0 ){
651 testThreadLockingBehavior(fd);
652 }
653 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
654#endif
drhbbd42a62004-05-22 17:41:58 +0000655 memset(&key2, 0, sizeof(key2));
656 key2.dev = statbuf.st_dev;
657 key2.ino = statbuf.st_ino;
658 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
659 if( pLock==0 ){
660 struct lockInfo *pOld;
danielk1977750b03e2006-02-14 10:48:39 +0000661 pLock = sqlite3ThreadSafeMalloc( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000662 if( pLock==0 ){
663 rc = 1;
664 goto exit_findlockinfo;
665 }
drhbbd42a62004-05-22 17:41:58 +0000666 pLock->key = key1;
667 pLock->nRef = 1;
668 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000669 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000670 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
671 if( pOld!=0 ){
672 assert( pOld==pLock );
danielk1977750b03e2006-02-14 10:48:39 +0000673 sqlite3ThreadSafeFree(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000674 rc = 1;
675 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000676 }
677 }else{
678 pLock->nRef++;
679 }
680 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000681 if( ppOpen!=0 ){
682 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
drhbbd42a62004-05-22 17:41:58 +0000683 if( pOpen==0 ){
drh029b44b2006-01-15 00:13:15 +0000684 struct openCnt *pOld;
danielk1977750b03e2006-02-14 10:48:39 +0000685 pOpen = sqlite3ThreadSafeMalloc( sizeof(*pOpen) );
drh029b44b2006-01-15 00:13:15 +0000686 if( pOpen==0 ){
687 releaseLockInfo(pLock);
688 rc = 1;
689 goto exit_findlockinfo;
690 }
691 pOpen->key = key2;
692 pOpen->nRef = 1;
693 pOpen->nLock = 0;
694 pOpen->nPending = 0;
695 pOpen->aPending = 0;
696 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
697 if( pOld!=0 ){
698 assert( pOld==pOpen );
danielk1977750b03e2006-02-14 10:48:39 +0000699 sqlite3ThreadSafeFree(pOpen);
drh029b44b2006-01-15 00:13:15 +0000700 releaseLockInfo(pLock);
701 rc = 1;
702 goto exit_findlockinfo;
703 }
704 }else{
705 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000706 }
drh029b44b2006-01-15 00:13:15 +0000707 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000708 }
danielk1977441b09a2006-01-05 13:48:29 +0000709
710exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000711 return rc;
drhbbd42a62004-05-22 17:41:58 +0000712}
713
drh64b1bea2006-01-15 02:30:57 +0000714#ifdef SQLITE_DEBUG
715/*
716** Helper function for printing out trace information from debugging
717** binaries. This returns the string represetation of the supplied
718** integer lock-type.
719*/
720static const char *locktypeName(int locktype){
721 switch( locktype ){
722 case NO_LOCK: return "NONE";
723 case SHARED_LOCK: return "SHARED";
724 case RESERVED_LOCK: return "RESERVED";
725 case PENDING_LOCK: return "PENDING";
726 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
727 }
728 return "ERROR";
729}
730#endif
731
drhbbd42a62004-05-22 17:41:58 +0000732/*
drh029b44b2006-01-15 00:13:15 +0000733** If we are currently in a different thread than the thread that the
734** unixFile argument belongs to, then transfer ownership of the unixFile
735** over to the current thread.
736**
737** A unixFile is only owned by a thread on systems where one thread is
738** unable to override locks created by a different thread. RedHat9 is
739** an example of such a system.
740**
741** Ownership transfer is only allowed if the unixFile is currently unlocked.
742** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000743** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000744*/
745#ifdef SQLITE_UNIX_THREADS
746static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000747 int rc;
drh029b44b2006-01-15 00:13:15 +0000748 pthread_t hSelf;
749 if( threadsOverrideEachOthersLocks ){
750 /* Ownership transfers not needed on this system */
751 return SQLITE_OK;
752 }
753 hSelf = pthread_self();
754 if( pthread_equal(pFile->tid, hSelf) ){
755 /* We are still in the same thread */
drh64b1bea2006-01-15 02:30:57 +0000756 TRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000757 return SQLITE_OK;
758 }
759 if( pFile->locktype!=NO_LOCK ){
760 /* We cannot change ownership while we are holding a lock! */
761 return SQLITE_MISUSE;
762 }
drh64b1bea2006-01-15 02:30:57 +0000763 TRACE4("Transfer ownership of %d from %d to %d\n", pFile->h,pFile->tid,hSelf);
drh029b44b2006-01-15 00:13:15 +0000764 pFile->tid = hSelf;
drhbfe66312006-10-03 17:40:40 +0000765 if (pFile->pLock != NULL) {
766 releaseLockInfo(pFile->pLock);
767 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
768 TRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
769 locktypeName(pFile->locktype),
770 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
771 return rc;
772 } else {
773 return SQLITE_OK;
774 }
drh029b44b2006-01-15 00:13:15 +0000775}
776#else
drhf1a221e2006-01-15 17:27:17 +0000777 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +0000778# define transferOwnership(X) SQLITE_OK
779#endif
780
781/*
drhbbd42a62004-05-22 17:41:58 +0000782** Delete the named file
783*/
drh66560ad2006-01-06 14:32:19 +0000784int sqlite3UnixDelete(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000785 unlink(zFilename);
786 return SQLITE_OK;
787}
788
789/*
790** Return TRUE if the named file exists.
791*/
drh66560ad2006-01-06 14:32:19 +0000792int sqlite3UnixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000793 return access(zFilename, 0)==0;
794}
795
drh054889e2005-11-30 03:20:31 +0000796/* Forward declaration */
drhbfe66312006-10-03 17:40:40 +0000797static int allocateUnixFile(
798 int h, /* File descriptor of the open file */
799 OsFile **pId, /* Write the real file descriptor here */
800 const char *zFilename, /* Name of the file being opened */
801 int delFlag /* If true, make sure the file deletes on close */
802);
drh9cbe6352005-11-29 03:13:21 +0000803
804/*
drhbbd42a62004-05-22 17:41:58 +0000805** Attempt to open a file for both reading and writing. If that
806** fails, try opening it read-only. If the file does not exist,
807** try to create it.
808**
809** On success, a handle for the open file is written to *id
810** and *pReadonly is set to 0 if the file was opened for reading and
811** writing or 1 if the file was opened read-only. The function returns
812** SQLITE_OK.
813**
814** On failure, the function returns SQLITE_CANTOPEN and leaves
815** *id and *pReadonly unchanged.
816*/
drh66560ad2006-01-06 14:32:19 +0000817int sqlite3UnixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000818 const char *zFilename,
drh9cbe6352005-11-29 03:13:21 +0000819 OsFile **pId,
drhbbd42a62004-05-22 17:41:58 +0000820 int *pReadonly
821){
drhbfe66312006-10-03 17:40:40 +0000822 int h;
823
drh66560ad2006-01-06 14:32:19 +0000824 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
drh9cbe6352005-11-29 03:13:21 +0000825 assert( 0==*pId );
drhbfe66312006-10-03 17:40:40 +0000826 h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
827 SQLITE_DEFAULT_FILE_PERMISSIONS);
828 if( h<0 ){
drh6458e392004-07-20 01:14:13 +0000829#ifdef EISDIR
830 if( errno==EISDIR ){
831 return SQLITE_CANTOPEN;
832 }
833#endif
drhbfe66312006-10-03 17:40:40 +0000834 h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
835 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000836 return SQLITE_CANTOPEN;
837 }
838 *pReadonly = 1;
839 }else{
840 *pReadonly = 0;
841 }
drhbfe66312006-10-03 17:40:40 +0000842 return allocateUnixFile(h, pId, zFilename, 0);
drhbbd42a62004-05-22 17:41:58 +0000843}
844
845
846/*
847** Attempt to open a new file for exclusive access by this process.
848** The file will be opened for both reading and writing. To avoid
849** a potential security problem, we do not allow the file to have
850** previously existed. Nor do we allow the file to be a symbolic
851** link.
852**
853** If delFlag is true, then make arrangements to automatically delete
854** the file when it is closed.
855**
856** On success, write the file handle into *id and return SQLITE_OK.
857**
858** On failure, return SQLITE_CANTOPEN.
859*/
drh66560ad2006-01-06 14:32:19 +0000860int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
drhbfe66312006-10-03 17:40:40 +0000861 int h;
drh9cbe6352005-11-29 03:13:21 +0000862
drh66560ad2006-01-06 14:32:19 +0000863 CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
drh9cbe6352005-11-29 03:13:21 +0000864 assert( 0==*pId );
drhbfe66312006-10-03 17:40:40 +0000865 h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000866 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
drh3f56e6e2007-03-15 01:16:47 +0000867 delFlag ? 0600 : SQLITE_DEFAULT_FILE_PERMISSIONS);
drhbfe66312006-10-03 17:40:40 +0000868 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000869 return SQLITE_CANTOPEN;
870 }
drhbfe66312006-10-03 17:40:40 +0000871 return allocateUnixFile(h, pId, zFilename, delFlag);
drhbbd42a62004-05-22 17:41:58 +0000872}
873
874/*
875** Attempt to open a new file for read-only access.
876**
877** On success, write the file handle into *id and return SQLITE_OK.
878**
879** On failure, return SQLITE_CANTOPEN.
880*/
drh66560ad2006-01-06 14:32:19 +0000881int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
drhbfe66312006-10-03 17:40:40 +0000882 int h;
883
drh66560ad2006-01-06 14:32:19 +0000884 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
drh9cbe6352005-11-29 03:13:21 +0000885 assert( 0==*pId );
drhbfe66312006-10-03 17:40:40 +0000886 h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
887 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000888 return SQLITE_CANTOPEN;
889 }
drhbfe66312006-10-03 17:40:40 +0000890 return allocateUnixFile(h, pId, zFilename, 0);
drhbbd42a62004-05-22 17:41:58 +0000891}
892
893/*
894** Attempt to open a file descriptor for the directory that contains a
895** file. This file descriptor can be used to fsync() the directory
896** in order to make sure the creation of a new file is actually written
897** to disk.
898**
899** This routine is only meaningful for Unix. It is a no-op under
900** windows since windows does not support hard links.
901**
drhbfe66312006-10-03 17:40:40 +0000902** If FULL_FSYNC is enabled, this function is not longer useful,
903** a FULL_FSYNC sync applies to all pending disk operations.
904**
drh9cbe6352005-11-29 03:13:21 +0000905** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000906** updated with the new directory file descriptor and SQLITE_OK is
907** returned.
908**
909** On failure, the function returns SQLITE_CANTOPEN and leaves
910** *id unchanged.
911*/
drh9c06c952005-11-26 00:25:00 +0000912static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000913 OsFile *id,
914 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000915){
drh054889e2005-11-30 03:20:31 +0000916 unixFile *pFile = (unixFile*)id;
917 if( pFile==0 ){
drhbbd42a62004-05-22 17:41:58 +0000918 /* Do not open the directory if the corresponding file is not already
919 ** open. */
920 return SQLITE_CANTOPEN;
921 }
drh054889e2005-11-30 03:20:31 +0000922 SET_THREADID(pFile);
923 assert( pFile->dirfd<0 );
924 pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
925 if( pFile->dirfd<0 ){
drhbbd42a62004-05-22 17:41:58 +0000926 return SQLITE_CANTOPEN;
927 }
drh054889e2005-11-30 03:20:31 +0000928 TRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000929 return SQLITE_OK;
930}
931
932/*
drhab3f9fe2004-08-14 17:10:10 +0000933** If the following global variable points to a string which is the
934** name of a directory, then that directory will be used to store
935** temporary files.
drhf1a221e2006-01-15 17:27:17 +0000936**
937** See also the "PRAGMA temp_store_directory" SQL command.
drhab3f9fe2004-08-14 17:10:10 +0000938*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000939char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000940
941/*
drhbbd42a62004-05-22 17:41:58 +0000942** Create a temporary file name in zBuf. zBuf must be big enough to
943** hold at least SQLITE_TEMPNAME_SIZE characters.
944*/
drh66560ad2006-01-06 14:32:19 +0000945int sqlite3UnixTempFileName(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +0000946 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000947 0,
drhbbd42a62004-05-22 17:41:58 +0000948 "/var/tmp",
949 "/usr/tmp",
950 "/tmp",
951 ".",
952 };
drh57196282004-10-06 15:41:16 +0000953 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000954 "abcdefghijklmnopqrstuvwxyz"
955 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
956 "0123456789";
957 int i, j;
958 struct stat buf;
959 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000960 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000961 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000962 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000963 if( stat(azDirs[i], &buf) ) continue;
964 if( !S_ISDIR(buf.st_mode) ) continue;
965 if( access(azDirs[i], 07) ) continue;
966 zDir = azDirs[i];
967 break;
968 }
969 do{
970 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
971 j = strlen(zBuf);
972 sqlite3Randomness(15, &zBuf[j]);
973 for(i=0; i<15; i++, j++){
974 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
975 }
976 zBuf[j] = 0;
977 }while( access(zBuf,0)==0 );
978 return SQLITE_OK;
979}
980
981/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000982** Check that a given pathname is a directory and is writable
983**
984*/
drh66560ad2006-01-06 14:32:19 +0000985int sqlite3UnixIsDirWritable(char *zBuf){
drh9c06c952005-11-26 00:25:00 +0000986#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000987 struct stat buf;
988 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000989 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000990 if( stat(zBuf, &buf) ) return 0;
991 if( !S_ISDIR(buf.st_mode) ) return 0;
992 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000993#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000994 return 1;
995}
996
997/*
drhb912b282006-03-23 22:42:20 +0000998** Seek to the offset in id->offset then read cnt bytes into pBuf.
999** Return the number of bytes actually read. Update the offset.
1000*/
1001static int seekAndRead(unixFile *id, void *pBuf, int cnt){
1002 int got;
drh8ebf6702007-02-06 11:11:08 +00001003 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +00001004 TIMER_START;
drh8350a212007-03-22 15:22:06 +00001005#if defined(USE_PREAD)
drhb912b282006-03-23 22:42:20 +00001006 got = pread(id->h, pBuf, cnt, id->offset);
drh8350a212007-03-22 15:22:06 +00001007#elif defined(USE_PREAD64)
1008 got = pread64(id->h, pBuf, cnt, id->offset);
drhb912b282006-03-23 22:42:20 +00001009#else
drh8ebf6702007-02-06 11:11:08 +00001010 newOffset = lseek(id->h, id->offset, SEEK_SET);
1011 if( newOffset!=id->offset ){
1012 return -1;
1013 }
drhb912b282006-03-23 22:42:20 +00001014 got = read(id->h, pBuf, cnt);
1015#endif
drh15d00c42007-02-27 02:01:14 +00001016 TIMER_END;
1017 TRACE5("READ %-3d %5d %7lld %d\n", id->h, got, id->offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +00001018 if( got>0 ){
1019 id->offset += got;
1020 }
1021 return got;
1022}
1023
1024/*
drhbbd42a62004-05-22 17:41:58 +00001025** Read data from a file into a buffer. Return SQLITE_OK if all
1026** bytes were read successfully and SQLITE_IOERR if anything goes
1027** wrong.
1028*/
drh9c06c952005-11-26 00:25:00 +00001029static int unixRead(OsFile *id, void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +00001030 int got;
drh9cbe6352005-11-29 03:13:21 +00001031 assert( id );
drhb912b282006-03-23 22:42:20 +00001032 got = seekAndRead((unixFile*)id, pBuf, amt);
drh551b7732006-11-06 21:20:25 +00001033 SimulateIOError( got = -1 );
drhbbd42a62004-05-22 17:41:58 +00001034 if( got==amt ){
1035 return SQLITE_OK;
drh4ac285a2006-09-15 07:28:50 +00001036 }else if( got<0 ){
1037 return SQLITE_IOERR_READ;
drhbbd42a62004-05-22 17:41:58 +00001038 }else{
drhbafda092007-01-03 23:36:22 +00001039 memset(&((char*)pBuf)[got], 0, amt-got);
drh4ac285a2006-09-15 07:28:50 +00001040 return SQLITE_IOERR_SHORT_READ;
drhbbd42a62004-05-22 17:41:58 +00001041 }
1042}
1043
1044/*
drhb912b282006-03-23 22:42:20 +00001045** Seek to the offset in id->offset then read cnt bytes into pBuf.
1046** Return the number of bytes actually read. Update the offset.
1047*/
1048static int seekAndWrite(unixFile *id, const void *pBuf, int cnt){
1049 int got;
drh8ebf6702007-02-06 11:11:08 +00001050 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +00001051 TIMER_START;
drh8350a212007-03-22 15:22:06 +00001052#if defined(USE_PREAD)
drhb912b282006-03-23 22:42:20 +00001053 got = pwrite(id->h, pBuf, cnt, id->offset);
drh8350a212007-03-22 15:22:06 +00001054#elif defined(USE_PREAD64)
1055 got = pwrite64(id->h, pBuf, cnt, id->offset);
drhb912b282006-03-23 22:42:20 +00001056#else
drh8ebf6702007-02-06 11:11:08 +00001057 newOffset = lseek(id->h, id->offset, SEEK_SET);
1058 if( newOffset!=id->offset ){
1059 return -1;
1060 }
drhb912b282006-03-23 22:42:20 +00001061 got = write(id->h, pBuf, cnt);
1062#endif
drh15d00c42007-02-27 02:01:14 +00001063 TIMER_END;
1064 TRACE5("WRITE %-3d %5d %7lld %d\n", id->h, got, id->offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +00001065 if( got>0 ){
1066 id->offset += got;
1067 }
1068 return got;
1069}
1070
1071
1072/*
drhbbd42a62004-05-22 17:41:58 +00001073** Write data from a buffer into a file. Return SQLITE_OK on success
1074** or some other error code on failure.
1075*/
drh9c06c952005-11-26 00:25:00 +00001076static int unixWrite(OsFile *id, const void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +00001077 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +00001078 assert( id );
drh4c7f9412005-02-03 00:29:47 +00001079 assert( amt>0 );
drhb912b282006-03-23 22:42:20 +00001080 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +00001081 amt -= wrote;
1082 pBuf = &((char*)pBuf)[wrote];
1083 }
drh59685932006-09-14 13:47:11 +00001084 SimulateIOError(( wrote=(-1), amt=1 ));
1085 SimulateDiskfullError(( wrote=0, amt=1 ));
drhbbd42a62004-05-22 17:41:58 +00001086 if( amt>0 ){
drh59685932006-09-14 13:47:11 +00001087 if( wrote<0 ){
drh4ac285a2006-09-15 07:28:50 +00001088 return SQLITE_IOERR_WRITE;
drh59685932006-09-14 13:47:11 +00001089 }else{
1090 return SQLITE_FULL;
1091 }
drhbbd42a62004-05-22 17:41:58 +00001092 }
1093 return SQLITE_OK;
1094}
1095
1096/*
1097** Move the read/write pointer in a file.
1098*/
drh9c06c952005-11-26 00:25:00 +00001099static int unixSeek(OsFile *id, i64 offset){
drh9cbe6352005-11-29 03:13:21 +00001100 assert( id );
drhb4746b92005-09-09 01:32:06 +00001101#ifdef SQLITE_TEST
drh59685932006-09-14 13:47:11 +00001102 if( offset ) SimulateDiskfullError(return SQLITE_FULL);
drhb4746b92005-09-09 01:32:06 +00001103#endif
drhb912b282006-03-23 22:42:20 +00001104 ((unixFile*)id)->offset = offset;
drhbbd42a62004-05-22 17:41:58 +00001105 return SQLITE_OK;
1106}
1107
drhb851b2c2005-03-10 14:11:12 +00001108#ifdef SQLITE_TEST
1109/*
1110** Count the number of fullsyncs and normal syncs. This is used to test
1111** that syncs and fullsyncs are occuring at the right times.
1112*/
1113int sqlite3_sync_count = 0;
1114int sqlite3_fullsync_count = 0;
1115#endif
1116
drhf2f23912005-10-05 10:29:36 +00001117/*
1118** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
1119** Otherwise use fsync() in its place.
1120*/
1121#ifndef HAVE_FDATASYNC
1122# define fdatasync fsync
1123#endif
1124
drhac530b12006-02-11 01:25:50 +00001125/*
1126** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
1127** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
1128** only available on Mac OS X. But that could change.
1129*/
1130#ifdef F_FULLFSYNC
1131# define HAVE_FULLFSYNC 1
1132#else
1133# define HAVE_FULLFSYNC 0
1134#endif
1135
drhb851b2c2005-03-10 14:11:12 +00001136
drhbbd42a62004-05-22 17:41:58 +00001137/*
drhdd809b02004-07-17 21:44:57 +00001138** The fsync() system call does not work as advertised on many
1139** unix systems. The following procedure is an attempt to make
1140** it work better.
drh1398ad32005-01-19 23:24:50 +00001141**
1142** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
1143** for testing when we want to run through the test suite quickly.
1144** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
1145** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
1146** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +00001147*/
drheb796a72005-09-08 12:38:41 +00001148static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +00001149 int rc;
drhb851b2c2005-03-10 14:11:12 +00001150
1151 /* Record the number of times that we do a normal fsync() and
1152 ** FULLSYNC. This is used during testing to verify that this procedure
1153 ** gets called with the correct arguments.
1154 */
1155#ifdef SQLITE_TEST
1156 if( fullSync ) sqlite3_fullsync_count++;
1157 sqlite3_sync_count++;
1158#endif
1159
1160 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
1161 ** no-op
1162 */
1163#ifdef SQLITE_NO_SYNC
1164 rc = SQLITE_OK;
1165#else
1166
drhac530b12006-02-11 01:25:50 +00001167#if HAVE_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +00001168 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +00001169 rc = fcntl(fd, F_FULLFSYNC, 0);
aswiftae0943b2007-01-31 23:37:07 +00001170 }else{
1171 rc = 1;
1172 }
1173 /* If the FULLFSYNC failed, fall back to attempting an fsync().
1174 * It shouldn't be possible for fullfsync to fail on the local
1175 * file system (on OSX), so failure indicates that FULLFSYNC
1176 * isn't supported for this file system. So, attempt an fsync
1177 * and (for now) ignore the overhead of a superfluous fcntl call.
1178 * It'd be better to detect fullfsync support once and avoid
1179 * the fcntl call every time sync is called.
1180 */
1181 if( rc ) rc = fsync(fd);
1182
1183#else
drheb796a72005-09-08 12:38:41 +00001184 if( dataOnly ){
1185 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +00001186 }else{
drheb796a72005-09-08 12:38:41 +00001187 rc = fsync(fd);
1188 }
aswiftae0943b2007-01-31 23:37:07 +00001189#endif /* HAVE_FULLFSYNC */
drhb851b2c2005-03-10 14:11:12 +00001190#endif /* defined(SQLITE_NO_SYNC) */
1191
drhdd809b02004-07-17 21:44:57 +00001192 return rc;
1193}
1194
1195/*
drhbbd42a62004-05-22 17:41:58 +00001196** Make sure all writes to a particular file are committed to disk.
1197**
drheb796a72005-09-08 12:38:41 +00001198** If dataOnly==0 then both the file itself and its metadata (file
1199** size, access time, etc) are synced. If dataOnly!=0 then only the
1200** file data is synced.
1201**
drhbbd42a62004-05-22 17:41:58 +00001202** Under Unix, also make sure that the directory entry for the file
1203** has been created by fsync-ing the directory that contains the file.
1204** If we do not do this and we encounter a power failure, the directory
1205** entry for the journal might not exist after we reboot. The next
1206** SQLite to access the file will not know that the journal exists (because
1207** the directory entry for the journal was never created) and the transaction
1208** will not roll back - possibly leading to database corruption.
1209*/
drh9c06c952005-11-26 00:25:00 +00001210static int unixSync(OsFile *id, int dataOnly){
drh59685932006-09-14 13:47:11 +00001211 int rc;
drh054889e2005-11-30 03:20:31 +00001212 unixFile *pFile = (unixFile*)id;
1213 assert( pFile );
drh054889e2005-11-30 03:20:31 +00001214 TRACE2("SYNC %-3d\n", pFile->h);
drh59685932006-09-14 13:47:11 +00001215 rc = full_fsync(pFile->h, pFile->fullSync, dataOnly);
1216 SimulateIOError( rc=1 );
1217 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001218 return SQLITE_IOERR_FSYNC;
drhbbd42a62004-05-22 17:41:58 +00001219 }
drh054889e2005-11-30 03:20:31 +00001220 if( pFile->dirfd>=0 ){
drhac530b12006-02-11 01:25:50 +00001221 TRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
1222 HAVE_FULLFSYNC, pFile->fullSync);
danielk1977d7c03f72005-11-25 10:38:22 +00001223#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001224 /* The directory sync is only attempted if full_fsync is
1225 ** turned off or unavailable. If a full_fsync occurred above,
1226 ** then the directory sync is superfluous.
1227 */
1228 if( (!HAVE_FULLFSYNC || !pFile->fullSync) && full_fsync(pFile->dirfd,0,0) ){
1229 /*
1230 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001231 ** errors when applied to directories on certain file systems.
1232 ** A failed directory sync is not a big deal. So it seems
1233 ** better to ignore the error. Ticket #1657
1234 */
1235 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001236 }
danielk1977d7c03f72005-11-25 10:38:22 +00001237#endif
drh054889e2005-11-30 03:20:31 +00001238 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1239 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001240 }
drha2854222004-06-17 19:04:17 +00001241 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001242}
1243
1244/*
danielk1977962398d2004-06-14 09:35:16 +00001245** Sync the directory zDirname. This is a no-op on operating systems other
1246** than UNIX.
drhb851b2c2005-03-10 14:11:12 +00001247**
1248** This is used to make sure the master journal file has truely been deleted
1249** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +00001250** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +00001251*/
drh66560ad2006-01-06 14:32:19 +00001252int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +00001253#ifdef SQLITE_DISABLE_DIRSYNC
1254 return SQLITE_OK;
1255#else
danielk1977962398d2004-06-14 09:35:16 +00001256 int fd;
1257 int r;
drh8e855772005-05-17 11:25:31 +00001258 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +00001259 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001260 if( fd<0 ){
1261 return SQLITE_CANTOPEN;
1262 }
1263 r = fsync(fd);
1264 close(fd);
drh59685932006-09-14 13:47:11 +00001265 SimulateIOError( r=1 );
1266 if( r ){
drh4ac285a2006-09-15 07:28:50 +00001267 return SQLITE_IOERR_DIR_FSYNC;
drh59685932006-09-14 13:47:11 +00001268 }else{
1269 return SQLITE_OK;
1270 }
danielk1977d7c03f72005-11-25 10:38:22 +00001271#endif
danielk1977962398d2004-06-14 09:35:16 +00001272}
1273
1274/*
drhbbd42a62004-05-22 17:41:58 +00001275** Truncate an open file to a specified size
1276*/
drh9c06c952005-11-26 00:25:00 +00001277static int unixTruncate(OsFile *id, i64 nByte){
drh59685932006-09-14 13:47:11 +00001278 int rc;
drh9cbe6352005-11-29 03:13:21 +00001279 assert( id );
drh59685932006-09-14 13:47:11 +00001280 rc = ftruncate(((unixFile*)id)->h, nByte);
1281 SimulateIOError( rc=1 );
1282 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001283 return SQLITE_IOERR_TRUNCATE;
drh59685932006-09-14 13:47:11 +00001284 }else{
1285 return SQLITE_OK;
1286 }
drhbbd42a62004-05-22 17:41:58 +00001287}
1288
1289/*
1290** Determine the current size of a file in bytes
1291*/
drh9c06c952005-11-26 00:25:00 +00001292static int unixFileSize(OsFile *id, i64 *pSize){
drh59685932006-09-14 13:47:11 +00001293 int rc;
drhbbd42a62004-05-22 17:41:58 +00001294 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001295 assert( id );
drh59685932006-09-14 13:47:11 +00001296 rc = fstat(((unixFile*)id)->h, &buf);
1297 SimulateIOError( rc=1 );
1298 if( rc!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001299 return SQLITE_IOERR_FSTAT;
drhbbd42a62004-05-22 17:41:58 +00001300 }
1301 *pSize = buf.st_size;
1302 return SQLITE_OK;
1303}
1304
danielk19779a1d0ab2004-06-01 14:09:28 +00001305/*
danielk197713adf8a2004-06-03 16:08:41 +00001306** This routine checks if there is a RESERVED lock held on the specified
1307** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001308** non-zero. If the file is unlocked or holds only SHARED locks, then
1309** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001310*/
drh9c06c952005-11-26 00:25:00 +00001311static int unixCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +00001312 int r = 0;
drh054889e2005-11-30 03:20:31 +00001313 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001314
drh054889e2005-11-30 03:20:31 +00001315 assert( pFile );
drh66560ad2006-01-06 14:32:19 +00001316 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001317
1318 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001319 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001320 r = 1;
1321 }
1322
drh2ac3ee92004-06-07 16:27:46 +00001323 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001324 */
1325 if( !r ){
1326 struct flock lock;
1327 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001328 lock.l_start = RESERVED_BYTE;
1329 lock.l_len = 1;
1330 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001331 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001332 if( lock.l_type!=F_UNLCK ){
1333 r = 1;
1334 }
1335 }
1336
drh66560ad2006-01-06 14:32:19 +00001337 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001338 TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001339
1340 return r;
1341}
1342
1343/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001344** Lock the file with the lock specified by parameter locktype - one
1345** of the following:
1346**
drh2ac3ee92004-06-07 16:27:46 +00001347** (1) SHARED_LOCK
1348** (2) RESERVED_LOCK
1349** (3) PENDING_LOCK
1350** (4) EXCLUSIVE_LOCK
1351**
drhb3e04342004-06-08 00:47:47 +00001352** Sometimes when requesting one lock state, additional lock states
1353** are inserted in between. The locking might fail on one of the later
1354** transitions leaving the lock state different from what it started but
1355** still short of its goal. The following chart shows the allowed
1356** transitions and the inserted intermediate states:
1357**
1358** UNLOCKED -> SHARED
1359** SHARED -> RESERVED
1360** SHARED -> (PENDING) -> EXCLUSIVE
1361** RESERVED -> (PENDING) -> EXCLUSIVE
1362** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001363**
drha6abd042004-06-09 17:37:22 +00001364** This routine will only increase a lock. Use the sqlite3OsUnlock()
1365** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001366*/
drh9c06c952005-11-26 00:25:00 +00001367static int unixLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001368 /* The following describes the implementation of the various locks and
1369 ** lock transitions in terms of the POSIX advisory shared and exclusive
1370 ** lock primitives (called read-locks and write-locks below, to avoid
1371 ** confusion with SQLite lock names). The algorithms are complicated
1372 ** slightly in order to be compatible with windows systems simultaneously
1373 ** accessing the same database file, in case that is ever required.
1374 **
1375 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1376 ** byte', each single bytes at well known offsets, and the 'shared byte
1377 ** range', a range of 510 bytes at a well known offset.
1378 **
1379 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1380 ** byte'. If this is successful, a random byte from the 'shared byte
1381 ** range' is read-locked and the lock on the 'pending byte' released.
1382 **
danielk197790ba3bd2004-06-25 08:32:25 +00001383 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1384 ** A RESERVED lock is implemented by grabbing a write-lock on the
1385 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001386 **
1387 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001388 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1389 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1390 ** obtained, but existing SHARED locks are allowed to persist. A process
1391 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1392 ** This property is used by the algorithm for rolling back a journal file
1393 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001394 **
danielk197790ba3bd2004-06-25 08:32:25 +00001395 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1396 ** implemented by obtaining a write-lock on the entire 'shared byte
1397 ** range'. Since all other locks require a read-lock on one of the bytes
1398 ** within this range, this ensures that no other locks are held on the
1399 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001400 **
1401 ** The reason a single byte cannot be used instead of the 'shared byte
1402 ** range' is that some versions of windows do not support read-locks. By
1403 ** locking a random byte from a range, concurrent SHARED locks may exist
1404 ** even if the locking primitive used is always a write-lock.
1405 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001406 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001407 unixFile *pFile = (unixFile*)id;
1408 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001409 struct flock lock;
1410 int s;
1411
drh054889e2005-11-30 03:20:31 +00001412 assert( pFile );
1413 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
1414 locktypeName(locktype), locktypeName(pFile->locktype),
1415 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001416
1417 /* If there is already a lock of this type or more restrictive on the
1418 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh66560ad2006-01-06 14:32:19 +00001419 ** sqlite3OsEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001420 */
drh054889e2005-11-30 03:20:31 +00001421 if( pFile->locktype>=locktype ){
1422 TRACE3("LOCK %d %s ok (already held)\n", pFile->h,
1423 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001424 return SQLITE_OK;
1425 }
1426
drhb3e04342004-06-08 00:47:47 +00001427 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001428 */
drh054889e2005-11-30 03:20:31 +00001429 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001430 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001431 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001432
drh054889e2005-11-30 03:20:31 +00001433 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001434 */
drh66560ad2006-01-06 14:32:19 +00001435 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001436
drh029b44b2006-01-15 00:13:15 +00001437 /* Make sure the current thread owns the pFile.
1438 */
1439 rc = transferOwnership(pFile);
1440 if( rc!=SQLITE_OK ){
1441 sqlite3OsLeaveMutex();
1442 return rc;
1443 }
drh64b1bea2006-01-15 02:30:57 +00001444 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001445
danielk19779a1d0ab2004-06-01 14:09:28 +00001446 /* If some thread using this PID has a lock via a different OsFile*
1447 ** handle that precludes the requested lock, return BUSY.
1448 */
drh054889e2005-11-30 03:20:31 +00001449 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001450 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001451 ){
1452 rc = SQLITE_BUSY;
1453 goto end_lock;
1454 }
1455
1456 /* If a SHARED lock is requested, and some thread using this PID already
1457 ** has a SHARED or RESERVED lock, then increment reference counts and
1458 ** return SQLITE_OK.
1459 */
1460 if( locktype==SHARED_LOCK &&
1461 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1462 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001463 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001464 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001465 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001466 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001467 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001468 goto end_lock;
1469 }
1470
danielk197713adf8a2004-06-03 16:08:41 +00001471 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001472
danielk19779a1d0ab2004-06-01 14:09:28 +00001473 lock.l_whence = SEEK_SET;
1474
drh3cde3bb2004-06-12 02:17:14 +00001475 /* A PENDING lock is needed before acquiring a SHARED lock and before
1476 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1477 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001478 */
drh3cde3bb2004-06-12 02:17:14 +00001479 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001480 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001481 ){
danielk1977489468c2004-06-28 08:25:47 +00001482 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001483 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001484 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001485 if( s ){
1486 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1487 goto end_lock;
1488 }
drh3cde3bb2004-06-12 02:17:14 +00001489 }
1490
1491
1492 /* If control gets to this point, then actually go ahead and make
1493 ** operating system calls for the specified lock.
1494 */
1495 if( locktype==SHARED_LOCK ){
1496 assert( pLock->cnt==0 );
1497 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001498
drh2ac3ee92004-06-07 16:27:46 +00001499 /* Now get the read-lock */
1500 lock.l_start = SHARED_FIRST;
1501 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001502 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001503
1504 /* Drop the temporary PENDING lock */
1505 lock.l_start = PENDING_BYTE;
1506 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001507 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001508 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001509 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001510 goto end_lock;
1511 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001512 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001513 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1514 }else{
drh054889e2005-11-30 03:20:31 +00001515 pFile->locktype = SHARED_LOCK;
1516 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001517 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001518 }
drh3cde3bb2004-06-12 02:17:14 +00001519 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1520 /* We are trying for an exclusive lock but another thread in this
1521 ** same process is still holding a shared lock. */
1522 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001523 }else{
drh3cde3bb2004-06-12 02:17:14 +00001524 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001525 ** assumed that there is a SHARED or greater lock on the file
1526 ** already.
1527 */
drh054889e2005-11-30 03:20:31 +00001528 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001529 lock.l_type = F_WRLCK;
1530 switch( locktype ){
1531 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001532 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001533 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001534 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001535 lock.l_start = SHARED_FIRST;
1536 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001537 break;
1538 default:
1539 assert(0);
1540 }
drh054889e2005-11-30 03:20:31 +00001541 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001542 if( s ){
1543 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1544 }
drhbbd42a62004-05-22 17:41:58 +00001545 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001546
danielk1977ecb2a962004-06-02 06:30:16 +00001547 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001548 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001549 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001550 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001551 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001552 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001553 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001554
1555end_lock:
drh66560ad2006-01-06 14:32:19 +00001556 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001557 TRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001558 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001559 return rc;
1560}
1561
1562/*
drh054889e2005-11-30 03:20:31 +00001563** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001564** must be either NO_LOCK or SHARED_LOCK.
1565**
1566** If the locking level of the file descriptor is already at or below
1567** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001568*/
drh9c06c952005-11-26 00:25:00 +00001569static int unixUnlock(OsFile *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001570 struct lockInfo *pLock;
1571 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001572 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001573 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001574
drh054889e2005-11-30 03:20:31 +00001575 assert( pFile );
1576 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
1577 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001578
1579 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001580 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001581 return SQLITE_OK;
1582 }
drhf1a221e2006-01-15 17:27:17 +00001583 if( CHECK_THREADID(pFile) ){
1584 return SQLITE_MISUSE;
1585 }
drh66560ad2006-01-06 14:32:19 +00001586 sqlite3OsEnterMutex();
drh054889e2005-11-30 03:20:31 +00001587 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001588 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001589 if( pFile->locktype>SHARED_LOCK ){
1590 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001591 if( locktype==SHARED_LOCK ){
1592 lock.l_type = F_RDLCK;
1593 lock.l_whence = SEEK_SET;
1594 lock.l_start = SHARED_FIRST;
1595 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001596 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh9c105bb2004-10-02 20:38:28 +00001597 /* This should never happen */
drh4ac285a2006-09-15 07:28:50 +00001598 rc = SQLITE_IOERR_RDLOCK;
drh9c105bb2004-10-02 20:38:28 +00001599 }
1600 }
drhbbd42a62004-05-22 17:41:58 +00001601 lock.l_type = F_UNLCK;
1602 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001603 lock.l_start = PENDING_BYTE;
1604 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh054889e2005-11-30 03:20:31 +00001605 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001606 pLock->locktype = SHARED_LOCK;
1607 }else{
drh4ac285a2006-09-15 07:28:50 +00001608 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001609 }
drhbbd42a62004-05-22 17:41:58 +00001610 }
drha6abd042004-06-09 17:37:22 +00001611 if( locktype==NO_LOCK ){
1612 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001613
drha6abd042004-06-09 17:37:22 +00001614 /* Decrement the shared lock counter. Release the lock using an
1615 ** OS call only when all threads in this same process have released
1616 ** the lock.
1617 */
1618 pLock->cnt--;
1619 if( pLock->cnt==0 ){
1620 lock.l_type = F_UNLCK;
1621 lock.l_whence = SEEK_SET;
1622 lock.l_start = lock.l_len = 0L;
drh054889e2005-11-30 03:20:31 +00001623 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001624 pLock->locktype = NO_LOCK;
1625 }else{
drh4ac285a2006-09-15 07:28:50 +00001626 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001627 }
drha6abd042004-06-09 17:37:22 +00001628 }
1629
drhbbd42a62004-05-22 17:41:58 +00001630 /* Decrement the count of locks against this same file. When the
1631 ** count reaches zero, close any other file descriptors whose close
1632 ** was deferred because of outstanding locks.
1633 */
drh054889e2005-11-30 03:20:31 +00001634 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001635 pOpen->nLock--;
1636 assert( pOpen->nLock>=0 );
1637 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1638 int i;
1639 for(i=0; i<pOpen->nPending; i++){
1640 close(pOpen->aPending[i]);
1641 }
drh64b1bea2006-01-15 02:30:57 +00001642 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001643 pOpen->nPending = 0;
1644 pOpen->aPending = 0;
1645 }
1646 }
drh66560ad2006-01-06 14:32:19 +00001647 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001648 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001649 return rc;
drhbbd42a62004-05-22 17:41:58 +00001650}
1651
1652/*
danielk1977e3026632004-06-22 11:29:02 +00001653** Close a file.
1654*/
drh9cbe6352005-11-29 03:13:21 +00001655static int unixClose(OsFile **pId){
drh054889e2005-11-30 03:20:31 +00001656 unixFile *id = (unixFile*)*pId;
drh029b44b2006-01-15 00:13:15 +00001657
drh9cbe6352005-11-29 03:13:21 +00001658 if( !id ) return SQLITE_OK;
drh38322302006-01-15 02:43:16 +00001659 unixUnlock(*pId, NO_LOCK);
danielk1977e3026632004-06-22 11:29:02 +00001660 if( id->dirfd>=0 ) close(id->dirfd);
1661 id->dirfd = -1;
drh66560ad2006-01-06 14:32:19 +00001662 sqlite3OsEnterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001663
drh38322302006-01-15 02:43:16 +00001664 if( id->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001665 /* If there are outstanding locks, do not actually close the file just
1666 ** yet because that would clear those locks. Instead, add the file
1667 ** descriptor to pOpen->aPending. It will be automatically closed when
1668 ** the last lock is cleared.
1669 */
1670 int *aNew;
1671 struct openCnt *pOpen = id->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001672 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001673 if( aNew==0 ){
1674 /* If a malloc fails, just leak the file descriptor */
1675 }else{
1676 pOpen->aPending = aNew;
drhad81e872005-08-21 21:45:01 +00001677 pOpen->aPending[pOpen->nPending] = id->h;
1678 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001679 }
1680 }else{
1681 /* There are no outstanding locks so we can close the file immediately */
1682 close(id->h);
1683 }
1684 releaseLockInfo(id->pLock);
1685 releaseOpenCnt(id->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001686
drh66560ad2006-01-06 14:32:19 +00001687 sqlite3OsLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001688 id->isOpen = 0;
1689 TRACE2("CLOSE %-3d\n", id->h);
1690 OpenCounter(-1);
danielk1977750b03e2006-02-14 10:48:39 +00001691 sqlite3ThreadSafeFree(id);
drh9cbe6352005-11-29 03:13:21 +00001692 *pId = 0;
drh02afc862006-01-20 18:10:57 +00001693 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001694}
1695
drhbfe66312006-10-03 17:40:40 +00001696
1697#ifdef SQLITE_ENABLE_LOCKING_STYLE
1698#pragma mark AFP Support
1699
1700/*
1701 ** The afpLockingContext structure contains all afp lock specific state
1702 */
1703typedef struct afpLockingContext afpLockingContext;
1704struct afpLockingContext {
1705 unsigned long long sharedLockByte;
1706 char *filePath;
1707};
1708
1709struct ByteRangeLockPB2
1710{
1711 unsigned long long offset; /* offset to first byte to lock */
1712 unsigned long long length; /* nbr of bytes to lock */
1713 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
1714 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
1715 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
1716 int fd; /* file desc to assoc this lock with */
1717};
1718
1719#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
1720
1721/* return 0 on success, 1 on failure. To match the behavior of the
1722 normal posix file locking (used in unixLock for example), we should
1723 provide 'richer' return codes - specifically to differentiate between
1724 'file busy' and 'file system error' results */
1725static int _AFPFSSetLock(const char *path, int fd, unsigned long long offset,
1726 unsigned long long length, int setLockFlag)
1727{
1728 struct ByteRangeLockPB2 pb;
1729 int err;
1730
1731 pb.unLockFlag = setLockFlag ? 0 : 1;
1732 pb.startEndFlag = 0;
1733 pb.offset = offset;
1734 pb.length = length;
1735 pb.fd = fd;
1736 TRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
1737 (setLockFlag?"ON":"OFF"), fd, offset, length);
1738 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
1739 if ( err==-1 ) {
1740 TRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno,
1741 strerror(errno));
1742 return 1; // error
1743 } else {
1744 return 0;
1745 }
1746}
1747
1748/*
1749 ** This routine checks if there is a RESERVED lock held on the specified
1750 ** file by this or any other process. If such a lock is held, return
1751 ** non-zero. If the file is unlocked or holds only SHARED locks, then
1752 ** return zero.
1753 */
1754static int afpUnixCheckReservedLock(OsFile *id){
1755 int r = 0;
1756 unixFile *pFile = (unixFile*)id;
1757
1758 assert( pFile );
1759 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1760
1761 /* Check if a thread in this process holds such a lock */
1762 if( pFile->locktype>SHARED_LOCK ){
1763 r = 1;
1764 }
1765
1766 /* Otherwise see if some other process holds it.
1767 */
1768 if ( !r ) {
1769 // lock the byte
1770 int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1771 if (failed) {
1772 /* if we failed to get the lock then someone else must have it */
1773 r = 1;
1774 } else {
1775 /* if we succeeded in taking the reserved lock, unlock it to restore
1776 ** the original state */
1777 _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
1778 }
1779 }
1780 TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
1781
1782 return r;
1783}
1784
1785/* AFP-style locking following the behavior of unixLock, see the unixLock
1786** function comments for details of lock management. */
1787static int afpUnixLock(OsFile *id, int locktype)
1788{
1789 int rc = SQLITE_OK;
1790 unixFile *pFile = (unixFile*)id;
1791 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1792 int gotPendingLock = 0;
1793
1794 assert( pFile );
1795 TRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
1796 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
1797 /* If there is already a lock of this type or more restrictive on the
1798 ** OsFile, do nothing. Don't use the afp_end_lock: exit path, as
1799 ** sqlite3OsEnterMutex() hasn't been called yet.
1800 */
1801 if( pFile->locktype>=locktype ){
1802 TRACE3("LOCK %d %s ok (already held)\n", pFile->h,
1803 locktypeName(locktype));
1804 return SQLITE_OK;
1805 }
1806
1807 /* Make sure the locking sequence is correct
1808 */
1809 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
1810 assert( locktype!=PENDING_LOCK );
1811 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1812
1813 /* This mutex is needed because pFile->pLock is shared across threads
1814 */
1815 sqlite3OsEnterMutex();
1816
1817 /* Make sure the current thread owns the pFile.
1818 */
1819 rc = transferOwnership(pFile);
1820 if( rc!=SQLITE_OK ){
1821 sqlite3OsLeaveMutex();
1822 return rc;
1823 }
1824
1825 /* A PENDING lock is needed before acquiring a SHARED lock and before
1826 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1827 ** be released.
1828 */
1829 if( locktype==SHARED_LOCK
1830 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
1831 ){
1832 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1833 PENDING_BYTE, 1, 1);
1834 if (failed) {
1835 rc = SQLITE_BUSY;
1836 goto afp_end_lock;
1837 }
1838 }
1839
1840 /* If control gets to this point, then actually go ahead and make
1841 ** operating system calls for the specified lock.
1842 */
1843 if( locktype==SHARED_LOCK ){
1844 int lk, failed;
1845 int tries = 0;
1846
1847 /* Now get the read-lock */
1848 /* note that the quality of the randomness doesn't matter that much */
1849 lk = random();
1850 context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
1851 failed = _AFPFSSetLock(context->filePath, pFile->h,
1852 SHARED_FIRST+context->sharedLockByte, 1, 1);
1853
1854 /* Drop the temporary PENDING lock */
1855 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
1856 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1857 goto afp_end_lock;
1858 }
1859
1860 if( failed ){
1861 rc = SQLITE_BUSY;
1862 } else {
1863 pFile->locktype = SHARED_LOCK;
1864 }
1865 }else{
1866 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1867 ** assumed that there is a SHARED or greater lock on the file
1868 ** already.
1869 */
1870 int failed = 0;
1871 assert( 0!=pFile->locktype );
1872 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
1873 /* Acquire a RESERVED lock */
1874 failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1875 }
1876 if (!failed && locktype == EXCLUSIVE_LOCK) {
1877 /* Acquire an EXCLUSIVE lock */
1878
1879 /* Remove the shared lock before trying the range. we'll need to
1880 ** reestablish the shared lock if we can't get the afpUnixUnlock
1881 */
1882 if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1883 context->sharedLockByte, 1, 0)) {
1884 /* now attemmpt to get the exclusive lock range */
1885 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1886 SHARED_SIZE, 1);
1887 if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1888 context->sharedLockByte, 1, 1)) {
1889 rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
1890 }
1891 } else {
1892 /* */
1893 rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
1894 }
1895 }
1896 if( failed && rc == SQLITE_OK){
1897 rc = SQLITE_BUSY;
1898 }
1899 }
1900
1901 if( rc==SQLITE_OK ){
1902 pFile->locktype = locktype;
1903 }else if( locktype==EXCLUSIVE_LOCK ){
1904 pFile->locktype = PENDING_LOCK;
1905 }
1906
1907afp_end_lock:
1908 sqlite3OsLeaveMutex();
1909 TRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
1910 rc==SQLITE_OK ? "ok" : "failed");
1911 return rc;
1912}
1913
1914/*
1915 ** Lower the locking level on file descriptor pFile to locktype. locktype
1916 ** must be either NO_LOCK or SHARED_LOCK.
1917 **
1918 ** If the locking level of the file descriptor is already at or below
1919 ** the requested locking level, this routine is a no-op.
1920 */
1921static int afpUnixUnlock(OsFile *id, int locktype) {
1922 struct flock lock;
1923 int rc = SQLITE_OK;
1924 unixFile *pFile = (unixFile*)id;
1925 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1926
1927 assert( pFile );
1928 TRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
1929 pFile->locktype, getpid());
1930
1931 assert( locktype<=SHARED_LOCK );
1932 if( pFile->locktype<=locktype ){
1933 return SQLITE_OK;
1934 }
1935 if( CHECK_THREADID(pFile) ){
1936 return SQLITE_MISUSE;
1937 }
1938 sqlite3OsEnterMutex();
1939 if( pFile->locktype>SHARED_LOCK ){
1940 if( locktype==SHARED_LOCK ){
1941 int failed = 0;
1942
1943 /* unlock the exclusive range - then re-establish the shared lock */
1944 if (pFile->locktype==EXCLUSIVE_LOCK) {
1945 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1946 SHARED_SIZE, 0);
1947 if (!failed) {
1948 /* successfully removed the exclusive lock */
1949 if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
1950 context->sharedLockByte, 1, 1)) {
1951 /* failed to re-establish our shared lock */
1952 rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
1953 }
1954 } else {
1955 /* This should never happen - failed to unlock the exclusive range */
1956 rc = SQLITE_IOERR_UNLOCK;
1957 }
1958 }
1959 }
1960 if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
1961 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
1962 /* failed to release the pending lock */
1963 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1964 }
1965 }
1966 if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
1967 if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
1968 /* failed to release the reserved lock */
1969 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1970 }
1971 }
1972 }
1973 if( locktype==NO_LOCK ){
1974 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1975 SHARED_FIRST + context->sharedLockByte, 1, 0);
1976 if (failed) {
1977 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1978 }
1979 }
1980 if (rc == SQLITE_OK)
1981 pFile->locktype = locktype;
1982 sqlite3OsLeaveMutex();
1983 return rc;
1984}
1985
1986/*
1987 ** Close a file & cleanup AFP specific locking context
1988 */
1989static int afpUnixClose(OsFile **pId) {
1990 unixFile *id = (unixFile*)*pId;
1991
1992 if( !id ) return SQLITE_OK;
1993 afpUnixUnlock(*pId, NO_LOCK);
1994 /* free the AFP locking structure */
1995 if (id->lockingContext != NULL) {
1996 if (((afpLockingContext *)id->lockingContext)->filePath != NULL)
1997 sqlite3ThreadSafeFree(((afpLockingContext*)id->lockingContext)->filePath);
1998 sqlite3ThreadSafeFree(id->lockingContext);
1999 }
2000
2001 if( id->dirfd>=0 ) close(id->dirfd);
2002 id->dirfd = -1;
2003 close(id->h);
2004 id->isOpen = 0;
2005 TRACE2("CLOSE %-3d\n", id->h);
2006 OpenCounter(-1);
2007 sqlite3ThreadSafeFree(id);
2008 *pId = 0;
2009 return SQLITE_OK;
2010}
2011
2012
2013#pragma mark flock() style locking
2014
2015/*
2016 ** The flockLockingContext is not used
2017 */
2018typedef void flockLockingContext;
2019
2020static int flockUnixCheckReservedLock(OsFile *id) {
2021 unixFile *pFile = (unixFile*)id;
2022
2023 if (pFile->locktype == RESERVED_LOCK) {
2024 return 1; // already have a reserved lock
2025 } else {
2026 // attempt to get the lock
2027 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
2028 if (!rc) {
2029 // got the lock, unlock it
2030 flock(pFile->h, LOCK_UN);
2031 return 0; // no one has it reserved
2032 }
2033 return 1; // someone else might have it reserved
2034 }
2035}
2036
2037static int flockUnixLock(OsFile *id, int locktype) {
2038 unixFile *pFile = (unixFile*)id;
2039
2040 // if we already have a lock, it is exclusive.
2041 // Just adjust level and punt on outta here.
2042 if (pFile->locktype > NO_LOCK) {
2043 pFile->locktype = locktype;
2044 return SQLITE_OK;
2045 }
2046
2047 // grab an exclusive lock
2048 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
2049 if (rc) {
2050 // didn't get, must be busy
2051 return SQLITE_BUSY;
2052 } else {
2053 // got it, set the type and return ok
2054 pFile->locktype = locktype;
2055 return SQLITE_OK;
2056 }
2057}
2058
2059static int flockUnixUnlock(OsFile *id, int locktype) {
2060 unixFile *pFile = (unixFile*)id;
2061
2062 assert( locktype<=SHARED_LOCK );
2063
2064 // no-op if possible
2065 if( pFile->locktype==locktype ){
2066 return SQLITE_OK;
2067 }
2068
2069 // shared can just be set because we always have an exclusive
2070 if (locktype==SHARED_LOCK) {
2071 pFile->locktype = locktype;
2072 return SQLITE_OK;
2073 }
2074
2075 // no, really, unlock.
2076 int rc = flock(pFile->h, LOCK_UN);
2077 if (rc)
2078 return SQLITE_IOERR_UNLOCK;
2079 else {
2080 pFile->locktype = NO_LOCK;
2081 return SQLITE_OK;
2082 }
2083}
2084
2085/*
2086 ** Close a file.
2087 */
2088static int flockUnixClose(OsFile **pId) {
2089 unixFile *id = (unixFile*)*pId;
2090
2091 if( !id ) return SQLITE_OK;
2092 flockUnixUnlock(*pId, NO_LOCK);
2093
2094 if( id->dirfd>=0 ) close(id->dirfd);
2095 id->dirfd = -1;
2096 sqlite3OsEnterMutex();
2097
2098 close(id->h);
2099 sqlite3OsLeaveMutex();
2100 id->isOpen = 0;
2101 TRACE2("CLOSE %-3d\n", id->h);
2102 OpenCounter(-1);
2103 sqlite3ThreadSafeFree(id);
2104 *pId = 0;
2105 return SQLITE_OK;
2106}
2107
2108#pragma mark Old-School .lock file based locking
2109
2110/*
2111 ** The dotlockLockingContext structure contains all dotlock (.lock) lock
2112 ** specific state
2113 */
2114typedef struct dotlockLockingContext dotlockLockingContext;
2115struct dotlockLockingContext {
2116 char *lockPath;
2117};
2118
2119
2120static int dotlockUnixCheckReservedLock(OsFile *id) {
2121 unixFile *pFile = (unixFile*)id;
2122 dotlockLockingContext *context =
2123 (dotlockLockingContext *) pFile->lockingContext;
2124
2125 if (pFile->locktype == RESERVED_LOCK) {
2126 return 1; // already have a reserved lock
2127 } else {
2128 struct stat statBuf;
2129 if (lstat(context->lockPath,&statBuf) == 0)
2130 // file exists, someone else has the lock
2131 return 1;
2132 else
2133 // file does not exist, we could have it if we want it
2134 return 0;
2135 }
2136}
2137
2138static int dotlockUnixLock(OsFile *id, int locktype) {
2139 unixFile *pFile = (unixFile*)id;
2140 dotlockLockingContext *context =
2141 (dotlockLockingContext *) pFile->lockingContext;
2142
2143 // if we already have a lock, it is exclusive.
2144 // Just adjust level and punt on outta here.
2145 if (pFile->locktype > NO_LOCK) {
2146 pFile->locktype = locktype;
2147
2148 /* Always update the timestamp on the old file */
2149 utimes(context->lockPath,NULL);
2150 return SQLITE_OK;
2151 }
2152
2153 // check to see if lock file already exists
2154 struct stat statBuf;
2155 if (lstat(context->lockPath,&statBuf) == 0){
2156 return SQLITE_BUSY; // it does, busy
2157 }
2158
2159 // grab an exclusive lock
2160 int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
2161 if (fd < 0) {
2162 // failed to open/create the file, someone else may have stolen the lock
2163 return SQLITE_BUSY;
2164 }
2165 close(fd);
2166
2167 // got it, set the type and return ok
2168 pFile->locktype = locktype;
2169 return SQLITE_OK;
2170}
2171
2172static int dotlockUnixUnlock(OsFile *id, int locktype) {
2173 unixFile *pFile = (unixFile*)id;
2174 dotlockLockingContext *context =
2175 (dotlockLockingContext *) pFile->lockingContext;
2176
2177 assert( locktype<=SHARED_LOCK );
2178
2179 // no-op if possible
2180 if( pFile->locktype==locktype ){
2181 return SQLITE_OK;
2182 }
2183
2184 // shared can just be set because we always have an exclusive
2185 if (locktype==SHARED_LOCK) {
2186 pFile->locktype = locktype;
2187 return SQLITE_OK;
2188 }
2189
2190 // no, really, unlock.
2191 unlink(context->lockPath);
2192 pFile->locktype = NO_LOCK;
2193 return SQLITE_OK;
2194}
2195
2196/*
2197 ** Close a file.
2198 */
2199static int dotlockUnixClose(OsFile **pId) {
2200 unixFile *id = (unixFile*)*pId;
2201
2202 if( !id ) return SQLITE_OK;
2203 dotlockUnixUnlock(*pId, NO_LOCK);
2204 /* free the dotlock locking structure */
2205 if (id->lockingContext != NULL) {
2206 if (((dotlockLockingContext *)id->lockingContext)->lockPath != NULL)
2207 sqlite3ThreadSafeFree( ( (dotlockLockingContext *)
2208 id->lockingContext)->lockPath);
2209 sqlite3ThreadSafeFree(id->lockingContext);
2210 }
2211
2212 if( id->dirfd>=0 ) close(id->dirfd);
2213 id->dirfd = -1;
2214 sqlite3OsEnterMutex();
2215
2216 close(id->h);
2217
2218 sqlite3OsLeaveMutex();
2219 id->isOpen = 0;
2220 TRACE2("CLOSE %-3d\n", id->h);
2221 OpenCounter(-1);
2222 sqlite3ThreadSafeFree(id);
2223 *pId = 0;
2224 return SQLITE_OK;
2225}
2226
2227
2228#pragma mark No locking
2229
2230/*
2231 ** The nolockLockingContext is void
2232 */
2233typedef void nolockLockingContext;
2234
2235static int nolockUnixCheckReservedLock(OsFile *id) {
2236 return 0;
2237}
2238
2239static int nolockUnixLock(OsFile *id, int locktype) {
2240 return SQLITE_OK;
2241}
2242
2243static int nolockUnixUnlock(OsFile *id, int locktype) {
2244 return SQLITE_OK;
2245}
2246
2247/*
2248 ** Close a file.
2249 */
2250static int nolockUnixClose(OsFile **pId) {
2251 unixFile *id = (unixFile*)*pId;
2252
2253 if( !id ) return SQLITE_OK;
2254 if( id->dirfd>=0 ) close(id->dirfd);
2255 id->dirfd = -1;
2256 sqlite3OsEnterMutex();
2257
2258 close(id->h);
2259
2260 sqlite3OsLeaveMutex();
2261 id->isOpen = 0;
2262 TRACE2("CLOSE %-3d\n", id->h);
2263 OpenCounter(-1);
2264 sqlite3ThreadSafeFree(id);
2265 *pId = 0;
2266 return SQLITE_OK;
2267}
2268
2269#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2270
danielk1977e3026632004-06-22 11:29:02 +00002271/*
drh0ccebe72005-06-07 22:22:50 +00002272** Turn a relative pathname into a full pathname. Return a pointer
2273** to the full pathname stored in space obtained from sqliteMalloc().
2274** The calling function is responsible for freeing this space once it
2275** is no longer needed.
2276*/
drh66560ad2006-01-06 14:32:19 +00002277char *sqlite3UnixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00002278 char *zFull = 0;
2279 if( zRelative[0]=='/' ){
2280 sqlite3SetString(&zFull, zRelative, (char*)0);
2281 }else{
drh79158e12005-09-06 21:40:45 +00002282 char *zBuf = sqliteMalloc(5000);
2283 if( zBuf==0 ){
2284 return 0;
2285 }
drh0ccebe72005-06-07 22:22:50 +00002286 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00002287 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00002288 (char*)0);
drh79158e12005-09-06 21:40:45 +00002289 sqliteFree(zBuf);
drh0ccebe72005-06-07 22:22:50 +00002290 }
drh4eb9a972006-02-13 18:42:21 +00002291
2292#if 0
drh89ea9312006-02-13 17:03:47 +00002293 /*
2294 ** Remove "/./" path elements and convert "/A/./" path elements
2295 ** to just "/".
2296 */
2297 if( zFull ){
drh4eb9a972006-02-13 18:42:21 +00002298 int i, j;
drh89ea9312006-02-13 17:03:47 +00002299 for(i=j=0; zFull[i]; i++){
2300 if( zFull[i]=='/' ){
2301 if( zFull[i+1]=='/' ) continue;
2302 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
2303 i += 1;
2304 continue;
2305 }
2306 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
2307 while( j>0 && zFull[j-1]!='/' ){ j--; }
2308 i += 3;
2309 continue;
2310 }
2311 }
2312 zFull[j++] = zFull[i];
2313 }
2314 zFull[j] = 0;
2315 }
drh4eb9a972006-02-13 18:42:21 +00002316#endif
2317
drh0ccebe72005-06-07 22:22:50 +00002318 return zFull;
2319}
2320
drh18839212005-11-26 03:43:23 +00002321/*
drh9cbe6352005-11-29 03:13:21 +00002322** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00002323*/
drh9cbe6352005-11-29 03:13:21 +00002324static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00002325 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00002326}
2327
2328/*
2329** Return the underlying file handle for an OsFile
2330*/
2331static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00002332 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00002333}
2334
2335/*
2336** Return an integer that indices the type of lock currently held
2337** by this handle. (Used for testing and analysis only.)
2338*/
2339static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00002340 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00002341}
drh0ccebe72005-06-07 22:22:50 +00002342
drh9c06c952005-11-26 00:25:00 +00002343/*
drh054889e2005-11-30 03:20:31 +00002344** This vector defines all the methods that can operate on an OsFile
2345** for unix.
drh9c06c952005-11-26 00:25:00 +00002346*/
drh054889e2005-11-30 03:20:31 +00002347static const IoMethod sqlite3UnixIoMethod = {
drh9c06c952005-11-26 00:25:00 +00002348 unixClose,
drh054889e2005-11-30 03:20:31 +00002349 unixOpenDirectory,
drh9c06c952005-11-26 00:25:00 +00002350 unixRead,
2351 unixWrite,
2352 unixSeek,
drh9c06c952005-11-26 00:25:00 +00002353 unixTruncate,
drh054889e2005-11-30 03:20:31 +00002354 unixSync,
drh9cbe6352005-11-29 03:13:21 +00002355 unixSetFullSync,
2356 unixFileHandle,
drh054889e2005-11-30 03:20:31 +00002357 unixFileSize,
2358 unixLock,
2359 unixUnlock,
drh9cbe6352005-11-29 03:13:21 +00002360 unixLockState,
drh054889e2005-11-30 03:20:31 +00002361 unixCheckReservedLock,
danielk1977b4721172007-03-19 05:54:48 +00002362 osGenericSectorSize,
drh9c06c952005-11-26 00:25:00 +00002363};
2364
drhbfe66312006-10-03 17:40:40 +00002365#ifdef SQLITE_ENABLE_LOCKING_STYLE
drh054889e2005-11-30 03:20:31 +00002366/*
drhbfe66312006-10-03 17:40:40 +00002367 ** This vector defines all the methods that can operate on an OsFile
2368 ** for unix with AFP style file locking.
2369 */
2370static const IoMethod sqlite3AFPLockingUnixIoMethod = {
2371 afpUnixClose,
2372 unixOpenDirectory,
2373 unixRead,
2374 unixWrite,
2375 unixSeek,
2376 unixTruncate,
2377 unixSync,
2378 unixSetFullSync,
2379 unixFileHandle,
2380 unixFileSize,
2381 afpUnixLock,
2382 afpUnixUnlock,
2383 unixLockState,
2384 afpUnixCheckReservedLock,
danielk1977b4721172007-03-19 05:54:48 +00002385 osGenericSectorSize,
drhbfe66312006-10-03 17:40:40 +00002386};
2387
2388/*
2389 ** This vector defines all the methods that can operate on an OsFile
2390 ** for unix with flock() style file locking.
2391 */
2392static const IoMethod sqlite3FlockLockingUnixIoMethod = {
2393 flockUnixClose,
2394 unixOpenDirectory,
2395 unixRead,
2396 unixWrite,
2397 unixSeek,
2398 unixTruncate,
2399 unixSync,
2400 unixSetFullSync,
2401 unixFileHandle,
2402 unixFileSize,
2403 flockUnixLock,
2404 flockUnixUnlock,
2405 unixLockState,
2406 flockUnixCheckReservedLock,
danielk1977b4721172007-03-19 05:54:48 +00002407 osGenericSectorSize,
drhbfe66312006-10-03 17:40:40 +00002408};
2409
2410/*
2411 ** This vector defines all the methods that can operate on an OsFile
2412 ** for unix with dotlock style file locking.
2413 */
2414static const IoMethod sqlite3DotlockLockingUnixIoMethod = {
2415 dotlockUnixClose,
2416 unixOpenDirectory,
2417 unixRead,
2418 unixWrite,
2419 unixSeek,
2420 unixTruncate,
2421 unixSync,
2422 unixSetFullSync,
2423 unixFileHandle,
2424 unixFileSize,
2425 dotlockUnixLock,
2426 dotlockUnixUnlock,
2427 unixLockState,
2428 dotlockUnixCheckReservedLock,
danielk1977b4721172007-03-19 05:54:48 +00002429 osGenericSectorSize,
drhbfe66312006-10-03 17:40:40 +00002430};
2431
2432/*
2433 ** This vector defines all the methods that can operate on an OsFile
2434 ** for unix with dotlock style file locking.
2435 */
2436static const IoMethod sqlite3NolockLockingUnixIoMethod = {
2437 nolockUnixClose,
2438 unixOpenDirectory,
2439 unixRead,
2440 unixWrite,
2441 unixSeek,
2442 unixTruncate,
2443 unixSync,
2444 unixSetFullSync,
2445 unixFileHandle,
2446 unixFileSize,
2447 nolockUnixLock,
2448 nolockUnixUnlock,
2449 unixLockState,
2450 nolockUnixCheckReservedLock,
danielk1977b4721172007-03-19 05:54:48 +00002451 osGenericSectorSize,
drhbfe66312006-10-03 17:40:40 +00002452};
2453
2454#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2455
2456/*
2457** Allocate memory for a new unixFile and initialize that unixFile.
2458** Write a pointer to the new unixFile into *pId.
2459** If we run out of memory, close the file and return an error.
drh054889e2005-11-30 03:20:31 +00002460*/
drhbfe66312006-10-03 17:40:40 +00002461#ifdef SQLITE_ENABLE_LOCKING_STYLE
2462/*
2463 ** When locking extensions are enabled, the filepath and locking style
2464 ** are needed to determine the unixFile pMethod to use for locking operations.
2465 ** The locking-style specific lockingContext data structure is created
2466 ** and assigned here also.
2467 */
2468static int allocateUnixFile(
2469 int h, /* Open file descriptor of file being opened */
2470 OsFile **pId, /* Write completed initialization here */
2471 const char *zFilename, /* Name of the file being opened */
2472 int delFlag /* Delete-on-or-before-close flag */
2473){
aswift108bc322006-10-11 17:19:46 +00002474 sqlite3LockingStyle lockingStyle;
drh054889e2005-11-30 03:20:31 +00002475 unixFile *pNew;
drhbfe66312006-10-03 17:40:40 +00002476 unixFile f;
2477 int rc;
2478
aswift448aa6f2006-11-11 01:31:58 +00002479 lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
drhbfe66312006-10-03 17:40:40 +00002480 if ( lockingStyle == posixLockingStyle ) {
2481 sqlite3OsEnterMutex();
2482 rc = findLockInfo(h, &f.pLock, &f.pOpen);
2483 sqlite3OsLeaveMutex();
2484 if( rc ){
2485 close(h);
2486 unlink(zFilename);
2487 return SQLITE_NOMEM;
2488 }
2489 } else {
2490 // pLock and pOpen are only used for posix advisory locking
2491 f.pLock = NULL;
2492 f.pOpen = NULL;
2493 }
2494 if( delFlag ){
2495 unlink(zFilename);
2496 }
2497 f.dirfd = -1;
2498 f.fullSync = 0;
2499 f.locktype = 0;
2500 f.offset = 0;
2501 f.h = h;
2502 SET_THREADID(&f);
danielk1977750b03e2006-02-14 10:48:39 +00002503 pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
drh054889e2005-11-30 03:20:31 +00002504 if( pNew==0 ){
drhbfe66312006-10-03 17:40:40 +00002505 close(h);
drh029b44b2006-01-15 00:13:15 +00002506 sqlite3OsEnterMutex();
drhbfe66312006-10-03 17:40:40 +00002507 releaseLockInfo(f.pLock);
2508 releaseOpenCnt(f.pOpen);
drh029b44b2006-01-15 00:13:15 +00002509 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00002510 *pId = 0;
2511 return SQLITE_NOMEM;
2512 }else{
drhbfe66312006-10-03 17:40:40 +00002513 *pNew = f;
aswift108bc322006-10-11 17:19:46 +00002514 switch(lockingStyle) {
drhbfe66312006-10-03 17:40:40 +00002515 case afpLockingStyle:
2516 /* afp locking uses the file path so it needs to be included in
2517 ** the afpLockingContext */
2518 pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
2519 pNew->lockingContext =
2520 sqlite3ThreadSafeMalloc(sizeof(afpLockingContext));
2521 ((afpLockingContext *)pNew->lockingContext)->filePath =
2522 sqlite3ThreadSafeMalloc(strlen(zFilename) + 1);
2523 strcpy(((afpLockingContext *)pNew->lockingContext)->filePath,
2524 zFilename);
2525 srandomdev();
2526 break;
2527 case flockLockingStyle:
2528 /* flock locking doesn't need additional lockingContext information */
2529 pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
2530 break;
2531 case dotlockLockingStyle:
2532 /* dotlock locking uses the file path so it needs to be included in
2533 ** the dotlockLockingContext */
2534 pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
2535 pNew->lockingContext = sqlite3ThreadSafeMalloc(
2536 sizeof(dotlockLockingContext));
2537 ((dotlockLockingContext *)pNew->lockingContext)->lockPath =
2538 sqlite3ThreadSafeMalloc(strlen(zFilename) + strlen(".lock") + 1);
2539 sprintf(((dotlockLockingContext *)pNew->lockingContext)->lockPath,
2540 "%s.lock", zFilename);
2541 break;
2542 case posixLockingStyle:
2543 /* posix locking doesn't need additional lockingContext information */
2544 pNew->pMethod = &sqlite3UnixIoMethod;
2545 break;
2546 case noLockingStyle:
2547 case unsupportedLockingStyle:
2548 default:
2549 pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
2550 }
2551 *pId = (OsFile*)pNew;
2552 OpenCounter(+1);
2553 return SQLITE_OK;
2554 }
2555}
2556#else /* SQLITE_ENABLE_LOCKING_STYLE */
2557static int allocateUnixFile(
2558 int h, /* Open file descriptor on file being opened */
2559 OsFile **pId, /* Write the resul unixFile structure here */
2560 const char *zFilename, /* Name of the file being opened */
2561 int delFlag /* If true, delete the file on or before closing */
2562){
2563 unixFile *pNew;
2564 unixFile f;
2565 int rc;
2566
2567 sqlite3OsEnterMutex();
2568 rc = findLockInfo(h, &f.pLock, &f.pOpen);
2569 sqlite3OsLeaveMutex();
2570 if( delFlag ){
2571 unlink(zFilename);
2572 }
2573 if( rc ){
2574 close(h);
2575 return SQLITE_NOMEM;
2576 }
2577 TRACE3("OPEN %-3d %s\n", h, zFilename);
2578 f.dirfd = -1;
2579 f.fullSync = 0;
2580 f.locktype = 0;
2581 f.offset = 0;
2582 f.h = h;
2583 SET_THREADID(&f);
2584 pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
2585 if( pNew==0 ){
2586 close(h);
2587 sqlite3OsEnterMutex();
2588 releaseLockInfo(f.pLock);
2589 releaseOpenCnt(f.pOpen);
2590 sqlite3OsLeaveMutex();
2591 *pId = 0;
2592 return SQLITE_NOMEM;
2593 }else{
2594 *pNew = f;
drh054889e2005-11-30 03:20:31 +00002595 pNew->pMethod = &sqlite3UnixIoMethod;
2596 *pId = (OsFile*)pNew;
2597 OpenCounter(+1);
2598 return SQLITE_OK;
2599 }
2600}
drhbfe66312006-10-03 17:40:40 +00002601#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9c06c952005-11-26 00:25:00 +00002602
drh0ccebe72005-06-07 22:22:50 +00002603#endif /* SQLITE_OMIT_DISKIO */
2604/***************************************************************************
2605** Everything above deals with file I/O. Everything that follows deals
2606** with other miscellanous aspects of the operating system interface
2607****************************************************************************/
2608
2609
drh761df872006-12-21 01:29:22 +00002610#ifndef SQLITE_OMIT_LOAD_EXTENSION
2611/*
2612** Interfaces for opening a shared library, finding entry points
2613** within the shared library, and closing the shared library.
2614*/
2615#include <dlfcn.h>
2616void *sqlite3UnixDlopen(const char *zFilename){
2617 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
2618}
2619void *sqlite3UnixDlsym(void *pHandle, const char *zSymbol){
2620 return dlsym(pHandle, zSymbol);
2621}
2622int sqlite3UnixDlclose(void *pHandle){
2623 return dlclose(pHandle);
2624}
2625#endif /* SQLITE_OMIT_LOAD_EXTENSION */
2626
drh0ccebe72005-06-07 22:22:50 +00002627/*
drhbbd42a62004-05-22 17:41:58 +00002628** Get information to seed the random number generator. The seed
2629** is written into the buffer zBuf[256]. The calling function must
2630** supply a sufficiently large buffer.
2631*/
drh66560ad2006-01-06 14:32:19 +00002632int sqlite3UnixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00002633 /* We have to initialize zBuf to prevent valgrind from reporting
2634 ** errors. The reports issued by valgrind are incorrect - we would
2635 ** prefer that the randomness be increased by making use of the
2636 ** uninitialized space in zBuf - but valgrind errors tend to worry
2637 ** some users. Rather than argue, it seems easier just to initialize
2638 ** the whole array and silence valgrind, even if that means less randomness
2639 ** in the random seed.
2640 **
2641 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00002642 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00002643 ** tests repeatable.
2644 */
2645 memset(zBuf, 0, 256);
2646#if !defined(SQLITE_TEST)
2647 {
drh842b8642005-01-21 17:53:17 +00002648 int pid, fd;
2649 fd = open("/dev/urandom", O_RDONLY);
2650 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00002651 time_t t;
2652 time(&t);
2653 memcpy(zBuf, &t, sizeof(t));
drh842b8642005-01-21 17:53:17 +00002654 pid = getpid();
2655 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
2656 }else{
2657 read(fd, zBuf, 256);
2658 close(fd);
2659 }
drhbbd42a62004-05-22 17:41:58 +00002660 }
2661#endif
2662 return SQLITE_OK;
2663}
2664
2665/*
2666** Sleep for a little while. Return the amount of time slept.
drhf1a221e2006-01-15 17:27:17 +00002667** The argument is the number of milliseconds we want to sleep.
drhbbd42a62004-05-22 17:41:58 +00002668*/
drh66560ad2006-01-06 14:32:19 +00002669int sqlite3UnixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00002670#if defined(HAVE_USLEEP) && HAVE_USLEEP
2671 usleep(ms*1000);
2672 return ms;
2673#else
2674 sleep((ms+999)/1000);
2675 return 1000*((ms+999)/1000);
2676#endif
2677}
2678
2679/*
drh5c111232006-02-10 04:33:12 +00002680** Static variables used for thread synchronization.
2681**
2682** inMutex the nesting depth of the recursive mutex. The thread
2683** holding mutexMain can read this variable at any time.
2684** But is must hold mutexAux to change this variable. Other
drh6a3d6702006-02-10 13:11:32 +00002685** threads must hold mutexAux to read the variable and can
2686** never write.
drh5c111232006-02-10 04:33:12 +00002687**
2688** mutexOwner The thread id of the thread holding mutexMain. Same
2689** access rules as for inMutex.
2690**
drh6a3d6702006-02-10 13:11:32 +00002691** mutexOwnerValid True if the value in mutexOwner is valid. The same
2692** access rules apply as for inMutex.
drh5c111232006-02-10 04:33:12 +00002693**
2694** mutexMain The main mutex. Hold this mutex in order to get exclusive
2695** access to SQLite data structures.
2696**
2697** mutexAux An auxiliary mutex needed to access variables defined above.
2698**
drh6a3d6702006-02-10 13:11:32 +00002699** Mutexes are always acquired in this order: mutexMain mutexAux. It
2700** is not necessary to acquire mutexMain in order to get mutexAux - just
2701** do not attempt to acquire them in the reverse order: mutexAux mutexMain.
2702** Either get the mutexes with mutexMain first or get mutexAux only.
2703**
2704** When running on a platform where the three variables inMutex, mutexOwner,
2705** and mutexOwnerValid can be set atomically, the mutexAux is not required.
2706** On many systems, all three are 32-bit integers and writing to a 32-bit
2707** integer is atomic. I think. But there are no guarantees. So it seems
2708** safer to protect them using mutexAux.
drhbbd42a62004-05-22 17:41:58 +00002709*/
2710static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00002711#ifdef SQLITE_UNIX_THREADS
drh6a3d6702006-02-10 13:11:32 +00002712static pthread_t mutexOwner; /* Thread holding mutexMain */
drh5c111232006-02-10 04:33:12 +00002713static int mutexOwnerValid = 0; /* True if mutexOwner is valid */
2714static pthread_mutex_t mutexMain = PTHREAD_MUTEX_INITIALIZER; /* The mutex */
2715static pthread_mutex_t mutexAux = PTHREAD_MUTEX_INITIALIZER; /* Aux mutex */
drh79069752004-05-22 21:30:40 +00002716#endif
drhbbd42a62004-05-22 17:41:58 +00002717
2718/*
2719** The following pair of routine implement mutual exclusion for
2720** multi-threaded processes. Only a single thread is allowed to
2721** executed code that is surrounded by EnterMutex() and LeaveMutex().
2722**
2723** SQLite uses only a single Mutex. There is not much critical
2724** code and what little there is executes quickly and without blocking.
drhf1a221e2006-01-15 17:27:17 +00002725**
drh757b04e2006-01-18 17:25:45 +00002726** As of version 3.3.2, this mutex must be recursive.
drhbbd42a62004-05-22 17:41:58 +00002727*/
drh66560ad2006-01-06 14:32:19 +00002728void sqlite3UnixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00002729#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00002730 pthread_mutex_lock(&mutexAux);
2731 if( !mutexOwnerValid || !pthread_equal(mutexOwner, pthread_self()) ){
2732 pthread_mutex_unlock(&mutexAux);
2733 pthread_mutex_lock(&mutexMain);
2734 assert( inMutex==0 );
2735 assert( !mutexOwnerValid );
2736 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00002737 mutexOwner = pthread_self();
drh5c111232006-02-10 04:33:12 +00002738 mutexOwnerValid = 1;
drha3fad6f2006-01-18 14:06:37 +00002739 }
drha3fad6f2006-01-18 14:06:37 +00002740 inMutex++;
drh5c111232006-02-10 04:33:12 +00002741 pthread_mutex_unlock(&mutexAux);
2742#else
drhe9565a62006-02-11 02:03:52 +00002743 inMutex++;
drh5c111232006-02-10 04:33:12 +00002744#endif
drhbbd42a62004-05-22 17:41:58 +00002745}
drh66560ad2006-01-06 14:32:19 +00002746void sqlite3UnixLeaveMutex(){
drha3fad6f2006-01-18 14:06:37 +00002747 assert( inMutex>0 );
drhbbd42a62004-05-22 17:41:58 +00002748#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00002749 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00002750 inMutex--;
drh5c111232006-02-10 04:33:12 +00002751 assert( pthread_equal(mutexOwner, pthread_self()) );
drha3fad6f2006-01-18 14:06:37 +00002752 if( inMutex==0 ){
drh5c111232006-02-10 04:33:12 +00002753 assert( mutexOwnerValid );
2754 mutexOwnerValid = 0;
2755 pthread_mutex_unlock(&mutexMain);
drha3fad6f2006-01-18 14:06:37 +00002756 }
drh5c111232006-02-10 04:33:12 +00002757 pthread_mutex_unlock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00002758#else
2759 inMutex--;
drhbbd42a62004-05-22 17:41:58 +00002760#endif
2761}
2762
2763/*
drh757b04e2006-01-18 17:25:45 +00002764** Return TRUE if the mutex is currently held.
2765**
drh5c111232006-02-10 04:33:12 +00002766** If the thisThrd parameter is true, return true only if the
drh757b04e2006-01-18 17:25:45 +00002767** calling thread holds the mutex. If the parameter is false, return
2768** true if any thread holds the mutex.
drh88f474a2006-01-02 20:00:12 +00002769*/
drh5c111232006-02-10 04:33:12 +00002770int sqlite3UnixInMutex(int thisThrd){
drha3fad6f2006-01-18 14:06:37 +00002771#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00002772 int rc;
2773 pthread_mutex_lock(&mutexAux);
2774 rc = inMutex>0 && (thisThrd==0 || pthread_equal(mutexOwner,pthread_self()));
2775 pthread_mutex_unlock(&mutexAux);
2776 return rc;
drha3fad6f2006-01-18 14:06:37 +00002777#else
drh757b04e2006-01-18 17:25:45 +00002778 return inMutex>0;
drha3fad6f2006-01-18 14:06:37 +00002779#endif
drh88f474a2006-01-02 20:00:12 +00002780}
2781
2782/*
drhb4bc7052006-01-11 23:40:33 +00002783** Remember the number of thread-specific-data blocks allocated.
2784** Use this to verify that we are not leaking thread-specific-data.
2785** Ticket #1601
2786*/
2787#ifdef SQLITE_TEST
2788int sqlite3_tsd_count = 0;
2789# ifdef SQLITE_UNIX_THREADS
2790 static pthread_mutex_t tsd_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
2791# define TSD_COUNTER(N) \
2792 pthread_mutex_lock(&tsd_counter_mutex); \
2793 sqlite3_tsd_count += N; \
2794 pthread_mutex_unlock(&tsd_counter_mutex);
2795# else
2796# define TSD_COUNTER(N) sqlite3_tsd_count += N
2797# endif
2798#else
2799# define TSD_COUNTER(N) /* no-op */
2800#endif
2801
drhb4bc7052006-01-11 23:40:33 +00002802/*
drhf1a221e2006-01-15 17:27:17 +00002803** If called with allocateFlag>0, then return a pointer to thread
drh6f7adc82006-01-11 21:41:20 +00002804** specific data for the current thread. Allocate and zero the
drhf1a221e2006-01-15 17:27:17 +00002805** thread-specific data if it does not already exist.
danielk197713a68c32005-12-15 10:11:30 +00002806**
drh6f7adc82006-01-11 21:41:20 +00002807** If called with allocateFlag==0, then check the current thread
drh70ff98a2006-01-12 01:25:18 +00002808** specific data. Return it if it exists. If it does not exist,
2809** then return NULL.
2810**
2811** If called with allocateFlag<0, check to see if the thread specific
2812** data is allocated and is all zero. If it is then deallocate it.
drh6f7adc82006-01-11 21:41:20 +00002813** Return a pointer to the thread specific data or NULL if it is
drh70ff98a2006-01-12 01:25:18 +00002814** unallocated or gets deallocated.
danielk197713a68c32005-12-15 10:11:30 +00002815*/
drh6f7adc82006-01-11 21:41:20 +00002816ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
danielk19774d5238f2006-01-27 06:32:00 +00002817 static const ThreadData zeroData = {0}; /* Initializer to silence warnings
2818 ** from broken compilers */
danielk197713a68c32005-12-15 10:11:30 +00002819#ifdef SQLITE_UNIX_THREADS
2820 static pthread_key_t key;
2821 static int keyInit = 0;
drh6f7adc82006-01-11 21:41:20 +00002822 ThreadData *pTsd;
danielk197713a68c32005-12-15 10:11:30 +00002823
2824 if( !keyInit ){
drh66560ad2006-01-06 14:32:19 +00002825 sqlite3OsEnterMutex();
danielk197713a68c32005-12-15 10:11:30 +00002826 if( !keyInit ){
2827 int rc;
drh6f7adc82006-01-11 21:41:20 +00002828 rc = pthread_key_create(&key, 0);
danielk197713a68c32005-12-15 10:11:30 +00002829 if( rc ){
drh8c0ca7d2006-01-07 04:06:54 +00002830 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00002831 return 0;
2832 }
2833 keyInit = 1;
2834 }
drh66560ad2006-01-06 14:32:19 +00002835 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00002836 }
2837
drh3fbb0b12006-01-06 00:36:00 +00002838 pTsd = pthread_getspecific(key);
drh70ff98a2006-01-12 01:25:18 +00002839 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00002840 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00002841 if( !sqlite3TestMallocFail() ){
2842 pTsd = sqlite3OsMalloc(sizeof(zeroData));
2843 }
2844#ifdef SQLITE_MEMDEBUG
2845 sqlite3_isFail = 0;
2846#endif
drh6f7adc82006-01-11 21:41:20 +00002847 if( pTsd ){
2848 *pTsd = zeroData;
2849 pthread_setspecific(key, pTsd);
drhb4bc7052006-01-11 23:40:33 +00002850 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00002851 }
danielk197713a68c32005-12-15 10:11:30 +00002852 }
drh70ff98a2006-01-12 01:25:18 +00002853 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00002854 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00002855 sqlite3OsFree(pTsd);
2856 pthread_setspecific(key, 0);
drhb4bc7052006-01-11 23:40:33 +00002857 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00002858 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00002859 }
2860 return pTsd;
2861#else
drh6f7adc82006-01-11 21:41:20 +00002862 static ThreadData *pTsd = 0;
drh70ff98a2006-01-12 01:25:18 +00002863 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00002864 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00002865 if( !sqlite3TestMallocFail() ){
2866 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
2867 }
2868#ifdef SQLITE_MEMDEBUG
2869 sqlite3_isFail = 0;
2870#endif
drh6f7adc82006-01-11 21:41:20 +00002871 if( pTsd ){
2872 *pTsd = zeroData;
drhb4bc7052006-01-11 23:40:33 +00002873 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00002874 }
drh3fbb0b12006-01-06 00:36:00 +00002875 }
drh70ff98a2006-01-12 01:25:18 +00002876 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00002877 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00002878 sqlite3OsFree(pTsd);
drhb4bc7052006-01-11 23:40:33 +00002879 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00002880 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00002881 }
drh3fbb0b12006-01-06 00:36:00 +00002882 return pTsd;
danielk197713a68c32005-12-15 10:11:30 +00002883#endif
2884}
2885
2886/*
drhbbd42a62004-05-22 17:41:58 +00002887** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00002888** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00002889*/
2890#ifdef SQLITE_TEST
2891int sqlite3_current_time = 0;
2892#endif
2893
2894/*
2895** Find the current time (in Universal Coordinated Time). Write the
2896** current time and date as a Julian Day number into *prNow and
2897** return 0. Return 1 if the time and date cannot be found.
2898*/
drh66560ad2006-01-06 14:32:19 +00002899int sqlite3UnixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00002900#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00002901 time_t t;
2902 time(&t);
2903 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00002904#else
2905 struct timeval sNow;
2906 struct timezone sTz; /* Not used */
2907 gettimeofday(&sNow, &sTz);
2908 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
2909#endif
drhbbd42a62004-05-22 17:41:58 +00002910#ifdef SQLITE_TEST
2911 if( sqlite3_current_time ){
2912 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
2913 }
2914#endif
2915 return 0;
2916}
2917
drhbbd42a62004-05-22 17:41:58 +00002918#endif /* OS_UNIX */