blob: 00eb2f2499dd36ab6cdc278488ec67d7fd50f78a [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
13** This file contains code that is specific to Unix systems.
14*/
drhbbd42a62004-05-22 17:41:58 +000015#include "sqliteInt.h"
drheb206252004-10-01 02:00:31 +000016#include "os.h"
17#if OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000018
drhbfe66312006-10-03 17:40:40 +000019/* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
20
drh9cbe6352005-11-29 03:13:21 +000021/*
22** These #defines should enable >2GB file support on Posix if the
23** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000024** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000025**
26** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
27** on the compiler command line. This is necessary if you are compiling
28** on a recent machine (ex: RedHat 7.2) but you want your code to work
29** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
30** without this option, LFS is enable. But LFS does not exist in the kernel
31** in RedHat 6.0, so the code won't work. Hence, for maximum binary
32** portability you should omit LFS.
drh9cbe6352005-11-29 03:13:21 +000033*/
34#ifndef SQLITE_DISABLE_LFS
35# define _LARGE_FILE 1
36# ifndef _FILE_OFFSET_BITS
37# define _FILE_OFFSET_BITS 64
38# endif
39# define _LARGEFILE_SOURCE 1
40#endif
drhbbd42a62004-05-22 17:41:58 +000041
drh9cbe6352005-11-29 03:13:21 +000042/*
43** standard include files.
44*/
45#include <sys/types.h>
46#include <sys/stat.h>
47#include <fcntl.h>
48#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000049#include <time.h>
drh19e2d372005-08-29 23:00:03 +000050#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000051#include <errno.h>
drhbfe66312006-10-03 17:40:40 +000052#ifdef SQLITE_ENABLE_LOCKING_STYLE
53#include <sys/ioctl.h>
54#include <sys/param.h>
55#include <sys/mount.h>
56#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000057
58/*
drhf1a221e2006-01-15 17:27:17 +000059** If we are to be thread-safe, include the pthreads header and define
60** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +000061*/
drh2c547df2007-04-01 18:46:19 +000062#ifndef THREADSAFE
63# define THREADSAFE 1
64#endif
65#if THREADSAFE
drh9cbe6352005-11-29 03:13:21 +000066# include <pthread.h>
67# define SQLITE_UNIX_THREADS 1
68#endif
69
70/*
71** Default permissions when creating a new file
72*/
73#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
74# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
75#endif
76
danielk1977b4b47412007-08-17 15:53:36 +000077/*
78** Maximum supported path-length.
79*/
80#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +000081
82
83/*
drh054889e2005-11-30 03:20:31 +000084** The unixFile structure is subclass of OsFile specific for the unix
85** protability layer.
drh9cbe6352005-11-29 03:13:21 +000086*/
drh054889e2005-11-30 03:20:31 +000087typedef struct unixFile unixFile;
88struct unixFile {
danielk197762079062007-08-15 17:08:46 +000089 sqlite3_io_methods const *pMethod; /* Always the first entry */
drh9cbe6352005-11-29 03:13:21 +000090 struct openCnt *pOpen; /* Info about all open fd's on this inode */
91 struct lockInfo *pLock; /* Info about locks on this inode */
drhbfe66312006-10-03 17:40:40 +000092#ifdef SQLITE_ENABLE_LOCKING_STYLE
93 void *lockingContext; /* Locking style specific state */
94#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000095 int h; /* The file descriptor */
96 unsigned char locktype; /* The type of lock held on this fd */
97 unsigned char isOpen; /* True if needs to be closed */
drh9cbe6352005-11-29 03:13:21 +000098 int dirfd; /* File descriptor for the directory */
drhb912b282006-03-23 22:42:20 +000099 i64 offset; /* Seek offset */
drh9cbe6352005-11-29 03:13:21 +0000100#ifdef SQLITE_UNIX_THREADS
drhf1a221e2006-01-15 17:27:17 +0000101 pthread_t tid; /* The thread that "owns" this OsFile */
drh9cbe6352005-11-29 03:13:21 +0000102#endif
103};
104
danielk197762079062007-08-15 17:08:46 +0000105
drh66560ad2006-01-06 14:32:19 +0000106/*
107** Provide the ability to override some OS-layer functions during
108** testing. This is used to simulate OS crashes to verify that
109** commits are atomic even in the event of an OS crash.
110*/
111#ifdef SQLITE_CRASH_TEST
112 extern int sqlite3CrashTestEnable;
danielk197762079062007-08-15 17:08:46 +0000113 int sqlite3CrashFileWrap(sqlite3_file *, const char *, sqlite3_file **);
114 static int CRASH_TEST_OVERRIDE(const char *zFile, sqlite3_file **pId, int rc){
115 if( rc==SQLITE_OK && sqlite3CrashTestEnable ){
116 rc = sqlite3CrashFileWrap(*pId, zFile, pId);
117 }
118 return rc;
119 }
drh66560ad2006-01-06 14:32:19 +0000120#else
danielk197762079062007-08-15 17:08:46 +0000121# define CRASH_TEST_OVERRIDE(A,B,C) C
drh66560ad2006-01-06 14:32:19 +0000122#endif
123
drh0ccebe72005-06-07 22:22:50 +0000124
125/*
drh198bf392006-01-06 21:52:49 +0000126** Include code that is common to all os_*.c files
127*/
128#include "os_common.h"
129
130/*
drh0ccebe72005-06-07 22:22:50 +0000131** Do not include any of the File I/O interface procedures if the
drhf1a221e2006-01-15 17:27:17 +0000132** SQLITE_OMIT_DISKIO macro is defined (indicating that the database
drh0ccebe72005-06-07 22:22:50 +0000133** will be in-memory only)
134*/
135#ifndef SQLITE_OMIT_DISKIO
136
137
138/*
139** Define various macros that are missing from some systems.
140*/
drhbbd42a62004-05-22 17:41:58 +0000141#ifndef O_LARGEFILE
142# define O_LARGEFILE 0
143#endif
144#ifdef SQLITE_DISABLE_LFS
145# undef O_LARGEFILE
146# define O_LARGEFILE 0
147#endif
148#ifndef O_NOFOLLOW
149# define O_NOFOLLOW 0
150#endif
151#ifndef O_BINARY
152# define O_BINARY 0
153#endif
154
155/*
156** The DJGPP compiler environment looks mostly like Unix, but it
157** lacks the fcntl() system call. So redefine fcntl() to be something
158** that always succeeds. This means that locking does not occur under
danielk197726c5d792005-11-25 09:01:23 +0000159** DJGPP. But it's DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000160*/
161#ifdef __DJGPP__
162# define fcntl(A,B,C) 0
163#endif
164
165/*
drh2b4b5962005-06-15 17:47:55 +0000166** The threadid macro resolves to the thread-id or to 0. Used for
167** testing and debugging only.
168*/
169#ifdef SQLITE_UNIX_THREADS
170#define threadid pthread_self()
171#else
172#define threadid 0
173#endif
174
175/*
176** Set or check the OsFile.tid field. This field is set when an OsFile
177** is first opened. All subsequent uses of the OsFile verify that the
178** same thread is operating on the OsFile. Some operating systems do
179** not allow locks to be overridden by other threads and that restriction
180** means that sqlite3* database handles cannot be moved from one thread
181** to another. This logic makes sure a user does not try to do that
182** by mistake.
drhf1a221e2006-01-15 17:27:17 +0000183**
184** Version 3.3.1 (2006-01-15): OsFiles can be moved from one thread to
185** another as long as we are running on a system that supports threads
186** overriding each others locks (which now the most common behavior)
187** or if no locks are held. But the OsFile.pLock field needs to be
188** recomputed because its key includes the thread-id. See the
189** transferOwnership() function below for additional information
drh2b4b5962005-06-15 17:47:55 +0000190*/
drh029b44b2006-01-15 00:13:15 +0000191#if defined(SQLITE_UNIX_THREADS)
drh9cbe6352005-11-29 03:13:21 +0000192# define SET_THREADID(X) (X)->tid = pthread_self()
drh029b44b2006-01-15 00:13:15 +0000193# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
194 !pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000195#else
196# define SET_THREADID(X)
197# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000198#endif
199
drhbbd42a62004-05-22 17:41:58 +0000200/*
201** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
202** section 6.5.2.2 lines 483 through 490 specify that when a process
203** sets or clears a lock, that operation overrides any prior locks set
204** by the same process. It does not explicitly say so, but this implies
205** that it overrides locks set by the same process using a different
206** file descriptor. Consider this test case:
207**
208** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
209** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
210**
211** Suppose ./file1 and ./file2 are really the same file (because
212** one is a hard or symbolic link to the other) then if you set
213** an exclusive lock on fd1, then try to get an exclusive lock
214** on fd2, it works. I would have expected the second lock to
215** fail since there was already a lock on the file due to fd1.
216** But not so. Since both locks came from the same process, the
217** second overrides the first, even though they were on different
218** file descriptors opened on different file names.
219**
220** Bummer. If you ask me, this is broken. Badly broken. It means
221** that we cannot use POSIX locks to synchronize file access among
222** competing threads of the same process. POSIX locks will work fine
223** to synchronize access for threads in separate processes, but not
224** threads within the same process.
225**
226** To work around the problem, SQLite has to manage file locks internally
227** on its own. Whenever a new database is opened, we have to find the
228** specific inode of the database file (the inode is determined by the
229** st_dev and st_ino fields of the stat structure that fstat() fills in)
230** and check for locks already existing on that inode. When locks are
231** created or removed, we have to look at our own internal record of the
232** locks to see if another thread has previously set a lock on that same
233** inode.
234**
235** The OsFile structure for POSIX is no longer just an integer file
236** descriptor. It is now a structure that holds the integer file
237** descriptor and a pointer to a structure that describes the internal
238** locks on the corresponding inode. There is one locking structure
239** per inode, so if the same inode is opened twice, both OsFile structures
240** point to the same locking structure. The locking structure keeps
241** a reference count (so we will know when to delete it) and a "cnt"
242** field that tells us its internal lock status. cnt==0 means the
243** file is unlocked. cnt==-1 means the file has an exclusive lock.
244** cnt>0 means there are cnt shared locks on the file.
245**
246** Any attempt to lock or unlock a file first checks the locking
247** structure. The fcntl() system call is only invoked to set a
248** POSIX lock if the internal lock structure transitions between
249** a locked and an unlocked state.
250**
251** 2004-Jan-11:
252** More recent discoveries about POSIX advisory locks. (The more
253** I discover, the more I realize the a POSIX advisory locks are
254** an abomination.)
255**
256** If you close a file descriptor that points to a file that has locks,
257** all locks on that file that are owned by the current process are
258** released. To work around this problem, each OsFile structure contains
259** a pointer to an openCnt structure. There is one openCnt structure
260** per open inode, which means that multiple OsFiles can point to a single
261** openCnt. When an attempt is made to close an OsFile, if there are
262** other OsFiles open on the same inode that are holding locks, the call
263** to close() the file descriptor is deferred until all of the locks clear.
264** The openCnt structure keeps a list of file descriptors that need to
265** be closed and that list is walked (and cleared) when the last lock
266** clears.
267**
268** First, under Linux threads, because each thread has a separate
269** process ID, lock operations in one thread do not override locks
270** to the same file in other threads. Linux threads behave like
271** separate processes in this respect. But, if you close a file
272** descriptor in linux threads, all locks are cleared, even locks
273** on other threads and even though the other threads have different
274** process IDs. Linux threads is inconsistent in this respect.
275** (I'm beginning to think that linux threads is an abomination too.)
276** The consequence of this all is that the hash table for the lockInfo
277** structure has to include the process id as part of its key because
278** locks in different threads are treated as distinct. But the
279** openCnt structure should not include the process id in its
280** key because close() clears lock on all threads, not just the current
281** thread. Were it not for this goofiness in linux threads, we could
282** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000283**
284** 2004-Jun-28:
285** On some versions of linux, threads can override each others locks.
286** On others not. Sometimes you can change the behavior on the same
287** system by setting the LD_ASSUME_KERNEL environment variable. The
288** POSIX standard is silent as to which behavior is correct, as far
289** as I can tell, so other versions of unix might show the same
290** inconsistency. There is no little doubt in my mind that posix
291** advisory locks and linux threads are profoundly broken.
292**
293** To work around the inconsistencies, we have to test at runtime
294** whether or not threads can override each others locks. This test
295** is run once, the first time any lock is attempted. A static
296** variable is set to record the results of this test for future
297** use.
drhbbd42a62004-05-22 17:41:58 +0000298*/
299
300/*
301** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000302** to locate a particular lockInfo structure given its inode.
303**
304** If threads cannot override each others locks, then we set the
305** lockKey.tid field to the thread ID. If threads can override
drhf1a221e2006-01-15 17:27:17 +0000306** each others locks then tid is always set to zero. tid is omitted
307** if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000308*/
309struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000310 dev_t dev; /* Device number */
311 ino_t ino; /* Inode number */
312#ifdef SQLITE_UNIX_THREADS
drhd9cb6ac2005-10-20 07:28:17 +0000313 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000314#endif
drhbbd42a62004-05-22 17:41:58 +0000315};
316
317/*
318** An instance of the following structure is allocated for each open
319** inode on each thread with a different process ID. (Threads have
320** different process IDs on linux, but not on most other unixes.)
321**
322** A single inode can have multiple file descriptors, so each OsFile
323** structure contains a pointer to an instance of this object and this
324** object keeps a count of the number of OsFiles pointing to it.
325*/
326struct lockInfo {
327 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000328 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000329 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000330 int nRef; /* Number of pointers to this structure */
331};
332
333/*
334** An instance of the following structure serves as the key used
335** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000336** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000337*/
338struct openKey {
339 dev_t dev; /* Device number */
340 ino_t ino; /* Inode number */
341};
342
343/*
344** An instance of the following structure is allocated for each open
345** inode. This structure keeps track of the number of locks on that
346** inode. If a close is attempted against an inode that is holding
347** locks, the close is deferred until all locks clear by adding the
348** file descriptor to be closed to the pending list.
349*/
350struct openCnt {
351 struct openKey key; /* The lookup key */
352 int nRef; /* Number of pointers to this structure */
353 int nLock; /* Number of outstanding locks */
354 int nPending; /* Number of pending close() operations */
355 int *aPending; /* Malloced space holding fd's awaiting a close() */
356};
357
358/*
drhf1a221e2006-01-15 17:27:17 +0000359** These hash tables map inodes and file descriptors (really, lockKey and
360** openKey structures) into lockInfo and openCnt structures. Access to
361** these hash tables must be protected by a mutex.
drhbbd42a62004-05-22 17:41:58 +0000362*/
drh17435752007-08-16 04:30:38 +0000363static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
364static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
drh5fdae772004-06-29 03:29:00 +0000365
drhbfe66312006-10-03 17:40:40 +0000366#ifdef SQLITE_ENABLE_LOCKING_STYLE
367/*
368** The locking styles are associated with the different file locking
369** capabilities supported by different file systems.
370**
371** POSIX locking style fully supports shared and exclusive byte-range locks
372** ADP locking only supports exclusive byte-range locks
373** FLOCK only supports a single file-global exclusive lock
374** DOTLOCK isn't a true locking style, it refers to the use of a special
375** file named the same as the database file with a '.lock' extension, this
376** can be used on file systems that do not offer any reliable file locking
377** NO locking means that no locking will be attempted, this is only used for
378** read-only file systems currently
379** UNSUPPORTED means that no locking will be attempted, this is only used for
380** file systems that are known to be unsupported
381*/
382typedef enum {
drhfd131da2007-08-07 17:13:03 +0000383 posixLockingStyle = 0, /* standard posix-advisory locks */
384 afpLockingStyle, /* use afp locks */
385 flockLockingStyle, /* use flock() */
386 dotlockLockingStyle, /* use <file>.lock files */
387 noLockingStyle, /* useful for read-only file system */
388 unsupportedLockingStyle /* indicates unsupported file system */
drhbfe66312006-10-03 17:40:40 +0000389} sqlite3LockingStyle;
390#endif /* SQLITE_ENABLE_LOCKING_STYLE */
391
danielk1977b4b47412007-08-17 15:53:36 +0000392static void enterMutex(){
393 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_GLOBAL));
394}
395static void leaveMutex(){
396 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_GLOBAL));
397}
398
drh5fdae772004-06-29 03:29:00 +0000399#ifdef SQLITE_UNIX_THREADS
400/*
401** This variable records whether or not threads can override each others
402** locks.
403**
404** 0: No. Threads cannot override each others locks.
405** 1: Yes. Threads can override each others locks.
406** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000407**
drh5062d3a2006-01-31 23:03:35 +0000408** On some systems, we know at compile-time if threads can override each
409** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
410** will be set appropriately. On other systems, we have to check at
411** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
412** undefined.
413**
drhf1a221e2006-01-15 17:27:17 +0000414** This variable normally has file scope only. But during testing, we make
415** it a global so that the test code can change its value in order to verify
416** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000417*/
drh5062d3a2006-01-31 23:03:35 +0000418#ifndef SQLITE_THREAD_OVERRIDE_LOCK
419# define SQLITE_THREAD_OVERRIDE_LOCK -1
420#endif
drh029b44b2006-01-15 00:13:15 +0000421#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000422int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000423#else
drh5062d3a2006-01-31 23:03:35 +0000424static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000425#endif
drh5fdae772004-06-29 03:29:00 +0000426
427/*
428** This structure holds information passed into individual test
429** threads by the testThreadLockingBehavior() routine.
430*/
431struct threadTestData {
432 int fd; /* File to be locked */
433 struct flock lock; /* The locking operation */
434 int result; /* Result of the locking operation */
435};
436
drh2b4b5962005-06-15 17:47:55 +0000437#ifdef SQLITE_LOCK_TRACE
438/*
439** Print out information about all locking operations.
440**
441** This routine is used for troubleshooting locks on multithreaded
442** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
443** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000444** turned off.
drh2b4b5962005-06-15 17:47:55 +0000445*/
446static int lockTrace(int fd, int op, struct flock *p){
447 char *zOpName, *zType;
448 int s;
449 int savedErrno;
450 if( op==F_GETLK ){
451 zOpName = "GETLK";
452 }else if( op==F_SETLK ){
453 zOpName = "SETLK";
454 }else{
455 s = fcntl(fd, op, p);
456 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
457 return s;
458 }
459 if( p->l_type==F_RDLCK ){
460 zType = "RDLCK";
461 }else if( p->l_type==F_WRLCK ){
462 zType = "WRLCK";
463 }else if( p->l_type==F_UNLCK ){
464 zType = "UNLCK";
465 }else{
466 assert( 0 );
467 }
468 assert( p->l_whence==SEEK_SET );
469 s = fcntl(fd, op, p);
470 savedErrno = errno;
471 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
472 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
473 (int)p->l_pid, s);
drhe2396a12007-03-29 20:19:58 +0000474 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
drh2b4b5962005-06-15 17:47:55 +0000475 struct flock l2;
476 l2 = *p;
477 fcntl(fd, F_GETLK, &l2);
478 if( l2.l_type==F_RDLCK ){
479 zType = "RDLCK";
480 }else if( l2.l_type==F_WRLCK ){
481 zType = "WRLCK";
482 }else if( l2.l_type==F_UNLCK ){
483 zType = "UNLCK";
484 }else{
485 assert( 0 );
486 }
487 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
488 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
489 }
490 errno = savedErrno;
491 return s;
492}
493#define fcntl lockTrace
494#endif /* SQLITE_LOCK_TRACE */
495
drh5fdae772004-06-29 03:29:00 +0000496/*
497** The testThreadLockingBehavior() routine launches two separate
498** threads on this routine. This routine attempts to lock a file
499** descriptor then returns. The success or failure of that attempt
500** allows the testThreadLockingBehavior() procedure to determine
501** whether or not threads can override each others locks.
502*/
503static void *threadLockingTest(void *pArg){
504 struct threadTestData *pData = (struct threadTestData*)pArg;
505 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
506 return pArg;
507}
508
509/*
510** This procedure attempts to determine whether or not threads
511** can override each others locks then sets the
512** threadsOverrideEachOthersLocks variable appropriately.
513*/
danielk19774d5238f2006-01-27 06:32:00 +0000514static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000515 int fd;
516 struct threadTestData d[2];
517 pthread_t t[2];
518
519 fd = dup(fd_orig);
520 if( fd<0 ) return;
521 memset(d, 0, sizeof(d));
522 d[0].fd = fd;
523 d[0].lock.l_type = F_RDLCK;
524 d[0].lock.l_len = 1;
525 d[0].lock.l_start = 0;
526 d[0].lock.l_whence = SEEK_SET;
527 d[1] = d[0];
528 d[1].lock.l_type = F_WRLCK;
529 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
530 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
531 pthread_join(t[0], 0);
532 pthread_join(t[1], 0);
533 close(fd);
534 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
535}
536#endif /* SQLITE_UNIX_THREADS */
537
drhbbd42a62004-05-22 17:41:58 +0000538/*
539** Release a lockInfo structure previously allocated by findLockInfo().
540*/
541static void releaseLockInfo(struct lockInfo *pLock){
drhbfe66312006-10-03 17:40:40 +0000542 if (pLock == NULL)
543 return;
drhbbd42a62004-05-22 17:41:58 +0000544 pLock->nRef--;
545 if( pLock->nRef==0 ){
546 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
drh17435752007-08-16 04:30:38 +0000547 sqlite3_free(pLock);
drhbbd42a62004-05-22 17:41:58 +0000548 }
549}
550
551/*
552** Release a openCnt structure previously allocated by findLockInfo().
553*/
554static void releaseOpenCnt(struct openCnt *pOpen){
drhbfe66312006-10-03 17:40:40 +0000555 if (pOpen == NULL)
556 return;
drhbbd42a62004-05-22 17:41:58 +0000557 pOpen->nRef--;
558 if( pOpen->nRef==0 ){
559 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
drh64b1bea2006-01-15 02:30:57 +0000560 free(pOpen->aPending);
drh17435752007-08-16 04:30:38 +0000561 sqlite3_free(pOpen);
drhbbd42a62004-05-22 17:41:58 +0000562 }
563}
564
drhbfe66312006-10-03 17:40:40 +0000565#ifdef SQLITE_ENABLE_LOCKING_STYLE
566/*
567** Tests a byte-range locking query to see if byte range locks are
568** supported, if not we fall back to dotlockLockingStyle.
569*/
570static sqlite3LockingStyle sqlite3TestLockingStyle(const char *filePath,
571 int fd) {
572 /* test byte-range lock using fcntl */
573 struct flock lockInfo;
574
575 lockInfo.l_len = 1;
576 lockInfo.l_start = 0;
577 lockInfo.l_whence = SEEK_SET;
578 lockInfo.l_type = F_RDLCK;
579
aswiftae0943b2007-01-31 23:37:07 +0000580 if (fcntl(fd, F_GETLK, &lockInfo) != -1) {
drhbfe66312006-10-03 17:40:40 +0000581 return posixLockingStyle;
582 }
583
584 /* testing for flock can give false positives. So if if the above test
585 ** fails, then we fall back to using dot-lock style locking.
586 */
587 return dotlockLockingStyle;
588}
589
590/*
591** Examines the f_fstypename entry in the statfs structure as returned by
592** stat() for the file system hosting the database file, assigns the
593** appropriate locking style based on it's value. These values and
594** assignments are based on Darwin/OSX behavior and have not been tested on
595** other systems.
596*/
597static sqlite3LockingStyle sqlite3DetectLockingStyle(const char *filePath,
598 int fd) {
599
600#ifdef SQLITE_FIXED_LOCKING_STYLE
601 return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
602#else
603 struct statfs fsInfo;
604
605 if (statfs(filePath, &fsInfo) == -1)
606 return sqlite3TestLockingStyle(filePath, fd);
607
608 if (fsInfo.f_flags & MNT_RDONLY)
609 return noLockingStyle;
610
611 if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
612 (!strcmp(fsInfo.f_fstypename, "ufs")) )
drhfd131da2007-08-07 17:13:03 +0000613 return posixLockingStyle;
drhbfe66312006-10-03 17:40:40 +0000614
615 if(!strcmp(fsInfo.f_fstypename, "afpfs"))
616 return afpLockingStyle;
617
618 if(!strcmp(fsInfo.f_fstypename, "nfs"))
619 return sqlite3TestLockingStyle(filePath, fd);
620
621 if(!strcmp(fsInfo.f_fstypename, "smbfs"))
622 return flockLockingStyle;
623
624 if(!strcmp(fsInfo.f_fstypename, "msdos"))
625 return dotlockLockingStyle;
626
627 if(!strcmp(fsInfo.f_fstypename, "webdav"))
628 return unsupportedLockingStyle;
629
630 return sqlite3TestLockingStyle(filePath, fd);
drh3b62b2f2007-06-08 18:27:03 +0000631#endif /* SQLITE_FIXED_LOCKING_STYLE */
drhbfe66312006-10-03 17:40:40 +0000632}
633
634#endif /* SQLITE_ENABLE_LOCKING_STYLE */
635
drhbbd42a62004-05-22 17:41:58 +0000636/*
637** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000638** describes that file descriptor. Create new ones if necessary. The
639** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000640**
641** Return the number of errors.
642*/
drh38f82712004-06-18 17:10:16 +0000643static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000644 int fd, /* The file descriptor used in the key */
645 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000646 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000647){
648 int rc;
649 struct lockKey key1;
650 struct openKey key2;
651 struct stat statbuf;
652 struct lockInfo *pLock;
653 struct openCnt *pOpen;
654 rc = fstat(fd, &statbuf);
655 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000656
drhbbd42a62004-05-22 17:41:58 +0000657 memset(&key1, 0, sizeof(key1));
658 key1.dev = statbuf.st_dev;
659 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000660#ifdef SQLITE_UNIX_THREADS
661 if( threadsOverrideEachOthersLocks<0 ){
662 testThreadLockingBehavior(fd);
663 }
664 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
665#endif
drhbbd42a62004-05-22 17:41:58 +0000666 memset(&key2, 0, sizeof(key2));
667 key2.dev = statbuf.st_dev;
668 key2.ino = statbuf.st_ino;
669 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
670 if( pLock==0 ){
671 struct lockInfo *pOld;
drh17435752007-08-16 04:30:38 +0000672 pLock = sqlite3_malloc( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000673 if( pLock==0 ){
674 rc = 1;
675 goto exit_findlockinfo;
676 }
drhbbd42a62004-05-22 17:41:58 +0000677 pLock->key = key1;
678 pLock->nRef = 1;
679 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000680 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000681 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
682 if( pOld!=0 ){
683 assert( pOld==pLock );
drh17435752007-08-16 04:30:38 +0000684 sqlite3_free(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000685 rc = 1;
686 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000687 }
688 }else{
689 pLock->nRef++;
690 }
691 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000692 if( ppOpen!=0 ){
693 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
drhbbd42a62004-05-22 17:41:58 +0000694 if( pOpen==0 ){
drh029b44b2006-01-15 00:13:15 +0000695 struct openCnt *pOld;
drh17435752007-08-16 04:30:38 +0000696 pOpen = sqlite3_malloc( sizeof(*pOpen) );
drh029b44b2006-01-15 00:13:15 +0000697 if( pOpen==0 ){
698 releaseLockInfo(pLock);
699 rc = 1;
700 goto exit_findlockinfo;
701 }
702 pOpen->key = key2;
703 pOpen->nRef = 1;
704 pOpen->nLock = 0;
705 pOpen->nPending = 0;
706 pOpen->aPending = 0;
707 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
708 if( pOld!=0 ){
709 assert( pOld==pOpen );
drh17435752007-08-16 04:30:38 +0000710 sqlite3_free(pOpen);
drh029b44b2006-01-15 00:13:15 +0000711 releaseLockInfo(pLock);
712 rc = 1;
713 goto exit_findlockinfo;
714 }
715 }else{
716 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000717 }
drh029b44b2006-01-15 00:13:15 +0000718 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000719 }
danielk1977441b09a2006-01-05 13:48:29 +0000720
721exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000722 return rc;
drhbbd42a62004-05-22 17:41:58 +0000723}
724
drh64b1bea2006-01-15 02:30:57 +0000725#ifdef SQLITE_DEBUG
726/*
727** Helper function for printing out trace information from debugging
728** binaries. This returns the string represetation of the supplied
729** integer lock-type.
730*/
731static const char *locktypeName(int locktype){
732 switch( locktype ){
733 case NO_LOCK: return "NONE";
734 case SHARED_LOCK: return "SHARED";
735 case RESERVED_LOCK: return "RESERVED";
736 case PENDING_LOCK: return "PENDING";
737 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
738 }
739 return "ERROR";
740}
741#endif
742
drhbbd42a62004-05-22 17:41:58 +0000743/*
drh029b44b2006-01-15 00:13:15 +0000744** If we are currently in a different thread than the thread that the
745** unixFile argument belongs to, then transfer ownership of the unixFile
746** over to the current thread.
747**
748** A unixFile is only owned by a thread on systems where one thread is
749** unable to override locks created by a different thread. RedHat9 is
750** an example of such a system.
751**
752** Ownership transfer is only allowed if the unixFile is currently unlocked.
753** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000754** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000755*/
756#ifdef SQLITE_UNIX_THREADS
757static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000758 int rc;
drh029b44b2006-01-15 00:13:15 +0000759 pthread_t hSelf;
760 if( threadsOverrideEachOthersLocks ){
761 /* Ownership transfers not needed on this system */
762 return SQLITE_OK;
763 }
764 hSelf = pthread_self();
765 if( pthread_equal(pFile->tid, hSelf) ){
766 /* We are still in the same thread */
drh4f0c5872007-03-26 22:05:01 +0000767 OSTRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000768 return SQLITE_OK;
769 }
770 if( pFile->locktype!=NO_LOCK ){
771 /* We cannot change ownership while we are holding a lock! */
772 return SQLITE_MISUSE;
773 }
drh4f0c5872007-03-26 22:05:01 +0000774 OSTRACE4("Transfer ownership of %d from %d to %d\n",
775 pFile->h, pFile->tid, hSelf);
drh029b44b2006-01-15 00:13:15 +0000776 pFile->tid = hSelf;
drhbfe66312006-10-03 17:40:40 +0000777 if (pFile->pLock != NULL) {
778 releaseLockInfo(pFile->pLock);
779 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
drh4f0c5872007-03-26 22:05:01 +0000780 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +0000781 locktypeName(pFile->locktype),
782 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
783 return rc;
784 } else {
785 return SQLITE_OK;
786 }
drh029b44b2006-01-15 00:13:15 +0000787}
788#else
drhf1a221e2006-01-15 17:27:17 +0000789 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +0000790# define transferOwnership(X) SQLITE_OK
791#endif
792
793/*
drhbbd42a62004-05-22 17:41:58 +0000794** Delete the named file
795*/
drh66560ad2006-01-06 14:32:19 +0000796int sqlite3UnixDelete(const char *zFilename){
danielk1977979f38e2007-03-27 16:19:51 +0000797 SimulateIOError(return SQLITE_IOERR_DELETE);
drhbbd42a62004-05-22 17:41:58 +0000798 unlink(zFilename);
799 return SQLITE_OK;
800}
801
802/*
803** Return TRUE if the named file exists.
804*/
drh66560ad2006-01-06 14:32:19 +0000805int sqlite3UnixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000806 return access(zFilename, 0)==0;
807}
808
drh9cbe6352005-11-29 03:13:21 +0000809/*
drhbbd42a62004-05-22 17:41:58 +0000810** Attempt to open a file for both reading and writing. If that
811** fails, try opening it read-only. If the file does not exist,
812** try to create it.
813**
814** On success, a handle for the open file is written to *id
815** and *pReadonly is set to 0 if the file was opened for reading and
816** writing or 1 if the file was opened read-only. The function returns
817** SQLITE_OK.
818**
819** On failure, the function returns SQLITE_CANTOPEN and leaves
820** *id and *pReadonly unchanged.
821*/
danielk1977b4b47412007-08-17 15:53:36 +0000822#if 0
drh66560ad2006-01-06 14:32:19 +0000823int sqlite3UnixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000824 const char *zFilename,
danielk197762079062007-08-15 17:08:46 +0000825 sqlite3_file **pId,
drhbbd42a62004-05-22 17:41:58 +0000826 int *pReadonly
827){
drhbfe66312006-10-03 17:40:40 +0000828 int h;
829
drh9cbe6352005-11-29 03:13:21 +0000830 assert( 0==*pId );
drhbfe66312006-10-03 17:40:40 +0000831 h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
832 SQLITE_DEFAULT_FILE_PERMISSIONS);
833 if( h<0 ){
drh6458e392004-07-20 01:14:13 +0000834#ifdef EISDIR
835 if( errno==EISDIR ){
836 return SQLITE_CANTOPEN;
837 }
838#endif
drhbfe66312006-10-03 17:40:40 +0000839 h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
840 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000841 return SQLITE_CANTOPEN;
842 }
843 *pReadonly = 1;
844 }else{
845 *pReadonly = 0;
846 }
danielk197762079062007-08-15 17:08:46 +0000847
848 return CRASH_TEST_OVERRIDE(
849 zFilename, pId, allocateUnixFile(h, pId, zFilename, 0)
850 );
drhbbd42a62004-05-22 17:41:58 +0000851}
852
853
854/*
855** Attempt to open a new file for exclusive access by this process.
856** The file will be opened for both reading and writing. To avoid
857** a potential security problem, we do not allow the file to have
858** previously existed. Nor do we allow the file to be a symbolic
859** link.
860**
861** If delFlag is true, then make arrangements to automatically delete
862** the file when it is closed.
863**
864** On success, write the file handle into *id and return SQLITE_OK.
865**
866** On failure, return SQLITE_CANTOPEN.
867*/
danielk197762079062007-08-15 17:08:46 +0000868int sqlite3UnixOpenExclusive(
869 const char *zFilename,
870 sqlite3_file **pId,
871 int delFlag
872){
drhbfe66312006-10-03 17:40:40 +0000873 int h;
drh9cbe6352005-11-29 03:13:21 +0000874
875 assert( 0==*pId );
drhbfe66312006-10-03 17:40:40 +0000876 h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000877 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
drh3f56e6e2007-03-15 01:16:47 +0000878 delFlag ? 0600 : SQLITE_DEFAULT_FILE_PERMISSIONS);
drhbfe66312006-10-03 17:40:40 +0000879 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000880 return SQLITE_CANTOPEN;
881 }
danielk197762079062007-08-15 17:08:46 +0000882 return CRASH_TEST_OVERRIDE(
883 zFilename, pId, allocateUnixFile(h, pId, zFilename, delFlag)
884 );
drhbbd42a62004-05-22 17:41:58 +0000885}
886
887/*
888** Attempt to open a new file for read-only access.
889**
890** On success, write the file handle into *id and return SQLITE_OK.
891**
892** On failure, return SQLITE_CANTOPEN.
893*/
danielk197762079062007-08-15 17:08:46 +0000894int sqlite3UnixOpenReadOnly(const char *zFilename, sqlite3_file **pId){
drhbfe66312006-10-03 17:40:40 +0000895 int h;
896
drh9cbe6352005-11-29 03:13:21 +0000897 assert( 0==*pId );
drhbfe66312006-10-03 17:40:40 +0000898 h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
899 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000900 return SQLITE_CANTOPEN;
901 }
danielk197762079062007-08-15 17:08:46 +0000902 return CRASH_TEST_OVERRIDE(
903 zFilename, pId, allocateUnixFile(h, pId, zFilename, 0)
904 );
drhbbd42a62004-05-22 17:41:58 +0000905}
danielk1977b4b47412007-08-17 15:53:36 +0000906#endif
drhbbd42a62004-05-22 17:41:58 +0000907
908/*
909** Attempt to open a file descriptor for the directory that contains a
910** file. This file descriptor can be used to fsync() the directory
911** in order to make sure the creation of a new file is actually written
912** to disk.
913**
914** This routine is only meaningful for Unix. It is a no-op under
915** windows since windows does not support hard links.
916**
drhbfe66312006-10-03 17:40:40 +0000917** If FULL_FSYNC is enabled, this function is not longer useful,
918** a FULL_FSYNC sync applies to all pending disk operations.
919**
drh9cbe6352005-11-29 03:13:21 +0000920** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000921** updated with the new directory file descriptor and SQLITE_OK is
922** returned.
923**
924** On failure, the function returns SQLITE_CANTOPEN and leaves
925** *id unchanged.
926*/
danielk197790949c22007-08-17 16:50:38 +0000927#if 0
drh9c06c952005-11-26 00:25:00 +0000928static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000929 OsFile *id,
930 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000931){
drhe78669b2007-06-29 12:04:26 +0000932 int h;
drh054889e2005-11-30 03:20:31 +0000933 unixFile *pFile = (unixFile*)id;
drhbb5f18d2007-04-06 18:23:17 +0000934 assert( pFile!=0 );
drh054889e2005-11-30 03:20:31 +0000935 SET_THREADID(pFile);
936 assert( pFile->dirfd<0 );
drhe78669b2007-06-29 12:04:26 +0000937 pFile->dirfd = h = open(zDirname, O_RDONLY|O_BINARY, 0);
938 if( h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000939 return SQLITE_CANTOPEN;
940 }
drhe78669b2007-06-29 12:04:26 +0000941#ifdef FD_CLOEXEC
942 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
943#endif
944 OSTRACE3("OPENDIR %-3d %s\n", h, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000945 return SQLITE_OK;
946}
danielk197790949c22007-08-17 16:50:38 +0000947#endif
drhbbd42a62004-05-22 17:41:58 +0000948
949/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000950** Check that a given pathname is a directory and is writable
951**
952*/
drh66560ad2006-01-06 14:32:19 +0000953int sqlite3UnixIsDirWritable(char *zBuf){
drh9c06c952005-11-26 00:25:00 +0000954#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000955 struct stat buf;
956 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000957 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000958 if( stat(zBuf, &buf) ) return 0;
959 if( !S_ISDIR(buf.st_mode) ) return 0;
960 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000961#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000962 return 1;
963}
964
965/*
drhb912b282006-03-23 22:42:20 +0000966** Seek to the offset in id->offset then read cnt bytes into pBuf.
967** Return the number of bytes actually read. Update the offset.
968*/
danielk197762079062007-08-15 17:08:46 +0000969static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +0000970 int got;
drh8ebf6702007-02-06 11:11:08 +0000971 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +0000972 TIMER_START;
drh8350a212007-03-22 15:22:06 +0000973#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +0000974 got = pread(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +0000975 SimulateIOError( got = -1 );
drh8350a212007-03-22 15:22:06 +0000976#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +0000977 got = pread64(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +0000978 SimulateIOError( got = -1 );
drhb912b282006-03-23 22:42:20 +0000979#else
danielk197762079062007-08-15 17:08:46 +0000980 newOffset = lseek(id->h, offset, SEEK_SET);
drhbb5f18d2007-04-06 18:23:17 +0000981 SimulateIOError( newOffset-- );
danielk197762079062007-08-15 17:08:46 +0000982 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +0000983 return -1;
984 }
drhb912b282006-03-23 22:42:20 +0000985 got = read(id->h, pBuf, cnt);
986#endif
drh15d00c42007-02-27 02:01:14 +0000987 TIMER_END;
drh4f0c5872007-03-26 22:05:01 +0000988 OSTRACE5("READ %-3d %5d %7lld %d\n", id->h, got, id->offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +0000989 return got;
990}
991
992/*
drhbbd42a62004-05-22 17:41:58 +0000993** Read data from a file into a buffer. Return SQLITE_OK if all
994** bytes were read successfully and SQLITE_IOERR if anything goes
995** wrong.
996*/
danielk197762079062007-08-15 17:08:46 +0000997static int unixRead(
998 sqlite3_file *id,
999 void *pBuf,
1000 int amt,
1001 sqlite3_int64 offset
1002){
drhbbd42a62004-05-22 17:41:58 +00001003 int got;
drh9cbe6352005-11-29 03:13:21 +00001004 assert( id );
danielk197762079062007-08-15 17:08:46 +00001005 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +00001006 if( got==amt ){
1007 return SQLITE_OK;
drh4ac285a2006-09-15 07:28:50 +00001008 }else if( got<0 ){
1009 return SQLITE_IOERR_READ;
drhbbd42a62004-05-22 17:41:58 +00001010 }else{
drhbafda092007-01-03 23:36:22 +00001011 memset(&((char*)pBuf)[got], 0, amt-got);
drh4ac285a2006-09-15 07:28:50 +00001012 return SQLITE_IOERR_SHORT_READ;
drhbbd42a62004-05-22 17:41:58 +00001013 }
1014}
1015
1016/*
drhb912b282006-03-23 22:42:20 +00001017** Seek to the offset in id->offset then read cnt bytes into pBuf.
1018** Return the number of bytes actually read. Update the offset.
1019*/
danielk197762079062007-08-15 17:08:46 +00001020static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +00001021 int got;
drh8ebf6702007-02-06 11:11:08 +00001022 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +00001023 TIMER_START;
drh8350a212007-03-22 15:22:06 +00001024#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +00001025 got = pwrite(id->h, pBuf, cnt, offset);
drh8350a212007-03-22 15:22:06 +00001026#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +00001027 got = pwrite64(id->h, pBuf, cnt, offset);
drhb912b282006-03-23 22:42:20 +00001028#else
danielk197762079062007-08-15 17:08:46 +00001029 newOffset = lseek(id->h, offset, SEEK_SET);
1030 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +00001031 return -1;
1032 }
drhb912b282006-03-23 22:42:20 +00001033 got = write(id->h, pBuf, cnt);
1034#endif
drh15d00c42007-02-27 02:01:14 +00001035 TIMER_END;
danielk197762079062007-08-15 17:08:46 +00001036 OSTRACE5("WRITE %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +00001037 return got;
1038}
1039
1040
1041/*
drhbbd42a62004-05-22 17:41:58 +00001042** Write data from a buffer into a file. Return SQLITE_OK on success
1043** or some other error code on failure.
1044*/
danielk197762079062007-08-15 17:08:46 +00001045static int unixWrite(
1046 sqlite3_file *id,
1047 const void *pBuf,
1048 int amt,
1049 sqlite3_int64 offset
1050){
drhbbd42a62004-05-22 17:41:58 +00001051 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +00001052 assert( id );
drh4c7f9412005-02-03 00:29:47 +00001053 assert( amt>0 );
danielk197762079062007-08-15 17:08:46 +00001054 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +00001055 amt -= wrote;
danielk197762079062007-08-15 17:08:46 +00001056 offset += wrote;
drhbbd42a62004-05-22 17:41:58 +00001057 pBuf = &((char*)pBuf)[wrote];
1058 }
drh59685932006-09-14 13:47:11 +00001059 SimulateIOError(( wrote=(-1), amt=1 ));
1060 SimulateDiskfullError(( wrote=0, amt=1 ));
drhbbd42a62004-05-22 17:41:58 +00001061 if( amt>0 ){
drh59685932006-09-14 13:47:11 +00001062 if( wrote<0 ){
drh4ac285a2006-09-15 07:28:50 +00001063 return SQLITE_IOERR_WRITE;
drh59685932006-09-14 13:47:11 +00001064 }else{
1065 return SQLITE_FULL;
1066 }
drhbbd42a62004-05-22 17:41:58 +00001067 }
1068 return SQLITE_OK;
1069}
1070
drhb851b2c2005-03-10 14:11:12 +00001071#ifdef SQLITE_TEST
1072/*
1073** Count the number of fullsyncs and normal syncs. This is used to test
1074** that syncs and fullsyncs are occuring at the right times.
1075*/
1076int sqlite3_sync_count = 0;
1077int sqlite3_fullsync_count = 0;
1078#endif
1079
drhf2f23912005-10-05 10:29:36 +00001080/*
1081** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
1082** Otherwise use fsync() in its place.
1083*/
1084#ifndef HAVE_FDATASYNC
1085# define fdatasync fsync
1086#endif
1087
drhac530b12006-02-11 01:25:50 +00001088/*
1089** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
1090** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
1091** only available on Mac OS X. But that could change.
1092*/
1093#ifdef F_FULLFSYNC
1094# define HAVE_FULLFSYNC 1
1095#else
1096# define HAVE_FULLFSYNC 0
1097#endif
1098
drhb851b2c2005-03-10 14:11:12 +00001099
drhbbd42a62004-05-22 17:41:58 +00001100/*
drhdd809b02004-07-17 21:44:57 +00001101** The fsync() system call does not work as advertised on many
1102** unix systems. The following procedure is an attempt to make
1103** it work better.
drh1398ad32005-01-19 23:24:50 +00001104**
1105** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
1106** for testing when we want to run through the test suite quickly.
1107** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
1108** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
1109** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +00001110*/
drheb796a72005-09-08 12:38:41 +00001111static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +00001112 int rc;
drhb851b2c2005-03-10 14:11:12 +00001113
1114 /* Record the number of times that we do a normal fsync() and
1115 ** FULLSYNC. This is used during testing to verify that this procedure
1116 ** gets called with the correct arguments.
1117 */
1118#ifdef SQLITE_TEST
1119 if( fullSync ) sqlite3_fullsync_count++;
1120 sqlite3_sync_count++;
1121#endif
1122
1123 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
1124 ** no-op
1125 */
1126#ifdef SQLITE_NO_SYNC
1127 rc = SQLITE_OK;
1128#else
1129
drhac530b12006-02-11 01:25:50 +00001130#if HAVE_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +00001131 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +00001132 rc = fcntl(fd, F_FULLFSYNC, 0);
aswiftae0943b2007-01-31 23:37:07 +00001133 }else{
1134 rc = 1;
1135 }
1136 /* If the FULLFSYNC failed, fall back to attempting an fsync().
1137 * It shouldn't be possible for fullfsync to fail on the local
1138 * file system (on OSX), so failure indicates that FULLFSYNC
1139 * isn't supported for this file system. So, attempt an fsync
1140 * and (for now) ignore the overhead of a superfluous fcntl call.
1141 * It'd be better to detect fullfsync support once and avoid
1142 * the fcntl call every time sync is called.
1143 */
1144 if( rc ) rc = fsync(fd);
1145
1146#else
drheb796a72005-09-08 12:38:41 +00001147 if( dataOnly ){
1148 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +00001149 }else{
drheb796a72005-09-08 12:38:41 +00001150 rc = fsync(fd);
1151 }
aswiftae0943b2007-01-31 23:37:07 +00001152#endif /* HAVE_FULLFSYNC */
drhb851b2c2005-03-10 14:11:12 +00001153#endif /* defined(SQLITE_NO_SYNC) */
1154
drhdd809b02004-07-17 21:44:57 +00001155 return rc;
1156}
1157
1158/*
drhbbd42a62004-05-22 17:41:58 +00001159** Make sure all writes to a particular file are committed to disk.
1160**
drheb796a72005-09-08 12:38:41 +00001161** If dataOnly==0 then both the file itself and its metadata (file
1162** size, access time, etc) are synced. If dataOnly!=0 then only the
1163** file data is synced.
1164**
drhbbd42a62004-05-22 17:41:58 +00001165** Under Unix, also make sure that the directory entry for the file
1166** has been created by fsync-ing the directory that contains the file.
1167** If we do not do this and we encounter a power failure, the directory
1168** entry for the journal might not exist after we reboot. The next
1169** SQLite to access the file will not know that the journal exists (because
1170** the directory entry for the journal was never created) and the transaction
1171** will not roll back - possibly leading to database corruption.
1172*/
danielk197790949c22007-08-17 16:50:38 +00001173static int unixSync(sqlite3_file *id, int flags){
drh59685932006-09-14 13:47:11 +00001174 int rc;
drh054889e2005-11-30 03:20:31 +00001175 unixFile *pFile = (unixFile*)id;
danielk197790949c22007-08-17 16:50:38 +00001176
1177 int isDataOnly = (flags & SQLITE_SYNC_DATAONLY);
1178 int isFullsync = (flags & SQLITE_SYNC_FULL);
1179
drh054889e2005-11-30 03:20:31 +00001180 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001181 OSTRACE2("SYNC %-3d\n", pFile->h);
danielk197790949c22007-08-17 16:50:38 +00001182 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
drh59685932006-09-14 13:47:11 +00001183 SimulateIOError( rc=1 );
1184 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001185 return SQLITE_IOERR_FSYNC;
drhbbd42a62004-05-22 17:41:58 +00001186 }
drh054889e2005-11-30 03:20:31 +00001187 if( pFile->dirfd>=0 ){
drh4f0c5872007-03-26 22:05:01 +00001188 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
danielk197790949c22007-08-17 16:50:38 +00001189 HAVE_FULLFSYNC, isFullsync);
danielk1977d7c03f72005-11-25 10:38:22 +00001190#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001191 /* The directory sync is only attempted if full_fsync is
1192 ** turned off or unavailable. If a full_fsync occurred above,
1193 ** then the directory sync is superfluous.
1194 */
danielk197790949c22007-08-17 16:50:38 +00001195 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
drhac530b12006-02-11 01:25:50 +00001196 /*
1197 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001198 ** errors when applied to directories on certain file systems.
1199 ** A failed directory sync is not a big deal. So it seems
1200 ** better to ignore the error. Ticket #1657
1201 */
1202 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001203 }
danielk1977d7c03f72005-11-25 10:38:22 +00001204#endif
drh054889e2005-11-30 03:20:31 +00001205 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1206 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001207 }
drha2854222004-06-17 19:04:17 +00001208 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001209}
1210
1211/*
danielk1977962398d2004-06-14 09:35:16 +00001212** Sync the directory zDirname. This is a no-op on operating systems other
1213** than UNIX.
drhb851b2c2005-03-10 14:11:12 +00001214**
1215** This is used to make sure the master journal file has truely been deleted
1216** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +00001217** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +00001218*/
drh66560ad2006-01-06 14:32:19 +00001219int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +00001220#ifdef SQLITE_DISABLE_DIRSYNC
1221 return SQLITE_OK;
1222#else
danielk1977962398d2004-06-14 09:35:16 +00001223 int fd;
1224 int r;
drh8e855772005-05-17 11:25:31 +00001225 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh4f0c5872007-03-26 22:05:01 +00001226 OSTRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001227 if( fd<0 ){
1228 return SQLITE_CANTOPEN;
1229 }
1230 r = fsync(fd);
1231 close(fd);
drh59685932006-09-14 13:47:11 +00001232 SimulateIOError( r=1 );
1233 if( r ){
drh4ac285a2006-09-15 07:28:50 +00001234 return SQLITE_IOERR_DIR_FSYNC;
drh59685932006-09-14 13:47:11 +00001235 }else{
1236 return SQLITE_OK;
1237 }
danielk1977d7c03f72005-11-25 10:38:22 +00001238#endif
danielk1977962398d2004-06-14 09:35:16 +00001239}
1240
1241/*
drhbbd42a62004-05-22 17:41:58 +00001242** Truncate an open file to a specified size
1243*/
danielk197762079062007-08-15 17:08:46 +00001244static int unixTruncate(sqlite3_file *id, i64 nByte){
drh59685932006-09-14 13:47:11 +00001245 int rc;
drh9cbe6352005-11-29 03:13:21 +00001246 assert( id );
drh63fff5f2007-06-19 10:50:38 +00001247 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
drh59685932006-09-14 13:47:11 +00001248 SimulateIOError( rc=1 );
1249 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001250 return SQLITE_IOERR_TRUNCATE;
drh59685932006-09-14 13:47:11 +00001251 }else{
1252 return SQLITE_OK;
1253 }
drhbbd42a62004-05-22 17:41:58 +00001254}
1255
1256/*
1257** Determine the current size of a file in bytes
1258*/
danielk197762079062007-08-15 17:08:46 +00001259static int unixFileSize(sqlite3_file *id, i64 *pSize){
drh59685932006-09-14 13:47:11 +00001260 int rc;
drhbbd42a62004-05-22 17:41:58 +00001261 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001262 assert( id );
drh59685932006-09-14 13:47:11 +00001263 rc = fstat(((unixFile*)id)->h, &buf);
1264 SimulateIOError( rc=1 );
1265 if( rc!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001266 return SQLITE_IOERR_FSTAT;
drhbbd42a62004-05-22 17:41:58 +00001267 }
1268 *pSize = buf.st_size;
1269 return SQLITE_OK;
1270}
1271
danielk19779a1d0ab2004-06-01 14:09:28 +00001272/*
danielk197713adf8a2004-06-03 16:08:41 +00001273** This routine checks if there is a RESERVED lock held on the specified
1274** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001275** non-zero. If the file is unlocked or holds only SHARED locks, then
1276** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001277*/
danielk197762079062007-08-15 17:08:46 +00001278static int unixCheckReservedLock(sqlite3_file *id){
danielk197713adf8a2004-06-03 16:08:41 +00001279 int r = 0;
drh054889e2005-11-30 03:20:31 +00001280 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001281
drh054889e2005-11-30 03:20:31 +00001282 assert( pFile );
danielk1977b4b47412007-08-17 15:53:36 +00001283 enterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001284
1285 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001286 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001287 r = 1;
1288 }
1289
drh2ac3ee92004-06-07 16:27:46 +00001290 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001291 */
1292 if( !r ){
1293 struct flock lock;
1294 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001295 lock.l_start = RESERVED_BYTE;
1296 lock.l_len = 1;
1297 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001298 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001299 if( lock.l_type!=F_UNLCK ){
1300 r = 1;
1301 }
1302 }
1303
danielk1977b4b47412007-08-17 15:53:36 +00001304 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001305 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001306
1307 return r;
1308}
1309
1310/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001311** Lock the file with the lock specified by parameter locktype - one
1312** of the following:
1313**
drh2ac3ee92004-06-07 16:27:46 +00001314** (1) SHARED_LOCK
1315** (2) RESERVED_LOCK
1316** (3) PENDING_LOCK
1317** (4) EXCLUSIVE_LOCK
1318**
drhb3e04342004-06-08 00:47:47 +00001319** Sometimes when requesting one lock state, additional lock states
1320** are inserted in between. The locking might fail on one of the later
1321** transitions leaving the lock state different from what it started but
1322** still short of its goal. The following chart shows the allowed
1323** transitions and the inserted intermediate states:
1324**
1325** UNLOCKED -> SHARED
1326** SHARED -> RESERVED
1327** SHARED -> (PENDING) -> EXCLUSIVE
1328** RESERVED -> (PENDING) -> EXCLUSIVE
1329** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001330**
drha6abd042004-06-09 17:37:22 +00001331** This routine will only increase a lock. Use the sqlite3OsUnlock()
1332** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001333*/
danielk197762079062007-08-15 17:08:46 +00001334static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001335 /* The following describes the implementation of the various locks and
1336 ** lock transitions in terms of the POSIX advisory shared and exclusive
1337 ** lock primitives (called read-locks and write-locks below, to avoid
1338 ** confusion with SQLite lock names). The algorithms are complicated
1339 ** slightly in order to be compatible with windows systems simultaneously
1340 ** accessing the same database file, in case that is ever required.
1341 **
1342 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1343 ** byte', each single bytes at well known offsets, and the 'shared byte
1344 ** range', a range of 510 bytes at a well known offset.
1345 **
1346 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1347 ** byte'. If this is successful, a random byte from the 'shared byte
1348 ** range' is read-locked and the lock on the 'pending byte' released.
1349 **
danielk197790ba3bd2004-06-25 08:32:25 +00001350 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1351 ** A RESERVED lock is implemented by grabbing a write-lock on the
1352 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001353 **
1354 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001355 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1356 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1357 ** obtained, but existing SHARED locks are allowed to persist. A process
1358 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1359 ** This property is used by the algorithm for rolling back a journal file
1360 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001361 **
danielk197790ba3bd2004-06-25 08:32:25 +00001362 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1363 ** implemented by obtaining a write-lock on the entire 'shared byte
1364 ** range'. Since all other locks require a read-lock on one of the bytes
1365 ** within this range, this ensures that no other locks are held on the
1366 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001367 **
1368 ** The reason a single byte cannot be used instead of the 'shared byte
1369 ** range' is that some versions of windows do not support read-locks. By
1370 ** locking a random byte from a range, concurrent SHARED locks may exist
1371 ** even if the locking primitive used is always a write-lock.
1372 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001373 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001374 unixFile *pFile = (unixFile*)id;
1375 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001376 struct flock lock;
1377 int s;
1378
drh054889e2005-11-30 03:20:31 +00001379 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001380 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001381 locktypeName(locktype), locktypeName(pFile->locktype),
1382 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001383
1384 /* If there is already a lock of this type or more restrictive on the
1385 ** OsFile, do nothing. Don't use the end_lock: exit path, as
danielk1977b4b47412007-08-17 15:53:36 +00001386 ** enterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001387 */
drh054889e2005-11-30 03:20:31 +00001388 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001389 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001390 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001391 return SQLITE_OK;
1392 }
1393
drhb3e04342004-06-08 00:47:47 +00001394 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001395 */
drh054889e2005-11-30 03:20:31 +00001396 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001397 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001398 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001399
drh054889e2005-11-30 03:20:31 +00001400 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001401 */
danielk1977b4b47412007-08-17 15:53:36 +00001402 enterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001403
drh029b44b2006-01-15 00:13:15 +00001404 /* Make sure the current thread owns the pFile.
1405 */
1406 rc = transferOwnership(pFile);
1407 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001408 leaveMutex();
drh029b44b2006-01-15 00:13:15 +00001409 return rc;
1410 }
drh64b1bea2006-01-15 02:30:57 +00001411 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001412
danielk19779a1d0ab2004-06-01 14:09:28 +00001413 /* If some thread using this PID has a lock via a different OsFile*
1414 ** handle that precludes the requested lock, return BUSY.
1415 */
drh054889e2005-11-30 03:20:31 +00001416 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001417 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001418 ){
1419 rc = SQLITE_BUSY;
1420 goto end_lock;
1421 }
1422
1423 /* If a SHARED lock is requested, and some thread using this PID already
1424 ** has a SHARED or RESERVED lock, then increment reference counts and
1425 ** return SQLITE_OK.
1426 */
1427 if( locktype==SHARED_LOCK &&
1428 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1429 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001430 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001431 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001432 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001433 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001434 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001435 goto end_lock;
1436 }
1437
danielk197713adf8a2004-06-03 16:08:41 +00001438 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001439
danielk19779a1d0ab2004-06-01 14:09:28 +00001440 lock.l_whence = SEEK_SET;
1441
drh3cde3bb2004-06-12 02:17:14 +00001442 /* A PENDING lock is needed before acquiring a SHARED lock and before
1443 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1444 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001445 */
drh3cde3bb2004-06-12 02:17:14 +00001446 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001447 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001448 ){
danielk1977489468c2004-06-28 08:25:47 +00001449 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001450 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001451 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001452 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001453 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1454 goto end_lock;
1455 }
drh3cde3bb2004-06-12 02:17:14 +00001456 }
1457
1458
1459 /* If control gets to this point, then actually go ahead and make
1460 ** operating system calls for the specified lock.
1461 */
1462 if( locktype==SHARED_LOCK ){
1463 assert( pLock->cnt==0 );
1464 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001465
drh2ac3ee92004-06-07 16:27:46 +00001466 /* Now get the read-lock */
1467 lock.l_start = SHARED_FIRST;
1468 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001469 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001470
1471 /* Drop the temporary PENDING lock */
1472 lock.l_start = PENDING_BYTE;
1473 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001474 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001475 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001476 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001477 goto end_lock;
1478 }
drhe2396a12007-03-29 20:19:58 +00001479 if( s==(-1) ){
drhbbd42a62004-05-22 17:41:58 +00001480 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1481 }else{
drh054889e2005-11-30 03:20:31 +00001482 pFile->locktype = SHARED_LOCK;
1483 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001484 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001485 }
drh3cde3bb2004-06-12 02:17:14 +00001486 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1487 /* We are trying for an exclusive lock but another thread in this
1488 ** same process is still holding a shared lock. */
1489 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001490 }else{
drh3cde3bb2004-06-12 02:17:14 +00001491 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001492 ** assumed that there is a SHARED or greater lock on the file
1493 ** already.
1494 */
drh054889e2005-11-30 03:20:31 +00001495 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001496 lock.l_type = F_WRLCK;
1497 switch( locktype ){
1498 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001499 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001500 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001501 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001502 lock.l_start = SHARED_FIRST;
1503 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001504 break;
1505 default:
1506 assert(0);
1507 }
drh054889e2005-11-30 03:20:31 +00001508 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001509 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001510 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1511 }
drhbbd42a62004-05-22 17:41:58 +00001512 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001513
danielk1977ecb2a962004-06-02 06:30:16 +00001514 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001515 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001516 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001517 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001518 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001519 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001520 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001521
1522end_lock:
danielk1977b4b47412007-08-17 15:53:36 +00001523 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001524 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001525 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001526 return rc;
1527}
1528
1529/*
drh054889e2005-11-30 03:20:31 +00001530** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001531** must be either NO_LOCK or SHARED_LOCK.
1532**
1533** If the locking level of the file descriptor is already at or below
1534** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001535*/
danielk197762079062007-08-15 17:08:46 +00001536static int unixUnlock(sqlite3_file *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001537 struct lockInfo *pLock;
1538 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001539 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001540 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001541
drh054889e2005-11-30 03:20:31 +00001542 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001543 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001544 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001545
1546 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001547 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001548 return SQLITE_OK;
1549 }
drhf1a221e2006-01-15 17:27:17 +00001550 if( CHECK_THREADID(pFile) ){
1551 return SQLITE_MISUSE;
1552 }
danielk1977b4b47412007-08-17 15:53:36 +00001553 enterMutex();
drh054889e2005-11-30 03:20:31 +00001554 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001555 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001556 if( pFile->locktype>SHARED_LOCK ){
1557 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001558 if( locktype==SHARED_LOCK ){
1559 lock.l_type = F_RDLCK;
1560 lock.l_whence = SEEK_SET;
1561 lock.l_start = SHARED_FIRST;
1562 lock.l_len = SHARED_SIZE;
drhe2396a12007-03-29 20:19:58 +00001563 if( fcntl(pFile->h, F_SETLK, &lock)==(-1) ){
drh9c105bb2004-10-02 20:38:28 +00001564 /* This should never happen */
drh4ac285a2006-09-15 07:28:50 +00001565 rc = SQLITE_IOERR_RDLOCK;
drh9c105bb2004-10-02 20:38:28 +00001566 }
1567 }
drhbbd42a62004-05-22 17:41:58 +00001568 lock.l_type = F_UNLCK;
1569 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001570 lock.l_start = PENDING_BYTE;
1571 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drhe2396a12007-03-29 20:19:58 +00001572 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001573 pLock->locktype = SHARED_LOCK;
1574 }else{
drh4ac285a2006-09-15 07:28:50 +00001575 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001576 }
drhbbd42a62004-05-22 17:41:58 +00001577 }
drha6abd042004-06-09 17:37:22 +00001578 if( locktype==NO_LOCK ){
1579 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001580
drha6abd042004-06-09 17:37:22 +00001581 /* Decrement the shared lock counter. Release the lock using an
1582 ** OS call only when all threads in this same process have released
1583 ** the lock.
1584 */
1585 pLock->cnt--;
1586 if( pLock->cnt==0 ){
1587 lock.l_type = F_UNLCK;
1588 lock.l_whence = SEEK_SET;
1589 lock.l_start = lock.l_len = 0L;
drhe2396a12007-03-29 20:19:58 +00001590 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001591 pLock->locktype = NO_LOCK;
1592 }else{
drh4ac285a2006-09-15 07:28:50 +00001593 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001594 }
drha6abd042004-06-09 17:37:22 +00001595 }
1596
drhbbd42a62004-05-22 17:41:58 +00001597 /* Decrement the count of locks against this same file. When the
1598 ** count reaches zero, close any other file descriptors whose close
1599 ** was deferred because of outstanding locks.
1600 */
drh054889e2005-11-30 03:20:31 +00001601 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001602 pOpen->nLock--;
1603 assert( pOpen->nLock>=0 );
1604 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1605 int i;
1606 for(i=0; i<pOpen->nPending; i++){
1607 close(pOpen->aPending[i]);
1608 }
drh64b1bea2006-01-15 02:30:57 +00001609 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001610 pOpen->nPending = 0;
1611 pOpen->aPending = 0;
1612 }
1613 }
danielk1977b4b47412007-08-17 15:53:36 +00001614 leaveMutex();
drh054889e2005-11-30 03:20:31 +00001615 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001616 return rc;
drhbbd42a62004-05-22 17:41:58 +00001617}
1618
1619/*
danielk1977e3026632004-06-22 11:29:02 +00001620** Close a file.
1621*/
danielk197762079062007-08-15 17:08:46 +00001622static int unixClose(sqlite3_file *id){
1623 unixFile *pFile = (unixFile *)id;
1624 if( !pFile ) return SQLITE_OK;
1625 unixUnlock(id, NO_LOCK);
1626 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1627 pFile->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00001628 enterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001629
danielk197762079062007-08-15 17:08:46 +00001630 if( pFile->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001631 /* If there are outstanding locks, do not actually close the file just
1632 ** yet because that would clear those locks. Instead, add the file
1633 ** descriptor to pOpen->aPending. It will be automatically closed when
1634 ** the last lock is cleared.
1635 */
1636 int *aNew;
danielk197762079062007-08-15 17:08:46 +00001637 struct openCnt *pOpen = pFile->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001638 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001639 if( aNew==0 ){
1640 /* If a malloc fails, just leak the file descriptor */
1641 }else{
1642 pOpen->aPending = aNew;
danielk197762079062007-08-15 17:08:46 +00001643 pOpen->aPending[pOpen->nPending] = pFile->h;
drhad81e872005-08-21 21:45:01 +00001644 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001645 }
1646 }else{
1647 /* There are no outstanding locks so we can close the file immediately */
danielk197762079062007-08-15 17:08:46 +00001648 close(pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001649 }
danielk197762079062007-08-15 17:08:46 +00001650 releaseLockInfo(pFile->pLock);
1651 releaseOpenCnt(pFile->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001652
danielk1977b4b47412007-08-17 15:53:36 +00001653 leaveMutex();
danielk197762079062007-08-15 17:08:46 +00001654 pFile->isOpen = 0;
1655 OSTRACE2("CLOSE %-3d\n", pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001656 OpenCounter(-1);
danielk1977b4b47412007-08-17 15:53:36 +00001657 memset(pFile, 0, sizeof(unixFile));
drh02afc862006-01-20 18:10:57 +00001658 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001659}
1660
drhbfe66312006-10-03 17:40:40 +00001661
1662#ifdef SQLITE_ENABLE_LOCKING_STYLE
1663#pragma mark AFP Support
1664
1665/*
1666 ** The afpLockingContext structure contains all afp lock specific state
1667 */
1668typedef struct afpLockingContext afpLockingContext;
1669struct afpLockingContext {
1670 unsigned long long sharedLockByte;
1671 char *filePath;
1672};
1673
1674struct ByteRangeLockPB2
1675{
1676 unsigned long long offset; /* offset to first byte to lock */
1677 unsigned long long length; /* nbr of bytes to lock */
1678 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
1679 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
1680 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
1681 int fd; /* file desc to assoc this lock with */
1682};
1683
drhfd131da2007-08-07 17:13:03 +00001684#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00001685
1686/* return 0 on success, 1 on failure. To match the behavior of the
1687 normal posix file locking (used in unixLock for example), we should
1688 provide 'richer' return codes - specifically to differentiate between
1689 'file busy' and 'file system error' results */
1690static int _AFPFSSetLock(const char *path, int fd, unsigned long long offset,
1691 unsigned long long length, int setLockFlag)
1692{
drhfd131da2007-08-07 17:13:03 +00001693 struct ByteRangeLockPB2 pb;
drhbfe66312006-10-03 17:40:40 +00001694 int err;
1695
1696 pb.unLockFlag = setLockFlag ? 0 : 1;
1697 pb.startEndFlag = 0;
1698 pb.offset = offset;
1699 pb.length = length;
1700 pb.fd = fd;
drh4f0c5872007-03-26 22:05:01 +00001701 OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
drhbfe66312006-10-03 17:40:40 +00001702 (setLockFlag?"ON":"OFF"), fd, offset, length);
1703 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
1704 if ( err==-1 ) {
drh4f0c5872007-03-26 22:05:01 +00001705 OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno,
drhbfe66312006-10-03 17:40:40 +00001706 strerror(errno));
drh3b62b2f2007-06-08 18:27:03 +00001707 return 1; /* error */
drhbfe66312006-10-03 17:40:40 +00001708 } else {
1709 return 0;
1710 }
1711}
1712
1713/*
1714 ** This routine checks if there is a RESERVED lock held on the specified
1715 ** file by this or any other process. If such a lock is held, return
1716 ** non-zero. If the file is unlocked or holds only SHARED locks, then
1717 ** return zero.
1718 */
1719static int afpUnixCheckReservedLock(OsFile *id){
1720 int r = 0;
1721 unixFile *pFile = (unixFile*)id;
1722
1723 assert( pFile );
1724 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1725
1726 /* Check if a thread in this process holds such a lock */
1727 if( pFile->locktype>SHARED_LOCK ){
1728 r = 1;
1729 }
1730
1731 /* Otherwise see if some other process holds it.
1732 */
1733 if ( !r ) {
drh3b62b2f2007-06-08 18:27:03 +00001734 /* lock the byte */
drhbfe66312006-10-03 17:40:40 +00001735 int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1736 if (failed) {
1737 /* if we failed to get the lock then someone else must have it */
1738 r = 1;
1739 } else {
1740 /* if we succeeded in taking the reserved lock, unlock it to restore
1741 ** the original state */
1742 _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
1743 }
1744 }
drh4f0c5872007-03-26 22:05:01 +00001745 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
drhbfe66312006-10-03 17:40:40 +00001746
1747 return r;
1748}
1749
1750/* AFP-style locking following the behavior of unixLock, see the unixLock
1751** function comments for details of lock management. */
1752static int afpUnixLock(OsFile *id, int locktype)
1753{
1754 int rc = SQLITE_OK;
1755 unixFile *pFile = (unixFile*)id;
1756 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1757 int gotPendingLock = 0;
1758
1759 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001760 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001761 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
1762 /* If there is already a lock of this type or more restrictive on the
1763 ** OsFile, do nothing. Don't use the afp_end_lock: exit path, as
danielk1977b4b47412007-08-17 15:53:36 +00001764 ** enterMutex() hasn't been called yet.
drhbfe66312006-10-03 17:40:40 +00001765 */
1766 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001767 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001768 locktypeName(locktype));
1769 return SQLITE_OK;
1770 }
1771
1772 /* Make sure the locking sequence is correct
1773 */
1774 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
1775 assert( locktype!=PENDING_LOCK );
1776 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1777
1778 /* This mutex is needed because pFile->pLock is shared across threads
1779 */
danielk1977b4b47412007-08-17 15:53:36 +00001780 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001781
1782 /* Make sure the current thread owns the pFile.
1783 */
1784 rc = transferOwnership(pFile);
1785 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001786 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001787 return rc;
1788 }
1789
1790 /* A PENDING lock is needed before acquiring a SHARED lock and before
1791 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1792 ** be released.
1793 */
1794 if( locktype==SHARED_LOCK
1795 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
1796 ){
1797 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1798 PENDING_BYTE, 1, 1);
1799 if (failed) {
1800 rc = SQLITE_BUSY;
1801 goto afp_end_lock;
1802 }
1803 }
1804
1805 /* If control gets to this point, then actually go ahead and make
1806 ** operating system calls for the specified lock.
1807 */
1808 if( locktype==SHARED_LOCK ){
1809 int lk, failed;
1810 int tries = 0;
1811
1812 /* Now get the read-lock */
1813 /* note that the quality of the randomness doesn't matter that much */
1814 lk = random();
1815 context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
1816 failed = _AFPFSSetLock(context->filePath, pFile->h,
1817 SHARED_FIRST+context->sharedLockByte, 1, 1);
1818
1819 /* Drop the temporary PENDING lock */
1820 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
1821 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1822 goto afp_end_lock;
1823 }
1824
1825 if( failed ){
1826 rc = SQLITE_BUSY;
1827 } else {
1828 pFile->locktype = SHARED_LOCK;
1829 }
1830 }else{
1831 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1832 ** assumed that there is a SHARED or greater lock on the file
1833 ** already.
1834 */
1835 int failed = 0;
1836 assert( 0!=pFile->locktype );
1837 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
1838 /* Acquire a RESERVED lock */
1839 failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1840 }
1841 if (!failed && locktype == EXCLUSIVE_LOCK) {
1842 /* Acquire an EXCLUSIVE lock */
1843
1844 /* Remove the shared lock before trying the range. we'll need to
1845 ** reestablish the shared lock if we can't get the afpUnixUnlock
1846 */
1847 if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1848 context->sharedLockByte, 1, 0)) {
1849 /* now attemmpt to get the exclusive lock range */
1850 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1851 SHARED_SIZE, 1);
1852 if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1853 context->sharedLockByte, 1, 1)) {
1854 rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
1855 }
1856 } else {
1857 /* */
1858 rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
1859 }
1860 }
1861 if( failed && rc == SQLITE_OK){
1862 rc = SQLITE_BUSY;
1863 }
1864 }
1865
1866 if( rc==SQLITE_OK ){
1867 pFile->locktype = locktype;
1868 }else if( locktype==EXCLUSIVE_LOCK ){
1869 pFile->locktype = PENDING_LOCK;
1870 }
1871
1872afp_end_lock:
danielk1977b4b47412007-08-17 15:53:36 +00001873 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001874 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00001875 rc==SQLITE_OK ? "ok" : "failed");
1876 return rc;
1877}
1878
1879/*
1880 ** Lower the locking level on file descriptor pFile to locktype. locktype
1881 ** must be either NO_LOCK or SHARED_LOCK.
1882 **
1883 ** If the locking level of the file descriptor is already at or below
1884 ** the requested locking level, this routine is a no-op.
1885 */
1886static int afpUnixUnlock(OsFile *id, int locktype) {
1887 struct flock lock;
1888 int rc = SQLITE_OK;
1889 unixFile *pFile = (unixFile*)id;
1890 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1891
1892 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001893 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00001894 pFile->locktype, getpid());
1895
1896 assert( locktype<=SHARED_LOCK );
1897 if( pFile->locktype<=locktype ){
1898 return SQLITE_OK;
1899 }
1900 if( CHECK_THREADID(pFile) ){
1901 return SQLITE_MISUSE;
1902 }
danielk1977b4b47412007-08-17 15:53:36 +00001903 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001904 if( pFile->locktype>SHARED_LOCK ){
1905 if( locktype==SHARED_LOCK ){
1906 int failed = 0;
1907
1908 /* unlock the exclusive range - then re-establish the shared lock */
1909 if (pFile->locktype==EXCLUSIVE_LOCK) {
1910 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1911 SHARED_SIZE, 0);
1912 if (!failed) {
1913 /* successfully removed the exclusive lock */
1914 if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
1915 context->sharedLockByte, 1, 1)) {
1916 /* failed to re-establish our shared lock */
1917 rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
1918 }
1919 } else {
1920 /* This should never happen - failed to unlock the exclusive range */
1921 rc = SQLITE_IOERR_UNLOCK;
1922 }
1923 }
1924 }
1925 if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
1926 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
1927 /* failed to release the pending lock */
1928 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1929 }
1930 }
1931 if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
1932 if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
1933 /* failed to release the reserved lock */
1934 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1935 }
1936 }
1937 }
1938 if( locktype==NO_LOCK ){
1939 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1940 SHARED_FIRST + context->sharedLockByte, 1, 0);
1941 if (failed) {
1942 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1943 }
1944 }
1945 if (rc == SQLITE_OK)
1946 pFile->locktype = locktype;
danielk1977b4b47412007-08-17 15:53:36 +00001947 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001948 return rc;
1949}
1950
1951/*
1952 ** Close a file & cleanup AFP specific locking context
1953 */
1954static int afpUnixClose(OsFile **pId) {
1955 unixFile *id = (unixFile*)*pId;
1956
1957 if( !id ) return SQLITE_OK;
1958 afpUnixUnlock(*pId, NO_LOCK);
1959 /* free the AFP locking structure */
1960 if (id->lockingContext != NULL) {
1961 if (((afpLockingContext *)id->lockingContext)->filePath != NULL)
drh17435752007-08-16 04:30:38 +00001962 sqlite3_free(((afpLockingContext*)id->lockingContext)->filePath);
1963 sqlite3_free(id->lockingContext);
drhbfe66312006-10-03 17:40:40 +00001964 }
1965
1966 if( id->dirfd>=0 ) close(id->dirfd);
1967 id->dirfd = -1;
1968 close(id->h);
1969 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00001970 OSTRACE2("CLOSE %-3d\n", id->h);
drhbfe66312006-10-03 17:40:40 +00001971 OpenCounter(-1);
drh17435752007-08-16 04:30:38 +00001972 sqlite3_free(id);
drhbfe66312006-10-03 17:40:40 +00001973 *pId = 0;
1974 return SQLITE_OK;
1975}
1976
1977
1978#pragma mark flock() style locking
1979
1980/*
1981 ** The flockLockingContext is not used
1982 */
1983typedef void flockLockingContext;
1984
1985static int flockUnixCheckReservedLock(OsFile *id) {
1986 unixFile *pFile = (unixFile*)id;
1987
1988 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00001989 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00001990 } else {
drh3b62b2f2007-06-08 18:27:03 +00001991 /* attempt to get the lock */
drhbfe66312006-10-03 17:40:40 +00001992 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1993 if (!rc) {
drh3b62b2f2007-06-08 18:27:03 +00001994 /* got the lock, unlock it */
drhbfe66312006-10-03 17:40:40 +00001995 flock(pFile->h, LOCK_UN);
drh3b62b2f2007-06-08 18:27:03 +00001996 return 0; /* no one has it reserved */
drhbfe66312006-10-03 17:40:40 +00001997 }
drh3b62b2f2007-06-08 18:27:03 +00001998 return 1; /* someone else might have it reserved */
drhbfe66312006-10-03 17:40:40 +00001999 }
2000}
2001
2002static int flockUnixLock(OsFile *id, int locktype) {
2003 unixFile *pFile = (unixFile*)id;
2004
drh3b62b2f2007-06-08 18:27:03 +00002005 /* if we already have a lock, it is exclusive.
2006 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00002007 if (pFile->locktype > NO_LOCK) {
2008 pFile->locktype = locktype;
2009 return SQLITE_OK;
2010 }
2011
drh3b62b2f2007-06-08 18:27:03 +00002012 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00002013 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
2014 if (rc) {
drh3b62b2f2007-06-08 18:27:03 +00002015 /* didn't get, must be busy */
drhbfe66312006-10-03 17:40:40 +00002016 return SQLITE_BUSY;
2017 } else {
drh3b62b2f2007-06-08 18:27:03 +00002018 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00002019 pFile->locktype = locktype;
2020 return SQLITE_OK;
2021 }
2022}
2023
2024static int flockUnixUnlock(OsFile *id, int locktype) {
2025 unixFile *pFile = (unixFile*)id;
2026
2027 assert( locktype<=SHARED_LOCK );
2028
drh3b62b2f2007-06-08 18:27:03 +00002029 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00002030 if( pFile->locktype==locktype ){
2031 return SQLITE_OK;
2032 }
2033
drh3b62b2f2007-06-08 18:27:03 +00002034 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00002035 if (locktype==SHARED_LOCK) {
2036 pFile->locktype = locktype;
2037 return SQLITE_OK;
2038 }
2039
drh3b62b2f2007-06-08 18:27:03 +00002040 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00002041 int rc = flock(pFile->h, LOCK_UN);
2042 if (rc)
2043 return SQLITE_IOERR_UNLOCK;
2044 else {
2045 pFile->locktype = NO_LOCK;
2046 return SQLITE_OK;
2047 }
2048}
2049
2050/*
2051 ** Close a file.
2052 */
2053static int flockUnixClose(OsFile **pId) {
2054 unixFile *id = (unixFile*)*pId;
2055
2056 if( !id ) return SQLITE_OK;
2057 flockUnixUnlock(*pId, NO_LOCK);
2058
2059 if( id->dirfd>=0 ) close(id->dirfd);
2060 id->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00002061 enterMutex();
drhbfe66312006-10-03 17:40:40 +00002062
2063 close(id->h);
danielk1977b4b47412007-08-17 15:53:36 +00002064 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002065 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00002066 OSTRACE2("CLOSE %-3d\n", id->h);
drhbfe66312006-10-03 17:40:40 +00002067 OpenCounter(-1);
drh17435752007-08-16 04:30:38 +00002068 sqlite3_free(id);
drhbfe66312006-10-03 17:40:40 +00002069 *pId = 0;
2070 return SQLITE_OK;
2071}
2072
2073#pragma mark Old-School .lock file based locking
2074
2075/*
2076 ** The dotlockLockingContext structure contains all dotlock (.lock) lock
2077 ** specific state
2078 */
2079typedef struct dotlockLockingContext dotlockLockingContext;
2080struct dotlockLockingContext {
2081 char *lockPath;
2082};
2083
2084
2085static int dotlockUnixCheckReservedLock(OsFile *id) {
2086 unixFile *pFile = (unixFile*)id;
2087 dotlockLockingContext *context =
2088 (dotlockLockingContext *) pFile->lockingContext;
2089
2090 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00002091 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00002092 } else {
2093 struct stat statBuf;
2094 if (lstat(context->lockPath,&statBuf) == 0)
drh3b62b2f2007-06-08 18:27:03 +00002095 /* file exists, someone else has the lock */
drhbfe66312006-10-03 17:40:40 +00002096 return 1;
2097 else
drh3b62b2f2007-06-08 18:27:03 +00002098 /* file does not exist, we could have it if we want it */
drhbfe66312006-10-03 17:40:40 +00002099 return 0;
2100 }
2101}
2102
2103static int dotlockUnixLock(OsFile *id, int locktype) {
2104 unixFile *pFile = (unixFile*)id;
2105 dotlockLockingContext *context =
2106 (dotlockLockingContext *) pFile->lockingContext;
2107
drh3b62b2f2007-06-08 18:27:03 +00002108 /* if we already have a lock, it is exclusive.
2109 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00002110 if (pFile->locktype > NO_LOCK) {
2111 pFile->locktype = locktype;
2112
2113 /* Always update the timestamp on the old file */
2114 utimes(context->lockPath,NULL);
2115 return SQLITE_OK;
2116 }
2117
drh3b62b2f2007-06-08 18:27:03 +00002118 /* check to see if lock file already exists */
drhbfe66312006-10-03 17:40:40 +00002119 struct stat statBuf;
2120 if (lstat(context->lockPath,&statBuf) == 0){
drh3b62b2f2007-06-08 18:27:03 +00002121 return SQLITE_BUSY; /* it does, busy */
drhbfe66312006-10-03 17:40:40 +00002122 }
2123
drh3b62b2f2007-06-08 18:27:03 +00002124 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00002125 int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
2126 if (fd < 0) {
drh3b62b2f2007-06-08 18:27:03 +00002127 /* failed to open/create the file, someone else may have stolen the lock */
drhbfe66312006-10-03 17:40:40 +00002128 return SQLITE_BUSY;
2129 }
2130 close(fd);
2131
drh3b62b2f2007-06-08 18:27:03 +00002132 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00002133 pFile->locktype = locktype;
2134 return SQLITE_OK;
2135}
2136
2137static int dotlockUnixUnlock(OsFile *id, int locktype) {
2138 unixFile *pFile = (unixFile*)id;
2139 dotlockLockingContext *context =
2140 (dotlockLockingContext *) pFile->lockingContext;
2141
2142 assert( locktype<=SHARED_LOCK );
2143
drh3b62b2f2007-06-08 18:27:03 +00002144 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00002145 if( pFile->locktype==locktype ){
2146 return SQLITE_OK;
2147 }
2148
drh3b62b2f2007-06-08 18:27:03 +00002149 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00002150 if (locktype==SHARED_LOCK) {
2151 pFile->locktype = locktype;
2152 return SQLITE_OK;
2153 }
2154
drh3b62b2f2007-06-08 18:27:03 +00002155 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00002156 unlink(context->lockPath);
2157 pFile->locktype = NO_LOCK;
2158 return SQLITE_OK;
2159}
2160
2161/*
2162 ** Close a file.
2163 */
2164static int dotlockUnixClose(OsFile **pId) {
2165 unixFile *id = (unixFile*)*pId;
2166
2167 if( !id ) return SQLITE_OK;
2168 dotlockUnixUnlock(*pId, NO_LOCK);
2169 /* free the dotlock locking structure */
2170 if (id->lockingContext != NULL) {
2171 if (((dotlockLockingContext *)id->lockingContext)->lockPath != NULL)
drh17435752007-08-16 04:30:38 +00002172 sqlite3_free( ( (dotlockLockingContext *)
drhbfe66312006-10-03 17:40:40 +00002173 id->lockingContext)->lockPath);
drh17435752007-08-16 04:30:38 +00002174 sqlite3_free(id->lockingContext);
drhbfe66312006-10-03 17:40:40 +00002175 }
2176
2177 if( id->dirfd>=0 ) close(id->dirfd);
2178 id->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00002179 enterMutex();
drhbfe66312006-10-03 17:40:40 +00002180
2181 close(id->h);
2182
danielk1977b4b47412007-08-17 15:53:36 +00002183 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002184 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00002185 OSTRACE2("CLOSE %-3d\n", id->h);
drhbfe66312006-10-03 17:40:40 +00002186 OpenCounter(-1);
drh17435752007-08-16 04:30:38 +00002187 sqlite3_free(id);
drhbfe66312006-10-03 17:40:40 +00002188 *pId = 0;
2189 return SQLITE_OK;
2190}
2191
2192
2193#pragma mark No locking
2194
2195/*
2196 ** The nolockLockingContext is void
2197 */
2198typedef void nolockLockingContext;
2199
2200static int nolockUnixCheckReservedLock(OsFile *id) {
2201 return 0;
2202}
2203
2204static int nolockUnixLock(OsFile *id, int locktype) {
2205 return SQLITE_OK;
2206}
2207
2208static int nolockUnixUnlock(OsFile *id, int locktype) {
2209 return SQLITE_OK;
2210}
2211
2212/*
2213 ** Close a file.
2214 */
2215static int nolockUnixClose(OsFile **pId) {
2216 unixFile *id = (unixFile*)*pId;
2217
2218 if( !id ) return SQLITE_OK;
2219 if( id->dirfd>=0 ) close(id->dirfd);
2220 id->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00002221 enterMutex();
drhbfe66312006-10-03 17:40:40 +00002222
2223 close(id->h);
2224
danielk1977b4b47412007-08-17 15:53:36 +00002225 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002226 id->isOpen = 0;
drh4f0c5872007-03-26 22:05:01 +00002227 OSTRACE2("CLOSE %-3d\n", id->h);
drhbfe66312006-10-03 17:40:40 +00002228 OpenCounter(-1);
drh17435752007-08-16 04:30:38 +00002229 sqlite3_free(id);
drhbfe66312006-10-03 17:40:40 +00002230 *pId = 0;
2231 return SQLITE_OK;
2232}
2233
2234#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2235
danielk197790949c22007-08-17 16:50:38 +00002236#if 0
danielk1977e3026632004-06-22 11:29:02 +00002237/*
drh9cbe6352005-11-29 03:13:21 +00002238** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00002239*/
drh9cbe6352005-11-29 03:13:21 +00002240static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00002241 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00002242}
2243
2244/*
2245** Return the underlying file handle for an OsFile
2246*/
2247static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00002248 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00002249}
2250
danielk197790949c22007-08-17 16:50:38 +00002251#endif
drh0ccebe72005-06-07 22:22:50 +00002252
drh9c06c952005-11-26 00:25:00 +00002253/*
danielk1977a3d4c882007-03-23 10:08:38 +00002254** Return the sector size in bytes of the underlying block device for
2255** the specified file. This is almost always 512 bytes, but may be
2256** larger for some devices.
2257**
2258** SQLite code assumes this function cannot fail. It also assumes that
2259** if two files are created in the same file-system directory (i.e.
2260** a database and it's journal file) that the sector size will be the
2261** same for both.
2262*/
danielk197762079062007-08-15 17:08:46 +00002263static int unixSectorSize(sqlite3_file *id){
drh3ceeb752007-03-29 18:19:52 +00002264 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00002265}
2266
danielk197790949c22007-08-17 16:50:38 +00002267/*
2268** Return the device characteristics for the file. This is always 0.
2269*/
danielk197762079062007-08-15 17:08:46 +00002270static int unixDeviceCharacteristics(sqlite3_file *id){
2271 return 0;
2272}
2273
2274static int unixBreakLock(sqlite3_file *id){
2275 assert(!"TODO: unixBreakLock()");
2276 return 0;
2277}
2278
danielk1977a3d4c882007-03-23 10:08:38 +00002279/*
danielk197790949c22007-08-17 16:50:38 +00002280** Return an integer that indices the type of lock currently held
2281** by this handle. (Used for testing and analysis only.)
2282*/
2283static int unixLockState(sqlite3_file *id){
2284 return ((unixFile*)id)->locktype;
2285}
2286
2287/*
drh054889e2005-11-30 03:20:31 +00002288** This vector defines all the methods that can operate on an OsFile
2289** for unix.
drh9c06c952005-11-26 00:25:00 +00002290*/
danielk197762079062007-08-15 17:08:46 +00002291static const sqlite3_io_methods sqlite3UnixIoMethod = {
2292 1, /* iVersion */
drh9c06c952005-11-26 00:25:00 +00002293 unixClose,
2294 unixRead,
2295 unixWrite,
drh9c06c952005-11-26 00:25:00 +00002296 unixTruncate,
drh054889e2005-11-30 03:20:31 +00002297 unixSync,
drh054889e2005-11-30 03:20:31 +00002298 unixFileSize,
2299 unixLock,
2300 unixUnlock,
drh054889e2005-11-30 03:20:31 +00002301 unixCheckReservedLock,
danielk197762079062007-08-15 17:08:46 +00002302 unixBreakLock,
danielk197790949c22007-08-17 16:50:38 +00002303 unixLockState,
danielk1977a3d4c882007-03-23 10:08:38 +00002304 unixSectorSize,
danielk197762079062007-08-15 17:08:46 +00002305 unixDeviceCharacteristics
drh9c06c952005-11-26 00:25:00 +00002306};
2307
drhbfe66312006-10-03 17:40:40 +00002308#ifdef SQLITE_ENABLE_LOCKING_STYLE
drh054889e2005-11-30 03:20:31 +00002309/*
drhbfe66312006-10-03 17:40:40 +00002310 ** This vector defines all the methods that can operate on an OsFile
2311 ** for unix with AFP style file locking.
2312 */
2313static const IoMethod sqlite3AFPLockingUnixIoMethod = {
2314 afpUnixClose,
2315 unixOpenDirectory,
2316 unixRead,
2317 unixWrite,
2318 unixSeek,
2319 unixTruncate,
2320 unixSync,
2321 unixSetFullSync,
2322 unixFileHandle,
2323 unixFileSize,
2324 afpUnixLock,
2325 afpUnixUnlock,
2326 unixLockState,
2327 afpUnixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002328 unixSectorSize,
drhbfe66312006-10-03 17:40:40 +00002329};
2330
2331/*
2332 ** This vector defines all the methods that can operate on an OsFile
2333 ** for unix with flock() style file locking.
2334 */
2335static const IoMethod sqlite3FlockLockingUnixIoMethod = {
2336 flockUnixClose,
2337 unixOpenDirectory,
2338 unixRead,
2339 unixWrite,
2340 unixSeek,
2341 unixTruncate,
2342 unixSync,
2343 unixSetFullSync,
2344 unixFileHandle,
2345 unixFileSize,
2346 flockUnixLock,
2347 flockUnixUnlock,
2348 unixLockState,
2349 flockUnixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002350 unixSectorSize,
drhbfe66312006-10-03 17:40:40 +00002351};
2352
2353/*
2354 ** This vector defines all the methods that can operate on an OsFile
2355 ** for unix with dotlock style file locking.
2356 */
2357static const IoMethod sqlite3DotlockLockingUnixIoMethod = {
2358 dotlockUnixClose,
2359 unixOpenDirectory,
2360 unixRead,
2361 unixWrite,
2362 unixSeek,
2363 unixTruncate,
2364 unixSync,
2365 unixSetFullSync,
2366 unixFileHandle,
2367 unixFileSize,
2368 dotlockUnixLock,
2369 dotlockUnixUnlock,
2370 unixLockState,
2371 dotlockUnixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002372 unixSectorSize,
drhbfe66312006-10-03 17:40:40 +00002373};
2374
2375/*
2376 ** This vector defines all the methods that can operate on an OsFile
2377 ** for unix with dotlock style file locking.
2378 */
2379static const IoMethod sqlite3NolockLockingUnixIoMethod = {
2380 nolockUnixClose,
2381 unixOpenDirectory,
2382 unixRead,
2383 unixWrite,
2384 unixSeek,
2385 unixTruncate,
2386 unixSync,
2387 unixSetFullSync,
2388 unixFileHandle,
2389 unixFileSize,
2390 nolockUnixLock,
2391 nolockUnixUnlock,
2392 unixLockState,
2393 nolockUnixCheckReservedLock,
danielk1977a3d4c882007-03-23 10:08:38 +00002394 unixSectorSize,
drhbfe66312006-10-03 17:40:40 +00002395};
2396
2397#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2398
2399/*
2400** Allocate memory for a new unixFile and initialize that unixFile.
2401** Write a pointer to the new unixFile into *pId.
2402** If we run out of memory, close the file and return an error.
drh054889e2005-11-30 03:20:31 +00002403*/
drhbfe66312006-10-03 17:40:40 +00002404#ifdef SQLITE_ENABLE_LOCKING_STYLE
2405/*
2406 ** When locking extensions are enabled, the filepath and locking style
2407 ** are needed to determine the unixFile pMethod to use for locking operations.
2408 ** The locking-style specific lockingContext data structure is created
2409 ** and assigned here also.
2410 */
2411static int allocateUnixFile(
2412 int h, /* Open file descriptor of file being opened */
2413 OsFile **pId, /* Write completed initialization here */
2414 const char *zFilename, /* Name of the file being opened */
2415 int delFlag /* Delete-on-or-before-close flag */
2416){
aswift108bc322006-10-11 17:19:46 +00002417 sqlite3LockingStyle lockingStyle;
drh054889e2005-11-30 03:20:31 +00002418 unixFile *pNew;
drhbfe66312006-10-03 17:40:40 +00002419 unixFile f;
2420 int rc;
2421
drh61fc5952007-04-01 23:49:51 +00002422 memset(&f, 0, sizeof(f));
aswift448aa6f2006-11-11 01:31:58 +00002423 lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
drhbfe66312006-10-03 17:40:40 +00002424 if ( lockingStyle == posixLockingStyle ) {
danielk1977b4b47412007-08-17 15:53:36 +00002425 enterMutex();
drhbfe66312006-10-03 17:40:40 +00002426 rc = findLockInfo(h, &f.pLock, &f.pOpen);
danielk1977b4b47412007-08-17 15:53:36 +00002427 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002428 if( rc ){
2429 close(h);
2430 unlink(zFilename);
2431 return SQLITE_NOMEM;
2432 }
2433 } else {
drh3b62b2f2007-06-08 18:27:03 +00002434 /* pLock and pOpen are only used for posix advisory locking */
drhbfe66312006-10-03 17:40:40 +00002435 f.pLock = NULL;
2436 f.pOpen = NULL;
2437 }
2438 if( delFlag ){
2439 unlink(zFilename);
2440 }
2441 f.dirfd = -1;
drhbfe66312006-10-03 17:40:40 +00002442 f.h = h;
2443 SET_THREADID(&f);
drh17435752007-08-16 04:30:38 +00002444 pNew = sqlite3_malloc( sizeof(unixFile) );
drh054889e2005-11-30 03:20:31 +00002445 if( pNew==0 ){
drhbfe66312006-10-03 17:40:40 +00002446 close(h);
danielk1977b4b47412007-08-17 15:53:36 +00002447 enterMutex();
drhbfe66312006-10-03 17:40:40 +00002448 releaseLockInfo(f.pLock);
2449 releaseOpenCnt(f.pOpen);
danielk1977b4b47412007-08-17 15:53:36 +00002450 leaveMutex();
drh054889e2005-11-30 03:20:31 +00002451 *pId = 0;
2452 return SQLITE_NOMEM;
2453 }else{
drhbfe66312006-10-03 17:40:40 +00002454 *pNew = f;
aswift108bc322006-10-11 17:19:46 +00002455 switch(lockingStyle) {
drh5bb3eb92007-05-04 13:15:55 +00002456 case afpLockingStyle: {
drhbfe66312006-10-03 17:40:40 +00002457 /* afp locking uses the file path so it needs to be included in
2458 ** the afpLockingContext */
drh5bb3eb92007-05-04 13:15:55 +00002459 int nFilename;
drhbfe66312006-10-03 17:40:40 +00002460 pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
2461 pNew->lockingContext =
drh17435752007-08-16 04:30:38 +00002462 sqlite3_malloc(sizeof(afpLockingContext));
drh5bb3eb92007-05-04 13:15:55 +00002463 nFilename = strlen(zFilename)+1;
drhbfe66312006-10-03 17:40:40 +00002464 ((afpLockingContext *)pNew->lockingContext)->filePath =
drh17435752007-08-16 04:30:38 +00002465 sqlite3_malloc(nFilename);
drh5bb3eb92007-05-04 13:15:55 +00002466 memcpy(((afpLockingContext *)pNew->lockingContext)->filePath,
2467 zFilename, nFilename);
drhbfe66312006-10-03 17:40:40 +00002468 srandomdev();
2469 break;
drh5bb3eb92007-05-04 13:15:55 +00002470 }
drhbfe66312006-10-03 17:40:40 +00002471 case flockLockingStyle:
2472 /* flock locking doesn't need additional lockingContext information */
2473 pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
2474 break;
drh5bb3eb92007-05-04 13:15:55 +00002475 case dotlockLockingStyle: {
drhbfe66312006-10-03 17:40:40 +00002476 /* dotlock locking uses the file path so it needs to be included in
2477 ** the dotlockLockingContext */
drh5bb3eb92007-05-04 13:15:55 +00002478 int nFilename;
drhbfe66312006-10-03 17:40:40 +00002479 pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
drh17435752007-08-16 04:30:38 +00002480 pNew->lockingContext = sqlite3_malloc(
drhbfe66312006-10-03 17:40:40 +00002481 sizeof(dotlockLockingContext));
drh5bb3eb92007-05-04 13:15:55 +00002482 nFilename = strlen(zFilename) + 6;
drhbfe66312006-10-03 17:40:40 +00002483 ((dotlockLockingContext *)pNew->lockingContext)->lockPath =
drh17435752007-08-16 04:30:38 +00002484 sqlite3_malloc( nFilename );
drh5bb3eb92007-05-04 13:15:55 +00002485 sqlite3_snprintf(nFilename,
2486 ((dotlockLockingContext *)pNew->lockingContext)->lockPath,
drhbfe66312006-10-03 17:40:40 +00002487 "%s.lock", zFilename);
2488 break;
drh5bb3eb92007-05-04 13:15:55 +00002489 }
drhbfe66312006-10-03 17:40:40 +00002490 case posixLockingStyle:
2491 /* posix locking doesn't need additional lockingContext information */
2492 pNew->pMethod = &sqlite3UnixIoMethod;
2493 break;
2494 case noLockingStyle:
2495 case unsupportedLockingStyle:
2496 default:
2497 pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
2498 }
2499 *pId = (OsFile*)pNew;
2500 OpenCounter(+1);
2501 return SQLITE_OK;
2502 }
2503}
2504#else /* SQLITE_ENABLE_LOCKING_STYLE */
danielk1977b4b47412007-08-17 15:53:36 +00002505static int fillInUnixFile(
drhbfe66312006-10-03 17:40:40 +00002506 int h, /* Open file descriptor on file being opened */
danielk1977b4b47412007-08-17 15:53:36 +00002507 sqlite3_file *pId, /* Write to the unixFile structure here */
2508 const char *zFilename /* Name of the file being opened */
drhbfe66312006-10-03 17:40:40 +00002509){
danielk1977b4b47412007-08-17 15:53:36 +00002510 unixFile *pNew = (unixFile *)pId;
drhbfe66312006-10-03 17:40:40 +00002511 int rc;
2512
drhe78669b2007-06-29 12:04:26 +00002513#ifdef FD_CLOEXEC
2514 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
2515#endif
danielk1977b4b47412007-08-17 15:53:36 +00002516
2517 enterMutex();
2518 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
2519 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002520 if( rc ){
2521 close(h);
2522 return SQLITE_NOMEM;
2523 }
danielk1977b4b47412007-08-17 15:53:36 +00002524
drh4f0c5872007-03-26 22:05:01 +00002525 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977b4b47412007-08-17 15:53:36 +00002526 pNew->dirfd = -1;
2527 pNew->h = h;
2528 SET_THREADID(pNew);
2529
2530 pNew->pMethod = &sqlite3UnixIoMethod;
2531 OpenCounter(+1);
2532 return SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00002533}
drhbfe66312006-10-03 17:40:40 +00002534#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9c06c952005-11-26 00:25:00 +00002535
drh0ccebe72005-06-07 22:22:50 +00002536#endif /* SQLITE_OMIT_DISKIO */
2537/***************************************************************************
2538** Everything above deals with file I/O. Everything that follows deals
2539** with other miscellanous aspects of the operating system interface
2540****************************************************************************/
2541
danielk1977b4b47412007-08-17 15:53:36 +00002542/*
2543** Previously, the SQLite OS layer used three functions in place of this
2544** one:
2545**
2546** sqlite3OsOpenReadWrite();
2547** sqlite3OsOpenReadOnly();
2548** sqlite3OsOpenExclusive();
2549**
2550** These calls correspond to the following combinations of flags:
2551**
2552** ReadWrite() -> (READWRITE | CREATE)
2553** ReadOnly() -> (READONLY)
2554** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
2555**
2556** The old OpenExclusive() accepted a boolean argument - "delFlag". If
2557** true, the file was configured to be automatically deleted when the
2558** file handle closed. To achieve the same effect using this new
2559** interface, add the DELETEONCLOSE flag to those specified above for
2560** OpenExclusive().
2561*/
2562static int unixOpen(
2563 void *pNotUsed,
2564 const char *zPath,
2565 sqlite3_file *pFile,
2566 int flags,
2567 int *pOutFlags
2568){
2569 int fd = 0;
2570 int oflags = 0;
2571
2572 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
2573 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
2574 int isCreate = (flags & SQLITE_OPEN_CREATE);
2575 int isReadonly = (flags & SQLITE_OPEN_READONLY);
2576 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
2577
2578 /* Exactly one of the READWRITE and READONLY flags must be set */
2579 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
2580
2581 /* If isCreate is true, then the file must be opened for read/write access. */
2582 assert(isCreate==0 || isReadWrite);
2583
2584 /* If isExclusive is true, then isCreate must also be true */
2585 assert(isExclusive==0 || isCreate);
2586
2587 if( isReadonly ) oflags |= O_RDONLY;
2588 if( isReadWrite ) oflags |= O_RDWR;
2589 if( isCreate ) oflags |= O_CREAT;
2590 if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
2591 oflags |= (O_LARGEFILE|O_BINARY);
2592
2593 memset(pFile, 0, sizeof(unixFile));
2594 fd = open(zPath, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
2595 if( fd<0 && isReadWrite && !isExclusive ){
2596 /* Failed to open the file for read/write access. Try read-only. */
2597 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
2598 flags |= SQLITE_OPEN_READONLY;
2599 return unixOpen(pNotUsed, zPath, pFile, flags, pOutFlags);
2600 }
2601 if( fd<0 ){
2602 return SQLITE_CANTOPEN;
2603 }
2604 if( isDelete ){
2605 unlink(zPath);
2606 }
2607 if( pOutFlags ){
2608 *pOutFlags = flags;
2609 }
2610
2611 assert(fd!=0);
2612 return fillInUnixFile(fd, pFile, zPath);
2613}
2614
2615/*
2616** Delete the file at zPath.
2617*/
2618static int unixDelete(void *pNotUsed, const char *zPath){
2619 SimulateIOError(return SQLITE_IOERR_DELETE);
2620 unlink(zPath);
2621 return SQLITE_OK;
2622}
2623
danielk197790949c22007-08-17 16:50:38 +00002624/*
2625** Test the existance of or access permissions of file zPath. The
2626** test performed depends on the value of flags:
2627**
2628** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
2629** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
2630** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
2631**
2632** Otherwise return 0.
2633*/
danielk1977b4b47412007-08-17 15:53:36 +00002634static int unixAccess(void *pNotUsed, const char *zPath, int flags){
2635 int amode;
2636 switch( flags ){
2637 case SQLITE_ACCESS_EXISTS:
2638 amode = F_OK;
2639 break;
2640 case SQLITE_ACCESS_READWRITE:
2641 amode = W_OK|R_OK;
2642 break;
2643 case SQLITE_ACCESS_READONLY:
2644 amode = R_OK;
2645 break;
2646
2647 default:
2648 assert(!"Invalid flags argument");
2649 }
2650 return (access(zPath, amode)==0);
2651}
2652
2653/*
2654** Create a temporary file name in zBuf. zBuf must be big enough to
2655** hold at least MAX_PATHNAME characters.
2656*/
2657static int unixGetTempName(void *pNotUsed, char *zBuf){
2658 static const char *azDirs[] = {
2659 0,
2660 "/var/tmp",
2661 "/usr/tmp",
2662 "/tmp",
2663 ".",
2664 };
2665 static const unsigned char zChars[] =
2666 "abcdefghijklmnopqrstuvwxyz"
2667 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2668 "0123456789";
2669 int i, j;
2670 struct stat buf;
2671 const char *zDir = ".";
2672 azDirs[0] = sqlite3_temp_directory;
2673 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
2674 if( azDirs[i]==0 ) continue;
2675 if( stat(azDirs[i], &buf) ) continue;
2676 if( !S_ISDIR(buf.st_mode) ) continue;
2677 if( access(azDirs[i], 07) ) continue;
2678 zDir = azDirs[i];
2679 break;
2680 }
2681 do{
2682 sqlite3_snprintf(MAX_PATHNAME-17, zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
2683 j = strlen(zBuf);
2684 sqlite3Randomness(15, &zBuf[j]);
2685 for(i=0; i<15; i++, j++){
2686 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
2687 }
2688 zBuf[j] = 0;
2689 }while( access(zBuf,0)==0 );
2690 return SQLITE_OK;
2691}
2692
2693
2694/*
2695** Turn a relative pathname into a full pathname. The relative path
2696** is stored as a nul-terminated string in the buffer pointed to by
2697** zPath.
2698**
2699** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
2700** (in this case, MAX_PATHNAME bytes). The full-path is written to
2701** this buffer before returning.
2702*/
2703static int unixFullPathname(void *pNotUsed, const char *zPath, char *zOut){
2704 zOut[MAX_PATHNAME-1] = '\0';
2705 if( zPath[0]=='/' ){
2706 strncpy(zOut, zPath, MAX_PATHNAME-1);
2707 }else{
2708 int nCwd;
2709 if( getcwd(zOut, MAX_PATHNAME-1)==0 ){
2710 return SQLITE_ERROR;
2711 }
2712 nCwd = strlen(zOut);
2713 zOut[nCwd] = '/';
2714 strncpy(&zOut[nCwd+1], zPath, MAX_PATHNAME-1-nCwd-1);
2715 }
2716 return SQLITE_OK;
2717
2718#if 0
2719 /*
2720 ** Remove "/./" path elements and convert "/A/./" path elements
2721 ** to just "/".
2722 */
2723 if( zFull ){
2724 int i, j;
2725 for(i=j=0; zFull[i]; i++){
2726 if( zFull[i]=='/' ){
2727 if( zFull[i+1]=='/' ) continue;
2728 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
2729 i += 1;
2730 continue;
2731 }
2732 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
2733 while( j>0 && zFull[j-1]!='/' ){ j--; }
2734 i += 3;
2735 continue;
2736 }
2737 }
2738 zFull[j++] = zFull[i];
2739 }
2740 zFull[j] = 0;
2741 }
2742#endif
2743}
2744
drh0ccebe72005-06-07 22:22:50 +00002745
drh761df872006-12-21 01:29:22 +00002746#ifndef SQLITE_OMIT_LOAD_EXTENSION
2747/*
2748** Interfaces for opening a shared library, finding entry points
2749** within the shared library, and closing the shared library.
2750*/
2751#include <dlfcn.h>
danielk1977b4b47412007-08-17 15:53:36 +00002752static void *unixDlOpen(void *pNotUsed, const char *zFilename){
drh761df872006-12-21 01:29:22 +00002753 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
2754}
danielk1977b4b47412007-08-17 15:53:36 +00002755static void unixDlError(void *pNotUsed, int nBuf, char *zBufOut){
2756 char *zErr;
2757 enterMutex();
2758 zErr = dlerror();
2759 if( zErr ){
2760 strncpy(zBufOut, zErr, nBuf-1);
2761 zBufOut[nBuf-1] = '\0';
2762 }else if(nBuf>0) {
2763 zBufOut[0] = '\0';
2764 }
2765 leaveMutex();
2766}
2767void *unixDlSym(void *pHandle, const char *zSymbol){
drh761df872006-12-21 01:29:22 +00002768 return dlsym(pHandle, zSymbol);
2769}
danielk1977b4b47412007-08-17 15:53:36 +00002770void unixDlClose(void *pHandle){
2771 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00002772}
danielk1977b4b47412007-08-17 15:53:36 +00002773#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
2774 #define unixDlOpen 0
2775 #define unixDlError 0
2776 #define unixDlSym 0
2777 #define unixDlClose 0
2778#endif
2779
2780/*
danielk197790949c22007-08-17 16:50:38 +00002781** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00002782*/
danielk1977b4b47412007-08-17 15:53:36 +00002783static int unixRandomness(void *pNotUsed, int nBuf, char *zBuf){
danielk197790949c22007-08-17 16:50:38 +00002784
2785 assert(nBuf>=(sizeof(time_t)+sizeof(int)));
2786
drhbbd42a62004-05-22 17:41:58 +00002787 /* We have to initialize zBuf to prevent valgrind from reporting
2788 ** errors. The reports issued by valgrind are incorrect - we would
2789 ** prefer that the randomness be increased by making use of the
2790 ** uninitialized space in zBuf - but valgrind errors tend to worry
2791 ** some users. Rather than argue, it seems easier just to initialize
2792 ** the whole array and silence valgrind, even if that means less randomness
2793 ** in the random seed.
2794 **
2795 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00002796 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00002797 ** tests repeatable.
2798 */
danielk1977b4b47412007-08-17 15:53:36 +00002799 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00002800#if !defined(SQLITE_TEST)
2801 {
drh842b8642005-01-21 17:53:17 +00002802 int pid, fd;
2803 fd = open("/dev/urandom", O_RDONLY);
2804 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00002805 time_t t;
2806 time(&t);
danielk197790949c22007-08-17 16:50:38 +00002807 memcpy(zBuf, &t, sizeof(t));
2808 pid = getpid();
2809 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
drh842b8642005-01-21 17:53:17 +00002810 }else{
danielk1977b4b47412007-08-17 15:53:36 +00002811 read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00002812 close(fd);
2813 }
drhbbd42a62004-05-22 17:41:58 +00002814 }
2815#endif
2816 return SQLITE_OK;
2817}
2818
danielk1977b4b47412007-08-17 15:53:36 +00002819
drhbbd42a62004-05-22 17:41:58 +00002820/*
2821** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00002822** The argument is the number of microseconds we want to sleep.
drhbbd42a62004-05-22 17:41:58 +00002823*/
danielk1977b4b47412007-08-17 15:53:36 +00002824static int unixSleep(void *pNotUsed, int microseconds){
drhbbd42a62004-05-22 17:41:58 +00002825#if defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00002826 usleep(microseconds);
2827 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00002828#else
danielk1977b4b47412007-08-17 15:53:36 +00002829 int seconds = (microseconds+999999)/1000000;
2830 sleep(seconds);
2831 return seconds;
drha3fad6f2006-01-18 14:06:37 +00002832#endif
drh88f474a2006-01-02 20:00:12 +00002833}
2834
2835/*
drhbbd42a62004-05-22 17:41:58 +00002836** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00002837** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00002838*/
2839#ifdef SQLITE_TEST
2840int sqlite3_current_time = 0;
2841#endif
2842
2843/*
2844** Find the current time (in Universal Coordinated Time). Write the
2845** current time and date as a Julian Day number into *prNow and
2846** return 0. Return 1 if the time and date cannot be found.
2847*/
danielk1977b4b47412007-08-17 15:53:36 +00002848static int unixCurrentTime(void *pNotUsed, double *prNow){
drh19e2d372005-08-29 23:00:03 +00002849#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00002850 time_t t;
2851 time(&t);
2852 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00002853#else
2854 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00002855 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00002856 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
2857#endif
drhbbd42a62004-05-22 17:41:58 +00002858#ifdef SQLITE_TEST
2859 if( sqlite3_current_time ){
2860 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
2861 }
2862#endif
2863 return 0;
2864}
danielk1977b4b47412007-08-17 15:53:36 +00002865
2866
2867sqlite3_vfs sqlite3DefaultVfs = {
2868 1, /* iVersion */
2869 sizeof(unixFile), /* szOsFile */
2870 MAX_PATHNAME, /* mxPathname */
2871 0, /* nRef */
2872 0, /* vfsMutex */
2873 0, /* pNext */
2874 0, /* pPrev */
2875 "unix", /* zName */
2876 0, /* pAppData */
2877
2878 unixOpen, /* xOpen */
2879 unixDelete, /* xDelete */
2880 unixAccess, /* xAccess */
2881 unixGetTempName, /* xGetTempName */
2882 unixFullPathname, /* xFullPathname */
2883 unixDlOpen, /* xDlOpen */
2884 unixDlError, /* xDlError */
2885 unixDlSym, /* xDlSym */
2886 unixDlClose, /* xDlClose */
2887 unixRandomness, /* xRandomness */
2888 unixSleep, /* xSleep */
2889 unixCurrentTime /* xCurrentTime */
2890};
drhdce8bdb2007-08-16 13:01:44 +00002891
drhbbd42a62004-05-22 17:41:58 +00002892#endif /* OS_UNIX */