blob: df30a1cc2bfcb8a8584fdb5753cebbd0d4965f7f [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#if OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000017
drhbfe66312006-10-03 17:40:40 +000018/* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
19
drh9cbe6352005-11-29 03:13:21 +000020/*
21** These #defines should enable >2GB file support on Posix if the
22** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000023** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000024**
25** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
26** on the compiler command line. This is necessary if you are compiling
27** on a recent machine (ex: RedHat 7.2) but you want your code to work
28** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
29** without this option, LFS is enable. But LFS does not exist in the kernel
30** in RedHat 6.0, so the code won't work. Hence, for maximum binary
31** portability you should omit LFS.
drh9cbe6352005-11-29 03:13:21 +000032*/
33#ifndef SQLITE_DISABLE_LFS
34# define _LARGE_FILE 1
35# ifndef _FILE_OFFSET_BITS
36# define _FILE_OFFSET_BITS 64
37# endif
38# define _LARGEFILE_SOURCE 1
39#endif
drhbbd42a62004-05-22 17:41:58 +000040
drh9cbe6352005-11-29 03:13:21 +000041/*
42** standard include files.
43*/
44#include <sys/types.h>
45#include <sys/stat.h>
46#include <fcntl.h>
47#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000048#include <time.h>
drh19e2d372005-08-29 23:00:03 +000049#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000050#include <errno.h>
drhbfe66312006-10-03 17:40:40 +000051#ifdef SQLITE_ENABLE_LOCKING_STYLE
52#include <sys/ioctl.h>
53#include <sys/param.h>
54#include <sys/mount.h>
55#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000056
57/*
drhf1a221e2006-01-15 17:27:17 +000058** If we are to be thread-safe, include the pthreads header and define
59** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +000060*/
drhd677b3d2007-08-20 22:48:41 +000061#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +000062# include <pthread.h>
63# define SQLITE_UNIX_THREADS 1
64#endif
65
66/*
67** Default permissions when creating a new file
68*/
69#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
70# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
71#endif
72
danielk1977b4b47412007-08-17 15:53:36 +000073/*
74** Maximum supported path-length.
75*/
76#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +000077
78
79/*
danielk1977ad94b582007-08-20 06:44:22 +000080** The unixFile structure is subclass of sqlite3_file specific for the unix
drh054889e2005-11-30 03:20:31 +000081** protability layer.
drh9cbe6352005-11-29 03:13:21 +000082*/
drh054889e2005-11-30 03:20:31 +000083typedef struct unixFile unixFile;
84struct unixFile {
danielk197762079062007-08-15 17:08:46 +000085 sqlite3_io_methods const *pMethod; /* Always the first entry */
danielk1977967a4a12007-08-20 14:23:44 +000086#ifdef SQLITE_TEST
87 /* In test mode, increase the size of this structure a bit so that
88 ** it is larger than the struct CrashFile defined in test6.c.
89 */
90 char aPadding[32];
91#endif
drh9cbe6352005-11-29 03:13:21 +000092 struct openCnt *pOpen; /* Info about all open fd's on this inode */
93 struct lockInfo *pLock; /* Info about locks on this inode */
drhbfe66312006-10-03 17:40:40 +000094#ifdef SQLITE_ENABLE_LOCKING_STYLE
95 void *lockingContext; /* Locking style specific state */
96#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000097 int h; /* The file descriptor */
98 unsigned char locktype; /* The type of lock held on this fd */
drh9cbe6352005-11-29 03:13:21 +000099 int dirfd; /* File descriptor for the directory */
drhd677b3d2007-08-20 22:48:41 +0000100#if SQLITE_THREADSAFE
danielk1977ad94b582007-08-20 06:44:22 +0000101 pthread_t tid; /* The thread that "owns" this unixFile */
drh9cbe6352005-11-29 03:13:21 +0000102#endif
103};
104
drh0ccebe72005-06-07 22:22:50 +0000105/*
drh198bf392006-01-06 21:52:49 +0000106** Include code that is common to all os_*.c files
107*/
108#include "os_common.h"
109
110/*
drh0ccebe72005-06-07 22:22:50 +0000111** Define various macros that are missing from some systems.
112*/
drhbbd42a62004-05-22 17:41:58 +0000113#ifndef O_LARGEFILE
114# define O_LARGEFILE 0
115#endif
116#ifdef SQLITE_DISABLE_LFS
117# undef O_LARGEFILE
118# define O_LARGEFILE 0
119#endif
120#ifndef O_NOFOLLOW
121# define O_NOFOLLOW 0
122#endif
123#ifndef O_BINARY
124# define O_BINARY 0
125#endif
126
127/*
128** The DJGPP compiler environment looks mostly like Unix, but it
129** lacks the fcntl() system call. So redefine fcntl() to be something
130** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000131** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000132*/
133#ifdef __DJGPP__
134# define fcntl(A,B,C) 0
135#endif
136
137/*
drh2b4b5962005-06-15 17:47:55 +0000138** The threadid macro resolves to the thread-id or to 0. Used for
139** testing and debugging only.
140*/
drhd677b3d2007-08-20 22:48:41 +0000141#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000142#define threadid pthread_self()
143#else
144#define threadid 0
145#endif
146
147/*
danielk1977ad94b582007-08-20 06:44:22 +0000148** Set or check the unixFile.tid field. This field is set when an unixFile
149** is first opened. All subsequent uses of the unixFile verify that the
150** same thread is operating on the unixFile. Some operating systems do
drh2b4b5962005-06-15 17:47:55 +0000151** not allow locks to be overridden by other threads and that restriction
152** means that sqlite3* database handles cannot be moved from one thread
153** to another. This logic makes sure a user does not try to do that
154** by mistake.
drhf1a221e2006-01-15 17:27:17 +0000155**
danielk1977ad94b582007-08-20 06:44:22 +0000156** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
drhf1a221e2006-01-15 17:27:17 +0000157** another as long as we are running on a system that supports threads
158** overriding each others locks (which now the most common behavior)
danielk1977ad94b582007-08-20 06:44:22 +0000159** or if no locks are held. But the unixFile.pLock field needs to be
drhf1a221e2006-01-15 17:27:17 +0000160** recomputed because its key includes the thread-id. See the
161** transferOwnership() function below for additional information
drh2b4b5962005-06-15 17:47:55 +0000162*/
drhd677b3d2007-08-20 22:48:41 +0000163#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000164# define SET_THREADID(X) (X)->tid = pthread_self()
drh029b44b2006-01-15 00:13:15 +0000165# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
166 !pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000167#else
168# define SET_THREADID(X)
169# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000170#endif
171
drhbbd42a62004-05-22 17:41:58 +0000172/*
173** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
174** section 6.5.2.2 lines 483 through 490 specify that when a process
175** sets or clears a lock, that operation overrides any prior locks set
176** by the same process. It does not explicitly say so, but this implies
177** that it overrides locks set by the same process using a different
178** file descriptor. Consider this test case:
179**
180** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
181** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
182**
183** Suppose ./file1 and ./file2 are really the same file (because
184** one is a hard or symbolic link to the other) then if you set
185** an exclusive lock on fd1, then try to get an exclusive lock
186** on fd2, it works. I would have expected the second lock to
187** fail since there was already a lock on the file due to fd1.
188** But not so. Since both locks came from the same process, the
189** second overrides the first, even though they were on different
190** file descriptors opened on different file names.
191**
192** Bummer. If you ask me, this is broken. Badly broken. It means
193** that we cannot use POSIX locks to synchronize file access among
194** competing threads of the same process. POSIX locks will work fine
195** to synchronize access for threads in separate processes, but not
196** threads within the same process.
197**
198** To work around the problem, SQLite has to manage file locks internally
199** on its own. Whenever a new database is opened, we have to find the
200** specific inode of the database file (the inode is determined by the
201** st_dev and st_ino fields of the stat structure that fstat() fills in)
202** and check for locks already existing on that inode. When locks are
203** created or removed, we have to look at our own internal record of the
204** locks to see if another thread has previously set a lock on that same
205** inode.
206**
danielk1977ad94b582007-08-20 06:44:22 +0000207** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000208** descriptor. It is now a structure that holds the integer file
209** descriptor and a pointer to a structure that describes the internal
210** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000211** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000212** point to the same locking structure. The locking structure keeps
213** a reference count (so we will know when to delete it) and a "cnt"
214** field that tells us its internal lock status. cnt==0 means the
215** file is unlocked. cnt==-1 means the file has an exclusive lock.
216** cnt>0 means there are cnt shared locks on the file.
217**
218** Any attempt to lock or unlock a file first checks the locking
219** structure. The fcntl() system call is only invoked to set a
220** POSIX lock if the internal lock structure transitions between
221** a locked and an unlocked state.
222**
223** 2004-Jan-11:
224** More recent discoveries about POSIX advisory locks. (The more
225** I discover, the more I realize the a POSIX advisory locks are
226** an abomination.)
227**
228** If you close a file descriptor that points to a file that has locks,
229** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000230** released. To work around this problem, each unixFile structure contains
drhbbd42a62004-05-22 17:41:58 +0000231** a pointer to an openCnt structure. There is one openCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000232** per open inode, which means that multiple unixFile can point to a single
233** openCnt. When an attempt is made to close an unixFile, if there are
234** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000235** to close() the file descriptor is deferred until all of the locks clear.
236** The openCnt structure keeps a list of file descriptors that need to
237** be closed and that list is walked (and cleared) when the last lock
238** clears.
239**
240** First, under Linux threads, because each thread has a separate
241** process ID, lock operations in one thread do not override locks
242** to the same file in other threads. Linux threads behave like
243** separate processes in this respect. But, if you close a file
244** descriptor in linux threads, all locks are cleared, even locks
245** on other threads and even though the other threads have different
246** process IDs. Linux threads is inconsistent in this respect.
247** (I'm beginning to think that linux threads is an abomination too.)
248** The consequence of this all is that the hash table for the lockInfo
249** structure has to include the process id as part of its key because
250** locks in different threads are treated as distinct. But the
251** openCnt structure should not include the process id in its
252** key because close() clears lock on all threads, not just the current
253** thread. Were it not for this goofiness in linux threads, we could
254** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000255**
256** 2004-Jun-28:
257** On some versions of linux, threads can override each others locks.
258** On others not. Sometimes you can change the behavior on the same
259** system by setting the LD_ASSUME_KERNEL environment variable. The
260** POSIX standard is silent as to which behavior is correct, as far
261** as I can tell, so other versions of unix might show the same
262** inconsistency. There is no little doubt in my mind that posix
263** advisory locks and linux threads are profoundly broken.
264**
265** To work around the inconsistencies, we have to test at runtime
266** whether or not threads can override each others locks. This test
267** is run once, the first time any lock is attempted. A static
268** variable is set to record the results of this test for future
269** use.
drhbbd42a62004-05-22 17:41:58 +0000270*/
271
272/*
273** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000274** to locate a particular lockInfo structure given its inode.
275**
276** If threads cannot override each others locks, then we set the
277** lockKey.tid field to the thread ID. If threads can override
drhf1a221e2006-01-15 17:27:17 +0000278** each others locks then tid is always set to zero. tid is omitted
279** if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000280*/
281struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000282 dev_t dev; /* Device number */
283 ino_t ino; /* Inode number */
drhd677b3d2007-08-20 22:48:41 +0000284#if SQLITE_THREADSAFE
drhd9cb6ac2005-10-20 07:28:17 +0000285 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000286#endif
drhbbd42a62004-05-22 17:41:58 +0000287};
288
289/*
290** An instance of the following structure is allocated for each open
291** inode on each thread with a different process ID. (Threads have
292** different process IDs on linux, but not on most other unixes.)
293**
danielk1977ad94b582007-08-20 06:44:22 +0000294** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000295** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000296** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000297*/
298struct lockInfo {
299 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000300 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000301 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000302 int nRef; /* Number of pointers to this structure */
303};
304
305/*
306** An instance of the following structure serves as the key used
307** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000308** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000309*/
310struct openKey {
311 dev_t dev; /* Device number */
312 ino_t ino; /* Inode number */
313};
314
315/*
316** An instance of the following structure is allocated for each open
317** inode. This structure keeps track of the number of locks on that
318** inode. If a close is attempted against an inode that is holding
319** locks, the close is deferred until all locks clear by adding the
320** file descriptor to be closed to the pending list.
321*/
322struct openCnt {
323 struct openKey key; /* The lookup key */
324 int nRef; /* Number of pointers to this structure */
325 int nLock; /* Number of outstanding locks */
326 int nPending; /* Number of pending close() operations */
327 int *aPending; /* Malloced space holding fd's awaiting a close() */
328};
329
330/*
drhf1a221e2006-01-15 17:27:17 +0000331** These hash tables map inodes and file descriptors (really, lockKey and
332** openKey structures) into lockInfo and openCnt structures. Access to
333** these hash tables must be protected by a mutex.
drhbbd42a62004-05-22 17:41:58 +0000334*/
drh17435752007-08-16 04:30:38 +0000335static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
336static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
drh5fdae772004-06-29 03:29:00 +0000337
drhbfe66312006-10-03 17:40:40 +0000338#ifdef SQLITE_ENABLE_LOCKING_STYLE
339/*
340** The locking styles are associated with the different file locking
341** capabilities supported by different file systems.
342**
343** POSIX locking style fully supports shared and exclusive byte-range locks
344** ADP locking only supports exclusive byte-range locks
345** FLOCK only supports a single file-global exclusive lock
346** DOTLOCK isn't a true locking style, it refers to the use of a special
347** file named the same as the database file with a '.lock' extension, this
348** can be used on file systems that do not offer any reliable file locking
349** NO locking means that no locking will be attempted, this is only used for
350** read-only file systems currently
351** UNSUPPORTED means that no locking will be attempted, this is only used for
352** file systems that are known to be unsupported
353*/
354typedef enum {
drh339eb0b2008-03-07 15:34:11 +0000355 posixLockingStyle = 0, /* standard posix-advisory locks */
356 afpLockingStyle, /* use afp locks */
357 flockLockingStyle, /* use flock() */
358 dotlockLockingStyle, /* use <file>.lock files */
359 noLockingStyle, /* useful for read-only file system */
360 unsupportedLockingStyle /* indicates unsupported file system */
drhbfe66312006-10-03 17:40:40 +0000361} sqlite3LockingStyle;
362#endif /* SQLITE_ENABLE_LOCKING_STYLE */
363
danielk1977ad94b582007-08-20 06:44:22 +0000364/*
365** Helper functions to obtain and relinquish the global mutex.
366*/
danielk1977b4b47412007-08-17 15:53:36 +0000367static void enterMutex(){
drh51fc3472007-08-21 13:51:23 +0000368 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
danielk1977b4b47412007-08-17 15:53:36 +0000369}
370static void leaveMutex(){
drh51fc3472007-08-21 13:51:23 +0000371 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
danielk1977b4b47412007-08-17 15:53:36 +0000372}
373
drhd677b3d2007-08-20 22:48:41 +0000374#if SQLITE_THREADSAFE
drh5fdae772004-06-29 03:29:00 +0000375/*
376** This variable records whether or not threads can override each others
377** locks.
378**
379** 0: No. Threads cannot override each others locks.
380** 1: Yes. Threads can override each others locks.
381** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000382**
drh5062d3a2006-01-31 23:03:35 +0000383** On some systems, we know at compile-time if threads can override each
384** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
385** will be set appropriately. On other systems, we have to check at
386** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
387** undefined.
388**
drhf1a221e2006-01-15 17:27:17 +0000389** This variable normally has file scope only. But during testing, we make
390** it a global so that the test code can change its value in order to verify
391** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000392*/
drh5062d3a2006-01-31 23:03:35 +0000393#ifndef SQLITE_THREAD_OVERRIDE_LOCK
394# define SQLITE_THREAD_OVERRIDE_LOCK -1
395#endif
drh029b44b2006-01-15 00:13:15 +0000396#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000397int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000398#else
drh5062d3a2006-01-31 23:03:35 +0000399static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000400#endif
drh5fdae772004-06-29 03:29:00 +0000401
402/*
403** This structure holds information passed into individual test
404** threads by the testThreadLockingBehavior() routine.
405*/
406struct threadTestData {
407 int fd; /* File to be locked */
408 struct flock lock; /* The locking operation */
409 int result; /* Result of the locking operation */
410};
411
drh2b4b5962005-06-15 17:47:55 +0000412#ifdef SQLITE_LOCK_TRACE
413/*
414** Print out information about all locking operations.
415**
416** This routine is used for troubleshooting locks on multithreaded
417** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
418** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000419** turned off.
drh2b4b5962005-06-15 17:47:55 +0000420*/
421static int lockTrace(int fd, int op, struct flock *p){
422 char *zOpName, *zType;
423 int s;
424 int savedErrno;
425 if( op==F_GETLK ){
426 zOpName = "GETLK";
427 }else if( op==F_SETLK ){
428 zOpName = "SETLK";
429 }else{
430 s = fcntl(fd, op, p);
431 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
432 return s;
433 }
434 if( p->l_type==F_RDLCK ){
435 zType = "RDLCK";
436 }else if( p->l_type==F_WRLCK ){
437 zType = "WRLCK";
438 }else if( p->l_type==F_UNLCK ){
439 zType = "UNLCK";
440 }else{
441 assert( 0 );
442 }
443 assert( p->l_whence==SEEK_SET );
444 s = fcntl(fd, op, p);
445 savedErrno = errno;
446 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
447 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
448 (int)p->l_pid, s);
drhe2396a12007-03-29 20:19:58 +0000449 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
drh2b4b5962005-06-15 17:47:55 +0000450 struct flock l2;
451 l2 = *p;
452 fcntl(fd, F_GETLK, &l2);
453 if( l2.l_type==F_RDLCK ){
454 zType = "RDLCK";
455 }else if( l2.l_type==F_WRLCK ){
456 zType = "WRLCK";
457 }else if( l2.l_type==F_UNLCK ){
458 zType = "UNLCK";
459 }else{
460 assert( 0 );
461 }
462 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
463 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
464 }
465 errno = savedErrno;
466 return s;
467}
468#define fcntl lockTrace
469#endif /* SQLITE_LOCK_TRACE */
470
drh5fdae772004-06-29 03:29:00 +0000471/*
472** The testThreadLockingBehavior() routine launches two separate
473** threads on this routine. This routine attempts to lock a file
474** descriptor then returns. The success or failure of that attempt
475** allows the testThreadLockingBehavior() procedure to determine
476** whether or not threads can override each others locks.
477*/
478static void *threadLockingTest(void *pArg){
479 struct threadTestData *pData = (struct threadTestData*)pArg;
480 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
481 return pArg;
482}
483
484/*
485** This procedure attempts to determine whether or not threads
486** can override each others locks then sets the
487** threadsOverrideEachOthersLocks variable appropriately.
488*/
danielk19774d5238f2006-01-27 06:32:00 +0000489static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000490 int fd;
491 struct threadTestData d[2];
492 pthread_t t[2];
493
494 fd = dup(fd_orig);
495 if( fd<0 ) return;
496 memset(d, 0, sizeof(d));
497 d[0].fd = fd;
498 d[0].lock.l_type = F_RDLCK;
499 d[0].lock.l_len = 1;
500 d[0].lock.l_start = 0;
501 d[0].lock.l_whence = SEEK_SET;
502 d[1] = d[0];
503 d[1].lock.l_type = F_WRLCK;
504 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
505 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
506 pthread_join(t[0], 0);
507 pthread_join(t[1], 0);
508 close(fd);
509 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
510}
drhd677b3d2007-08-20 22:48:41 +0000511#endif /* SQLITE_THREADSAFE */
drh5fdae772004-06-29 03:29:00 +0000512
drhbbd42a62004-05-22 17:41:58 +0000513/*
514** Release a lockInfo structure previously allocated by findLockInfo().
515*/
516static void releaseLockInfo(struct lockInfo *pLock){
drhbfe66312006-10-03 17:40:40 +0000517 if (pLock == NULL)
518 return;
drhbbd42a62004-05-22 17:41:58 +0000519 pLock->nRef--;
520 if( pLock->nRef==0 ){
521 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
drh17435752007-08-16 04:30:38 +0000522 sqlite3_free(pLock);
drhbbd42a62004-05-22 17:41:58 +0000523 }
524}
525
526/*
527** Release a openCnt structure previously allocated by findLockInfo().
528*/
529static void releaseOpenCnt(struct openCnt *pOpen){
drhbfe66312006-10-03 17:40:40 +0000530 if (pOpen == NULL)
531 return;
drhbbd42a62004-05-22 17:41:58 +0000532 pOpen->nRef--;
533 if( pOpen->nRef==0 ){
534 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
drh64b1bea2006-01-15 02:30:57 +0000535 free(pOpen->aPending);
drh17435752007-08-16 04:30:38 +0000536 sqlite3_free(pOpen);
drhbbd42a62004-05-22 17:41:58 +0000537 }
538}
539
drhbfe66312006-10-03 17:40:40 +0000540#ifdef SQLITE_ENABLE_LOCKING_STYLE
541/*
542** Tests a byte-range locking query to see if byte range locks are
543** supported, if not we fall back to dotlockLockingStyle.
544*/
danielk1977ad94b582007-08-20 06:44:22 +0000545static sqlite3LockingStyle sqlite3TestLockingStyle(
546 const char *filePath,
547 int fd
548){
drhbfe66312006-10-03 17:40:40 +0000549 /* test byte-range lock using fcntl */
550 struct flock lockInfo;
551
552 lockInfo.l_len = 1;
553 lockInfo.l_start = 0;
554 lockInfo.l_whence = SEEK_SET;
555 lockInfo.l_type = F_RDLCK;
556
danielk1977ad94b582007-08-20 06:44:22 +0000557 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
drhbfe66312006-10-03 17:40:40 +0000558 return posixLockingStyle;
559 }
560
561 /* testing for flock can give false positives. So if if the above test
562 ** fails, then we fall back to using dot-lock style locking.
563 */
564 return dotlockLockingStyle;
565}
566
567/*
568** Examines the f_fstypename entry in the statfs structure as returned by
569** stat() for the file system hosting the database file, assigns the
drh85b623f2007-12-13 21:54:09 +0000570** appropriate locking style based on its value. These values and
drhbfe66312006-10-03 17:40:40 +0000571** assignments are based on Darwin/OSX behavior and have not been tested on
572** other systems.
573*/
danielk1977ad94b582007-08-20 06:44:22 +0000574static sqlite3LockingStyle sqlite3DetectLockingStyle(
575 const char *filePath,
576 int fd
577){
drhbfe66312006-10-03 17:40:40 +0000578
579#ifdef SQLITE_FIXED_LOCKING_STYLE
580 return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
581#else
582 struct statfs fsInfo;
583
drh339eb0b2008-03-07 15:34:11 +0000584 if( statfs(filePath, &fsInfo) == -1 ){
drhbfe66312006-10-03 17:40:40 +0000585 return sqlite3TestLockingStyle(filePath, fd);
drh339eb0b2008-03-07 15:34:11 +0000586 }
587 if( fsInfo.f_flags & MNT_RDONLY ){
drhbfe66312006-10-03 17:40:40 +0000588 return noLockingStyle;
drh339eb0b2008-03-07 15:34:11 +0000589 }
590 if( strcmp(fsInfo.f_fstypename, "hfs")==0 ||
591 strcmp(fsInfo.f_fstypename, "ufs")==0 ){
592 return posixLockingStyle;
593 }
594 if( strcmp(fsInfo.f_fstypename, "afpfs")==0 ){
drhbfe66312006-10-03 17:40:40 +0000595 return afpLockingStyle;
drh339eb0b2008-03-07 15:34:11 +0000596 }
597 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
drhbfe66312006-10-03 17:40:40 +0000598 return sqlite3TestLockingStyle(filePath, fd);
drh339eb0b2008-03-07 15:34:11 +0000599 }
600 if( strcmp(fsInfo.f_fstypename, "smbfs")==0 ){
drhbfe66312006-10-03 17:40:40 +0000601 return flockLockingStyle;
drh339eb0b2008-03-07 15:34:11 +0000602 }
603 if( strcmp(fsInfo.f_fstypename, "msdos")==0 ){
drhbfe66312006-10-03 17:40:40 +0000604 return dotlockLockingStyle;
drh339eb0b2008-03-07 15:34:11 +0000605 }
606 if( strcmp(fsInfo.f_fstypename, "webdav")==0 ){
drhbfe66312006-10-03 17:40:40 +0000607 return unsupportedLockingStyle;
drh339eb0b2008-03-07 15:34:11 +0000608 }
drhbfe66312006-10-03 17:40:40 +0000609 return sqlite3TestLockingStyle(filePath, fd);
drh3b62b2f2007-06-08 18:27:03 +0000610#endif /* SQLITE_FIXED_LOCKING_STYLE */
drhbfe66312006-10-03 17:40:40 +0000611}
612
613#endif /* SQLITE_ENABLE_LOCKING_STYLE */
614
drhbbd42a62004-05-22 17:41:58 +0000615/*
616** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000617** describes that file descriptor. Create new ones if necessary. The
618** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000619**
620** Return the number of errors.
621*/
drh38f82712004-06-18 17:10:16 +0000622static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000623 int fd, /* The file descriptor used in the key */
624 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000625 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000626){
627 int rc;
628 struct lockKey key1;
629 struct openKey key2;
630 struct stat statbuf;
631 struct lockInfo *pLock;
632 struct openCnt *pOpen;
633 rc = fstat(fd, &statbuf);
634 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000635
drhbbd42a62004-05-22 17:41:58 +0000636 memset(&key1, 0, sizeof(key1));
637 key1.dev = statbuf.st_dev;
638 key1.ino = statbuf.st_ino;
drhd677b3d2007-08-20 22:48:41 +0000639#if SQLITE_THREADSAFE
drh5fdae772004-06-29 03:29:00 +0000640 if( threadsOverrideEachOthersLocks<0 ){
641 testThreadLockingBehavior(fd);
642 }
643 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
644#endif
drhbbd42a62004-05-22 17:41:58 +0000645 memset(&key2, 0, sizeof(key2));
646 key2.dev = statbuf.st_dev;
647 key2.ino = statbuf.st_ino;
648 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
649 if( pLock==0 ){
650 struct lockInfo *pOld;
drh17435752007-08-16 04:30:38 +0000651 pLock = sqlite3_malloc( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000652 if( pLock==0 ){
653 rc = 1;
654 goto exit_findlockinfo;
655 }
drhbbd42a62004-05-22 17:41:58 +0000656 pLock->key = key1;
657 pLock->nRef = 1;
658 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000659 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000660 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
661 if( pOld!=0 ){
662 assert( pOld==pLock );
drh17435752007-08-16 04:30:38 +0000663 sqlite3_free(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000664 rc = 1;
665 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000666 }
667 }else{
668 pLock->nRef++;
669 }
670 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000671 if( ppOpen!=0 ){
672 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
drhbbd42a62004-05-22 17:41:58 +0000673 if( pOpen==0 ){
drh029b44b2006-01-15 00:13:15 +0000674 struct openCnt *pOld;
drh17435752007-08-16 04:30:38 +0000675 pOpen = sqlite3_malloc( sizeof(*pOpen) );
drh029b44b2006-01-15 00:13:15 +0000676 if( pOpen==0 ){
677 releaseLockInfo(pLock);
678 rc = 1;
679 goto exit_findlockinfo;
680 }
681 pOpen->key = key2;
682 pOpen->nRef = 1;
683 pOpen->nLock = 0;
684 pOpen->nPending = 0;
685 pOpen->aPending = 0;
686 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
687 if( pOld!=0 ){
688 assert( pOld==pOpen );
drh17435752007-08-16 04:30:38 +0000689 sqlite3_free(pOpen);
drh029b44b2006-01-15 00:13:15 +0000690 releaseLockInfo(pLock);
691 rc = 1;
692 goto exit_findlockinfo;
693 }
694 }else{
695 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000696 }
drh029b44b2006-01-15 00:13:15 +0000697 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000698 }
danielk1977441b09a2006-01-05 13:48:29 +0000699
700exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000701 return rc;
drhbbd42a62004-05-22 17:41:58 +0000702}
703
drh64b1bea2006-01-15 02:30:57 +0000704#ifdef SQLITE_DEBUG
705/*
706** Helper function for printing out trace information from debugging
707** binaries. This returns the string represetation of the supplied
708** integer lock-type.
709*/
710static const char *locktypeName(int locktype){
711 switch( locktype ){
712 case NO_LOCK: return "NONE";
713 case SHARED_LOCK: return "SHARED";
714 case RESERVED_LOCK: return "RESERVED";
715 case PENDING_LOCK: return "PENDING";
716 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
717 }
718 return "ERROR";
719}
720#endif
721
drhbbd42a62004-05-22 17:41:58 +0000722/*
drh029b44b2006-01-15 00:13:15 +0000723** If we are currently in a different thread than the thread that the
724** unixFile argument belongs to, then transfer ownership of the unixFile
725** over to the current thread.
726**
727** A unixFile is only owned by a thread on systems where one thread is
728** unable to override locks created by a different thread. RedHat9 is
729** an example of such a system.
730**
731** Ownership transfer is only allowed if the unixFile is currently unlocked.
732** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000733** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000734*/
drhd677b3d2007-08-20 22:48:41 +0000735#if SQLITE_THREADSAFE
drh029b44b2006-01-15 00:13:15 +0000736static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000737 int rc;
drh029b44b2006-01-15 00:13:15 +0000738 pthread_t hSelf;
739 if( threadsOverrideEachOthersLocks ){
740 /* Ownership transfers not needed on this system */
741 return SQLITE_OK;
742 }
743 hSelf = pthread_self();
744 if( pthread_equal(pFile->tid, hSelf) ){
745 /* We are still in the same thread */
drh4f0c5872007-03-26 22:05:01 +0000746 OSTRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000747 return SQLITE_OK;
748 }
749 if( pFile->locktype!=NO_LOCK ){
750 /* We cannot change ownership while we are holding a lock! */
751 return SQLITE_MISUSE;
752 }
drh4f0c5872007-03-26 22:05:01 +0000753 OSTRACE4("Transfer ownership of %d from %d to %d\n",
754 pFile->h, pFile->tid, hSelf);
drh029b44b2006-01-15 00:13:15 +0000755 pFile->tid = hSelf;
drhbfe66312006-10-03 17:40:40 +0000756 if (pFile->pLock != NULL) {
757 releaseLockInfo(pFile->pLock);
758 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
drh4f0c5872007-03-26 22:05:01 +0000759 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +0000760 locktypeName(pFile->locktype),
761 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
762 return rc;
763 } else {
764 return SQLITE_OK;
765 }
drh029b44b2006-01-15 00:13:15 +0000766}
767#else
drhf1a221e2006-01-15 17:27:17 +0000768 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +0000769# define transferOwnership(X) SQLITE_OK
770#endif
771
772/*
danielk19772a6bdf62007-08-20 16:07:00 +0000773** Seek to the offset passed as the second argument, then read cnt
774** bytes into pBuf. Return the number of bytes actually read.
drh9e0ebbf2007-10-23 15:59:18 +0000775**
776** NB: If you define USE_PREAD or USE_PREAD64, then it might also
777** be necessary to define _XOPEN_SOURCE to be 500. This varies from
778** one system to another. Since SQLite does not define USE_PREAD
779** any any form by default, we will not attempt to define _XOPEN_SOURCE.
780** See tickets #2741 and #2681.
drhb912b282006-03-23 22:42:20 +0000781*/
danielk197762079062007-08-15 17:08:46 +0000782static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +0000783 int got;
drh8ebf6702007-02-06 11:11:08 +0000784 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +0000785 TIMER_START;
drh8350a212007-03-22 15:22:06 +0000786#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +0000787 got = pread(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +0000788 SimulateIOError( got = -1 );
drh8350a212007-03-22 15:22:06 +0000789#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +0000790 got = pread64(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +0000791 SimulateIOError( got = -1 );
drhb912b282006-03-23 22:42:20 +0000792#else
danielk197762079062007-08-15 17:08:46 +0000793 newOffset = lseek(id->h, offset, SEEK_SET);
drhbb5f18d2007-04-06 18:23:17 +0000794 SimulateIOError( newOffset-- );
danielk197762079062007-08-15 17:08:46 +0000795 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +0000796 return -1;
797 }
drhb912b282006-03-23 22:42:20 +0000798 got = read(id->h, pBuf, cnt);
799#endif
drh15d00c42007-02-27 02:01:14 +0000800 TIMER_END;
danielk1977967a4a12007-08-20 14:23:44 +0000801 OSTRACE5("READ %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +0000802 return got;
803}
804
805/*
drhbbd42a62004-05-22 17:41:58 +0000806** Read data from a file into a buffer. Return SQLITE_OK if all
807** bytes were read successfully and SQLITE_IOERR if anything goes
808** wrong.
809*/
danielk197762079062007-08-15 17:08:46 +0000810static int unixRead(
811 sqlite3_file *id,
812 void *pBuf,
813 int amt,
814 sqlite3_int64 offset
815){
drhbbd42a62004-05-22 17:41:58 +0000816 int got;
drh9cbe6352005-11-29 03:13:21 +0000817 assert( id );
danielk197762079062007-08-15 17:08:46 +0000818 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000819 if( got==amt ){
820 return SQLITE_OK;
drh4ac285a2006-09-15 07:28:50 +0000821 }else if( got<0 ){
822 return SQLITE_IOERR_READ;
drhbbd42a62004-05-22 17:41:58 +0000823 }else{
drhbafda092007-01-03 23:36:22 +0000824 memset(&((char*)pBuf)[got], 0, amt-got);
drh4ac285a2006-09-15 07:28:50 +0000825 return SQLITE_IOERR_SHORT_READ;
drhbbd42a62004-05-22 17:41:58 +0000826 }
827}
828
829/*
drhb912b282006-03-23 22:42:20 +0000830** Seek to the offset in id->offset then read cnt bytes into pBuf.
831** Return the number of bytes actually read. Update the offset.
832*/
danielk197762079062007-08-15 17:08:46 +0000833static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +0000834 int got;
drh8ebf6702007-02-06 11:11:08 +0000835 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +0000836 TIMER_START;
drh8350a212007-03-22 15:22:06 +0000837#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +0000838 got = pwrite(id->h, pBuf, cnt, offset);
drh8350a212007-03-22 15:22:06 +0000839#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +0000840 got = pwrite64(id->h, pBuf, cnt, offset);
drhb912b282006-03-23 22:42:20 +0000841#else
danielk197762079062007-08-15 17:08:46 +0000842 newOffset = lseek(id->h, offset, SEEK_SET);
843 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +0000844 return -1;
845 }
drhb912b282006-03-23 22:42:20 +0000846 got = write(id->h, pBuf, cnt);
847#endif
drh15d00c42007-02-27 02:01:14 +0000848 TIMER_END;
danielk197762079062007-08-15 17:08:46 +0000849 OSTRACE5("WRITE %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +0000850 return got;
851}
852
853
854/*
drhbbd42a62004-05-22 17:41:58 +0000855** Write data from a buffer into a file. Return SQLITE_OK on success
856** or some other error code on failure.
857*/
danielk197762079062007-08-15 17:08:46 +0000858static int unixWrite(
859 sqlite3_file *id,
860 const void *pBuf,
861 int amt,
862 sqlite3_int64 offset
863){
drhbbd42a62004-05-22 17:41:58 +0000864 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000865 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000866 assert( amt>0 );
danielk197762079062007-08-15 17:08:46 +0000867 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000868 amt -= wrote;
danielk197762079062007-08-15 17:08:46 +0000869 offset += wrote;
drhbbd42a62004-05-22 17:41:58 +0000870 pBuf = &((char*)pBuf)[wrote];
871 }
drh59685932006-09-14 13:47:11 +0000872 SimulateIOError(( wrote=(-1), amt=1 ));
873 SimulateDiskfullError(( wrote=0, amt=1 ));
drhbbd42a62004-05-22 17:41:58 +0000874 if( amt>0 ){
drh59685932006-09-14 13:47:11 +0000875 if( wrote<0 ){
drh4ac285a2006-09-15 07:28:50 +0000876 return SQLITE_IOERR_WRITE;
drh59685932006-09-14 13:47:11 +0000877 }else{
878 return SQLITE_FULL;
879 }
drhbbd42a62004-05-22 17:41:58 +0000880 }
881 return SQLITE_OK;
882}
883
drhb851b2c2005-03-10 14:11:12 +0000884#ifdef SQLITE_TEST
885/*
886** Count the number of fullsyncs and normal syncs. This is used to test
887** that syncs and fullsyncs are occuring at the right times.
888*/
889int sqlite3_sync_count = 0;
890int sqlite3_fullsync_count = 0;
891#endif
892
drhf2f23912005-10-05 10:29:36 +0000893/*
894** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
895** Otherwise use fsync() in its place.
896*/
897#ifndef HAVE_FDATASYNC
898# define fdatasync fsync
899#endif
900
drhac530b12006-02-11 01:25:50 +0000901/*
902** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
903** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
904** only available on Mac OS X. But that could change.
905*/
906#ifdef F_FULLFSYNC
907# define HAVE_FULLFSYNC 1
908#else
909# define HAVE_FULLFSYNC 0
910#endif
911
drhb851b2c2005-03-10 14:11:12 +0000912
drhbbd42a62004-05-22 17:41:58 +0000913/*
drhdd809b02004-07-17 21:44:57 +0000914** The fsync() system call does not work as advertised on many
915** unix systems. The following procedure is an attempt to make
916** it work better.
drh1398ad32005-01-19 23:24:50 +0000917**
918** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
919** for testing when we want to run through the test suite quickly.
920** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
921** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
922** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000923*/
drheb796a72005-09-08 12:38:41 +0000924static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +0000925 int rc;
drhb851b2c2005-03-10 14:11:12 +0000926
927 /* Record the number of times that we do a normal fsync() and
928 ** FULLSYNC. This is used during testing to verify that this procedure
929 ** gets called with the correct arguments.
930 */
931#ifdef SQLITE_TEST
932 if( fullSync ) sqlite3_fullsync_count++;
933 sqlite3_sync_count++;
934#endif
935
936 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
937 ** no-op
938 */
939#ifdef SQLITE_NO_SYNC
940 rc = SQLITE_OK;
941#else
942
drhac530b12006-02-11 01:25:50 +0000943#if HAVE_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +0000944 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +0000945 rc = fcntl(fd, F_FULLFSYNC, 0);
aswiftae0943b2007-01-31 23:37:07 +0000946 }else{
947 rc = 1;
948 }
949 /* If the FULLFSYNC failed, fall back to attempting an fsync().
950 * It shouldn't be possible for fullfsync to fail on the local
951 * file system (on OSX), so failure indicates that FULLFSYNC
952 * isn't supported for this file system. So, attempt an fsync
953 * and (for now) ignore the overhead of a superfluous fcntl call.
954 * It'd be better to detect fullfsync support once and avoid
955 * the fcntl call every time sync is called.
956 */
957 if( rc ) rc = fsync(fd);
958
959#else
drheb796a72005-09-08 12:38:41 +0000960 if( dataOnly ){
961 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +0000962 }else{
drheb796a72005-09-08 12:38:41 +0000963 rc = fsync(fd);
964 }
aswiftae0943b2007-01-31 23:37:07 +0000965#endif /* HAVE_FULLFSYNC */
drhb851b2c2005-03-10 14:11:12 +0000966#endif /* defined(SQLITE_NO_SYNC) */
967
drhdd809b02004-07-17 21:44:57 +0000968 return rc;
969}
970
971/*
drhbbd42a62004-05-22 17:41:58 +0000972** Make sure all writes to a particular file are committed to disk.
973**
drheb796a72005-09-08 12:38:41 +0000974** If dataOnly==0 then both the file itself and its metadata (file
975** size, access time, etc) are synced. If dataOnly!=0 then only the
976** file data is synced.
977**
drhbbd42a62004-05-22 17:41:58 +0000978** Under Unix, also make sure that the directory entry for the file
979** has been created by fsync-ing the directory that contains the file.
980** If we do not do this and we encounter a power failure, the directory
981** entry for the journal might not exist after we reboot. The next
982** SQLite to access the file will not know that the journal exists (because
983** the directory entry for the journal was never created) and the transaction
984** will not roll back - possibly leading to database corruption.
985*/
danielk197790949c22007-08-17 16:50:38 +0000986static int unixSync(sqlite3_file *id, int flags){
drh59685932006-09-14 13:47:11 +0000987 int rc;
drh054889e2005-11-30 03:20:31 +0000988 unixFile *pFile = (unixFile*)id;
danielk197790949c22007-08-17 16:50:38 +0000989
danielk1977f036aef2007-08-20 05:36:51 +0000990 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
991 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
992
danielk1977c16d4632007-08-30 14:49:58 +0000993 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
danielk1977f036aef2007-08-20 05:36:51 +0000994 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
995 || (flags&0x0F)==SQLITE_SYNC_FULL
danielk1977f036aef2007-08-20 05:36:51 +0000996 );
danielk197790949c22007-08-17 16:50:38 +0000997
drh054889e2005-11-30 03:20:31 +0000998 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +0000999 OSTRACE2("SYNC %-3d\n", pFile->h);
danielk197790949c22007-08-17 16:50:38 +00001000 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
drh59685932006-09-14 13:47:11 +00001001 SimulateIOError( rc=1 );
1002 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001003 return SQLITE_IOERR_FSYNC;
drhbbd42a62004-05-22 17:41:58 +00001004 }
drh054889e2005-11-30 03:20:31 +00001005 if( pFile->dirfd>=0 ){
drh4f0c5872007-03-26 22:05:01 +00001006 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
danielk197790949c22007-08-17 16:50:38 +00001007 HAVE_FULLFSYNC, isFullsync);
danielk1977d7c03f72005-11-25 10:38:22 +00001008#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001009 /* The directory sync is only attempted if full_fsync is
1010 ** turned off or unavailable. If a full_fsync occurred above,
1011 ** then the directory sync is superfluous.
1012 */
danielk197790949c22007-08-17 16:50:38 +00001013 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
drhac530b12006-02-11 01:25:50 +00001014 /*
1015 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001016 ** errors when applied to directories on certain file systems.
1017 ** A failed directory sync is not a big deal. So it seems
1018 ** better to ignore the error. Ticket #1657
1019 */
1020 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001021 }
danielk1977d7c03f72005-11-25 10:38:22 +00001022#endif
drh054889e2005-11-30 03:20:31 +00001023 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1024 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001025 }
drha2854222004-06-17 19:04:17 +00001026 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001027}
1028
1029/*
1030** Truncate an open file to a specified size
1031*/
danielk197762079062007-08-15 17:08:46 +00001032static int unixTruncate(sqlite3_file *id, i64 nByte){
drh59685932006-09-14 13:47:11 +00001033 int rc;
drh9cbe6352005-11-29 03:13:21 +00001034 assert( id );
drh93aed5a2008-01-16 17:46:38 +00001035 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
drh63fff5f2007-06-19 10:50:38 +00001036 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
drh59685932006-09-14 13:47:11 +00001037 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001038 return SQLITE_IOERR_TRUNCATE;
drh59685932006-09-14 13:47:11 +00001039 }else{
1040 return SQLITE_OK;
1041 }
drhbbd42a62004-05-22 17:41:58 +00001042}
1043
1044/*
1045** Determine the current size of a file in bytes
1046*/
danielk197762079062007-08-15 17:08:46 +00001047static int unixFileSize(sqlite3_file *id, i64 *pSize){
drh59685932006-09-14 13:47:11 +00001048 int rc;
drhbbd42a62004-05-22 17:41:58 +00001049 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001050 assert( id );
drh59685932006-09-14 13:47:11 +00001051 rc = fstat(((unixFile*)id)->h, &buf);
1052 SimulateIOError( rc=1 );
1053 if( rc!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001054 return SQLITE_IOERR_FSTAT;
drhbbd42a62004-05-22 17:41:58 +00001055 }
1056 *pSize = buf.st_size;
1057 return SQLITE_OK;
1058}
1059
danielk19779a1d0ab2004-06-01 14:09:28 +00001060/*
danielk197713adf8a2004-06-03 16:08:41 +00001061** This routine checks if there is a RESERVED lock held on the specified
1062** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001063** non-zero. If the file is unlocked or holds only SHARED locks, then
1064** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001065*/
danielk197762079062007-08-15 17:08:46 +00001066static int unixCheckReservedLock(sqlite3_file *id){
danielk197713adf8a2004-06-03 16:08:41 +00001067 int r = 0;
drh054889e2005-11-30 03:20:31 +00001068 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001069
drh054889e2005-11-30 03:20:31 +00001070 assert( pFile );
danielk1977b4b47412007-08-17 15:53:36 +00001071 enterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001072
1073 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001074 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001075 r = 1;
1076 }
1077
drh2ac3ee92004-06-07 16:27:46 +00001078 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001079 */
1080 if( !r ){
1081 struct flock lock;
1082 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001083 lock.l_start = RESERVED_BYTE;
1084 lock.l_len = 1;
1085 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001086 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001087 if( lock.l_type!=F_UNLCK ){
1088 r = 1;
1089 }
1090 }
1091
danielk1977b4b47412007-08-17 15:53:36 +00001092 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001093 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001094
1095 return r;
1096}
1097
1098/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001099** Lock the file with the lock specified by parameter locktype - one
1100** of the following:
1101**
drh2ac3ee92004-06-07 16:27:46 +00001102** (1) SHARED_LOCK
1103** (2) RESERVED_LOCK
1104** (3) PENDING_LOCK
1105** (4) EXCLUSIVE_LOCK
1106**
drhb3e04342004-06-08 00:47:47 +00001107** Sometimes when requesting one lock state, additional lock states
1108** are inserted in between. The locking might fail on one of the later
1109** transitions leaving the lock state different from what it started but
1110** still short of its goal. The following chart shows the allowed
1111** transitions and the inserted intermediate states:
1112**
1113** UNLOCKED -> SHARED
1114** SHARED -> RESERVED
1115** SHARED -> (PENDING) -> EXCLUSIVE
1116** RESERVED -> (PENDING) -> EXCLUSIVE
1117** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001118**
drha6abd042004-06-09 17:37:22 +00001119** This routine will only increase a lock. Use the sqlite3OsUnlock()
1120** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001121*/
danielk197762079062007-08-15 17:08:46 +00001122static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001123 /* The following describes the implementation of the various locks and
1124 ** lock transitions in terms of the POSIX advisory shared and exclusive
1125 ** lock primitives (called read-locks and write-locks below, to avoid
1126 ** confusion with SQLite lock names). The algorithms are complicated
1127 ** slightly in order to be compatible with windows systems simultaneously
1128 ** accessing the same database file, in case that is ever required.
1129 **
1130 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1131 ** byte', each single bytes at well known offsets, and the 'shared byte
1132 ** range', a range of 510 bytes at a well known offset.
1133 **
1134 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1135 ** byte'. If this is successful, a random byte from the 'shared byte
1136 ** range' is read-locked and the lock on the 'pending byte' released.
1137 **
danielk197790ba3bd2004-06-25 08:32:25 +00001138 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1139 ** A RESERVED lock is implemented by grabbing a write-lock on the
1140 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001141 **
1142 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001143 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1144 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1145 ** obtained, but existing SHARED locks are allowed to persist. A process
1146 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1147 ** This property is used by the algorithm for rolling back a journal file
1148 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001149 **
danielk197790ba3bd2004-06-25 08:32:25 +00001150 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1151 ** implemented by obtaining a write-lock on the entire 'shared byte
1152 ** range'. Since all other locks require a read-lock on one of the bytes
1153 ** within this range, this ensures that no other locks are held on the
1154 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001155 **
1156 ** The reason a single byte cannot be used instead of the 'shared byte
1157 ** range' is that some versions of windows do not support read-locks. By
1158 ** locking a random byte from a range, concurrent SHARED locks may exist
1159 ** even if the locking primitive used is always a write-lock.
1160 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001161 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001162 unixFile *pFile = (unixFile*)id;
1163 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001164 struct flock lock;
1165 int s;
1166
drh054889e2005-11-30 03:20:31 +00001167 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001168 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001169 locktypeName(locktype), locktypeName(pFile->locktype),
1170 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001171
1172 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001173 ** unixFile, do nothing. Don't use the end_lock: exit path, as
danielk1977b4b47412007-08-17 15:53:36 +00001174 ** enterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001175 */
drh054889e2005-11-30 03:20:31 +00001176 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001177 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001178 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001179 return SQLITE_OK;
1180 }
1181
drhb3e04342004-06-08 00:47:47 +00001182 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001183 */
drh054889e2005-11-30 03:20:31 +00001184 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001185 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001186 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001187
drh054889e2005-11-30 03:20:31 +00001188 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001189 */
danielk1977b4b47412007-08-17 15:53:36 +00001190 enterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001191
drh029b44b2006-01-15 00:13:15 +00001192 /* Make sure the current thread owns the pFile.
1193 */
1194 rc = transferOwnership(pFile);
1195 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001196 leaveMutex();
drh029b44b2006-01-15 00:13:15 +00001197 return rc;
1198 }
drh64b1bea2006-01-15 02:30:57 +00001199 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001200
danielk1977ad94b582007-08-20 06:44:22 +00001201 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001202 ** handle that precludes the requested lock, return BUSY.
1203 */
drh054889e2005-11-30 03:20:31 +00001204 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001205 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001206 ){
1207 rc = SQLITE_BUSY;
1208 goto end_lock;
1209 }
1210
1211 /* If a SHARED lock is requested, and some thread using this PID already
1212 ** has a SHARED or RESERVED lock, then increment reference counts and
1213 ** return SQLITE_OK.
1214 */
1215 if( locktype==SHARED_LOCK &&
1216 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1217 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001218 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001219 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001220 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001221 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001222 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001223 goto end_lock;
1224 }
1225
danielk197713adf8a2004-06-03 16:08:41 +00001226 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001227
danielk19779a1d0ab2004-06-01 14:09:28 +00001228 lock.l_whence = SEEK_SET;
1229
drh3cde3bb2004-06-12 02:17:14 +00001230 /* A PENDING lock is needed before acquiring a SHARED lock and before
1231 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1232 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001233 */
drh3cde3bb2004-06-12 02:17:14 +00001234 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001235 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001236 ){
danielk1977489468c2004-06-28 08:25:47 +00001237 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001238 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001239 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001240 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001241 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1242 goto end_lock;
1243 }
drh3cde3bb2004-06-12 02:17:14 +00001244 }
1245
1246
1247 /* If control gets to this point, then actually go ahead and make
1248 ** operating system calls for the specified lock.
1249 */
1250 if( locktype==SHARED_LOCK ){
1251 assert( pLock->cnt==0 );
1252 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001253
drh2ac3ee92004-06-07 16:27:46 +00001254 /* Now get the read-lock */
1255 lock.l_start = SHARED_FIRST;
1256 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001257 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001258
1259 /* Drop the temporary PENDING lock */
1260 lock.l_start = PENDING_BYTE;
1261 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001262 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001263 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001264 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001265 goto end_lock;
1266 }
drhe2396a12007-03-29 20:19:58 +00001267 if( s==(-1) ){
drhbbd42a62004-05-22 17:41:58 +00001268 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1269 }else{
drh054889e2005-11-30 03:20:31 +00001270 pFile->locktype = SHARED_LOCK;
1271 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001272 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001273 }
drh3cde3bb2004-06-12 02:17:14 +00001274 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1275 /* We are trying for an exclusive lock but another thread in this
1276 ** same process is still holding a shared lock. */
1277 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001278 }else{
drh3cde3bb2004-06-12 02:17:14 +00001279 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001280 ** assumed that there is a SHARED or greater lock on the file
1281 ** already.
1282 */
drh054889e2005-11-30 03:20:31 +00001283 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001284 lock.l_type = F_WRLCK;
1285 switch( locktype ){
1286 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001287 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001288 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001289 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001290 lock.l_start = SHARED_FIRST;
1291 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001292 break;
1293 default:
1294 assert(0);
1295 }
drh054889e2005-11-30 03:20:31 +00001296 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001297 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001298 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1299 }
drhbbd42a62004-05-22 17:41:58 +00001300 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001301
danielk1977ecb2a962004-06-02 06:30:16 +00001302 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001303 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001304 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001305 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001306 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001307 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001308 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001309
1310end_lock:
danielk1977b4b47412007-08-17 15:53:36 +00001311 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001312 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001313 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001314 return rc;
1315}
1316
1317/*
drh054889e2005-11-30 03:20:31 +00001318** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001319** must be either NO_LOCK or SHARED_LOCK.
1320**
1321** If the locking level of the file descriptor is already at or below
1322** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001323*/
danielk197762079062007-08-15 17:08:46 +00001324static int unixUnlock(sqlite3_file *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001325 struct lockInfo *pLock;
1326 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001327 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001328 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001329
drh054889e2005-11-30 03:20:31 +00001330 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001331 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001332 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001333
1334 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001335 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001336 return SQLITE_OK;
1337 }
drhf1a221e2006-01-15 17:27:17 +00001338 if( CHECK_THREADID(pFile) ){
1339 return SQLITE_MISUSE;
1340 }
danielk1977b4b47412007-08-17 15:53:36 +00001341 enterMutex();
drh054889e2005-11-30 03:20:31 +00001342 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001343 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001344 if( pFile->locktype>SHARED_LOCK ){
1345 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001346 if( locktype==SHARED_LOCK ){
1347 lock.l_type = F_RDLCK;
1348 lock.l_whence = SEEK_SET;
1349 lock.l_start = SHARED_FIRST;
1350 lock.l_len = SHARED_SIZE;
drhe2396a12007-03-29 20:19:58 +00001351 if( fcntl(pFile->h, F_SETLK, &lock)==(-1) ){
drh9c105bb2004-10-02 20:38:28 +00001352 /* This should never happen */
drh4ac285a2006-09-15 07:28:50 +00001353 rc = SQLITE_IOERR_RDLOCK;
drh9c105bb2004-10-02 20:38:28 +00001354 }
1355 }
drhbbd42a62004-05-22 17:41:58 +00001356 lock.l_type = F_UNLCK;
1357 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001358 lock.l_start = PENDING_BYTE;
1359 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drhe2396a12007-03-29 20:19:58 +00001360 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001361 pLock->locktype = SHARED_LOCK;
1362 }else{
drh4ac285a2006-09-15 07:28:50 +00001363 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001364 }
drhbbd42a62004-05-22 17:41:58 +00001365 }
drha6abd042004-06-09 17:37:22 +00001366 if( locktype==NO_LOCK ){
1367 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001368
drha6abd042004-06-09 17:37:22 +00001369 /* Decrement the shared lock counter. Release the lock using an
1370 ** OS call only when all threads in this same process have released
1371 ** the lock.
1372 */
1373 pLock->cnt--;
1374 if( pLock->cnt==0 ){
1375 lock.l_type = F_UNLCK;
1376 lock.l_whence = SEEK_SET;
1377 lock.l_start = lock.l_len = 0L;
drhe2396a12007-03-29 20:19:58 +00001378 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001379 pLock->locktype = NO_LOCK;
1380 }else{
drh4ac285a2006-09-15 07:28:50 +00001381 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001382 }
drha6abd042004-06-09 17:37:22 +00001383 }
1384
drhbbd42a62004-05-22 17:41:58 +00001385 /* Decrement the count of locks against this same file. When the
1386 ** count reaches zero, close any other file descriptors whose close
1387 ** was deferred because of outstanding locks.
1388 */
drh054889e2005-11-30 03:20:31 +00001389 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001390 pOpen->nLock--;
1391 assert( pOpen->nLock>=0 );
1392 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1393 int i;
1394 for(i=0; i<pOpen->nPending; i++){
1395 close(pOpen->aPending[i]);
1396 }
drh64b1bea2006-01-15 02:30:57 +00001397 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001398 pOpen->nPending = 0;
1399 pOpen->aPending = 0;
1400 }
1401 }
danielk1977b4b47412007-08-17 15:53:36 +00001402 leaveMutex();
drh054889e2005-11-30 03:20:31 +00001403 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001404 return rc;
drhbbd42a62004-05-22 17:41:58 +00001405}
1406
1407/*
danielk1977e3026632004-06-22 11:29:02 +00001408** Close a file.
1409*/
danielk197762079062007-08-15 17:08:46 +00001410static int unixClose(sqlite3_file *id){
1411 unixFile *pFile = (unixFile *)id;
1412 if( !pFile ) return SQLITE_OK;
1413 unixUnlock(id, NO_LOCK);
1414 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1415 pFile->dirfd = -1;
danielk1977b4b47412007-08-17 15:53:36 +00001416 enterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001417
danielk197762079062007-08-15 17:08:46 +00001418 if( pFile->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001419 /* If there are outstanding locks, do not actually close the file just
1420 ** yet because that would clear those locks. Instead, add the file
1421 ** descriptor to pOpen->aPending. It will be automatically closed when
1422 ** the last lock is cleared.
1423 */
1424 int *aNew;
danielk197762079062007-08-15 17:08:46 +00001425 struct openCnt *pOpen = pFile->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001426 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001427 if( aNew==0 ){
1428 /* If a malloc fails, just leak the file descriptor */
1429 }else{
1430 pOpen->aPending = aNew;
danielk197762079062007-08-15 17:08:46 +00001431 pOpen->aPending[pOpen->nPending] = pFile->h;
drhad81e872005-08-21 21:45:01 +00001432 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001433 }
1434 }else{
1435 /* There are no outstanding locks so we can close the file immediately */
danielk197762079062007-08-15 17:08:46 +00001436 close(pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001437 }
danielk197762079062007-08-15 17:08:46 +00001438 releaseLockInfo(pFile->pLock);
1439 releaseOpenCnt(pFile->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001440
danielk1977b4b47412007-08-17 15:53:36 +00001441 leaveMutex();
danielk197762079062007-08-15 17:08:46 +00001442 OSTRACE2("CLOSE %-3d\n", pFile->h);
danielk1977e3026632004-06-22 11:29:02 +00001443 OpenCounter(-1);
danielk1977b4b47412007-08-17 15:53:36 +00001444 memset(pFile, 0, sizeof(unixFile));
drh02afc862006-01-20 18:10:57 +00001445 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001446}
1447
drhbfe66312006-10-03 17:40:40 +00001448
1449#ifdef SQLITE_ENABLE_LOCKING_STYLE
1450#pragma mark AFP Support
1451
1452/*
1453 ** The afpLockingContext structure contains all afp lock specific state
1454 */
1455typedef struct afpLockingContext afpLockingContext;
1456struct afpLockingContext {
drh339eb0b2008-03-07 15:34:11 +00001457 unsigned long long sharedLockByte; /* Byte offset of shared lock byte */
1458 const char *filePath; /* Name of the file */
drhbfe66312006-10-03 17:40:40 +00001459};
1460
1461struct ByteRangeLockPB2
1462{
1463 unsigned long long offset; /* offset to first byte to lock */
1464 unsigned long long length; /* nbr of bytes to lock */
1465 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
1466 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
1467 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
1468 int fd; /* file desc to assoc this lock with */
1469};
1470
drhfd131da2007-08-07 17:13:03 +00001471#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00001472
danielk1977ad94b582007-08-20 06:44:22 +00001473/*
1474** Return 0 on success, 1 on failure. To match the behavior of the
1475** normal posix file locking (used in unixLock for example), we should
1476** provide 'richer' return codes - specifically to differentiate between
1477** 'file busy' and 'file system error' results.
1478*/
1479static int _AFPFSSetLock(
1480 const char *path,
1481 int fd,
1482 unsigned long long offset,
1483 unsigned long long length,
1484 int setLockFlag
1485){
drhfd131da2007-08-07 17:13:03 +00001486 struct ByteRangeLockPB2 pb;
drhbfe66312006-10-03 17:40:40 +00001487 int err;
1488
1489 pb.unLockFlag = setLockFlag ? 0 : 1;
1490 pb.startEndFlag = 0;
1491 pb.offset = offset;
1492 pb.length = length;
1493 pb.fd = fd;
drh4f0c5872007-03-26 22:05:01 +00001494 OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
drhbfe66312006-10-03 17:40:40 +00001495 (setLockFlag?"ON":"OFF"), fd, offset, length);
1496 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
1497 if ( err==-1 ) {
drh4f0c5872007-03-26 22:05:01 +00001498 OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno,
drhbfe66312006-10-03 17:40:40 +00001499 strerror(errno));
drh3b62b2f2007-06-08 18:27:03 +00001500 return 1; /* error */
drhbfe66312006-10-03 17:40:40 +00001501 } else {
1502 return 0;
1503 }
1504}
1505
1506/*
1507 ** This routine checks if there is a RESERVED lock held on the specified
1508 ** file by this or any other process. If such a lock is held, return
1509 ** non-zero. If the file is unlocked or holds only SHARED locks, then
1510 ** return zero.
1511 */
danielk1977ad94b582007-08-20 06:44:22 +00001512static int afpUnixCheckReservedLock(sqlite3_file *id){
drhbfe66312006-10-03 17:40:40 +00001513 int r = 0;
1514 unixFile *pFile = (unixFile*)id;
1515
1516 assert( pFile );
1517 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1518
1519 /* Check if a thread in this process holds such a lock */
1520 if( pFile->locktype>SHARED_LOCK ){
1521 r = 1;
1522 }
1523
1524 /* Otherwise see if some other process holds it.
1525 */
1526 if ( !r ) {
drh3b62b2f2007-06-08 18:27:03 +00001527 /* lock the byte */
drhbfe66312006-10-03 17:40:40 +00001528 int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1529 if (failed) {
1530 /* if we failed to get the lock then someone else must have it */
1531 r = 1;
1532 } else {
1533 /* if we succeeded in taking the reserved lock, unlock it to restore
1534 ** the original state */
1535 _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
1536 }
1537 }
drh4f0c5872007-03-26 22:05:01 +00001538 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
drhbfe66312006-10-03 17:40:40 +00001539
1540 return r;
1541}
1542
1543/* AFP-style locking following the behavior of unixLock, see the unixLock
1544** function comments for details of lock management. */
drh339eb0b2008-03-07 15:34:11 +00001545static int afpUnixLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00001546 int rc = SQLITE_OK;
1547 unixFile *pFile = (unixFile*)id;
1548 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1549 int gotPendingLock = 0;
1550
1551 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001552 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00001553 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
1554
drhbfe66312006-10-03 17:40:40 +00001555 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00001556 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
1557 ** enterMutex() hasn't been called yet.
1558 */
drhbfe66312006-10-03 17:40:40 +00001559 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001560 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001561 locktypeName(locktype));
1562 return SQLITE_OK;
1563 }
1564
1565 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00001566 */
drhbfe66312006-10-03 17:40:40 +00001567 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
1568 assert( locktype!=PENDING_LOCK );
1569 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1570
1571 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00001572 */
danielk1977b4b47412007-08-17 15:53:36 +00001573 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001574
1575 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00001576 */
drhbfe66312006-10-03 17:40:40 +00001577 rc = transferOwnership(pFile);
1578 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001579 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001580 return rc;
1581 }
1582
1583 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00001584 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1585 ** be released.
1586 */
drhbfe66312006-10-03 17:40:40 +00001587 if( locktype==SHARED_LOCK
1588 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00001589 ){
1590 int failed;
1591 failed = _AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00001592 if (failed) {
1593 rc = SQLITE_BUSY;
1594 goto afp_end_lock;
1595 }
1596 }
1597
1598 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00001599 ** operating system calls for the specified lock.
1600 */
drhbfe66312006-10-03 17:40:40 +00001601 if( locktype==SHARED_LOCK ){
1602 int lk, failed;
1603 int tries = 0;
1604
1605 /* Now get the read-lock */
1606 /* note that the quality of the randomness doesn't matter that much */
1607 lk = random();
1608 context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
1609 failed = _AFPFSSetLock(context->filePath, pFile->h,
1610 SHARED_FIRST+context->sharedLockByte, 1, 1);
1611
1612 /* Drop the temporary PENDING lock */
1613 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
1614 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1615 goto afp_end_lock;
1616 }
1617
1618 if( failed ){
1619 rc = SQLITE_BUSY;
1620 } else {
1621 pFile->locktype = SHARED_LOCK;
1622 }
1623 }else{
1624 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1625 ** assumed that there is a SHARED or greater lock on the file
1626 ** already.
1627 */
1628 int failed = 0;
1629 assert( 0!=pFile->locktype );
1630 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
1631 /* Acquire a RESERVED lock */
1632 failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1633 }
1634 if (!failed && locktype == EXCLUSIVE_LOCK) {
1635 /* Acquire an EXCLUSIVE lock */
1636
1637 /* Remove the shared lock before trying the range. we'll need to
1638 ** reestablish the shared lock if we can't get the afpUnixUnlock
1639 */
1640 if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1641 context->sharedLockByte, 1, 0)) {
1642 /* now attemmpt to get the exclusive lock range */
1643 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1644 SHARED_SIZE, 1);
1645 if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1646 context->sharedLockByte, 1, 1)) {
1647 rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
1648 }
1649 } else {
1650 /* */
1651 rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
1652 }
1653 }
1654 if( failed && rc == SQLITE_OK){
1655 rc = SQLITE_BUSY;
1656 }
1657 }
1658
1659 if( rc==SQLITE_OK ){
1660 pFile->locktype = locktype;
1661 }else if( locktype==EXCLUSIVE_LOCK ){
1662 pFile->locktype = PENDING_LOCK;
1663 }
1664
1665afp_end_lock:
drh339eb0b2008-03-07 15:34:11 +00001666 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001667 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00001668 rc==SQLITE_OK ? "ok" : "failed");
1669 return rc;
1670}
1671
1672/*
drh339eb0b2008-03-07 15:34:11 +00001673** Lower the locking level on file descriptor pFile to locktype. locktype
1674** must be either NO_LOCK or SHARED_LOCK.
1675**
1676** If the locking level of the file descriptor is already at or below
1677** the requested locking level, this routine is a no-op.
1678*/
danielk1977ad94b582007-08-20 06:44:22 +00001679static int afpUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001680 struct flock lock;
1681 int rc = SQLITE_OK;
1682 unixFile *pFile = (unixFile*)id;
1683 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1684
1685 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001686 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00001687 pFile->locktype, getpid());
1688
1689 assert( locktype<=SHARED_LOCK );
1690 if( pFile->locktype<=locktype ){
1691 return SQLITE_OK;
1692 }
1693 if( CHECK_THREADID(pFile) ){
1694 return SQLITE_MISUSE;
1695 }
danielk1977b4b47412007-08-17 15:53:36 +00001696 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001697 if( pFile->locktype>SHARED_LOCK ){
1698 if( locktype==SHARED_LOCK ){
1699 int failed = 0;
1700
1701 /* unlock the exclusive range - then re-establish the shared lock */
1702 if (pFile->locktype==EXCLUSIVE_LOCK) {
1703 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1704 SHARED_SIZE, 0);
1705 if (!failed) {
1706 /* successfully removed the exclusive lock */
1707 if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
1708 context->sharedLockByte, 1, 1)) {
1709 /* failed to re-establish our shared lock */
1710 rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
1711 }
1712 } else {
1713 /* This should never happen - failed to unlock the exclusive range */
1714 rc = SQLITE_IOERR_UNLOCK;
1715 }
1716 }
1717 }
1718 if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
1719 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
1720 /* failed to release the pending lock */
1721 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1722 }
1723 }
1724 if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
1725 if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
1726 /* failed to release the reserved lock */
1727 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1728 }
1729 }
1730 }
1731 if( locktype==NO_LOCK ){
1732 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1733 SHARED_FIRST + context->sharedLockByte, 1, 0);
1734 if (failed) {
1735 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1736 }
1737 }
1738 if (rc == SQLITE_OK)
1739 pFile->locktype = locktype;
danielk1977b4b47412007-08-17 15:53:36 +00001740 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001741 return rc;
1742}
1743
1744/*
drh339eb0b2008-03-07 15:34:11 +00001745** Close a file & cleanup AFP specific locking context
1746*/
danielk1977ad94b582007-08-20 06:44:22 +00001747static int afpUnixClose(sqlite3_file *id) {
drh218c5082008-03-07 00:27:10 +00001748 unixFile *pFile = (unixFile*)id;
danielk1977ad94b582007-08-20 06:44:22 +00001749
1750 if( !pFile ) return SQLITE_OK;
drh218c5082008-03-07 00:27:10 +00001751 afpUnixUnlock(id, NO_LOCK);
drh339eb0b2008-03-07 15:34:11 +00001752 sqlite3_free(pFile->lockingContext);
danielk1977ad94b582007-08-20 06:44:22 +00001753 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1754 pFile->dirfd = -1;
1755 close(pFile->h);
danielk1977ad94b582007-08-20 06:44:22 +00001756 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001757 OpenCounter(-1);
drh218c5082008-03-07 00:27:10 +00001758 memset(pFile, 0, sizeof(unixFile));
drhbfe66312006-10-03 17:40:40 +00001759 return SQLITE_OK;
1760}
1761
1762
1763#pragma mark flock() style locking
1764
1765/*
drh339eb0b2008-03-07 15:34:11 +00001766** The flockLockingContext is not used
1767*/
drhbfe66312006-10-03 17:40:40 +00001768typedef void flockLockingContext;
1769
drh339eb0b2008-03-07 15:34:11 +00001770static int flockUnixCheckReservedLock(sqlite3_file *id){
drhbfe66312006-10-03 17:40:40 +00001771 unixFile *pFile = (unixFile*)id;
1772
1773 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00001774 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00001775 } else {
drh3b62b2f2007-06-08 18:27:03 +00001776 /* attempt to get the lock */
drhbfe66312006-10-03 17:40:40 +00001777 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1778 if (!rc) {
drh3b62b2f2007-06-08 18:27:03 +00001779 /* got the lock, unlock it */
drhbfe66312006-10-03 17:40:40 +00001780 flock(pFile->h, LOCK_UN);
drh3b62b2f2007-06-08 18:27:03 +00001781 return 0; /* no one has it reserved */
drhbfe66312006-10-03 17:40:40 +00001782 }
drh3b62b2f2007-06-08 18:27:03 +00001783 return 1; /* someone else might have it reserved */
drhbfe66312006-10-03 17:40:40 +00001784 }
1785}
1786
danielk1977ad94b582007-08-20 06:44:22 +00001787static int flockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001788 unixFile *pFile = (unixFile*)id;
1789
drh3b62b2f2007-06-08 18:27:03 +00001790 /* if we already have a lock, it is exclusive.
1791 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00001792 if (pFile->locktype > NO_LOCK) {
1793 pFile->locktype = locktype;
1794 return SQLITE_OK;
1795 }
1796
drh3b62b2f2007-06-08 18:27:03 +00001797 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00001798 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1799 if (rc) {
drh3b62b2f2007-06-08 18:27:03 +00001800 /* didn't get, must be busy */
drhbfe66312006-10-03 17:40:40 +00001801 return SQLITE_BUSY;
1802 } else {
drh3b62b2f2007-06-08 18:27:03 +00001803 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00001804 pFile->locktype = locktype;
1805 return SQLITE_OK;
1806 }
1807}
1808
danielk1977ad94b582007-08-20 06:44:22 +00001809static int flockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001810 unixFile *pFile = (unixFile*)id;
1811
1812 assert( locktype<=SHARED_LOCK );
1813
drh3b62b2f2007-06-08 18:27:03 +00001814 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00001815 if( pFile->locktype==locktype ){
1816 return SQLITE_OK;
1817 }
1818
drh3b62b2f2007-06-08 18:27:03 +00001819 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00001820 if (locktype==SHARED_LOCK) {
1821 pFile->locktype = locktype;
1822 return SQLITE_OK;
1823 }
1824
drh3b62b2f2007-06-08 18:27:03 +00001825 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00001826 int rc = flock(pFile->h, LOCK_UN);
1827 if (rc)
1828 return SQLITE_IOERR_UNLOCK;
1829 else {
1830 pFile->locktype = NO_LOCK;
1831 return SQLITE_OK;
1832 }
1833}
1834
1835/*
drh339eb0b2008-03-07 15:34:11 +00001836** Close a file.
1837*/
drh218c5082008-03-07 00:27:10 +00001838static int flockUnixClose(sqlite3_file *id) {
1839 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00001840
danielk1977ad94b582007-08-20 06:44:22 +00001841 if( !pFile ) return SQLITE_OK;
drh218c5082008-03-07 00:27:10 +00001842 flockUnixUnlock(id, NO_LOCK);
drhbfe66312006-10-03 17:40:40 +00001843
danielk1977ad94b582007-08-20 06:44:22 +00001844 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1845 pFile->dirfd = -1;
danielk1977ad94b582007-08-20 06:44:22 +00001846 close(pFile->h);
danielk1977ad94b582007-08-20 06:44:22 +00001847 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001848 OpenCounter(-1);
drh218c5082008-03-07 00:27:10 +00001849 memset(pFile, 0, sizeof(unixFile));
drhbfe66312006-10-03 17:40:40 +00001850 return SQLITE_OK;
1851}
1852
1853#pragma mark Old-School .lock file based locking
1854
1855/*
drh339eb0b2008-03-07 15:34:11 +00001856** The dotlockLockingContext structure contains all dotlock (.lock) lock
1857** specific state
1858*/
drhbfe66312006-10-03 17:40:40 +00001859typedef struct dotlockLockingContext dotlockLockingContext;
1860struct dotlockLockingContext {
1861 char *lockPath;
1862};
1863
1864
danielk1977ad94b582007-08-20 06:44:22 +00001865static int dotlockUnixCheckReservedLock(sqlite3_file *id) {
drhbfe66312006-10-03 17:40:40 +00001866 unixFile *pFile = (unixFile*)id;
drh339eb0b2008-03-07 15:34:11 +00001867 dotlockLockingContext *context;
1868
1869 context = (dotlockLockingContext*)pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00001870 if (pFile->locktype == RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00001871 return 1; /* already have a reserved lock */
drhbfe66312006-10-03 17:40:40 +00001872 } else {
1873 struct stat statBuf;
drh339eb0b2008-03-07 15:34:11 +00001874 if (lstat(context->lockPath,&statBuf) == 0){
drh3b62b2f2007-06-08 18:27:03 +00001875 /* file exists, someone else has the lock */
drhbfe66312006-10-03 17:40:40 +00001876 return 1;
drh339eb0b2008-03-07 15:34:11 +00001877 }else{
drh3b62b2f2007-06-08 18:27:03 +00001878 /* file does not exist, we could have it if we want it */
drhbfe66312006-10-03 17:40:40 +00001879 return 0;
drh339eb0b2008-03-07 15:34:11 +00001880 }
drhbfe66312006-10-03 17:40:40 +00001881 }
1882}
1883
danielk1977ad94b582007-08-20 06:44:22 +00001884static int dotlockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001885 unixFile *pFile = (unixFile*)id;
drh339eb0b2008-03-07 15:34:11 +00001886 dotlockLockingContext *context;
1887 int fd;
1888
1889 context = (dotlockLockingContext*)pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00001890
drh3b62b2f2007-06-08 18:27:03 +00001891 /* if we already have a lock, it is exclusive.
1892 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00001893 if (pFile->locktype > NO_LOCK) {
1894 pFile->locktype = locktype;
1895
1896 /* Always update the timestamp on the old file */
1897 utimes(context->lockPath,NULL);
1898 return SQLITE_OK;
1899 }
1900
drh3b62b2f2007-06-08 18:27:03 +00001901 /* check to see if lock file already exists */
drhbfe66312006-10-03 17:40:40 +00001902 struct stat statBuf;
1903 if (lstat(context->lockPath,&statBuf) == 0){
drh3b62b2f2007-06-08 18:27:03 +00001904 return SQLITE_BUSY; /* it does, busy */
drhbfe66312006-10-03 17:40:40 +00001905 }
1906
drh3b62b2f2007-06-08 18:27:03 +00001907 /* grab an exclusive lock */
drh339eb0b2008-03-07 15:34:11 +00001908 fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
1909 if( fd<0 ){
drh3b62b2f2007-06-08 18:27:03 +00001910 /* failed to open/create the file, someone else may have stolen the lock */
drhbfe66312006-10-03 17:40:40 +00001911 return SQLITE_BUSY;
1912 }
1913 close(fd);
1914
drh3b62b2f2007-06-08 18:27:03 +00001915 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00001916 pFile->locktype = locktype;
1917 return SQLITE_OK;
1918}
1919
danielk1977ad94b582007-08-20 06:44:22 +00001920static int dotlockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001921 unixFile *pFile = (unixFile*)id;
drh339eb0b2008-03-07 15:34:11 +00001922 dotlockLockingContext *context;
1923
1924 context = (dotlockLockingContext*)pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00001925
1926 assert( locktype<=SHARED_LOCK );
1927
drh3b62b2f2007-06-08 18:27:03 +00001928 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00001929 if( pFile->locktype==locktype ){
1930 return SQLITE_OK;
1931 }
1932
drh3b62b2f2007-06-08 18:27:03 +00001933 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00001934 if (locktype==SHARED_LOCK) {
1935 pFile->locktype = locktype;
1936 return SQLITE_OK;
1937 }
1938
drh3b62b2f2007-06-08 18:27:03 +00001939 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00001940 unlink(context->lockPath);
1941 pFile->locktype = NO_LOCK;
1942 return SQLITE_OK;
1943}
1944
1945/*
1946 ** Close a file.
1947 */
danielk1977ad94b582007-08-20 06:44:22 +00001948static int dotlockUnixClose(sqlite3_file *id) {
1949 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00001950
danielk1977ad94b582007-08-20 06:44:22 +00001951 if( !pFile ) return SQLITE_OK;
drh218c5082008-03-07 00:27:10 +00001952 dotlockUnixUnlock(id, NO_LOCK);
drh339eb0b2008-03-07 15:34:11 +00001953 sqlite3_free(pFile->lockingContext);
danielk1977ad94b582007-08-20 06:44:22 +00001954 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1955 pFile->dirfd = -1;
danielk1977ad94b582007-08-20 06:44:22 +00001956 close(pFile->h);
danielk1977ad94b582007-08-20 06:44:22 +00001957 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001958 OpenCounter(-1);
drh218c5082008-03-07 00:27:10 +00001959 memset(pFile, 0, sizeof(unixFile));
drhbfe66312006-10-03 17:40:40 +00001960 return SQLITE_OK;
1961}
1962
1963
1964#pragma mark No locking
1965
1966/*
drh339eb0b2008-03-07 15:34:11 +00001967** The nolockLockingContext is void
1968*/
drhbfe66312006-10-03 17:40:40 +00001969typedef void nolockLockingContext;
1970
danielk1977ad94b582007-08-20 06:44:22 +00001971static int nolockUnixCheckReservedLock(sqlite3_file *id) {
drhbfe66312006-10-03 17:40:40 +00001972 return 0;
1973}
1974
danielk1977ad94b582007-08-20 06:44:22 +00001975static int nolockUnixLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001976 return SQLITE_OK;
1977}
1978
danielk1977ad94b582007-08-20 06:44:22 +00001979static int nolockUnixUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001980 return SQLITE_OK;
1981}
1982
1983/*
drh339eb0b2008-03-07 15:34:11 +00001984** Close a file.
1985*/
danielk1977ad94b582007-08-20 06:44:22 +00001986static int nolockUnixClose(sqlite3_file *id) {
1987 unixFile *pFile = (unixFile*)id;
drhbfe66312006-10-03 17:40:40 +00001988
danielk1977ad94b582007-08-20 06:44:22 +00001989 if( !pFile ) return SQLITE_OK;
1990 if( pFile->dirfd>=0 ) close(pFile->dirfd);
1991 pFile->dirfd = -1;
danielk1977ad94b582007-08-20 06:44:22 +00001992 close(pFile->h);
danielk1977ad94b582007-08-20 06:44:22 +00001993 OSTRACE2("CLOSE %-3d\n", pFile->h);
drhbfe66312006-10-03 17:40:40 +00001994 OpenCounter(-1);
drh218c5082008-03-07 00:27:10 +00001995 memset(pFile, 0, sizeof(unixFile));
drhbfe66312006-10-03 17:40:40 +00001996 return SQLITE_OK;
1997}
1998
1999#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2000
danielk1977ad94b582007-08-20 06:44:22 +00002001
danielk1977e3026632004-06-22 11:29:02 +00002002/*
drh9e33c2c2007-08-31 18:34:59 +00002003** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00002004*/
drhcc6bb3e2007-08-31 16:11:35 +00002005static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00002006 switch( op ){
2007 case SQLITE_FCNTL_LOCKSTATE: {
2008 *(int*)pArg = ((unixFile*)id)->locktype;
2009 return SQLITE_OK;
2010 }
2011 }
drhcc6bb3e2007-08-31 16:11:35 +00002012 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00002013}
2014
2015/*
danielk1977a3d4c882007-03-23 10:08:38 +00002016** Return the sector size in bytes of the underlying block device for
2017** the specified file. This is almost always 512 bytes, but may be
2018** larger for some devices.
2019**
2020** SQLite code assumes this function cannot fail. It also assumes that
2021** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00002022** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00002023** same for both.
2024*/
danielk197762079062007-08-15 17:08:46 +00002025static int unixSectorSize(sqlite3_file *id){
drh3ceeb752007-03-29 18:19:52 +00002026 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00002027}
2028
danielk197790949c22007-08-17 16:50:38 +00002029/*
2030** Return the device characteristics for the file. This is always 0.
2031*/
danielk197762079062007-08-15 17:08:46 +00002032static int unixDeviceCharacteristics(sqlite3_file *id){
2033 return 0;
2034}
2035
danielk1977a3d4c882007-03-23 10:08:38 +00002036/*
danielk1977ad94b582007-08-20 06:44:22 +00002037** This vector defines all the methods that can operate on an sqlite3_file
drh054889e2005-11-30 03:20:31 +00002038** for unix.
drh9c06c952005-11-26 00:25:00 +00002039*/
danielk197762079062007-08-15 17:08:46 +00002040static const sqlite3_io_methods sqlite3UnixIoMethod = {
2041 1, /* iVersion */
drh9c06c952005-11-26 00:25:00 +00002042 unixClose,
2043 unixRead,
2044 unixWrite,
drh9c06c952005-11-26 00:25:00 +00002045 unixTruncate,
drh054889e2005-11-30 03:20:31 +00002046 unixSync,
drh054889e2005-11-30 03:20:31 +00002047 unixFileSize,
2048 unixLock,
2049 unixUnlock,
drh054889e2005-11-30 03:20:31 +00002050 unixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002051 unixFileControl,
danielk1977a3d4c882007-03-23 10:08:38 +00002052 unixSectorSize,
danielk197762079062007-08-15 17:08:46 +00002053 unixDeviceCharacteristics
drh9c06c952005-11-26 00:25:00 +00002054};
2055
drhbfe66312006-10-03 17:40:40 +00002056#ifdef SQLITE_ENABLE_LOCKING_STYLE
drh054889e2005-11-30 03:20:31 +00002057/*
danielk1977ad94b582007-08-20 06:44:22 +00002058** This vector defines all the methods that can operate on an sqlite3_file
2059** for unix with AFP style file locking.
2060*/
2061static const sqlite3_io_methods sqlite3AFPLockingUnixIoMethod = {
2062 1, /* iVersion */
drh218c5082008-03-07 00:27:10 +00002063 afpUnixClose,
drhbfe66312006-10-03 17:40:40 +00002064 unixRead,
2065 unixWrite,
drhbfe66312006-10-03 17:40:40 +00002066 unixTruncate,
2067 unixSync,
danielk1977ad94b582007-08-20 06:44:22 +00002068 unixFileSize,
2069 afpUnixLock,
2070 afpUnixUnlock,
2071 afpUnixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002072 unixFileControl,
danielk1977ad94b582007-08-20 06:44:22 +00002073 unixSectorSize,
2074 unixDeviceCharacteristics
2075};
2076
2077/*
2078** This vector defines all the methods that can operate on an sqlite3_file
2079** for unix with flock() style file locking.
2080*/
2081static const sqlite3_io_methods sqlite3FlockLockingUnixIoMethod = {
2082 1, /* iVersion */
2083 flockUnixClose,
2084 unixRead,
2085 unixWrite,
2086 unixTruncate,
2087 unixSync,
2088 unixFileSize,
2089 flockUnixLock,
2090 flockUnixUnlock,
2091 flockUnixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002092 unixFileControl,
danielk1977ad94b582007-08-20 06:44:22 +00002093 unixSectorSize,
2094 unixDeviceCharacteristics
2095};
2096
2097/*
2098** This vector defines all the methods that can operate on an sqlite3_file
2099** for unix with dotlock style file locking.
2100*/
2101static const sqlite3_io_methods sqlite3DotlockLockingUnixIoMethod = {
2102 1, /* iVersion */
2103 dotlockUnixClose,
2104 unixRead,
2105 unixWrite,
2106 unixTruncate,
2107 unixSync,
2108 unixFileSize,
2109 dotlockUnixLock,
2110 dotlockUnixUnlock,
2111 dotlockUnixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002112 unixFileControl,
danielk1977ad94b582007-08-20 06:44:22 +00002113 unixSectorSize,
2114 unixDeviceCharacteristics
2115};
2116
2117/*
2118** This vector defines all the methods that can operate on an sqlite3_file
drh339eb0b2008-03-07 15:34:11 +00002119** for unix with nolock style file locking.
danielk1977ad94b582007-08-20 06:44:22 +00002120*/
2121static const sqlite3_io_methods sqlite3NolockLockingUnixIoMethod = {
2122 1, /* iVersion */
2123 nolockUnixClose,
2124 unixRead,
2125 unixWrite,
2126 unixTruncate,
2127 unixSync,
drhbfe66312006-10-03 17:40:40 +00002128 unixFileSize,
2129 nolockUnixLock,
2130 nolockUnixUnlock,
drhbfe66312006-10-03 17:40:40 +00002131 nolockUnixCheckReservedLock,
drhcc6bb3e2007-08-31 16:11:35 +00002132 unixFileControl,
danielk1977a3d4c882007-03-23 10:08:38 +00002133 unixSectorSize,
danielk1977ad94b582007-08-20 06:44:22 +00002134 unixDeviceCharacteristics
drhbfe66312006-10-03 17:40:40 +00002135};
2136
2137#endif /* SQLITE_ENABLE_LOCKING_STYLE */
2138
2139/*
2140** Allocate memory for a new unixFile and initialize that unixFile.
2141** Write a pointer to the new unixFile into *pId.
2142** If we run out of memory, close the file and return an error.
drh054889e2005-11-30 03:20:31 +00002143*/
drhbfe66312006-10-03 17:40:40 +00002144#ifdef SQLITE_ENABLE_LOCKING_STYLE
2145/*
danielk1977ad94b582007-08-20 06:44:22 +00002146** When locking extensions are enabled, the filepath and locking style
2147** are needed to determine the unixFile pMethod to use for locking operations.
2148** The locking-style specific lockingContext data structure is created
2149** and assigned here also.
2150*/
2151static int fillInUnixFile(
drhbfe66312006-10-03 17:40:40 +00002152 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00002153 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00002154 sqlite3_file *pId, /* Write to the unixFile structure here */
2155 const char *zFilename /* Name of the file being opened */
drhbfe66312006-10-03 17:40:40 +00002156){
aswift108bc322006-10-11 17:19:46 +00002157 sqlite3LockingStyle lockingStyle;
danielk1977ad94b582007-08-20 06:44:22 +00002158 unixFile *pNew = (unixFile *)pId;
drhbfe66312006-10-03 17:40:40 +00002159 int rc;
2160
drh218c5082008-03-07 00:27:10 +00002161#ifdef FD_CLOEXEC
2162 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
2163#endif
2164
aswift448aa6f2006-11-11 01:31:58 +00002165 lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
drh339eb0b2008-03-07 15:34:11 +00002166 if ( lockingStyle==posixLockingStyle ){
danielk1977b4b47412007-08-17 15:53:36 +00002167 enterMutex();
danielk1977ad94b582007-08-20 06:44:22 +00002168 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
danielk1977b4b47412007-08-17 15:53:36 +00002169 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002170 if( rc ){
drh218c5082008-03-07 00:27:10 +00002171 if( dirfd>=0 ) close(dirfd);
drhbfe66312006-10-03 17:40:40 +00002172 close(h);
drhbfe66312006-10-03 17:40:40 +00002173 return SQLITE_NOMEM;
2174 }
2175 } else {
drh3b62b2f2007-06-08 18:27:03 +00002176 /* pLock and pOpen are only used for posix advisory locking */
danielk1977ad94b582007-08-20 06:44:22 +00002177 pNew->pLock = NULL;
2178 pNew->pOpen = NULL;
drhbfe66312006-10-03 17:40:40 +00002179 }
drh218c5082008-03-07 00:27:10 +00002180
2181 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00002182 pNew->dirfd = -1;
2183 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00002184 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00002185 SET_THREADID(pNew);
drh218c5082008-03-07 00:27:10 +00002186
2187 switch(lockingStyle) {
2188 case afpLockingStyle: {
2189 /* afp locking uses the file path so it needs to be included in
2190 ** the afpLockingContext */
drh339eb0b2008-03-07 15:34:11 +00002191 afpLockingContext *context;
drh218c5082008-03-07 00:27:10 +00002192 pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
drh339eb0b2008-03-07 15:34:11 +00002193 pNew->lockingContext = context = sqlite3_malloc( sizeof(*context) );
2194 if( context==0 ){
2195 close(h);
2196 if( dirfd>=0 ) close(dirfd);
2197 return SQLITE_NOMEM;
2198 }
2199
2200 /* NB: zFilename exists and remains valid until the file is closed
2201 ** according to requirement F11141. So we do not need to make a
2202 ** copy of the filename. */
2203 context->filePath = zFilename;
drh218c5082008-03-07 00:27:10 +00002204 srandomdev();
2205 break;
drhbfe66312006-10-03 17:40:40 +00002206 }
drh218c5082008-03-07 00:27:10 +00002207 case flockLockingStyle:
2208 /* flock locking doesn't need additional lockingContext information */
2209 pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
2210 break;
2211 case dotlockLockingStyle: {
2212 /* dotlock locking uses the file path so it needs to be included in
drh339eb0b2008-03-07 15:34:11 +00002213 ** the dotlockLockingContext */
2214 dotlockLockingContext *context;
drh218c5082008-03-07 00:27:10 +00002215 int nFilename;
drh339eb0b2008-03-07 15:34:11 +00002216 nFilename = strlen(zFilename);
drh218c5082008-03-07 00:27:10 +00002217 pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
drh339eb0b2008-03-07 15:34:11 +00002218 pNew->lockingContext = context =
2219 sqlite3_malloc( sizeof(*context) + nFilename + 6 );
2220 if( context==0 ){
2221 close(h);
2222 if( dirfd>=0 ) close(dirfd);
2223 return SQLITE_NOMEM;
2224 }
2225 context->lockPath = (char*)&context[1];
2226 sqlite3_snprintf(nFilename, context->lockPath,
2227 "%s.lock", zFilename);
drh218c5082008-03-07 00:27:10 +00002228 break;
2229 }
2230 case posixLockingStyle:
2231 /* posix locking doesn't need additional lockingContext information */
2232 pNew->pMethod = &sqlite3UnixIoMethod;
2233 break;
2234 case noLockingStyle:
2235 case unsupportedLockingStyle:
2236 default:
2237 pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
drhbfe66312006-10-03 17:40:40 +00002238 }
drh218c5082008-03-07 00:27:10 +00002239 OpenCounter(+1);
2240 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002241}
2242#else /* SQLITE_ENABLE_LOCKING_STYLE */
danielk1977b4b47412007-08-17 15:53:36 +00002243static int fillInUnixFile(
drhbfe66312006-10-03 17:40:40 +00002244 int h, /* Open file descriptor on file being opened */
danielk1977fee2d252007-08-18 10:59:19 +00002245 int dirfd,
danielk1977b4b47412007-08-17 15:53:36 +00002246 sqlite3_file *pId, /* Write to the unixFile structure here */
2247 const char *zFilename /* Name of the file being opened */
drhbfe66312006-10-03 17:40:40 +00002248){
danielk1977b4b47412007-08-17 15:53:36 +00002249 unixFile *pNew = (unixFile *)pId;
drhbfe66312006-10-03 17:40:40 +00002250 int rc;
2251
drhe78669b2007-06-29 12:04:26 +00002252#ifdef FD_CLOEXEC
2253 fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
2254#endif
danielk1977b4b47412007-08-17 15:53:36 +00002255
2256 enterMutex();
2257 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
2258 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002259 if( rc ){
danielk19777c055b92007-10-30 17:28:51 +00002260 if( dirfd>=0 ) close(dirfd);
drhbfe66312006-10-03 17:40:40 +00002261 close(h);
2262 return SQLITE_NOMEM;
2263 }
danielk1977b4b47412007-08-17 15:53:36 +00002264
drh4f0c5872007-03-26 22:05:01 +00002265 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977b4b47412007-08-17 15:53:36 +00002266 pNew->dirfd = -1;
2267 pNew->h = h;
danielk1977fee2d252007-08-18 10:59:19 +00002268 pNew->dirfd = dirfd;
danielk1977b4b47412007-08-17 15:53:36 +00002269 SET_THREADID(pNew);
2270
2271 pNew->pMethod = &sqlite3UnixIoMethod;
2272 OpenCounter(+1);
2273 return SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00002274}
drhbfe66312006-10-03 17:40:40 +00002275#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9c06c952005-11-26 00:25:00 +00002276
danielk1977ad94b582007-08-20 06:44:22 +00002277/*
2278** Open a file descriptor to the directory containing file zFilename.
2279** If successful, *pFd is set to the opened file descriptor and
2280** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
2281** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
2282** value.
2283**
2284** If SQLITE_OK is returned, the caller is responsible for closing
2285** the file descriptor *pFd using close().
2286*/
danielk1977fee2d252007-08-18 10:59:19 +00002287static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00002288 int ii;
drh777b17a2007-09-20 10:02:54 +00002289 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00002290 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00002291
drh153c62c2007-08-24 03:51:33 +00002292 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
danielk1977fee2d252007-08-18 10:59:19 +00002293 for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
2294 if( ii>0 ){
2295 zDirname[ii] = '\0';
2296 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00002297 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00002298#ifdef FD_CLOEXEC
2299 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
2300#endif
2301 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
2302 }
2303 }
danielk1977fee2d252007-08-18 10:59:19 +00002304 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00002305 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00002306}
2307
danielk1977b4b47412007-08-17 15:53:36 +00002308/*
danielk1977ad94b582007-08-20 06:44:22 +00002309** Open the file zPath.
2310**
danielk1977b4b47412007-08-17 15:53:36 +00002311** Previously, the SQLite OS layer used three functions in place of this
2312** one:
2313**
2314** sqlite3OsOpenReadWrite();
2315** sqlite3OsOpenReadOnly();
2316** sqlite3OsOpenExclusive();
2317**
2318** These calls correspond to the following combinations of flags:
2319**
2320** ReadWrite() -> (READWRITE | CREATE)
2321** ReadOnly() -> (READONLY)
2322** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
2323**
2324** The old OpenExclusive() accepted a boolean argument - "delFlag". If
2325** true, the file was configured to be automatically deleted when the
2326** file handle closed. To achieve the same effect using this new
2327** interface, add the DELETEONCLOSE flag to those specified above for
2328** OpenExclusive().
2329*/
2330static int unixOpen(
drh153c62c2007-08-24 03:51:33 +00002331 sqlite3_vfs *pVfs,
danielk1977b4b47412007-08-17 15:53:36 +00002332 const char *zPath,
2333 sqlite3_file *pFile,
2334 int flags,
2335 int *pOutFlags
2336){
danielk1977fee2d252007-08-18 10:59:19 +00002337 int fd = 0; /* File descriptor returned by open() */
2338 int dirfd = -1; /* Directory file descriptor */
2339 int oflags = 0; /* Flags to pass to open() */
2340 int eType = flags&0xFFFFFF00; /* Type of file to open */
danielk1977b4b47412007-08-17 15:53:36 +00002341
2342 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
2343 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
2344 int isCreate = (flags & SQLITE_OPEN_CREATE);
2345 int isReadonly = (flags & SQLITE_OPEN_READONLY);
2346 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
2347
danielk1977fee2d252007-08-18 10:59:19 +00002348 /* If creating a master or main-file journal, this function will open
2349 ** a file-descriptor on the directory too. The first time unixSync()
2350 ** is called the directory file descriptor will be fsync()ed and close()d.
2351 */
2352 int isOpenDirectory = (isCreate &&
2353 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
2354 );
2355
2356 /* Check the following statements are true:
2357 **
2358 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
2359 ** (b) if CREATE is set, then READWRITE must also be set, and
2360 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00002361 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00002362 */
danielk1977b4b47412007-08-17 15:53:36 +00002363 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00002364 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00002365 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00002366 assert(isDelete==0 || isCreate);
2367
2368
2369 /* The main DB, main journal, and master journal are never automatically
2370 ** deleted
2371 */
2372 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
2373 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
2374 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00002375
danielk1977fee2d252007-08-18 10:59:19 +00002376 /* Assert that the upper layer has set one of the "file-type" flags. */
2377 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
2378 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
2379 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00002380 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00002381 );
2382
danielk1977b4b47412007-08-17 15:53:36 +00002383 if( isReadonly ) oflags |= O_RDONLY;
2384 if( isReadWrite ) oflags |= O_RDWR;
2385 if( isCreate ) oflags |= O_CREAT;
2386 if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
2387 oflags |= (O_LARGEFILE|O_BINARY);
2388
2389 memset(pFile, 0, sizeof(unixFile));
2390 fd = open(zPath, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
danielk19772f2d8c72007-08-30 16:13:33 +00002391 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00002392 /* Failed to open the file for read/write access. Try read-only. */
2393 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
2394 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00002395 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00002396 }
2397 if( fd<0 ){
2398 return SQLITE_CANTOPEN;
2399 }
2400 if( isDelete ){
2401 unlink(zPath);
2402 }
2403 if( pOutFlags ){
2404 *pOutFlags = flags;
2405 }
2406
2407 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00002408 if( isOpenDirectory ){
2409 int rc = openDirectory(zPath, &dirfd);
2410 if( rc!=SQLITE_OK ){
2411 close(fd);
2412 return rc;
2413 }
2414 }
2415 return fillInUnixFile(fd, dirfd, pFile, zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002416}
2417
2418/*
danielk1977fee2d252007-08-18 10:59:19 +00002419** Delete the file at zPath. If the dirSync argument is true, fsync()
2420** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00002421*/
drh153c62c2007-08-24 03:51:33 +00002422static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
danielk1977fee2d252007-08-18 10:59:19 +00002423 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00002424 SimulateIOError(return SQLITE_IOERR_DELETE);
2425 unlink(zPath);
danielk1977fee2d252007-08-18 10:59:19 +00002426 if( dirSync ){
2427 int fd;
2428 rc = openDirectory(zPath, &fd);
2429 if( rc==SQLITE_OK ){
2430 if( fsync(fd) ){
2431 rc = SQLITE_IOERR_DIR_FSYNC;
2432 }
2433 close(fd);
2434 }
2435 }
2436 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00002437}
2438
danielk197790949c22007-08-17 16:50:38 +00002439/*
2440** Test the existance of or access permissions of file zPath. The
2441** test performed depends on the value of flags:
2442**
2443** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
2444** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
2445** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
2446**
2447** Otherwise return 0.
2448*/
drh153c62c2007-08-24 03:51:33 +00002449static int unixAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
rse25c0d1a2007-09-20 08:38:14 +00002450 int amode = 0;
danielk1977b4b47412007-08-17 15:53:36 +00002451 switch( flags ){
2452 case SQLITE_ACCESS_EXISTS:
2453 amode = F_OK;
2454 break;
2455 case SQLITE_ACCESS_READWRITE:
2456 amode = W_OK|R_OK;
2457 break;
drh50d3f902007-08-27 21:10:36 +00002458 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00002459 amode = R_OK;
2460 break;
2461
2462 default:
2463 assert(!"Invalid flags argument");
2464 }
2465 return (access(zPath, amode)==0);
2466}
2467
2468/*
drh153c62c2007-08-24 03:51:33 +00002469** Create a temporary file name in zBuf. zBuf must be allocated
2470** by the calling process and must be big enough to hold at least
2471** pVfs->mxPathname bytes.
danielk1977b4b47412007-08-17 15:53:36 +00002472*/
danielk1977adfb9b02007-09-17 07:02:56 +00002473static int unixGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
danielk1977b4b47412007-08-17 15:53:36 +00002474 static const char *azDirs[] = {
2475 0,
2476 "/var/tmp",
2477 "/usr/tmp",
2478 "/tmp",
2479 ".",
2480 };
2481 static const unsigned char zChars[] =
2482 "abcdefghijklmnopqrstuvwxyz"
2483 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2484 "0123456789";
2485 int i, j;
2486 struct stat buf;
2487 const char *zDir = ".";
danielk1977843e65f2007-09-01 16:16:15 +00002488
2489 /* It's odd to simulate an io-error here, but really this is just
2490 ** using the io-error infrastructure to test that SQLite handles this
2491 ** function failing.
2492 */
2493 SimulateIOError( return SQLITE_ERROR );
2494
danielk1977b4b47412007-08-17 15:53:36 +00002495 azDirs[0] = sqlite3_temp_directory;
2496 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
2497 if( azDirs[i]==0 ) continue;
2498 if( stat(azDirs[i], &buf) ) continue;
2499 if( !S_ISDIR(buf.st_mode) ) continue;
2500 if( access(azDirs[i], 07) ) continue;
2501 zDir = azDirs[i];
2502 break;
2503 }
drh3c7f2dc2007-12-06 13:26:20 +00002504 if( strlen(zDir) - sizeof(SQLITE_TEMP_FILE_PREFIX) - 17 <=0 ){
2505 return SQLITE_ERROR;
2506 }
danielk1977b4b47412007-08-17 15:53:36 +00002507 do{
drh153c62c2007-08-24 03:51:33 +00002508 assert( pVfs->mxPathname==MAX_PATHNAME );
drh3c7f2dc2007-12-06 13:26:20 +00002509 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
danielk1977b4b47412007-08-17 15:53:36 +00002510 j = strlen(zBuf);
2511 sqlite3Randomness(15, &zBuf[j]);
2512 for(i=0; i<15; i++, j++){
2513 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
2514 }
2515 zBuf[j] = 0;
2516 }while( access(zBuf,0)==0 );
2517 return SQLITE_OK;
2518}
2519
2520
2521/*
2522** Turn a relative pathname into a full pathname. The relative path
2523** is stored as a nul-terminated string in the buffer pointed to by
2524** zPath.
2525**
2526** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
2527** (in this case, MAX_PATHNAME bytes). The full-path is written to
2528** this buffer before returning.
2529*/
danielk1977adfb9b02007-09-17 07:02:56 +00002530static int unixFullPathname(
2531 sqlite3_vfs *pVfs, /* Pointer to vfs object */
2532 const char *zPath, /* Possibly relative input path */
2533 int nOut, /* Size of output buffer in bytes */
2534 char *zOut /* Output buffer */
2535){
danielk1977843e65f2007-09-01 16:16:15 +00002536
2537 /* It's odd to simulate an io-error here, but really this is just
2538 ** using the io-error infrastructure to test that SQLite handles this
2539 ** function failing. This function could fail if, for example, the
2540 ** current working directly has been unlinked.
2541 */
2542 SimulateIOError( return SQLITE_ERROR );
2543
drh153c62c2007-08-24 03:51:33 +00002544 assert( pVfs->mxPathname==MAX_PATHNAME );
drh3c7f2dc2007-12-06 13:26:20 +00002545 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00002546 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00002547 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002548 }else{
2549 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00002550 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00002551 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00002552 }
2553 nCwd = strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00002554 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002555 }
2556 return SQLITE_OK;
2557
2558#if 0
2559 /*
2560 ** Remove "/./" path elements and convert "/A/./" path elements
2561 ** to just "/".
2562 */
2563 if( zFull ){
2564 int i, j;
2565 for(i=j=0; zFull[i]; i++){
2566 if( zFull[i]=='/' ){
2567 if( zFull[i+1]=='/' ) continue;
2568 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
2569 i += 1;
2570 continue;
2571 }
2572 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
2573 while( j>0 && zFull[j-1]!='/' ){ j--; }
2574 i += 3;
2575 continue;
2576 }
2577 }
2578 zFull[j++] = zFull[i];
2579 }
2580 zFull[j] = 0;
2581 }
2582#endif
2583}
2584
drh0ccebe72005-06-07 22:22:50 +00002585
drh761df872006-12-21 01:29:22 +00002586#ifndef SQLITE_OMIT_LOAD_EXTENSION
2587/*
2588** Interfaces for opening a shared library, finding entry points
2589** within the shared library, and closing the shared library.
2590*/
2591#include <dlfcn.h>
drh153c62c2007-08-24 03:51:33 +00002592static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
drh761df872006-12-21 01:29:22 +00002593 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
2594}
danielk197795c8a542007-09-01 06:51:27 +00002595
2596/*
2597** SQLite calls this function immediately after a call to unixDlSym() or
2598** unixDlOpen() fails (returns a null pointer). If a more detailed error
2599** message is available, it is written to zBufOut. If no error message
2600** is available, zBufOut is left unmodified and SQLite uses a default
2601** error message.
2602*/
drh153c62c2007-08-24 03:51:33 +00002603static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00002604 char *zErr;
2605 enterMutex();
2606 zErr = dlerror();
2607 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00002608 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00002609 }
2610 leaveMutex();
2611}
drh46c99e02007-08-27 23:26:59 +00002612static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
drh761df872006-12-21 01:29:22 +00002613 return dlsym(pHandle, zSymbol);
2614}
drh46c99e02007-08-27 23:26:59 +00002615static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
danielk1977b4b47412007-08-17 15:53:36 +00002616 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00002617}
danielk1977b4b47412007-08-17 15:53:36 +00002618#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
2619 #define unixDlOpen 0
2620 #define unixDlError 0
2621 #define unixDlSym 0
2622 #define unixDlClose 0
2623#endif
2624
2625/*
danielk197790949c22007-08-17 16:50:38 +00002626** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00002627*/
drh153c62c2007-08-24 03:51:33 +00002628static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
danielk197790949c22007-08-17 16:50:38 +00002629
2630 assert(nBuf>=(sizeof(time_t)+sizeof(int)));
2631
drhbbd42a62004-05-22 17:41:58 +00002632 /* We have to initialize zBuf to prevent valgrind from reporting
2633 ** errors. The reports issued by valgrind are incorrect - we would
2634 ** prefer that the randomness be increased by making use of the
2635 ** uninitialized space in zBuf - but valgrind errors tend to worry
2636 ** some users. Rather than argue, it seems easier just to initialize
2637 ** the whole array and silence valgrind, even if that means less randomness
2638 ** in the random seed.
2639 **
2640 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00002641 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00002642 ** tests repeatable.
2643 */
danielk1977b4b47412007-08-17 15:53:36 +00002644 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00002645#if !defined(SQLITE_TEST)
2646 {
drh842b8642005-01-21 17:53:17 +00002647 int pid, fd;
2648 fd = open("/dev/urandom", O_RDONLY);
2649 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00002650 time_t t;
2651 time(&t);
danielk197790949c22007-08-17 16:50:38 +00002652 memcpy(zBuf, &t, sizeof(t));
2653 pid = getpid();
2654 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
drh842b8642005-01-21 17:53:17 +00002655 }else{
danielk1977b4b47412007-08-17 15:53:36 +00002656 read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00002657 close(fd);
2658 }
drhbbd42a62004-05-22 17:41:58 +00002659 }
2660#endif
2661 return SQLITE_OK;
2662}
2663
danielk1977b4b47412007-08-17 15:53:36 +00002664
drhbbd42a62004-05-22 17:41:58 +00002665/*
2666** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00002667** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00002668** The return value is the number of microseconds of sleep actually
2669** requested from the underlying operating system, a number which
2670** might be greater than or equal to the argument, but not less
2671** than the argument.
drhbbd42a62004-05-22 17:41:58 +00002672*/
drh153c62c2007-08-24 03:51:33 +00002673static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
drhbbd42a62004-05-22 17:41:58 +00002674#if defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00002675 usleep(microseconds);
2676 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00002677#else
danielk1977b4b47412007-08-17 15:53:36 +00002678 int seconds = (microseconds+999999)/1000000;
2679 sleep(seconds);
drh4a50aac2007-08-23 02:47:53 +00002680 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00002681#endif
drh88f474a2006-01-02 20:00:12 +00002682}
2683
2684/*
drhbbd42a62004-05-22 17:41:58 +00002685** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00002686** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00002687*/
2688#ifdef SQLITE_TEST
2689int sqlite3_current_time = 0;
2690#endif
2691
2692/*
2693** Find the current time (in Universal Coordinated Time). Write the
2694** current time and date as a Julian Day number into *prNow and
2695** return 0. Return 1 if the time and date cannot be found.
2696*/
drh153c62c2007-08-24 03:51:33 +00002697static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
drh19e2d372005-08-29 23:00:03 +00002698#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00002699 time_t t;
2700 time(&t);
2701 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00002702#else
2703 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00002704 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00002705 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
2706#endif
drhbbd42a62004-05-22 17:41:58 +00002707#ifdef SQLITE_TEST
2708 if( sqlite3_current_time ){
2709 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
2710 }
2711#endif
2712 return 0;
2713}
danielk1977b4b47412007-08-17 15:53:36 +00002714
drh153c62c2007-08-24 03:51:33 +00002715/*
2716** Return a pointer to the sqlite3DefaultVfs structure. We use
2717** a function rather than give the structure global scope because
2718** some compilers (MSVC) do not allow forward declarations of
2719** initialized structures.
2720*/
2721sqlite3_vfs *sqlite3OsDefaultVfs(void){
2722 static sqlite3_vfs unixVfs = {
2723 1, /* iVersion */
2724 sizeof(unixFile), /* szOsFile */
2725 MAX_PATHNAME, /* mxPathname */
drh153c62c2007-08-24 03:51:33 +00002726 0, /* pNext */
2727 "unix", /* zName */
2728 0, /* pAppData */
2729
2730 unixOpen, /* xOpen */
2731 unixDelete, /* xDelete */
2732 unixAccess, /* xAccess */
danielk197776ee37f2007-09-17 06:06:39 +00002733 unixGetTempname, /* xGetTempName */
drh153c62c2007-08-24 03:51:33 +00002734 unixFullPathname, /* xFullPathname */
2735 unixDlOpen, /* xDlOpen */
2736 unixDlError, /* xDlError */
2737 unixDlSym, /* xDlSym */
2738 unixDlClose, /* xDlClose */
2739 unixRandomness, /* xRandomness */
2740 unixSleep, /* xSleep */
2741 unixCurrentTime /* xCurrentTime */
2742 };
2743
2744 return &unixVfs;
2745}
drhdce8bdb2007-08-16 13:01:44 +00002746
drhbbd42a62004-05-22 17:41:58 +00002747#endif /* OS_UNIX */