blob: 9c361a17170609c51f4d6f6ff8d2d351c33549dc [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
13** This file contains code that is specific to Unix systems.
14*/
drhbbd42a62004-05-22 17:41:58 +000015#include "sqliteInt.h"
drheb206252004-10-01 02:00:31 +000016#include "os.h"
17#if OS_UNIX /* This file is used on unix only */
drhbbd42a62004-05-22 17:41:58 +000018
19
20#include <time.h>
21#include <errno.h>
22#include <unistd.h>
drh0ccebe72005-06-07 22:22:50 +000023
24/*
25** Do not include any of the File I/O interface procedures if the
26** SQLITE_OMIT_DISKIO macro is defined (indicating that there database
27** will be in-memory only)
28*/
29#ifndef SQLITE_OMIT_DISKIO
30
31
32/*
33** Define various macros that are missing from some systems.
34*/
drhbbd42a62004-05-22 17:41:58 +000035#ifndef O_LARGEFILE
36# define O_LARGEFILE 0
37#endif
38#ifdef SQLITE_DISABLE_LFS
39# undef O_LARGEFILE
40# define O_LARGEFILE 0
41#endif
42#ifndef O_NOFOLLOW
43# define O_NOFOLLOW 0
44#endif
45#ifndef O_BINARY
46# define O_BINARY 0
47#endif
48
49/*
50** The DJGPP compiler environment looks mostly like Unix, but it
51** lacks the fcntl() system call. So redefine fcntl() to be something
52** that always succeeds. This means that locking does not occur under
53** DJGPP. But its DOS - what did you expect?
54*/
55#ifdef __DJGPP__
56# define fcntl(A,B,C) 0
57#endif
58
59/*
60** Macros used to determine whether or not to use threads. The
61** SQLITE_UNIX_THREADS macro is defined if we are synchronizing for
62** Posix threads and SQLITE_W32_THREADS is defined if we are
63** synchronizing using Win32 threads.
64*/
65#if defined(THREADSAFE) && THREADSAFE
66# include <pthread.h>
67# define SQLITE_UNIX_THREADS 1
68#endif
69
70
71/*
72** Include code that is common to all os_*.c files
73*/
74#include "os_common.h"
75
drh0bb132b2004-07-20 14:06:51 +000076#if defined(THREADSAFE) && THREADSAFE && defined(__linux__)
danielk197713adf8a2004-06-03 16:08:41 +000077#define getpid pthread_self
78#endif
79
drhbbd42a62004-05-22 17:41:58 +000080/*
81** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
82** section 6.5.2.2 lines 483 through 490 specify that when a process
83** sets or clears a lock, that operation overrides any prior locks set
84** by the same process. It does not explicitly say so, but this implies
85** that it overrides locks set by the same process using a different
86** file descriptor. Consider this test case:
87**
88** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
89** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
90**
91** Suppose ./file1 and ./file2 are really the same file (because
92** one is a hard or symbolic link to the other) then if you set
93** an exclusive lock on fd1, then try to get an exclusive lock
94** on fd2, it works. I would have expected the second lock to
95** fail since there was already a lock on the file due to fd1.
96** But not so. Since both locks came from the same process, the
97** second overrides the first, even though they were on different
98** file descriptors opened on different file names.
99**
100** Bummer. If you ask me, this is broken. Badly broken. It means
101** that we cannot use POSIX locks to synchronize file access among
102** competing threads of the same process. POSIX locks will work fine
103** to synchronize access for threads in separate processes, but not
104** threads within the same process.
105**
106** To work around the problem, SQLite has to manage file locks internally
107** on its own. Whenever a new database is opened, we have to find the
108** specific inode of the database file (the inode is determined by the
109** st_dev and st_ino fields of the stat structure that fstat() fills in)
110** and check for locks already existing on that inode. When locks are
111** created or removed, we have to look at our own internal record of the
112** locks to see if another thread has previously set a lock on that same
113** inode.
114**
115** The OsFile structure for POSIX is no longer just an integer file
116** descriptor. It is now a structure that holds the integer file
117** descriptor and a pointer to a structure that describes the internal
118** locks on the corresponding inode. There is one locking structure
119** per inode, so if the same inode is opened twice, both OsFile structures
120** point to the same locking structure. The locking structure keeps
121** a reference count (so we will know when to delete it) and a "cnt"
122** field that tells us its internal lock status. cnt==0 means the
123** file is unlocked. cnt==-1 means the file has an exclusive lock.
124** cnt>0 means there are cnt shared locks on the file.
125**
126** Any attempt to lock or unlock a file first checks the locking
127** structure. The fcntl() system call is only invoked to set a
128** POSIX lock if the internal lock structure transitions between
129** a locked and an unlocked state.
130**
131** 2004-Jan-11:
132** More recent discoveries about POSIX advisory locks. (The more
133** I discover, the more I realize the a POSIX advisory locks are
134** an abomination.)
135**
136** If you close a file descriptor that points to a file that has locks,
137** all locks on that file that are owned by the current process are
138** released. To work around this problem, each OsFile structure contains
139** a pointer to an openCnt structure. There is one openCnt structure
140** per open inode, which means that multiple OsFiles can point to a single
141** openCnt. When an attempt is made to close an OsFile, if there are
142** other OsFiles open on the same inode that are holding locks, the call
143** to close() the file descriptor is deferred until all of the locks clear.
144** The openCnt structure keeps a list of file descriptors that need to
145** be closed and that list is walked (and cleared) when the last lock
146** clears.
147**
148** First, under Linux threads, because each thread has a separate
149** process ID, lock operations in one thread do not override locks
150** to the same file in other threads. Linux threads behave like
151** separate processes in this respect. But, if you close a file
152** descriptor in linux threads, all locks are cleared, even locks
153** on other threads and even though the other threads have different
154** process IDs. Linux threads is inconsistent in this respect.
155** (I'm beginning to think that linux threads is an abomination too.)
156** The consequence of this all is that the hash table for the lockInfo
157** structure has to include the process id as part of its key because
158** locks in different threads are treated as distinct. But the
159** openCnt structure should not include the process id in its
160** key because close() clears lock on all threads, not just the current
161** thread. Were it not for this goofiness in linux threads, we could
162** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000163**
164** 2004-Jun-28:
165** On some versions of linux, threads can override each others locks.
166** On others not. Sometimes you can change the behavior on the same
167** system by setting the LD_ASSUME_KERNEL environment variable. The
168** POSIX standard is silent as to which behavior is correct, as far
169** as I can tell, so other versions of unix might show the same
170** inconsistency. There is no little doubt in my mind that posix
171** advisory locks and linux threads are profoundly broken.
172**
173** To work around the inconsistencies, we have to test at runtime
174** whether or not threads can override each others locks. This test
175** is run once, the first time any lock is attempted. A static
176** variable is set to record the results of this test for future
177** use.
drhbbd42a62004-05-22 17:41:58 +0000178*/
179
180/*
181** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000182** to locate a particular lockInfo structure given its inode.
183**
184** If threads cannot override each others locks, then we set the
185** lockKey.tid field to the thread ID. If threads can override
186** each others locks then tid is always set to zero. tid is also
187** set to zero if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000188*/
189struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000190 dev_t dev; /* Device number */
191 ino_t ino; /* Inode number */
192#ifdef SQLITE_UNIX_THREADS
193 pthread_t tid; /* Thread ID or zero if threads cannot override each other */
194#endif
drhbbd42a62004-05-22 17:41:58 +0000195};
196
197/*
198** An instance of the following structure is allocated for each open
199** inode on each thread with a different process ID. (Threads have
200** different process IDs on linux, but not on most other unixes.)
201**
202** A single inode can have multiple file descriptors, so each OsFile
203** structure contains a pointer to an instance of this object and this
204** object keeps a count of the number of OsFiles pointing to it.
205*/
206struct lockInfo {
207 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000208 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000209 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000210 int nRef; /* Number of pointers to this structure */
211};
212
213/*
214** An instance of the following structure serves as the key used
215** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000216** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000217*/
218struct openKey {
219 dev_t dev; /* Device number */
220 ino_t ino; /* Inode number */
221};
222
223/*
224** An instance of the following structure is allocated for each open
225** inode. This structure keeps track of the number of locks on that
226** inode. If a close is attempted against an inode that is holding
227** locks, the close is deferred until all locks clear by adding the
228** file descriptor to be closed to the pending list.
229*/
230struct openCnt {
231 struct openKey key; /* The lookup key */
232 int nRef; /* Number of pointers to this structure */
233 int nLock; /* Number of outstanding locks */
234 int nPending; /* Number of pending close() operations */
235 int *aPending; /* Malloced space holding fd's awaiting a close() */
236};
237
238/*
239** These hash table maps inodes and process IDs into lockInfo and openCnt
240** structures. Access to these hash tables must be protected by a mutex.
241*/
242static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
243static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
244
drh5fdae772004-06-29 03:29:00 +0000245
246#ifdef SQLITE_UNIX_THREADS
247/*
248** This variable records whether or not threads can override each others
249** locks.
250**
251** 0: No. Threads cannot override each others locks.
252** 1: Yes. Threads can override each others locks.
253** -1: We don't know yet.
254*/
255static int threadsOverrideEachOthersLocks = -1;
256
257/*
258** This structure holds information passed into individual test
259** threads by the testThreadLockingBehavior() routine.
260*/
261struct threadTestData {
262 int fd; /* File to be locked */
263 struct flock lock; /* The locking operation */
264 int result; /* Result of the locking operation */
265};
266
267/*
268** The testThreadLockingBehavior() routine launches two separate
269** threads on this routine. This routine attempts to lock a file
270** descriptor then returns. The success or failure of that attempt
271** allows the testThreadLockingBehavior() procedure to determine
272** whether or not threads can override each others locks.
273*/
274static void *threadLockingTest(void *pArg){
275 struct threadTestData *pData = (struct threadTestData*)pArg;
276 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
277 return pArg;
278}
279
280/*
281** This procedure attempts to determine whether or not threads
282** can override each others locks then sets the
283** threadsOverrideEachOthersLocks variable appropriately.
284*/
285static void testThreadLockingBehavior(fd_orig){
286 int fd;
287 struct threadTestData d[2];
288 pthread_t t[2];
289
290 fd = dup(fd_orig);
291 if( fd<0 ) return;
292 memset(d, 0, sizeof(d));
293 d[0].fd = fd;
294 d[0].lock.l_type = F_RDLCK;
295 d[0].lock.l_len = 1;
296 d[0].lock.l_start = 0;
297 d[0].lock.l_whence = SEEK_SET;
298 d[1] = d[0];
299 d[1].lock.l_type = F_WRLCK;
300 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
301 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
302 pthread_join(t[0], 0);
303 pthread_join(t[1], 0);
304 close(fd);
305 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
306}
307#endif /* SQLITE_UNIX_THREADS */
308
drhbbd42a62004-05-22 17:41:58 +0000309/*
310** Release a lockInfo structure previously allocated by findLockInfo().
311*/
312static void releaseLockInfo(struct lockInfo *pLock){
313 pLock->nRef--;
314 if( pLock->nRef==0 ){
315 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
316 sqliteFree(pLock);
317 }
318}
319
320/*
321** Release a openCnt structure previously allocated by findLockInfo().
322*/
323static void releaseOpenCnt(struct openCnt *pOpen){
324 pOpen->nRef--;
325 if( pOpen->nRef==0 ){
326 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
327 sqliteFree(pOpen->aPending);
328 sqliteFree(pOpen);
329 }
330}
331
332/*
333** Given a file descriptor, locate lockInfo and openCnt structures that
334** describes that file descriptor. Create a new ones if necessary. The
335** return values might be unset if an error occurs.
336**
337** Return the number of errors.
338*/
drh38f82712004-06-18 17:10:16 +0000339static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000340 int fd, /* The file descriptor used in the key */
341 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000342 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000343){
344 int rc;
345 struct lockKey key1;
346 struct openKey key2;
347 struct stat statbuf;
348 struct lockInfo *pLock;
349 struct openCnt *pOpen;
350 rc = fstat(fd, &statbuf);
351 if( rc!=0 ) return 1;
352 memset(&key1, 0, sizeof(key1));
353 key1.dev = statbuf.st_dev;
354 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000355#ifdef SQLITE_UNIX_THREADS
356 if( threadsOverrideEachOthersLocks<0 ){
357 testThreadLockingBehavior(fd);
358 }
359 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
360#endif
drhbbd42a62004-05-22 17:41:58 +0000361 memset(&key2, 0, sizeof(key2));
362 key2.dev = statbuf.st_dev;
363 key2.ino = statbuf.st_ino;
364 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
365 if( pLock==0 ){
366 struct lockInfo *pOld;
367 pLock = sqliteMallocRaw( sizeof(*pLock) );
368 if( pLock==0 ) return 1;
369 pLock->key = key1;
370 pLock->nRef = 1;
371 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000372 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000373 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
374 if( pOld!=0 ){
375 assert( pOld==pLock );
376 sqliteFree(pLock);
377 return 1;
378 }
379 }else{
380 pLock->nRef++;
381 }
382 *ppLock = pLock;
383 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
384 if( pOpen==0 ){
385 struct openCnt *pOld;
386 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
387 if( pOpen==0 ){
388 releaseLockInfo(pLock);
389 return 1;
390 }
391 pOpen->key = key2;
392 pOpen->nRef = 1;
393 pOpen->nLock = 0;
394 pOpen->nPending = 0;
395 pOpen->aPending = 0;
396 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
397 if( pOld!=0 ){
398 assert( pOld==pOpen );
399 sqliteFree(pOpen);
400 releaseLockInfo(pLock);
401 return 1;
402 }
403 }else{
404 pOpen->nRef++;
405 }
406 *ppOpen = pOpen;
407 return 0;
408}
409
410/*
411** Delete the named file
412*/
413int sqlite3OsDelete(const char *zFilename){
414 unlink(zFilename);
415 return SQLITE_OK;
416}
417
418/*
419** Return TRUE if the named file exists.
420*/
421int sqlite3OsFileExists(const char *zFilename){
422 return access(zFilename, 0)==0;
423}
424
425/*
426** Attempt to open a file for both reading and writing. If that
427** fails, try opening it read-only. If the file does not exist,
428** try to create it.
429**
430** On success, a handle for the open file is written to *id
431** and *pReadonly is set to 0 if the file was opened for reading and
432** writing or 1 if the file was opened read-only. The function returns
433** SQLITE_OK.
434**
435** On failure, the function returns SQLITE_CANTOPEN and leaves
436** *id and *pReadonly unchanged.
437*/
438int sqlite3OsOpenReadWrite(
439 const char *zFilename,
440 OsFile *id,
441 int *pReadonly
442){
443 int rc;
drhda71ce12004-06-21 18:14:45 +0000444 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000445 id->dirfd = -1;
drh8e855772005-05-17 11:25:31 +0000446 id->h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
447 SQLITE_DEFAULT_FILE_PERMISSIONS);
drha6abd042004-06-09 17:37:22 +0000448 if( id->h<0 ){
drh6458e392004-07-20 01:14:13 +0000449#ifdef EISDIR
450 if( errno==EISDIR ){
451 return SQLITE_CANTOPEN;
452 }
453#endif
drha6abd042004-06-09 17:37:22 +0000454 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
455 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000456 return SQLITE_CANTOPEN;
457 }
458 *pReadonly = 1;
459 }else{
460 *pReadonly = 0;
461 }
462 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000463 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000464 sqlite3OsLeaveMutex();
465 if( rc ){
drha6abd042004-06-09 17:37:22 +0000466 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000467 return SQLITE_NOMEM;
468 }
danielk197713adf8a2004-06-03 16:08:41 +0000469 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000470 id->isOpen = 1;
drha6abd042004-06-09 17:37:22 +0000471 TRACE3("OPEN %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000472 OpenCounter(+1);
473 return SQLITE_OK;
474}
475
476
477/*
478** Attempt to open a new file for exclusive access by this process.
479** The file will be opened for both reading and writing. To avoid
480** a potential security problem, we do not allow the file to have
481** previously existed. Nor do we allow the file to be a symbolic
482** link.
483**
484** If delFlag is true, then make arrangements to automatically delete
485** the file when it is closed.
486**
487** On success, write the file handle into *id and return SQLITE_OK.
488**
489** On failure, return SQLITE_CANTOPEN.
490*/
491int sqlite3OsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){
492 int rc;
drhda71ce12004-06-21 18:14:45 +0000493 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000494 if( access(zFilename, 0)==0 ){
495 return SQLITE_CANTOPEN;
496 }
497 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000498 id->h = open(zFilename,
drhbbd42a62004-05-22 17:41:58 +0000499 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY, 0600);
drha6abd042004-06-09 17:37:22 +0000500 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000501 return SQLITE_CANTOPEN;
502 }
503 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000504 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000505 sqlite3OsLeaveMutex();
506 if( rc ){
drha6abd042004-06-09 17:37:22 +0000507 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000508 unlink(zFilename);
509 return SQLITE_NOMEM;
510 }
danielk197713adf8a2004-06-03 16:08:41 +0000511 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000512 id->isOpen = 1;
drhbbd42a62004-05-22 17:41:58 +0000513 if( delFlag ){
514 unlink(zFilename);
515 }
drha6abd042004-06-09 17:37:22 +0000516 TRACE3("OPEN-EX %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000517 OpenCounter(+1);
518 return SQLITE_OK;
519}
520
521/*
522** Attempt to open a new file for read-only access.
523**
524** On success, write the file handle into *id and return SQLITE_OK.
525**
526** On failure, return SQLITE_CANTOPEN.
527*/
528int sqlite3OsOpenReadOnly(const char *zFilename, OsFile *id){
529 int rc;
drhda71ce12004-06-21 18:14:45 +0000530 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000531 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000532 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
533 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000534 return SQLITE_CANTOPEN;
535 }
536 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000537 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000538 sqlite3OsLeaveMutex();
539 if( rc ){
drha6abd042004-06-09 17:37:22 +0000540 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000541 return SQLITE_NOMEM;
542 }
danielk197713adf8a2004-06-03 16:08:41 +0000543 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000544 id->isOpen = 1;
drha6abd042004-06-09 17:37:22 +0000545 TRACE3("OPEN-RO %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000546 OpenCounter(+1);
547 return SQLITE_OK;
548}
549
550/*
551** Attempt to open a file descriptor for the directory that contains a
552** file. This file descriptor can be used to fsync() the directory
553** in order to make sure the creation of a new file is actually written
554** to disk.
555**
556** This routine is only meaningful for Unix. It is a no-op under
557** windows since windows does not support hard links.
558**
559** On success, a handle for a previously open file is at *id is
560** updated with the new directory file descriptor and SQLITE_OK is
561** returned.
562**
563** On failure, the function returns SQLITE_CANTOPEN and leaves
564** *id unchanged.
565*/
566int sqlite3OsOpenDirectory(
567 const char *zDirname,
568 OsFile *id
569){
drhda71ce12004-06-21 18:14:45 +0000570 if( !id->isOpen ){
drhbbd42a62004-05-22 17:41:58 +0000571 /* Do not open the directory if the corresponding file is not already
572 ** open. */
573 return SQLITE_CANTOPEN;
574 }
575 assert( id->dirfd<0 );
drh8e855772005-05-17 11:25:31 +0000576 id->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
drhbbd42a62004-05-22 17:41:58 +0000577 if( id->dirfd<0 ){
578 return SQLITE_CANTOPEN;
579 }
580 TRACE3("OPENDIR %-3d %s\n", id->dirfd, zDirname);
581 return SQLITE_OK;
582}
583
584/*
drhab3f9fe2004-08-14 17:10:10 +0000585** If the following global variable points to a string which is the
586** name of a directory, then that directory will be used to store
587** temporary files.
588*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000589char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000590
591/*
drhbbd42a62004-05-22 17:41:58 +0000592** Create a temporary file name in zBuf. zBuf must be big enough to
593** hold at least SQLITE_TEMPNAME_SIZE characters.
594*/
595int sqlite3OsTempFileName(char *zBuf){
596 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000597 0,
drhbbd42a62004-05-22 17:41:58 +0000598 "/var/tmp",
599 "/usr/tmp",
600 "/tmp",
601 ".",
602 };
drh57196282004-10-06 15:41:16 +0000603 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000604 "abcdefghijklmnopqrstuvwxyz"
605 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
606 "0123456789";
607 int i, j;
608 struct stat buf;
609 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000610 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000611 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000612 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000613 if( stat(azDirs[i], &buf) ) continue;
614 if( !S_ISDIR(buf.st_mode) ) continue;
615 if( access(azDirs[i], 07) ) continue;
616 zDir = azDirs[i];
617 break;
618 }
619 do{
620 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
621 j = strlen(zBuf);
622 sqlite3Randomness(15, &zBuf[j]);
623 for(i=0; i<15; i++, j++){
624 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
625 }
626 zBuf[j] = 0;
627 }while( access(zBuf,0)==0 );
628 return SQLITE_OK;
629}
630
drh268283b2005-01-08 15:44:25 +0000631#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhbbd42a62004-05-22 17:41:58 +0000632/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000633** Check that a given pathname is a directory and is writable
634**
635*/
636int sqlite3OsIsDirWritable(char *zBuf){
637 struct stat buf;
638 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000639 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000640 if( stat(zBuf, &buf) ) return 0;
641 if( !S_ISDIR(buf.st_mode) ) return 0;
642 if( access(zBuf, 07) ) return 0;
643 return 1;
644}
drh268283b2005-01-08 15:44:25 +0000645#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000646
647/*
drhbbd42a62004-05-22 17:41:58 +0000648** Read data from a file into a buffer. Return SQLITE_OK if all
649** bytes were read successfully and SQLITE_IOERR if anything goes
650** wrong.
651*/
652int sqlite3OsRead(OsFile *id, void *pBuf, int amt){
653 int got;
drhda71ce12004-06-21 18:14:45 +0000654 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000655 SimulateIOError(SQLITE_IOERR);
656 TIMER_START;
drha6abd042004-06-09 17:37:22 +0000657 got = read(id->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000658 TIMER_END;
drhe29b9152005-03-18 14:03:15 +0000659 TRACE5("READ %-3d %5d %7d %d\n", id->h, got, last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000660 SEEK(0);
661 /* if( got<0 ) got = 0; */
662 if( got==amt ){
663 return SQLITE_OK;
664 }else{
665 return SQLITE_IOERR;
666 }
667}
668
669/*
670** Write data from a buffer into a file. Return SQLITE_OK on success
671** or some other error code on failure.
672*/
673int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
674 int wrote = 0;
drhda71ce12004-06-21 18:14:45 +0000675 assert( id->isOpen );
drh4c7f9412005-02-03 00:29:47 +0000676 assert( amt>0 );
drhbbd42a62004-05-22 17:41:58 +0000677 SimulateIOError(SQLITE_IOERR);
drh047d4832004-10-01 14:38:02 +0000678 SimulateDiskfullError;
drhbbd42a62004-05-22 17:41:58 +0000679 TIMER_START;
drha6abd042004-06-09 17:37:22 +0000680 while( amt>0 && (wrote = write(id->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000681 amt -= wrote;
682 pBuf = &((char*)pBuf)[wrote];
683 }
684 TIMER_END;
drhe29b9152005-03-18 14:03:15 +0000685 TRACE5("WRITE %-3d %5d %7d %d\n", id->h, wrote, last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000686 SEEK(0);
687 if( amt>0 ){
688 return SQLITE_FULL;
689 }
690 return SQLITE_OK;
691}
692
693/*
694** Move the read/write pointer in a file.
695*/
drheb206252004-10-01 02:00:31 +0000696int sqlite3OsSeek(OsFile *id, i64 offset){
drhda71ce12004-06-21 18:14:45 +0000697 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000698 SEEK(offset/1024 + 1);
drha6abd042004-06-09 17:37:22 +0000699 lseek(id->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000700 return SQLITE_OK;
701}
702
drhb851b2c2005-03-10 14:11:12 +0000703#ifdef SQLITE_TEST
704/*
705** Count the number of fullsyncs and normal syncs. This is used to test
706** that syncs and fullsyncs are occuring at the right times.
707*/
708int sqlite3_sync_count = 0;
709int sqlite3_fullsync_count = 0;
710#endif
711
712
drhbbd42a62004-05-22 17:41:58 +0000713/*
drhdd809b02004-07-17 21:44:57 +0000714** The fsync() system call does not work as advertised on many
715** unix systems. The following procedure is an attempt to make
716** it work better.
drh1398ad32005-01-19 23:24:50 +0000717**
718** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
719** for testing when we want to run through the test suite quickly.
720** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
721** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
722** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000723*/
drhb851b2c2005-03-10 14:11:12 +0000724static int full_fsync(int fd, int fullSync){
drhdd809b02004-07-17 21:44:57 +0000725 int rc;
drhb851b2c2005-03-10 14:11:12 +0000726
727 /* Record the number of times that we do a normal fsync() and
728 ** FULLSYNC. This is used during testing to verify that this procedure
729 ** gets called with the correct arguments.
730 */
731#ifdef SQLITE_TEST
732 if( fullSync ) sqlite3_fullsync_count++;
733 sqlite3_sync_count++;
734#endif
735
736 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
737 ** no-op
738 */
739#ifdef SQLITE_NO_SYNC
740 rc = SQLITE_OK;
741#else
742
drhdd809b02004-07-17 21:44:57 +0000743#ifdef F_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +0000744 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +0000745 rc = fcntl(fd, F_FULLFSYNC, 0);
drhb851b2c2005-03-10 14:11:12 +0000746 }else{
747 rc = 1;
748 }
749 /* If the FULLSYNC failed, try to do a normal fsync() */
drhdd809b02004-07-17 21:44:57 +0000750 if( rc ) rc = fsync(fd);
drhb851b2c2005-03-10 14:11:12 +0000751
drhdd809b02004-07-17 21:44:57 +0000752#else
753 rc = fsync(fd);
drhf30cc942005-03-11 17:52:34 +0000754#endif /* defined(F_FULLFSYNC) */
drhb851b2c2005-03-10 14:11:12 +0000755#endif /* defined(SQLITE_NO_SYNC) */
756
drhdd809b02004-07-17 21:44:57 +0000757 return rc;
758}
759
760/*
drhbbd42a62004-05-22 17:41:58 +0000761** Make sure all writes to a particular file are committed to disk.
762**
763** Under Unix, also make sure that the directory entry for the file
764** has been created by fsync-ing the directory that contains the file.
765** If we do not do this and we encounter a power failure, the directory
766** entry for the journal might not exist after we reboot. The next
767** SQLite to access the file will not know that the journal exists (because
768** the directory entry for the journal was never created) and the transaction
769** will not roll back - possibly leading to database corruption.
770*/
771int sqlite3OsSync(OsFile *id){
drhda71ce12004-06-21 18:14:45 +0000772 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000773 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000774 TRACE2("SYNC %-3d\n", id->h);
drhb851b2c2005-03-10 14:11:12 +0000775 if( full_fsync(id->h, id->fullSync) ){
drhbbd42a62004-05-22 17:41:58 +0000776 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000777 }
drha2854222004-06-17 19:04:17 +0000778 if( id->dirfd>=0 ){
779 TRACE2("DIRSYNC %-3d\n", id->dirfd);
drhb851b2c2005-03-10 14:11:12 +0000780 full_fsync(id->dirfd, id->fullSync);
drha2854222004-06-17 19:04:17 +0000781 close(id->dirfd); /* Only need to sync once, so close the directory */
782 id->dirfd = -1; /* when we are done. */
783 }
drha2854222004-06-17 19:04:17 +0000784 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +0000785}
786
787/*
danielk1977962398d2004-06-14 09:35:16 +0000788** Sync the directory zDirname. This is a no-op on operating systems other
789** than UNIX.
drhb851b2c2005-03-10 14:11:12 +0000790**
791** This is used to make sure the master journal file has truely been deleted
792** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +0000793** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +0000794*/
795int sqlite3OsSyncDirectory(const char *zDirname){
796 int fd;
797 int r;
danielk1977369f27e2004-06-15 11:40:04 +0000798 SimulateIOError(SQLITE_IOERR);
drh8e855772005-05-17 11:25:31 +0000799 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +0000800 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +0000801 if( fd<0 ){
802 return SQLITE_CANTOPEN;
803 }
804 r = fsync(fd);
805 close(fd);
806 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
807}
808
809/*
drhbbd42a62004-05-22 17:41:58 +0000810** Truncate an open file to a specified size
811*/
drheb206252004-10-01 02:00:31 +0000812int sqlite3OsTruncate(OsFile *id, i64 nByte){
drhda71ce12004-06-21 18:14:45 +0000813 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000814 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000815 return ftruncate(id->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000816}
817
818/*
819** Determine the current size of a file in bytes
820*/
drheb206252004-10-01 02:00:31 +0000821int sqlite3OsFileSize(OsFile *id, i64 *pSize){
drhbbd42a62004-05-22 17:41:58 +0000822 struct stat buf;
drhda71ce12004-06-21 18:14:45 +0000823 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000824 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000825 if( fstat(id->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +0000826 return SQLITE_IOERR;
827 }
828 *pSize = buf.st_size;
829 return SQLITE_OK;
830}
831
danielk19779a1d0ab2004-06-01 14:09:28 +0000832/*
danielk197713adf8a2004-06-03 16:08:41 +0000833** This routine checks if there is a RESERVED lock held on the specified
834** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +0000835** non-zero. If the file is unlocked or holds only SHARED locks, then
836** return zero.
danielk197713adf8a2004-06-03 16:08:41 +0000837*/
drha6abd042004-06-09 17:37:22 +0000838int sqlite3OsCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +0000839 int r = 0;
840
drhda71ce12004-06-21 18:14:45 +0000841 assert( id->isOpen );
drh2ac3ee92004-06-07 16:27:46 +0000842 sqlite3OsEnterMutex(); /* Needed because id->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000843
844 /* Check if a thread in this process holds such a lock */
845 if( id->pLock->locktype>SHARED_LOCK ){
846 r = 1;
847 }
848
drh2ac3ee92004-06-07 16:27:46 +0000849 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000850 */
851 if( !r ){
852 struct flock lock;
853 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000854 lock.l_start = RESERVED_BYTE;
855 lock.l_len = 1;
856 lock.l_type = F_WRLCK;
drha6abd042004-06-09 17:37:22 +0000857 fcntl(id->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +0000858 if( lock.l_type!=F_UNLCK ){
859 r = 1;
860 }
861 }
862
863 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +0000864 TRACE3("TEST WR-LOCK %d %d\n", id->h, r);
danielk197713adf8a2004-06-03 16:08:41 +0000865
866 return r;
867}
868
danielk19772b444852004-06-29 07:45:33 +0000869#ifdef SQLITE_DEBUG
870/*
871** Helper function for printing out trace information from debugging
872** binaries. This returns the string represetation of the supplied
873** integer lock-type.
874*/
875static const char * locktypeName(int locktype){
876 switch( locktype ){
877 case NO_LOCK: return "NONE";
878 case SHARED_LOCK: return "SHARED";
879 case RESERVED_LOCK: return "RESERVED";
880 case PENDING_LOCK: return "PENDING";
881 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
882 }
883 return "ERROR";
884}
885#endif
886
danielk197713adf8a2004-06-03 16:08:41 +0000887/*
danielk19779a1d0ab2004-06-01 14:09:28 +0000888** Lock the file with the lock specified by parameter locktype - one
889** of the following:
890**
drh2ac3ee92004-06-07 16:27:46 +0000891** (1) SHARED_LOCK
892** (2) RESERVED_LOCK
893** (3) PENDING_LOCK
894** (4) EXCLUSIVE_LOCK
895**
drhb3e04342004-06-08 00:47:47 +0000896** Sometimes when requesting one lock state, additional lock states
897** are inserted in between. The locking might fail on one of the later
898** transitions leaving the lock state different from what it started but
899** still short of its goal. The following chart shows the allowed
900** transitions and the inserted intermediate states:
901**
902** UNLOCKED -> SHARED
903** SHARED -> RESERVED
904** SHARED -> (PENDING) -> EXCLUSIVE
905** RESERVED -> (PENDING) -> EXCLUSIVE
906** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +0000907**
drha6abd042004-06-09 17:37:22 +0000908** This routine will only increase a lock. Use the sqlite3OsUnlock()
909** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +0000910*/
911int sqlite3OsLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +0000912 /* The following describes the implementation of the various locks and
913 ** lock transitions in terms of the POSIX advisory shared and exclusive
914 ** lock primitives (called read-locks and write-locks below, to avoid
915 ** confusion with SQLite lock names). The algorithms are complicated
916 ** slightly in order to be compatible with windows systems simultaneously
917 ** accessing the same database file, in case that is ever required.
918 **
919 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
920 ** byte', each single bytes at well known offsets, and the 'shared byte
921 ** range', a range of 510 bytes at a well known offset.
922 **
923 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
924 ** byte'. If this is successful, a random byte from the 'shared byte
925 ** range' is read-locked and the lock on the 'pending byte' released.
926 **
danielk197790ba3bd2004-06-25 08:32:25 +0000927 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
928 ** A RESERVED lock is implemented by grabbing a write-lock on the
929 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +0000930 **
931 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +0000932 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
933 ** on the 'pending byte'. This ensures that no new SHARED locks can be
934 ** obtained, but existing SHARED locks are allowed to persist. A process
935 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
936 ** This property is used by the algorithm for rolling back a journal file
937 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +0000938 **
danielk197790ba3bd2004-06-25 08:32:25 +0000939 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
940 ** implemented by obtaining a write-lock on the entire 'shared byte
941 ** range'. Since all other locks require a read-lock on one of the bytes
942 ** within this range, this ensures that no other locks are held on the
943 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +0000944 **
945 ** The reason a single byte cannot be used instead of the 'shared byte
946 ** range' is that some versions of windows do not support read-locks. By
947 ** locking a random byte from a range, concurrent SHARED locks may exist
948 ** even if the locking primitive used is always a write-lock.
949 */
danielk19779a1d0ab2004-06-01 14:09:28 +0000950 int rc = SQLITE_OK;
951 struct lockInfo *pLock = id->pLock;
952 struct flock lock;
953 int s;
954
drhda71ce12004-06-21 18:14:45 +0000955 assert( id->isOpen );
drhe29b9152005-03-18 14:03:15 +0000956 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", id->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +0000957 locktypeName(id->locktype), locktypeName(pLock->locktype), pLock->cnt
958 ,getpid() );
danielk19779a1d0ab2004-06-01 14:09:28 +0000959
960 /* If there is already a lock of this type or more restrictive on the
961 ** OsFile, do nothing. Don't use the end_lock: exit path, as
962 ** sqlite3OsEnterMutex() hasn't been called yet.
963 */
danielk197713adf8a2004-06-03 16:08:41 +0000964 if( id->locktype>=locktype ){
drhe29b9152005-03-18 14:03:15 +0000965 TRACE3("LOCK %d %s ok (already held)\n", id->h, locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +0000966 return SQLITE_OK;
967 }
968
drhb3e04342004-06-08 00:47:47 +0000969 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +0000970 */
drhb3e04342004-06-08 00:47:47 +0000971 assert( id->locktype!=NO_LOCK || locktype==SHARED_LOCK );
972 assert( locktype!=PENDING_LOCK );
973 assert( locktype!=RESERVED_LOCK || id->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +0000974
drhb3e04342004-06-08 00:47:47 +0000975 /* This mutex is needed because id->pLock is shared across threads
976 */
977 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +0000978
979 /* If some thread using this PID has a lock via a different OsFile*
980 ** handle that precludes the requested lock, return BUSY.
981 */
danielk197713adf8a2004-06-03 16:08:41 +0000982 if( (id->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +0000983 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +0000984 ){
985 rc = SQLITE_BUSY;
986 goto end_lock;
987 }
988
989 /* If a SHARED lock is requested, and some thread using this PID already
990 ** has a SHARED or RESERVED lock, then increment reference counts and
991 ** return SQLITE_OK.
992 */
993 if( locktype==SHARED_LOCK &&
994 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
995 assert( locktype==SHARED_LOCK );
danielk197713adf8a2004-06-03 16:08:41 +0000996 assert( id->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +0000997 assert( pLock->cnt>0 );
danielk197713adf8a2004-06-03 16:08:41 +0000998 id->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +0000999 pLock->cnt++;
1000 id->pOpen->nLock++;
1001 goto end_lock;
1002 }
1003
danielk197713adf8a2004-06-03 16:08:41 +00001004 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001005 lock.l_whence = SEEK_SET;
1006
drh3cde3bb2004-06-12 02:17:14 +00001007 /* A PENDING lock is needed before acquiring a SHARED lock and before
1008 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1009 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001010 */
drh3cde3bb2004-06-12 02:17:14 +00001011 if( locktype==SHARED_LOCK
1012 || (locktype==EXCLUSIVE_LOCK && id->locktype<PENDING_LOCK)
1013 ){
danielk1977489468c2004-06-28 08:25:47 +00001014 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001015 lock.l_start = PENDING_BYTE;
drha6abd042004-06-09 17:37:22 +00001016 s = fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001017 if( s ){
1018 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1019 goto end_lock;
1020 }
drh3cde3bb2004-06-12 02:17:14 +00001021 }
1022
1023
1024 /* If control gets to this point, then actually go ahead and make
1025 ** operating system calls for the specified lock.
1026 */
1027 if( locktype==SHARED_LOCK ){
1028 assert( pLock->cnt==0 );
1029 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001030
drh2ac3ee92004-06-07 16:27:46 +00001031 /* Now get the read-lock */
1032 lock.l_start = SHARED_FIRST;
1033 lock.l_len = SHARED_SIZE;
drha6abd042004-06-09 17:37:22 +00001034 s = fcntl(id->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001035
1036 /* Drop the temporary PENDING lock */
1037 lock.l_start = PENDING_BYTE;
1038 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001039 lock.l_type = F_UNLCK;
drha6abd042004-06-09 17:37:22 +00001040 fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001041 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001042 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1043 }else{
danielk197713adf8a2004-06-03 16:08:41 +00001044 id->locktype = SHARED_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001045 id->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001046 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001047 }
drh3cde3bb2004-06-12 02:17:14 +00001048 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1049 /* We are trying for an exclusive lock but another thread in this
1050 ** same process is still holding a shared lock. */
1051 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001052 }else{
drh3cde3bb2004-06-12 02:17:14 +00001053 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001054 ** assumed that there is a SHARED or greater lock on the file
1055 ** already.
1056 */
danielk197713adf8a2004-06-03 16:08:41 +00001057 assert( 0!=id->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001058 lock.l_type = F_WRLCK;
1059 switch( locktype ){
1060 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001061 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001062 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001063 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001064 lock.l_start = SHARED_FIRST;
1065 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001066 break;
1067 default:
1068 assert(0);
1069 }
drha6abd042004-06-09 17:37:22 +00001070 s = fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001071 if( s ){
1072 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1073 }
drhbbd42a62004-05-22 17:41:58 +00001074 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001075
danielk1977ecb2a962004-06-02 06:30:16 +00001076 if( rc==SQLITE_OK ){
danielk197713adf8a2004-06-03 16:08:41 +00001077 id->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001078 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001079 }else if( locktype==EXCLUSIVE_LOCK ){
1080 id->locktype = PENDING_LOCK;
1081 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001082 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001083
1084end_lock:
drhbbd42a62004-05-22 17:41:58 +00001085 sqlite3OsLeaveMutex();
drhe29b9152005-03-18 14:03:15 +00001086 TRACE4("LOCK %d %s %s\n", id->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001087 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001088 return rc;
1089}
1090
1091/*
drha6abd042004-06-09 17:37:22 +00001092** Lower the locking level on file descriptor id to locktype. locktype
1093** must be either NO_LOCK or SHARED_LOCK.
1094**
1095** If the locking level of the file descriptor is already at or below
1096** the requested locking level, this routine is a no-op.
1097**
drh9c105bb2004-10-02 20:38:28 +00001098** It is not possible for this routine to fail if the second argument
1099** is NO_LOCK. If the second argument is SHARED_LOCK, this routine
1100** might return SQLITE_IOERR instead of SQLITE_OK.
drhbbd42a62004-05-22 17:41:58 +00001101*/
drha6abd042004-06-09 17:37:22 +00001102int sqlite3OsUnlock(OsFile *id, int locktype){
1103 struct lockInfo *pLock;
1104 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001105 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001106
drhda71ce12004-06-21 18:14:45 +00001107 assert( id->isOpen );
drhe29b9152005-03-18 14:03:15 +00001108 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", id->h, locktype, id->locktype,
danielk19772b444852004-06-29 07:45:33 +00001109 id->pLock->locktype, id->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001110
1111 assert( locktype<=SHARED_LOCK );
1112 if( id->locktype<=locktype ){
1113 return SQLITE_OK;
1114 }
drhbbd42a62004-05-22 17:41:58 +00001115 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +00001116 pLock = id->pLock;
1117 assert( pLock->cnt!=0 );
1118 if( id->locktype>SHARED_LOCK ){
1119 assert( pLock->locktype==id->locktype );
drh9c105bb2004-10-02 20:38:28 +00001120 if( locktype==SHARED_LOCK ){
1121 lock.l_type = F_RDLCK;
1122 lock.l_whence = SEEK_SET;
1123 lock.l_start = SHARED_FIRST;
1124 lock.l_len = SHARED_SIZE;
1125 if( fcntl(id->h, F_SETLK, &lock)!=0 ){
1126 /* This should never happen */
1127 rc = SQLITE_IOERR;
1128 }
1129 }
drhbbd42a62004-05-22 17:41:58 +00001130 lock.l_type = F_UNLCK;
1131 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001132 lock.l_start = PENDING_BYTE;
1133 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
1134 fcntl(id->h, F_SETLK, &lock);
1135 pLock->locktype = SHARED_LOCK;
drhbbd42a62004-05-22 17:41:58 +00001136 }
drha6abd042004-06-09 17:37:22 +00001137 if( locktype==NO_LOCK ){
1138 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001139
drha6abd042004-06-09 17:37:22 +00001140 /* Decrement the shared lock counter. Release the lock using an
1141 ** OS call only when all threads in this same process have released
1142 ** the lock.
1143 */
1144 pLock->cnt--;
1145 if( pLock->cnt==0 ){
1146 lock.l_type = F_UNLCK;
1147 lock.l_whence = SEEK_SET;
1148 lock.l_start = lock.l_len = 0L;
1149 fcntl(id->h, F_SETLK, &lock);
1150 pLock->locktype = NO_LOCK;
1151 }
1152
drhbbd42a62004-05-22 17:41:58 +00001153 /* Decrement the count of locks against this same file. When the
1154 ** count reaches zero, close any other file descriptors whose close
1155 ** was deferred because of outstanding locks.
1156 */
drha6abd042004-06-09 17:37:22 +00001157 pOpen = id->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001158 pOpen->nLock--;
1159 assert( pOpen->nLock>=0 );
1160 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1161 int i;
1162 for(i=0; i<pOpen->nPending; i++){
1163 close(pOpen->aPending[i]);
1164 }
1165 sqliteFree(pOpen->aPending);
1166 pOpen->nPending = 0;
1167 pOpen->aPending = 0;
1168 }
1169 }
1170 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +00001171 id->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001172 return rc;
drhbbd42a62004-05-22 17:41:58 +00001173}
1174
1175/*
danielk1977e3026632004-06-22 11:29:02 +00001176** Close a file.
1177*/
1178int sqlite3OsClose(OsFile *id){
1179 if( !id->isOpen ) return SQLITE_OK;
1180 sqlite3OsUnlock(id, NO_LOCK);
1181 if( id->dirfd>=0 ) close(id->dirfd);
1182 id->dirfd = -1;
1183 sqlite3OsEnterMutex();
1184 if( id->pOpen->nLock ){
1185 /* If there are outstanding locks, do not actually close the file just
1186 ** yet because that would clear those locks. Instead, add the file
1187 ** descriptor to pOpen->aPending. It will be automatically closed when
1188 ** the last lock is cleared.
1189 */
1190 int *aNew;
1191 struct openCnt *pOpen = id->pOpen;
1192 pOpen->nPending++;
1193 aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) );
1194 if( aNew==0 ){
1195 /* If a malloc fails, just leak the file descriptor */
1196 }else{
1197 pOpen->aPending = aNew;
1198 pOpen->aPending[pOpen->nPending-1] = id->h;
1199 }
1200 }else{
1201 /* There are no outstanding locks so we can close the file immediately */
1202 close(id->h);
1203 }
1204 releaseLockInfo(id->pLock);
1205 releaseOpenCnt(id->pOpen);
1206 sqlite3OsLeaveMutex();
1207 id->isOpen = 0;
1208 TRACE2("CLOSE %-3d\n", id->h);
1209 OpenCounter(-1);
1210 return SQLITE_OK;
1211}
1212
1213/*
drh0ccebe72005-06-07 22:22:50 +00001214** Turn a relative pathname into a full pathname. Return a pointer
1215** to the full pathname stored in space obtained from sqliteMalloc().
1216** The calling function is responsible for freeing this space once it
1217** is no longer needed.
1218*/
1219char *sqlite3OsFullPathname(const char *zRelative){
1220 char *zFull = 0;
1221 if( zRelative[0]=='/' ){
1222 sqlite3SetString(&zFull, zRelative, (char*)0);
1223 }else{
1224 char zBuf[5000];
1225 zBuf[0] = 0;
1226 sqlite3SetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative,
1227 (char*)0);
1228 }
1229 return zFull;
1230}
1231
1232
1233#endif /* SQLITE_OMIT_DISKIO */
1234/***************************************************************************
1235** Everything above deals with file I/O. Everything that follows deals
1236** with other miscellanous aspects of the operating system interface
1237****************************************************************************/
1238
1239
1240/*
drhbbd42a62004-05-22 17:41:58 +00001241** Get information to seed the random number generator. The seed
1242** is written into the buffer zBuf[256]. The calling function must
1243** supply a sufficiently large buffer.
1244*/
1245int sqlite3OsRandomSeed(char *zBuf){
1246 /* We have to initialize zBuf to prevent valgrind from reporting
1247 ** errors. The reports issued by valgrind are incorrect - we would
1248 ** prefer that the randomness be increased by making use of the
1249 ** uninitialized space in zBuf - but valgrind errors tend to worry
1250 ** some users. Rather than argue, it seems easier just to initialize
1251 ** the whole array and silence valgrind, even if that means less randomness
1252 ** in the random seed.
1253 **
1254 ** When testing, initializing zBuf[] to zero is all we do. That means
1255 ** that we always use the same random number sequence.* This makes the
1256 ** tests repeatable.
1257 */
1258 memset(zBuf, 0, 256);
1259#if !defined(SQLITE_TEST)
1260 {
drh842b8642005-01-21 17:53:17 +00001261 int pid, fd;
1262 fd = open("/dev/urandom", O_RDONLY);
1263 if( fd<0 ){
1264 time((time_t*)zBuf);
1265 pid = getpid();
1266 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1267 }else{
1268 read(fd, zBuf, 256);
1269 close(fd);
1270 }
drhbbd42a62004-05-22 17:41:58 +00001271 }
1272#endif
1273 return SQLITE_OK;
1274}
1275
1276/*
1277** Sleep for a little while. Return the amount of time slept.
1278*/
1279int sqlite3OsSleep(int ms){
1280#if defined(HAVE_USLEEP) && HAVE_USLEEP
1281 usleep(ms*1000);
1282 return ms;
1283#else
1284 sleep((ms+999)/1000);
1285 return 1000*((ms+999)/1000);
1286#endif
1287}
1288
1289/*
1290** Static variables used for thread synchronization
1291*/
1292static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001293#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +00001294static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +00001295#endif
drhbbd42a62004-05-22 17:41:58 +00001296
1297/*
1298** The following pair of routine implement mutual exclusion for
1299** multi-threaded processes. Only a single thread is allowed to
1300** executed code that is surrounded by EnterMutex() and LeaveMutex().
1301**
1302** SQLite uses only a single Mutex. There is not much critical
1303** code and what little there is executes quickly and without blocking.
1304*/
1305void sqlite3OsEnterMutex(){
1306#ifdef SQLITE_UNIX_THREADS
1307 pthread_mutex_lock(&mutex);
1308#endif
1309 assert( !inMutex );
1310 inMutex = 1;
1311}
1312void sqlite3OsLeaveMutex(){
1313 assert( inMutex );
1314 inMutex = 0;
1315#ifdef SQLITE_UNIX_THREADS
1316 pthread_mutex_unlock(&mutex);
1317#endif
1318}
1319
1320/*
drhbbd42a62004-05-22 17:41:58 +00001321** The following variable, if set to a non-zero value, becomes the result
1322** returned from sqlite3OsCurrentTime(). This is used for testing.
1323*/
1324#ifdef SQLITE_TEST
1325int sqlite3_current_time = 0;
1326#endif
1327
1328/*
1329** Find the current time (in Universal Coordinated Time). Write the
1330** current time and date as a Julian Day number into *prNow and
1331** return 0. Return 1 if the time and date cannot be found.
1332*/
1333int sqlite3OsCurrentTime(double *prNow){
1334 time_t t;
1335 time(&t);
1336 *prNow = t/86400.0 + 2440587.5;
1337#ifdef SQLITE_TEST
1338 if( sqlite3_current_time ){
1339 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1340 }
1341#endif
1342 return 0;
1343}
1344
drhbbd42a62004-05-22 17:41:58 +00001345#endif /* OS_UNIX */