blob: 48d2ff176922262f97cc324ed963d796956ba968 [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.
danielk1977822a5162008-05-16 04:51:54 +000014**
drhda0e7682008-07-30 15:27:54 +000015** $Id: os_unix.c,v 1.194 2008/07/30 15:27:54 drh Exp $
drhbbd42a62004-05-22 17:41:58 +000016*/
drhbbd42a62004-05-22 17:41:58 +000017#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000018#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000019
danielk1977e339d652008-06-28 11:23:00 +000020/*
21** If SQLITE_ENABLE_LOCKING_STYLE is defined, then several different
22** locking implementations are provided:
23**
24** * POSIX locking (the default),
25** * No locking,
26** * Dot-file locking,
27** * flock() locking,
28** * AFP locking (OSX only).
29*/
drhbfe66312006-10-03 17:40:40 +000030/* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
31
drh9cbe6352005-11-29 03:13:21 +000032/*
33** These #defines should enable >2GB file support on Posix if the
34** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000035** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000036**
37** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
38** on the compiler command line. This is necessary if you are compiling
39** on a recent machine (ex: RedHat 7.2) but you want your code to work
40** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
41** without this option, LFS is enable. But LFS does not exist in the kernel
42** in RedHat 6.0, so the code won't work. Hence, for maximum binary
43** portability you should omit LFS.
drh9cbe6352005-11-29 03:13:21 +000044*/
45#ifndef SQLITE_DISABLE_LFS
46# define _LARGE_FILE 1
47# ifndef _FILE_OFFSET_BITS
48# define _FILE_OFFSET_BITS 64
49# endif
50# define _LARGEFILE_SOURCE 1
51#endif
drhbbd42a62004-05-22 17:41:58 +000052
drh9cbe6352005-11-29 03:13:21 +000053/*
54** standard include files.
55*/
56#include <sys/types.h>
57#include <sys/stat.h>
58#include <fcntl.h>
59#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000060#include <time.h>
drh19e2d372005-08-29 23:00:03 +000061#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000062#include <errno.h>
danielk1977e339d652008-06-28 11:23:00 +000063
drhbfe66312006-10-03 17:40:40 +000064#ifdef SQLITE_ENABLE_LOCKING_STYLE
65#include <sys/ioctl.h>
66#include <sys/param.h>
67#include <sys/mount.h>
68#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000069
70/*
drhf1a221e2006-01-15 17:27:17 +000071** If we are to be thread-safe, include the pthreads header and define
72** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +000073*/
drhd677b3d2007-08-20 22:48:41 +000074#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +000075# include <pthread.h>
76# define SQLITE_UNIX_THREADS 1
77#endif
78
79/*
80** Default permissions when creating a new file
81*/
82#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
83# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
84#endif
85
danielk1977b4b47412007-08-17 15:53:36 +000086/*
87** Maximum supported path-length.
88*/
89#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +000090
91
92/*
danielk1977ad94b582007-08-20 06:44:22 +000093** The unixFile structure is subclass of sqlite3_file specific for the unix
drh054889e2005-11-30 03:20:31 +000094** protability layer.
drh9cbe6352005-11-29 03:13:21 +000095*/
drh054889e2005-11-30 03:20:31 +000096typedef struct unixFile unixFile;
97struct unixFile {
danielk197762079062007-08-15 17:08:46 +000098 sqlite3_io_methods const *pMethod; /* Always the first entry */
danielk1977967a4a12007-08-20 14:23:44 +000099#ifdef SQLITE_TEST
100 /* In test mode, increase the size of this structure a bit so that
101 ** it is larger than the struct CrashFile defined in test6.c.
102 */
103 char aPadding[32];
104#endif
drh9cbe6352005-11-29 03:13:21 +0000105 struct openCnt *pOpen; /* Info about all open fd's on this inode */
106 struct lockInfo *pLock; /* Info about locks on this inode */
drhbfe66312006-10-03 17:40:40 +0000107#ifdef SQLITE_ENABLE_LOCKING_STYLE
108 void *lockingContext; /* Locking style specific state */
danielk1977e339d652008-06-28 11:23:00 +0000109#endif
drh9cbe6352005-11-29 03:13:21 +0000110 int h; /* The file descriptor */
111 unsigned char locktype; /* The type of lock held on this fd */
drh9cbe6352005-11-29 03:13:21 +0000112 int dirfd; /* File descriptor for the directory */
drhd677b3d2007-08-20 22:48:41 +0000113#if SQLITE_THREADSAFE
danielk1977ad94b582007-08-20 06:44:22 +0000114 pthread_t tid; /* The thread that "owns" this unixFile */
drh9cbe6352005-11-29 03:13:21 +0000115#endif
116};
117
drh0ccebe72005-06-07 22:22:50 +0000118/*
drh198bf392006-01-06 21:52:49 +0000119** Include code that is common to all os_*.c files
120*/
121#include "os_common.h"
122
123/*
drh0ccebe72005-06-07 22:22:50 +0000124** Define various macros that are missing from some systems.
125*/
drhbbd42a62004-05-22 17:41:58 +0000126#ifndef O_LARGEFILE
127# define O_LARGEFILE 0
128#endif
129#ifdef SQLITE_DISABLE_LFS
130# undef O_LARGEFILE
131# define O_LARGEFILE 0
132#endif
133#ifndef O_NOFOLLOW
134# define O_NOFOLLOW 0
135#endif
136#ifndef O_BINARY
137# define O_BINARY 0
138#endif
139
140/*
141** The DJGPP compiler environment looks mostly like Unix, but it
142** lacks the fcntl() system call. So redefine fcntl() to be something
143** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000144** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000145*/
146#ifdef __DJGPP__
147# define fcntl(A,B,C) 0
148#endif
149
150/*
drh2b4b5962005-06-15 17:47:55 +0000151** The threadid macro resolves to the thread-id or to 0. Used for
152** testing and debugging only.
153*/
drhd677b3d2007-08-20 22:48:41 +0000154#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000155#define threadid pthread_self()
156#else
157#define threadid 0
158#endif
159
160/*
danielk1977ad94b582007-08-20 06:44:22 +0000161** Set or check the unixFile.tid field. This field is set when an unixFile
162** is first opened. All subsequent uses of the unixFile verify that the
163** same thread is operating on the unixFile. Some operating systems do
drh2b4b5962005-06-15 17:47:55 +0000164** not allow locks to be overridden by other threads and that restriction
165** means that sqlite3* database handles cannot be moved from one thread
166** to another. This logic makes sure a user does not try to do that
167** by mistake.
drhf1a221e2006-01-15 17:27:17 +0000168**
danielk1977ad94b582007-08-20 06:44:22 +0000169** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
drhf1a221e2006-01-15 17:27:17 +0000170** another as long as we are running on a system that supports threads
171** overriding each others locks (which now the most common behavior)
danielk1977ad94b582007-08-20 06:44:22 +0000172** or if no locks are held. But the unixFile.pLock field needs to be
drhf1a221e2006-01-15 17:27:17 +0000173** recomputed because its key includes the thread-id. See the
174** transferOwnership() function below for additional information
drh2b4b5962005-06-15 17:47:55 +0000175*/
drhd677b3d2007-08-20 22:48:41 +0000176#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000177# define SET_THREADID(X) (X)->tid = pthread_self()
drh029b44b2006-01-15 00:13:15 +0000178# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
179 !pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000180#else
181# define SET_THREADID(X)
182# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000183#endif
184
drhbbd42a62004-05-22 17:41:58 +0000185/*
186** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
187** section 6.5.2.2 lines 483 through 490 specify that when a process
188** sets or clears a lock, that operation overrides any prior locks set
189** by the same process. It does not explicitly say so, but this implies
190** that it overrides locks set by the same process using a different
191** file descriptor. Consider this test case:
drhbbd42a62004-05-22 17:41:58 +0000192** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
193**
194** Suppose ./file1 and ./file2 are really the same file (because
195** one is a hard or symbolic link to the other) then if you set
196** an exclusive lock on fd1, then try to get an exclusive lock
197** on fd2, it works. I would have expected the second lock to
198** fail since there was already a lock on the file due to fd1.
199** But not so. Since both locks came from the same process, the
200** second overrides the first, even though they were on different
201** file descriptors opened on different file names.
202**
203** Bummer. If you ask me, this is broken. Badly broken. It means
204** that we cannot use POSIX locks to synchronize file access among
205** competing threads of the same process. POSIX locks will work fine
206** to synchronize access for threads in separate processes, but not
207** threads within the same process.
208**
209** To work around the problem, SQLite has to manage file locks internally
210** on its own. Whenever a new database is opened, we have to find the
211** specific inode of the database file (the inode is determined by the
212** st_dev and st_ino fields of the stat structure that fstat() fills in)
213** and check for locks already existing on that inode. When locks are
214** created or removed, we have to look at our own internal record of the
215** locks to see if another thread has previously set a lock on that same
216** inode.
217**
danielk1977ad94b582007-08-20 06:44:22 +0000218** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000219** descriptor. It is now a structure that holds the integer file
220** descriptor and a pointer to a structure that describes the internal
221** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000222** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000223** point to the same locking structure. The locking structure keeps
224** a reference count (so we will know when to delete it) and a "cnt"
225** field that tells us its internal lock status. cnt==0 means the
226** file is unlocked. cnt==-1 means the file has an exclusive lock.
227** cnt>0 means there are cnt shared locks on the file.
228**
229** Any attempt to lock or unlock a file first checks the locking
230** structure. The fcntl() system call is only invoked to set a
231** POSIX lock if the internal lock structure transitions between
232** a locked and an unlocked state.
233**
234** 2004-Jan-11:
235** More recent discoveries about POSIX advisory locks. (The more
236** I discover, the more I realize the a POSIX advisory locks are
237** an abomination.)
238**
239** If you close a file descriptor that points to a file that has locks,
240** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000241** released. To work around this problem, each unixFile structure contains
drhbbd42a62004-05-22 17:41:58 +0000242** a pointer to an openCnt structure. There is one openCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000243** per open inode, which means that multiple unixFile can point to a single
244** openCnt. When an attempt is made to close an unixFile, if there are
245** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000246** to close() the file descriptor is deferred until all of the locks clear.
247** The openCnt structure keeps a list of file descriptors that need to
248** be closed and that list is walked (and cleared) when the last lock
249** clears.
250**
251** First, under Linux threads, because each thread has a separate
252** process ID, lock operations in one thread do not override locks
253** to the same file in other threads. Linux threads behave like
254** separate processes in this respect. But, if you close a file
255** descriptor in linux threads, all locks are cleared, even locks
256** on other threads and even though the other threads have different
257** process IDs. Linux threads is inconsistent in this respect.
258** (I'm beginning to think that linux threads is an abomination too.)
259** The consequence of this all is that the hash table for the lockInfo
260** structure has to include the process id as part of its key because
261** locks in different threads are treated as distinct. But the
262** openCnt structure should not include the process id in its
263** key because close() clears lock on all threads, not just the current
264** thread. Were it not for this goofiness in linux threads, we could
265** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000266**
267** 2004-Jun-28:
268** On some versions of linux, threads can override each others locks.
269** On others not. Sometimes you can change the behavior on the same
270** system by setting the LD_ASSUME_KERNEL environment variable. The
271** POSIX standard is silent as to which behavior is correct, as far
272** as I can tell, so other versions of unix might show the same
273** inconsistency. There is no little doubt in my mind that posix
274** advisory locks and linux threads are profoundly broken.
275**
276** To work around the inconsistencies, we have to test at runtime
277** whether or not threads can override each others locks. This test
278** is run once, the first time any lock is attempted. A static
279** variable is set to record the results of this test for future
280** use.
drhbbd42a62004-05-22 17:41:58 +0000281*/
282
283/*
284** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000285** to locate a particular lockInfo structure given its inode.
286**
287** If threads cannot override each others locks, then we set the
288** lockKey.tid field to the thread ID. If threads can override
drhf1a221e2006-01-15 17:27:17 +0000289** each others locks then tid is always set to zero. tid is omitted
290** if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000291*/
292struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000293 dev_t dev; /* Device number */
294 ino_t ino; /* Inode number */
drhd677b3d2007-08-20 22:48:41 +0000295#if SQLITE_THREADSAFE
drhd9cb6ac2005-10-20 07:28:17 +0000296 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000297#endif
drhbbd42a62004-05-22 17:41:58 +0000298};
299
300/*
301** An instance of the following structure is allocated for each open
302** inode on each thread with a different process ID. (Threads have
303** different process IDs on linux, but not on most other unixes.)
304**
danielk1977ad94b582007-08-20 06:44:22 +0000305** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000306** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000307** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000308*/
309struct lockInfo {
310 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000311 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000312 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000313 int nRef; /* Number of pointers to this structure */
drhda0e7682008-07-30 15:27:54 +0000314 struct lockInfo *pNext, *pPrev; /* List of all lockInfo objects */
drhbbd42a62004-05-22 17:41:58 +0000315};
316
317/*
318** An instance of the following structure serves as the key used
319** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000320** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000321*/
322struct openKey {
323 dev_t dev; /* Device number */
324 ino_t ino; /* Inode number */
325};
326
327/*
328** An instance of the following structure is allocated for each open
329** inode. This structure keeps track of the number of locks on that
330** inode. If a close is attempted against an inode that is holding
331** locks, the close is deferred until all locks clear by adding the
332** file descriptor to be closed to the pending list.
333*/
334struct openCnt {
335 struct openKey key; /* The lookup key */
336 int nRef; /* Number of pointers to this structure */
337 int nLock; /* Number of outstanding locks */
338 int nPending; /* Number of pending close() operations */
339 int *aPending; /* Malloced space holding fd's awaiting a close() */
drhda0e7682008-07-30 15:27:54 +0000340 struct openCnt *pNext, *pPrev; /* List of all openCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000341};
342
drhda0e7682008-07-30 15:27:54 +0000343/*
344** List of all lockInfo and openCnt objects. This used to be a hash
345** table. But the number of objects is rarely more than a dozen and
346** never exceeds a few thousand. And lookup is not on a critical
347** path oo a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000348*/
drhda0e7682008-07-30 15:27:54 +0000349static struct lockInfo *lockList = 0;
350static struct openCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000351
drhbfe66312006-10-03 17:40:40 +0000352/*
353** The locking styles are associated with the different file locking
354** capabilities supported by different file systems.
355**
356** POSIX locking style fully supports shared and exclusive byte-range locks
danielk1977e339d652008-06-28 11:23:00 +0000357** AFP locking only supports exclusive byte-range locks
drhbfe66312006-10-03 17:40:40 +0000358** FLOCK only supports a single file-global exclusive lock
359** DOTLOCK isn't a true locking style, it refers to the use of a special
360** file named the same as the database file with a '.lock' extension, this
361** can be used on file systems that do not offer any reliable file locking
362** NO locking means that no locking will be attempted, this is only used for
363** read-only file systems currently
364** UNSUPPORTED means that no locking will be attempted, this is only used for
365** file systems that are known to be unsupported
366*/
danielk1977e339d652008-06-28 11:23:00 +0000367#define LOCKING_STYLE_POSIX 1
drhda0e7682008-07-30 15:27:54 +0000368#define LOCKING_STYLE_NONE 2
danielk1977e339d652008-06-28 11:23:00 +0000369#define LOCKING_STYLE_DOTFILE 3
drhda0e7682008-07-30 15:27:54 +0000370#define LOCKING_STYLE_FLOCK 4
danielk1977e339d652008-06-28 11:23:00 +0000371#define LOCKING_STYLE_AFP 5
drhbfe66312006-10-03 17:40:40 +0000372
danielk1977ad94b582007-08-20 06:44:22 +0000373/*
374** Helper functions to obtain and relinquish the global mutex.
375*/
danielk1977b4b47412007-08-17 15:53:36 +0000376static void enterMutex(){
danielk197759f8c082008-06-18 17:09:10 +0000377 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
danielk1977b4b47412007-08-17 15:53:36 +0000378}
379static void leaveMutex(){
danielk197759f8c082008-06-18 17:09:10 +0000380 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
danielk1977b4b47412007-08-17 15:53:36 +0000381}
382
drhd677b3d2007-08-20 22:48:41 +0000383#if SQLITE_THREADSAFE
drh5fdae772004-06-29 03:29:00 +0000384/*
385** This variable records whether or not threads can override each others
386** locks.
387**
388** 0: No. Threads cannot override each others locks.
389** 1: Yes. Threads can override each others locks.
390** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000391**
drh5062d3a2006-01-31 23:03:35 +0000392** On some systems, we know at compile-time if threads can override each
393** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
394** will be set appropriately. On other systems, we have to check at
395** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
396** undefined.
397**
drhf1a221e2006-01-15 17:27:17 +0000398** This variable normally has file scope only. But during testing, we make
399** it a global so that the test code can change its value in order to verify
400** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000401*/
drh5062d3a2006-01-31 23:03:35 +0000402#ifndef SQLITE_THREAD_OVERRIDE_LOCK
403# define SQLITE_THREAD_OVERRIDE_LOCK -1
404#endif
drh029b44b2006-01-15 00:13:15 +0000405#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000406int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000407#else
drh5062d3a2006-01-31 23:03:35 +0000408static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000409#endif
drh5fdae772004-06-29 03:29:00 +0000410
411/*
412** This structure holds information passed into individual test
413** threads by the testThreadLockingBehavior() routine.
414*/
415struct threadTestData {
416 int fd; /* File to be locked */
417 struct flock lock; /* The locking operation */
418 int result; /* Result of the locking operation */
419};
420
drh2b4b5962005-06-15 17:47:55 +0000421#ifdef SQLITE_LOCK_TRACE
422/*
423** Print out information about all locking operations.
424**
425** This routine is used for troubleshooting locks on multithreaded
426** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
427** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000428** turned off.
drh2b4b5962005-06-15 17:47:55 +0000429*/
430static int lockTrace(int fd, int op, struct flock *p){
431 char *zOpName, *zType;
432 int s;
433 int savedErrno;
434 if( op==F_GETLK ){
435 zOpName = "GETLK";
436 }else if( op==F_SETLK ){
437 zOpName = "SETLK";
438 }else{
439 s = fcntl(fd, op, p);
440 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
441 return s;
442 }
443 if( p->l_type==F_RDLCK ){
444 zType = "RDLCK";
445 }else if( p->l_type==F_WRLCK ){
446 zType = "WRLCK";
447 }else if( p->l_type==F_UNLCK ){
448 zType = "UNLCK";
449 }else{
450 assert( 0 );
451 }
452 assert( p->l_whence==SEEK_SET );
453 s = fcntl(fd, op, p);
454 savedErrno = errno;
455 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
456 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
457 (int)p->l_pid, s);
drhe2396a12007-03-29 20:19:58 +0000458 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
drh2b4b5962005-06-15 17:47:55 +0000459 struct flock l2;
460 l2 = *p;
461 fcntl(fd, F_GETLK, &l2);
462 if( l2.l_type==F_RDLCK ){
463 zType = "RDLCK";
464 }else if( l2.l_type==F_WRLCK ){
465 zType = "WRLCK";
466 }else if( l2.l_type==F_UNLCK ){
467 zType = "UNLCK";
468 }else{
469 assert( 0 );
470 }
471 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
472 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
473 }
474 errno = savedErrno;
475 return s;
476}
477#define fcntl lockTrace
478#endif /* SQLITE_LOCK_TRACE */
479
drh5fdae772004-06-29 03:29:00 +0000480/*
481** The testThreadLockingBehavior() routine launches two separate
482** threads on this routine. This routine attempts to lock a file
483** descriptor then returns. The success or failure of that attempt
484** allows the testThreadLockingBehavior() procedure to determine
485** whether or not threads can override each others locks.
486*/
487static void *threadLockingTest(void *pArg){
488 struct threadTestData *pData = (struct threadTestData*)pArg;
489 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
490 return pArg;
491}
492
493/*
494** This procedure attempts to determine whether or not threads
495** can override each others locks then sets the
496** threadsOverrideEachOthersLocks variable appropriately.
497*/
danielk19774d5238f2006-01-27 06:32:00 +0000498static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000499 int fd;
500 struct threadTestData d[2];
501 pthread_t t[2];
502
503 fd = dup(fd_orig);
504 if( fd<0 ) return;
505 memset(d, 0, sizeof(d));
506 d[0].fd = fd;
507 d[0].lock.l_type = F_RDLCK;
508 d[0].lock.l_len = 1;
509 d[0].lock.l_start = 0;
510 d[0].lock.l_whence = SEEK_SET;
511 d[1] = d[0];
512 d[1].lock.l_type = F_WRLCK;
513 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
514 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
515 pthread_join(t[0], 0);
516 pthread_join(t[1], 0);
517 close(fd);
518 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
519}
drhd677b3d2007-08-20 22:48:41 +0000520#endif /* SQLITE_THREADSAFE */
drh5fdae772004-06-29 03:29:00 +0000521
drhbbd42a62004-05-22 17:41:58 +0000522/*
523** Release a lockInfo structure previously allocated by findLockInfo().
524*/
525static void releaseLockInfo(struct lockInfo *pLock){
danielk1977e339d652008-06-28 11:23:00 +0000526 if( pLock ){
527 pLock->nRef--;
528 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000529 if( pLock->pPrev ){
530 assert( pLock->pPrev->pNext==pLock );
531 pLock->pPrev->pNext = pLock->pNext;
532 }else{
533 assert( lockList==pLock );
534 lockList = pLock->pNext;
535 }
536 if( pLock->pNext ){
537 assert( pLock->pNext->pPrev==pLock );
538 pLock->pNext->pPrev = pLock->pPrev;
539 }
danielk1977e339d652008-06-28 11:23:00 +0000540 sqlite3_free(pLock);
541 }
drhbbd42a62004-05-22 17:41:58 +0000542 }
543}
544
545/*
546** Release a openCnt structure previously allocated by findLockInfo().
547*/
548static void releaseOpenCnt(struct openCnt *pOpen){
danielk1977e339d652008-06-28 11:23:00 +0000549 if( pOpen ){
550 pOpen->nRef--;
551 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000552 if( pOpen->pPrev ){
553 assert( pOpen->pPrev->pNext==pOpen );
554 pOpen->pPrev->pNext = pOpen->pNext;
555 }else{
556 assert( openList==pOpen );
557 openList = pOpen->pNext;
558 }
559 if( pOpen->pNext ){
560 assert( pOpen->pNext->pPrev==pOpen );
561 pOpen->pNext->pPrev = pOpen->pPrev;
562 }
563 sqlite3_free(pOpen->aPending);
danielk1977e339d652008-06-28 11:23:00 +0000564 sqlite3_free(pOpen);
565 }
drhbbd42a62004-05-22 17:41:58 +0000566 }
567}
568
drh93a960a2008-07-10 00:32:42 +0000569#ifdef SQLITE_ENABLE_LOCKING_STYLE
drhbfe66312006-10-03 17:40:40 +0000570/*
571** Tests a byte-range locking query to see if byte range locks are
572** supported, if not we fall back to dotlockLockingStyle.
573*/
danielk1977e339d652008-06-28 11:23:00 +0000574static int testLockingStyle(int fd){
drhbfe66312006-10-03 17:40:40 +0000575 struct flock lockInfo;
danielk1977e339d652008-06-28 11:23:00 +0000576
577 /* Test byte-range lock using fcntl(). If the call succeeds,
578 ** assume that the file-system supports POSIX style locks.
579 */
drhbfe66312006-10-03 17:40:40 +0000580 lockInfo.l_len = 1;
581 lockInfo.l_start = 0;
582 lockInfo.l_whence = SEEK_SET;
583 lockInfo.l_type = F_RDLCK;
danielk1977ad94b582007-08-20 06:44:22 +0000584 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
danielk1977e339d652008-06-28 11:23:00 +0000585 return LOCKING_STYLE_POSIX;
586 }
drhbfe66312006-10-03 17:40:40 +0000587
danielk1977e339d652008-06-28 11:23:00 +0000588 /* Testing for flock() can give false positives. So if if the above
589 ** test fails, then we fall back to using dot-file style locking.
drhbfe66312006-10-03 17:40:40 +0000590 */
danielk1977e339d652008-06-28 11:23:00 +0000591 return LOCKING_STYLE_DOTFILE;
drhbfe66312006-10-03 17:40:40 +0000592}
drh93a960a2008-07-10 00:32:42 +0000593#endif
drhbfe66312006-10-03 17:40:40 +0000594
595/*
danielk1977e339d652008-06-28 11:23:00 +0000596** If SQLITE_ENABLE_LOCKING_STYLE is defined, this function Examines the
597** f_fstypename entry in the statfs structure as returned by stat() for
598** the file system hosting the database file and selects the appropriate
599** locking style based on its value. These values and assignments are
600** based on Darwin/OSX behavior and have not been thoroughly tested on
drhbfe66312006-10-03 17:40:40 +0000601** other systems.
danielk1977e339d652008-06-28 11:23:00 +0000602**
603** If SQLITE_ENABLE_LOCKING_STYLE is not defined, this function always
604** returns LOCKING_STYLE_POSIX.
drhbfe66312006-10-03 17:40:40 +0000605*/
danielk1977e339d652008-06-28 11:23:00 +0000606static int detectLockingStyle(
607 sqlite3_vfs *pVfs,
danielk1977ad94b582007-08-20 06:44:22 +0000608 const char *filePath,
609 int fd
610){
danielk1977e339d652008-06-28 11:23:00 +0000611#ifdef SQLITE_ENABLE_LOCKING_STYLE
612 struct Mapping {
613 const char *zFilesystem;
614 int eLockingStyle;
615 } aMap[] = {
616 { "hfs", LOCKING_STYLE_POSIX },
617 { "ufs", LOCKING_STYLE_POSIX },
618 { "afpfs", LOCKING_STYLE_AFP },
619 { "smbfs", LOCKING_STYLE_FLOCK },
620 { "msdos", LOCKING_STYLE_DOTFILE },
621 { "webdav", LOCKING_STYLE_NONE },
622 { 0, 0 }
623 };
624 int i;
drhbfe66312006-10-03 17:40:40 +0000625 struct statfs fsInfo;
626
danielk1977e339d652008-06-28 11:23:00 +0000627 if( !filePath ){
628 return LOCKING_STYLE_NONE;
drh339eb0b2008-03-07 15:34:11 +0000629 }
danielk1977e339d652008-06-28 11:23:00 +0000630 if( pVfs->pAppData ){
631 return (int)pVfs->pAppData;
drh339eb0b2008-03-07 15:34:11 +0000632 }
drhbfe66312006-10-03 17:40:40 +0000633
danielk1977e339d652008-06-28 11:23:00 +0000634 if( statfs(filePath, &fsInfo) != -1 ){
635 if( fsInfo.f_flags & MNT_RDONLY ){
636 return LOCKING_STYLE_NONE;
637 }
638 for(i=0; aMap[i].zFilesystem; i++){
639 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
640 return aMap[i].eLockingStyle;
641 }
642 }
643 }
644
645 /* Default case. Handles, amongst others, "nfs". */
646 return testLockingStyle(fd);
647#endif
648 return LOCKING_STYLE_POSIX;
649}
drhbfe66312006-10-03 17:40:40 +0000650
drhbbd42a62004-05-22 17:41:58 +0000651/*
652** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000653** describes that file descriptor. Create new ones if necessary. The
654** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000655**
drh65594042008-05-05 16:56:34 +0000656** Return an appropriate error code.
drhbbd42a62004-05-22 17:41:58 +0000657*/
drh38f82712004-06-18 17:10:16 +0000658static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000659 int fd, /* The file descriptor used in the key */
660 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000661 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000662){
663 int rc;
664 struct lockKey key1;
665 struct openKey key2;
666 struct stat statbuf;
667 struct lockInfo *pLock;
668 struct openCnt *pOpen;
669 rc = fstat(fd, &statbuf);
drh65594042008-05-05 16:56:34 +0000670 if( rc!=0 ){
671#ifdef EOVERFLOW
672 if( errno==EOVERFLOW ) return SQLITE_NOLFS;
673#endif
674 return SQLITE_IOERR;
675 }
danielk1977441b09a2006-01-05 13:48:29 +0000676
drhbbd42a62004-05-22 17:41:58 +0000677 memset(&key1, 0, sizeof(key1));
678 key1.dev = statbuf.st_dev;
679 key1.ino = statbuf.st_ino;
drhd677b3d2007-08-20 22:48:41 +0000680#if SQLITE_THREADSAFE
drh5fdae772004-06-29 03:29:00 +0000681 if( threadsOverrideEachOthersLocks<0 ){
682 testThreadLockingBehavior(fd);
683 }
684 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
685#endif
drhbbd42a62004-05-22 17:41:58 +0000686 memset(&key2, 0, sizeof(key2));
687 key2.dev = statbuf.st_dev;
688 key2.ino = statbuf.st_ino;
drhda0e7682008-07-30 15:27:54 +0000689 pLock = lockList;
690 while( pLock && memcmp(&key1, &pLock->key, sizeof(key1)) ){
691 pLock = pLock->pNext;
692 }
drhbbd42a62004-05-22 17:41:58 +0000693 if( pLock==0 ){
drh17435752007-08-16 04:30:38 +0000694 pLock = sqlite3_malloc( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000695 if( pLock==0 ){
drh65594042008-05-05 16:56:34 +0000696 rc = SQLITE_NOMEM;
danielk1977441b09a2006-01-05 13:48:29 +0000697 goto exit_findlockinfo;
698 }
drhbbd42a62004-05-22 17:41:58 +0000699 pLock->key = key1;
700 pLock->nRef = 1;
701 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000702 pLock->locktype = 0;
drhda0e7682008-07-30 15:27:54 +0000703 pLock->pNext = lockList;
704 pLock->pPrev = 0;
705 if( lockList ) lockList->pPrev = pLock;
706 lockList = pLock;
drhbbd42a62004-05-22 17:41:58 +0000707 }else{
708 pLock->nRef++;
709 }
710 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000711 if( ppOpen!=0 ){
drhda0e7682008-07-30 15:27:54 +0000712 pOpen = openList;
713 while( pOpen && memcmp(&key2, &pOpen->key, sizeof(key2)) ){
714 pOpen = pOpen->pNext;
715 }
drhbbd42a62004-05-22 17:41:58 +0000716 if( pOpen==0 ){
drh17435752007-08-16 04:30:38 +0000717 pOpen = sqlite3_malloc( sizeof(*pOpen) );
drh029b44b2006-01-15 00:13:15 +0000718 if( pOpen==0 ){
719 releaseLockInfo(pLock);
drh65594042008-05-05 16:56:34 +0000720 rc = SQLITE_NOMEM;
drh029b44b2006-01-15 00:13:15 +0000721 goto exit_findlockinfo;
722 }
723 pOpen->key = key2;
724 pOpen->nRef = 1;
725 pOpen->nLock = 0;
726 pOpen->nPending = 0;
727 pOpen->aPending = 0;
drhda0e7682008-07-30 15:27:54 +0000728 pOpen->pNext = openList;
729 pOpen->pPrev = 0;
730 if( openList ) openList->pPrev = pOpen;
731 openList = pOpen;
drh029b44b2006-01-15 00:13:15 +0000732 }else{
733 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000734 }
drh029b44b2006-01-15 00:13:15 +0000735 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000736 }
danielk1977441b09a2006-01-05 13:48:29 +0000737
738exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000739 return rc;
drhbbd42a62004-05-22 17:41:58 +0000740}
741
drh64b1bea2006-01-15 02:30:57 +0000742#ifdef SQLITE_DEBUG
743/*
744** Helper function for printing out trace information from debugging
745** binaries. This returns the string represetation of the supplied
746** integer lock-type.
747*/
748static const char *locktypeName(int locktype){
749 switch( locktype ){
750 case NO_LOCK: return "NONE";
751 case SHARED_LOCK: return "SHARED";
752 case RESERVED_LOCK: return "RESERVED";
753 case PENDING_LOCK: return "PENDING";
754 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
755 }
756 return "ERROR";
757}
758#endif
759
drhbbd42a62004-05-22 17:41:58 +0000760/*
drh029b44b2006-01-15 00:13:15 +0000761** If we are currently in a different thread than the thread that the
762** unixFile argument belongs to, then transfer ownership of the unixFile
763** over to the current thread.
764**
765** A unixFile is only owned by a thread on systems where one thread is
766** unable to override locks created by a different thread. RedHat9 is
767** an example of such a system.
768**
769** Ownership transfer is only allowed if the unixFile is currently unlocked.
770** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000771** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000772*/
drhd677b3d2007-08-20 22:48:41 +0000773#if SQLITE_THREADSAFE
drh029b44b2006-01-15 00:13:15 +0000774static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000775 int rc;
drh029b44b2006-01-15 00:13:15 +0000776 pthread_t hSelf;
777 if( threadsOverrideEachOthersLocks ){
778 /* Ownership transfers not needed on this system */
779 return SQLITE_OK;
780 }
781 hSelf = pthread_self();
782 if( pthread_equal(pFile->tid, hSelf) ){
783 /* We are still in the same thread */
drh4f0c5872007-03-26 22:05:01 +0000784 OSTRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000785 return SQLITE_OK;
786 }
787 if( pFile->locktype!=NO_LOCK ){
788 /* We cannot change ownership while we are holding a lock! */
789 return SQLITE_MISUSE;
790 }
drh4f0c5872007-03-26 22:05:01 +0000791 OSTRACE4("Transfer ownership of %d from %d to %d\n",
792 pFile->h, pFile->tid, hSelf);
drh029b44b2006-01-15 00:13:15 +0000793 pFile->tid = hSelf;
drhbfe66312006-10-03 17:40:40 +0000794 if (pFile->pLock != NULL) {
795 releaseLockInfo(pFile->pLock);
796 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
drh4f0c5872007-03-26 22:05:01 +0000797 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +0000798 locktypeName(pFile->locktype),
799 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
800 return rc;
801 } else {
802 return SQLITE_OK;
803 }
drh029b44b2006-01-15 00:13:15 +0000804}
805#else
drhf1a221e2006-01-15 17:27:17 +0000806 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +0000807# define transferOwnership(X) SQLITE_OK
808#endif
809
810/*
danielk19772a6bdf62007-08-20 16:07:00 +0000811** Seek to the offset passed as the second argument, then read cnt
812** bytes into pBuf. Return the number of bytes actually read.
drh9e0ebbf2007-10-23 15:59:18 +0000813**
814** NB: If you define USE_PREAD or USE_PREAD64, then it might also
815** be necessary to define _XOPEN_SOURCE to be 500. This varies from
816** one system to another. Since SQLite does not define USE_PREAD
817** any any form by default, we will not attempt to define _XOPEN_SOURCE.
818** See tickets #2741 and #2681.
drhb912b282006-03-23 22:42:20 +0000819*/
danielk197762079062007-08-15 17:08:46 +0000820static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +0000821 int got;
drh8ebf6702007-02-06 11:11:08 +0000822 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +0000823 TIMER_START;
drh8350a212007-03-22 15:22:06 +0000824#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +0000825 got = pread(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +0000826 SimulateIOError( got = -1 );
drh8350a212007-03-22 15:22:06 +0000827#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +0000828 got = pread64(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +0000829 SimulateIOError( got = -1 );
drhb912b282006-03-23 22:42:20 +0000830#else
danielk197762079062007-08-15 17:08:46 +0000831 newOffset = lseek(id->h, offset, SEEK_SET);
drhbb5f18d2007-04-06 18:23:17 +0000832 SimulateIOError( newOffset-- );
danielk197762079062007-08-15 17:08:46 +0000833 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +0000834 return -1;
835 }
drhb912b282006-03-23 22:42:20 +0000836 got = read(id->h, pBuf, cnt);
837#endif
drh15d00c42007-02-27 02:01:14 +0000838 TIMER_END;
shane9bcbdad2008-05-29 20:22:37 +0000839 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +0000840 return got;
841}
842
843/*
drhbbd42a62004-05-22 17:41:58 +0000844** Read data from a file into a buffer. Return SQLITE_OK if all
845** bytes were read successfully and SQLITE_IOERR if anything goes
846** wrong.
847*/
danielk197762079062007-08-15 17:08:46 +0000848static int unixRead(
849 sqlite3_file *id,
850 void *pBuf,
851 int amt,
852 sqlite3_int64 offset
853){
drhbbd42a62004-05-22 17:41:58 +0000854 int got;
drh9cbe6352005-11-29 03:13:21 +0000855 assert( id );
danielk197762079062007-08-15 17:08:46 +0000856 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000857 if( got==amt ){
858 return SQLITE_OK;
drh4ac285a2006-09-15 07:28:50 +0000859 }else if( got<0 ){
860 return SQLITE_IOERR_READ;
drhbbd42a62004-05-22 17:41:58 +0000861 }else{
drhbafda092007-01-03 23:36:22 +0000862 memset(&((char*)pBuf)[got], 0, amt-got);
drh4ac285a2006-09-15 07:28:50 +0000863 return SQLITE_IOERR_SHORT_READ;
drhbbd42a62004-05-22 17:41:58 +0000864 }
865}
866
867/*
drhb912b282006-03-23 22:42:20 +0000868** Seek to the offset in id->offset then read cnt bytes into pBuf.
869** Return the number of bytes actually read. Update the offset.
870*/
danielk197762079062007-08-15 17:08:46 +0000871static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +0000872 int got;
drh8ebf6702007-02-06 11:11:08 +0000873 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +0000874 TIMER_START;
drh8350a212007-03-22 15:22:06 +0000875#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +0000876 got = pwrite(id->h, pBuf, cnt, offset);
drh8350a212007-03-22 15:22:06 +0000877#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +0000878 got = pwrite64(id->h, pBuf, cnt, offset);
drhb912b282006-03-23 22:42:20 +0000879#else
danielk197762079062007-08-15 17:08:46 +0000880 newOffset = lseek(id->h, offset, SEEK_SET);
881 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +0000882 return -1;
883 }
drhb912b282006-03-23 22:42:20 +0000884 got = write(id->h, pBuf, cnt);
885#endif
drh15d00c42007-02-27 02:01:14 +0000886 TIMER_END;
shane9bcbdad2008-05-29 20:22:37 +0000887 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +0000888 return got;
889}
890
891
892/*
drhbbd42a62004-05-22 17:41:58 +0000893** Write data from a buffer into a file. Return SQLITE_OK on success
894** or some other error code on failure.
895*/
danielk197762079062007-08-15 17:08:46 +0000896static int unixWrite(
897 sqlite3_file *id,
898 const void *pBuf,
899 int amt,
900 sqlite3_int64 offset
901){
drhbbd42a62004-05-22 17:41:58 +0000902 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000903 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000904 assert( amt>0 );
danielk197762079062007-08-15 17:08:46 +0000905 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000906 amt -= wrote;
danielk197762079062007-08-15 17:08:46 +0000907 offset += wrote;
drhbbd42a62004-05-22 17:41:58 +0000908 pBuf = &((char*)pBuf)[wrote];
909 }
drh59685932006-09-14 13:47:11 +0000910 SimulateIOError(( wrote=(-1), amt=1 ));
911 SimulateDiskfullError(( wrote=0, amt=1 ));
drhbbd42a62004-05-22 17:41:58 +0000912 if( amt>0 ){
drh59685932006-09-14 13:47:11 +0000913 if( wrote<0 ){
drh4ac285a2006-09-15 07:28:50 +0000914 return SQLITE_IOERR_WRITE;
drh59685932006-09-14 13:47:11 +0000915 }else{
916 return SQLITE_FULL;
917 }
drhbbd42a62004-05-22 17:41:58 +0000918 }
919 return SQLITE_OK;
920}
921
drhb851b2c2005-03-10 14:11:12 +0000922#ifdef SQLITE_TEST
923/*
924** Count the number of fullsyncs and normal syncs. This is used to test
925** that syncs and fullsyncs are occuring at the right times.
926*/
927int sqlite3_sync_count = 0;
928int sqlite3_fullsync_count = 0;
929#endif
930
drhf2f23912005-10-05 10:29:36 +0000931/*
932** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
933** Otherwise use fsync() in its place.
934*/
935#ifndef HAVE_FDATASYNC
936# define fdatasync fsync
937#endif
938
drhac530b12006-02-11 01:25:50 +0000939/*
940** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
941** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
942** only available on Mac OS X. But that could change.
943*/
944#ifdef F_FULLFSYNC
945# define HAVE_FULLFSYNC 1
946#else
947# define HAVE_FULLFSYNC 0
948#endif
949
drhb851b2c2005-03-10 14:11:12 +0000950
drhbbd42a62004-05-22 17:41:58 +0000951/*
drhdd809b02004-07-17 21:44:57 +0000952** The fsync() system call does not work as advertised on many
953** unix systems. The following procedure is an attempt to make
954** it work better.
drh1398ad32005-01-19 23:24:50 +0000955**
956** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
957** for testing when we want to run through the test suite quickly.
958** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
959** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
960** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000961*/
drheb796a72005-09-08 12:38:41 +0000962static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +0000963 int rc;
drhb851b2c2005-03-10 14:11:12 +0000964
965 /* Record the number of times that we do a normal fsync() and
966 ** FULLSYNC. This is used during testing to verify that this procedure
967 ** gets called with the correct arguments.
968 */
969#ifdef SQLITE_TEST
970 if( fullSync ) sqlite3_fullsync_count++;
971 sqlite3_sync_count++;
972#endif
973
974 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
975 ** no-op
976 */
977#ifdef SQLITE_NO_SYNC
978 rc = SQLITE_OK;
979#else
980
drhac530b12006-02-11 01:25:50 +0000981#if HAVE_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +0000982 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +0000983 rc = fcntl(fd, F_FULLFSYNC, 0);
aswiftae0943b2007-01-31 23:37:07 +0000984 }else{
985 rc = 1;
986 }
987 /* If the FULLFSYNC failed, fall back to attempting an fsync().
988 * It shouldn't be possible for fullfsync to fail on the local
989 * file system (on OSX), so failure indicates that FULLFSYNC
990 * isn't supported for this file system. So, attempt an fsync
991 * and (for now) ignore the overhead of a superfluous fcntl call.
992 * It'd be better to detect fullfsync support once and avoid
993 * the fcntl call every time sync is called.
994 */
995 if( rc ) rc = fsync(fd);
996
997#else
drheb796a72005-09-08 12:38:41 +0000998 if( dataOnly ){
999 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +00001000 }else{
drheb796a72005-09-08 12:38:41 +00001001 rc = fsync(fd);
1002 }
aswiftae0943b2007-01-31 23:37:07 +00001003#endif /* HAVE_FULLFSYNC */
drhb851b2c2005-03-10 14:11:12 +00001004#endif /* defined(SQLITE_NO_SYNC) */
1005
drhdd809b02004-07-17 21:44:57 +00001006 return rc;
1007}
1008
1009/*
drhbbd42a62004-05-22 17:41:58 +00001010** Make sure all writes to a particular file are committed to disk.
1011**
drheb796a72005-09-08 12:38:41 +00001012** If dataOnly==0 then both the file itself and its metadata (file
1013** size, access time, etc) are synced. If dataOnly!=0 then only the
1014** file data is synced.
1015**
drhbbd42a62004-05-22 17:41:58 +00001016** Under Unix, also make sure that the directory entry for the file
1017** has been created by fsync-ing the directory that contains the file.
1018** If we do not do this and we encounter a power failure, the directory
1019** entry for the journal might not exist after we reboot. The next
1020** SQLite to access the file will not know that the journal exists (because
1021** the directory entry for the journal was never created) and the transaction
1022** will not roll back - possibly leading to database corruption.
1023*/
danielk197790949c22007-08-17 16:50:38 +00001024static int unixSync(sqlite3_file *id, int flags){
drh59685932006-09-14 13:47:11 +00001025 int rc;
drh054889e2005-11-30 03:20:31 +00001026 unixFile *pFile = (unixFile*)id;
danielk197790949c22007-08-17 16:50:38 +00001027
danielk1977f036aef2007-08-20 05:36:51 +00001028 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
1029 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
1030
danielk1977c16d4632007-08-30 14:49:58 +00001031 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
danielk1977f036aef2007-08-20 05:36:51 +00001032 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
1033 || (flags&0x0F)==SQLITE_SYNC_FULL
danielk1977f036aef2007-08-20 05:36:51 +00001034 );
danielk197790949c22007-08-17 16:50:38 +00001035
drh054889e2005-11-30 03:20:31 +00001036 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001037 OSTRACE2("SYNC %-3d\n", pFile->h);
danielk197790949c22007-08-17 16:50:38 +00001038 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
drh59685932006-09-14 13:47:11 +00001039 SimulateIOError( rc=1 );
1040 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001041 return SQLITE_IOERR_FSYNC;
drhbbd42a62004-05-22 17:41:58 +00001042 }
drh054889e2005-11-30 03:20:31 +00001043 if( pFile->dirfd>=0 ){
drh4f0c5872007-03-26 22:05:01 +00001044 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
danielk197790949c22007-08-17 16:50:38 +00001045 HAVE_FULLFSYNC, isFullsync);
danielk1977d7c03f72005-11-25 10:38:22 +00001046#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001047 /* The directory sync is only attempted if full_fsync is
1048 ** turned off or unavailable. If a full_fsync occurred above,
1049 ** then the directory sync is superfluous.
1050 */
danielk197790949c22007-08-17 16:50:38 +00001051 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
drhac530b12006-02-11 01:25:50 +00001052 /*
1053 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001054 ** errors when applied to directories on certain file systems.
1055 ** A failed directory sync is not a big deal. So it seems
1056 ** better to ignore the error. Ticket #1657
1057 */
1058 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001059 }
danielk1977d7c03f72005-11-25 10:38:22 +00001060#endif
drh054889e2005-11-30 03:20:31 +00001061 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1062 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001063 }
drha2854222004-06-17 19:04:17 +00001064 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001065}
1066
1067/*
1068** Truncate an open file to a specified size
1069*/
danielk197762079062007-08-15 17:08:46 +00001070static int unixTruncate(sqlite3_file *id, i64 nByte){
drh59685932006-09-14 13:47:11 +00001071 int rc;
drh9cbe6352005-11-29 03:13:21 +00001072 assert( id );
drh93aed5a2008-01-16 17:46:38 +00001073 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
drh63fff5f2007-06-19 10:50:38 +00001074 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
drh59685932006-09-14 13:47:11 +00001075 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001076 return SQLITE_IOERR_TRUNCATE;
drh59685932006-09-14 13:47:11 +00001077 }else{
1078 return SQLITE_OK;
1079 }
drhbbd42a62004-05-22 17:41:58 +00001080}
1081
1082/*
1083** Determine the current size of a file in bytes
1084*/
danielk197762079062007-08-15 17:08:46 +00001085static int unixFileSize(sqlite3_file *id, i64 *pSize){
drh59685932006-09-14 13:47:11 +00001086 int rc;
drhbbd42a62004-05-22 17:41:58 +00001087 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001088 assert( id );
drh59685932006-09-14 13:47:11 +00001089 rc = fstat(((unixFile*)id)->h, &buf);
1090 SimulateIOError( rc=1 );
1091 if( rc!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001092 return SQLITE_IOERR_FSTAT;
drhbbd42a62004-05-22 17:41:58 +00001093 }
1094 *pSize = buf.st_size;
1095 return SQLITE_OK;
1096}
1097
danielk19779a1d0ab2004-06-01 14:09:28 +00001098/*
danielk197713adf8a2004-06-03 16:08:41 +00001099** This routine checks if there is a RESERVED lock held on the specified
1100** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001101** non-zero. If the file is unlocked or holds only SHARED locks, then
1102** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001103*/
danielk1977861f7452008-06-05 11:39:11 +00001104static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
danielk197713adf8a2004-06-03 16:08:41 +00001105 int r = 0;
drh054889e2005-11-30 03:20:31 +00001106 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001107
danielk1977861f7452008-06-05 11:39:11 +00001108 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1109
drh054889e2005-11-30 03:20:31 +00001110 assert( pFile );
danielk1977b4b47412007-08-17 15:53:36 +00001111 enterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001112
1113 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001114 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001115 r = 1;
1116 }
1117
drh2ac3ee92004-06-07 16:27:46 +00001118 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001119 */
1120 if( !r ){
1121 struct flock lock;
1122 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001123 lock.l_start = RESERVED_BYTE;
1124 lock.l_len = 1;
1125 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001126 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001127 if( lock.l_type!=F_UNLCK ){
1128 r = 1;
1129 }
1130 }
1131
danielk1977b4b47412007-08-17 15:53:36 +00001132 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001133 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001134
danielk1977861f7452008-06-05 11:39:11 +00001135 *pResOut = r;
1136 return SQLITE_OK;
danielk197713adf8a2004-06-03 16:08:41 +00001137}
1138
1139/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001140** Lock the file with the lock specified by parameter locktype - one
1141** of the following:
1142**
drh2ac3ee92004-06-07 16:27:46 +00001143** (1) SHARED_LOCK
1144** (2) RESERVED_LOCK
1145** (3) PENDING_LOCK
1146** (4) EXCLUSIVE_LOCK
1147**
drhb3e04342004-06-08 00:47:47 +00001148** Sometimes when requesting one lock state, additional lock states
1149** are inserted in between. The locking might fail on one of the later
1150** transitions leaving the lock state different from what it started but
1151** still short of its goal. The following chart shows the allowed
1152** transitions and the inserted intermediate states:
1153**
1154** UNLOCKED -> SHARED
1155** SHARED -> RESERVED
1156** SHARED -> (PENDING) -> EXCLUSIVE
1157** RESERVED -> (PENDING) -> EXCLUSIVE
1158** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001159**
drha6abd042004-06-09 17:37:22 +00001160** This routine will only increase a lock. Use the sqlite3OsUnlock()
1161** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001162*/
danielk197762079062007-08-15 17:08:46 +00001163static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001164 /* The following describes the implementation of the various locks and
1165 ** lock transitions in terms of the POSIX advisory shared and exclusive
1166 ** lock primitives (called read-locks and write-locks below, to avoid
1167 ** confusion with SQLite lock names). The algorithms are complicated
1168 ** slightly in order to be compatible with windows systems simultaneously
1169 ** accessing the same database file, in case that is ever required.
1170 **
1171 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1172 ** byte', each single bytes at well known offsets, and the 'shared byte
1173 ** range', a range of 510 bytes at a well known offset.
1174 **
1175 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1176 ** byte'. If this is successful, a random byte from the 'shared byte
1177 ** range' is read-locked and the lock on the 'pending byte' released.
1178 **
danielk197790ba3bd2004-06-25 08:32:25 +00001179 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1180 ** A RESERVED lock is implemented by grabbing a write-lock on the
1181 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001182 **
1183 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001184 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1185 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1186 ** obtained, but existing SHARED locks are allowed to persist. A process
1187 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1188 ** This property is used by the algorithm for rolling back a journal file
1189 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001190 **
danielk197790ba3bd2004-06-25 08:32:25 +00001191 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1192 ** implemented by obtaining a write-lock on the entire 'shared byte
1193 ** range'. Since all other locks require a read-lock on one of the bytes
1194 ** within this range, this ensures that no other locks are held on the
1195 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001196 **
1197 ** The reason a single byte cannot be used instead of the 'shared byte
1198 ** range' is that some versions of windows do not support read-locks. By
1199 ** locking a random byte from a range, concurrent SHARED locks may exist
1200 ** even if the locking primitive used is always a write-lock.
1201 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001202 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001203 unixFile *pFile = (unixFile*)id;
1204 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001205 struct flock lock;
1206 int s;
1207
drh054889e2005-11-30 03:20:31 +00001208 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001209 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001210 locktypeName(locktype), locktypeName(pFile->locktype),
1211 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001212
1213 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001214 ** unixFile, do nothing. Don't use the end_lock: exit path, as
danielk1977b4b47412007-08-17 15:53:36 +00001215 ** enterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001216 */
drh054889e2005-11-30 03:20:31 +00001217 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001218 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001219 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001220 return SQLITE_OK;
1221 }
1222
drhb3e04342004-06-08 00:47:47 +00001223 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001224 */
drh054889e2005-11-30 03:20:31 +00001225 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001226 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001227 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001228
drh054889e2005-11-30 03:20:31 +00001229 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001230 */
danielk1977b4b47412007-08-17 15:53:36 +00001231 enterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001232
drh029b44b2006-01-15 00:13:15 +00001233 /* Make sure the current thread owns the pFile.
1234 */
1235 rc = transferOwnership(pFile);
1236 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001237 leaveMutex();
drh029b44b2006-01-15 00:13:15 +00001238 return rc;
1239 }
drh64b1bea2006-01-15 02:30:57 +00001240 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001241
danielk1977ad94b582007-08-20 06:44:22 +00001242 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001243 ** handle that precludes the requested lock, return BUSY.
1244 */
drh054889e2005-11-30 03:20:31 +00001245 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001246 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001247 ){
1248 rc = SQLITE_BUSY;
1249 goto end_lock;
1250 }
1251
1252 /* If a SHARED lock is requested, and some thread using this PID already
1253 ** has a SHARED or RESERVED lock, then increment reference counts and
1254 ** return SQLITE_OK.
1255 */
1256 if( locktype==SHARED_LOCK &&
1257 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1258 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001259 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001260 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001261 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001262 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001263 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001264 goto end_lock;
1265 }
1266
danielk197713adf8a2004-06-03 16:08:41 +00001267 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001268
danielk19779a1d0ab2004-06-01 14:09:28 +00001269 lock.l_whence = SEEK_SET;
1270
drh3cde3bb2004-06-12 02:17:14 +00001271 /* A PENDING lock is needed before acquiring a SHARED lock and before
1272 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1273 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001274 */
drh3cde3bb2004-06-12 02:17:14 +00001275 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001276 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001277 ){
danielk1977489468c2004-06-28 08:25:47 +00001278 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001279 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001280 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001281 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001282 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1283 goto end_lock;
1284 }
drh3cde3bb2004-06-12 02:17:14 +00001285 }
1286
1287
1288 /* If control gets to this point, then actually go ahead and make
1289 ** operating system calls for the specified lock.
1290 */
1291 if( locktype==SHARED_LOCK ){
1292 assert( pLock->cnt==0 );
1293 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001294
drh2ac3ee92004-06-07 16:27:46 +00001295 /* Now get the read-lock */
1296 lock.l_start = SHARED_FIRST;
1297 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001298 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001299
1300 /* Drop the temporary PENDING lock */
1301 lock.l_start = PENDING_BYTE;
1302 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001303 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001304 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001305 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
drh2b4b5962005-06-15 17:47:55 +00001306 goto end_lock;
1307 }
drhe2396a12007-03-29 20:19:58 +00001308 if( s==(-1) ){
drhbbd42a62004-05-22 17:41:58 +00001309 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1310 }else{
drh054889e2005-11-30 03:20:31 +00001311 pFile->locktype = SHARED_LOCK;
1312 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001313 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001314 }
drh3cde3bb2004-06-12 02:17:14 +00001315 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1316 /* We are trying for an exclusive lock but another thread in this
1317 ** same process is still holding a shared lock. */
1318 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001319 }else{
drh3cde3bb2004-06-12 02:17:14 +00001320 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001321 ** assumed that there is a SHARED or greater lock on the file
1322 ** already.
1323 */
drh054889e2005-11-30 03:20:31 +00001324 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001325 lock.l_type = F_WRLCK;
1326 switch( locktype ){
1327 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001328 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001329 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001330 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001331 lock.l_start = SHARED_FIRST;
1332 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001333 break;
1334 default:
1335 assert(0);
1336 }
drh054889e2005-11-30 03:20:31 +00001337 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001338 if( s==(-1) ){
danielk19779a1d0ab2004-06-01 14:09:28 +00001339 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1340 }
drhbbd42a62004-05-22 17:41:58 +00001341 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001342
danielk1977ecb2a962004-06-02 06:30:16 +00001343 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001344 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001345 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001346 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001347 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001348 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001349 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001350
1351end_lock:
danielk1977b4b47412007-08-17 15:53:36 +00001352 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001353 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001354 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001355 return rc;
1356}
1357
1358/*
drh054889e2005-11-30 03:20:31 +00001359** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001360** must be either NO_LOCK or SHARED_LOCK.
1361**
1362** If the locking level of the file descriptor is already at or below
1363** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001364*/
danielk197762079062007-08-15 17:08:46 +00001365static int unixUnlock(sqlite3_file *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001366 struct lockInfo *pLock;
1367 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001368 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001369 unixFile *pFile = (unixFile*)id;
drh1aa5af12008-03-07 19:51:14 +00001370 int h;
drha6abd042004-06-09 17:37:22 +00001371
drh054889e2005-11-30 03:20:31 +00001372 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001373 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001374 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001375
1376 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001377 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001378 return SQLITE_OK;
1379 }
drhf1a221e2006-01-15 17:27:17 +00001380 if( CHECK_THREADID(pFile) ){
1381 return SQLITE_MISUSE;
1382 }
danielk1977b4b47412007-08-17 15:53:36 +00001383 enterMutex();
drh1aa5af12008-03-07 19:51:14 +00001384 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001385 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001386 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001387 if( pFile->locktype>SHARED_LOCK ){
1388 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001389 SimulateIOErrorBenign(1);
1390 SimulateIOError( h=(-1) )
1391 SimulateIOErrorBenign(0);
drh9c105bb2004-10-02 20:38:28 +00001392 if( locktype==SHARED_LOCK ){
1393 lock.l_type = F_RDLCK;
1394 lock.l_whence = SEEK_SET;
1395 lock.l_start = SHARED_FIRST;
1396 lock.l_len = SHARED_SIZE;
drh1aa5af12008-03-07 19:51:14 +00001397 if( fcntl(h, F_SETLK, &lock)==(-1) ){
drh4ac285a2006-09-15 07:28:50 +00001398 rc = SQLITE_IOERR_RDLOCK;
drh9c105bb2004-10-02 20:38:28 +00001399 }
1400 }
drhbbd42a62004-05-22 17:41:58 +00001401 lock.l_type = F_UNLCK;
1402 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001403 lock.l_start = PENDING_BYTE;
1404 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001405 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001406 pLock->locktype = SHARED_LOCK;
1407 }else{
drh1aa5af12008-03-07 19:51:14 +00001408 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001409 }
drhbbd42a62004-05-22 17:41:58 +00001410 }
drha6abd042004-06-09 17:37:22 +00001411 if( locktype==NO_LOCK ){
1412 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001413
drha6abd042004-06-09 17:37:22 +00001414 /* Decrement the shared lock counter. Release the lock using an
1415 ** OS call only when all threads in this same process have released
1416 ** the lock.
1417 */
1418 pLock->cnt--;
1419 if( pLock->cnt==0 ){
1420 lock.l_type = F_UNLCK;
1421 lock.l_whence = SEEK_SET;
1422 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001423 SimulateIOErrorBenign(1);
1424 SimulateIOError( h=(-1) )
1425 SimulateIOErrorBenign(0);
1426 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001427 pLock->locktype = NO_LOCK;
1428 }else{
drh1aa5af12008-03-07 19:51:14 +00001429 rc = SQLITE_IOERR_UNLOCK;
1430 pLock->cnt = 1;
drh2b4b5962005-06-15 17:47:55 +00001431 }
drha6abd042004-06-09 17:37:22 +00001432 }
1433
drhbbd42a62004-05-22 17:41:58 +00001434 /* Decrement the count of locks against this same file. When the
1435 ** count reaches zero, close any other file descriptors whose close
1436 ** was deferred because of outstanding locks.
1437 */
drh1aa5af12008-03-07 19:51:14 +00001438 if( rc==SQLITE_OK ){
1439 pOpen = pFile->pOpen;
1440 pOpen->nLock--;
1441 assert( pOpen->nLock>=0 );
1442 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1443 int i;
1444 for(i=0; i<pOpen->nPending; i++){
1445 close(pOpen->aPending[i]);
1446 }
drhda0e7682008-07-30 15:27:54 +00001447 sqlite3_free(pOpen->aPending);
drh1aa5af12008-03-07 19:51:14 +00001448 pOpen->nPending = 0;
1449 pOpen->aPending = 0;
drhbbd42a62004-05-22 17:41:58 +00001450 }
drhbbd42a62004-05-22 17:41:58 +00001451 }
1452 }
danielk1977b4b47412007-08-17 15:53:36 +00001453 leaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001454 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001455 return rc;
drhbbd42a62004-05-22 17:41:58 +00001456}
1457
1458/*
danielk1977e339d652008-06-28 11:23:00 +00001459** This function performs the parts of the "close file" operation
1460** common to all locking schemes. It closes the directory and file
1461** handles, if they are valid, and sets all fields of the unixFile
1462** structure to 0.
1463*/
1464static int closeUnixFile(sqlite3_file *id){
1465 unixFile *pFile = (unixFile*)id;
1466 if( pFile ){
1467 if( pFile->dirfd>=0 ){
1468 close(pFile->dirfd);
1469 }
1470 if( pFile->h>=0 ){
1471 close(pFile->h);
1472 }
1473 OSTRACE2("CLOSE %-3d\n", pFile->h);
1474 OpenCounter(-1);
1475 memset(pFile, 0, sizeof(unixFile));
1476 }
1477 return SQLITE_OK;
1478}
1479
1480/*
danielk1977e3026632004-06-22 11:29:02 +00001481** Close a file.
1482*/
danielk197762079062007-08-15 17:08:46 +00001483static int unixClose(sqlite3_file *id){
danielk1977e339d652008-06-28 11:23:00 +00001484 if( id ){
1485 unixFile *pFile = (unixFile *)id;
1486 unixUnlock(id, NO_LOCK);
1487 enterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001488 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001489 /* If there are outstanding locks, do not actually close the file just
1490 ** yet because that would clear those locks. Instead, add the file
1491 ** descriptor to pOpen->aPending. It will be automatically closed when
1492 ** the last lock is cleared.
1493 */
1494 int *aNew;
1495 struct openCnt *pOpen = pFile->pOpen;
drhda0e7682008-07-30 15:27:54 +00001496 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e339d652008-06-28 11:23:00 +00001497 if( aNew==0 ){
1498 /* If a malloc fails, just leak the file descriptor */
1499 }else{
1500 pOpen->aPending = aNew;
1501 pOpen->aPending[pOpen->nPending] = pFile->h;
1502 pOpen->nPending++;
1503 pFile->h = -1;
1504 }
danielk1977e3026632004-06-22 11:29:02 +00001505 }
danielk1977e339d652008-06-28 11:23:00 +00001506 releaseLockInfo(pFile->pLock);
1507 releaseOpenCnt(pFile->pOpen);
1508 closeUnixFile(id);
1509 leaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001510 }
drh02afc862006-01-20 18:10:57 +00001511 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001512}
1513
drhbfe66312006-10-03 17:40:40 +00001514
1515#ifdef SQLITE_ENABLE_LOCKING_STYLE
1516#pragma mark AFP Support
1517
1518/*
1519 ** The afpLockingContext structure contains all afp lock specific state
1520 */
1521typedef struct afpLockingContext afpLockingContext;
1522struct afpLockingContext {
drh1aa5af12008-03-07 19:51:14 +00001523 unsigned long long sharedLockByte;
drh308aa322008-03-07 20:14:38 +00001524 const char *filePath;
drhbfe66312006-10-03 17:40:40 +00001525};
1526
1527struct ByteRangeLockPB2
1528{
1529 unsigned long long offset; /* offset to first byte to lock */
1530 unsigned long long length; /* nbr of bytes to lock */
1531 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
1532 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
1533 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
1534 int fd; /* file desc to assoc this lock with */
1535};
1536
drhfd131da2007-08-07 17:13:03 +00001537#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00001538
danielk1977ad94b582007-08-20 06:44:22 +00001539/*
1540** Return 0 on success, 1 on failure. To match the behavior of the
1541** normal posix file locking (used in unixLock for example), we should
1542** provide 'richer' return codes - specifically to differentiate between
1543** 'file busy' and 'file system error' results.
1544*/
1545static int _AFPFSSetLock(
1546 const char *path,
1547 int fd,
1548 unsigned long long offset,
1549 unsigned long long length,
1550 int setLockFlag
1551){
drhfd131da2007-08-07 17:13:03 +00001552 struct ByteRangeLockPB2 pb;
drhbfe66312006-10-03 17:40:40 +00001553 int err;
1554
1555 pb.unLockFlag = setLockFlag ? 0 : 1;
1556 pb.startEndFlag = 0;
1557 pb.offset = offset;
1558 pb.length = length;
1559 pb.fd = fd;
drh4f0c5872007-03-26 22:05:01 +00001560 OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
drhbfe66312006-10-03 17:40:40 +00001561 (setLockFlag?"ON":"OFF"), fd, offset, length);
1562 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
1563 if ( err==-1 ) {
drh4f0c5872007-03-26 22:05:01 +00001564 OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno,
drhbfe66312006-10-03 17:40:40 +00001565 strerror(errno));
drh3b62b2f2007-06-08 18:27:03 +00001566 return 1; /* error */
drhbfe66312006-10-03 17:40:40 +00001567 } else {
1568 return 0;
1569 }
1570}
1571
1572/*
1573 ** This routine checks if there is a RESERVED lock held on the specified
1574 ** file by this or any other process. If such a lock is held, return
1575 ** non-zero. If the file is unlocked or holds only SHARED locks, then
1576 ** return zero.
1577 */
danielk1977e339d652008-06-28 11:23:00 +00001578static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
drhbfe66312006-10-03 17:40:40 +00001579 int r = 0;
1580 unixFile *pFile = (unixFile*)id;
1581
1582 assert( pFile );
1583 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1584
1585 /* Check if a thread in this process holds such a lock */
1586 if( pFile->locktype>SHARED_LOCK ){
1587 r = 1;
1588 }
1589
1590 /* Otherwise see if some other process holds it.
1591 */
1592 if ( !r ) {
drh3b62b2f2007-06-08 18:27:03 +00001593 /* lock the byte */
drhbfe66312006-10-03 17:40:40 +00001594 int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1595 if (failed) {
1596 /* if we failed to get the lock then someone else must have it */
1597 r = 1;
1598 } else {
1599 /* if we succeeded in taking the reserved lock, unlock it to restore
1600 ** the original state */
1601 _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
1602 }
1603 }
drh4f0c5872007-03-26 22:05:01 +00001604 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
drhbfe66312006-10-03 17:40:40 +00001605
danielk1977861f7452008-06-05 11:39:11 +00001606 *pResOut = r;
1607 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001608}
1609
1610/* AFP-style locking following the behavior of unixLock, see the unixLock
1611** function comments for details of lock management. */
danielk1977e339d652008-06-28 11:23:00 +00001612static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00001613 int rc = SQLITE_OK;
1614 unixFile *pFile = (unixFile*)id;
1615 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00001616
1617 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001618 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00001619 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
1620
drhbfe66312006-10-03 17:40:40 +00001621 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00001622 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
1623 ** enterMutex() hasn't been called yet.
1624 */
drhbfe66312006-10-03 17:40:40 +00001625 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001626 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001627 locktypeName(locktype));
1628 return SQLITE_OK;
1629 }
1630
1631 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00001632 */
drhbfe66312006-10-03 17:40:40 +00001633 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
1634 assert( locktype!=PENDING_LOCK );
1635 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1636
1637 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00001638 */
danielk1977b4b47412007-08-17 15:53:36 +00001639 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001640
1641 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00001642 */
drhbfe66312006-10-03 17:40:40 +00001643 rc = transferOwnership(pFile);
1644 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001645 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001646 return rc;
1647 }
1648
1649 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00001650 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1651 ** be released.
1652 */
drhbfe66312006-10-03 17:40:40 +00001653 if( locktype==SHARED_LOCK
1654 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00001655 ){
1656 int failed;
1657 failed = _AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00001658 if (failed) {
1659 rc = SQLITE_BUSY;
1660 goto afp_end_lock;
1661 }
1662 }
1663
1664 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00001665 ** operating system calls for the specified lock.
1666 */
drhbfe66312006-10-03 17:40:40 +00001667 if( locktype==SHARED_LOCK ){
1668 int lk, failed;
drhbfe66312006-10-03 17:40:40 +00001669
1670 /* Now get the read-lock */
1671 /* note that the quality of the randomness doesn't matter that much */
1672 lk = random();
1673 context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
1674 failed = _AFPFSSetLock(context->filePath, pFile->h,
1675 SHARED_FIRST+context->sharedLockByte, 1, 1);
1676
1677 /* Drop the temporary PENDING lock */
1678 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
1679 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1680 goto afp_end_lock;
1681 }
1682
1683 if( failed ){
1684 rc = SQLITE_BUSY;
1685 } else {
1686 pFile->locktype = SHARED_LOCK;
1687 }
1688 }else{
1689 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1690 ** assumed that there is a SHARED or greater lock on the file
1691 ** already.
1692 */
1693 int failed = 0;
1694 assert( 0!=pFile->locktype );
1695 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
1696 /* Acquire a RESERVED lock */
1697 failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
1698 }
1699 if (!failed && locktype == EXCLUSIVE_LOCK) {
1700 /* Acquire an EXCLUSIVE lock */
1701
1702 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00001703 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00001704 */
1705 if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1706 context->sharedLockByte, 1, 0)) {
1707 /* now attemmpt to get the exclusive lock range */
1708 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1709 SHARED_SIZE, 1);
1710 if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
1711 context->sharedLockByte, 1, 1)) {
1712 rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
1713 }
1714 } else {
1715 /* */
1716 rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
1717 }
1718 }
1719 if( failed && rc == SQLITE_OK){
1720 rc = SQLITE_BUSY;
1721 }
1722 }
1723
1724 if( rc==SQLITE_OK ){
1725 pFile->locktype = locktype;
1726 }else if( locktype==EXCLUSIVE_LOCK ){
1727 pFile->locktype = PENDING_LOCK;
1728 }
1729
1730afp_end_lock:
drh339eb0b2008-03-07 15:34:11 +00001731 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001732 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00001733 rc==SQLITE_OK ? "ok" : "failed");
1734 return rc;
1735}
1736
1737/*
drh339eb0b2008-03-07 15:34:11 +00001738** Lower the locking level on file descriptor pFile to locktype. locktype
1739** must be either NO_LOCK or SHARED_LOCK.
1740**
1741** If the locking level of the file descriptor is already at or below
1742** the requested locking level, this routine is a no-op.
1743*/
danielk1977e339d652008-06-28 11:23:00 +00001744static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001745 int rc = SQLITE_OK;
1746 unixFile *pFile = (unixFile*)id;
1747 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1748
1749 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001750 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00001751 pFile->locktype, getpid());
1752
1753 assert( locktype<=SHARED_LOCK );
1754 if( pFile->locktype<=locktype ){
1755 return SQLITE_OK;
1756 }
1757 if( CHECK_THREADID(pFile) ){
1758 return SQLITE_MISUSE;
1759 }
danielk1977b4b47412007-08-17 15:53:36 +00001760 enterMutex();
drhbfe66312006-10-03 17:40:40 +00001761 if( pFile->locktype>SHARED_LOCK ){
1762 if( locktype==SHARED_LOCK ){
1763 int failed = 0;
1764
1765 /* unlock the exclusive range - then re-establish the shared lock */
1766 if (pFile->locktype==EXCLUSIVE_LOCK) {
1767 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
1768 SHARED_SIZE, 0);
1769 if (!failed) {
1770 /* successfully removed the exclusive lock */
1771 if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
1772 context->sharedLockByte, 1, 1)) {
1773 /* failed to re-establish our shared lock */
1774 rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
1775 }
1776 } else {
1777 /* This should never happen - failed to unlock the exclusive range */
1778 rc = SQLITE_IOERR_UNLOCK;
1779 }
1780 }
1781 }
1782 if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
1783 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
1784 /* failed to release the pending lock */
1785 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1786 }
1787 }
1788 if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
1789 if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
1790 /* failed to release the reserved lock */
1791 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1792 }
1793 }
1794 }
1795 if( locktype==NO_LOCK ){
1796 int failed = _AFPFSSetLock(context->filePath, pFile->h,
1797 SHARED_FIRST + context->sharedLockByte, 1, 0);
1798 if (failed) {
1799 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
1800 }
1801 }
1802 if (rc == SQLITE_OK)
1803 pFile->locktype = locktype;
danielk1977b4b47412007-08-17 15:53:36 +00001804 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00001805 return rc;
1806}
1807
1808/*
drh339eb0b2008-03-07 15:34:11 +00001809** Close a file & cleanup AFP specific locking context
1810*/
danielk1977e339d652008-06-28 11:23:00 +00001811static int afpClose(sqlite3_file *id) {
1812 if( id ){
1813 unixFile *pFile = (unixFile*)id;
1814 afpUnlock(id, NO_LOCK);
1815 sqlite3_free(pFile->lockingContext);
1816 }
1817 return closeUnixFile(id);
drhbfe66312006-10-03 17:40:40 +00001818}
1819
1820
1821#pragma mark flock() style locking
1822
1823/*
drh339eb0b2008-03-07 15:34:11 +00001824** The flockLockingContext is not used
1825*/
drhbfe66312006-10-03 17:40:40 +00001826typedef void flockLockingContext;
1827
danielk1977e339d652008-06-28 11:23:00 +00001828static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
danielk1977861f7452008-06-05 11:39:11 +00001829 int r = 1;
drhbfe66312006-10-03 17:40:40 +00001830 unixFile *pFile = (unixFile*)id;
1831
danielk1977861f7452008-06-05 11:39:11 +00001832 if (pFile->locktype != RESERVED_LOCK) {
drh3b62b2f2007-06-08 18:27:03 +00001833 /* attempt to get the lock */
drhbfe66312006-10-03 17:40:40 +00001834 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1835 if (!rc) {
drh3b62b2f2007-06-08 18:27:03 +00001836 /* got the lock, unlock it */
drhbfe66312006-10-03 17:40:40 +00001837 flock(pFile->h, LOCK_UN);
danielk1977861f7452008-06-05 11:39:11 +00001838 r = 0; /* no one has it reserved */
drhbfe66312006-10-03 17:40:40 +00001839 }
drhbfe66312006-10-03 17:40:40 +00001840 }
danielk1977861f7452008-06-05 11:39:11 +00001841
1842 *pResOut = r;
1843 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001844}
1845
danielk1977e339d652008-06-28 11:23:00 +00001846static int flockLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001847 unixFile *pFile = (unixFile*)id;
1848
drh3b62b2f2007-06-08 18:27:03 +00001849 /* if we already have a lock, it is exclusive.
1850 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00001851 if (pFile->locktype > NO_LOCK) {
1852 pFile->locktype = locktype;
1853 return SQLITE_OK;
1854 }
1855
drh3b62b2f2007-06-08 18:27:03 +00001856 /* grab an exclusive lock */
drhbfe66312006-10-03 17:40:40 +00001857 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
1858 if (rc) {
drh3b62b2f2007-06-08 18:27:03 +00001859 /* didn't get, must be busy */
drhbfe66312006-10-03 17:40:40 +00001860 return SQLITE_BUSY;
1861 } else {
drh3b62b2f2007-06-08 18:27:03 +00001862 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00001863 pFile->locktype = locktype;
1864 return SQLITE_OK;
1865 }
1866}
1867
danielk1977e339d652008-06-28 11:23:00 +00001868static int flockUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001869 unixFile *pFile = (unixFile*)id;
1870
1871 assert( locktype<=SHARED_LOCK );
1872
drh3b62b2f2007-06-08 18:27:03 +00001873 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00001874 if( pFile->locktype==locktype ){
1875 return SQLITE_OK;
1876 }
1877
drh3b62b2f2007-06-08 18:27:03 +00001878 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00001879 if (locktype==SHARED_LOCK) {
1880 pFile->locktype = locktype;
1881 return SQLITE_OK;
1882 }
1883
drh3b62b2f2007-06-08 18:27:03 +00001884 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00001885 int rc = flock(pFile->h, LOCK_UN);
1886 if (rc)
1887 return SQLITE_IOERR_UNLOCK;
1888 else {
1889 pFile->locktype = NO_LOCK;
1890 return SQLITE_OK;
1891 }
1892}
1893
1894/*
drh339eb0b2008-03-07 15:34:11 +00001895** Close a file.
1896*/
danielk1977e339d652008-06-28 11:23:00 +00001897static int flockClose(sqlite3_file *id) {
1898 if( id ){
1899 flockUnlock(id, NO_LOCK);
1900 }
1901 return closeUnixFile(id);
drhbfe66312006-10-03 17:40:40 +00001902}
1903
1904#pragma mark Old-School .lock file based locking
1905
danielk1977e339d652008-06-28 11:23:00 +00001906static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
danielk1977861f7452008-06-05 11:39:11 +00001907 int r = 1;
drhbfe66312006-10-03 17:40:40 +00001908 unixFile *pFile = (unixFile*)id;
danielk1977e339d652008-06-28 11:23:00 +00001909 char *zLockFile = (char *)pFile->lockingContext;
drh339eb0b2008-03-07 15:34:11 +00001910
danielk1977861f7452008-06-05 11:39:11 +00001911 if (pFile->locktype != RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00001912 struct stat statBuf;
danielk1977e339d652008-06-28 11:23:00 +00001913 if (lstat(zLockFile, &statBuf) != 0){
drh3b62b2f2007-06-08 18:27:03 +00001914 /* file does not exist, we could have it if we want it */
danielk1977861f7452008-06-05 11:39:11 +00001915 r = 0;
drh339eb0b2008-03-07 15:34:11 +00001916 }
drhbfe66312006-10-03 17:40:40 +00001917 }
danielk1977861f7452008-06-05 11:39:11 +00001918
1919 *pResOut = r;
1920 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001921}
1922
danielk1977e339d652008-06-28 11:23:00 +00001923static int dotlockLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001924 unixFile *pFile = (unixFile*)id;
drh339eb0b2008-03-07 15:34:11 +00001925 int fd;
danielk1977e339d652008-06-28 11:23:00 +00001926 char *zLockFile = (char *)pFile->lockingContext;
drh339eb0b2008-03-07 15:34:11 +00001927
drh3b62b2f2007-06-08 18:27:03 +00001928 /* if we already have a lock, it is exclusive.
1929 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00001930 if (pFile->locktype > NO_LOCK) {
1931 pFile->locktype = locktype;
1932
1933 /* Always update the timestamp on the old file */
danielk1977e339d652008-06-28 11:23:00 +00001934 utimes(zLockFile, NULL);
drhbfe66312006-10-03 17:40:40 +00001935 return SQLITE_OK;
1936 }
1937
drh3b62b2f2007-06-08 18:27:03 +00001938 /* check to see if lock file already exists */
drhbfe66312006-10-03 17:40:40 +00001939 struct stat statBuf;
danielk1977e339d652008-06-28 11:23:00 +00001940 if (lstat(zLockFile,&statBuf) == 0){
drh3b62b2f2007-06-08 18:27:03 +00001941 return SQLITE_BUSY; /* it does, busy */
drhbfe66312006-10-03 17:40:40 +00001942 }
1943
drh3b62b2f2007-06-08 18:27:03 +00001944 /* grab an exclusive lock */
danielk1977e339d652008-06-28 11:23:00 +00001945 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh339eb0b2008-03-07 15:34:11 +00001946 if( fd<0 ){
drh3b62b2f2007-06-08 18:27:03 +00001947 /* failed to open/create the file, someone else may have stolen the lock */
drhbfe66312006-10-03 17:40:40 +00001948 return SQLITE_BUSY;
1949 }
1950 close(fd);
1951
drh3b62b2f2007-06-08 18:27:03 +00001952 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00001953 pFile->locktype = locktype;
1954 return SQLITE_OK;
1955}
1956
danielk1977e339d652008-06-28 11:23:00 +00001957static int dotlockUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00001958 unixFile *pFile = (unixFile*)id;
danielk1977e339d652008-06-28 11:23:00 +00001959 char *zLockFile = (char *)pFile->lockingContext;
drh339eb0b2008-03-07 15:34:11 +00001960
drhbfe66312006-10-03 17:40:40 +00001961 assert( locktype<=SHARED_LOCK );
1962
drh3b62b2f2007-06-08 18:27:03 +00001963 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00001964 if( pFile->locktype==locktype ){
1965 return SQLITE_OK;
1966 }
1967
drh3b62b2f2007-06-08 18:27:03 +00001968 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00001969 if (locktype==SHARED_LOCK) {
1970 pFile->locktype = locktype;
1971 return SQLITE_OK;
1972 }
1973
drh3b62b2f2007-06-08 18:27:03 +00001974 /* no, really, unlock. */
danielk1977e339d652008-06-28 11:23:00 +00001975 unlink(zLockFile);
drhbfe66312006-10-03 17:40:40 +00001976 pFile->locktype = NO_LOCK;
1977 return SQLITE_OK;
1978}
1979
1980/*
1981 ** Close a file.
1982 */
danielk1977e339d652008-06-28 11:23:00 +00001983static int dotlockClose(sqlite3_file *id) {
1984 if( id ){
1985 unixFile *pFile = (unixFile*)id;
1986 dotlockUnlock(id, NO_LOCK);
1987 sqlite3_free(pFile->lockingContext);
1988 }
1989 return closeUnixFile(id);
drhbfe66312006-10-03 17:40:40 +00001990}
1991
1992
drhda0e7682008-07-30 15:27:54 +00001993#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drhbfe66312006-10-03 17:40:40 +00001994
1995/*
drh339eb0b2008-03-07 15:34:11 +00001996** The nolockLockingContext is void
1997*/
drhbfe66312006-10-03 17:40:40 +00001998typedef void nolockLockingContext;
1999
danielk1977e339d652008-06-28 11:23:00 +00002000static int nolockCheckReservedLock(sqlite3_file *id, int *pResOut) {
danielk1977861f7452008-06-05 11:39:11 +00002001 *pResOut = 0;
2002 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002003}
2004
danielk1977e339d652008-06-28 11:23:00 +00002005static int nolockLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002006 return SQLITE_OK;
2007}
2008
danielk1977e339d652008-06-28 11:23:00 +00002009static int nolockUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002010 return SQLITE_OK;
2011}
2012
2013/*
drh339eb0b2008-03-07 15:34:11 +00002014** Close a file.
2015*/
danielk1977e339d652008-06-28 11:23:00 +00002016static int nolockClose(sqlite3_file *id) {
2017 return closeUnixFile(id);
drhbfe66312006-10-03 17:40:40 +00002018}
2019
danielk1977ad94b582007-08-20 06:44:22 +00002020
danielk1977e3026632004-06-22 11:29:02 +00002021/*
drh9e33c2c2007-08-31 18:34:59 +00002022** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00002023*/
drhcc6bb3e2007-08-31 16:11:35 +00002024static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00002025 switch( op ){
2026 case SQLITE_FCNTL_LOCKSTATE: {
2027 *(int*)pArg = ((unixFile*)id)->locktype;
2028 return SQLITE_OK;
2029 }
2030 }
drhcc6bb3e2007-08-31 16:11:35 +00002031 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00002032}
2033
2034/*
danielk1977a3d4c882007-03-23 10:08:38 +00002035** Return the sector size in bytes of the underlying block device for
2036** the specified file. This is almost always 512 bytes, but may be
2037** larger for some devices.
2038**
2039** SQLite code assumes this function cannot fail. It also assumes that
2040** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00002041** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00002042** same for both.
2043*/
danielk197762079062007-08-15 17:08:46 +00002044static int unixSectorSize(sqlite3_file *id){
drh3ceeb752007-03-29 18:19:52 +00002045 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00002046}
2047
danielk197790949c22007-08-17 16:50:38 +00002048/*
2049** Return the device characteristics for the file. This is always 0.
2050*/
danielk197762079062007-08-15 17:08:46 +00002051static int unixDeviceCharacteristics(sqlite3_file *id){
2052 return 0;
2053}
2054
danielk1977a3d4c882007-03-23 10:08:38 +00002055/*
danielk1977e339d652008-06-28 11:23:00 +00002056** Initialize the contents of the unixFile structure pointed to by pId.
2057**
danielk1977ad94b582007-08-20 06:44:22 +00002058** When locking extensions are enabled, the filepath and locking style
2059** are needed to determine the unixFile pMethod to use for locking operations.
2060** The locking-style specific lockingContext data structure is created
2061** and assigned here also.
2062*/
2063static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00002064 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00002065 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00002066 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00002067 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00002068 const char *zFilename, /* Name of the file being opened */
2069 int noLock /* Omit locking if true */
drhbfe66312006-10-03 17:40:40 +00002070){
drhda0e7682008-07-30 15:27:54 +00002071 int eLockingStyle;
2072 unixFile *pNew = (unixFile *)pId;
2073 int rc = SQLITE_OK;
2074
danielk1977e339d652008-06-28 11:23:00 +00002075 /* Macro to define the static contents of an sqlite3_io_methods
2076 ** structure for a unix backend file. Different locking methods
2077 ** require different functions for the xClose, xLock, xUnlock and
2078 ** xCheckReservedLock methods.
2079 */
2080 #define IOMETHODS(xClose, xLock, xUnlock, xCheckReservedLock) { \
2081 1, /* iVersion */ \
2082 xClose, /* xClose */ \
2083 unixRead, /* xRead */ \
2084 unixWrite, /* xWrite */ \
2085 unixTruncate, /* xTruncate */ \
2086 unixSync, /* xSync */ \
2087 unixFileSize, /* xFileSize */ \
2088 xLock, /* xLock */ \
2089 xUnlock, /* xUnlock */ \
2090 xCheckReservedLock, /* xCheckReservedLock */ \
2091 unixFileControl, /* xFileControl */ \
2092 unixSectorSize, /* xSectorSize */ \
2093 unixDeviceCharacteristics /* xDeviceCapabilities */ \
2094 }
2095 static sqlite3_io_methods aIoMethod[] = {
2096 IOMETHODS(unixClose, unixLock, unixUnlock, unixCheckReservedLock)
danielk1977e339d652008-06-28 11:23:00 +00002097 ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
drhda0e7682008-07-30 15:27:54 +00002098#ifdef SQLITE_ENABLE_LOCKING_STYLE
2099 ,IOMETHODS(dotlockClose, dotlockLock, dotlockUnlock,dotlockCheckReservedLock)
2100 ,IOMETHODS(flockClose, flockLock, flockUnlock, flockCheckReservedLock)
danielk1977e339d652008-06-28 11:23:00 +00002101 ,IOMETHODS(afpClose, afpLock, afpUnlock, afpCheckReservedLock)
drh218c5082008-03-07 00:27:10 +00002102#endif
danielk1977e339d652008-06-28 11:23:00 +00002103 };
drhda0e7682008-07-30 15:27:54 +00002104 /* The order of the IOMETHODS macros above is important. It must be the
2105 ** same order as the LOCKING_STYLE numbers
2106 */
2107 assert(LOCKING_STYLE_POSIX==1);
2108 assert(LOCKING_STYLE_NONE==2);
2109 assert(LOCKING_STYLE_DOTFILE==3);
2110 assert(LOCKING_STYLE_FLOCK==4);
2111 assert(LOCKING_STYLE_AFP==5);
drh218c5082008-03-07 00:27:10 +00002112
danielk197717b90b52008-06-06 11:11:25 +00002113 assert( pNew->pLock==NULL );
2114 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00002115
2116 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00002117 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00002118 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00002119 SET_THREADID(pNew);
drh339eb0b2008-03-07 15:34:11 +00002120
drhda0e7682008-07-30 15:27:54 +00002121 if( noLock ){
2122 eLockingStyle = LOCKING_STYLE_NONE;
2123 }else{
2124 eLockingStyle = detectLockingStyle(pVfs, zFilename, h);
2125 }
danielk1977e339d652008-06-28 11:23:00 +00002126
2127 switch( eLockingStyle ){
2128
2129 case LOCKING_STYLE_POSIX: {
2130 enterMutex();
2131 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
2132 leaveMutex();
drh218c5082008-03-07 00:27:10 +00002133 break;
drhbfe66312006-10-03 17:40:40 +00002134 }
danielk1977e339d652008-06-28 11:23:00 +00002135
2136#ifdef SQLITE_ENABLE_LOCKING_STYLE
2137 case LOCKING_STYLE_AFP: {
2138 /* AFP locking uses the file path so it needs to be included in
2139 ** the afpLockingContext.
2140 */
2141 afpLockingContext *pCtx;
2142 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
2143 if( pCtx==0 ){
2144 rc = SQLITE_NOMEM;
2145 }else{
2146 /* NB: zFilename exists and remains valid until the file is closed
2147 ** according to requirement F11141. So we do not need to make a
2148 ** copy of the filename. */
2149 pCtx->filePath = zFilename;
2150 srandomdev();
2151 }
drh218c5082008-03-07 00:27:10 +00002152 break;
danielk1977e339d652008-06-28 11:23:00 +00002153 }
2154
2155 case LOCKING_STYLE_DOTFILE: {
2156 /* Dotfile locking uses the file path so it needs to be included in
2157 ** the dotlockLockingContext
2158 */
2159 char *zLockFile;
drh218c5082008-03-07 00:27:10 +00002160 int nFilename;
danielk1977e339d652008-06-28 11:23:00 +00002161 nFilename = strlen(zFilename) + 6;
2162 zLockFile = (char *)sqlite3_malloc(nFilename);
2163 if( zLockFile==0 ){
2164 rc = SQLITE_NOMEM;
2165 }else{
2166 sqlite3_snprintf(nFilename, zLockFile, "%s.lock", zFilename);
drh339eb0b2008-03-07 15:34:11 +00002167 }
danielk1977e339d652008-06-28 11:23:00 +00002168 pNew->lockingContext = zLockFile;
drh218c5082008-03-07 00:27:10 +00002169 break;
2170 }
danielk1977e339d652008-06-28 11:23:00 +00002171
2172 case LOCKING_STYLE_FLOCK:
2173 case LOCKING_STYLE_NONE:
drh218c5082008-03-07 00:27:10 +00002174 break;
drhe78669b2007-06-29 12:04:26 +00002175#endif
danielk1977e339d652008-06-28 11:23:00 +00002176 }
danielk1977b4b47412007-08-17 15:53:36 +00002177
danielk1977e339d652008-06-28 11:23:00 +00002178 if( rc!=SQLITE_OK ){
danielk19777c055b92007-10-30 17:28:51 +00002179 if( dirfd>=0 ) close(dirfd);
drhbfe66312006-10-03 17:40:40 +00002180 close(h);
danielk1977e339d652008-06-28 11:23:00 +00002181 }else{
danielk19776cb427f2008-06-30 10:16:04 +00002182 pNew->pMethod = &aIoMethod[eLockingStyle-1];
danielk1977e339d652008-06-28 11:23:00 +00002183 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00002184 }
danielk1977e339d652008-06-28 11:23:00 +00002185 return rc;
drh054889e2005-11-30 03:20:31 +00002186}
drh9c06c952005-11-26 00:25:00 +00002187
danielk1977ad94b582007-08-20 06:44:22 +00002188/*
2189** Open a file descriptor to the directory containing file zFilename.
2190** If successful, *pFd is set to the opened file descriptor and
2191** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
2192** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
2193** value.
2194**
2195** If SQLITE_OK is returned, the caller is responsible for closing
2196** the file descriptor *pFd using close().
2197*/
danielk1977fee2d252007-08-18 10:59:19 +00002198static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00002199 int ii;
drh777b17a2007-09-20 10:02:54 +00002200 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00002201 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00002202
drh153c62c2007-08-24 03:51:33 +00002203 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
danielk1977fee2d252007-08-18 10:59:19 +00002204 for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
2205 if( ii>0 ){
2206 zDirname[ii] = '\0';
2207 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00002208 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00002209#ifdef FD_CLOEXEC
2210 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
2211#endif
2212 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
2213 }
2214 }
danielk1977fee2d252007-08-18 10:59:19 +00002215 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00002216 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00002217}
2218
danielk1977b4b47412007-08-17 15:53:36 +00002219/*
danielk197717b90b52008-06-06 11:11:25 +00002220** Create a temporary file name in zBuf. zBuf must be allocated
2221** by the calling process and must be big enough to hold at least
2222** pVfs->mxPathname bytes.
2223*/
2224static int getTempname(int nBuf, char *zBuf){
2225 static const char *azDirs[] = {
2226 0,
2227 "/var/tmp",
2228 "/usr/tmp",
2229 "/tmp",
2230 ".",
2231 };
2232 static const unsigned char zChars[] =
2233 "abcdefghijklmnopqrstuvwxyz"
2234 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2235 "0123456789";
2236 int i, j;
2237 struct stat buf;
2238 const char *zDir = ".";
2239
2240 /* It's odd to simulate an io-error here, but really this is just
2241 ** using the io-error infrastructure to test that SQLite handles this
2242 ** function failing.
2243 */
2244 SimulateIOError( return SQLITE_IOERR );
2245
2246 azDirs[0] = sqlite3_temp_directory;
2247 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
2248 if( azDirs[i]==0 ) continue;
2249 if( stat(azDirs[i], &buf) ) continue;
2250 if( !S_ISDIR(buf.st_mode) ) continue;
2251 if( access(azDirs[i], 07) ) continue;
2252 zDir = azDirs[i];
2253 break;
2254 }
2255
2256 /* Check that the output buffer is large enough for the temporary file
2257 ** name. If it is not, return SQLITE_ERROR.
2258 */
2259 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
2260 return SQLITE_ERROR;
2261 }
2262
2263 do{
2264 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
2265 j = strlen(zBuf);
2266 sqlite3_randomness(15, &zBuf[j]);
2267 for(i=0; i<15; i++, j++){
2268 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
2269 }
2270 zBuf[j] = 0;
2271 }while( access(zBuf,0)==0 );
2272 return SQLITE_OK;
2273}
2274
2275
2276/*
danielk1977ad94b582007-08-20 06:44:22 +00002277** Open the file zPath.
2278**
danielk1977b4b47412007-08-17 15:53:36 +00002279** Previously, the SQLite OS layer used three functions in place of this
2280** one:
2281**
2282** sqlite3OsOpenReadWrite();
2283** sqlite3OsOpenReadOnly();
2284** sqlite3OsOpenExclusive();
2285**
2286** These calls correspond to the following combinations of flags:
2287**
2288** ReadWrite() -> (READWRITE | CREATE)
2289** ReadOnly() -> (READONLY)
2290** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
2291**
2292** The old OpenExclusive() accepted a boolean argument - "delFlag". If
2293** true, the file was configured to be automatically deleted when the
2294** file handle closed. To achieve the same effect using this new
2295** interface, add the DELETEONCLOSE flag to those specified above for
2296** OpenExclusive().
2297*/
2298static int unixOpen(
drh153c62c2007-08-24 03:51:33 +00002299 sqlite3_vfs *pVfs,
danielk1977b4b47412007-08-17 15:53:36 +00002300 const char *zPath,
2301 sqlite3_file *pFile,
2302 int flags,
2303 int *pOutFlags
2304){
danielk1977fee2d252007-08-18 10:59:19 +00002305 int fd = 0; /* File descriptor returned by open() */
2306 int dirfd = -1; /* Directory file descriptor */
2307 int oflags = 0; /* Flags to pass to open() */
2308 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00002309 int noLock; /* True to omit locking primitives */
danielk1977b4b47412007-08-17 15:53:36 +00002310
2311 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
2312 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
2313 int isCreate = (flags & SQLITE_OPEN_CREATE);
2314 int isReadonly = (flags & SQLITE_OPEN_READONLY);
2315 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
2316
danielk1977fee2d252007-08-18 10:59:19 +00002317 /* If creating a master or main-file journal, this function will open
2318 ** a file-descriptor on the directory too. The first time unixSync()
2319 ** is called the directory file descriptor will be fsync()ed and close()d.
2320 */
2321 int isOpenDirectory = (isCreate &&
2322 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
2323 );
2324
danielk197717b90b52008-06-06 11:11:25 +00002325 /* If argument zPath is a NULL pointer, this function is required to open
2326 ** a temporary file. Use this buffer to store the file name in.
2327 */
2328 char zTmpname[MAX_PATHNAME+1];
2329 const char *zName = zPath;
2330
danielk1977fee2d252007-08-18 10:59:19 +00002331 /* Check the following statements are true:
2332 **
2333 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
2334 ** (b) if CREATE is set, then READWRITE must also be set, and
2335 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00002336 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00002337 */
danielk1977b4b47412007-08-17 15:53:36 +00002338 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00002339 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00002340 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00002341 assert(isDelete==0 || isCreate);
2342
drh33f4e022007-09-03 15:19:34 +00002343 /* The main DB, main journal, and master journal are never automatically
2344 ** deleted
2345 */
2346 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
2347 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
2348 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00002349
danielk1977fee2d252007-08-18 10:59:19 +00002350 /* Assert that the upper layer has set one of the "file-type" flags. */
2351 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
2352 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
2353 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00002354 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00002355 );
2356
danielk1977e339d652008-06-28 11:23:00 +00002357 memset(pFile, 0, sizeof(unixFile));
2358
danielk197717b90b52008-06-06 11:11:25 +00002359 if( !zName ){
2360 int rc;
2361 assert(isDelete && !isOpenDirectory);
2362 rc = getTempname(MAX_PATHNAME+1, zTmpname);
2363 if( rc!=SQLITE_OK ){
2364 return rc;
2365 }
2366 zName = zTmpname;
2367 }
2368
danielk1977b4b47412007-08-17 15:53:36 +00002369 if( isReadonly ) oflags |= O_RDONLY;
2370 if( isReadWrite ) oflags |= O_RDWR;
2371 if( isCreate ) oflags |= O_CREAT;
2372 if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
2373 oflags |= (O_LARGEFILE|O_BINARY);
2374
danielk197717b90b52008-06-06 11:11:25 +00002375 fd = open(zName, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
danielk19772f2d8c72007-08-30 16:13:33 +00002376 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00002377 /* Failed to open the file for read/write access. Try read-only. */
2378 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
2379 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00002380 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00002381 }
2382 if( fd<0 ){
2383 return SQLITE_CANTOPEN;
2384 }
2385 if( isDelete ){
danielk197717b90b52008-06-06 11:11:25 +00002386 unlink(zName);
danielk1977b4b47412007-08-17 15:53:36 +00002387 }
2388 if( pOutFlags ){
2389 *pOutFlags = flags;
2390 }
2391
2392 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00002393 if( isOpenDirectory ){
2394 int rc = openDirectory(zPath, &dirfd);
2395 if( rc!=SQLITE_OK ){
2396 close(fd);
2397 return rc;
2398 }
2399 }
danielk1977e339d652008-06-28 11:23:00 +00002400
2401#ifdef FD_CLOEXEC
2402 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
2403#endif
2404
drhda0e7682008-07-30 15:27:54 +00002405 noLock = eType!=SQLITE_OPEN_MAIN_DB;
2406 return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock);
danielk1977b4b47412007-08-17 15:53:36 +00002407}
2408
2409/*
danielk1977fee2d252007-08-18 10:59:19 +00002410** Delete the file at zPath. If the dirSync argument is true, fsync()
2411** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00002412*/
drh153c62c2007-08-24 03:51:33 +00002413static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
danielk1977fee2d252007-08-18 10:59:19 +00002414 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00002415 SimulateIOError(return SQLITE_IOERR_DELETE);
2416 unlink(zPath);
danielk1977fee2d252007-08-18 10:59:19 +00002417 if( dirSync ){
2418 int fd;
2419 rc = openDirectory(zPath, &fd);
2420 if( rc==SQLITE_OK ){
2421 if( fsync(fd) ){
2422 rc = SQLITE_IOERR_DIR_FSYNC;
2423 }
2424 close(fd);
2425 }
2426 }
2427 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00002428}
2429
danielk197790949c22007-08-17 16:50:38 +00002430/*
2431** Test the existance of or access permissions of file zPath. The
2432** test performed depends on the value of flags:
2433**
2434** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
2435** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
2436** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
2437**
2438** Otherwise return 0.
2439*/
danielk1977861f7452008-06-05 11:39:11 +00002440static int unixAccess(
2441 sqlite3_vfs *pVfs,
2442 const char *zPath,
2443 int flags,
2444 int *pResOut
2445){
rse25c0d1a2007-09-20 08:38:14 +00002446 int amode = 0;
danielk1977861f7452008-06-05 11:39:11 +00002447 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00002448 switch( flags ){
2449 case SQLITE_ACCESS_EXISTS:
2450 amode = F_OK;
2451 break;
2452 case SQLITE_ACCESS_READWRITE:
2453 amode = W_OK|R_OK;
2454 break;
drh50d3f902007-08-27 21:10:36 +00002455 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00002456 amode = R_OK;
2457 break;
2458
2459 default:
2460 assert(!"Invalid flags argument");
2461 }
danielk1977861f7452008-06-05 11:39:11 +00002462 *pResOut = (access(zPath, amode)==0);
2463 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00002464}
2465
danielk1977b4b47412007-08-17 15:53:36 +00002466
2467/*
2468** Turn a relative pathname into a full pathname. The relative path
2469** is stored as a nul-terminated string in the buffer pointed to by
2470** zPath.
2471**
2472** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
2473** (in this case, MAX_PATHNAME bytes). The full-path is written to
2474** this buffer before returning.
2475*/
danielk1977adfb9b02007-09-17 07:02:56 +00002476static int unixFullPathname(
2477 sqlite3_vfs *pVfs, /* Pointer to vfs object */
2478 const char *zPath, /* Possibly relative input path */
2479 int nOut, /* Size of output buffer in bytes */
2480 char *zOut /* Output buffer */
2481){
danielk1977843e65f2007-09-01 16:16:15 +00002482
2483 /* It's odd to simulate an io-error here, but really this is just
2484 ** using the io-error infrastructure to test that SQLite handles this
2485 ** function failing. This function could fail if, for example, the
2486 ** current working directly has been unlinked.
2487 */
2488 SimulateIOError( return SQLITE_ERROR );
2489
drh153c62c2007-08-24 03:51:33 +00002490 assert( pVfs->mxPathname==MAX_PATHNAME );
drh3c7f2dc2007-12-06 13:26:20 +00002491 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00002492 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00002493 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002494 }else{
2495 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00002496 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00002497 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00002498 }
2499 nCwd = strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00002500 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00002501 }
2502 return SQLITE_OK;
2503
2504#if 0
2505 /*
2506 ** Remove "/./" path elements and convert "/A/./" path elements
2507 ** to just "/".
2508 */
2509 if( zFull ){
2510 int i, j;
2511 for(i=j=0; zFull[i]; i++){
2512 if( zFull[i]=='/' ){
2513 if( zFull[i+1]=='/' ) continue;
2514 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
2515 i += 1;
2516 continue;
2517 }
2518 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
2519 while( j>0 && zFull[j-1]!='/' ){ j--; }
2520 i += 3;
2521 continue;
2522 }
2523 }
2524 zFull[j++] = zFull[i];
2525 }
2526 zFull[j] = 0;
2527 }
2528#endif
2529}
2530
drh0ccebe72005-06-07 22:22:50 +00002531
drh761df872006-12-21 01:29:22 +00002532#ifndef SQLITE_OMIT_LOAD_EXTENSION
2533/*
2534** Interfaces for opening a shared library, finding entry points
2535** within the shared library, and closing the shared library.
2536*/
2537#include <dlfcn.h>
drh153c62c2007-08-24 03:51:33 +00002538static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
drh761df872006-12-21 01:29:22 +00002539 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
2540}
danielk197795c8a542007-09-01 06:51:27 +00002541
2542/*
2543** SQLite calls this function immediately after a call to unixDlSym() or
2544** unixDlOpen() fails (returns a null pointer). If a more detailed error
2545** message is available, it is written to zBufOut. If no error message
2546** is available, zBufOut is left unmodified and SQLite uses a default
2547** error message.
2548*/
drh153c62c2007-08-24 03:51:33 +00002549static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00002550 char *zErr;
2551 enterMutex();
2552 zErr = dlerror();
2553 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00002554 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00002555 }
2556 leaveMutex();
2557}
drh46c99e02007-08-27 23:26:59 +00002558static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
drh761df872006-12-21 01:29:22 +00002559 return dlsym(pHandle, zSymbol);
2560}
drh46c99e02007-08-27 23:26:59 +00002561static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
danielk1977b4b47412007-08-17 15:53:36 +00002562 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00002563}
danielk1977b4b47412007-08-17 15:53:36 +00002564#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
2565 #define unixDlOpen 0
2566 #define unixDlError 0
2567 #define unixDlSym 0
2568 #define unixDlClose 0
2569#endif
2570
2571/*
danielk197790949c22007-08-17 16:50:38 +00002572** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00002573*/
drh153c62c2007-08-24 03:51:33 +00002574static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
danielk197790949c22007-08-17 16:50:38 +00002575
2576 assert(nBuf>=(sizeof(time_t)+sizeof(int)));
2577
drhbbd42a62004-05-22 17:41:58 +00002578 /* We have to initialize zBuf to prevent valgrind from reporting
2579 ** errors. The reports issued by valgrind are incorrect - we would
2580 ** prefer that the randomness be increased by making use of the
2581 ** uninitialized space in zBuf - but valgrind errors tend to worry
2582 ** some users. Rather than argue, it seems easier just to initialize
2583 ** the whole array and silence valgrind, even if that means less randomness
2584 ** in the random seed.
2585 **
2586 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00002587 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00002588 ** tests repeatable.
2589 */
danielk1977b4b47412007-08-17 15:53:36 +00002590 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00002591#if !defined(SQLITE_TEST)
2592 {
drh842b8642005-01-21 17:53:17 +00002593 int pid, fd;
2594 fd = open("/dev/urandom", O_RDONLY);
2595 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00002596 time_t t;
2597 time(&t);
danielk197790949c22007-08-17 16:50:38 +00002598 memcpy(zBuf, &t, sizeof(t));
2599 pid = getpid();
2600 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
drh842b8642005-01-21 17:53:17 +00002601 }else{
danielk1977b4b47412007-08-17 15:53:36 +00002602 read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00002603 close(fd);
2604 }
drhbbd42a62004-05-22 17:41:58 +00002605 }
2606#endif
2607 return SQLITE_OK;
2608}
2609
danielk1977b4b47412007-08-17 15:53:36 +00002610
drhbbd42a62004-05-22 17:41:58 +00002611/*
2612** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00002613** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00002614** The return value is the number of microseconds of sleep actually
2615** requested from the underlying operating system, a number which
2616** might be greater than or equal to the argument, but not less
2617** than the argument.
drhbbd42a62004-05-22 17:41:58 +00002618*/
drh153c62c2007-08-24 03:51:33 +00002619static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
drhbbd42a62004-05-22 17:41:58 +00002620#if defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00002621 usleep(microseconds);
2622 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00002623#else
danielk1977b4b47412007-08-17 15:53:36 +00002624 int seconds = (microseconds+999999)/1000000;
2625 sleep(seconds);
drh4a50aac2007-08-23 02:47:53 +00002626 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00002627#endif
drh88f474a2006-01-02 20:00:12 +00002628}
2629
2630/*
drhbbd42a62004-05-22 17:41:58 +00002631** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00002632** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00002633*/
2634#ifdef SQLITE_TEST
2635int sqlite3_current_time = 0;
2636#endif
2637
2638/*
2639** Find the current time (in Universal Coordinated Time). Write the
2640** current time and date as a Julian Day number into *prNow and
2641** return 0. Return 1 if the time and date cannot be found.
2642*/
drh153c62c2007-08-24 03:51:33 +00002643static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
drh19e2d372005-08-29 23:00:03 +00002644#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00002645 time_t t;
2646 time(&t);
2647 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00002648#else
2649 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00002650 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00002651 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
2652#endif
drhbbd42a62004-05-22 17:41:58 +00002653#ifdef SQLITE_TEST
2654 if( sqlite3_current_time ){
2655 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
2656 }
2657#endif
2658 return 0;
2659}
danielk1977b4b47412007-08-17 15:53:36 +00002660
danielk1977bcb97fe2008-06-06 15:49:29 +00002661static int unixGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
2662 return 0;
2663}
2664
drh153c62c2007-08-24 03:51:33 +00002665/*
danielk1977e339d652008-06-28 11:23:00 +00002666** Initialize the operating system interface.
drh153c62c2007-08-24 03:51:33 +00002667*/
danielk1977c0fa4c52008-06-25 17:19:00 +00002668int sqlite3_os_init(void){
danielk1977e339d652008-06-28 11:23:00 +00002669 /* Macro to define the static contents of an sqlite3_vfs structure for
2670 ** the unix backend. The two parameters are the values to use for
2671 ** the sqlite3_vfs.zName and sqlite3_vfs.pAppData fields, respectively.
2672 **
2673 */
2674 #define UNIXVFS(zVfsName, pVfsAppData) { \
2675 1, /* iVersion */ \
2676 sizeof(unixFile), /* szOsFile */ \
2677 MAX_PATHNAME, /* mxPathname */ \
2678 0, /* pNext */ \
2679 zVfsName, /* zName */ \
2680 (void *)pVfsAppData, /* pAppData */ \
2681 unixOpen, /* xOpen */ \
2682 unixDelete, /* xDelete */ \
2683 unixAccess, /* xAccess */ \
2684 unixFullPathname, /* xFullPathname */ \
2685 unixDlOpen, /* xDlOpen */ \
2686 unixDlError, /* xDlError */ \
2687 unixDlSym, /* xDlSym */ \
2688 unixDlClose, /* xDlClose */ \
2689 unixRandomness, /* xRandomness */ \
2690 unixSleep, /* xSleep */ \
2691 unixCurrentTime, /* xCurrentTime */ \
2692 unixGetLastError /* xGetLastError */ \
2693 }
2694
2695 static sqlite3_vfs unixVfs = UNIXVFS("unix", 0);
2696#ifdef SQLITE_ENABLE_LOCKING_STYLE
2697#if 0
2698 int i;
2699 static sqlite3_vfs aVfs[] = {
2700 UNIXVFS("unix-posix", LOCKING_STYLE_POSIX),
2701 UNIXVFS("unix-afp", LOCKING_STYLE_AFP),
2702 UNIXVFS("unix-flock", LOCKING_STYLE_FLOCK),
2703 UNIXVFS("unix-dotfile", LOCKING_STYLE_DOTFILE),
2704 UNIXVFS("unix-none", LOCKING_STYLE_NONE)
drh153c62c2007-08-24 03:51:33 +00002705 };
danielk1977e339d652008-06-28 11:23:00 +00002706 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
2707 sqlite3_vfs_register(&aVfs[i], 0);
2708 }
2709#endif
2710#endif
danielk1977c0fa4c52008-06-25 17:19:00 +00002711 sqlite3_vfs_register(&unixVfs, 1);
2712 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00002713}
danielk1977e339d652008-06-28 11:23:00 +00002714
2715/*
2716** Shutdown the operating system interface. This is a no-op for unix.
2717*/
danielk1977c0fa4c52008-06-25 17:19:00 +00002718int sqlite3_os_end(void){
2719 return SQLITE_OK;
2720}
drhdce8bdb2007-08-16 13:01:44 +00002721
danielk197729bafea2008-06-26 10:41:19 +00002722#endif /* SQLITE_OS_UNIX */