blob: c2309495eb44e7609f7305146a9011ec98af16f2 [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*/
15#include "os.h" /* Must be first to enable large file support */
16#if OS_UNIX /* This file is used on unix only */
17#include "sqliteInt.h"
18
19
20#include <time.h>
21#include <errno.h>
22#include <unistd.h>
23#ifndef O_LARGEFILE
24# define O_LARGEFILE 0
25#endif
26#ifdef SQLITE_DISABLE_LFS
27# undef O_LARGEFILE
28# define O_LARGEFILE 0
29#endif
30#ifndef O_NOFOLLOW
31# define O_NOFOLLOW 0
32#endif
33#ifndef O_BINARY
34# define O_BINARY 0
35#endif
36
37/*
38** The DJGPP compiler environment looks mostly like Unix, but it
39** lacks the fcntl() system call. So redefine fcntl() to be something
40** that always succeeds. This means that locking does not occur under
41** DJGPP. But its DOS - what did you expect?
42*/
43#ifdef __DJGPP__
44# define fcntl(A,B,C) 0
45#endif
46
47/*
48** Macros used to determine whether or not to use threads. The
49** SQLITE_UNIX_THREADS macro is defined if we are synchronizing for
50** Posix threads and SQLITE_W32_THREADS is defined if we are
51** synchronizing using Win32 threads.
52*/
53#if defined(THREADSAFE) && THREADSAFE
54# include <pthread.h>
55# define SQLITE_UNIX_THREADS 1
56#endif
57
58
59/*
60** Include code that is common to all os_*.c files
61*/
62#include "os_common.h"
63
danielk197713adf8a2004-06-03 16:08:41 +000064#if defined(THREADSAFE) && defined(__linux__)
65#define getpid pthread_self
66#endif
67
drhbbd42a62004-05-22 17:41:58 +000068/*
69** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
70** section 6.5.2.2 lines 483 through 490 specify that when a process
71** sets or clears a lock, that operation overrides any prior locks set
72** by the same process. It does not explicitly say so, but this implies
73** that it overrides locks set by the same process using a different
74** file descriptor. Consider this test case:
75**
76** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
77** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
78**
79** Suppose ./file1 and ./file2 are really the same file (because
80** one is a hard or symbolic link to the other) then if you set
81** an exclusive lock on fd1, then try to get an exclusive lock
82** on fd2, it works. I would have expected the second lock to
83** fail since there was already a lock on the file due to fd1.
84** But not so. Since both locks came from the same process, the
85** second overrides the first, even though they were on different
86** file descriptors opened on different file names.
87**
88** Bummer. If you ask me, this is broken. Badly broken. It means
89** that we cannot use POSIX locks to synchronize file access among
90** competing threads of the same process. POSIX locks will work fine
91** to synchronize access for threads in separate processes, but not
92** threads within the same process.
93**
94** To work around the problem, SQLite has to manage file locks internally
95** on its own. Whenever a new database is opened, we have to find the
96** specific inode of the database file (the inode is determined by the
97** st_dev and st_ino fields of the stat structure that fstat() fills in)
98** and check for locks already existing on that inode. When locks are
99** created or removed, we have to look at our own internal record of the
100** locks to see if another thread has previously set a lock on that same
101** inode.
102**
103** The OsFile structure for POSIX is no longer just an integer file
104** descriptor. It is now a structure that holds the integer file
105** descriptor and a pointer to a structure that describes the internal
106** locks on the corresponding inode. There is one locking structure
107** per inode, so if the same inode is opened twice, both OsFile structures
108** point to the same locking structure. The locking structure keeps
109** a reference count (so we will know when to delete it) and a "cnt"
110** field that tells us its internal lock status. cnt==0 means the
111** file is unlocked. cnt==-1 means the file has an exclusive lock.
112** cnt>0 means there are cnt shared locks on the file.
113**
114** Any attempt to lock or unlock a file first checks the locking
115** structure. The fcntl() system call is only invoked to set a
116** POSIX lock if the internal lock structure transitions between
117** a locked and an unlocked state.
118**
119** 2004-Jan-11:
120** More recent discoveries about POSIX advisory locks. (The more
121** I discover, the more I realize the a POSIX advisory locks are
122** an abomination.)
123**
124** If you close a file descriptor that points to a file that has locks,
125** all locks on that file that are owned by the current process are
126** released. To work around this problem, each OsFile structure contains
127** a pointer to an openCnt structure. There is one openCnt structure
128** per open inode, which means that multiple OsFiles can point to a single
129** openCnt. When an attempt is made to close an OsFile, if there are
130** other OsFiles open on the same inode that are holding locks, the call
131** to close() the file descriptor is deferred until all of the locks clear.
132** The openCnt structure keeps a list of file descriptors that need to
133** be closed and that list is walked (and cleared) when the last lock
134** clears.
135**
136** First, under Linux threads, because each thread has a separate
137** process ID, lock operations in one thread do not override locks
138** to the same file in other threads. Linux threads behave like
139** separate processes in this respect. But, if you close a file
140** descriptor in linux threads, all locks are cleared, even locks
141** on other threads and even though the other threads have different
142** process IDs. Linux threads is inconsistent in this respect.
143** (I'm beginning to think that linux threads is an abomination too.)
144** The consequence of this all is that the hash table for the lockInfo
145** structure has to include the process id as part of its key because
146** locks in different threads are treated as distinct. But the
147** openCnt structure should not include the process id in its
148** key because close() clears lock on all threads, not just the current
149** thread. Were it not for this goofiness in linux threads, we could
150** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000151**
152** 2004-Jun-28:
153** On some versions of linux, threads can override each others locks.
154** On others not. Sometimes you can change the behavior on the same
155** system by setting the LD_ASSUME_KERNEL environment variable. The
156** POSIX standard is silent as to which behavior is correct, as far
157** as I can tell, so other versions of unix might show the same
158** inconsistency. There is no little doubt in my mind that posix
159** advisory locks and linux threads are profoundly broken.
160**
161** To work around the inconsistencies, we have to test at runtime
162** whether or not threads can override each others locks. This test
163** is run once, the first time any lock is attempted. A static
164** variable is set to record the results of this test for future
165** use.
drhbbd42a62004-05-22 17:41:58 +0000166*/
167
168/*
169** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000170** to locate a particular lockInfo structure given its inode.
171**
172** If threads cannot override each others locks, then we set the
173** lockKey.tid field to the thread ID. If threads can override
174** each others locks then tid is always set to zero. tid is also
175** set to zero if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000176*/
177struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000178 dev_t dev; /* Device number */
179 ino_t ino; /* Inode number */
180#ifdef SQLITE_UNIX_THREADS
181 pthread_t tid; /* Thread ID or zero if threads cannot override each other */
182#endif
drhbbd42a62004-05-22 17:41:58 +0000183};
184
185/*
186** An instance of the following structure is allocated for each open
187** inode on each thread with a different process ID. (Threads have
188** different process IDs on linux, but not on most other unixes.)
189**
190** A single inode can have multiple file descriptors, so each OsFile
191** structure contains a pointer to an instance of this object and this
192** object keeps a count of the number of OsFiles pointing to it.
193*/
194struct lockInfo {
195 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000196 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000197 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000198 int nRef; /* Number of pointers to this structure */
199};
200
201/*
202** An instance of the following structure serves as the key used
203** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000204** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000205*/
206struct openKey {
207 dev_t dev; /* Device number */
208 ino_t ino; /* Inode number */
209};
210
211/*
212** An instance of the following structure is allocated for each open
213** inode. This structure keeps track of the number of locks on that
214** inode. If a close is attempted against an inode that is holding
215** locks, the close is deferred until all locks clear by adding the
216** file descriptor to be closed to the pending list.
217*/
218struct openCnt {
219 struct openKey key; /* The lookup key */
220 int nRef; /* Number of pointers to this structure */
221 int nLock; /* Number of outstanding locks */
222 int nPending; /* Number of pending close() operations */
223 int *aPending; /* Malloced space holding fd's awaiting a close() */
224};
225
226/*
227** These hash table maps inodes and process IDs into lockInfo and openCnt
228** structures. Access to these hash tables must be protected by a mutex.
229*/
230static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
231static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
232
drh5fdae772004-06-29 03:29:00 +0000233
234#ifdef SQLITE_UNIX_THREADS
235/*
236** This variable records whether or not threads can override each others
237** locks.
238**
239** 0: No. Threads cannot override each others locks.
240** 1: Yes. Threads can override each others locks.
241** -1: We don't know yet.
242*/
243static int threadsOverrideEachOthersLocks = -1;
244
245/*
246** This structure holds information passed into individual test
247** threads by the testThreadLockingBehavior() routine.
248*/
249struct threadTestData {
250 int fd; /* File to be locked */
251 struct flock lock; /* The locking operation */
252 int result; /* Result of the locking operation */
253};
254
255/*
256** The testThreadLockingBehavior() routine launches two separate
257** threads on this routine. This routine attempts to lock a file
258** descriptor then returns. The success or failure of that attempt
259** allows the testThreadLockingBehavior() procedure to determine
260** whether or not threads can override each others locks.
261*/
262static void *threadLockingTest(void *pArg){
263 struct threadTestData *pData = (struct threadTestData*)pArg;
264 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
265 return pArg;
266}
267
268/*
269** This procedure attempts to determine whether or not threads
270** can override each others locks then sets the
271** threadsOverrideEachOthersLocks variable appropriately.
272*/
273static void testThreadLockingBehavior(fd_orig){
274 int fd;
275 struct threadTestData d[2];
276 pthread_t t[2];
277
278 fd = dup(fd_orig);
279 if( fd<0 ) return;
280 memset(d, 0, sizeof(d));
281 d[0].fd = fd;
282 d[0].lock.l_type = F_RDLCK;
283 d[0].lock.l_len = 1;
284 d[0].lock.l_start = 0;
285 d[0].lock.l_whence = SEEK_SET;
286 d[1] = d[0];
287 d[1].lock.l_type = F_WRLCK;
288 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
289 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
290 pthread_join(t[0], 0);
291 pthread_join(t[1], 0);
292 close(fd);
293 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
294}
295#endif /* SQLITE_UNIX_THREADS */
296
drhbbd42a62004-05-22 17:41:58 +0000297/*
298** Release a lockInfo structure previously allocated by findLockInfo().
299*/
300static void releaseLockInfo(struct lockInfo *pLock){
301 pLock->nRef--;
302 if( pLock->nRef==0 ){
303 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
304 sqliteFree(pLock);
305 }
306}
307
308/*
309** Release a openCnt structure previously allocated by findLockInfo().
310*/
311static void releaseOpenCnt(struct openCnt *pOpen){
312 pOpen->nRef--;
313 if( pOpen->nRef==0 ){
314 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
315 sqliteFree(pOpen->aPending);
316 sqliteFree(pOpen);
317 }
318}
319
320/*
321** Given a file descriptor, locate lockInfo and openCnt structures that
322** describes that file descriptor. Create a new ones if necessary. The
323** return values might be unset if an error occurs.
324**
325** Return the number of errors.
326*/
drh38f82712004-06-18 17:10:16 +0000327static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000328 int fd, /* The file descriptor used in the key */
329 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000330 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000331){
332 int rc;
333 struct lockKey key1;
334 struct openKey key2;
335 struct stat statbuf;
336 struct lockInfo *pLock;
337 struct openCnt *pOpen;
338 rc = fstat(fd, &statbuf);
339 if( rc!=0 ) return 1;
340 memset(&key1, 0, sizeof(key1));
341 key1.dev = statbuf.st_dev;
342 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000343#ifdef SQLITE_UNIX_THREADS
344 if( threadsOverrideEachOthersLocks<0 ){
345 testThreadLockingBehavior(fd);
346 }
347 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
348#endif
drhbbd42a62004-05-22 17:41:58 +0000349 memset(&key2, 0, sizeof(key2));
350 key2.dev = statbuf.st_dev;
351 key2.ino = statbuf.st_ino;
352 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
353 if( pLock==0 ){
354 struct lockInfo *pOld;
355 pLock = sqliteMallocRaw( sizeof(*pLock) );
356 if( pLock==0 ) return 1;
357 pLock->key = key1;
358 pLock->nRef = 1;
359 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000360 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000361 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
362 if( pOld!=0 ){
363 assert( pOld==pLock );
364 sqliteFree(pLock);
365 return 1;
366 }
367 }else{
368 pLock->nRef++;
369 }
370 *ppLock = pLock;
371 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
372 if( pOpen==0 ){
373 struct openCnt *pOld;
374 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
375 if( pOpen==0 ){
376 releaseLockInfo(pLock);
377 return 1;
378 }
379 pOpen->key = key2;
380 pOpen->nRef = 1;
381 pOpen->nLock = 0;
382 pOpen->nPending = 0;
383 pOpen->aPending = 0;
384 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
385 if( pOld!=0 ){
386 assert( pOld==pOpen );
387 sqliteFree(pOpen);
388 releaseLockInfo(pLock);
389 return 1;
390 }
391 }else{
392 pOpen->nRef++;
393 }
394 *ppOpen = pOpen;
395 return 0;
396}
397
398/*
399** Delete the named file
400*/
401int sqlite3OsDelete(const char *zFilename){
402 unlink(zFilename);
403 return SQLITE_OK;
404}
405
406/*
407** Return TRUE if the named file exists.
408*/
409int sqlite3OsFileExists(const char *zFilename){
410 return access(zFilename, 0)==0;
411}
412
413/*
414** Attempt to open a file for both reading and writing. If that
415** fails, try opening it read-only. If the file does not exist,
416** try to create it.
417**
418** On success, a handle for the open file is written to *id
419** and *pReadonly is set to 0 if the file was opened for reading and
420** writing or 1 if the file was opened read-only. The function returns
421** SQLITE_OK.
422**
423** On failure, the function returns SQLITE_CANTOPEN and leaves
424** *id and *pReadonly unchanged.
425*/
426int sqlite3OsOpenReadWrite(
427 const char *zFilename,
428 OsFile *id,
429 int *pReadonly
430){
431 int rc;
drhda71ce12004-06-21 18:14:45 +0000432 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000433 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000434 id->h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY, 0644);
435 if( id->h<0 ){
436 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
437 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000438 return SQLITE_CANTOPEN;
439 }
440 *pReadonly = 1;
441 }else{
442 *pReadonly = 0;
443 }
444 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000445 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000446 sqlite3OsLeaveMutex();
447 if( rc ){
drha6abd042004-06-09 17:37:22 +0000448 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000449 return SQLITE_NOMEM;
450 }
danielk197713adf8a2004-06-03 16:08:41 +0000451 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000452 id->isOpen = 1;
drha6abd042004-06-09 17:37:22 +0000453 TRACE3("OPEN %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000454 OpenCounter(+1);
455 return SQLITE_OK;
456}
457
458
459/*
460** Attempt to open a new file for exclusive access by this process.
461** The file will be opened for both reading and writing. To avoid
462** a potential security problem, we do not allow the file to have
463** previously existed. Nor do we allow the file to be a symbolic
464** link.
465**
466** If delFlag is true, then make arrangements to automatically delete
467** the file when it is closed.
468**
469** On success, write the file handle into *id and return SQLITE_OK.
470**
471** On failure, return SQLITE_CANTOPEN.
472*/
473int sqlite3OsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){
474 int rc;
drhda71ce12004-06-21 18:14:45 +0000475 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000476 if( access(zFilename, 0)==0 ){
477 return SQLITE_CANTOPEN;
478 }
479 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000480 id->h = open(zFilename,
drhbbd42a62004-05-22 17:41:58 +0000481 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY, 0600);
drha6abd042004-06-09 17:37:22 +0000482 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000483 return SQLITE_CANTOPEN;
484 }
485 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000486 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000487 sqlite3OsLeaveMutex();
488 if( rc ){
drha6abd042004-06-09 17:37:22 +0000489 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000490 unlink(zFilename);
491 return SQLITE_NOMEM;
492 }
danielk197713adf8a2004-06-03 16:08:41 +0000493 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000494 id->isOpen = 1;
drhbbd42a62004-05-22 17:41:58 +0000495 if( delFlag ){
496 unlink(zFilename);
497 }
drha6abd042004-06-09 17:37:22 +0000498 TRACE3("OPEN-EX %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000499 OpenCounter(+1);
500 return SQLITE_OK;
501}
502
503/*
504** Attempt to open a new file for read-only access.
505**
506** On success, write the file handle into *id and return SQLITE_OK.
507**
508** On failure, return SQLITE_CANTOPEN.
509*/
510int sqlite3OsOpenReadOnly(const char *zFilename, OsFile *id){
511 int rc;
drhda71ce12004-06-21 18:14:45 +0000512 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000513 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000514 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
515 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000516 return SQLITE_CANTOPEN;
517 }
518 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000519 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000520 sqlite3OsLeaveMutex();
521 if( rc ){
drha6abd042004-06-09 17:37:22 +0000522 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000523 return SQLITE_NOMEM;
524 }
danielk197713adf8a2004-06-03 16:08:41 +0000525 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000526 id->isOpen = 1;
drha6abd042004-06-09 17:37:22 +0000527 TRACE3("OPEN-RO %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000528 OpenCounter(+1);
529 return SQLITE_OK;
530}
531
532/*
533** Attempt to open a file descriptor for the directory that contains a
534** file. This file descriptor can be used to fsync() the directory
535** in order to make sure the creation of a new file is actually written
536** to disk.
537**
538** This routine is only meaningful for Unix. It is a no-op under
539** windows since windows does not support hard links.
540**
541** On success, a handle for a previously open file is at *id is
542** updated with the new directory file descriptor and SQLITE_OK is
543** returned.
544**
545** On failure, the function returns SQLITE_CANTOPEN and leaves
546** *id unchanged.
547*/
548int sqlite3OsOpenDirectory(
549 const char *zDirname,
550 OsFile *id
551){
drhda71ce12004-06-21 18:14:45 +0000552 if( !id->isOpen ){
drhbbd42a62004-05-22 17:41:58 +0000553 /* Do not open the directory if the corresponding file is not already
554 ** open. */
555 return SQLITE_CANTOPEN;
556 }
557 assert( id->dirfd<0 );
558 id->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0644);
559 if( id->dirfd<0 ){
560 return SQLITE_CANTOPEN;
561 }
562 TRACE3("OPENDIR %-3d %s\n", id->dirfd, zDirname);
563 return SQLITE_OK;
564}
565
566/*
567** Create a temporary file name in zBuf. zBuf must be big enough to
568** hold at least SQLITE_TEMPNAME_SIZE characters.
569*/
570int sqlite3OsTempFileName(char *zBuf){
571 static const char *azDirs[] = {
572 "/var/tmp",
573 "/usr/tmp",
574 "/tmp",
575 ".",
576 };
577 static unsigned char zChars[] =
578 "abcdefghijklmnopqrstuvwxyz"
579 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
580 "0123456789";
581 int i, j;
582 struct stat buf;
583 const char *zDir = ".";
584 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
585 if( stat(azDirs[i], &buf) ) continue;
586 if( !S_ISDIR(buf.st_mode) ) continue;
587 if( access(azDirs[i], 07) ) continue;
588 zDir = azDirs[i];
589 break;
590 }
591 do{
592 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
593 j = strlen(zBuf);
594 sqlite3Randomness(15, &zBuf[j]);
595 for(i=0; i<15; i++, j++){
596 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
597 }
598 zBuf[j] = 0;
599 }while( access(zBuf,0)==0 );
600 return SQLITE_OK;
601}
602
603/*
drhbbd42a62004-05-22 17:41:58 +0000604** Read data from a file into a buffer. Return SQLITE_OK if all
605** bytes were read successfully and SQLITE_IOERR if anything goes
606** wrong.
607*/
608int sqlite3OsRead(OsFile *id, void *pBuf, int amt){
609 int got;
drhda71ce12004-06-21 18:14:45 +0000610 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000611 SimulateIOError(SQLITE_IOERR);
612 TIMER_START;
drha6abd042004-06-09 17:37:22 +0000613 got = read(id->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000614 TIMER_END;
drha6abd042004-06-09 17:37:22 +0000615 TRACE4("READ %-3d %7d %d\n", id->h, last_page, elapse);
drhbbd42a62004-05-22 17:41:58 +0000616 SEEK(0);
617 /* if( got<0 ) got = 0; */
618 if( got==amt ){
619 return SQLITE_OK;
620 }else{
621 return SQLITE_IOERR;
622 }
623}
624
625/*
626** Write data from a buffer into a file. Return SQLITE_OK on success
627** or some other error code on failure.
628*/
629int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
630 int wrote = 0;
drhda71ce12004-06-21 18:14:45 +0000631 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000632 SimulateIOError(SQLITE_IOERR);
633 TIMER_START;
drha6abd042004-06-09 17:37:22 +0000634 while( amt>0 && (wrote = write(id->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000635 amt -= wrote;
636 pBuf = &((char*)pBuf)[wrote];
637 }
638 TIMER_END;
drha6abd042004-06-09 17:37:22 +0000639 TRACE4("WRITE %-3d %7d %d\n", id->h, last_page, elapse);
drhbbd42a62004-05-22 17:41:58 +0000640 SEEK(0);
641 if( amt>0 ){
642 return SQLITE_FULL;
643 }
644 return SQLITE_OK;
645}
646
647/*
648** Move the read/write pointer in a file.
649*/
650int sqlite3OsSeek(OsFile *id, off_t offset){
drhda71ce12004-06-21 18:14:45 +0000651 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000652 SEEK(offset/1024 + 1);
drha6abd042004-06-09 17:37:22 +0000653 lseek(id->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000654 return SQLITE_OK;
655}
656
657/*
658** Make sure all writes to a particular file are committed to disk.
659**
660** Under Unix, also make sure that the directory entry for the file
661** has been created by fsync-ing the directory that contains the file.
662** If we do not do this and we encounter a power failure, the directory
663** entry for the journal might not exist after we reboot. The next
664** SQLite to access the file will not know that the journal exists (because
665** the directory entry for the journal was never created) and the transaction
666** will not roll back - possibly leading to database corruption.
667*/
668int sqlite3OsSync(OsFile *id){
drhda71ce12004-06-21 18:14:45 +0000669 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000670 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000671 TRACE2("SYNC %-3d\n", id->h);
672 if( fsync(id->h) ){
drhbbd42a62004-05-22 17:41:58 +0000673 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000674 }
drha2854222004-06-17 19:04:17 +0000675 if( id->dirfd>=0 ){
676 TRACE2("DIRSYNC %-3d\n", id->dirfd);
677 fsync(id->dirfd);
678 close(id->dirfd); /* Only need to sync once, so close the directory */
679 id->dirfd = -1; /* when we are done. */
680 }
drha2854222004-06-17 19:04:17 +0000681 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +0000682}
683
684/*
danielk1977962398d2004-06-14 09:35:16 +0000685** Sync the directory zDirname. This is a no-op on operating systems other
686** than UNIX.
687*/
688int sqlite3OsSyncDirectory(const char *zDirname){
689 int fd;
690 int r;
danielk1977369f27e2004-06-15 11:40:04 +0000691 SimulateIOError(SQLITE_IOERR);
danielk1977962398d2004-06-14 09:35:16 +0000692 fd = open(zDirname, O_RDONLY|O_BINARY, 0644);
danielk1977369f27e2004-06-15 11:40:04 +0000693 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +0000694 if( fd<0 ){
695 return SQLITE_CANTOPEN;
696 }
697 r = fsync(fd);
698 close(fd);
699 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
700}
701
702/*
drhbbd42a62004-05-22 17:41:58 +0000703** Truncate an open file to a specified size
704*/
705int sqlite3OsTruncate(OsFile *id, off_t nByte){
drhda71ce12004-06-21 18:14:45 +0000706 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000707 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000708 return ftruncate(id->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000709}
710
711/*
712** Determine the current size of a file in bytes
713*/
714int sqlite3OsFileSize(OsFile *id, off_t *pSize){
715 struct stat buf;
drhda71ce12004-06-21 18:14:45 +0000716 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000717 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000718 if( fstat(id->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +0000719 return SQLITE_IOERR;
720 }
721 *pSize = buf.st_size;
722 return SQLITE_OK;
723}
724
danielk19779a1d0ab2004-06-01 14:09:28 +0000725/*
danielk197713adf8a2004-06-03 16:08:41 +0000726** This routine checks if there is a RESERVED lock held on the specified
727** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +0000728** non-zero. If the file is unlocked or holds only SHARED locks, then
729** return zero.
danielk197713adf8a2004-06-03 16:08:41 +0000730*/
drha6abd042004-06-09 17:37:22 +0000731int sqlite3OsCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +0000732 int r = 0;
733
drhda71ce12004-06-21 18:14:45 +0000734 assert( id->isOpen );
drh2ac3ee92004-06-07 16:27:46 +0000735 sqlite3OsEnterMutex(); /* Needed because id->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000736
737 /* Check if a thread in this process holds such a lock */
738 if( id->pLock->locktype>SHARED_LOCK ){
739 r = 1;
740 }
741
drh2ac3ee92004-06-07 16:27:46 +0000742 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000743 */
744 if( !r ){
745 struct flock lock;
746 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000747 lock.l_start = RESERVED_BYTE;
748 lock.l_len = 1;
749 lock.l_type = F_WRLCK;
drha6abd042004-06-09 17:37:22 +0000750 fcntl(id->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +0000751 if( lock.l_type!=F_UNLCK ){
752 r = 1;
753 }
754 }
755
756 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +0000757 TRACE3("TEST WR-LOCK %d %d\n", id->h, r);
danielk197713adf8a2004-06-03 16:08:41 +0000758
759 return r;
760}
761
762/*
danielk19779a1d0ab2004-06-01 14:09:28 +0000763** Lock the file with the lock specified by parameter locktype - one
764** of the following:
765**
drh2ac3ee92004-06-07 16:27:46 +0000766** (1) SHARED_LOCK
767** (2) RESERVED_LOCK
768** (3) PENDING_LOCK
769** (4) EXCLUSIVE_LOCK
770**
drhb3e04342004-06-08 00:47:47 +0000771** Sometimes when requesting one lock state, additional lock states
772** are inserted in between. The locking might fail on one of the later
773** transitions leaving the lock state different from what it started but
774** still short of its goal. The following chart shows the allowed
775** transitions and the inserted intermediate states:
776**
777** UNLOCKED -> SHARED
778** SHARED -> RESERVED
779** SHARED -> (PENDING) -> EXCLUSIVE
780** RESERVED -> (PENDING) -> EXCLUSIVE
781** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +0000782**
drha6abd042004-06-09 17:37:22 +0000783** This routine will only increase a lock. Use the sqlite3OsUnlock()
784** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +0000785*/
786int sqlite3OsLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +0000787 /* The following describes the implementation of the various locks and
788 ** lock transitions in terms of the POSIX advisory shared and exclusive
789 ** lock primitives (called read-locks and write-locks below, to avoid
790 ** confusion with SQLite lock names). The algorithms are complicated
791 ** slightly in order to be compatible with windows systems simultaneously
792 ** accessing the same database file, in case that is ever required.
793 **
794 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
795 ** byte', each single bytes at well known offsets, and the 'shared byte
796 ** range', a range of 510 bytes at a well known offset.
797 **
798 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
799 ** byte'. If this is successful, a random byte from the 'shared byte
800 ** range' is read-locked and the lock on the 'pending byte' released.
801 **
danielk197790ba3bd2004-06-25 08:32:25 +0000802 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
803 ** A RESERVED lock is implemented by grabbing a write-lock on the
804 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +0000805 **
806 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +0000807 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
808 ** on the 'pending byte'. This ensures that no new SHARED locks can be
809 ** obtained, but existing SHARED locks are allowed to persist. A process
810 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
811 ** This property is used by the algorithm for rolling back a journal file
812 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +0000813 **
danielk197790ba3bd2004-06-25 08:32:25 +0000814 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
815 ** implemented by obtaining a write-lock on the entire 'shared byte
816 ** range'. Since all other locks require a read-lock on one of the bytes
817 ** within this range, this ensures that no other locks are held on the
818 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +0000819 **
820 ** The reason a single byte cannot be used instead of the 'shared byte
821 ** range' is that some versions of windows do not support read-locks. By
822 ** locking a random byte from a range, concurrent SHARED locks may exist
823 ** even if the locking primitive used is always a write-lock.
824 */
danielk19779a1d0ab2004-06-01 14:09:28 +0000825 int rc = SQLITE_OK;
826 struct lockInfo *pLock = id->pLock;
827 struct flock lock;
828 int s;
829
drhda71ce12004-06-21 18:14:45 +0000830 assert( id->isOpen );
drha6abd042004-06-09 17:37:22 +0000831 TRACE6("LOCK %d %d was %d(%d,%d)\n",
832 id->h, locktype, id->locktype, pLock->locktype, pLock->cnt);
danielk19779a1d0ab2004-06-01 14:09:28 +0000833
834 /* If there is already a lock of this type or more restrictive on the
835 ** OsFile, do nothing. Don't use the end_lock: exit path, as
836 ** sqlite3OsEnterMutex() hasn't been called yet.
837 */
danielk197713adf8a2004-06-03 16:08:41 +0000838 if( id->locktype>=locktype ){
danielk19779a1d0ab2004-06-01 14:09:28 +0000839 return SQLITE_OK;
840 }
841
drhb3e04342004-06-08 00:47:47 +0000842 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +0000843 */
drhb3e04342004-06-08 00:47:47 +0000844 assert( id->locktype!=NO_LOCK || locktype==SHARED_LOCK );
845 assert( locktype!=PENDING_LOCK );
846 assert( locktype!=RESERVED_LOCK || id->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +0000847
drhb3e04342004-06-08 00:47:47 +0000848 /* This mutex is needed because id->pLock is shared across threads
849 */
850 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +0000851
852 /* If some thread using this PID has a lock via a different OsFile*
853 ** handle that precludes the requested lock, return BUSY.
854 */
danielk197713adf8a2004-06-03 16:08:41 +0000855 if( (id->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +0000856 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +0000857 ){
858 rc = SQLITE_BUSY;
859 goto end_lock;
860 }
861
862 /* If a SHARED lock is requested, and some thread using this PID already
863 ** has a SHARED or RESERVED lock, then increment reference counts and
864 ** return SQLITE_OK.
865 */
866 if( locktype==SHARED_LOCK &&
867 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
868 assert( locktype==SHARED_LOCK );
danielk197713adf8a2004-06-03 16:08:41 +0000869 assert( id->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +0000870 assert( pLock->cnt>0 );
danielk197713adf8a2004-06-03 16:08:41 +0000871 id->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +0000872 pLock->cnt++;
873 id->pOpen->nLock++;
874 goto end_lock;
875 }
876
danielk197713adf8a2004-06-03 16:08:41 +0000877 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +0000878 lock.l_whence = SEEK_SET;
879
drh3cde3bb2004-06-12 02:17:14 +0000880 /* A PENDING lock is needed before acquiring a SHARED lock and before
881 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
882 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +0000883 */
drh3cde3bb2004-06-12 02:17:14 +0000884 if( locktype==SHARED_LOCK
885 || (locktype==EXCLUSIVE_LOCK && id->locktype<PENDING_LOCK)
886 ){
danielk1977489468c2004-06-28 08:25:47 +0000887 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +0000888 lock.l_start = PENDING_BYTE;
drha6abd042004-06-09 17:37:22 +0000889 s = fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000890 if( s ){
891 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
892 goto end_lock;
893 }
drh3cde3bb2004-06-12 02:17:14 +0000894 }
895
896
897 /* If control gets to this point, then actually go ahead and make
898 ** operating system calls for the specified lock.
899 */
900 if( locktype==SHARED_LOCK ){
901 assert( pLock->cnt==0 );
902 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +0000903
drh2ac3ee92004-06-07 16:27:46 +0000904 /* Now get the read-lock */
905 lock.l_start = SHARED_FIRST;
906 lock.l_len = SHARED_SIZE;
drha6abd042004-06-09 17:37:22 +0000907 s = fcntl(id->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +0000908
909 /* Drop the temporary PENDING lock */
910 lock.l_start = PENDING_BYTE;
911 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +0000912 lock.l_type = F_UNLCK;
drha6abd042004-06-09 17:37:22 +0000913 fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000914 if( s ){
drhbbd42a62004-05-22 17:41:58 +0000915 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
916 }else{
danielk197713adf8a2004-06-03 16:08:41 +0000917 id->locktype = SHARED_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +0000918 id->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +0000919 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +0000920 }
drh3cde3bb2004-06-12 02:17:14 +0000921 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
922 /* We are trying for an exclusive lock but another thread in this
923 ** same process is still holding a shared lock. */
924 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +0000925 }else{
drh3cde3bb2004-06-12 02:17:14 +0000926 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +0000927 ** assumed that there is a SHARED or greater lock on the file
928 ** already.
929 */
danielk197713adf8a2004-06-03 16:08:41 +0000930 assert( 0!=id->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +0000931 lock.l_type = F_WRLCK;
932 switch( locktype ){
933 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +0000934 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +0000935 break;
danielk19779a1d0ab2004-06-01 14:09:28 +0000936 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +0000937 lock.l_start = SHARED_FIRST;
938 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +0000939 break;
940 default:
941 assert(0);
942 }
drha6abd042004-06-09 17:37:22 +0000943 s = fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000944 if( s ){
945 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
946 }
drhbbd42a62004-05-22 17:41:58 +0000947 }
danielk19779a1d0ab2004-06-01 14:09:28 +0000948
danielk1977ecb2a962004-06-02 06:30:16 +0000949 if( rc==SQLITE_OK ){
danielk197713adf8a2004-06-03 16:08:41 +0000950 id->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +0000951 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +0000952 }else if( locktype==EXCLUSIVE_LOCK ){
953 id->locktype = PENDING_LOCK;
954 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +0000955 }
danielk19779a1d0ab2004-06-01 14:09:28 +0000956
957end_lock:
drhbbd42a62004-05-22 17:41:58 +0000958 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +0000959 TRACE4("LOCK %d %d %s\n", id->h, locktype, rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +0000960 return rc;
961}
962
963/*
drha6abd042004-06-09 17:37:22 +0000964** Lower the locking level on file descriptor id to locktype. locktype
965** must be either NO_LOCK or SHARED_LOCK.
966**
967** If the locking level of the file descriptor is already at or below
968** the requested locking level, this routine is a no-op.
969**
970** It is not possible for this routine to fail.
drhbbd42a62004-05-22 17:41:58 +0000971*/
drha6abd042004-06-09 17:37:22 +0000972int sqlite3OsUnlock(OsFile *id, int locktype){
973 struct lockInfo *pLock;
974 struct flock lock;
975
drhda71ce12004-06-21 18:14:45 +0000976 assert( id->isOpen );
drha6abd042004-06-09 17:37:22 +0000977 TRACE6("UNLOCK %d %d was %d(%d,%d)\n",
978 id->h, locktype, id->locktype, id->pLock->locktype, id->pLock->cnt);
979
980 assert( locktype<=SHARED_LOCK );
981 if( id->locktype<=locktype ){
982 return SQLITE_OK;
983 }
drhbbd42a62004-05-22 17:41:58 +0000984 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000985 pLock = id->pLock;
986 assert( pLock->cnt!=0 );
987 if( id->locktype>SHARED_LOCK ){
988 assert( pLock->locktype==id->locktype );
drhbbd42a62004-05-22 17:41:58 +0000989 lock.l_type = F_UNLCK;
990 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +0000991 lock.l_start = PENDING_BYTE;
992 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
993 fcntl(id->h, F_SETLK, &lock);
994 pLock->locktype = SHARED_LOCK;
drhbbd42a62004-05-22 17:41:58 +0000995 }
drha6abd042004-06-09 17:37:22 +0000996 if( locktype==NO_LOCK ){
997 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +0000998
drha6abd042004-06-09 17:37:22 +0000999 /* Decrement the shared lock counter. Release the lock using an
1000 ** OS call only when all threads in this same process have released
1001 ** the lock.
1002 */
1003 pLock->cnt--;
1004 if( pLock->cnt==0 ){
1005 lock.l_type = F_UNLCK;
1006 lock.l_whence = SEEK_SET;
1007 lock.l_start = lock.l_len = 0L;
1008 fcntl(id->h, F_SETLK, &lock);
1009 pLock->locktype = NO_LOCK;
1010 }
1011
drhbbd42a62004-05-22 17:41:58 +00001012 /* Decrement the count of locks against this same file. When the
1013 ** count reaches zero, close any other file descriptors whose close
1014 ** was deferred because of outstanding locks.
1015 */
drha6abd042004-06-09 17:37:22 +00001016 pOpen = id->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001017 pOpen->nLock--;
1018 assert( pOpen->nLock>=0 );
1019 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1020 int i;
1021 for(i=0; i<pOpen->nPending; i++){
1022 close(pOpen->aPending[i]);
1023 }
1024 sqliteFree(pOpen->aPending);
1025 pOpen->nPending = 0;
1026 pOpen->aPending = 0;
1027 }
1028 }
1029 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +00001030 id->locktype = locktype;
1031 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001032}
1033
1034/*
danielk1977e3026632004-06-22 11:29:02 +00001035** Close a file.
1036*/
1037int sqlite3OsClose(OsFile *id){
1038 if( !id->isOpen ) return SQLITE_OK;
1039 sqlite3OsUnlock(id, NO_LOCK);
1040 if( id->dirfd>=0 ) close(id->dirfd);
1041 id->dirfd = -1;
1042 sqlite3OsEnterMutex();
1043 if( id->pOpen->nLock ){
1044 /* If there are outstanding locks, do not actually close the file just
1045 ** yet because that would clear those locks. Instead, add the file
1046 ** descriptor to pOpen->aPending. It will be automatically closed when
1047 ** the last lock is cleared.
1048 */
1049 int *aNew;
1050 struct openCnt *pOpen = id->pOpen;
1051 pOpen->nPending++;
1052 aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) );
1053 if( aNew==0 ){
1054 /* If a malloc fails, just leak the file descriptor */
1055 }else{
1056 pOpen->aPending = aNew;
1057 pOpen->aPending[pOpen->nPending-1] = id->h;
1058 }
1059 }else{
1060 /* There are no outstanding locks so we can close the file immediately */
1061 close(id->h);
1062 }
1063 releaseLockInfo(id->pLock);
1064 releaseOpenCnt(id->pOpen);
1065 sqlite3OsLeaveMutex();
1066 id->isOpen = 0;
1067 TRACE2("CLOSE %-3d\n", id->h);
1068 OpenCounter(-1);
1069 return SQLITE_OK;
1070}
1071
1072/*
drhbbd42a62004-05-22 17:41:58 +00001073** Get information to seed the random number generator. The seed
1074** is written into the buffer zBuf[256]. The calling function must
1075** supply a sufficiently large buffer.
1076*/
1077int sqlite3OsRandomSeed(char *zBuf){
1078 /* We have to initialize zBuf to prevent valgrind from reporting
1079 ** errors. The reports issued by valgrind are incorrect - we would
1080 ** prefer that the randomness be increased by making use of the
1081 ** uninitialized space in zBuf - but valgrind errors tend to worry
1082 ** some users. Rather than argue, it seems easier just to initialize
1083 ** the whole array and silence valgrind, even if that means less randomness
1084 ** in the random seed.
1085 **
1086 ** When testing, initializing zBuf[] to zero is all we do. That means
1087 ** that we always use the same random number sequence.* This makes the
1088 ** tests repeatable.
1089 */
1090 memset(zBuf, 0, 256);
1091#if !defined(SQLITE_TEST)
1092 {
1093 int pid;
1094 time((time_t*)zBuf);
1095 pid = getpid();
1096 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1097 }
1098#endif
1099 return SQLITE_OK;
1100}
1101
1102/*
1103** Sleep for a little while. Return the amount of time slept.
1104*/
1105int sqlite3OsSleep(int ms){
1106#if defined(HAVE_USLEEP) && HAVE_USLEEP
1107 usleep(ms*1000);
1108 return ms;
1109#else
1110 sleep((ms+999)/1000);
1111 return 1000*((ms+999)/1000);
1112#endif
1113}
1114
1115/*
1116** Static variables used for thread synchronization
1117*/
1118static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001119#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +00001120static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +00001121#endif
drhbbd42a62004-05-22 17:41:58 +00001122
1123/*
1124** The following pair of routine implement mutual exclusion for
1125** multi-threaded processes. Only a single thread is allowed to
1126** executed code that is surrounded by EnterMutex() and LeaveMutex().
1127**
1128** SQLite uses only a single Mutex. There is not much critical
1129** code and what little there is executes quickly and without blocking.
1130*/
1131void sqlite3OsEnterMutex(){
1132#ifdef SQLITE_UNIX_THREADS
1133 pthread_mutex_lock(&mutex);
1134#endif
1135 assert( !inMutex );
1136 inMutex = 1;
1137}
1138void sqlite3OsLeaveMutex(){
1139 assert( inMutex );
1140 inMutex = 0;
1141#ifdef SQLITE_UNIX_THREADS
1142 pthread_mutex_unlock(&mutex);
1143#endif
1144}
1145
1146/*
1147** Turn a relative pathname into a full pathname. Return a pointer
1148** to the full pathname stored in space obtained from sqliteMalloc().
1149** The calling function is responsible for freeing this space once it
1150** is no longer needed.
1151*/
1152char *sqlite3OsFullPathname(const char *zRelative){
1153 char *zFull = 0;
1154 if( zRelative[0]=='/' ){
1155 sqlite3SetString(&zFull, zRelative, (char*)0);
1156 }else{
1157 char zBuf[5000];
1158 sqlite3SetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative,
1159 (char*)0);
1160 }
1161 return zFull;
1162}
1163
1164/*
1165** The following variable, if set to a non-zero value, becomes the result
1166** returned from sqlite3OsCurrentTime(). This is used for testing.
1167*/
1168#ifdef SQLITE_TEST
1169int sqlite3_current_time = 0;
1170#endif
1171
1172/*
1173** Find the current time (in Universal Coordinated Time). Write the
1174** current time and date as a Julian Day number into *prNow and
1175** return 0. Return 1 if the time and date cannot be found.
1176*/
1177int sqlite3OsCurrentTime(double *prNow){
1178 time_t t;
1179 time(&t);
1180 *prNow = t/86400.0 + 2440587.5;
1181#ifdef SQLITE_TEST
1182 if( sqlite3_current_time ){
1183 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1184 }
1185#endif
1186 return 0;
1187}
1188
drhbf9a7e42004-06-15 00:29:03 +00001189/*
1190** Find the time that the file was last modified. Write the
1191** modification time and date as a Julian Day number into *prNow and
1192** return SQLITE_OK. Return SQLITE_ERROR if the modification
1193** time cannot be found.
1194*/
1195int sqlite3OsFileModTime(OsFile *id, double *prNow){
1196 int rc;
1197 struct stat statbuf;
1198 if( fstat(id->h, &statbuf)==0 ){
1199 *prNow = statbuf.st_mtime/86400.0 + 2440587.5;
1200 rc = SQLITE_OK;
1201 }else{
1202 rc = SQLITE_ERROR;
1203 }
1204 return rc;
1205}
1206
drhbbd42a62004-05-22 17:41:58 +00001207#endif /* OS_UNIX */