fix curls detection of ssl on AROS. Adjust the used link libraries (linking ssl twice...
[AROS-Contrib.git] / sqlite3 / os_aros.c
blob87e33e99afacc3f4afa3b3513f2fc8b1faf2484d
1 /*
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.
11 ******************************************************************************
13 ** This file contains code that is specific to Unix systems.
15 #include "sqliteInt.h"
16 #include "os.h"
17 #if OS_AROS /* This file is used on unix only */
20 #include <time.h>
21 #include <errno.h>
22 #include <unistd.h>
24 #ifdef SQLITE_DEBUG
25 const char *arosErrLoc = NULL;
26 const char const *__arossql__NULL = NULL;
27 #endif
30 ** Do not include any of the File I/O interface procedures if the
31 ** SQLITE_OMIT_DISKIO macro is defined (indicating that there database
32 ** will be in-memory only)
34 #ifndef SQLITE_OMIT_DISKIO
38 ** Define various macros that are missing from some systems.
40 #ifndef O_LARGEFILE
41 # define O_LARGEFILE 0
42 #endif
43 #ifdef SQLITE_DISABLE_LFS
44 # undef O_LARGEFILE
45 # define O_LARGEFILE 0
46 #endif
47 #ifndef O_NOFOLLOW
48 # define O_NOFOLLOW 0
49 #endif
50 #ifndef O_BINARY
51 # define O_BINARY 0
52 #endif
54 /* Include code that is common to all os_*.c files */
55 #include "os_common.h"
59 * An instance of the following structure serves as the key used to locate
60 * a particular lockInfo structure given its inode.
61 * */
62 struct lockKey {
63 dev_t dev; /* Device number */
64 ino_t ino; /* Inode number */
66 #define openKey lockKey
70 * An instance of the following structure is allocated for each open inode on
71 * each thread with a different process ID. (Threads have different process IDs
72 * on linux, but not on most other unixes.)
74 * A single inode can have multiple file descriptors, so each OsFile structure
75 * contains a pointer to an instance of this object and this object keeps
76 * a count of the number of OsFiles pointing to it.
77 * */
78 struct lockInfo {
79 struct lockKey key; /* The lookup key */
80 int cnt; /* Number of SHARED locks held */
81 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
82 int nRef; /* Number of pointers to this structure */
87 * An instance of the following structure is allocated for each open inode.
88 * This structure keeps track of the number of locks on that inode. If a close
89 * is attempted against an inode that is holding locks, the close is deferred
90 * until all locks clear by adding the file descriptor to be closed to the
91 * pending list.
92 * */
93 struct openCnt {
94 struct openKey key; /* The lookup key */
95 int nRef; /* Number of pointers to this structure */
96 int nLock; /* Number of outstanding locks */
97 int nPending; /* Number of pending close() operations */
98 int *aPending; /* Malloced space holding fd's awaiting a close() */
103 * These hash table maps inodes and process IDs into lockInfo and openCnt
104 * structures. Access to these hash tables must be protected by a mutex.
105 * */
106 static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
107 static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
111 * Release a lockInfo structure previously allocated by findLockInfo().
112 * */
113 static void releaseLockInfo(struct lockInfo *pLock)
115 pLock->nRef--;
116 if( pLock->nRef==0 )
118 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
119 sqliteFree(pLock);
125 * Release a openCnt structure previously allocated by findLockInfo().
126 * */
127 static void releaseOpenCnt(struct openCnt *pOpen)
129 pOpen->nRef--;
130 if( pOpen->nRef==0 )
132 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
133 sqliteFree(pOpen->aPending);
134 sqliteFree(pOpen);
140 * Given a file descriptor, locate lockInfo and openCnt structures that
141 * describes that file descriptor. Create a new ones if necessary. The return
142 * values might be unset if an error occurs.
144 * Return the number of errors.
145 * */
146 static int findLockInfo(
147 int fd, /* The file descriptor used in the key */
148 struct lockInfo **ppLock, /* Return the lockInfo structure here */
149 struct openCnt **ppOpen /* Return the openCnt structure here */
152 int rc;
153 struct lockKey key1;
154 struct openKey key2;
155 struct stat statbuf;
156 struct lockInfo *pLock;
157 struct openCnt *pOpen;
158 rc = fstat(fd, &statbuf);
159 if( rc!=0 ) return 1;
160 memset(&key1, 0, sizeof(key1));
161 key1.dev = statbuf.st_dev;
162 key1.ino = statbuf.st_ino;
163 memset(&key2, 0, sizeof(key2));
164 key2.dev = statbuf.st_dev;
165 key2.ino = statbuf.st_ino;
166 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
167 if( !pLock )
169 struct lockInfo *pOld;
170 pLock = sqliteMallocRaw( sizeof(*pLock) );
171 if( !pLock ) return 1;
172 pLock->key = key1;
173 pLock->nRef = 1;
174 pLock->cnt = 0;
175 pLock->locktype = 0;
176 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
177 if( pOld )
179 assert( pOld==pLock );
180 sqliteFree(pLock);
181 return 1;
184 else pLock->nRef++;
186 *ppLock = pLock;
187 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
188 if( !pOpen )
190 struct openCnt *pOld;
191 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
192 if( !pOpen )
194 releaseLockInfo(pLock);
195 return 1;
197 pOpen->key = key2;
198 pOpen->nRef = 1;
199 pOpen->nLock = 0;
200 pOpen->nPending = 0;
201 pOpen->aPending = NULL;
202 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
203 if( pOld )
205 assert( pOld==pOpen );
206 sqliteFree(pOpen);
207 releaseLockInfo(pLock);
208 return 1;
211 else pOpen->nRef++;
213 *ppOpen = pOpen;
214 return 0;
219 * Delete the named file.
220 * */
221 err_t sqlite3OsDelete( CONST_STRPTR zFilename )
223 unlink(zFilename);
224 return SQLITE_OK;
229 * Return TRUE if the named file exists.
230 * */
231 BOOL sqlite3OsFileExists( CONST_STRPTR zFilename )
233 return access(zFilename, F_OK)==0;
238 * Attempt to open a file for both reading and writing. If that fails, try
239 * opening it read-only. If the file does not exist, try to create it.
241 * On success, a handle for the open file is written to *id and *pReadonly is
242 * set to 0 if the file was opened for reading and writing or 1 if the file was
243 * opened read-only. The function returns SQLITE_OK.
245 * On failure, the function returns SQLITE_CANTOPEN and leaves *id and
246 * *pReadonly unchanged.
247 * */
248 err_t sqlite3OsOpenReadWrite(
249 CONST_STRPTR zFilename,
250 OsFile *id,
251 int *pReadonly
254 int rc;
255 assert( !id->isOpen );
256 id->dirfd = -1;
257 id->h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
258 SQLITE_DEFAULT_FILE_PERMISSIONS);
259 if( id->h < 0 )
261 #ifdef EISDIR
262 if( errno==EISDIR ) return SQLITE_CANTOPEN;
263 #endif
264 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
265 if( id->h < 0 ) return SQLITE_CANTOPEN;
266 *pReadonly = TRUE;
268 else *pReadonly = FALSE;
270 sqlite3OsEnterMutex();
271 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
272 sqlite3OsLeaveMutex();
273 if( rc )
275 close(id->h);
276 return SQLITE_NOMEM;
278 id->locktype = 0;
279 id->isOpen = 1;
280 TRACE("OPEN %-3d %s\n", id->h, zFilename);
281 OpenCounter(+1);
282 return SQLITE_OK;
287 * Attempt to open a new file for exclusive access by this process. The file
288 * will be opened for both reading and writing. To avoid a potential security
289 * problem, we do not allow the file to have previously existed. Nor do we
290 * allow the file to be a symbolic link.
292 * If delFlag is true, then make arrangements to automatically delete the file
293 * when it is closed.
295 * On success, write the file handle into *id and return SQLITE_OK.
297 * On failure, return SQLITE_CANTOPEN.
298 * */
299 err_t sqlite3OsOpenExclusive(CONST_STRPTR zFilename, OsFile *id, BOOL delFlag)
301 int rc;
303 assert( !id->isOpen );
304 if( access(zFilename, F_OK)==0 )
305 return SQLITE_CANTOPEN;
307 id->dirfd = -1;
308 if( 0 > (id->h = open(zFilename,
309 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
310 0600)))
311 return SQLITE_CANTOPEN;
313 sqlite3OsEnterMutex();
314 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
315 sqlite3OsLeaveMutex();
316 if( rc )
318 close(id->h);
319 unlink(zFilename);
320 return SQLITE_NOMEM;
322 id->locktype = 0;
323 id->isOpen = TRUE;
324 if( delFlag )
325 unlink(zFilename);
326 TRACE("OPEN-EX %-3d %s\n", id->h, zFilename);
327 OpenCounter(+1);
328 return SQLITE_OK;
333 * Attempt to open a new file for read-only access.
335 * On success, write the file handle into *id and return SQLITE_OK.
336 * On failure, return SQLITE_CANTOPEN.
337 * */
338 err_t sqlite3OsOpenReadOnly( CONST_STRPTR zFilename, OsFile *id )
340 int rc;
341 assert( !id->isOpen );
342 id->dirfd = -1;
343 if( 0 > (id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY)))
344 return SQLITE_CANTOPEN;
345 sqlite3OsEnterMutex();
346 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
347 sqlite3OsLeaveMutex();
348 if( rc )
350 close(id->h);
351 return SQLITE_NOMEM;
353 id->locktype = 0;
354 id->isOpen = TRUE;
355 TRACE("OPEN-RO %-3d %s\n", id->h, zFilename);
356 OpenCounter(+1);
357 return SQLITE_OK;
362 * Attempt to open a file descriptor for the directory that contains a file.
363 * This file descriptor can be used to fsync() the directory in order to make
364 * sure the creation of a new file is actually written to disk.
366 * This routine is only meaningful for Unix. It is a no-op under windows since
367 * windows does not support hard links.
369 * On success, a handle for a previously open file is at *id is updated with
370 * the new directory file descriptor and SQLITE_OK is returned.
372 * On failure, the function returns SQLITE_CANTOPEN and leaves *id unchanged.
373 * */
374 err_t sqlite3OsOpenDirectory( CONST_STRPTR zDirname, OsFile *id )
376 if( !id->isOpen )
379 * Do not open the directory if the corresponding file is not already
380 * open.
381 * */
382 return SQLITE_CANTOPEN;
384 assert( id->dirfd<0 );
385 if( 0 > (id->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0)))
386 return SQLITE_CANTOPEN;
387 TRACE("OPENDIR %-3d %s\n", id->dirfd, zDirname);
388 return SQLITE_OK;
393 * If the following global variable points to a string which is the name of
394 * a directory, then that directory will be used to store temporary files.
395 * */
396 STRPTR sqlite3_temp_directory = NULL;
400 * Create a temporary file name in zBuf. zBuf must be big enough to hold at
401 * least SQLITE_TEMPNAME_SIZE characters.
402 * */
403 err_t sqlite3OsTempFileName(char *zBuf)
405 static CONST_STRPTR azDirs[] = {
407 "T:",
408 "RAM:",
410 static const unsigned char zChars[] =
411 "abcdefghijklmnopqrstuvwxyz"
412 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
413 "0123456789";
414 int i, j;
415 struct stat buf;
416 CONST_STRPTR zDir = ".";
418 azDirs[0] = sqlite3_temp_directory;
420 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++)
422 if( !azDirs[i] ) continue;
423 if( stat(azDirs[i], &buf) ) continue;
424 if( !S_ISDIR(buf.st_mode) ) continue;
425 if( access(azDirs[i], F_OK) ) continue;
426 zDir = azDirs[i];
427 break;
429 do {
430 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
431 j = strlen(zBuf);
432 sqlite3Randomness(15, &zBuf[j]);
433 for(i=0; i<15; i++, j++)
434 zBuf[j] = (char)zChars[((unsigned char)zBuf[j])%(sizeof(zChars)-1)];
435 zBuf[j] = '\0';
436 }while( access(zBuf,F_OK)==0 );
437 return SQLITE_OK;
441 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
443 * Check that a given pathname is a directory and is writable.
444 * */
445 BOOL sqlite3OsIsDirWritable( CONST_STRPTR zBuf )
447 struct stat buf;
448 if( !zBuf ) return FALSE;
449 if( zBuf[0]=='\0' ) return FALSE;
450 if( stat(zBuf, &buf) ) return FALSE;
451 if( !S_ISDIR(buf.st_mode) ) return FALSE;
452 if( access(zBuf, R_OK|W_OK|X_OK) ) return FALSE;
453 return TRUE;
455 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
459 * Read data from a file into a buffer. Return SQLITE_OK if all bytes were read
460 * successfully and SQLITE_IOERR if anything goes wrong.
461 * */
462 err_t sqlite3OsRead(OsFile *id, void *pBuf, int amt)
464 int got;
465 assert( id->isOpen );
466 SimulateIOError(SQLITE_IOERR);
467 TIMER_START;
468 got = read(id->h, pBuf, amt);
469 TIMER_END;
470 TRACE("READ %-3d %5d %7d %d\n", id->h, got, last_page, TIMER_ELAPSED);
471 SEEK(0);
472 /* if( got<0 ) got = 0; */
473 if( got==amt ) return SQLITE_OK;
474 return SQLITE_IOERR;
479 * Write data from a buffer into a file. Return SQLITE_OK on success or some
480 * other error code on failure.
481 * */
482 err_t sqlite3OsWrite(OsFile *id, const void *pBuf, int amt)
484 int wrote = 0;
485 assert( id->isOpen );
486 assert( amt>0 );
487 SimulateIOError(SQLITE_IOERR);
488 SimulateDiskfullError;
489 TIMER_START;
490 while( amt>0 && (wrote = write(id->h, pBuf, amt))>0 )
492 amt -= wrote;
493 pBuf = &((char*)pBuf)[wrote];
495 TIMER_END;
496 TRACE("WRITE %-3d %5d %7d %d\n", id->h, wrote, last_page, TIMER_ELAPSED);
497 SEEK(0);
498 if( amt>0 ) return SQLITE_FULL;
499 return SQLITE_OK;
504 * Move the read/write pointer in a file.
505 * */
506 err_t sqlite3OsSeek(OsFile *id, i64 offset)
508 assert( id->isOpen );
509 SEEK(offset/1024 + 1);
510 lseek(id->h, offset, SEEK_SET);
511 return SQLITE_OK;
515 #ifdef SQLITE_TEST
517 * Count the number of fullsyncs and normal syncs. This is used to test that
518 * syncs and fullsyncs are occuring at the right times.
519 * */
520 int sqlite3_sync_count = 0;
521 int sqlite3_fullsync_count = 0;
522 #endif
526 * The fsync() system call does not work as advertised on many unix systems.
527 * The following procedure is an attempt to make it work better.
529 * The SQLITE_NO_SYNC macro disables all fsync()s. This is useful for testing
530 * when we want to run through the test suite quickly. You are strongly
531 * advised *not* to deploy with SQLITE_NO_SYNC enabled, however, since with
532 * SQLITE_NO_SYNC enabled, an OS crash or power failure will likely corrupt
533 * the database file.
534 * */
535 static int full_fsync(int fd, int fullSync)
537 int rc;
540 * Record the number of times that we do a normal fsync() and FULLSYNC.
541 * This is used during testing to verify that this procedure gets called
542 * with the correct arguments.
543 * */
544 #ifdef SQLITE_TEST
545 if( fullSync ) sqlite3_fullsync_count++;
546 sqlite3_sync_count++;
547 #endif
550 * If we compiled with the SQLITE_NO_SYNC flag, then syncing is a no-op
551 * */
552 #ifdef SQLITE_NO_SYNC
553 rc = SQLITE_OK;
554 #else
556 #ifdef F_FULLFSYNC
557 if( fullSync )
558 rc = fcntl(fd, F_FULLFSYNC, 0);
559 else rc = 1;
561 /* If the FULLSYNC failed, try to do a normal fsync() */
562 if( rc ) rc = fsync(fd);
563 #else
564 rc = fsync(fd);
565 #endif /* defined(F_FULLFSYNC) */
566 #endif /* defined(SQLITE_NO_SYNC) */
568 return rc;
573 * Make sure all writes to a particular file are committed to disk.
575 * Under Unix, also make sure that the directory entry for the file has been
576 * created by fsync-ing the directory that contains the file. If we do not do
577 * this and we encounter a power failure, the directory entry for the journal
578 * might not exist after we reboot. The next SQLite to access the file will not
579 * know that the journal exists (because the directory entry for the journal
580 * was never created) and the transaction will not roll back - possibly leading
581 * to database corruption.
582 * */
583 err_t sqlite3OsSync(OsFile *id)
585 assert( id->isOpen );
586 SimulateIOError(SQLITE_IOERR);
587 TRACE("SYNC %-3d\n", id->h);
588 if( full_fsync(id->h, id->fullSync) )
589 return SQLITE_IOERR;
590 if( id->dirfd>=0 )
592 TRACE("DIRSYNC %-3d\n", id->dirfd);
593 full_fsync(id->dirfd, id->fullSync);
594 close(id->dirfd); /* Only need to sync once, so close the directory */
595 id->dirfd = -1; /* when we are done. */
597 return SQLITE_OK;
602 * Sync the directory zDirname. This is a no-op on operating systems other
603 * than UNIX.
605 * This is used to make sure the master journal file has truely been deleted
606 * before making changes to individual journals on a multi-database commit.
607 * The F_FULLFSYNC option is not needed here.
608 * */
609 err_t sqlite3OsSyncDirectory( CONST_STRPTR zDirname )
611 int fd;
612 int r;
613 SimulateIOError(SQLITE_IOERR);
614 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
615 TRACE("DIRSYNC %-3d (%s)\n", fd, zDirname);
616 if( fd<0 ) return SQLITE_CANTOPEN;
618 r = fsync(fd);
619 close(fd);
620 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
625 * Truncate an open file to a specified size.
626 * */
627 err_t sqlite3OsTruncate(OsFile *id, i64 nByte)
629 assert( id->isOpen );
630 SimulateIOError(SQLITE_IOERR);
631 return ftruncate(id->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
636 * Determine the current size of a file in bytes.
637 * */
638 err_t sqlite3OsFileSize(OsFile *id, i64 *pSize)
640 struct stat buf;
641 assert( id->isOpen );
642 SimulateIOError(SQLITE_IOERR);
643 if( fstat(id->h, &buf)!=0 )
644 return SQLITE_IOERR;
645 *pSize = buf.st_size;
646 return SQLITE_OK;
651 * This routine checks if there is a RESERVED lock held on the specified file
652 * by this or any other process. If such a lock is held, return non-zero. If
653 * the file is unlocked or holds only SHARED locks, then return zero.
654 * */
655 BOOL sqlite3OsCheckReservedLock(OsFile *id)
657 BOOL r = FALSE;
659 assert( id->isOpen );
660 sqlite3OsEnterMutex(); /* Needed because id->pLock is shared across
661 threads */
662 /* Check if a thread in this process holds such a lock */
663 if( id->pLock->locktype > SHARED_LOCK )
664 r = TRUE;
666 /* Otherwise see if some other process holds it. */
667 #if !OS_AROS
668 if( !r )
670 struct flock lock;
671 lock.l_whence = SEEK_SET;
672 lock.l_start = RESERVED_BYTE;
673 lock.l_len = 1;
674 lock.l_type = F_WRLCK;
675 fcntl(id->h, F_GETLK, &lock);
676 if( lock.l_type != F_UNLCK )
677 r = TRUE;
679 #endif
681 sqlite3OsLeaveMutex();
682 TRACE("TEST WR-LOCK %d %d\n", id->h, r);
684 return r;
688 #ifdef SQLITE_DEBUG
690 * Helper function for printing out trace information from debugging binaries.
691 * This returns the string represetation of the supplied integer lock-type.
692 * */
693 static const char * locktypeName(int locktype)
695 switch( locktype )
697 case NO_LOCK: return "NONE";
698 case SHARED_LOCK: return "SHARED";
699 case RESERVED_LOCK: return "RESERVED";
700 case PENDING_LOCK: return "PENDING";
701 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
703 return "ERROR";
705 #endif
709 * Lock the file with the lock specified by parameter locktype - one of the
710 * following:
711 * (1) SHARED_LOCK
712 * (2) RESERVED_LOCK
713 * (3) PENDING_LOCK
714 * (4) EXCLUSIVE_LOCK
716 * Sometimes when requesting one lock state, additional lock states are
717 * inserted in between. The locking might fail on one of the later transitions
718 * leaving the lock state different from what it started but still short of its
719 * goal. The following chart shows the allowed transitions and the inserted
720 * intermediate states:
722 * UNLOCKED -> SHARED
723 * SHARED -> RESERVED
724 * SHARED -> (PENDING) -> EXCLUSIVE
725 * RESERVED -> (PENDING) -> EXCLUSIVE
726 * PENDING -> EXCLUSIVE
728 * This routine will only increase a lock. Use the sqlite3OsUnlock() routine to
729 * lower a locking level.
730 * */
731 err_t sqlite3OsLock(OsFile *id, int locktype)
734 * The following describes the implementation of the various locks and lock
735 * transitions in terms of the POSIX advisory shared and exclusive lock
736 * primitives (called read-locks and write-locks below, to avoid confusion
737 * with SQLite lock names). The algorithms are complicated slightly in
738 * order to be compatible with windows systems simultaneously accessing the
739 * same database file, in case that is ever required.
741 * Symbols defined in os.h indentify the 'pending byte' and the 'reserved
742 * byte', each single bytes at well known offsets, and the 'shared byte
743 * range', a range of 510 bytes at a well known offset.
745 * To obtain a SHARED lock, a read-lock is obtained on the 'pending byte'.
746 * If this is successful, a random byte from the 'shared byte range' is
747 * read-locked and the lock on the 'pending byte' released. A process may
748 * only obtain a RESERVED lock after it has a SHARED lock. A RESERVED lock
749 * is implemented by grabbing a write-lock on the 'reserved byte'.
751 * A process may only obtain a PENDING lock after it has obtained a SHARED
752 * lock. A PENDING lock is implemented by obtaining a write-lock on the
753 * 'pending byte'. This ensures that no new SHARED locks can be obtained,
754 * but existing SHARED locks are allowed to persist. A process does not
755 * have to obtain a RESERVED lock on the way to a PENDING lock. This
756 * property is used by the algorithm for rolling back a journal file after
757 * a crash.
759 * An EXCLUSIVE lock, obtained after a PENDING lock is held, is implemented
760 * by obtaining a write-lock on the entire 'shared byte range'. Since all
761 * other locks require a read-lock on one of the bytes within this range,
762 * this ensures that no other locks are held on the database.
764 * The reason a single byte cannot be used instead of the 'shared byte
765 * range' is that some versions of windows do not support read-locks. By
766 * locking a random byte from a range, concurrent SHARED locks may exist
767 * even if the locking primitive used is always a write-lock.
768 * */
769 int rc = SQLITE_OK;
770 struct lockInfo *pLock = id->pLock;
771 struct flock lock;
772 int s;
773 SETFNC( "sqlite3OsLock" );
775 assert( id->isOpen );
776 TRACE("LOCK %d %s was %s(%s,%d) pid=%d\n", id->h,
777 locktypeName(locktype),
778 locktypeName(id->locktype),
779 locktypeName(pLock->locktype),
780 pLock->cnt, getpid() );
783 * If there is already a lock of this type or more restrictive on the
784 * OsFile, do nothing. Don't use the end_lock: exit path, as
785 * sqlite3OsEnterMutex() hasn't been called yet.
786 * */
787 if( id->locktype >= locktype )
789 TRACE("LOCK %d %s ok (already held)\n", id->h,
790 locktypeName(locktype));
791 return SQLITE_OK;
794 /* Make sure the locking sequence is correct */
795 assert( id->locktype != NO_LOCK || locktype == SHARED_LOCK );
796 assert( locktype != PENDING_LOCK );
797 assert( locktype != RESERVED_LOCK || id->locktype == SHARED_LOCK );
799 /* This mutex is needed because id->pLock is shared across threads */
800 sqlite3OsEnterMutex();
803 * If some thread using this PID has a lock via a different OsFile* handle
804 * that precludes the requested lock, return BUSY.
805 * */
806 if( (id->locktype != pLock->locktype
807 && (pLock->locktype >= PENDING_LOCK
808 || locktype > SHARED_LOCK)))
810 rc = SQLITE_BUSY;
811 goto end_lock;
815 * If a SHARED lock is requested, and some thread using this PID already
816 * has a SHARED or RESERVED lock, then increment reference counts and
817 * return SQLITE_OK.
818 * */
819 if( locktype == SHARED_LOCK
820 && (pLock->locktype == SHARED_LOCK
821 || pLock->locktype == RESERVED_LOCK))
823 assert( locktype == SHARED_LOCK );
824 assert( id->locktype == NO_LOCK );
825 assert( pLock->cnt > 0 );
826 id->locktype = SHARED_LOCK;
827 pLock->cnt++;
828 id->pOpen->nLock++;
829 goto end_lock;
832 lock.l_len = 1L;
833 lock.l_whence = SEEK_SET;
836 * A PENDING lock is needed before acquiring a SHARED lock and before
837 * acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will be
838 * released.
839 * */
840 if( locktype == SHARED_LOCK
841 || (locktype == EXCLUSIVE_LOCK
842 && id->locktype < PENDING_LOCK))
844 lock.l_type = (locktype == SHARED_LOCK ? F_RDLCK : F_WRLCK);
845 lock.l_start = PENDING_BYTE;
846 s = fcntl(id->h, F_SETLK, &lock);
847 #if !OS_AROS
848 if( s )
850 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
851 ERRLOC( funcn );
852 goto end_lock;
854 #endif
858 * If control gets to this point, then actually go ahead and make OS calls
859 * for the specified lock.
860 * */
861 if( locktype == SHARED_LOCK )
863 assert( !pLock->cnt );
864 assert( !pLock->locktype );
866 /* Now get the read-lock */
867 lock.l_start = SHARED_FIRST;
868 lock.l_len = SHARED_SIZE;
869 s = fcntl(id->h, F_SETLK, &lock);
871 /* Drop the temporary PENDING lock */
872 lock.l_start = PENDING_BYTE;
873 lock.l_len = 1L;
874 lock.l_type = F_UNLCK;
875 #if !OS_AROS
876 fcntl(id->h, F_SETLK, &lock);
877 if( s )
879 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
880 ERRLOC( funcn );
882 else
883 #endif
885 id->locktype = SHARED_LOCK;
886 id->pOpen->nLock++;
887 pLock->cnt = 1;
890 else if( locktype == EXCLUSIVE_LOCK && pLock->cnt > 1 )
893 * We are trying for an exclusive lock but another thread in this same
894 * process is still holding a shared lock.
895 * */
896 rc = SQLITE_BUSY;
898 else
901 * The request was for a RESERVED or EXCLUSIVE lock. It is assumed that
902 * there is a SHARED or greater lock on the file already.
903 * */
904 assert( id->locktype );
905 lock.l_type = F_WRLCK;
906 switch( locktype )
908 case RESERVED_LOCK:
909 lock.l_start = RESERVED_BYTE;
910 break;
911 case EXCLUSIVE_LOCK:
912 lock.l_start = SHARED_FIRST;
913 lock.l_len = SHARED_SIZE;
914 break;
915 default:
916 assert(0);
918 s = fcntl(id->h, F_SETLK, &lock);
919 #if !OS_AROS
920 if( s )
922 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
923 ERRLOC( funcn );
925 #endif
928 if( rc == SQLITE_OK )
930 id->locktype = locktype;
931 pLock->locktype = locktype;
933 else if( locktype == EXCLUSIVE_LOCK )
935 id->locktype = PENDING_LOCK;
936 pLock->locktype = PENDING_LOCK;
939 end_lock:
940 sqlite3OsLeaveMutex();
941 TRACE("LOCK %d %s %s\n", id->h, locktypeName(locktype),
942 rc==SQLITE_OK ? "ok" : "failed");
943 return rc;
948 * Lower the locking level on file descriptor id to locktype. locktype must be
949 * either NO_LOCK or SHARED_LOCK.
951 * If the locking level of the file descriptor is already at or below the
952 * requested locking level, this routine is a no-op.
954 * It is not possible for this routine to fail if the second argument is
955 * NO_LOCK. If the second argument is SHARED_LOCK, this routine might return
956 * SQLITE_IOERR instead of SQLITE_OK.
957 * */
958 err_t sqlite3OsUnlock(OsFile *id, int locktype)
960 struct lockInfo *pLock;
961 struct flock lock;
962 int rc = SQLITE_OK;
964 assert( id->isOpen );
965 TRACE("UNLOCK %d %d was %d(%d,%d) pid=%d\n", id->h, locktype,
966 id->locktype, id->pLock->locktype, id->pLock->cnt, getpid());
968 assert( locktype <= SHARED_LOCK );
969 if( id->locktype <= locktype )
970 return SQLITE_OK;
972 sqlite3OsEnterMutex();
973 pLock = id->pLock;
974 assert( pLock->cnt );
975 if( id->locktype > SHARED_LOCK )
977 assert( pLock->locktype == id->locktype );
978 if( locktype == SHARED_LOCK )
980 lock.l_type = F_RDLCK;
981 lock.l_whence = SEEK_SET;
982 lock.l_start = SHARED_FIRST;
983 lock.l_len = SHARED_SIZE;
984 #if !OS_AROS
985 if( fcntl(id->h, F_SETLK, &lock)!=0 )
987 /* This should never happen */
988 rc = SQLITE_IOERR;
990 #endif
992 lock.l_type = F_UNLCK;
993 lock.l_whence = SEEK_SET;
994 lock.l_start = PENDING_BYTE;
995 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
996 #if !OS_AROS
997 fcntl(id->h, F_SETLK, &lock);
998 #endif
999 pLock->locktype = SHARED_LOCK;
1002 if( locktype == NO_LOCK )
1004 struct openCnt *pOpen;
1007 * Decrement the shared lock counter. Release the lock using an OS call
1008 * only when all threads in this same process have released the lock.
1009 * */
1010 pLock->cnt--;
1011 if( !pLock->cnt )
1013 lock.l_type = F_UNLCK;
1014 lock.l_whence = SEEK_SET;
1015 lock.l_start = lock.l_len = 0L;
1016 #if !OS_AROS
1017 fcntl(id->h, F_SETLK, &lock);
1018 #endif
1019 pLock->locktype = NO_LOCK;
1023 * Decrement the count of locks against this same file. When the count
1024 * reaches zero, close any other file descriptors whose close was
1025 * deferred because of outstanding locks.
1026 * */
1027 pOpen = id->pOpen;
1028 pOpen->nLock--;
1029 assert( pOpen->nLock >= 0 );
1030 if( pOpen->nLock==0 && pOpen->nPending>0 )
1032 int i;
1033 for(i=0; i<pOpen->nPending; i++)
1034 close(pOpen->aPending[i]);
1035 sqliteFree(pOpen->aPending);
1036 pOpen->nPending = 0;
1037 pOpen->aPending = 0;
1040 sqlite3OsLeaveMutex();
1041 id->locktype = locktype;
1042 return rc;
1047 * Close a file.
1048 * */
1049 err_t sqlite3OsClose(OsFile *id)
1051 if( !id->isOpen ) return SQLITE_OK;
1052 sqlite3OsUnlock(id, NO_LOCK);
1053 if( id->dirfd>=0 ) close(id->dirfd);
1054 id->dirfd = -1;
1055 sqlite3OsEnterMutex();
1056 if( id->pOpen->nLock )
1059 * If there are outstanding locks, do not actually close the file just
1060 * yet because that would clear those locks. Instead, add the file
1061 * descriptor to pOpen->aPending. It will be automatically closed when
1062 * the last lock is cleared.
1063 * */
1064 int *aNew;
1065 struct openCnt *pOpen = id->pOpen;
1066 pOpen->nPending++;
1067 aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) );
1068 if( !aNew )
1069 ; /* If a malloc fails, just leak the file descriptor */
1070 else
1072 pOpen->aPending = aNew;
1073 pOpen->aPending[pOpen->nPending-1] = id->h;
1076 else
1078 /* There are no outstanding locks so we can close the file
1079 * immediately.
1080 * */
1081 close(id->h);
1083 releaseLockInfo(id->pLock);
1084 releaseOpenCnt(id->pOpen);
1085 sqlite3OsLeaveMutex();
1086 id->isOpen = FALSE;
1087 TRACE("CLOSE %-3d\n", id->h);
1088 OpenCounter(-1);
1089 return SQLITE_OK;
1094 * Turn a relative pathname into a full pathname. Return a pointer to the full
1095 * pathname stored in space obtained from sqliteMalloc(). The calling function
1096 * is responsible for freeing this space once it is no longer needed.
1097 * */
1098 char *sqlite3OsFullPathname(CONST_STRPTR zRelative)
1100 STRPTR zFull = NULL;
1101 #if !OS_AROS
1102 if( zRelative[0]=='/' )
1104 sqlite3SetString(&zFull, zRelative, NULL);
1106 else
1107 #endif
1109 char zBuf[5000];
1110 zBuf[0] = 0;
1111 sqlite3SetString( &zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative,
1112 NULL);
1114 return zFull;
1116 #endif /* SQLITE_OMIT_DISKIO */
1120 * Everything above deals with file I/O. Everything that follows deals with
1121 * other miscellanous aspects of the operating system interface.
1123 * */
1127 * Get information to seed the random number generator. The seed is written
1128 * into the buffer zBuf[256]. The calling function must supply a sufficiently
1129 * large buffer.
1130 * */
1131 int sqlite3OsRandomSeed(char *zBuf)
1134 * When testing, initializing zBuf[] to zero is all we do. That means that
1135 * we always use the same random number sequence.* This makes the tests
1136 * repeatable.
1137 * */
1138 memset(zBuf, 0, 256);
1139 #if !defined(SQLITE_TEST)
1141 int pid, fd;
1142 /* See if we can use /dev/urandom for random numbers... */
1143 fd = open("/dev/urandom", O_RDONLY);
1144 if( fd < 0 )
1146 time((time_t*)zBuf);
1147 pid = getpid();
1148 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1150 else
1152 read(fd, zBuf, 256);
1153 close(fd);
1156 #endif
1157 return SQLITE_OK;
1162 * Sleep for a little while. Return the amount of time slept.
1163 * */
1164 int sqlite3OsSleep(int ms)
1166 #if defined(HAVE_USLEEP) && HAVE_USLEEP
1167 usleep(ms*1000);
1168 return ms;
1169 #else
1170 sleep((ms+999)/1000);
1171 return 1000*((ms+999)/1000);
1172 #endif
1177 * Static variables used for thread synchronization.
1178 * */
1179 static BOOL inMutex = FALSE;
1183 * The following pair of routine implement mutual exclusion for multi-threaded
1184 * processes. Only a single thread is allowed to executed code that is
1185 * surrounded by EnterMutex() and LeaveMutex().
1187 * SQLite uses only a single Mutex. There is not much critical code and what
1188 * little there is executes quickly and without blocking.
1189 * */
1190 void sqlite3OsEnterMutex()
1192 assert( !inMutex );
1193 inMutex = TRUE;
1195 void sqlite3OsLeaveMutex()
1197 assert( inMutex );
1198 inMutex = FALSE;
1203 * The following variable, if set to a non-zero value, becomes the result
1204 * returned from sqlite3OsCurrentTime(). This is used for testing.
1205 * */
1206 #ifdef SQLITE_TEST
1207 int sqlite3_current_time = 0;
1208 #endif
1212 * Find the current time (in Universal Coordinated Time). Write the current
1213 * time and date as a Julian Day number into *prNow and return FALSE. Return
1214 * TRUE if the time and date cannot be found.
1215 * */
1216 BOOL sqlite3OsCurrentTime(double *prNow)
1218 time_t t;
1219 time(&t);
1220 *prNow = t/86400.0 + 2440587.5;
1221 #ifdef SQLITE_TEST
1222 if( sqlite3_current_time )
1223 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1224 #endif
1225 return FALSE;
1228 #endif /* OS_AROS */