4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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"
17 #if OS_AROS /* This file is used on unix only */
25 const char *arosErrLoc
= NULL
;
26 const char const *__arossql__NULL
= NULL
;
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.
41 # define O_LARGEFILE 0
43 #ifdef SQLITE_DISABLE_LFS
45 # define O_LARGEFILE 0
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.
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.
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
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.
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().
113 static void releaseLockInfo(struct lockInfo
*pLock
)
118 sqlite3HashInsert(&lockHash
, &pLock
->key
, sizeof(pLock
->key
), 0);
125 * Release a openCnt structure previously allocated by findLockInfo().
127 static void releaseOpenCnt(struct openCnt
*pOpen
)
132 sqlite3HashInsert(&openHash
, &pOpen
->key
, sizeof(pOpen
->key
), 0);
133 sqliteFree(pOpen
->aPending
);
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.
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 */
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
));
169 struct lockInfo
*pOld
;
170 pLock
= sqliteMallocRaw( sizeof(*pLock
) );
171 if( !pLock
) return 1;
176 pOld
= sqlite3HashInsert(&lockHash
, &pLock
->key
, sizeof(key1
), pLock
);
179 assert( pOld
==pLock
);
187 pOpen
= (struct openCnt
*)sqlite3HashFind(&openHash
, &key2
, sizeof(key2
));
190 struct openCnt
*pOld
;
191 pOpen
= sqliteMallocRaw( sizeof(*pOpen
) );
194 releaseLockInfo(pLock
);
201 pOpen
->aPending
= NULL
;
202 pOld
= sqlite3HashInsert(&openHash
, &pOpen
->key
, sizeof(key2
), pOpen
);
205 assert( pOld
==pOpen
);
207 releaseLockInfo(pLock
);
219 * Delete the named file.
221 err_t
sqlite3OsDelete( CONST_STRPTR zFilename
)
229 * Return TRUE if the named file exists.
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.
248 err_t
sqlite3OsOpenReadWrite(
249 CONST_STRPTR zFilename
,
255 assert( !id
->isOpen
);
257 id
->h
= open(zFilename
, O_RDWR
|O_CREAT
|O_LARGEFILE
|O_BINARY
,
258 SQLITE_DEFAULT_FILE_PERMISSIONS
);
262 if( errno
==EISDIR
) return SQLITE_CANTOPEN
;
264 id
->h
= open(zFilename
, O_RDONLY
|O_LARGEFILE
|O_BINARY
);
265 if( id
->h
< 0 ) return SQLITE_CANTOPEN
;
268 else *pReadonly
= FALSE
;
270 sqlite3OsEnterMutex();
271 rc
= findLockInfo(id
->h
, &id
->pLock
, &id
->pOpen
);
272 sqlite3OsLeaveMutex();
280 TRACE("OPEN %-3d %s\n", id
->h
, zFilename
);
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
295 * On success, write the file handle into *id and return SQLITE_OK.
297 * On failure, return SQLITE_CANTOPEN.
299 err_t
sqlite3OsOpenExclusive(CONST_STRPTR zFilename
, OsFile
*id
, BOOL delFlag
)
303 assert( !id
->isOpen
);
304 if( access(zFilename
, F_OK
)==0 )
305 return SQLITE_CANTOPEN
;
308 if( 0 > (id
->h
= open(zFilename
,
309 O_RDWR
|O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_LARGEFILE
|O_BINARY
,
311 return SQLITE_CANTOPEN
;
313 sqlite3OsEnterMutex();
314 rc
= findLockInfo(id
->h
, &id
->pLock
, &id
->pOpen
);
315 sqlite3OsLeaveMutex();
326 TRACE("OPEN-EX %-3d %s\n", id
->h
, zFilename
);
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.
338 err_t
sqlite3OsOpenReadOnly( CONST_STRPTR zFilename
, OsFile
*id
)
341 assert( !id
->isOpen
);
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();
355 TRACE("OPEN-RO %-3d %s\n", id
->h
, zFilename
);
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.
374 err_t
sqlite3OsOpenDirectory( CONST_STRPTR zDirname
, OsFile
*id
)
379 * Do not open the directory if the corresponding file is not already
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
);
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.
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.
403 err_t
sqlite3OsTempFileName(char *zBuf
)
405 static CONST_STRPTR azDirs
[] = {
410 static const unsigned char zChars
[] =
411 "abcdefghijklmnopqrstuvwxyz"
412 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
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;
430 sprintf(zBuf
, "%s/"TEMP_FILE_PREFIX
, zDir
);
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)];
436 }while( access(zBuf
,F_OK
)==0 );
441 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
443 * Check that a given pathname is a directory and is writable.
445 BOOL
sqlite3OsIsDirWritable( CONST_STRPTR zBuf
)
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
;
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.
462 err_t
sqlite3OsRead(OsFile
*id
, void *pBuf
, int amt
)
465 assert( id
->isOpen
);
466 SimulateIOError(SQLITE_IOERR
);
468 got
= read(id
->h
, pBuf
, amt
);
470 TRACE("READ %-3d %5d %7d %d\n", id
->h
, got
, last_page
, TIMER_ELAPSED
);
472 /* if( got<0 ) got = 0; */
473 if( got
==amt
) return SQLITE_OK
;
479 * Write data from a buffer into a file. Return SQLITE_OK on success or some
480 * other error code on failure.
482 err_t
sqlite3OsWrite(OsFile
*id
, const void *pBuf
, int amt
)
485 assert( id
->isOpen
);
487 SimulateIOError(SQLITE_IOERR
);
488 SimulateDiskfullError
;
490 while( amt
>0 && (wrote
= write(id
->h
, pBuf
, amt
))>0 )
493 pBuf
= &((char*)pBuf
)[wrote
];
496 TRACE("WRITE %-3d %5d %7d %d\n", id
->h
, wrote
, last_page
, TIMER_ELAPSED
);
498 if( amt
>0 ) return SQLITE_FULL
;
504 * Move the read/write pointer in a file.
506 err_t
sqlite3OsSeek(OsFile
*id
, i64 offset
)
508 assert( id
->isOpen
);
509 SEEK(offset
/1024 + 1);
510 lseek(id
->h
, offset
, SEEK_SET
);
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.
520 int sqlite3_sync_count
= 0;
521 int sqlite3_fullsync_count
= 0;
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
535 static int full_fsync(int fd
, int fullSync
)
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.
545 if( fullSync
) sqlite3_fullsync_count
++;
546 sqlite3_sync_count
++;
550 * If we compiled with the SQLITE_NO_SYNC flag, then syncing is a no-op
552 #ifdef SQLITE_NO_SYNC
558 rc
= fcntl(fd
, F_FULLFSYNC
, 0);
561 /* If the FULLSYNC failed, try to do a normal fsync() */
562 if( rc
) rc
= fsync(fd
);
565 #endif /* defined(F_FULLFSYNC) */
566 #endif /* defined(SQLITE_NO_SYNC) */
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.
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
) )
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. */
602 * Sync the directory zDirname. This is a no-op on operating systems other
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.
609 err_t
sqlite3OsSyncDirectory( CONST_STRPTR zDirname
)
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
;
620 return ((r
==0)?SQLITE_OK
:SQLITE_IOERR
);
625 * Truncate an open file to a specified size.
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.
638 err_t
sqlite3OsFileSize(OsFile
*id
, i64
*pSize
)
641 assert( id
->isOpen
);
642 SimulateIOError(SQLITE_IOERR
);
643 if( fstat(id
->h
, &buf
)!=0 )
645 *pSize
= buf
.st_size
;
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.
655 BOOL
sqlite3OsCheckReservedLock(OsFile
*id
)
659 assert( id
->isOpen
);
660 sqlite3OsEnterMutex(); /* Needed because id->pLock is shared across
662 /* Check if a thread in this process holds such a lock */
663 if( id
->pLock
->locktype
> SHARED_LOCK
)
666 /* Otherwise see if some other process holds it. */
671 lock
.l_whence
= SEEK_SET
;
672 lock
.l_start
= RESERVED_BYTE
;
674 lock
.l_type
= F_WRLCK
;
675 fcntl(id
->h
, F_GETLK
, &lock
);
676 if( lock
.l_type
!= F_UNLCK
)
681 sqlite3OsLeaveMutex();
682 TRACE("TEST WR-LOCK %d %d\n", id
->h
, r
);
690 * Helper function for printing out trace information from debugging binaries.
691 * This returns the string represetation of the supplied integer lock-type.
693 static const char * locktypeName(int 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";
709 * Lock the file with the lock specified by parameter locktype - one of the
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:
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.
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
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.
770 struct lockInfo
*pLock
= id
->pLock
;
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.
787 if( id
->locktype
>= locktype
)
789 TRACE("LOCK %d %s ok (already held)\n", id
->h
,
790 locktypeName(locktype
));
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.
806 if( (id
->locktype
!= pLock
->locktype
807 && (pLock
->locktype
>= PENDING_LOCK
808 || locktype
> SHARED_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
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
;
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
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
);
850 rc
= (errno
==EINVAL
) ? SQLITE_NOLFS
: SQLITE_BUSY
;
858 * If control gets to this point, then actually go ahead and make OS calls
859 * for the specified lock.
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
;
874 lock
.l_type
= F_UNLCK
;
876 fcntl(id
->h
, F_SETLK
, &lock
);
879 rc
= (errno
==EINVAL
) ? SQLITE_NOLFS
: SQLITE_BUSY
;
885 id
->locktype
= SHARED_LOCK
;
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.
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.
904 assert( id
->locktype
);
905 lock
.l_type
= F_WRLCK
;
909 lock
.l_start
= RESERVED_BYTE
;
912 lock
.l_start
= SHARED_FIRST
;
913 lock
.l_len
= SHARED_SIZE
;
918 s
= fcntl(id
->h
, F_SETLK
, &lock
);
922 rc
= (errno
==EINVAL
) ? SQLITE_NOLFS
: SQLITE_BUSY
;
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
;
940 sqlite3OsLeaveMutex();
941 TRACE("LOCK %d %s %s\n", id
->h
, locktypeName(locktype
),
942 rc
==SQLITE_OK
? "ok" : "failed");
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.
958 err_t
sqlite3OsUnlock(OsFile
*id
, int locktype
)
960 struct lockInfo
*pLock
;
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
)
972 sqlite3OsEnterMutex();
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
;
985 if( fcntl(id
->h
, F_SETLK
, &lock
)!=0 )
987 /* This should never happen */
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
);
997 fcntl(id
->h
, F_SETLK
, &lock
);
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.
1013 lock
.l_type
= F_UNLCK
;
1014 lock
.l_whence
= SEEK_SET
;
1015 lock
.l_start
= lock
.l_len
= 0L;
1017 fcntl(id
->h
, F_SETLK
, &lock
);
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.
1029 assert( pOpen
->nLock
>= 0 );
1030 if( pOpen
->nLock
==0 && pOpen
->nPending
>0 )
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
;
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
);
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.
1065 struct openCnt
*pOpen
= id
->pOpen
;
1067 aNew
= sqliteRealloc( pOpen
->aPending
, pOpen
->nPending
*sizeof(int) );
1069 ; /* If a malloc fails, just leak the file descriptor */
1072 pOpen
->aPending
= aNew
;
1073 pOpen
->aPending
[pOpen
->nPending
-1] = id
->h
;
1078 /* There are no outstanding locks so we can close the file
1083 releaseLockInfo(id
->pLock
);
1084 releaseOpenCnt(id
->pOpen
);
1085 sqlite3OsLeaveMutex();
1087 TRACE("CLOSE %-3d\n", id
->h
);
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.
1098 char *sqlite3OsFullPathname(CONST_STRPTR zRelative
)
1100 STRPTR zFull
= NULL
;
1102 if( zRelative
[0]=='/' )
1104 sqlite3SetString(&zFull
, zRelative
, NULL
);
1111 sqlite3SetString( &zFull
, getcwd(zBuf
, sizeof(zBuf
)), "/", zRelative
,
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.
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
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
1138 memset(zBuf
, 0, 256);
1139 #if !defined(SQLITE_TEST)
1142 /* See if we can use /dev/urandom for random numbers... */
1143 fd
= open("/dev/urandom", O_RDONLY
);
1146 time((time_t*)zBuf
);
1148 memcpy(&zBuf
[sizeof(time_t)], &pid
, sizeof(pid
));
1152 read(fd
, zBuf
, 256);
1162 * Sleep for a little while. Return the amount of time slept.
1164 int sqlite3OsSleep(int ms
)
1166 #if defined(HAVE_USLEEP) && HAVE_USLEEP
1170 sleep((ms
+999)/1000);
1171 return 1000*((ms
+999)/1000);
1177 * Static variables used for thread synchronization.
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.
1190 void sqlite3OsEnterMutex()
1195 void sqlite3OsLeaveMutex()
1203 * The following variable, if set to a non-zero value, becomes the result
1204 * returned from sqlite3OsCurrentTime(). This is used for testing.
1207 int sqlite3_current_time
= 0;
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.
1216 BOOL
sqlite3OsCurrentTime(double *prNow
)
1220 *prNow
= t
/86400.0 + 2440587.5;
1222 if( sqlite3_current_time
)
1223 *prNow
= sqlite3_current_time
/86400.0 + 2440587.5;
1228 #endif /* OS_AROS */