blob: 364b6b0e1da26219f26c9bf70ee7a486f7946179 [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**
chw97185482008-11-17 08:05:31 +000015** $Id: os_unix.c,v 1.210 2008/11/17 08:05:32 chw 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/*
drh40bbb0a2008-09-23 10:23:26 +000021** If SQLITE_ENABLE_LOCKING_STYLE is defined and is non-zero, then several
22** alternative locking implementations are provided:
danielk1977e339d652008-06-28 11:23:00 +000023**
24** * POSIX locking (the default),
25** * No locking,
26** * Dot-file locking,
27** * flock() locking,
chw97185482008-11-17 08:05:31 +000028** * AFP locking (OSX only),
29** * Named POSIX semaphores (VXWorks only).
drh40bbb0a2008-09-23 10:23:26 +000030**
31** SQLITE_ENABLE_LOCKING_STYLE only works on a Mac. It is turned on by
32** default on a Mac and disabled on all other posix platforms.
danielk1977e339d652008-06-28 11:23:00 +000033*/
drh40bbb0a2008-09-23 10:23:26 +000034#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
35# if defined(__DARWIN__)
36# define SQLITE_ENABLE_LOCKING_STYLE 1
37# else
38# define SQLITE_ENABLE_LOCKING_STYLE 0
39# endif
40#endif
drhbfe66312006-10-03 17:40:40 +000041
drh9cbe6352005-11-29 03:13:21 +000042/*
43** These #defines should enable >2GB file support on Posix if the
44** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000045** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000046**
47** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
48** on the compiler command line. This is necessary if you are compiling
49** on a recent machine (ex: RedHat 7.2) but you want your code to work
50** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
51** without this option, LFS is enable. But LFS does not exist in the kernel
52** in RedHat 6.0, so the code won't work. Hence, for maximum binary
53** portability you should omit LFS.
drh9cbe6352005-11-29 03:13:21 +000054*/
55#ifndef SQLITE_DISABLE_LFS
56# define _LARGE_FILE 1
57# ifndef _FILE_OFFSET_BITS
58# define _FILE_OFFSET_BITS 64
59# endif
60# define _LARGEFILE_SOURCE 1
61#endif
drhbbd42a62004-05-22 17:41:58 +000062
drh9cbe6352005-11-29 03:13:21 +000063/*
64** standard include files.
65*/
66#include <sys/types.h>
67#include <sys/stat.h>
68#include <fcntl.h>
69#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000070#include <time.h>
drh19e2d372005-08-29 23:00:03 +000071#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000072#include <errno.h>
danielk1977e339d652008-06-28 11:23:00 +000073
drh40bbb0a2008-09-23 10:23:26 +000074#if SQLITE_ENABLE_LOCKING_STYLE
drhbfe66312006-10-03 17:40:40 +000075#include <sys/ioctl.h>
chw97185482008-11-17 08:05:31 +000076#if defined(__RTP__) || defined(_WRS_KERNEL)
77#define lstat stat
78#include <semaphore.h>
79#include <limits.h>
80#else
drhbfe66312006-10-03 17:40:40 +000081#include <sys/param.h>
82#include <sys/mount.h>
chw97185482008-11-17 08:05:31 +000083#endif
drhbfe66312006-10-03 17:40:40 +000084#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000085
86/*
drhf1a221e2006-01-15 17:27:17 +000087** If we are to be thread-safe, include the pthreads header and define
88** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +000089*/
drhd677b3d2007-08-20 22:48:41 +000090#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +000091# include <pthread.h>
92# define SQLITE_UNIX_THREADS 1
93#endif
94
95/*
96** Default permissions when creating a new file
97*/
98#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
99# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
100#endif
101
danielk1977b4b47412007-08-17 15:53:36 +0000102/*
103** Maximum supported path-length.
104*/
105#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000106
107
108/*
danielk1977ad94b582007-08-20 06:44:22 +0000109** The unixFile structure is subclass of sqlite3_file specific for the unix
drh054889e2005-11-30 03:20:31 +0000110** protability layer.
drh9cbe6352005-11-29 03:13:21 +0000111*/
drh054889e2005-11-30 03:20:31 +0000112typedef struct unixFile unixFile;
113struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000114 sqlite3_io_methods const *pMethod; /* Always the first entry */
danielk1977967a4a12007-08-20 14:23:44 +0000115#ifdef SQLITE_TEST
116 /* In test mode, increase the size of this structure a bit so that
117 ** it is larger than the struct CrashFile defined in test6.c.
118 */
119 char aPadding[32];
120#endif
drh9cbe6352005-11-29 03:13:21 +0000121 struct openCnt *pOpen; /* Info about all open fd's on this inode */
122 struct lockInfo *pLock; /* Info about locks on this inode */
drh40bbb0a2008-09-23 10:23:26 +0000123#if SQLITE_ENABLE_LOCKING_STYLE
drhbfe66312006-10-03 17:40:40 +0000124 void *lockingContext; /* Locking style specific state */
danielk1977e339d652008-06-28 11:23:00 +0000125#endif
drh9cbe6352005-11-29 03:13:21 +0000126 int h; /* The file descriptor */
127 unsigned char locktype; /* The type of lock held on this fd */
drh9cbe6352005-11-29 03:13:21 +0000128 int dirfd; /* File descriptor for the directory */
drhd677b3d2007-08-20 22:48:41 +0000129#if SQLITE_THREADSAFE
danielk1977ad94b582007-08-20 06:44:22 +0000130 pthread_t tid; /* The thread that "owns" this unixFile */
drh9cbe6352005-11-29 03:13:21 +0000131#endif
aswift5b1a2562008-08-22 00:22:35 +0000132 int lastErrno; /* The unix errno from the last I/O error */
chw97185482008-11-17 08:05:31 +0000133#if defined(__RTP__) || defined(_WRS_KERNEL)
134 int isDelete; /* Delete on close if true */
135 char *zRealpath;
136#endif
drh9cbe6352005-11-29 03:13:21 +0000137};
138
drh0ccebe72005-06-07 22:22:50 +0000139/*
drh198bf392006-01-06 21:52:49 +0000140** Include code that is common to all os_*.c files
141*/
142#include "os_common.h"
143
144/*
drh0ccebe72005-06-07 22:22:50 +0000145** Define various macros that are missing from some systems.
146*/
drhbbd42a62004-05-22 17:41:58 +0000147#ifndef O_LARGEFILE
148# define O_LARGEFILE 0
149#endif
150#ifdef SQLITE_DISABLE_LFS
151# undef O_LARGEFILE
152# define O_LARGEFILE 0
153#endif
154#ifndef O_NOFOLLOW
155# define O_NOFOLLOW 0
156#endif
157#ifndef O_BINARY
158# define O_BINARY 0
159#endif
160
161/*
162** The DJGPP compiler environment looks mostly like Unix, but it
163** lacks the fcntl() system call. So redefine fcntl() to be something
164** that always succeeds. This means that locking does not occur under
drh85b623f2007-12-13 21:54:09 +0000165** DJGPP. But it is DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000166*/
167#ifdef __DJGPP__
168# define fcntl(A,B,C) 0
169#endif
170
171/*
drh2b4b5962005-06-15 17:47:55 +0000172** The threadid macro resolves to the thread-id or to 0. Used for
173** testing and debugging only.
174*/
drhd677b3d2007-08-20 22:48:41 +0000175#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000176#define threadid pthread_self()
177#else
178#define threadid 0
179#endif
180
181/*
danielk1977ad94b582007-08-20 06:44:22 +0000182** Set or check the unixFile.tid field. This field is set when an unixFile
183** is first opened. All subsequent uses of the unixFile verify that the
184** same thread is operating on the unixFile. Some operating systems do
drh2b4b5962005-06-15 17:47:55 +0000185** not allow locks to be overridden by other threads and that restriction
186** means that sqlite3* database handles cannot be moved from one thread
187** to another. This logic makes sure a user does not try to do that
188** by mistake.
drhf1a221e2006-01-15 17:27:17 +0000189**
danielk1977ad94b582007-08-20 06:44:22 +0000190** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
drhf1a221e2006-01-15 17:27:17 +0000191** another as long as we are running on a system that supports threads
192** overriding each others locks (which now the most common behavior)
danielk1977ad94b582007-08-20 06:44:22 +0000193** or if no locks are held. But the unixFile.pLock field needs to be
drhf1a221e2006-01-15 17:27:17 +0000194** recomputed because its key includes the thread-id. See the
195** transferOwnership() function below for additional information
drh2b4b5962005-06-15 17:47:55 +0000196*/
drhd677b3d2007-08-20 22:48:41 +0000197#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000198# define SET_THREADID(X) (X)->tid = pthread_self()
drh029b44b2006-01-15 00:13:15 +0000199# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
200 !pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000201#else
202# define SET_THREADID(X)
203# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000204#endif
205
drhbbd42a62004-05-22 17:41:58 +0000206/*
207** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
208** section 6.5.2.2 lines 483 through 490 specify that when a process
209** sets or clears a lock, that operation overrides any prior locks set
210** by the same process. It does not explicitly say so, but this implies
211** that it overrides locks set by the same process using a different
212** file descriptor. Consider this test case:
drhbbd42a62004-05-22 17:41:58 +0000213** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
214**
215** Suppose ./file1 and ./file2 are really the same file (because
216** one is a hard or symbolic link to the other) then if you set
217** an exclusive lock on fd1, then try to get an exclusive lock
218** on fd2, it works. I would have expected the second lock to
219** fail since there was already a lock on the file due to fd1.
220** But not so. Since both locks came from the same process, the
221** second overrides the first, even though they were on different
222** file descriptors opened on different file names.
223**
224** Bummer. If you ask me, this is broken. Badly broken. It means
225** that we cannot use POSIX locks to synchronize file access among
226** competing threads of the same process. POSIX locks will work fine
227** to synchronize access for threads in separate processes, but not
228** threads within the same process.
229**
230** To work around the problem, SQLite has to manage file locks internally
231** on its own. Whenever a new database is opened, we have to find the
232** specific inode of the database file (the inode is determined by the
233** st_dev and st_ino fields of the stat structure that fstat() fills in)
234** and check for locks already existing on that inode. When locks are
235** created or removed, we have to look at our own internal record of the
236** locks to see if another thread has previously set a lock on that same
237** inode.
238**
danielk1977ad94b582007-08-20 06:44:22 +0000239** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000240** descriptor. It is now a structure that holds the integer file
241** descriptor and a pointer to a structure that describes the internal
242** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000243** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000244** point to the same locking structure. The locking structure keeps
245** a reference count (so we will know when to delete it) and a "cnt"
246** field that tells us its internal lock status. cnt==0 means the
247** file is unlocked. cnt==-1 means the file has an exclusive lock.
248** cnt>0 means there are cnt shared locks on the file.
249**
250** Any attempt to lock or unlock a file first checks the locking
251** structure. The fcntl() system call is only invoked to set a
252** POSIX lock if the internal lock structure transitions between
253** a locked and an unlocked state.
254**
255** 2004-Jan-11:
256** More recent discoveries about POSIX advisory locks. (The more
257** I discover, the more I realize the a POSIX advisory locks are
258** an abomination.)
259**
260** If you close a file descriptor that points to a file that has locks,
261** all locks on that file that are owned by the current process are
danielk1977ad94b582007-08-20 06:44:22 +0000262** released. To work around this problem, each unixFile structure contains
drhbbd42a62004-05-22 17:41:58 +0000263** a pointer to an openCnt structure. There is one openCnt structure
danielk1977ad94b582007-08-20 06:44:22 +0000264** per open inode, which means that multiple unixFile can point to a single
265** openCnt. When an attempt is made to close an unixFile, if there are
266** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000267** to close() the file descriptor is deferred until all of the locks clear.
268** The openCnt structure keeps a list of file descriptors that need to
269** be closed and that list is walked (and cleared) when the last lock
270** clears.
271**
272** First, under Linux threads, because each thread has a separate
273** process ID, lock operations in one thread do not override locks
274** to the same file in other threads. Linux threads behave like
275** separate processes in this respect. But, if you close a file
276** descriptor in linux threads, all locks are cleared, even locks
277** on other threads and even though the other threads have different
278** process IDs. Linux threads is inconsistent in this respect.
279** (I'm beginning to think that linux threads is an abomination too.)
280** The consequence of this all is that the hash table for the lockInfo
281** structure has to include the process id as part of its key because
282** locks in different threads are treated as distinct. But the
283** openCnt structure should not include the process id in its
284** key because close() clears lock on all threads, not just the current
285** thread. Were it not for this goofiness in linux threads, we could
286** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000287**
288** 2004-Jun-28:
289** On some versions of linux, threads can override each others locks.
290** On others not. Sometimes you can change the behavior on the same
291** system by setting the LD_ASSUME_KERNEL environment variable. The
292** POSIX standard is silent as to which behavior is correct, as far
293** as I can tell, so other versions of unix might show the same
294** inconsistency. There is no little doubt in my mind that posix
295** advisory locks and linux threads are profoundly broken.
296**
297** To work around the inconsistencies, we have to test at runtime
298** whether or not threads can override each others locks. This test
299** is run once, the first time any lock is attempted. A static
300** variable is set to record the results of this test for future
301** use.
drhbbd42a62004-05-22 17:41:58 +0000302*/
303
304/*
305** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000306** to locate a particular lockInfo structure given its inode.
307**
308** If threads cannot override each others locks, then we set the
309** lockKey.tid field to the thread ID. If threads can override
drhf1a221e2006-01-15 17:27:17 +0000310** each others locks then tid is always set to zero. tid is omitted
311** if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000312*/
313struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000314 dev_t dev; /* Device number */
chw97185482008-11-17 08:05:31 +0000315#if defined(__RTP__) || defined(_WRS_KERNEL)
316 void *rnam; /* Realname since inode unusable */
317#else
drh5fdae772004-06-29 03:29:00 +0000318 ino_t ino; /* Inode number */
chw97185482008-11-17 08:05:31 +0000319#endif
drhd677b3d2007-08-20 22:48:41 +0000320#if SQLITE_THREADSAFE
drhd9cb6ac2005-10-20 07:28:17 +0000321 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000322#endif
drhbbd42a62004-05-22 17:41:58 +0000323};
324
325/*
326** An instance of the following structure is allocated for each open
327** inode on each thread with a different process ID. (Threads have
328** different process IDs on linux, but not on most other unixes.)
329**
danielk1977ad94b582007-08-20 06:44:22 +0000330** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000331** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000332** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000333*/
334struct lockInfo {
335 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000336 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000337 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000338 int nRef; /* Number of pointers to this structure */
drhda0e7682008-07-30 15:27:54 +0000339 struct lockInfo *pNext, *pPrev; /* List of all lockInfo objects */
drhbbd42a62004-05-22 17:41:58 +0000340};
341
342/*
343** An instance of the following structure serves as the key used
344** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000345** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000346*/
347struct openKey {
348 dev_t dev; /* Device number */
chw97185482008-11-17 08:05:31 +0000349#if defined(__RTP__) || defined(_WRS_KERNEL)
350 void *rnam; /* Realname since inode unusable */
351#else
drhbbd42a62004-05-22 17:41:58 +0000352 ino_t ino; /* Inode number */
chw97185482008-11-17 08:05:31 +0000353#endif
drhbbd42a62004-05-22 17:41:58 +0000354};
355
356/*
357** An instance of the following structure is allocated for each open
358** inode. This structure keeps track of the number of locks on that
359** inode. If a close is attempted against an inode that is holding
360** locks, the close is deferred until all locks clear by adding the
361** file descriptor to be closed to the pending list.
362*/
363struct openCnt {
364 struct openKey key; /* The lookup key */
365 int nRef; /* Number of pointers to this structure */
366 int nLock; /* Number of outstanding locks */
367 int nPending; /* Number of pending close() operations */
368 int *aPending; /* Malloced space holding fd's awaiting a close() */
chw97185482008-11-17 08:05:31 +0000369#if defined(__RTP__) || defined(_WRS_KERNEL)
370 sem_t *pSem; /* Named POSIX semaphore */
371 char aSemName[MAX_PATHNAME+1]; /* Name of that semaphore */
372#endif
drhda0e7682008-07-30 15:27:54 +0000373 struct openCnt *pNext, *pPrev; /* List of all openCnt objects */
drhbbd42a62004-05-22 17:41:58 +0000374};
375
drhda0e7682008-07-30 15:27:54 +0000376/*
377** List of all lockInfo and openCnt objects. This used to be a hash
378** table. But the number of objects is rarely more than a dozen and
379** never exceeds a few thousand. And lookup is not on a critical
380** path oo a simple linked list will suffice.
drhbbd42a62004-05-22 17:41:58 +0000381*/
drhda0e7682008-07-30 15:27:54 +0000382static struct lockInfo *lockList = 0;
383static struct openCnt *openList = 0;
drh5fdae772004-06-29 03:29:00 +0000384
chw97185482008-11-17 08:05:31 +0000385#if defined(__RTP__) || defined(_WRS_KERNEL)
386/*
387** This hash table is used to bind the canonical file name to a
388** unixFile structure and use the hash key (= canonical name)
389** instead of the Inode number of the file to find the matching
390** lockInfo and openCnt structures. It also helps to make the
391** name of the semaphore when LOCKING_STYLE_NAMEDSEM is used
392** for the file.
393*/
394static Hash nameHash;
395#endif
396
drhbfe66312006-10-03 17:40:40 +0000397/*
398** The locking styles are associated with the different file locking
399** capabilities supported by different file systems.
400**
401** POSIX locking style fully supports shared and exclusive byte-range locks
danielk1977e339d652008-06-28 11:23:00 +0000402** AFP locking only supports exclusive byte-range locks
drhbfe66312006-10-03 17:40:40 +0000403** FLOCK only supports a single file-global exclusive lock
404** DOTLOCK isn't a true locking style, it refers to the use of a special
405** file named the same as the database file with a '.lock' extension, this
406** can be used on file systems that do not offer any reliable file locking
407** NO locking means that no locking will be attempted, this is only used for
408** read-only file systems currently
chw97185482008-11-17 08:05:31 +0000409** NAMEDSEM is similar to DOTLOCK but uses a named semaphore instead of an
410** indicator file.
drhbfe66312006-10-03 17:40:40 +0000411** UNSUPPORTED means that no locking will be attempted, this is only used for
412** file systems that are known to be unsupported
413*/
danielk1977e339d652008-06-28 11:23:00 +0000414#define LOCKING_STYLE_POSIX 1
drhda0e7682008-07-30 15:27:54 +0000415#define LOCKING_STYLE_NONE 2
danielk1977e339d652008-06-28 11:23:00 +0000416#define LOCKING_STYLE_DOTFILE 3
drhda0e7682008-07-30 15:27:54 +0000417#define LOCKING_STYLE_FLOCK 4
danielk1977e339d652008-06-28 11:23:00 +0000418#define LOCKING_STYLE_AFP 5
chw97185482008-11-17 08:05:31 +0000419#define LOCKING_STYLE_NAMEDSEM 6
drhbfe66312006-10-03 17:40:40 +0000420
danielk1977ad94b582007-08-20 06:44:22 +0000421/*
aswift5b1a2562008-08-22 00:22:35 +0000422** Only set the lastErrno if the error code is a real error and not
423** a normal expected return code of SQLITE_BUSY or SQLITE_OK
424*/
425#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
426
427/*
danielk1977ad94b582007-08-20 06:44:22 +0000428** Helper functions to obtain and relinquish the global mutex.
429*/
danielk19770afae932008-09-24 09:12:46 +0000430static void enterMutex(void){
danielk197759f8c082008-06-18 17:09:10 +0000431 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
danielk1977b4b47412007-08-17 15:53:36 +0000432}
danielk19770afae932008-09-24 09:12:46 +0000433static void leaveMutex(void){
danielk197759f8c082008-06-18 17:09:10 +0000434 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
danielk1977b4b47412007-08-17 15:53:36 +0000435}
436
drhd677b3d2007-08-20 22:48:41 +0000437#if SQLITE_THREADSAFE
drh5fdae772004-06-29 03:29:00 +0000438/*
439** This variable records whether or not threads can override each others
440** locks.
441**
442** 0: No. Threads cannot override each others locks.
443** 1: Yes. Threads can override each others locks.
444** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000445**
drh5062d3a2006-01-31 23:03:35 +0000446** On some systems, we know at compile-time if threads can override each
447** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
448** will be set appropriately. On other systems, we have to check at
449** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
450** undefined.
451**
drhf1a221e2006-01-15 17:27:17 +0000452** This variable normally has file scope only. But during testing, we make
453** it a global so that the test code can change its value in order to verify
454** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000455*/
drh5062d3a2006-01-31 23:03:35 +0000456#ifndef SQLITE_THREAD_OVERRIDE_LOCK
457# define SQLITE_THREAD_OVERRIDE_LOCK -1
458#endif
drh029b44b2006-01-15 00:13:15 +0000459#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000460int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000461#else
drh5062d3a2006-01-31 23:03:35 +0000462static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000463#endif
drh5fdae772004-06-29 03:29:00 +0000464
465/*
466** This structure holds information passed into individual test
467** threads by the testThreadLockingBehavior() routine.
468*/
469struct threadTestData {
470 int fd; /* File to be locked */
471 struct flock lock; /* The locking operation */
472 int result; /* Result of the locking operation */
473};
474
drh2b4b5962005-06-15 17:47:55 +0000475#ifdef SQLITE_LOCK_TRACE
476/*
477** Print out information about all locking operations.
478**
479** This routine is used for troubleshooting locks on multithreaded
480** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
481** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000482** turned off.
drh2b4b5962005-06-15 17:47:55 +0000483*/
484static int lockTrace(int fd, int op, struct flock *p){
485 char *zOpName, *zType;
486 int s;
487 int savedErrno;
488 if( op==F_GETLK ){
489 zOpName = "GETLK";
490 }else if( op==F_SETLK ){
491 zOpName = "SETLK";
492 }else{
493 s = fcntl(fd, op, p);
494 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
495 return s;
496 }
497 if( p->l_type==F_RDLCK ){
498 zType = "RDLCK";
499 }else if( p->l_type==F_WRLCK ){
500 zType = "WRLCK";
501 }else if( p->l_type==F_UNLCK ){
502 zType = "UNLCK";
503 }else{
504 assert( 0 );
505 }
506 assert( p->l_whence==SEEK_SET );
507 s = fcntl(fd, op, p);
508 savedErrno = errno;
509 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
510 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
511 (int)p->l_pid, s);
drhe2396a12007-03-29 20:19:58 +0000512 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
drh2b4b5962005-06-15 17:47:55 +0000513 struct flock l2;
514 l2 = *p;
515 fcntl(fd, F_GETLK, &l2);
516 if( l2.l_type==F_RDLCK ){
517 zType = "RDLCK";
518 }else if( l2.l_type==F_WRLCK ){
519 zType = "WRLCK";
520 }else if( l2.l_type==F_UNLCK ){
521 zType = "UNLCK";
522 }else{
523 assert( 0 );
524 }
525 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
526 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
527 }
528 errno = savedErrno;
529 return s;
530}
531#define fcntl lockTrace
532#endif /* SQLITE_LOCK_TRACE */
533
danielk197741a6a612008-11-11 18:34:35 +0000534#ifdef __linux__
drh5fdae772004-06-29 03:29:00 +0000535/*
danielk197741a6a612008-11-11 18:34:35 +0000536** This function is used as the main routine for a thread launched by
537** testThreadLockingBehavior(). It tests whether the shared-lock obtained
538** by the main thread in testThreadLockingBehavior() conflicts with a
539** hypothetical write-lock obtained by this thread on the same file.
540**
541** The write-lock is not actually acquired, as this is not possible if
542** the file is open in read-only mode (see ticket #3472).
543*/
drh5fdae772004-06-29 03:29:00 +0000544static void *threadLockingTest(void *pArg){
545 struct threadTestData *pData = (struct threadTestData*)pArg;
danielk197741a6a612008-11-11 18:34:35 +0000546 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
drh5fdae772004-06-29 03:29:00 +0000547 return pArg;
548}
549
550/*
551** This procedure attempts to determine whether or not threads
552** can override each others locks then sets the
553** threadsOverrideEachOthersLocks variable appropriately.
554*/
danielk19774d5238f2006-01-27 06:32:00 +0000555static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000556 int fd;
danielk197741a6a612008-11-11 18:34:35 +0000557 int rc;
558 struct threadTestData d;
559 struct flock l;
560 pthread_t t;
drh5fdae772004-06-29 03:29:00 +0000561
562 fd = dup(fd_orig);
563 if( fd<0 ) return;
danielk197741a6a612008-11-11 18:34:35 +0000564 memset(&l, 0, sizeof(l));
565 l.l_type = F_RDLCK;
566 l.l_len = 1;
567 l.l_start = 0;
568 l.l_whence = SEEK_SET;
569 rc = fcntl(fd_orig, F_SETLK, &l);
570 if( rc!=0 ) return;
571 memset(&d, 0, sizeof(d));
572 d.fd = fd;
573 d.lock = l;
574 d.lock.l_type = F_WRLCK;
575 pthread_create(&t, 0, threadLockingTest, &d);
576 pthread_join(t, 0);
drh5fdae772004-06-29 03:29:00 +0000577 close(fd);
danielk197741a6a612008-11-11 18:34:35 +0000578 if( d.result!=0 ) return;
579 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
drh5fdae772004-06-29 03:29:00 +0000580}
danielk197741a6a612008-11-11 18:34:35 +0000581#else
582/*
583** On anything other than linux, assume threads override each others locks.
584*/
585static void testThreadLockingBehavior(int fd_orig){
586 threadsOverrideEachOthersLocks = 1;
587}
588#endif /* __linux__ */
589
drhd677b3d2007-08-20 22:48:41 +0000590#endif /* SQLITE_THREADSAFE */
drh5fdae772004-06-29 03:29:00 +0000591
drhbbd42a62004-05-22 17:41:58 +0000592/*
593** Release a lockInfo structure previously allocated by findLockInfo().
594*/
595static void releaseLockInfo(struct lockInfo *pLock){
danielk1977e339d652008-06-28 11:23:00 +0000596 if( pLock ){
597 pLock->nRef--;
598 if( pLock->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000599 if( pLock->pPrev ){
600 assert( pLock->pPrev->pNext==pLock );
601 pLock->pPrev->pNext = pLock->pNext;
602 }else{
603 assert( lockList==pLock );
604 lockList = pLock->pNext;
605 }
606 if( pLock->pNext ){
607 assert( pLock->pNext->pPrev==pLock );
608 pLock->pNext->pPrev = pLock->pPrev;
609 }
danielk1977e339d652008-06-28 11:23:00 +0000610 sqlite3_free(pLock);
611 }
drhbbd42a62004-05-22 17:41:58 +0000612 }
613}
614
615/*
616** Release a openCnt structure previously allocated by findLockInfo().
617*/
618static void releaseOpenCnt(struct openCnt *pOpen){
danielk1977e339d652008-06-28 11:23:00 +0000619 if( pOpen ){
620 pOpen->nRef--;
621 if( pOpen->nRef==0 ){
drhda0e7682008-07-30 15:27:54 +0000622 if( pOpen->pPrev ){
623 assert( pOpen->pPrev->pNext==pOpen );
624 pOpen->pPrev->pNext = pOpen->pNext;
625 }else{
626 assert( openList==pOpen );
627 openList = pOpen->pNext;
628 }
629 if( pOpen->pNext ){
630 assert( pOpen->pNext->pPrev==pOpen );
631 pOpen->pNext->pPrev = pOpen->pPrev;
632 }
633 sqlite3_free(pOpen->aPending);
danielk1977e339d652008-06-28 11:23:00 +0000634 sqlite3_free(pOpen);
635 }
drhbbd42a62004-05-22 17:41:58 +0000636 }
637}
638
chw97185482008-11-17 08:05:31 +0000639#if defined(__RTP__) || defined(_WRS_KERNEL)
640/*
641** Implementation of a realpath() like function for vxWorks
642** to determine canonical path name from given name. It does
643** not support symlinks. Neither does it handle volume prefixes.
644*/
645char *
646vxrealpath(const char *pathname, int dostat)
647{
648 struct stat sbuf;
649 int len;
650 char *where, *ptr, *last;
651 char *result, *curpath, *workpath, *namebuf;
652
653 len = pathconf(pathname, _PC_PATH_MAX);
654 if( len<0 ){
655 len = PATH_MAX;
656 }
657 result = sqlite3_malloc(len * 4);
658 if( !result ){
659 return 0;
660 }
661 curpath = result + len;
662 workpath = curpath + len;
663 namebuf = workpath + len;
664 strcpy(curpath, pathname);
665 if( *pathname!='/' ){
666 if( !getcwd(workpath, len) ){
667 sqlite3_free(result);
668 return 0;
669 }
670 }else{
671 *workpath = '\0';
672 }
673 where = curpath;
674 while( *where ){
675 if( !strcmp(where, ".") ){
676 where++;
677 continue;
678 }
679 if( !strncmp(where, "./", 2) ){
680 where += 2;
681 continue;
682 }
683 if( !strncmp(where, "../", 3) ){
684 where += 3;
685 ptr = last = workpath;
686 while( *ptr ){
687 if( *ptr=='/' ){
688 last = ptr;
689 }
690 ptr++;
691 }
692 *last = '\0';
693 continue;
694 }
695 ptr = strchr(where, '/');
696 if( !ptr ){
697 ptr = where + strlen(where) - 1;
698 }else{
699 *ptr = '\0';
700 }
701 strcpy(namebuf, workpath);
702 for( last = namebuf; *last; last++ ){
703 continue;
704 }
705 if( *--last!='/' ){
706 strcat(namebuf, "/");
707 }
708 strcat(namebuf, where);
709 where = ++ptr;
710 if( dostat ){
711 if( stat(namebuf, &sbuf)==-1 ){
712 sqlite3_free(result);
713 return 0;
714 }
715 if( (sbuf.st_mode & S_IFDIR)==S_IFDIR ){
716 strcpy(workpath, namebuf);
717 continue;
718 }
719 if( *where ){
720 sqlite3_free(result);
721 return 0;
722 }
723 }
724 strcpy(workpath, namebuf);
725 }
726 strcpy(result, workpath);
727 return result;
728}
729#endif
730
drh40bbb0a2008-09-23 10:23:26 +0000731#if SQLITE_ENABLE_LOCKING_STYLE
drhbfe66312006-10-03 17:40:40 +0000732/*
733** Tests a byte-range locking query to see if byte range locks are
734** supported, if not we fall back to dotlockLockingStyle.
chw97185482008-11-17 08:05:31 +0000735** On vxWorks we fall back to namedsemLockingStyle.
drhbfe66312006-10-03 17:40:40 +0000736*/
danielk1977e339d652008-06-28 11:23:00 +0000737static int testLockingStyle(int fd){
drhbfe66312006-10-03 17:40:40 +0000738 struct flock lockInfo;
danielk1977e339d652008-06-28 11:23:00 +0000739
740 /* Test byte-range lock using fcntl(). If the call succeeds,
741 ** assume that the file-system supports POSIX style locks.
742 */
drhbfe66312006-10-03 17:40:40 +0000743 lockInfo.l_len = 1;
744 lockInfo.l_start = 0;
745 lockInfo.l_whence = SEEK_SET;
746 lockInfo.l_type = F_RDLCK;
danielk1977ad94b582007-08-20 06:44:22 +0000747 if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
danielk1977e339d652008-06-28 11:23:00 +0000748 return LOCKING_STYLE_POSIX;
749 }
drhbfe66312006-10-03 17:40:40 +0000750
danielk1977e339d652008-06-28 11:23:00 +0000751 /* Testing for flock() can give false positives. So if if the above
752 ** test fails, then we fall back to using dot-file style locking.
chw97185482008-11-17 08:05:31 +0000753 */
754#if defined(__RTP__) || defined(_WRS_KERNEL)
755 return LOCKING_STYLE_NAMEDSEM;
756#else
danielk1977e339d652008-06-28 11:23:00 +0000757 return LOCKING_STYLE_DOTFILE;
chw97185482008-11-17 08:05:31 +0000758#endif
drhbfe66312006-10-03 17:40:40 +0000759}
drh93a960a2008-07-10 00:32:42 +0000760#endif
drhbfe66312006-10-03 17:40:40 +0000761
762/*
danielk1977e339d652008-06-28 11:23:00 +0000763** If SQLITE_ENABLE_LOCKING_STYLE is defined, this function Examines the
764** f_fstypename entry in the statfs structure as returned by stat() for
765** the file system hosting the database file and selects the appropriate
766** locking style based on its value. These values and assignments are
767** based on Darwin/OSX behavior and have not been thoroughly tested on
drhbfe66312006-10-03 17:40:40 +0000768** other systems.
danielk1977e339d652008-06-28 11:23:00 +0000769**
770** If SQLITE_ENABLE_LOCKING_STYLE is not defined, this function always
771** returns LOCKING_STYLE_POSIX.
drhbfe66312006-10-03 17:40:40 +0000772*/
danielk1977e339d652008-06-28 11:23:00 +0000773static int detectLockingStyle(
774 sqlite3_vfs *pVfs,
danielk1977ad94b582007-08-20 06:44:22 +0000775 const char *filePath,
776 int fd
777){
drh40bbb0a2008-09-23 10:23:26 +0000778#if SQLITE_ENABLE_LOCKING_STYLE
chw97185482008-11-17 08:05:31 +0000779#if defined(__RTP__) || defined(_WRS_KERNEL)
780 if( !filePath ){
781 return LOCKING_STYLE_NONE;
782 }
783 if( pVfs->pAppData ){
784 return SQLITE_PTR_TO_INT(pVfs->pAppData);
785 }
786 if (access(filePath, 0) != -1){
787 return testLockingStyle(fd);
788 }
789#else
danielk1977e339d652008-06-28 11:23:00 +0000790 struct Mapping {
791 const char *zFilesystem;
792 int eLockingStyle;
793 } aMap[] = {
794 { "hfs", LOCKING_STYLE_POSIX },
795 { "ufs", LOCKING_STYLE_POSIX },
796 { "afpfs", LOCKING_STYLE_AFP },
aswift5b1a2562008-08-22 00:22:35 +0000797#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
798 { "smbfs", LOCKING_STYLE_AFP },
799#else
danielk1977e339d652008-06-28 11:23:00 +0000800 { "smbfs", LOCKING_STYLE_FLOCK },
aswift5b1a2562008-08-22 00:22:35 +0000801#endif
danielk1977e339d652008-06-28 11:23:00 +0000802 { "msdos", LOCKING_STYLE_DOTFILE },
803 { "webdav", LOCKING_STYLE_NONE },
804 { 0, 0 }
805 };
806 int i;
drhbfe66312006-10-03 17:40:40 +0000807 struct statfs fsInfo;
808
danielk1977e339d652008-06-28 11:23:00 +0000809 if( !filePath ){
810 return LOCKING_STYLE_NONE;
drh339eb0b2008-03-07 15:34:11 +0000811 }
danielk1977e339d652008-06-28 11:23:00 +0000812 if( pVfs->pAppData ){
aswiftf54b1b32008-08-22 18:41:37 +0000813 return SQLITE_PTR_TO_INT(pVfs->pAppData);
drh339eb0b2008-03-07 15:34:11 +0000814 }
drhbfe66312006-10-03 17:40:40 +0000815
danielk1977e339d652008-06-28 11:23:00 +0000816 if( statfs(filePath, &fsInfo) != -1 ){
817 if( fsInfo.f_flags & MNT_RDONLY ){
818 return LOCKING_STYLE_NONE;
819 }
820 for(i=0; aMap[i].zFilesystem; i++){
821 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
822 return aMap[i].eLockingStyle;
823 }
824 }
825 }
826
827 /* Default case. Handles, amongst others, "nfs". */
828 return testLockingStyle(fd);
829#endif
chw97185482008-11-17 08:05:31 +0000830#endif
danielk1977e339d652008-06-28 11:23:00 +0000831 return LOCKING_STYLE_POSIX;
832}
drhbfe66312006-10-03 17:40:40 +0000833
drhbbd42a62004-05-22 17:41:58 +0000834/*
835** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000836** describes that file descriptor. Create new ones if necessary. The
837** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000838**
drh65594042008-05-05 16:56:34 +0000839** Return an appropriate error code.
drhbbd42a62004-05-22 17:41:58 +0000840*/
drh38f82712004-06-18 17:10:16 +0000841static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000842 int fd, /* The file descriptor used in the key */
chw97185482008-11-17 08:05:31 +0000843#if defined(__RTP__) || defined(_WRS_KERNEL)
844 void *rnam, /* vxWorks realname */
845#endif
drhbbd42a62004-05-22 17:41:58 +0000846 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000847 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000848){
849 int rc;
850 struct lockKey key1;
851 struct openKey key2;
852 struct stat statbuf;
853 struct lockInfo *pLock;
854 struct openCnt *pOpen;
855 rc = fstat(fd, &statbuf);
drh65594042008-05-05 16:56:34 +0000856 if( rc!=0 ){
857#ifdef EOVERFLOW
858 if( errno==EOVERFLOW ) return SQLITE_NOLFS;
859#endif
860 return SQLITE_IOERR;
861 }
danielk1977441b09a2006-01-05 13:48:29 +0000862
drh54626242008-07-30 17:28:04 +0000863 /* On OS X on an msdos filesystem, the inode number is reported
864 ** incorrectly for zero-size files. See ticket #3260. To work
865 ** around this problem (we consider it a bug in OS X, not SQLite)
866 ** we always increase the file size to 1 by writing a single byte
867 ** prior to accessing the inode number. The one byte written is
868 ** an ASCII 'S' character which also happens to be the first byte
869 ** in the header of every SQLite database. In this way, if there
870 ** is a race condition such that another thread has already populated
871 ** the first page of the database, no damage is done.
872 */
873 if( statbuf.st_size==0 ){
874 write(fd, "S", 1);
875 rc = fstat(fd, &statbuf);
876 if( rc!=0 ){
877 return SQLITE_IOERR;
878 }
879 }
880
drhbbd42a62004-05-22 17:41:58 +0000881 memset(&key1, 0, sizeof(key1));
882 key1.dev = statbuf.st_dev;
chw97185482008-11-17 08:05:31 +0000883#if defined(__RTP__) || defined(_WRS_KERNEL)
884 key1.rnam = rnam;
885#else
drhbbd42a62004-05-22 17:41:58 +0000886 key1.ino = statbuf.st_ino;
chw97185482008-11-17 08:05:31 +0000887#endif
drhd677b3d2007-08-20 22:48:41 +0000888#if SQLITE_THREADSAFE
drh5fdae772004-06-29 03:29:00 +0000889 if( threadsOverrideEachOthersLocks<0 ){
890 testThreadLockingBehavior(fd);
891 }
892 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
893#endif
drhbbd42a62004-05-22 17:41:58 +0000894 memset(&key2, 0, sizeof(key2));
895 key2.dev = statbuf.st_dev;
chw97185482008-11-17 08:05:31 +0000896#if defined(__RTP__) || defined(_WRS_KERNEL)
897 key2.rnam = rnam;
898#else
drhbbd42a62004-05-22 17:41:58 +0000899 key2.ino = statbuf.st_ino;
chw97185482008-11-17 08:05:31 +0000900#endif
drhda0e7682008-07-30 15:27:54 +0000901 pLock = lockList;
902 while( pLock && memcmp(&key1, &pLock->key, sizeof(key1)) ){
903 pLock = pLock->pNext;
904 }
drhbbd42a62004-05-22 17:41:58 +0000905 if( pLock==0 ){
drh17435752007-08-16 04:30:38 +0000906 pLock = sqlite3_malloc( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000907 if( pLock==0 ){
drh65594042008-05-05 16:56:34 +0000908 rc = SQLITE_NOMEM;
danielk1977441b09a2006-01-05 13:48:29 +0000909 goto exit_findlockinfo;
910 }
drhbbd42a62004-05-22 17:41:58 +0000911 pLock->key = key1;
912 pLock->nRef = 1;
913 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000914 pLock->locktype = 0;
drhda0e7682008-07-30 15:27:54 +0000915 pLock->pNext = lockList;
916 pLock->pPrev = 0;
917 if( lockList ) lockList->pPrev = pLock;
918 lockList = pLock;
drhbbd42a62004-05-22 17:41:58 +0000919 }else{
920 pLock->nRef++;
921 }
922 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000923 if( ppOpen!=0 ){
drhda0e7682008-07-30 15:27:54 +0000924 pOpen = openList;
925 while( pOpen && memcmp(&key2, &pOpen->key, sizeof(key2)) ){
926 pOpen = pOpen->pNext;
927 }
drhbbd42a62004-05-22 17:41:58 +0000928 if( pOpen==0 ){
drh17435752007-08-16 04:30:38 +0000929 pOpen = sqlite3_malloc( sizeof(*pOpen) );
drh029b44b2006-01-15 00:13:15 +0000930 if( pOpen==0 ){
931 releaseLockInfo(pLock);
drh65594042008-05-05 16:56:34 +0000932 rc = SQLITE_NOMEM;
drh029b44b2006-01-15 00:13:15 +0000933 goto exit_findlockinfo;
934 }
935 pOpen->key = key2;
936 pOpen->nRef = 1;
937 pOpen->nLock = 0;
938 pOpen->nPending = 0;
939 pOpen->aPending = 0;
drhda0e7682008-07-30 15:27:54 +0000940 pOpen->pNext = openList;
941 pOpen->pPrev = 0;
942 if( openList ) openList->pPrev = pOpen;
943 openList = pOpen;
chw97185482008-11-17 08:05:31 +0000944#if defined(__RTP__) || defined(_WRS_KERNEL)
945 pOpen->pSem = NULL;
946 pOpen->aSemName[0] = '\0';
947#endif
drh029b44b2006-01-15 00:13:15 +0000948 }else{
949 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000950 }
drh029b44b2006-01-15 00:13:15 +0000951 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000952 }
danielk1977441b09a2006-01-05 13:48:29 +0000953
954exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000955 return rc;
drhbbd42a62004-05-22 17:41:58 +0000956}
957
drh64b1bea2006-01-15 02:30:57 +0000958#ifdef SQLITE_DEBUG
959/*
960** Helper function for printing out trace information from debugging
961** binaries. This returns the string represetation of the supplied
962** integer lock-type.
963*/
964static const char *locktypeName(int locktype){
965 switch( locktype ){
966 case NO_LOCK: return "NONE";
967 case SHARED_LOCK: return "SHARED";
968 case RESERVED_LOCK: return "RESERVED";
969 case PENDING_LOCK: return "PENDING";
970 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
971 }
972 return "ERROR";
973}
974#endif
975
drhbbd42a62004-05-22 17:41:58 +0000976/*
drh029b44b2006-01-15 00:13:15 +0000977** If we are currently in a different thread than the thread that the
978** unixFile argument belongs to, then transfer ownership of the unixFile
979** over to the current thread.
980**
981** A unixFile is only owned by a thread on systems where one thread is
982** unable to override locks created by a different thread. RedHat9 is
983** an example of such a system.
984**
985** Ownership transfer is only allowed if the unixFile is currently unlocked.
986** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000987** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000988*/
drhd677b3d2007-08-20 22:48:41 +0000989#if SQLITE_THREADSAFE
drh029b44b2006-01-15 00:13:15 +0000990static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000991 int rc;
drh029b44b2006-01-15 00:13:15 +0000992 pthread_t hSelf;
993 if( threadsOverrideEachOthersLocks ){
994 /* Ownership transfers not needed on this system */
995 return SQLITE_OK;
996 }
997 hSelf = pthread_self();
998 if( pthread_equal(pFile->tid, hSelf) ){
999 /* We are still in the same thread */
drh4f0c5872007-03-26 22:05:01 +00001000 OSTRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +00001001 return SQLITE_OK;
1002 }
1003 if( pFile->locktype!=NO_LOCK ){
1004 /* We cannot change ownership while we are holding a lock! */
1005 return SQLITE_MISUSE;
1006 }
drh4f0c5872007-03-26 22:05:01 +00001007 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1008 pFile->h, pFile->tid, hSelf);
drh029b44b2006-01-15 00:13:15 +00001009 pFile->tid = hSelf;
drhbfe66312006-10-03 17:40:40 +00001010 if (pFile->pLock != NULL) {
1011 releaseLockInfo(pFile->pLock);
chw97185482008-11-17 08:05:31 +00001012#if defined(__RTP__) || defined(_WRS_KERNEL)
1013 rc = findLockInfo(pFile->h, pFile->zRealpath, &pFile->pLock, 0);
1014#else
drhbfe66312006-10-03 17:40:40 +00001015 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
chw97185482008-11-17 08:05:31 +00001016#endif
drh4f0c5872007-03-26 22:05:01 +00001017 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00001018 locktypeName(pFile->locktype),
1019 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1020 return rc;
1021 } else {
1022 return SQLITE_OK;
1023 }
drh029b44b2006-01-15 00:13:15 +00001024}
1025#else
drhf1a221e2006-01-15 17:27:17 +00001026 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +00001027# define transferOwnership(X) SQLITE_OK
1028#endif
1029
1030/*
danielk19772a6bdf62007-08-20 16:07:00 +00001031** Seek to the offset passed as the second argument, then read cnt
1032** bytes into pBuf. Return the number of bytes actually read.
drh9e0ebbf2007-10-23 15:59:18 +00001033**
1034** NB: If you define USE_PREAD or USE_PREAD64, then it might also
1035** be necessary to define _XOPEN_SOURCE to be 500. This varies from
1036** one system to another. Since SQLite does not define USE_PREAD
1037** any any form by default, we will not attempt to define _XOPEN_SOURCE.
1038** See tickets #2741 and #2681.
drhb912b282006-03-23 22:42:20 +00001039*/
danielk197762079062007-08-15 17:08:46 +00001040static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +00001041 int got;
drh8ebf6702007-02-06 11:11:08 +00001042 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +00001043 TIMER_START;
drh8350a212007-03-22 15:22:06 +00001044#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +00001045 got = pread(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +00001046 SimulateIOError( got = -1 );
drh8350a212007-03-22 15:22:06 +00001047#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +00001048 got = pread64(id->h, pBuf, cnt, offset);
drhbb5f18d2007-04-06 18:23:17 +00001049 SimulateIOError( got = -1 );
drhb912b282006-03-23 22:42:20 +00001050#else
danielk197762079062007-08-15 17:08:46 +00001051 newOffset = lseek(id->h, offset, SEEK_SET);
drhbb5f18d2007-04-06 18:23:17 +00001052 SimulateIOError( newOffset-- );
danielk197762079062007-08-15 17:08:46 +00001053 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +00001054 return -1;
1055 }
drhb912b282006-03-23 22:42:20 +00001056 got = read(id->h, pBuf, cnt);
1057#endif
drh15d00c42007-02-27 02:01:14 +00001058 TIMER_END;
shane9bcbdad2008-05-29 20:22:37 +00001059 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +00001060 return got;
1061}
1062
1063/*
drhbbd42a62004-05-22 17:41:58 +00001064** Read data from a file into a buffer. Return SQLITE_OK if all
1065** bytes were read successfully and SQLITE_IOERR if anything goes
1066** wrong.
1067*/
danielk197762079062007-08-15 17:08:46 +00001068static int unixRead(
1069 sqlite3_file *id,
1070 void *pBuf,
1071 int amt,
1072 sqlite3_int64 offset
1073){
drhbbd42a62004-05-22 17:41:58 +00001074 int got;
drh9cbe6352005-11-29 03:13:21 +00001075 assert( id );
danielk197762079062007-08-15 17:08:46 +00001076 got = seekAndRead((unixFile*)id, offset, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +00001077 if( got==amt ){
1078 return SQLITE_OK;
drh4ac285a2006-09-15 07:28:50 +00001079 }else if( got<0 ){
1080 return SQLITE_IOERR_READ;
drhbbd42a62004-05-22 17:41:58 +00001081 }else{
drh4c17c3f2008-11-07 00:06:18 +00001082 /* Unread parts of the buffer must be zero-filled */
drhbafda092007-01-03 23:36:22 +00001083 memset(&((char*)pBuf)[got], 0, amt-got);
drh4ac285a2006-09-15 07:28:50 +00001084 return SQLITE_IOERR_SHORT_READ;
drhbbd42a62004-05-22 17:41:58 +00001085 }
1086}
1087
1088/*
drhb912b282006-03-23 22:42:20 +00001089** Seek to the offset in id->offset then read cnt bytes into pBuf.
1090** Return the number of bytes actually read. Update the offset.
1091*/
danielk197762079062007-08-15 17:08:46 +00001092static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
drhb912b282006-03-23 22:42:20 +00001093 int got;
drh8ebf6702007-02-06 11:11:08 +00001094 i64 newOffset;
drh15d00c42007-02-27 02:01:14 +00001095 TIMER_START;
drh8350a212007-03-22 15:22:06 +00001096#if defined(USE_PREAD)
danielk197762079062007-08-15 17:08:46 +00001097 got = pwrite(id->h, pBuf, cnt, offset);
drh8350a212007-03-22 15:22:06 +00001098#elif defined(USE_PREAD64)
danielk197762079062007-08-15 17:08:46 +00001099 got = pwrite64(id->h, pBuf, cnt, offset);
drhb912b282006-03-23 22:42:20 +00001100#else
danielk197762079062007-08-15 17:08:46 +00001101 newOffset = lseek(id->h, offset, SEEK_SET);
1102 if( newOffset!=offset ){
drh8ebf6702007-02-06 11:11:08 +00001103 return -1;
1104 }
drhb912b282006-03-23 22:42:20 +00001105 got = write(id->h, pBuf, cnt);
1106#endif
drh15d00c42007-02-27 02:01:14 +00001107 TIMER_END;
shane9bcbdad2008-05-29 20:22:37 +00001108 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
drhb912b282006-03-23 22:42:20 +00001109 return got;
1110}
1111
1112
1113/*
drhbbd42a62004-05-22 17:41:58 +00001114** Write data from a buffer into a file. Return SQLITE_OK on success
1115** or some other error code on failure.
1116*/
danielk197762079062007-08-15 17:08:46 +00001117static int unixWrite(
1118 sqlite3_file *id,
1119 const void *pBuf,
1120 int amt,
1121 sqlite3_int64 offset
1122){
drhbbd42a62004-05-22 17:41:58 +00001123 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +00001124 assert( id );
drh4c7f9412005-02-03 00:29:47 +00001125 assert( amt>0 );
danielk197762079062007-08-15 17:08:46 +00001126 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +00001127 amt -= wrote;
danielk197762079062007-08-15 17:08:46 +00001128 offset += wrote;
drhbbd42a62004-05-22 17:41:58 +00001129 pBuf = &((char*)pBuf)[wrote];
1130 }
drh59685932006-09-14 13:47:11 +00001131 SimulateIOError(( wrote=(-1), amt=1 ));
1132 SimulateDiskfullError(( wrote=0, amt=1 ));
drhbbd42a62004-05-22 17:41:58 +00001133 if( amt>0 ){
drh59685932006-09-14 13:47:11 +00001134 if( wrote<0 ){
drh4ac285a2006-09-15 07:28:50 +00001135 return SQLITE_IOERR_WRITE;
drh59685932006-09-14 13:47:11 +00001136 }else{
1137 return SQLITE_FULL;
1138 }
drhbbd42a62004-05-22 17:41:58 +00001139 }
1140 return SQLITE_OK;
1141}
1142
drhb851b2c2005-03-10 14:11:12 +00001143#ifdef SQLITE_TEST
1144/*
1145** Count the number of fullsyncs and normal syncs. This is used to test
1146** that syncs and fullsyncs are occuring at the right times.
1147*/
1148int sqlite3_sync_count = 0;
1149int sqlite3_fullsync_count = 0;
1150#endif
1151
drhf2f23912005-10-05 10:29:36 +00001152/*
1153** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
1154** Otherwise use fsync() in its place.
1155*/
1156#ifndef HAVE_FDATASYNC
1157# define fdatasync fsync
1158#endif
1159
drhac530b12006-02-11 01:25:50 +00001160/*
1161** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
1162** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
1163** only available on Mac OS X. But that could change.
1164*/
1165#ifdef F_FULLFSYNC
1166# define HAVE_FULLFSYNC 1
1167#else
1168# define HAVE_FULLFSYNC 0
1169#endif
1170
drhb851b2c2005-03-10 14:11:12 +00001171
drhbbd42a62004-05-22 17:41:58 +00001172/*
drhdd809b02004-07-17 21:44:57 +00001173** The fsync() system call does not work as advertised on many
1174** unix systems. The following procedure is an attempt to make
1175** it work better.
drh1398ad32005-01-19 23:24:50 +00001176**
1177** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
1178** for testing when we want to run through the test suite quickly.
1179** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
1180** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
1181** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +00001182*/
drheb796a72005-09-08 12:38:41 +00001183static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +00001184 int rc;
drhb851b2c2005-03-10 14:11:12 +00001185
1186 /* Record the number of times that we do a normal fsync() and
1187 ** FULLSYNC. This is used during testing to verify that this procedure
1188 ** gets called with the correct arguments.
1189 */
1190#ifdef SQLITE_TEST
1191 if( fullSync ) sqlite3_fullsync_count++;
1192 sqlite3_sync_count++;
1193#endif
1194
1195 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
1196 ** no-op
1197 */
1198#ifdef SQLITE_NO_SYNC
1199 rc = SQLITE_OK;
1200#else
1201
drhac530b12006-02-11 01:25:50 +00001202#if HAVE_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +00001203 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +00001204 rc = fcntl(fd, F_FULLFSYNC, 0);
aswiftae0943b2007-01-31 23:37:07 +00001205 }else{
1206 rc = 1;
1207 }
1208 /* If the FULLFSYNC failed, fall back to attempting an fsync().
1209 * It shouldn't be possible for fullfsync to fail on the local
1210 * file system (on OSX), so failure indicates that FULLFSYNC
1211 * isn't supported for this file system. So, attempt an fsync
1212 * and (for now) ignore the overhead of a superfluous fcntl call.
1213 * It'd be better to detect fullfsync support once and avoid
1214 * the fcntl call every time sync is called.
1215 */
1216 if( rc ) rc = fsync(fd);
1217
1218#else
drheb796a72005-09-08 12:38:41 +00001219 if( dataOnly ){
1220 rc = fdatasync(fd);
chw97185482008-11-17 08:05:31 +00001221#if defined(__RTP__) || defined(_WRS_KERNEL)
1222 if( rc==-1 && errno==ENOTSUP ){
1223 rc = fsync(fd);
1224 }
1225#endif
drhf2f23912005-10-05 10:29:36 +00001226 }else{
drheb796a72005-09-08 12:38:41 +00001227 rc = fsync(fd);
1228 }
aswiftae0943b2007-01-31 23:37:07 +00001229#endif /* HAVE_FULLFSYNC */
drhb851b2c2005-03-10 14:11:12 +00001230#endif /* defined(SQLITE_NO_SYNC) */
1231
chw97185482008-11-17 08:05:31 +00001232#if defined(__RTP__) || defined(_WRS_KERNEL)
1233 if( rc!= -1 ){
1234 rc = 0;
1235 }
1236#endif
1237
drhdd809b02004-07-17 21:44:57 +00001238 return rc;
1239}
1240
1241/*
drhbbd42a62004-05-22 17:41:58 +00001242** Make sure all writes to a particular file are committed to disk.
1243**
drheb796a72005-09-08 12:38:41 +00001244** If dataOnly==0 then both the file itself and its metadata (file
1245** size, access time, etc) are synced. If dataOnly!=0 then only the
1246** file data is synced.
1247**
drhbbd42a62004-05-22 17:41:58 +00001248** Under Unix, also make sure that the directory entry for the file
1249** has been created by fsync-ing the directory that contains the file.
1250** If we do not do this and we encounter a power failure, the directory
1251** entry for the journal might not exist after we reboot. The next
1252** SQLite to access the file will not know that the journal exists (because
1253** the directory entry for the journal was never created) and the transaction
1254** will not roll back - possibly leading to database corruption.
1255*/
danielk197790949c22007-08-17 16:50:38 +00001256static int unixSync(sqlite3_file *id, int flags){
drh59685932006-09-14 13:47:11 +00001257 int rc;
drh054889e2005-11-30 03:20:31 +00001258 unixFile *pFile = (unixFile*)id;
danielk197790949c22007-08-17 16:50:38 +00001259
danielk1977f036aef2007-08-20 05:36:51 +00001260 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
1261 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
1262
danielk1977c16d4632007-08-30 14:49:58 +00001263 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
danielk1977f036aef2007-08-20 05:36:51 +00001264 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
1265 || (flags&0x0F)==SQLITE_SYNC_FULL
danielk1977f036aef2007-08-20 05:36:51 +00001266 );
danielk197790949c22007-08-17 16:50:38 +00001267
danielk1977cd3b3c82008-09-22 11:46:32 +00001268 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
1269 ** line is to test that doing so does not cause any problems.
1270 */
1271 SimulateDiskfullError( return SQLITE_FULL );
1272
drh054889e2005-11-30 03:20:31 +00001273 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001274 OSTRACE2("SYNC %-3d\n", pFile->h);
danielk197790949c22007-08-17 16:50:38 +00001275 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
drh59685932006-09-14 13:47:11 +00001276 SimulateIOError( rc=1 );
1277 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001278 return SQLITE_IOERR_FSYNC;
drhbbd42a62004-05-22 17:41:58 +00001279 }
drh054889e2005-11-30 03:20:31 +00001280 if( pFile->dirfd>=0 ){
drh4f0c5872007-03-26 22:05:01 +00001281 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
danielk197790949c22007-08-17 16:50:38 +00001282 HAVE_FULLFSYNC, isFullsync);
danielk1977d7c03f72005-11-25 10:38:22 +00001283#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001284 /* The directory sync is only attempted if full_fsync is
1285 ** turned off or unavailable. If a full_fsync occurred above,
1286 ** then the directory sync is superfluous.
1287 */
danielk197790949c22007-08-17 16:50:38 +00001288 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
drhac530b12006-02-11 01:25:50 +00001289 /*
1290 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001291 ** errors when applied to directories on certain file systems.
1292 ** A failed directory sync is not a big deal. So it seems
1293 ** better to ignore the error. Ticket #1657
1294 */
1295 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001296 }
danielk1977d7c03f72005-11-25 10:38:22 +00001297#endif
drh054889e2005-11-30 03:20:31 +00001298 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1299 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001300 }
drha2854222004-06-17 19:04:17 +00001301 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001302}
1303
1304/*
1305** Truncate an open file to a specified size
1306*/
danielk197762079062007-08-15 17:08:46 +00001307static int unixTruncate(sqlite3_file *id, i64 nByte){
drh59685932006-09-14 13:47:11 +00001308 int rc;
drh9cbe6352005-11-29 03:13:21 +00001309 assert( id );
drh93aed5a2008-01-16 17:46:38 +00001310 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
drh63fff5f2007-06-19 10:50:38 +00001311 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
drh59685932006-09-14 13:47:11 +00001312 if( rc ){
drh4ac285a2006-09-15 07:28:50 +00001313 return SQLITE_IOERR_TRUNCATE;
drh59685932006-09-14 13:47:11 +00001314 }else{
1315 return SQLITE_OK;
1316 }
drhbbd42a62004-05-22 17:41:58 +00001317}
1318
1319/*
1320** Determine the current size of a file in bytes
1321*/
danielk197762079062007-08-15 17:08:46 +00001322static int unixFileSize(sqlite3_file *id, i64 *pSize){
drh59685932006-09-14 13:47:11 +00001323 int rc;
drhbbd42a62004-05-22 17:41:58 +00001324 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001325 assert( id );
drh59685932006-09-14 13:47:11 +00001326 rc = fstat(((unixFile*)id)->h, &buf);
1327 SimulateIOError( rc=1 );
1328 if( rc!=0 ){
drh4ac285a2006-09-15 07:28:50 +00001329 return SQLITE_IOERR_FSTAT;
drhbbd42a62004-05-22 17:41:58 +00001330 }
1331 *pSize = buf.st_size;
drh54626242008-07-30 17:28:04 +00001332
1333 /* When opening a zero-size database, the findLockInfo() procedure
1334 ** writes a single byte into that file in order to work around a bug
1335 ** in the OS-X msdos filesystem. In order to avoid problems with upper
1336 ** layers, we need to report this file size as zero even though it is
1337 ** really 1. Ticket #3260.
1338 */
1339 if( *pSize==1 ) *pSize = 0;
1340
1341
drhbbd42a62004-05-22 17:41:58 +00001342 return SQLITE_OK;
1343}
1344
danielk19779a1d0ab2004-06-01 14:09:28 +00001345/*
aswift5b1a2562008-08-22 00:22:35 +00001346** This routine translates a standard POSIX errno code into something
1347** useful to the clients of the sqlite3 functions. Specifically, it is
1348** intended to translate a variety of "try again" errors into SQLITE_BUSY
1349** and a variety of "please close the file descriptor NOW" errors into
1350** SQLITE_IOERR
1351**
1352** Errors during initialization of locks, or file system support for locks,
1353** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
1354*/
1355static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
1356 switch (posixError) {
1357 case 0:
1358 return SQLITE_OK;
1359
1360 case EAGAIN:
1361 case ETIMEDOUT:
1362 case EBUSY:
1363 case EINTR:
1364 case ENOLCK:
1365 /* random NFS retry error, unless during file system support
1366 * introspection, in which it actually means what it says */
1367 return SQLITE_BUSY;
1368
1369 case EACCES:
1370 /* EACCES is like EAGAIN during locking operations, but not any other time*/
1371 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
1372 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
1373 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
1374 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
1375 return SQLITE_BUSY;
1376 }
1377 /* else fall through */
1378 case EPERM:
1379 return SQLITE_PERM;
1380
1381 case EDEADLK:
1382 return SQLITE_IOERR_BLOCKED;
1383
drhf489c452008-08-22 00:47:53 +00001384#if EOPNOTSUPP!=ENOTSUP
aswift5b1a2562008-08-22 00:22:35 +00001385 case EOPNOTSUPP:
1386 /* something went terribly awry, unless during file system support
1387 * introspection, in which it actually means what it says */
drhf489c452008-08-22 00:47:53 +00001388#endif
danielk19775ad6a882008-09-15 04:20:31 +00001389#ifdef ENOTSUP
aswift5b1a2562008-08-22 00:22:35 +00001390 case ENOTSUP:
1391 /* invalid fd, unless during file system support introspection, in which
1392 * it actually means what it says */
danielk19775ad6a882008-09-15 04:20:31 +00001393#endif
aswift5b1a2562008-08-22 00:22:35 +00001394 case EIO:
1395 case EBADF:
1396 case EINVAL:
1397 case ENOTCONN:
1398 case ENODEV:
1399 case ENXIO:
1400 case ENOENT:
1401 case ESTALE:
1402 case ENOSYS:
1403 /* these should force the client to close the file and reconnect */
1404
1405 default:
1406 return sqliteIOErr;
1407 }
1408}
1409
1410/*
danielk197713adf8a2004-06-03 16:08:41 +00001411** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001412** file by this or any other process. If such a lock is held, set *pResOut
1413** to a non-zero value otherwise *pResOut is set to zero. The return value
1414** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001415*/
danielk1977861f7452008-06-05 11:39:11 +00001416static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001417 int rc = SQLITE_OK;
1418 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001419 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001420
danielk1977861f7452008-06-05 11:39:11 +00001421 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1422
drh054889e2005-11-30 03:20:31 +00001423 assert( pFile );
danielk1977b4b47412007-08-17 15:53:36 +00001424 enterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001425
1426 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001427 if( pFile->pLock->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001428 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001429 }
1430
drh2ac3ee92004-06-07 16:27:46 +00001431 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001432 */
aswift5b1a2562008-08-22 00:22:35 +00001433 if( !reserved ){
danielk197713adf8a2004-06-03 16:08:41 +00001434 struct flock lock;
1435 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001436 lock.l_start = RESERVED_BYTE;
1437 lock.l_len = 1;
1438 lock.l_type = F_WRLCK;
aswift5b1a2562008-08-22 00:22:35 +00001439 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1440 int tErrno = errno;
1441 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1442 pFile->lastErrno = tErrno;
1443 } else if( lock.l_type!=F_UNLCK ){
1444 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001445 }
1446 }
1447
danielk1977b4b47412007-08-17 15:53:36 +00001448 leaveMutex();
aswift5b1a2562008-08-22 00:22:35 +00001449 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
danielk197713adf8a2004-06-03 16:08:41 +00001450
aswift5b1a2562008-08-22 00:22:35 +00001451 *pResOut = reserved;
1452 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001453}
1454
1455/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001456** Lock the file with the lock specified by parameter locktype - one
1457** of the following:
1458**
drh2ac3ee92004-06-07 16:27:46 +00001459** (1) SHARED_LOCK
1460** (2) RESERVED_LOCK
1461** (3) PENDING_LOCK
1462** (4) EXCLUSIVE_LOCK
1463**
drhb3e04342004-06-08 00:47:47 +00001464** Sometimes when requesting one lock state, additional lock states
1465** are inserted in between. The locking might fail on one of the later
1466** transitions leaving the lock state different from what it started but
1467** still short of its goal. The following chart shows the allowed
1468** transitions and the inserted intermediate states:
1469**
1470** UNLOCKED -> SHARED
1471** SHARED -> RESERVED
1472** SHARED -> (PENDING) -> EXCLUSIVE
1473** RESERVED -> (PENDING) -> EXCLUSIVE
1474** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001475**
drha6abd042004-06-09 17:37:22 +00001476** This routine will only increase a lock. Use the sqlite3OsUnlock()
1477** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001478*/
danielk197762079062007-08-15 17:08:46 +00001479static int unixLock(sqlite3_file *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001480 /* The following describes the implementation of the various locks and
1481 ** lock transitions in terms of the POSIX advisory shared and exclusive
1482 ** lock primitives (called read-locks and write-locks below, to avoid
1483 ** confusion with SQLite lock names). The algorithms are complicated
1484 ** slightly in order to be compatible with windows systems simultaneously
1485 ** accessing the same database file, in case that is ever required.
1486 **
1487 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1488 ** byte', each single bytes at well known offsets, and the 'shared byte
1489 ** range', a range of 510 bytes at a well known offset.
1490 **
1491 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1492 ** byte'. If this is successful, a random byte from the 'shared byte
1493 ** range' is read-locked and the lock on the 'pending byte' released.
1494 **
danielk197790ba3bd2004-06-25 08:32:25 +00001495 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1496 ** A RESERVED lock is implemented by grabbing a write-lock on the
1497 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001498 **
1499 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001500 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1501 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1502 ** obtained, but existing SHARED locks are allowed to persist. A process
1503 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1504 ** This property is used by the algorithm for rolling back a journal file
1505 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001506 **
danielk197790ba3bd2004-06-25 08:32:25 +00001507 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1508 ** implemented by obtaining a write-lock on the entire 'shared byte
1509 ** range'. Since all other locks require a read-lock on one of the bytes
1510 ** within this range, this ensures that no other locks are held on the
1511 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001512 **
1513 ** The reason a single byte cannot be used instead of the 'shared byte
1514 ** range' is that some versions of windows do not support read-locks. By
1515 ** locking a random byte from a range, concurrent SHARED locks may exist
1516 ** even if the locking primitive used is always a write-lock.
1517 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001518 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001519 unixFile *pFile = (unixFile*)id;
1520 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001521 struct flock lock;
1522 int s;
1523
drh054889e2005-11-30 03:20:31 +00001524 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001525 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001526 locktypeName(locktype), locktypeName(pFile->locktype),
1527 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001528
1529 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001530 ** unixFile, do nothing. Don't use the end_lock: exit path, as
danielk1977b4b47412007-08-17 15:53:36 +00001531 ** enterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001532 */
drh054889e2005-11-30 03:20:31 +00001533 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00001534 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drh054889e2005-11-30 03:20:31 +00001535 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001536 return SQLITE_OK;
1537 }
1538
drhb3e04342004-06-08 00:47:47 +00001539 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001540 */
drh054889e2005-11-30 03:20:31 +00001541 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001542 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001543 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001544
drh054889e2005-11-30 03:20:31 +00001545 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001546 */
danielk1977b4b47412007-08-17 15:53:36 +00001547 enterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001548
drh029b44b2006-01-15 00:13:15 +00001549 /* Make sure the current thread owns the pFile.
1550 */
1551 rc = transferOwnership(pFile);
1552 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00001553 leaveMutex();
drh029b44b2006-01-15 00:13:15 +00001554 return rc;
1555 }
drh64b1bea2006-01-15 02:30:57 +00001556 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001557
danielk1977ad94b582007-08-20 06:44:22 +00001558 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001559 ** handle that precludes the requested lock, return BUSY.
1560 */
drh054889e2005-11-30 03:20:31 +00001561 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001562 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001563 ){
1564 rc = SQLITE_BUSY;
1565 goto end_lock;
1566 }
1567
1568 /* If a SHARED lock is requested, and some thread using this PID already
1569 ** has a SHARED or RESERVED lock, then increment reference counts and
1570 ** return SQLITE_OK.
1571 */
1572 if( locktype==SHARED_LOCK &&
1573 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1574 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001575 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001576 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001577 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001578 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001579 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001580 goto end_lock;
1581 }
1582
danielk197713adf8a2004-06-03 16:08:41 +00001583 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001584
danielk19779a1d0ab2004-06-01 14:09:28 +00001585 lock.l_whence = SEEK_SET;
1586
drh3cde3bb2004-06-12 02:17:14 +00001587 /* A PENDING lock is needed before acquiring a SHARED lock and before
1588 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1589 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001590 */
drh3cde3bb2004-06-12 02:17:14 +00001591 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001592 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001593 ){
danielk1977489468c2004-06-28 08:25:47 +00001594 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001595 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001596 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001597 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001598 int tErrno = errno;
1599 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1600 if( IS_LOCK_ERROR(rc) ){
1601 pFile->lastErrno = tErrno;
1602 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001603 goto end_lock;
1604 }
drh3cde3bb2004-06-12 02:17:14 +00001605 }
1606
1607
1608 /* If control gets to this point, then actually go ahead and make
1609 ** operating system calls for the specified lock.
1610 */
1611 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001612 int tErrno = 0;
drh3cde3bb2004-06-12 02:17:14 +00001613 assert( pLock->cnt==0 );
1614 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001615
drh2ac3ee92004-06-07 16:27:46 +00001616 /* Now get the read-lock */
1617 lock.l_start = SHARED_FIRST;
1618 lock.l_len = SHARED_SIZE;
aswift5b1a2562008-08-22 00:22:35 +00001619 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1620 tErrno = errno;
1621 }
drh2ac3ee92004-06-07 16:27:46 +00001622 /* Drop the temporary PENDING lock */
1623 lock.l_start = PENDING_BYTE;
1624 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001625 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001626 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
aswift5b1a2562008-08-22 00:22:35 +00001627 if( s != -1 ){
1628 /* This could happen with a network mount */
1629 tErrno = errno;
1630 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1631 if( IS_LOCK_ERROR(rc) ){
1632 pFile->lastErrno = tErrno;
1633 }
1634 goto end_lock;
1635 }
drh2b4b5962005-06-15 17:47:55 +00001636 }
drhe2396a12007-03-29 20:19:58 +00001637 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001638 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1639 if( IS_LOCK_ERROR(rc) ){
1640 pFile->lastErrno = tErrno;
1641 }
drhbbd42a62004-05-22 17:41:58 +00001642 }else{
drh054889e2005-11-30 03:20:31 +00001643 pFile->locktype = SHARED_LOCK;
1644 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001645 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001646 }
drh3cde3bb2004-06-12 02:17:14 +00001647 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1648 /* We are trying for an exclusive lock but another thread in this
1649 ** same process is still holding a shared lock. */
1650 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001651 }else{
drh3cde3bb2004-06-12 02:17:14 +00001652 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001653 ** assumed that there is a SHARED or greater lock on the file
1654 ** already.
1655 */
drh054889e2005-11-30 03:20:31 +00001656 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001657 lock.l_type = F_WRLCK;
1658 switch( locktype ){
1659 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001660 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001661 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001662 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001663 lock.l_start = SHARED_FIRST;
1664 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001665 break;
1666 default:
1667 assert(0);
1668 }
drh054889e2005-11-30 03:20:31 +00001669 s = fcntl(pFile->h, F_SETLK, &lock);
drhe2396a12007-03-29 20:19:58 +00001670 if( s==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001671 int tErrno = errno;
1672 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1673 if( IS_LOCK_ERROR(rc) ){
1674 pFile->lastErrno = tErrno;
1675 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001676 }
drhbbd42a62004-05-22 17:41:58 +00001677 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001678
danielk1977ecb2a962004-06-02 06:30:16 +00001679 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001680 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001681 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001682 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001683 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001684 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001685 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001686
1687end_lock:
danielk1977b4b47412007-08-17 15:53:36 +00001688 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00001689 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001690 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001691 return rc;
1692}
1693
1694/*
drh054889e2005-11-30 03:20:31 +00001695** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001696** must be either NO_LOCK or SHARED_LOCK.
1697**
1698** If the locking level of the file descriptor is already at or below
1699** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001700*/
danielk197762079062007-08-15 17:08:46 +00001701static int unixUnlock(sqlite3_file *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001702 struct lockInfo *pLock;
1703 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001704 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001705 unixFile *pFile = (unixFile*)id;
drh1aa5af12008-03-07 19:51:14 +00001706 int h;
drha6abd042004-06-09 17:37:22 +00001707
drh054889e2005-11-30 03:20:31 +00001708 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001709 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
drh054889e2005-11-30 03:20:31 +00001710 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001711
1712 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001713 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001714 return SQLITE_OK;
1715 }
drhf1a221e2006-01-15 17:27:17 +00001716 if( CHECK_THREADID(pFile) ){
1717 return SQLITE_MISUSE;
1718 }
danielk1977b4b47412007-08-17 15:53:36 +00001719 enterMutex();
drh1aa5af12008-03-07 19:51:14 +00001720 h = pFile->h;
drh054889e2005-11-30 03:20:31 +00001721 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001722 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001723 if( pFile->locktype>SHARED_LOCK ){
1724 assert( pLock->locktype==pFile->locktype );
drh1aa5af12008-03-07 19:51:14 +00001725 SimulateIOErrorBenign(1);
1726 SimulateIOError( h=(-1) )
1727 SimulateIOErrorBenign(0);
drh9c105bb2004-10-02 20:38:28 +00001728 if( locktype==SHARED_LOCK ){
1729 lock.l_type = F_RDLCK;
1730 lock.l_whence = SEEK_SET;
1731 lock.l_start = SHARED_FIRST;
1732 lock.l_len = SHARED_SIZE;
drh1aa5af12008-03-07 19:51:14 +00001733 if( fcntl(h, F_SETLK, &lock)==(-1) ){
aswift5b1a2562008-08-22 00:22:35 +00001734 int tErrno = errno;
1735 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1736 if( IS_LOCK_ERROR(rc) ){
1737 pFile->lastErrno = tErrno;
1738 }
1739 goto end_unlock;
drh9c105bb2004-10-02 20:38:28 +00001740 }
1741 }
drhbbd42a62004-05-22 17:41:58 +00001742 lock.l_type = F_UNLCK;
1743 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001744 lock.l_start = PENDING_BYTE;
1745 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh1aa5af12008-03-07 19:51:14 +00001746 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001747 pLock->locktype = SHARED_LOCK;
1748 }else{
aswift5b1a2562008-08-22 00:22:35 +00001749 int tErrno = errno;
1750 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1751 if( IS_LOCK_ERROR(rc) ){
1752 pFile->lastErrno = tErrno;
1753 }
1754 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001755 }
drhbbd42a62004-05-22 17:41:58 +00001756 }
drha6abd042004-06-09 17:37:22 +00001757 if( locktype==NO_LOCK ){
1758 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001759
drha6abd042004-06-09 17:37:22 +00001760 /* Decrement the shared lock counter. Release the lock using an
1761 ** OS call only when all threads in this same process have released
1762 ** the lock.
1763 */
1764 pLock->cnt--;
1765 if( pLock->cnt==0 ){
1766 lock.l_type = F_UNLCK;
1767 lock.l_whence = SEEK_SET;
1768 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001769 SimulateIOErrorBenign(1);
1770 SimulateIOError( h=(-1) )
1771 SimulateIOErrorBenign(0);
1772 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
drh2b4b5962005-06-15 17:47:55 +00001773 pLock->locktype = NO_LOCK;
1774 }else{
aswift5b1a2562008-08-22 00:22:35 +00001775 int tErrno = errno;
danielk19775ad6a882008-09-15 04:20:31 +00001776 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
aswift5b1a2562008-08-22 00:22:35 +00001777 if( IS_LOCK_ERROR(rc) ){
1778 pFile->lastErrno = tErrno;
1779 }
drh1aa5af12008-03-07 19:51:14 +00001780 pLock->cnt = 1;
aswift5b1a2562008-08-22 00:22:35 +00001781 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001782 }
drha6abd042004-06-09 17:37:22 +00001783 }
1784
drhbbd42a62004-05-22 17:41:58 +00001785 /* Decrement the count of locks against this same file. When the
1786 ** count reaches zero, close any other file descriptors whose close
1787 ** was deferred because of outstanding locks.
1788 */
drh1aa5af12008-03-07 19:51:14 +00001789 if( rc==SQLITE_OK ){
1790 pOpen = pFile->pOpen;
1791 pOpen->nLock--;
1792 assert( pOpen->nLock>=0 );
1793 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1794 int i;
1795 for(i=0; i<pOpen->nPending; i++){
1796 close(pOpen->aPending[i]);
1797 }
drhda0e7682008-07-30 15:27:54 +00001798 sqlite3_free(pOpen->aPending);
drh1aa5af12008-03-07 19:51:14 +00001799 pOpen->nPending = 0;
1800 pOpen->aPending = 0;
drhbbd42a62004-05-22 17:41:58 +00001801 }
drhbbd42a62004-05-22 17:41:58 +00001802 }
1803 }
aswift5b1a2562008-08-22 00:22:35 +00001804
1805end_unlock:
danielk1977b4b47412007-08-17 15:53:36 +00001806 leaveMutex();
drh1aa5af12008-03-07 19:51:14 +00001807 if( rc==SQLITE_OK ) pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001808 return rc;
drhbbd42a62004-05-22 17:41:58 +00001809}
1810
1811/*
danielk1977e339d652008-06-28 11:23:00 +00001812** This function performs the parts of the "close file" operation
1813** common to all locking schemes. It closes the directory and file
1814** handles, if they are valid, and sets all fields of the unixFile
1815** structure to 0.
1816*/
1817static int closeUnixFile(sqlite3_file *id){
1818 unixFile *pFile = (unixFile*)id;
1819 if( pFile ){
1820 if( pFile->dirfd>=0 ){
1821 close(pFile->dirfd);
1822 }
1823 if( pFile->h>=0 ){
1824 close(pFile->h);
1825 }
chw97185482008-11-17 08:05:31 +00001826#if defined(__RTP__) || defined(_WRS_KERNEL)
1827 if( pFile->isDelete && pFile->zRealpath ){
1828 unlink(pFile->zRealpath);
1829 }
1830 if( pFile->zRealpath ){
1831 HashElem *pElem;
1832 int n = strlen(pFile->zRealpath) + 1;
1833 pElem = sqlite3HashFindElem(&nameHash, pFile->zRealpath, n);
1834 if( pElem ){
1835 long cnt = (long)pElem->data;
1836 cnt--;
1837 if( cnt==0 ){
1838 sqlite3HashInsert(&nameHash, pFile->zRealpath, n, 0);
1839 }else{
1840 pElem->data = (void*)cnt;
1841 }
1842 }
1843 }
1844#endif
danielk1977e339d652008-06-28 11:23:00 +00001845 OSTRACE2("CLOSE %-3d\n", pFile->h);
1846 OpenCounter(-1);
1847 memset(pFile, 0, sizeof(unixFile));
1848 }
1849 return SQLITE_OK;
1850}
1851
1852/*
danielk1977e3026632004-06-22 11:29:02 +00001853** Close a file.
1854*/
danielk197762079062007-08-15 17:08:46 +00001855static int unixClose(sqlite3_file *id){
danielk1977e339d652008-06-28 11:23:00 +00001856 if( id ){
1857 unixFile *pFile = (unixFile *)id;
1858 unixUnlock(id, NO_LOCK);
1859 enterMutex();
danielk19776cb427f2008-06-30 10:16:04 +00001860 if( pFile->pOpen && pFile->pOpen->nLock ){
danielk1977e339d652008-06-28 11:23:00 +00001861 /* If there are outstanding locks, do not actually close the file just
1862 ** yet because that would clear those locks. Instead, add the file
1863 ** descriptor to pOpen->aPending. It will be automatically closed when
1864 ** the last lock is cleared.
1865 */
1866 int *aNew;
1867 struct openCnt *pOpen = pFile->pOpen;
drhda0e7682008-07-30 15:27:54 +00001868 aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e339d652008-06-28 11:23:00 +00001869 if( aNew==0 ){
1870 /* If a malloc fails, just leak the file descriptor */
1871 }else{
1872 pOpen->aPending = aNew;
1873 pOpen->aPending[pOpen->nPending] = pFile->h;
1874 pOpen->nPending++;
1875 pFile->h = -1;
1876 }
danielk1977e3026632004-06-22 11:29:02 +00001877 }
danielk1977e339d652008-06-28 11:23:00 +00001878 releaseLockInfo(pFile->pLock);
1879 releaseOpenCnt(pFile->pOpen);
1880 closeUnixFile(id);
1881 leaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001882 }
drh02afc862006-01-20 18:10:57 +00001883 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001884}
1885
drhbfe66312006-10-03 17:40:40 +00001886
drh40bbb0a2008-09-23 10:23:26 +00001887#if SQLITE_ENABLE_LOCKING_STYLE
chw97185482008-11-17 08:05:31 +00001888
1889#if !defined(__RTP__) && !defined(_WRS_KERNEL)
drhbfe66312006-10-03 17:40:40 +00001890#pragma mark AFP Support
1891
1892/*
1893 ** The afpLockingContext structure contains all afp lock specific state
1894 */
1895typedef struct afpLockingContext afpLockingContext;
1896struct afpLockingContext {
drh1aa5af12008-03-07 19:51:14 +00001897 unsigned long long sharedLockByte;
drh308aa322008-03-07 20:14:38 +00001898 const char *filePath;
drhbfe66312006-10-03 17:40:40 +00001899};
1900
1901struct ByteRangeLockPB2
1902{
1903 unsigned long long offset; /* offset to first byte to lock */
1904 unsigned long long length; /* nbr of bytes to lock */
1905 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
1906 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
1907 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
1908 int fd; /* file desc to assoc this lock with */
1909};
1910
drhfd131da2007-08-07 17:13:03 +00001911#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00001912
danielk1977ad94b582007-08-20 06:44:22 +00001913/*
aswift5b1a2562008-08-22 00:22:35 +00001914 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
1915 */
danielk1977ad94b582007-08-20 06:44:22 +00001916static int _AFPFSSetLock(
1917 const char *path,
aswift5b1a2562008-08-22 00:22:35 +00001918 unixFile *pFile,
danielk1977ad94b582007-08-20 06:44:22 +00001919 unsigned long long offset,
1920 unsigned long long length,
1921 int setLockFlag
1922){
drhfd131da2007-08-07 17:13:03 +00001923 struct ByteRangeLockPB2 pb;
drhbfe66312006-10-03 17:40:40 +00001924 int err;
1925
1926 pb.unLockFlag = setLockFlag ? 0 : 1;
1927 pb.startEndFlag = 0;
1928 pb.offset = offset;
1929 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00001930 pb.fd = pFile->h;
drh4f0c5872007-03-26 22:05:01 +00001931 OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
aswift5b1a2562008-08-22 00:22:35 +00001932 (setLockFlag?"ON":"OFF"), pFile->h, offset, length);
drhbfe66312006-10-03 17:40:40 +00001933 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
1934 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00001935 int rc;
1936 int tErrno = errno;
1937 OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, tErrno, strerror(tErrno));
1938 rc = sqliteErrorFromPosixError(tErrno, setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK); /* error */
1939 if( IS_LOCK_ERROR(rc) ){
1940 pFile->lastErrno = tErrno;
1941 }
1942 return rc;
drhbfe66312006-10-03 17:40:40 +00001943 } else {
aswift5b1a2562008-08-22 00:22:35 +00001944 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00001945 }
1946}
1947
aswift5b1a2562008-08-22 00:22:35 +00001948/* AFP-style reserved lock checking following the behavior of
1949** unixCheckReservedLock, see the unixCheckReservedLock function comments */
danielk1977e339d652008-06-28 11:23:00 +00001950static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001951 int rc = SQLITE_OK;
1952 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00001953 unixFile *pFile = (unixFile*)id;
1954
aswift5b1a2562008-08-22 00:22:35 +00001955 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1956
1957 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00001958 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
1959
1960 /* Check if a thread in this process holds such a lock */
1961 if( pFile->locktype>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001962 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00001963 }
1964
1965 /* Otherwise see if some other process holds it.
1966 */
aswift5b1a2562008-08-22 00:22:35 +00001967 if( !reserved ){
1968 /* lock the RESERVED byte */
1969 int lrc = _AFPFSSetLock(context->filePath, pFile, RESERVED_BYTE, 1,1);
1970 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00001971 /* if we succeeded in taking the reserved lock, unlock it to restore
1972 ** the original state */
aswift5b1a2562008-08-22 00:22:35 +00001973 lrc = _AFPFSSetLock(context->filePath, pFile, RESERVED_BYTE, 1, 0);
1974 } else {
1975 /* if we failed to get the lock then someone else must have it */
1976 reserved = 1;
1977 }
1978 if( IS_LOCK_ERROR(lrc) ){
1979 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00001980 }
1981 }
drhbfe66312006-10-03 17:40:40 +00001982
aswift5b1a2562008-08-22 00:22:35 +00001983 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
1984
1985 *pResOut = reserved;
1986 return rc;
drhbfe66312006-10-03 17:40:40 +00001987}
1988
1989/* AFP-style locking following the behavior of unixLock, see the unixLock
1990** function comments for details of lock management. */
danielk1977e339d652008-06-28 11:23:00 +00001991static int afpLock(sqlite3_file *id, int locktype){
drhbfe66312006-10-03 17:40:40 +00001992 int rc = SQLITE_OK;
1993 unixFile *pFile = (unixFile*)id;
1994 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00001995
1996 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00001997 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
drh339eb0b2008-03-07 15:34:11 +00001998 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
1999
drhbfe66312006-10-03 17:40:40 +00002000 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002001 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
2002 ** enterMutex() hasn't been called yet.
2003 */
drhbfe66312006-10-03 17:40:40 +00002004 if( pFile->locktype>=locktype ){
drh4f0c5872007-03-26 22:05:01 +00002005 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
drhbfe66312006-10-03 17:40:40 +00002006 locktypeName(locktype));
2007 return SQLITE_OK;
2008 }
2009
2010 /* Make sure the locking sequence is correct
drh339eb0b2008-03-07 15:34:11 +00002011 */
drhbfe66312006-10-03 17:40:40 +00002012 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2013 assert( locktype!=PENDING_LOCK );
2014 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2015
2016 /* This mutex is needed because pFile->pLock is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002017 */
danielk1977b4b47412007-08-17 15:53:36 +00002018 enterMutex();
drhbfe66312006-10-03 17:40:40 +00002019
2020 /* Make sure the current thread owns the pFile.
drh339eb0b2008-03-07 15:34:11 +00002021 */
drhbfe66312006-10-03 17:40:40 +00002022 rc = transferOwnership(pFile);
2023 if( rc!=SQLITE_OK ){
danielk1977b4b47412007-08-17 15:53:36 +00002024 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002025 return rc;
2026 }
2027
2028 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002029 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2030 ** be released.
2031 */
drhbfe66312006-10-03 17:40:40 +00002032 if( locktype==SHARED_LOCK
2033 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002034 ){
2035 int failed;
aswift5b1a2562008-08-22 00:22:35 +00002036 failed = _AFPFSSetLock(context->filePath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002037 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002038 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002039 goto afp_end_lock;
2040 }
2041 }
2042
2043 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002044 ** operating system calls for the specified lock.
2045 */
drhbfe66312006-10-03 17:40:40 +00002046 if( locktype==SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002047 int lk, lrc1, lrc2, lrc1Errno;
drhbfe66312006-10-03 17:40:40 +00002048
aswift5b1a2562008-08-22 00:22:35 +00002049 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002050 /* note that the quality of the randomness doesn't matter that much */
2051 lk = random();
2052 context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
aswift5b1a2562008-08-22 00:22:35 +00002053 lrc1 = _AFPFSSetLock(context->filePath, pFile,
2054 SHARED_FIRST+context->sharedLockByte, 1, 1);
2055 if( IS_LOCK_ERROR(lrc1) ){
2056 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002057 }
aswift5b1a2562008-08-22 00:22:35 +00002058 /* Drop the temporary PENDING lock */
2059 lrc2 = _AFPFSSetLock(context->filePath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002060
aswift5b1a2562008-08-22 00:22:35 +00002061 if( IS_LOCK_ERROR(lrc1) ) {
2062 pFile->lastErrno = lrc1Errno;
2063 rc = lrc1;
2064 goto afp_end_lock;
2065 } else if( IS_LOCK_ERROR(lrc2) ){
2066 rc = lrc2;
2067 goto afp_end_lock;
2068 } else if( lrc1 != SQLITE_OK ) {
2069 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002070 } else {
2071 pFile->locktype = SHARED_LOCK;
2072 }
2073 }else{
2074 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2075 ** assumed that there is a SHARED or greater lock on the file
2076 ** already.
2077 */
2078 int failed = 0;
2079 assert( 0!=pFile->locktype );
2080 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
2081 /* Acquire a RESERVED lock */
aswift5b1a2562008-08-22 00:22:35 +00002082 failed = _AFPFSSetLock(context->filePath, pFile, RESERVED_BYTE, 1,1);
drhbfe66312006-10-03 17:40:40 +00002083 }
2084 if (!failed && locktype == EXCLUSIVE_LOCK) {
2085 /* Acquire an EXCLUSIVE lock */
2086
2087 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002088 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002089 */
aswift5b1a2562008-08-22 00:22:35 +00002090 if (!(failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST +
2091 context->sharedLockByte, 1, 0))) {
drhbfe66312006-10-03 17:40:40 +00002092 /* now attemmpt to get the exclusive lock range */
aswift5b1a2562008-08-22 00:22:35 +00002093 failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002094 SHARED_SIZE, 1);
aswift5b1a2562008-08-22 00:22:35 +00002095 if (failed && (failed = _AFPFSSetLock(context->filePath, pFile,
2096 SHARED_FIRST + context->sharedLockByte, 1, 1))) {
2097 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002098 }
2099 } else {
aswift5b1a2562008-08-22 00:22:35 +00002100 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002101 }
2102 }
aswift5b1a2562008-08-22 00:22:35 +00002103 if( failed ){
2104 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002105 }
2106 }
2107
2108 if( rc==SQLITE_OK ){
2109 pFile->locktype = locktype;
2110 }else if( locktype==EXCLUSIVE_LOCK ){
2111 pFile->locktype = PENDING_LOCK;
2112 }
2113
2114afp_end_lock:
drh339eb0b2008-03-07 15:34:11 +00002115 leaveMutex();
drh4f0c5872007-03-26 22:05:01 +00002116 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
drhbfe66312006-10-03 17:40:40 +00002117 rc==SQLITE_OK ? "ok" : "failed");
2118 return rc;
2119}
2120
2121/*
drh339eb0b2008-03-07 15:34:11 +00002122** Lower the locking level on file descriptor pFile to locktype. locktype
2123** must be either NO_LOCK or SHARED_LOCK.
2124**
2125** If the locking level of the file descriptor is already at or below
2126** the requested locking level, this routine is a no-op.
2127*/
danielk1977e339d652008-06-28 11:23:00 +00002128static int afpUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002129 int rc = SQLITE_OK;
2130 unixFile *pFile = (unixFile*)id;
2131 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2132
2133 assert( pFile );
drh4f0c5872007-03-26 22:05:01 +00002134 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
drhbfe66312006-10-03 17:40:40 +00002135 pFile->locktype, getpid());
aswift5b1a2562008-08-22 00:22:35 +00002136
drhbfe66312006-10-03 17:40:40 +00002137 assert( locktype<=SHARED_LOCK );
2138 if( pFile->locktype<=locktype ){
2139 return SQLITE_OK;
2140 }
2141 if( CHECK_THREADID(pFile) ){
2142 return SQLITE_MISUSE;
2143 }
danielk1977b4b47412007-08-17 15:53:36 +00002144 enterMutex();
aswift5b1a2562008-08-22 00:22:35 +00002145 int failed = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002146 if( pFile->locktype>SHARED_LOCK ){
2147 if( locktype==SHARED_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002148
2149 /* unlock the exclusive range - then re-establish the shared lock */
2150 if (pFile->locktype==EXCLUSIVE_LOCK) {
aswift5b1a2562008-08-22 00:22:35 +00002151 failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002152 SHARED_SIZE, 0);
2153 if (!failed) {
2154 /* successfully removed the exclusive lock */
aswift5b1a2562008-08-22 00:22:35 +00002155 if ((failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST+
2156 context->sharedLockByte, 1, 1))) {
drhbfe66312006-10-03 17:40:40 +00002157 /* failed to re-establish our shared lock */
aswift5b1a2562008-08-22 00:22:35 +00002158 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002159 }
2160 } else {
aswift5b1a2562008-08-22 00:22:35 +00002161 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002162 }
2163 }
2164 }
2165 if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
aswift5b1a2562008-08-22 00:22:35 +00002166 if ((failed = _AFPFSSetLock(context->filePath, pFile,
2167 PENDING_BYTE, 1, 0))){
drhbfe66312006-10-03 17:40:40 +00002168 /* failed to release the pending lock */
aswift5b1a2562008-08-22 00:22:35 +00002169 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002170 }
2171 }
2172 if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
aswift5b1a2562008-08-22 00:22:35 +00002173 if ((failed = _AFPFSSetLock(context->filePath, pFile,
2174 RESERVED_BYTE, 1, 0))) {
drhbfe66312006-10-03 17:40:40 +00002175 /* failed to release the reserved lock */
aswift5b1a2562008-08-22 00:22:35 +00002176 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002177 }
2178 }
2179 }
2180 if( locktype==NO_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002181 int failed = _AFPFSSetLock(context->filePath, pFile,
drhbfe66312006-10-03 17:40:40 +00002182 SHARED_FIRST + context->sharedLockByte, 1, 0);
2183 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002184 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002185 }
2186 }
2187 if (rc == SQLITE_OK)
2188 pFile->locktype = locktype;
danielk1977b4b47412007-08-17 15:53:36 +00002189 leaveMutex();
drhbfe66312006-10-03 17:40:40 +00002190 return rc;
2191}
2192
2193/*
drh339eb0b2008-03-07 15:34:11 +00002194** Close a file & cleanup AFP specific locking context
2195*/
danielk1977e339d652008-06-28 11:23:00 +00002196static int afpClose(sqlite3_file *id) {
2197 if( id ){
2198 unixFile *pFile = (unixFile*)id;
2199 afpUnlock(id, NO_LOCK);
2200 sqlite3_free(pFile->lockingContext);
2201 }
2202 return closeUnixFile(id);
drhbfe66312006-10-03 17:40:40 +00002203}
2204
2205
2206#pragma mark flock() style locking
2207
2208/*
drh339eb0b2008-03-07 15:34:11 +00002209** The flockLockingContext is not used
2210*/
drhbfe66312006-10-03 17:40:40 +00002211typedef void flockLockingContext;
2212
aswift5b1a2562008-08-22 00:22:35 +00002213/* flock-style reserved lock checking following the behavior of
2214 ** unixCheckReservedLock, see the unixCheckReservedLock function comments */
danielk1977e339d652008-06-28 11:23:00 +00002215static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002216 int rc = SQLITE_OK;
2217 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002218 unixFile *pFile = (unixFile*)id;
2219
aswift5b1a2562008-08-22 00:22:35 +00002220 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2221
2222 assert( pFile );
2223
2224 /* Check if a thread in this process holds such a lock */
2225 if( pFile->locktype>SHARED_LOCK ){
2226 reserved = 1;
2227 }
2228
2229 /* Otherwise see if some other process holds it. */
2230 if( !reserved ){
drh3b62b2f2007-06-08 18:27:03 +00002231 /* attempt to get the lock */
aswift5b1a2562008-08-22 00:22:35 +00002232 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
2233 if( !lrc ){
drh3b62b2f2007-06-08 18:27:03 +00002234 /* got the lock, unlock it */
aswift5b1a2562008-08-22 00:22:35 +00002235 lrc = flock(pFile->h, LOCK_UN);
2236 if ( lrc ) {
2237 int tErrno = errno;
2238 /* unlock failed with an error */
2239 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2240 if( IS_LOCK_ERROR(lrc) ){
2241 pFile->lastErrno = tErrno;
2242 rc = lrc;
2243 }
2244 }
2245 } else {
2246 int tErrno = errno;
2247 reserved = 1;
2248 /* someone else might have it reserved */
2249 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2250 if( IS_LOCK_ERROR(lrc) ){
2251 pFile->lastErrno = tErrno;
2252 rc = lrc;
2253 }
drhbfe66312006-10-03 17:40:40 +00002254 }
drhbfe66312006-10-03 17:40:40 +00002255 }
aswift5b1a2562008-08-22 00:22:35 +00002256 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
danielk1977861f7452008-06-05 11:39:11 +00002257
aswift5b1a2562008-08-22 00:22:35 +00002258 *pResOut = reserved;
2259 return rc;
drhbfe66312006-10-03 17:40:40 +00002260}
2261
danielk1977e339d652008-06-28 11:23:00 +00002262static int flockLock(sqlite3_file *id, int locktype) {
aswift5b1a2562008-08-22 00:22:35 +00002263 int rc = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002264 unixFile *pFile = (unixFile*)id;
aswift5b1a2562008-08-22 00:22:35 +00002265
2266 assert( pFile );
2267
drh3b62b2f2007-06-08 18:27:03 +00002268 /* if we already have a lock, it is exclusive.
2269 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00002270 if (pFile->locktype > NO_LOCK) {
2271 pFile->locktype = locktype;
2272 return SQLITE_OK;
2273 }
2274
drh3b62b2f2007-06-08 18:27:03 +00002275 /* grab an exclusive lock */
aswift5b1a2562008-08-22 00:22:35 +00002276
2277 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
2278 int tErrno = errno;
drh3b62b2f2007-06-08 18:27:03 +00002279 /* didn't get, must be busy */
aswift5b1a2562008-08-22 00:22:35 +00002280 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2281 if( IS_LOCK_ERROR(rc) ){
2282 pFile->lastErrno = tErrno;
2283 }
drhbfe66312006-10-03 17:40:40 +00002284 } else {
drh3b62b2f2007-06-08 18:27:03 +00002285 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00002286 pFile->locktype = locktype;
drhbfe66312006-10-03 17:40:40 +00002287 }
aswift5b1a2562008-08-22 00:22:35 +00002288 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
2289 rc==SQLITE_OK ? "ok" : "failed");
2290 return rc;
drhbfe66312006-10-03 17:40:40 +00002291}
2292
danielk1977e339d652008-06-28 11:23:00 +00002293static int flockUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002294 unixFile *pFile = (unixFile*)id;
2295
aswift5b1a2562008-08-22 00:22:35 +00002296 assert( pFile );
2297 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2298 pFile->locktype, getpid());
drhbfe66312006-10-03 17:40:40 +00002299 assert( locktype<=SHARED_LOCK );
2300
drh3b62b2f2007-06-08 18:27:03 +00002301 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00002302 if( pFile->locktype==locktype ){
2303 return SQLITE_OK;
2304 }
2305
drh3b62b2f2007-06-08 18:27:03 +00002306 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00002307 if (locktype==SHARED_LOCK) {
2308 pFile->locktype = locktype;
2309 return SQLITE_OK;
2310 }
2311
drh3b62b2f2007-06-08 18:27:03 +00002312 /* no, really, unlock. */
drhbfe66312006-10-03 17:40:40 +00002313 int rc = flock(pFile->h, LOCK_UN);
aswift5b1a2562008-08-22 00:22:35 +00002314 if (rc) {
2315 int r, tErrno = errno;
2316 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2317 if( IS_LOCK_ERROR(r) ){
2318 pFile->lastErrno = tErrno;
2319 }
2320 return r;
2321 } else {
drhbfe66312006-10-03 17:40:40 +00002322 pFile->locktype = NO_LOCK;
2323 return SQLITE_OK;
2324 }
2325}
2326
2327/*
drh339eb0b2008-03-07 15:34:11 +00002328** Close a file.
2329*/
danielk1977e339d652008-06-28 11:23:00 +00002330static int flockClose(sqlite3_file *id) {
2331 if( id ){
2332 flockUnlock(id, NO_LOCK);
2333 }
2334 return closeUnixFile(id);
drhbfe66312006-10-03 17:40:40 +00002335}
2336
chw97185482008-11-17 08:05:31 +00002337#endif /* !defined(__RTP__) && !defined(_WRS_KERNEL) */
2338
drhbfe66312006-10-03 17:40:40 +00002339#pragma mark Old-School .lock file based locking
2340
aswift5b1a2562008-08-22 00:22:35 +00002341/* Dotlock-style reserved lock checking following the behavior of
2342** unixCheckReservedLock, see the unixCheckReservedLock function comments */
danielk1977e339d652008-06-28 11:23:00 +00002343static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
aswift5b1a2562008-08-22 00:22:35 +00002344 int rc = SQLITE_OK;
2345 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002346 unixFile *pFile = (unixFile*)id;
drh339eb0b2008-03-07 15:34:11 +00002347
aswift5b1a2562008-08-22 00:22:35 +00002348 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2349
2350 assert( pFile );
2351
2352 /* Check if a thread in this process holds such a lock */
2353 if( pFile->locktype>SHARED_LOCK ){
2354 reserved = 1;
2355 }
2356
2357 /* Otherwise see if some other process holds it. */
2358 if( !reserved ){
2359 char *zLockFile = (char *)pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002360 struct stat statBuf;
aswift5b1a2562008-08-22 00:22:35 +00002361
2362 if( lstat(zLockFile, &statBuf)==0 ){
2363 /* file exists, someone else has the lock */
2364 reserved = 1;
2365 }else{
drh3b62b2f2007-06-08 18:27:03 +00002366 /* file does not exist, we could have it if we want it */
chw97185482008-11-17 08:05:31 +00002367 int tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00002368 if( ENOENT != tErrno ){
2369 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2370 pFile->lastErrno = tErrno;
2371 }
drh339eb0b2008-03-07 15:34:11 +00002372 }
drhbfe66312006-10-03 17:40:40 +00002373 }
aswift5b1a2562008-08-22 00:22:35 +00002374 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
danielk1977861f7452008-06-05 11:39:11 +00002375
aswift5b1a2562008-08-22 00:22:35 +00002376 *pResOut = reserved;
2377 return rc;
drhbfe66312006-10-03 17:40:40 +00002378}
2379
danielk1977e339d652008-06-28 11:23:00 +00002380static int dotlockLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002381 unixFile *pFile = (unixFile*)id;
drh339eb0b2008-03-07 15:34:11 +00002382 int fd;
danielk1977e339d652008-06-28 11:23:00 +00002383 char *zLockFile = (char *)pFile->lockingContext;
aswift5b1a2562008-08-22 00:22:35 +00002384 int rc=SQLITE_OK;
drh339eb0b2008-03-07 15:34:11 +00002385
drh3b62b2f2007-06-08 18:27:03 +00002386 /* if we already have a lock, it is exclusive.
2387 ** Just adjust level and punt on outta here. */
drhbfe66312006-10-03 17:40:40 +00002388 if (pFile->locktype > NO_LOCK) {
2389 pFile->locktype = locktype;
chw97185482008-11-17 08:05:31 +00002390#if !defined(__RTP__) && !defined(_WRS_KERNEL)
drhbfe66312006-10-03 17:40:40 +00002391 /* Always update the timestamp on the old file */
danielk1977e339d652008-06-28 11:23:00 +00002392 utimes(zLockFile, NULL);
chw97185482008-11-17 08:05:31 +00002393#endif
aswift5b1a2562008-08-22 00:22:35 +00002394 rc = SQLITE_OK;
2395 goto dotlock_end_lock;
drhbfe66312006-10-03 17:40:40 +00002396 }
2397
drh3b62b2f2007-06-08 18:27:03 +00002398 /* check to see if lock file already exists */
drhbfe66312006-10-03 17:40:40 +00002399 struct stat statBuf;
danielk1977e339d652008-06-28 11:23:00 +00002400 if (lstat(zLockFile,&statBuf) == 0){
aswift5b1a2562008-08-22 00:22:35 +00002401 rc = SQLITE_BUSY; /* it does, busy */
2402 goto dotlock_end_lock;
drhbfe66312006-10-03 17:40:40 +00002403 }
2404
drh3b62b2f2007-06-08 18:27:03 +00002405 /* grab an exclusive lock */
danielk1977e339d652008-06-28 11:23:00 +00002406 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh339eb0b2008-03-07 15:34:11 +00002407 if( fd<0 ){
drh3b62b2f2007-06-08 18:27:03 +00002408 /* failed to open/create the file, someone else may have stolen the lock */
aswift5b1a2562008-08-22 00:22:35 +00002409 int tErrno = errno;
2410 if( EEXIST == tErrno ){
2411 rc = SQLITE_BUSY;
2412 } else {
2413 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2414 if( IS_LOCK_ERROR(rc) ){
2415 pFile->lastErrno = tErrno;
2416 }
2417 }
2418 goto dotlock_end_lock;
2419 }
drhbfe66312006-10-03 17:40:40 +00002420 close(fd);
2421
drh3b62b2f2007-06-08 18:27:03 +00002422 /* got it, set the type and return ok */
drhbfe66312006-10-03 17:40:40 +00002423 pFile->locktype = locktype;
aswift5b1a2562008-08-22 00:22:35 +00002424
2425 dotlock_end_lock:
2426 return rc;
drhbfe66312006-10-03 17:40:40 +00002427}
2428
danielk1977e339d652008-06-28 11:23:00 +00002429static int dotlockUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002430 unixFile *pFile = (unixFile*)id;
danielk1977e339d652008-06-28 11:23:00 +00002431 char *zLockFile = (char *)pFile->lockingContext;
drh339eb0b2008-03-07 15:34:11 +00002432
aswift5b1a2562008-08-22 00:22:35 +00002433 assert( pFile );
2434 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2435 pFile->locktype, getpid());
drhbfe66312006-10-03 17:40:40 +00002436 assert( locktype<=SHARED_LOCK );
2437
drh3b62b2f2007-06-08 18:27:03 +00002438 /* no-op if possible */
drhbfe66312006-10-03 17:40:40 +00002439 if( pFile->locktype==locktype ){
2440 return SQLITE_OK;
2441 }
2442
drh3b62b2f2007-06-08 18:27:03 +00002443 /* shared can just be set because we always have an exclusive */
drhbfe66312006-10-03 17:40:40 +00002444 if (locktype==SHARED_LOCK) {
2445 pFile->locktype = locktype;
2446 return SQLITE_OK;
2447 }
2448
drh3b62b2f2007-06-08 18:27:03 +00002449 /* no, really, unlock. */
aswift5b1a2562008-08-22 00:22:35 +00002450 if (unlink(zLockFile) ) {
2451 int rc, tErrno = errno;
2452 if( ENOENT != tErrno ){
2453 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2454 }
2455 if( IS_LOCK_ERROR(rc) ){
2456 pFile->lastErrno = tErrno;
2457 }
2458 return rc;
2459 }
drhbfe66312006-10-03 17:40:40 +00002460 pFile->locktype = NO_LOCK;
2461 return SQLITE_OK;
2462}
2463
2464/*
2465 ** Close a file.
2466 */
danielk1977e339d652008-06-28 11:23:00 +00002467static int dotlockClose(sqlite3_file *id) {
chw97185482008-11-17 08:05:31 +00002468#if defined(__RTP__) || defined(_WRS_KERNEL)
2469 int rc;
2470#endif
danielk1977e339d652008-06-28 11:23:00 +00002471 if( id ){
2472 unixFile *pFile = (unixFile*)id;
2473 dotlockUnlock(id, NO_LOCK);
2474 sqlite3_free(pFile->lockingContext);
2475 }
chw97185482008-11-17 08:05:31 +00002476#if defined(__RTP__) || defined(_WRS_KERNEL)
2477 enterMutex();
2478 rc = closeUnixFile(id);
2479 leaveMutex();
2480 return rc;
2481#else
danielk1977e339d652008-06-28 11:23:00 +00002482 return closeUnixFile(id);
chw97185482008-11-17 08:05:31 +00002483#endif
drhbfe66312006-10-03 17:40:40 +00002484}
2485
chw97185482008-11-17 08:05:31 +00002486#if defined(__RTP__) || defined(_WRS_KERNEL)
2487
2488#pragma mark POSIX/vxWorks named semaphore based locking
2489
2490/* Namedsem-style reserved lock checking following the behavior of
2491** unixCheckReservedLock, see the unixCheckReservedLock function comments */
2492static int namedsemCheckReservedLock(sqlite3_file *id, int *pResOut) {
2493 int rc = SQLITE_OK;
2494 int reserved = 0;
2495 unixFile *pFile = (unixFile*)id;
2496
2497 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2498
2499 assert( pFile );
2500
2501 /* Check if a thread in this process holds such a lock */
2502 if( pFile->locktype>SHARED_LOCK ){
2503 reserved = 1;
2504 }
2505
2506 /* Otherwise see if some other process holds it. */
2507 if( !reserved ){
2508 sem_t *pSem = pFile->pOpen->pSem;
2509 struct stat statBuf;
2510
2511 if( sem_trywait(pSem)==-1 ){
2512 int tErrno = errno;
2513 if( EAGAIN != tErrno ){
2514 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2515 pFile->lastErrno = tErrno;
2516 } else {
2517 /* someone else has the lock when we are in NO_LOCK */
2518 reserved = (pFile->locktype < SHARED_LOCK);
2519 }
2520 }else{
2521 /* we could have it if we want it */
2522 sem_post(pSem);
2523 }
2524 }
2525 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
2526
2527 *pResOut = reserved;
2528 return rc;
2529}
2530
2531static int namedsemLock(sqlite3_file *id, int locktype) {
2532 unixFile *pFile = (unixFile*)id;
2533 int fd;
2534 sem_t *pSem = pFile->pOpen->pSem;
2535 int rc = SQLITE_OK;
2536
2537 /* if we already have a lock, it is exclusive.
2538 ** Just adjust level and punt on outta here. */
2539 if (pFile->locktype > NO_LOCK) {
2540 pFile->locktype = locktype;
2541 rc = SQLITE_OK;
2542 goto namedsem_end_lock;
2543 }
2544
2545 /* lock semaphore now but bail out when already locked. */
2546 if( sem_trywait(pSem)==-1 ){
2547 rc = SQLITE_BUSY;
2548 goto namedsem_end_lock;
2549 }
2550
2551 /* got it, set the type and return ok */
2552 pFile->locktype = locktype;
2553
2554 namedsem_end_lock:
2555 return rc;
2556}
2557
2558static int namedsemUnlock(sqlite3_file *id, int locktype) {
2559 unixFile *pFile = (unixFile*)id;
2560 sem_t *pSem = pFile->pOpen->pSem;
2561
2562 assert( pFile );
2563 assert( pSem );
2564 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
2565 pFile->locktype, getpid());
2566 assert( locktype<=SHARED_LOCK );
2567
2568 /* no-op if possible */
2569 if( pFile->locktype==locktype ){
2570 return SQLITE_OK;
2571 }
2572
2573 /* shared can just be set because we always have an exclusive */
2574 if (locktype==SHARED_LOCK) {
2575 pFile->locktype = locktype;
2576 return SQLITE_OK;
2577 }
2578
2579 /* no, really unlock. */
2580 if ( sem_post(pSem)==-1 ) {
2581 int rc, tErrno = errno;
2582 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2583 if( IS_LOCK_ERROR(rc) ){
2584 pFile->lastErrno = tErrno;
2585 }
2586 return rc;
2587 }
2588 pFile->locktype = NO_LOCK;
2589 return SQLITE_OK;
2590}
2591
2592/*
2593 ** Close a file.
2594 */
2595static int namedsemClose(sqlite3_file *id) {
2596 if( id ){
2597 unixFile *pFile = (unixFile*)id;
2598 namedsemUnlock(id, NO_LOCK);
2599 assert( pFile );
2600 enterMutex();
2601 releaseLockInfo(pFile->pLock);
2602 releaseOpenCnt(pFile->pOpen);
2603 closeUnixFile(id);
2604 leaveMutex();
2605 }
2606 return SQLITE_OK;
2607}
2608
2609#endif /* defined(__RTP__) || defined(_WRS_KERNEL) */
drhbfe66312006-10-03 17:40:40 +00002610
drhda0e7682008-07-30 15:27:54 +00002611#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drhbfe66312006-10-03 17:40:40 +00002612
2613/*
drh339eb0b2008-03-07 15:34:11 +00002614** The nolockLockingContext is void
2615*/
drhbfe66312006-10-03 17:40:40 +00002616typedef void nolockLockingContext;
2617
danielk1977e339d652008-06-28 11:23:00 +00002618static int nolockCheckReservedLock(sqlite3_file *id, int *pResOut) {
danielk1977861f7452008-06-05 11:39:11 +00002619 *pResOut = 0;
2620 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002621}
2622
danielk1977e339d652008-06-28 11:23:00 +00002623static int nolockLock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002624 return SQLITE_OK;
2625}
2626
danielk1977e339d652008-06-28 11:23:00 +00002627static int nolockUnlock(sqlite3_file *id, int locktype) {
drhbfe66312006-10-03 17:40:40 +00002628 return SQLITE_OK;
2629}
2630
2631/*
drh339eb0b2008-03-07 15:34:11 +00002632** Close a file.
2633*/
danielk1977e339d652008-06-28 11:23:00 +00002634static int nolockClose(sqlite3_file *id) {
chw97185482008-11-17 08:05:31 +00002635#if defined(__RTP__) || defined(_WRS_KERNEL)
2636 int rc;
2637 enterMutex();
2638 rc = closeUnixFile(id);
2639 leaveMutex();
2640 return rc;
2641#else
danielk1977e339d652008-06-28 11:23:00 +00002642 return closeUnixFile(id);
chw97185482008-11-17 08:05:31 +00002643#endif
drhbfe66312006-10-03 17:40:40 +00002644}
2645
danielk1977ad94b582007-08-20 06:44:22 +00002646
danielk1977e3026632004-06-22 11:29:02 +00002647/*
drh9e33c2c2007-08-31 18:34:59 +00002648** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00002649*/
drhcc6bb3e2007-08-31 16:11:35 +00002650static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00002651 switch( op ){
2652 case SQLITE_FCNTL_LOCKSTATE: {
2653 *(int*)pArg = ((unixFile*)id)->locktype;
2654 return SQLITE_OK;
2655 }
2656 }
drhcc6bb3e2007-08-31 16:11:35 +00002657 return SQLITE_ERROR;
drh9cbe6352005-11-29 03:13:21 +00002658}
2659
2660/*
danielk1977a3d4c882007-03-23 10:08:38 +00002661** Return the sector size in bytes of the underlying block device for
2662** the specified file. This is almost always 512 bytes, but may be
2663** larger for some devices.
2664**
2665** SQLite code assumes this function cannot fail. It also assumes that
2666** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00002667** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00002668** same for both.
2669*/
danielk197762079062007-08-15 17:08:46 +00002670static int unixSectorSize(sqlite3_file *id){
drh3ceeb752007-03-29 18:19:52 +00002671 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00002672}
2673
danielk197790949c22007-08-17 16:50:38 +00002674/*
2675** Return the device characteristics for the file. This is always 0.
2676*/
danielk197762079062007-08-15 17:08:46 +00002677static int unixDeviceCharacteristics(sqlite3_file *id){
2678 return 0;
2679}
2680
danielk1977a3d4c882007-03-23 10:08:38 +00002681/*
danielk1977e339d652008-06-28 11:23:00 +00002682** Initialize the contents of the unixFile structure pointed to by pId.
2683**
danielk1977ad94b582007-08-20 06:44:22 +00002684** When locking extensions are enabled, the filepath and locking style
2685** are needed to determine the unixFile pMethod to use for locking operations.
2686** The locking-style specific lockingContext data structure is created
2687** and assigned here also.
2688*/
2689static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00002690 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00002691 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00002692 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00002693 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00002694 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00002695 int noLock, /* Omit locking if true */
2696 int isDelete /* Delete on close if true */
drhbfe66312006-10-03 17:40:40 +00002697){
drhda0e7682008-07-30 15:27:54 +00002698 int eLockingStyle;
2699 unixFile *pNew = (unixFile *)pId;
2700 int rc = SQLITE_OK;
2701
danielk1977e339d652008-06-28 11:23:00 +00002702 /* Macro to define the static contents of an sqlite3_io_methods
2703 ** structure for a unix backend file. Different locking methods
2704 ** require different functions for the xClose, xLock, xUnlock and
2705 ** xCheckReservedLock methods.
2706 */
2707 #define IOMETHODS(xClose, xLock, xUnlock, xCheckReservedLock) { \
2708 1, /* iVersion */ \
2709 xClose, /* xClose */ \
2710 unixRead, /* xRead */ \
2711 unixWrite, /* xWrite */ \
2712 unixTruncate, /* xTruncate */ \
2713 unixSync, /* xSync */ \
2714 unixFileSize, /* xFileSize */ \
2715 xLock, /* xLock */ \
2716 xUnlock, /* xUnlock */ \
2717 xCheckReservedLock, /* xCheckReservedLock */ \
2718 unixFileControl, /* xFileControl */ \
2719 unixSectorSize, /* xSectorSize */ \
2720 unixDeviceCharacteristics /* xDeviceCapabilities */ \
2721 }
2722 static sqlite3_io_methods aIoMethod[] = {
2723 IOMETHODS(unixClose, unixLock, unixUnlock, unixCheckReservedLock)
danielk1977e339d652008-06-28 11:23:00 +00002724 ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
drh40bbb0a2008-09-23 10:23:26 +00002725#if SQLITE_ENABLE_LOCKING_STYLE
drhda0e7682008-07-30 15:27:54 +00002726 ,IOMETHODS(dotlockClose, dotlockLock, dotlockUnlock,dotlockCheckReservedLock)
chw97185482008-11-17 08:05:31 +00002727#if defined(__RTP__) || defined(_WRS_KERNEL)
2728 ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
2729 ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
2730 ,IOMETHODS(namedsemClose, namedsemLock, namedsemUnlock, namedsemCheckReservedLock)
2731#else
drhda0e7682008-07-30 15:27:54 +00002732 ,IOMETHODS(flockClose, flockLock, flockUnlock, flockCheckReservedLock)
danielk1977e339d652008-06-28 11:23:00 +00002733 ,IOMETHODS(afpClose, afpLock, afpUnlock, afpCheckReservedLock)
chw97185482008-11-17 08:05:31 +00002734 ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
2735#endif
drh218c5082008-03-07 00:27:10 +00002736#endif
danielk1977e339d652008-06-28 11:23:00 +00002737 };
drhda0e7682008-07-30 15:27:54 +00002738 /* The order of the IOMETHODS macros above is important. It must be the
2739 ** same order as the LOCKING_STYLE numbers
2740 */
2741 assert(LOCKING_STYLE_POSIX==1);
2742 assert(LOCKING_STYLE_NONE==2);
2743 assert(LOCKING_STYLE_DOTFILE==3);
2744 assert(LOCKING_STYLE_FLOCK==4);
2745 assert(LOCKING_STYLE_AFP==5);
chw97185482008-11-17 08:05:31 +00002746 assert(LOCKING_STYLE_NAMEDSEM==6);
drh218c5082008-03-07 00:27:10 +00002747
danielk197717b90b52008-06-06 11:11:25 +00002748 assert( pNew->pLock==NULL );
2749 assert( pNew->pOpen==NULL );
drh218c5082008-03-07 00:27:10 +00002750
2751 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
danielk1977ad94b582007-08-20 06:44:22 +00002752 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00002753 pNew->dirfd = dirfd;
danielk1977ad94b582007-08-20 06:44:22 +00002754 SET_THREADID(pNew);
drh339eb0b2008-03-07 15:34:11 +00002755
chw97185482008-11-17 08:05:31 +00002756#if defined(__RTP__) || defined(_WRS_KERNEL)
2757 {
2758 HashElem *pElem;
2759 char *zRealname = vxrealpath(zFilename, 1);
2760 int n;
2761 pNew->zRealpath = 0;
2762 if( !zRealname ){
2763 rc = SQLITE_NOMEM;
2764 eLockingStyle = LOCKING_STYLE_NONE;
2765 }else{
2766 n = strlen(zRealname) + 1;
2767 enterMutex();
2768 pElem = sqlite3HashFindElem(&nameHash, zRealname, n);
2769 if( pElem ){
2770 long cnt = (long)pElem->data;
2771 cnt++;
2772 pNew->zRealpath = pElem->pKey;
2773 pElem->data = (void*)cnt;
2774 }else{
2775 if( sqlite3HashInsert(&nameHash, zRealname, n, (void*)1)==0 ){
2776 pElem = sqlite3HashFindElem(&nameHash, zRealname, n);
2777 if( pElem ){
2778 pNew->zRealpath = pElem->pKey;
2779 }else{
2780 sqlite3HashInsert(&nameHash, zRealname, n, 0);
2781 rc = SQLITE_NOMEM;
2782 eLockingStyle = LOCKING_STYLE_NONE;
2783 }
2784 }
2785 }
2786 leaveMutex();
2787 sqlite3_free(zRealname);
2788 }
2789 }
2790#endif
2791
drhda0e7682008-07-30 15:27:54 +00002792 if( noLock ){
2793 eLockingStyle = LOCKING_STYLE_NONE;
2794 }else{
2795 eLockingStyle = detectLockingStyle(pVfs, zFilename, h);
2796 }
danielk1977e339d652008-06-28 11:23:00 +00002797
2798 switch( eLockingStyle ){
2799
2800 case LOCKING_STYLE_POSIX: {
2801 enterMutex();
chw97185482008-11-17 08:05:31 +00002802#if defined(__RTP__) || defined(_WRS_KERNEL)
2803 rc = findLockInfo(h, pNew->zRealpath, &pNew->pLock, &pNew->pOpen);
2804#else
danielk1977e339d652008-06-28 11:23:00 +00002805 rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
chw97185482008-11-17 08:05:31 +00002806#endif
danielk1977e339d652008-06-28 11:23:00 +00002807 leaveMutex();
drh218c5082008-03-07 00:27:10 +00002808 break;
drhbfe66312006-10-03 17:40:40 +00002809 }
danielk1977e339d652008-06-28 11:23:00 +00002810
drh40bbb0a2008-09-23 10:23:26 +00002811#if SQLITE_ENABLE_LOCKING_STYLE
chw97185482008-11-17 08:05:31 +00002812
2813#if !defined(__RTP__) && !defined(_WRS_KERNEL)
danielk1977e339d652008-06-28 11:23:00 +00002814 case LOCKING_STYLE_AFP: {
2815 /* AFP locking uses the file path so it needs to be included in
2816 ** the afpLockingContext.
2817 */
2818 afpLockingContext *pCtx;
2819 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
2820 if( pCtx==0 ){
2821 rc = SQLITE_NOMEM;
2822 }else{
2823 /* NB: zFilename exists and remains valid until the file is closed
2824 ** according to requirement F11141. So we do not need to make a
2825 ** copy of the filename. */
2826 pCtx->filePath = zFilename;
2827 srandomdev();
2828 }
drh218c5082008-03-07 00:27:10 +00002829 break;
danielk1977e339d652008-06-28 11:23:00 +00002830 }
chw97185482008-11-17 08:05:31 +00002831#endif
danielk1977e339d652008-06-28 11:23:00 +00002832
2833 case LOCKING_STYLE_DOTFILE: {
2834 /* Dotfile locking uses the file path so it needs to be included in
2835 ** the dotlockLockingContext
2836 */
2837 char *zLockFile;
drh218c5082008-03-07 00:27:10 +00002838 int nFilename;
danielk1977e339d652008-06-28 11:23:00 +00002839 nFilename = strlen(zFilename) + 6;
2840 zLockFile = (char *)sqlite3_malloc(nFilename);
2841 if( zLockFile==0 ){
2842 rc = SQLITE_NOMEM;
2843 }else{
2844 sqlite3_snprintf(nFilename, zLockFile, "%s.lock", zFilename);
drh339eb0b2008-03-07 15:34:11 +00002845 }
danielk1977e339d652008-06-28 11:23:00 +00002846 pNew->lockingContext = zLockFile;
drh218c5082008-03-07 00:27:10 +00002847 break;
2848 }
danielk1977e339d652008-06-28 11:23:00 +00002849
chw97185482008-11-17 08:05:31 +00002850#if defined(__RTP__) || defined(_WRS_KERNEL)
2851 case LOCKING_STYLE_NAMEDSEM: {
2852 /* Named semaphore locking uses the file path so it needs to be
2853 ** included in the namedsemLockingContext
2854 */
2855 enterMutex();
2856 rc = findLockInfo(h, pNew->zRealpath, &pNew->pLock, &pNew->pOpen);
2857 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
2858 char *zSemName = pNew->pOpen->aSemName;
2859 int n;
2860 sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem", pNew->zRealpath);
2861 for( n=0; zSemName[n]; n++ )
2862 if( zSemName[n]=='/' ) zSemName[n] = '_';
2863 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
2864 if( pNew->pOpen->pSem == SEM_FAILED ){
2865 rc = SQLITE_NOMEM;
2866 pNew->pOpen->aSemName[0] = '\0';
2867 }
2868 }
2869 leaveMutex();
2870 break;
2871 }
2872#endif
2873
2874#if !defined(__RTP__) && !defined(_WRS_KERNEL)
danielk1977e339d652008-06-28 11:23:00 +00002875 case LOCKING_STYLE_FLOCK:
chw97185482008-11-17 08:05:31 +00002876#endif
danielk1977e339d652008-06-28 11:23:00 +00002877 case LOCKING_STYLE_NONE:
drh218c5082008-03-07 00:27:10 +00002878 break;
drhe78669b2007-06-29 12:04:26 +00002879#endif
danielk1977e339d652008-06-28 11:23:00 +00002880 }
aswift5b1a2562008-08-22 00:22:35 +00002881
2882 pNew->lastErrno = 0;
chw97185482008-11-17 08:05:31 +00002883#if defined(__RTP__) || defined(_WRS_KERNEL)
2884 if( rc!=SQLITE_OK ){
2885 unlink(zFilename);
2886 isDelete = 0;
2887 }
2888 pNew->isDelete = isDelete;
2889#endif
danielk1977e339d652008-06-28 11:23:00 +00002890 if( rc!=SQLITE_OK ){
danielk19777c055b92007-10-30 17:28:51 +00002891 if( dirfd>=0 ) close(dirfd);
drhbfe66312006-10-03 17:40:40 +00002892 close(h);
danielk1977e339d652008-06-28 11:23:00 +00002893 }else{
danielk19776cb427f2008-06-30 10:16:04 +00002894 pNew->pMethod = &aIoMethod[eLockingStyle-1];
danielk1977e339d652008-06-28 11:23:00 +00002895 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00002896 }
danielk1977e339d652008-06-28 11:23:00 +00002897 return rc;
drh054889e2005-11-30 03:20:31 +00002898}
drh9c06c952005-11-26 00:25:00 +00002899
danielk1977ad94b582007-08-20 06:44:22 +00002900/*
2901** Open a file descriptor to the directory containing file zFilename.
2902** If successful, *pFd is set to the opened file descriptor and
2903** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
2904** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
2905** value.
2906**
2907** If SQLITE_OK is returned, the caller is responsible for closing
2908** the file descriptor *pFd using close().
2909*/
danielk1977fee2d252007-08-18 10:59:19 +00002910static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00002911 int ii;
drh777b17a2007-09-20 10:02:54 +00002912 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00002913 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00002914
drh153c62c2007-08-24 03:51:33 +00002915 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
danielk1977fee2d252007-08-18 10:59:19 +00002916 for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
2917 if( ii>0 ){
2918 zDirname[ii] = '\0';
2919 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00002920 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00002921#ifdef FD_CLOEXEC
2922 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
2923#endif
2924 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
2925 }
2926 }
danielk1977fee2d252007-08-18 10:59:19 +00002927 *pFd = fd;
drh777b17a2007-09-20 10:02:54 +00002928 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
danielk1977fee2d252007-08-18 10:59:19 +00002929}
2930
danielk1977b4b47412007-08-17 15:53:36 +00002931/*
danielk197717b90b52008-06-06 11:11:25 +00002932** Create a temporary file name in zBuf. zBuf must be allocated
2933** by the calling process and must be big enough to hold at least
2934** pVfs->mxPathname bytes.
2935*/
2936static int getTempname(int nBuf, char *zBuf){
2937 static const char *azDirs[] = {
2938 0,
2939 "/var/tmp",
2940 "/usr/tmp",
2941 "/tmp",
2942 ".",
2943 };
2944 static const unsigned char zChars[] =
2945 "abcdefghijklmnopqrstuvwxyz"
2946 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2947 "0123456789";
2948 int i, j;
2949 struct stat buf;
2950 const char *zDir = ".";
2951
2952 /* It's odd to simulate an io-error here, but really this is just
2953 ** using the io-error infrastructure to test that SQLite handles this
2954 ** function failing.
2955 */
2956 SimulateIOError( return SQLITE_IOERR );
2957
2958 azDirs[0] = sqlite3_temp_directory;
2959 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
2960 if( azDirs[i]==0 ) continue;
2961 if( stat(azDirs[i], &buf) ) continue;
2962 if( !S_ISDIR(buf.st_mode) ) continue;
2963 if( access(azDirs[i], 07) ) continue;
2964 zDir = azDirs[i];
2965 break;
2966 }
2967
2968 /* Check that the output buffer is large enough for the temporary file
2969 ** name. If it is not, return SQLITE_ERROR.
2970 */
2971 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
2972 return SQLITE_ERROR;
2973 }
2974
2975 do{
2976 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
2977 j = strlen(zBuf);
2978 sqlite3_randomness(15, &zBuf[j]);
2979 for(i=0; i<15; i++, j++){
2980 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
2981 }
2982 zBuf[j] = 0;
2983 }while( access(zBuf,0)==0 );
2984 return SQLITE_OK;
2985}
2986
2987
2988/*
danielk1977ad94b582007-08-20 06:44:22 +00002989** Open the file zPath.
2990**
danielk1977b4b47412007-08-17 15:53:36 +00002991** Previously, the SQLite OS layer used three functions in place of this
2992** one:
2993**
2994** sqlite3OsOpenReadWrite();
2995** sqlite3OsOpenReadOnly();
2996** sqlite3OsOpenExclusive();
2997**
2998** These calls correspond to the following combinations of flags:
2999**
3000** ReadWrite() -> (READWRITE | CREATE)
3001** ReadOnly() -> (READONLY)
3002** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
3003**
3004** The old OpenExclusive() accepted a boolean argument - "delFlag". If
3005** true, the file was configured to be automatically deleted when the
3006** file handle closed. To achieve the same effect using this new
3007** interface, add the DELETEONCLOSE flag to those specified above for
3008** OpenExclusive().
3009*/
3010static int unixOpen(
drh153c62c2007-08-24 03:51:33 +00003011 sqlite3_vfs *pVfs,
danielk1977b4b47412007-08-17 15:53:36 +00003012 const char *zPath,
3013 sqlite3_file *pFile,
3014 int flags,
3015 int *pOutFlags
3016){
danielk1977fee2d252007-08-18 10:59:19 +00003017 int fd = 0; /* File descriptor returned by open() */
3018 int dirfd = -1; /* Directory file descriptor */
3019 int oflags = 0; /* Flags to pass to open() */
3020 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00003021 int noLock; /* True to omit locking primitives */
danielk1977b4b47412007-08-17 15:53:36 +00003022
3023 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
3024 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
3025 int isCreate = (flags & SQLITE_OPEN_CREATE);
3026 int isReadonly = (flags & SQLITE_OPEN_READONLY);
3027 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
3028
danielk1977fee2d252007-08-18 10:59:19 +00003029 /* If creating a master or main-file journal, this function will open
3030 ** a file-descriptor on the directory too. The first time unixSync()
3031 ** is called the directory file descriptor will be fsync()ed and close()d.
3032 */
3033 int isOpenDirectory = (isCreate &&
3034 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
3035 );
3036
danielk197717b90b52008-06-06 11:11:25 +00003037 /* If argument zPath is a NULL pointer, this function is required to open
3038 ** a temporary file. Use this buffer to store the file name in.
3039 */
3040 char zTmpname[MAX_PATHNAME+1];
3041 const char *zName = zPath;
3042
danielk1977fee2d252007-08-18 10:59:19 +00003043 /* Check the following statements are true:
3044 **
3045 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
3046 ** (b) if CREATE is set, then READWRITE must also be set, and
3047 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00003048 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00003049 */
danielk1977b4b47412007-08-17 15:53:36 +00003050 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00003051 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00003052 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00003053 assert(isDelete==0 || isCreate);
3054
drh33f4e022007-09-03 15:19:34 +00003055 /* The main DB, main journal, and master journal are never automatically
3056 ** deleted
3057 */
3058 assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
3059 assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
3060 assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
danielk1977b4b47412007-08-17 15:53:36 +00003061
danielk1977fee2d252007-08-18 10:59:19 +00003062 /* Assert that the upper layer has set one of the "file-type" flags. */
3063 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
3064 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3065 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
drh33f4e022007-09-03 15:19:34 +00003066 || eType==SQLITE_OPEN_TRANSIENT_DB
danielk1977fee2d252007-08-18 10:59:19 +00003067 );
3068
danielk1977e339d652008-06-28 11:23:00 +00003069 memset(pFile, 0, sizeof(unixFile));
3070
danielk197717b90b52008-06-06 11:11:25 +00003071 if( !zName ){
3072 int rc;
3073 assert(isDelete && !isOpenDirectory);
3074 rc = getTempname(MAX_PATHNAME+1, zTmpname);
3075 if( rc!=SQLITE_OK ){
3076 return rc;
3077 }
3078 zName = zTmpname;
3079 }
3080
danielk1977b4b47412007-08-17 15:53:36 +00003081 if( isReadonly ) oflags |= O_RDONLY;
3082 if( isReadWrite ) oflags |= O_RDWR;
3083 if( isCreate ) oflags |= O_CREAT;
3084 if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
3085 oflags |= (O_LARGEFILE|O_BINARY);
3086
danielk197717b90b52008-06-06 11:11:25 +00003087 fd = open(zName, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
chw97185482008-11-17 08:05:31 +00003088 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, oflags);
danielk19772f2d8c72007-08-30 16:13:33 +00003089 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
danielk1977b4b47412007-08-17 15:53:36 +00003090 /* Failed to open the file for read/write access. Try read-only. */
3091 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3092 flags |= SQLITE_OPEN_READONLY;
drh153c62c2007-08-24 03:51:33 +00003093 return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
danielk1977b4b47412007-08-17 15:53:36 +00003094 }
3095 if( fd<0 ){
3096 return SQLITE_CANTOPEN;
3097 }
3098 if( isDelete ){
chw97185482008-11-17 08:05:31 +00003099#if defined(__RTP__) || defined(_WRS_KERNEL)
3100 zPath = zName;
3101#else
danielk197717b90b52008-06-06 11:11:25 +00003102 unlink(zName);
chw97185482008-11-17 08:05:31 +00003103#endif
danielk1977b4b47412007-08-17 15:53:36 +00003104 }
3105 if( pOutFlags ){
3106 *pOutFlags = flags;
3107 }
3108
3109 assert(fd!=0);
danielk1977fee2d252007-08-18 10:59:19 +00003110 if( isOpenDirectory ){
3111 int rc = openDirectory(zPath, &dirfd);
3112 if( rc!=SQLITE_OK ){
3113 close(fd);
3114 return rc;
3115 }
3116 }
danielk1977e339d652008-06-28 11:23:00 +00003117
3118#ifdef FD_CLOEXEC
3119 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3120#endif
3121
drhda0e7682008-07-30 15:27:54 +00003122 noLock = eType!=SQLITE_OPEN_MAIN_DB;
chw97185482008-11-17 08:05:31 +00003123 return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
danielk1977b4b47412007-08-17 15:53:36 +00003124}
3125
3126/*
danielk1977fee2d252007-08-18 10:59:19 +00003127** Delete the file at zPath. If the dirSync argument is true, fsync()
3128** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00003129*/
drh153c62c2007-08-24 03:51:33 +00003130static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
danielk1977fee2d252007-08-18 10:59:19 +00003131 int rc = SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003132 SimulateIOError(return SQLITE_IOERR_DELETE);
3133 unlink(zPath);
danielk1977d39fa702008-10-16 13:27:40 +00003134#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00003135 if( dirSync ){
3136 int fd;
3137 rc = openDirectory(zPath, &fd);
3138 if( rc==SQLITE_OK ){
chw97185482008-11-17 08:05:31 +00003139#if defined(__RTP__) || defined(_WRS_KERNEL)
3140 if( fsync(fd)==-1 )
3141#else
3142 if( fsync(fd) )
3143#endif
3144 {
danielk1977fee2d252007-08-18 10:59:19 +00003145 rc = SQLITE_IOERR_DIR_FSYNC;
3146 }
3147 close(fd);
3148 }
3149 }
danielk1977d138dd82008-10-15 16:02:48 +00003150#endif
danielk1977fee2d252007-08-18 10:59:19 +00003151 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00003152}
3153
danielk197790949c22007-08-17 16:50:38 +00003154/*
3155** Test the existance of or access permissions of file zPath. The
3156** test performed depends on the value of flags:
3157**
3158** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
3159** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
3160** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
3161**
3162** Otherwise return 0.
3163*/
danielk1977861f7452008-06-05 11:39:11 +00003164static int unixAccess(
3165 sqlite3_vfs *pVfs,
3166 const char *zPath,
3167 int flags,
3168 int *pResOut
3169){
rse25c0d1a2007-09-20 08:38:14 +00003170 int amode = 0;
danielk1977861f7452008-06-05 11:39:11 +00003171 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00003172 switch( flags ){
3173 case SQLITE_ACCESS_EXISTS:
3174 amode = F_OK;
3175 break;
3176 case SQLITE_ACCESS_READWRITE:
3177 amode = W_OK|R_OK;
3178 break;
drh50d3f902007-08-27 21:10:36 +00003179 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00003180 amode = R_OK;
3181 break;
3182
3183 default:
3184 assert(!"Invalid flags argument");
3185 }
danielk1977861f7452008-06-05 11:39:11 +00003186 *pResOut = (access(zPath, amode)==0);
3187 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00003188}
3189
danielk1977b4b47412007-08-17 15:53:36 +00003190
3191/*
3192** Turn a relative pathname into a full pathname. The relative path
3193** is stored as a nul-terminated string in the buffer pointed to by
3194** zPath.
3195**
3196** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
3197** (in this case, MAX_PATHNAME bytes). The full-path is written to
3198** this buffer before returning.
3199*/
danielk1977adfb9b02007-09-17 07:02:56 +00003200static int unixFullPathname(
3201 sqlite3_vfs *pVfs, /* Pointer to vfs object */
3202 const char *zPath, /* Possibly relative input path */
3203 int nOut, /* Size of output buffer in bytes */
3204 char *zOut /* Output buffer */
3205){
danielk1977843e65f2007-09-01 16:16:15 +00003206
3207 /* It's odd to simulate an io-error here, but really this is just
3208 ** using the io-error infrastructure to test that SQLite handles this
3209 ** function failing. This function could fail if, for example, the
3210 ** current working directly has been unlinked.
3211 */
3212 SimulateIOError( return SQLITE_ERROR );
3213
drh153c62c2007-08-24 03:51:33 +00003214 assert( pVfs->mxPathname==MAX_PATHNAME );
chw97185482008-11-17 08:05:31 +00003215
3216#if defined(__RTP__) || defined(_WRS_KERNEL)
3217 {
3218 char *zRealname = vxrealpath(zPath, 0);
3219 zOut[0] = '\0';
3220 if( !zRealname ){
3221 return SQLITE_CANTOPEN;
3222 }
3223 sqlite3_snprintf(nOut, zOut, "%s", zRealname);
3224 sqlite3_free(zRealname);
3225 return SQLITE_OK;
3226 }
3227#else
drh3c7f2dc2007-12-06 13:26:20 +00003228 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00003229 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00003230 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003231 }else{
3232 int nCwd;
drh3c7f2dc2007-12-06 13:26:20 +00003233 if( getcwd(zOut, nOut-1)==0 ){
drh70c01452007-09-03 17:42:17 +00003234 return SQLITE_CANTOPEN;
danielk1977b4b47412007-08-17 15:53:36 +00003235 }
3236 nCwd = strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00003237 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00003238 }
3239 return SQLITE_OK;
3240
3241#if 0
3242 /*
3243 ** Remove "/./" path elements and convert "/A/./" path elements
3244 ** to just "/".
3245 */
3246 if( zFull ){
3247 int i, j;
3248 for(i=j=0; zFull[i]; i++){
3249 if( zFull[i]=='/' ){
3250 if( zFull[i+1]=='/' ) continue;
3251 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
3252 i += 1;
3253 continue;
3254 }
3255 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
3256 while( j>0 && zFull[j-1]!='/' ){ j--; }
3257 i += 3;
3258 continue;
3259 }
3260 }
3261 zFull[j++] = zFull[i];
3262 }
3263 zFull[j] = 0;
3264 }
3265#endif
chw97185482008-11-17 08:05:31 +00003266#endif
danielk1977b4b47412007-08-17 15:53:36 +00003267}
3268
drh0ccebe72005-06-07 22:22:50 +00003269
drh761df872006-12-21 01:29:22 +00003270#ifndef SQLITE_OMIT_LOAD_EXTENSION
3271/*
3272** Interfaces for opening a shared library, finding entry points
3273** within the shared library, and closing the shared library.
3274*/
3275#include <dlfcn.h>
drh153c62c2007-08-24 03:51:33 +00003276static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
drh761df872006-12-21 01:29:22 +00003277 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
3278}
danielk197795c8a542007-09-01 06:51:27 +00003279
3280/*
3281** SQLite calls this function immediately after a call to unixDlSym() or
3282** unixDlOpen() fails (returns a null pointer). If a more detailed error
3283** message is available, it is written to zBufOut. If no error message
3284** is available, zBufOut is left unmodified and SQLite uses a default
3285** error message.
3286*/
drh153c62c2007-08-24 03:51:33 +00003287static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
danielk1977b4b47412007-08-17 15:53:36 +00003288 char *zErr;
3289 enterMutex();
3290 zErr = dlerror();
3291 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00003292 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00003293 }
3294 leaveMutex();
3295}
drh46c99e02007-08-27 23:26:59 +00003296static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
drh761df872006-12-21 01:29:22 +00003297 return dlsym(pHandle, zSymbol);
3298}
drh46c99e02007-08-27 23:26:59 +00003299static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
danielk1977b4b47412007-08-17 15:53:36 +00003300 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00003301}
danielk1977b4b47412007-08-17 15:53:36 +00003302#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
3303 #define unixDlOpen 0
3304 #define unixDlError 0
3305 #define unixDlSym 0
3306 #define unixDlClose 0
3307#endif
3308
3309/*
danielk197790949c22007-08-17 16:50:38 +00003310** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00003311*/
drh153c62c2007-08-24 03:51:33 +00003312static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
danielk197790949c22007-08-17 16:50:38 +00003313
3314 assert(nBuf>=(sizeof(time_t)+sizeof(int)));
3315
drhbbd42a62004-05-22 17:41:58 +00003316 /* We have to initialize zBuf to prevent valgrind from reporting
3317 ** errors. The reports issued by valgrind are incorrect - we would
3318 ** prefer that the randomness be increased by making use of the
3319 ** uninitialized space in zBuf - but valgrind errors tend to worry
3320 ** some users. Rather than argue, it seems easier just to initialize
3321 ** the whole array and silence valgrind, even if that means less randomness
3322 ** in the random seed.
3323 **
3324 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00003325 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00003326 ** tests repeatable.
3327 */
danielk1977b4b47412007-08-17 15:53:36 +00003328 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00003329#if !defined(SQLITE_TEST)
3330 {
drh842b8642005-01-21 17:53:17 +00003331 int pid, fd;
3332 fd = open("/dev/urandom", O_RDONLY);
3333 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00003334 time_t t;
3335 time(&t);
danielk197790949c22007-08-17 16:50:38 +00003336 memcpy(zBuf, &t, sizeof(t));
3337 pid = getpid();
3338 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
drh72cbd072008-10-14 17:58:38 +00003339 assert( sizeof(t)+sizeof(pid)<=nBuf );
3340 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00003341 }else{
drh72cbd072008-10-14 17:58:38 +00003342 nBuf = read(fd, zBuf, nBuf);
drh842b8642005-01-21 17:53:17 +00003343 close(fd);
3344 }
drhbbd42a62004-05-22 17:41:58 +00003345 }
3346#endif
drh72cbd072008-10-14 17:58:38 +00003347 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00003348}
3349
danielk1977b4b47412007-08-17 15:53:36 +00003350
drhbbd42a62004-05-22 17:41:58 +00003351/*
3352** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00003353** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00003354** The return value is the number of microseconds of sleep actually
3355** requested from the underlying operating system, a number which
3356** might be greater than or equal to the argument, but not less
3357** than the argument.
drhbbd42a62004-05-22 17:41:58 +00003358*/
drh153c62c2007-08-24 03:51:33 +00003359static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
chw97185482008-11-17 08:05:31 +00003360#if defined(__RTP__) || defined(_WRS_KERNEL)
3361 struct timespec sp;
3362
3363 sp.tv_sec = microseconds / 1000000;
3364 sp.tv_nsec = (microseconds % 1000000) * 1000;
3365 nanosleep(&sp, NULL);
3366#else
drhbbd42a62004-05-22 17:41:58 +00003367#if defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00003368 usleep(microseconds);
3369 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00003370#else
danielk1977b4b47412007-08-17 15:53:36 +00003371 int seconds = (microseconds+999999)/1000000;
3372 sleep(seconds);
drh4a50aac2007-08-23 02:47:53 +00003373 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00003374#endif
chw97185482008-11-17 08:05:31 +00003375#endif
drh88f474a2006-01-02 20:00:12 +00003376}
3377
3378/*
drhbbd42a62004-05-22 17:41:58 +00003379** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00003380** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00003381*/
3382#ifdef SQLITE_TEST
3383int sqlite3_current_time = 0;
3384#endif
3385
3386/*
3387** Find the current time (in Universal Coordinated Time). Write the
3388** current time and date as a Julian Day number into *prNow and
3389** return 0. Return 1 if the time and date cannot be found.
3390*/
drh153c62c2007-08-24 03:51:33 +00003391static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
chw97185482008-11-17 08:05:31 +00003392#if defined(__RTP__) || defined(_WRS_KERNEL)
3393 struct timespec sNow;
3394 clock_gettime(CLOCK_REALTIME, &sNow);
3395 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
3396#else
drh19e2d372005-08-29 23:00:03 +00003397#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00003398 time_t t;
3399 time(&t);
3400 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00003401#else
3402 struct timeval sNow;
drhbdcc2762007-04-02 18:06:57 +00003403 gettimeofday(&sNow, 0);
drh19e2d372005-08-29 23:00:03 +00003404 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
3405#endif
chw97185482008-11-17 08:05:31 +00003406#endif
drhbbd42a62004-05-22 17:41:58 +00003407#ifdef SQLITE_TEST
3408 if( sqlite3_current_time ){
3409 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
3410 }
3411#endif
3412 return 0;
3413}
danielk1977b4b47412007-08-17 15:53:36 +00003414
danielk1977bcb97fe2008-06-06 15:49:29 +00003415static int unixGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
3416 return 0;
3417}
3418
drh153c62c2007-08-24 03:51:33 +00003419/*
danielk1977e339d652008-06-28 11:23:00 +00003420** Initialize the operating system interface.
drh153c62c2007-08-24 03:51:33 +00003421*/
danielk1977c0fa4c52008-06-25 17:19:00 +00003422int sqlite3_os_init(void){
danielk1977e339d652008-06-28 11:23:00 +00003423 /* Macro to define the static contents of an sqlite3_vfs structure for
3424 ** the unix backend. The two parameters are the values to use for
3425 ** the sqlite3_vfs.zName and sqlite3_vfs.pAppData fields, respectively.
3426 **
3427 */
3428 #define UNIXVFS(zVfsName, pVfsAppData) { \
3429 1, /* iVersion */ \
3430 sizeof(unixFile), /* szOsFile */ \
3431 MAX_PATHNAME, /* mxPathname */ \
3432 0, /* pNext */ \
3433 zVfsName, /* zName */ \
3434 (void *)pVfsAppData, /* pAppData */ \
3435 unixOpen, /* xOpen */ \
3436 unixDelete, /* xDelete */ \
3437 unixAccess, /* xAccess */ \
3438 unixFullPathname, /* xFullPathname */ \
3439 unixDlOpen, /* xDlOpen */ \
3440 unixDlError, /* xDlError */ \
3441 unixDlSym, /* xDlSym */ \
3442 unixDlClose, /* xDlClose */ \
3443 unixRandomness, /* xRandomness */ \
3444 unixSleep, /* xSleep */ \
3445 unixCurrentTime, /* xCurrentTime */ \
3446 unixGetLastError /* xGetLastError */ \
3447 }
3448
3449 static sqlite3_vfs unixVfs = UNIXVFS("unix", 0);
drh40bbb0a2008-09-23 10:23:26 +00003450#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977e339d652008-06-28 11:23:00 +00003451 int i;
3452 static sqlite3_vfs aVfs[] = {
3453 UNIXVFS("unix-posix", LOCKING_STYLE_POSIX),
3454 UNIXVFS("unix-afp", LOCKING_STYLE_AFP),
3455 UNIXVFS("unix-flock", LOCKING_STYLE_FLOCK),
3456 UNIXVFS("unix-dotfile", LOCKING_STYLE_DOTFILE),
chw97185482008-11-17 08:05:31 +00003457 UNIXVFS("unix-none", LOCKING_STYLE_NONE),
3458 UNIXVFS("unix-namedsem",LOCKING_STYLE_NAMEDSEM),
drh153c62c2007-08-24 03:51:33 +00003459 };
danielk1977e339d652008-06-28 11:23:00 +00003460 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
3461 sqlite3_vfs_register(&aVfs[i], 0);
3462 }
3463#endif
chw97185482008-11-17 08:05:31 +00003464#if defined(__RTP__) || defined(_WRS_KERNEL)
3465 sqlite3HashInit(&nameHash, 1);
3466#endif
danielk1977c0fa4c52008-06-25 17:19:00 +00003467 sqlite3_vfs_register(&unixVfs, 1);
3468 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00003469}
danielk1977e339d652008-06-28 11:23:00 +00003470
3471/*
3472** Shutdown the operating system interface. This is a no-op for unix.
3473*/
danielk1977c0fa4c52008-06-25 17:19:00 +00003474int sqlite3_os_end(void){
3475 return SQLITE_OK;
3476}
drhdce8bdb2007-08-16 13:01:44 +00003477
danielk197729bafea2008-06-26 10:41:19 +00003478#endif /* SQLITE_OS_UNIX */