blob: 4d6039161d21fab7fd6f1d61fda26730894788bd [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
drh0bb132b2004-07-20 14:06:51 +000064#if defined(THREADSAFE) && THREADSAFE && defined(__linux__)
danielk197713adf8a2004-06-03 16:08:41 +000065#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 ){
drh6458e392004-07-20 01:14:13 +0000436#ifdef EISDIR
437 if( errno==EISDIR ){
438 return SQLITE_CANTOPEN;
439 }
440#endif
drha6abd042004-06-09 17:37:22 +0000441 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
442 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000443 return SQLITE_CANTOPEN;
444 }
445 *pReadonly = 1;
446 }else{
447 *pReadonly = 0;
448 }
449 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000450 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000451 sqlite3OsLeaveMutex();
452 if( rc ){
drha6abd042004-06-09 17:37:22 +0000453 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000454 return SQLITE_NOMEM;
455 }
danielk197713adf8a2004-06-03 16:08:41 +0000456 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000457 id->isOpen = 1;
drha6abd042004-06-09 17:37:22 +0000458 TRACE3("OPEN %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000459 OpenCounter(+1);
460 return SQLITE_OK;
461}
462
463
464/*
465** Attempt to open a new file for exclusive access by this process.
466** The file will be opened for both reading and writing. To avoid
467** a potential security problem, we do not allow the file to have
468** previously existed. Nor do we allow the file to be a symbolic
469** link.
470**
471** If delFlag is true, then make arrangements to automatically delete
472** the file when it is closed.
473**
474** On success, write the file handle into *id and return SQLITE_OK.
475**
476** On failure, return SQLITE_CANTOPEN.
477*/
478int sqlite3OsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){
479 int rc;
drhda71ce12004-06-21 18:14:45 +0000480 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000481 if( access(zFilename, 0)==0 ){
482 return SQLITE_CANTOPEN;
483 }
484 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000485 id->h = open(zFilename,
drhbbd42a62004-05-22 17:41:58 +0000486 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY, 0600);
drha6abd042004-06-09 17:37:22 +0000487 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000488 return SQLITE_CANTOPEN;
489 }
490 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000491 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000492 sqlite3OsLeaveMutex();
493 if( rc ){
drha6abd042004-06-09 17:37:22 +0000494 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000495 unlink(zFilename);
496 return SQLITE_NOMEM;
497 }
danielk197713adf8a2004-06-03 16:08:41 +0000498 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000499 id->isOpen = 1;
drhbbd42a62004-05-22 17:41:58 +0000500 if( delFlag ){
501 unlink(zFilename);
502 }
drha6abd042004-06-09 17:37:22 +0000503 TRACE3("OPEN-EX %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000504 OpenCounter(+1);
505 return SQLITE_OK;
506}
507
508/*
509** Attempt to open a new file for read-only access.
510**
511** On success, write the file handle into *id and return SQLITE_OK.
512**
513** On failure, return SQLITE_CANTOPEN.
514*/
515int sqlite3OsOpenReadOnly(const char *zFilename, OsFile *id){
516 int rc;
drhda71ce12004-06-21 18:14:45 +0000517 assert( !id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000518 id->dirfd = -1;
drha6abd042004-06-09 17:37:22 +0000519 id->h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
520 if( id->h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000521 return SQLITE_CANTOPEN;
522 }
523 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +0000524 rc = findLockInfo(id->h, &id->pLock, &id->pOpen);
drhbbd42a62004-05-22 17:41:58 +0000525 sqlite3OsLeaveMutex();
526 if( rc ){
drha6abd042004-06-09 17:37:22 +0000527 close(id->h);
drhbbd42a62004-05-22 17:41:58 +0000528 return SQLITE_NOMEM;
529 }
danielk197713adf8a2004-06-03 16:08:41 +0000530 id->locktype = 0;
drhda71ce12004-06-21 18:14:45 +0000531 id->isOpen = 1;
drha6abd042004-06-09 17:37:22 +0000532 TRACE3("OPEN-RO %-3d %s\n", id->h, zFilename);
drhbbd42a62004-05-22 17:41:58 +0000533 OpenCounter(+1);
534 return SQLITE_OK;
535}
536
537/*
538** Attempt to open a file descriptor for the directory that contains a
539** file. This file descriptor can be used to fsync() the directory
540** in order to make sure the creation of a new file is actually written
541** to disk.
542**
543** This routine is only meaningful for Unix. It is a no-op under
544** windows since windows does not support hard links.
545**
546** On success, a handle for a previously open file is at *id is
547** updated with the new directory file descriptor and SQLITE_OK is
548** returned.
549**
550** On failure, the function returns SQLITE_CANTOPEN and leaves
551** *id unchanged.
552*/
553int sqlite3OsOpenDirectory(
554 const char *zDirname,
555 OsFile *id
556){
drhda71ce12004-06-21 18:14:45 +0000557 if( !id->isOpen ){
drhbbd42a62004-05-22 17:41:58 +0000558 /* Do not open the directory if the corresponding file is not already
559 ** open. */
560 return SQLITE_CANTOPEN;
561 }
562 assert( id->dirfd<0 );
563 id->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0644);
564 if( id->dirfd<0 ){
565 return SQLITE_CANTOPEN;
566 }
567 TRACE3("OPENDIR %-3d %s\n", id->dirfd, zDirname);
568 return SQLITE_OK;
569}
570
571/*
572** Create a temporary file name in zBuf. zBuf must be big enough to
573** hold at least SQLITE_TEMPNAME_SIZE characters.
574*/
575int sqlite3OsTempFileName(char *zBuf){
576 static const char *azDirs[] = {
577 "/var/tmp",
578 "/usr/tmp",
579 "/tmp",
580 ".",
581 };
582 static unsigned char zChars[] =
583 "abcdefghijklmnopqrstuvwxyz"
584 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
585 "0123456789";
586 int i, j;
587 struct stat buf;
588 const char *zDir = ".";
589 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
590 if( stat(azDirs[i], &buf) ) continue;
591 if( !S_ISDIR(buf.st_mode) ) continue;
592 if( access(azDirs[i], 07) ) continue;
593 zDir = azDirs[i];
594 break;
595 }
596 do{
597 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
598 j = strlen(zBuf);
599 sqlite3Randomness(15, &zBuf[j]);
600 for(i=0; i<15; i++, j++){
601 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
602 }
603 zBuf[j] = 0;
604 }while( access(zBuf,0)==0 );
605 return SQLITE_OK;
606}
607
608/*
drhbbd42a62004-05-22 17:41:58 +0000609** Read data from a file into a buffer. Return SQLITE_OK if all
610** bytes were read successfully and SQLITE_IOERR if anything goes
611** wrong.
612*/
613int sqlite3OsRead(OsFile *id, void *pBuf, int amt){
614 int got;
drhda71ce12004-06-21 18:14:45 +0000615 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000616 SimulateIOError(SQLITE_IOERR);
617 TIMER_START;
drha6abd042004-06-09 17:37:22 +0000618 got = read(id->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000619 TIMER_END;
drha9600bc2004-08-04 14:44:33 +0000620 TRACE4("READ %-3d %7d %d\n", id->h, last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000621 SEEK(0);
622 /* if( got<0 ) got = 0; */
623 if( got==amt ){
624 return SQLITE_OK;
625 }else{
626 return SQLITE_IOERR;
627 }
628}
629
630/*
631** Write data from a buffer into a file. Return SQLITE_OK on success
632** or some other error code on failure.
633*/
634int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
635 int wrote = 0;
drhda71ce12004-06-21 18:14:45 +0000636 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000637 SimulateIOError(SQLITE_IOERR);
638 TIMER_START;
drha6abd042004-06-09 17:37:22 +0000639 while( amt>0 && (wrote = write(id->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000640 amt -= wrote;
641 pBuf = &((char*)pBuf)[wrote];
642 }
643 TIMER_END;
drha9600bc2004-08-04 14:44:33 +0000644 TRACE4("WRITE %-3d %7d %d\n", id->h, last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000645 SEEK(0);
646 if( amt>0 ){
647 return SQLITE_FULL;
648 }
649 return SQLITE_OK;
650}
651
652/*
653** Move the read/write pointer in a file.
654*/
655int sqlite3OsSeek(OsFile *id, off_t offset){
drhda71ce12004-06-21 18:14:45 +0000656 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000657 SEEK(offset/1024 + 1);
drha6abd042004-06-09 17:37:22 +0000658 lseek(id->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000659 return SQLITE_OK;
660}
661
662/*
drhdd809b02004-07-17 21:44:57 +0000663** The fsync() system call does not work as advertised on many
664** unix systems. The following procedure is an attempt to make
665** it work better.
666*/
667static int full_fsync(int fd){
668 int rc;
669#ifdef F_FULLFSYNC
670 rc = fcntl(fd, F_FULLFSYNC, 0);
671 if( rc ) rc = fsync(fd);
672#else
673 rc = fsync(fd);
674#endif
675 return rc;
676}
677
678/*
drhbbd42a62004-05-22 17:41:58 +0000679** Make sure all writes to a particular file are committed to disk.
680**
681** Under Unix, also make sure that the directory entry for the file
682** has been created by fsync-ing the directory that contains the file.
683** If we do not do this and we encounter a power failure, the directory
684** entry for the journal might not exist after we reboot. The next
685** SQLite to access the file will not know that the journal exists (because
686** the directory entry for the journal was never created) and the transaction
687** will not roll back - possibly leading to database corruption.
688*/
689int sqlite3OsSync(OsFile *id){
drhda71ce12004-06-21 18:14:45 +0000690 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000691 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000692 TRACE2("SYNC %-3d\n", id->h);
drhdd809b02004-07-17 21:44:57 +0000693 if( full_fsync(id->h) ){
drhbbd42a62004-05-22 17:41:58 +0000694 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000695 }
drha2854222004-06-17 19:04:17 +0000696 if( id->dirfd>=0 ){
697 TRACE2("DIRSYNC %-3d\n", id->dirfd);
drhdd809b02004-07-17 21:44:57 +0000698 full_fsync(id->dirfd);
drha2854222004-06-17 19:04:17 +0000699 close(id->dirfd); /* Only need to sync once, so close the directory */
700 id->dirfd = -1; /* when we are done. */
701 }
drha2854222004-06-17 19:04:17 +0000702 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +0000703}
704
705/*
danielk1977962398d2004-06-14 09:35:16 +0000706** Sync the directory zDirname. This is a no-op on operating systems other
707** than UNIX.
708*/
709int sqlite3OsSyncDirectory(const char *zDirname){
710 int fd;
711 int r;
danielk1977369f27e2004-06-15 11:40:04 +0000712 SimulateIOError(SQLITE_IOERR);
danielk1977962398d2004-06-14 09:35:16 +0000713 fd = open(zDirname, O_RDONLY|O_BINARY, 0644);
danielk1977369f27e2004-06-15 11:40:04 +0000714 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +0000715 if( fd<0 ){
716 return SQLITE_CANTOPEN;
717 }
718 r = fsync(fd);
719 close(fd);
720 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
721}
722
723/*
drhbbd42a62004-05-22 17:41:58 +0000724** Truncate an open file to a specified size
725*/
726int sqlite3OsTruncate(OsFile *id, off_t nByte){
drhda71ce12004-06-21 18:14:45 +0000727 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000728 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000729 return ftruncate(id->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000730}
731
732/*
733** Determine the current size of a file in bytes
734*/
735int sqlite3OsFileSize(OsFile *id, off_t *pSize){
736 struct stat buf;
drhda71ce12004-06-21 18:14:45 +0000737 assert( id->isOpen );
drhbbd42a62004-05-22 17:41:58 +0000738 SimulateIOError(SQLITE_IOERR);
drha6abd042004-06-09 17:37:22 +0000739 if( fstat(id->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +0000740 return SQLITE_IOERR;
741 }
742 *pSize = buf.st_size;
743 return SQLITE_OK;
744}
745
danielk19779a1d0ab2004-06-01 14:09:28 +0000746/*
danielk197713adf8a2004-06-03 16:08:41 +0000747** This routine checks if there is a RESERVED lock held on the specified
748** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +0000749** non-zero. If the file is unlocked or holds only SHARED locks, then
750** return zero.
danielk197713adf8a2004-06-03 16:08:41 +0000751*/
drha6abd042004-06-09 17:37:22 +0000752int sqlite3OsCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +0000753 int r = 0;
754
drhda71ce12004-06-21 18:14:45 +0000755 assert( id->isOpen );
drh2ac3ee92004-06-07 16:27:46 +0000756 sqlite3OsEnterMutex(); /* Needed because id->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +0000757
758 /* Check if a thread in this process holds such a lock */
759 if( id->pLock->locktype>SHARED_LOCK ){
760 r = 1;
761 }
762
drh2ac3ee92004-06-07 16:27:46 +0000763 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +0000764 */
765 if( !r ){
766 struct flock lock;
767 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +0000768 lock.l_start = RESERVED_BYTE;
769 lock.l_len = 1;
770 lock.l_type = F_WRLCK;
drha6abd042004-06-09 17:37:22 +0000771 fcntl(id->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +0000772 if( lock.l_type!=F_UNLCK ){
773 r = 1;
774 }
775 }
776
777 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +0000778 TRACE3("TEST WR-LOCK %d %d\n", id->h, r);
danielk197713adf8a2004-06-03 16:08:41 +0000779
780 return r;
781}
782
danielk19772b444852004-06-29 07:45:33 +0000783#ifdef SQLITE_DEBUG
784/*
785** Helper function for printing out trace information from debugging
786** binaries. This returns the string represetation of the supplied
787** integer lock-type.
788*/
789static const char * locktypeName(int locktype){
790 switch( locktype ){
791 case NO_LOCK: return "NONE";
792 case SHARED_LOCK: return "SHARED";
793 case RESERVED_LOCK: return "RESERVED";
794 case PENDING_LOCK: return "PENDING";
795 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
796 }
797 return "ERROR";
798}
799#endif
800
danielk197713adf8a2004-06-03 16:08:41 +0000801/*
danielk19779a1d0ab2004-06-01 14:09:28 +0000802** Lock the file with the lock specified by parameter locktype - one
803** of the following:
804**
drh2ac3ee92004-06-07 16:27:46 +0000805** (1) SHARED_LOCK
806** (2) RESERVED_LOCK
807** (3) PENDING_LOCK
808** (4) EXCLUSIVE_LOCK
809**
drhb3e04342004-06-08 00:47:47 +0000810** Sometimes when requesting one lock state, additional lock states
811** are inserted in between. The locking might fail on one of the later
812** transitions leaving the lock state different from what it started but
813** still short of its goal. The following chart shows the allowed
814** transitions and the inserted intermediate states:
815**
816** UNLOCKED -> SHARED
817** SHARED -> RESERVED
818** SHARED -> (PENDING) -> EXCLUSIVE
819** RESERVED -> (PENDING) -> EXCLUSIVE
820** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +0000821**
drha6abd042004-06-09 17:37:22 +0000822** This routine will only increase a lock. Use the sqlite3OsUnlock()
823** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +0000824*/
825int sqlite3OsLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +0000826 /* The following describes the implementation of the various locks and
827 ** lock transitions in terms of the POSIX advisory shared and exclusive
828 ** lock primitives (called read-locks and write-locks below, to avoid
829 ** confusion with SQLite lock names). The algorithms are complicated
830 ** slightly in order to be compatible with windows systems simultaneously
831 ** accessing the same database file, in case that is ever required.
832 **
833 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
834 ** byte', each single bytes at well known offsets, and the 'shared byte
835 ** range', a range of 510 bytes at a well known offset.
836 **
837 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
838 ** byte'. If this is successful, a random byte from the 'shared byte
839 ** range' is read-locked and the lock on the 'pending byte' released.
840 **
danielk197790ba3bd2004-06-25 08:32:25 +0000841 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
842 ** A RESERVED lock is implemented by grabbing a write-lock on the
843 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +0000844 **
845 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +0000846 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
847 ** on the 'pending byte'. This ensures that no new SHARED locks can be
848 ** obtained, but existing SHARED locks are allowed to persist. A process
849 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
850 ** This property is used by the algorithm for rolling back a journal file
851 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +0000852 **
danielk197790ba3bd2004-06-25 08:32:25 +0000853 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
854 ** implemented by obtaining a write-lock on the entire 'shared byte
855 ** range'. Since all other locks require a read-lock on one of the bytes
856 ** within this range, this ensures that no other locks are held on the
857 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +0000858 **
859 ** The reason a single byte cannot be used instead of the 'shared byte
860 ** range' is that some versions of windows do not support read-locks. By
861 ** locking a random byte from a range, concurrent SHARED locks may exist
862 ** even if the locking primitive used is always a write-lock.
863 */
danielk19779a1d0ab2004-06-01 14:09:28 +0000864 int rc = SQLITE_OK;
865 struct lockInfo *pLock = id->pLock;
866 struct flock lock;
867 int s;
868
drhda71ce12004-06-21 18:14:45 +0000869 assert( id->isOpen );
danielk19772b444852004-06-29 07:45:33 +0000870 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", id->h, locktypeName(locktype),
871 locktypeName(id->locktype), locktypeName(pLock->locktype), pLock->cnt
872 ,getpid() );
danielk19779a1d0ab2004-06-01 14:09:28 +0000873
874 /* If there is already a lock of this type or more restrictive on the
875 ** OsFile, do nothing. Don't use the end_lock: exit path, as
876 ** sqlite3OsEnterMutex() hasn't been called yet.
877 */
danielk197713adf8a2004-06-03 16:08:41 +0000878 if( id->locktype>=locktype ){
danielk19772b444852004-06-29 07:45:33 +0000879 TRACE3("LOCK %d %s ok (already held)\n", id->h, locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +0000880 return SQLITE_OK;
881 }
882
drhb3e04342004-06-08 00:47:47 +0000883 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +0000884 */
drhb3e04342004-06-08 00:47:47 +0000885 assert( id->locktype!=NO_LOCK || locktype==SHARED_LOCK );
886 assert( locktype!=PENDING_LOCK );
887 assert( locktype!=RESERVED_LOCK || id->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +0000888
drhb3e04342004-06-08 00:47:47 +0000889 /* This mutex is needed because id->pLock is shared across threads
890 */
891 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +0000892
893 /* If some thread using this PID has a lock via a different OsFile*
894 ** handle that precludes the requested lock, return BUSY.
895 */
danielk197713adf8a2004-06-03 16:08:41 +0000896 if( (id->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +0000897 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +0000898 ){
899 rc = SQLITE_BUSY;
900 goto end_lock;
901 }
902
903 /* If a SHARED lock is requested, and some thread using this PID already
904 ** has a SHARED or RESERVED lock, then increment reference counts and
905 ** return SQLITE_OK.
906 */
907 if( locktype==SHARED_LOCK &&
908 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
909 assert( locktype==SHARED_LOCK );
danielk197713adf8a2004-06-03 16:08:41 +0000910 assert( id->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +0000911 assert( pLock->cnt>0 );
danielk197713adf8a2004-06-03 16:08:41 +0000912 id->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +0000913 pLock->cnt++;
914 id->pOpen->nLock++;
915 goto end_lock;
916 }
917
danielk197713adf8a2004-06-03 16:08:41 +0000918 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +0000919 lock.l_whence = SEEK_SET;
920
drh3cde3bb2004-06-12 02:17:14 +0000921 /* A PENDING lock is needed before acquiring a SHARED lock and before
922 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
923 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +0000924 */
drh3cde3bb2004-06-12 02:17:14 +0000925 if( locktype==SHARED_LOCK
926 || (locktype==EXCLUSIVE_LOCK && id->locktype<PENDING_LOCK)
927 ){
danielk1977489468c2004-06-28 08:25:47 +0000928 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +0000929 lock.l_start = PENDING_BYTE;
drha6abd042004-06-09 17:37:22 +0000930 s = fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000931 if( s ){
932 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
933 goto end_lock;
934 }
drh3cde3bb2004-06-12 02:17:14 +0000935 }
936
937
938 /* If control gets to this point, then actually go ahead and make
939 ** operating system calls for the specified lock.
940 */
941 if( locktype==SHARED_LOCK ){
942 assert( pLock->cnt==0 );
943 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +0000944
drh2ac3ee92004-06-07 16:27:46 +0000945 /* Now get the read-lock */
946 lock.l_start = SHARED_FIRST;
947 lock.l_len = SHARED_SIZE;
drha6abd042004-06-09 17:37:22 +0000948 s = fcntl(id->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +0000949
950 /* Drop the temporary PENDING lock */
951 lock.l_start = PENDING_BYTE;
952 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +0000953 lock.l_type = F_UNLCK;
drha6abd042004-06-09 17:37:22 +0000954 fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000955 if( s ){
drhbbd42a62004-05-22 17:41:58 +0000956 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
957 }else{
danielk197713adf8a2004-06-03 16:08:41 +0000958 id->locktype = SHARED_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +0000959 id->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +0000960 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +0000961 }
drh3cde3bb2004-06-12 02:17:14 +0000962 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
963 /* We are trying for an exclusive lock but another thread in this
964 ** same process is still holding a shared lock. */
965 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +0000966 }else{
drh3cde3bb2004-06-12 02:17:14 +0000967 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +0000968 ** assumed that there is a SHARED or greater lock on the file
969 ** already.
970 */
danielk197713adf8a2004-06-03 16:08:41 +0000971 assert( 0!=id->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +0000972 lock.l_type = F_WRLCK;
973 switch( locktype ){
974 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +0000975 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +0000976 break;
danielk19779a1d0ab2004-06-01 14:09:28 +0000977 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +0000978 lock.l_start = SHARED_FIRST;
979 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +0000980 break;
981 default:
982 assert(0);
983 }
drha6abd042004-06-09 17:37:22 +0000984 s = fcntl(id->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +0000985 if( s ){
986 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
987 }
drhbbd42a62004-05-22 17:41:58 +0000988 }
danielk19779a1d0ab2004-06-01 14:09:28 +0000989
danielk1977ecb2a962004-06-02 06:30:16 +0000990 if( rc==SQLITE_OK ){
danielk197713adf8a2004-06-03 16:08:41 +0000991 id->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +0000992 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +0000993 }else if( locktype==EXCLUSIVE_LOCK ){
994 id->locktype = PENDING_LOCK;
995 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +0000996 }
danielk19779a1d0ab2004-06-01 14:09:28 +0000997
998end_lock:
drhbbd42a62004-05-22 17:41:58 +0000999 sqlite3OsLeaveMutex();
danielk19772b444852004-06-29 07:45:33 +00001000 TRACE4("LOCK %d %s %s\n", id->h, locktypeName(locktype),
1001 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001002 return rc;
1003}
1004
1005/*
drha6abd042004-06-09 17:37:22 +00001006** Lower the locking level on file descriptor id to locktype. locktype
1007** must be either NO_LOCK or SHARED_LOCK.
1008**
1009** If the locking level of the file descriptor is already at or below
1010** the requested locking level, this routine is a no-op.
1011**
1012** It is not possible for this routine to fail.
drhbbd42a62004-05-22 17:41:58 +00001013*/
drha6abd042004-06-09 17:37:22 +00001014int sqlite3OsUnlock(OsFile *id, int locktype){
1015 struct lockInfo *pLock;
1016 struct flock lock;
1017
drhda71ce12004-06-21 18:14:45 +00001018 assert( id->isOpen );
danielk19772b444852004-06-29 07:45:33 +00001019 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", id->h, locktype, id->locktype,
1020 id->pLock->locktype, id->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001021
1022 assert( locktype<=SHARED_LOCK );
1023 if( id->locktype<=locktype ){
1024 return SQLITE_OK;
1025 }
drhbbd42a62004-05-22 17:41:58 +00001026 sqlite3OsEnterMutex();
drha6abd042004-06-09 17:37:22 +00001027 pLock = id->pLock;
1028 assert( pLock->cnt!=0 );
1029 if( id->locktype>SHARED_LOCK ){
1030 assert( pLock->locktype==id->locktype );
drhbbd42a62004-05-22 17:41:58 +00001031 lock.l_type = F_UNLCK;
1032 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001033 lock.l_start = PENDING_BYTE;
1034 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
1035 fcntl(id->h, F_SETLK, &lock);
1036 pLock->locktype = SHARED_LOCK;
drhbbd42a62004-05-22 17:41:58 +00001037 }
drha6abd042004-06-09 17:37:22 +00001038 if( locktype==NO_LOCK ){
1039 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001040
drha6abd042004-06-09 17:37:22 +00001041 /* Decrement the shared lock counter. Release the lock using an
1042 ** OS call only when all threads in this same process have released
1043 ** the lock.
1044 */
1045 pLock->cnt--;
1046 if( pLock->cnt==0 ){
1047 lock.l_type = F_UNLCK;
1048 lock.l_whence = SEEK_SET;
1049 lock.l_start = lock.l_len = 0L;
1050 fcntl(id->h, F_SETLK, &lock);
1051 pLock->locktype = NO_LOCK;
1052 }
1053
drhbbd42a62004-05-22 17:41:58 +00001054 /* Decrement the count of locks against this same file. When the
1055 ** count reaches zero, close any other file descriptors whose close
1056 ** was deferred because of outstanding locks.
1057 */
drha6abd042004-06-09 17:37:22 +00001058 pOpen = id->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001059 pOpen->nLock--;
1060 assert( pOpen->nLock>=0 );
1061 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1062 int i;
1063 for(i=0; i<pOpen->nPending; i++){
1064 close(pOpen->aPending[i]);
1065 }
1066 sqliteFree(pOpen->aPending);
1067 pOpen->nPending = 0;
1068 pOpen->aPending = 0;
1069 }
1070 }
1071 sqlite3OsLeaveMutex();
drha6abd042004-06-09 17:37:22 +00001072 id->locktype = locktype;
1073 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001074}
1075
1076/*
danielk1977e3026632004-06-22 11:29:02 +00001077** Close a file.
1078*/
1079int sqlite3OsClose(OsFile *id){
1080 if( !id->isOpen ) return SQLITE_OK;
1081 sqlite3OsUnlock(id, NO_LOCK);
1082 if( id->dirfd>=0 ) close(id->dirfd);
1083 id->dirfd = -1;
1084 sqlite3OsEnterMutex();
1085 if( id->pOpen->nLock ){
1086 /* If there are outstanding locks, do not actually close the file just
1087 ** yet because that would clear those locks. Instead, add the file
1088 ** descriptor to pOpen->aPending. It will be automatically closed when
1089 ** the last lock is cleared.
1090 */
1091 int *aNew;
1092 struct openCnt *pOpen = id->pOpen;
1093 pOpen->nPending++;
1094 aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) );
1095 if( aNew==0 ){
1096 /* If a malloc fails, just leak the file descriptor */
1097 }else{
1098 pOpen->aPending = aNew;
1099 pOpen->aPending[pOpen->nPending-1] = id->h;
1100 }
1101 }else{
1102 /* There are no outstanding locks so we can close the file immediately */
1103 close(id->h);
1104 }
1105 releaseLockInfo(id->pLock);
1106 releaseOpenCnt(id->pOpen);
1107 sqlite3OsLeaveMutex();
1108 id->isOpen = 0;
1109 TRACE2("CLOSE %-3d\n", id->h);
1110 OpenCounter(-1);
1111 return SQLITE_OK;
1112}
1113
1114/*
drhbbd42a62004-05-22 17:41:58 +00001115** Get information to seed the random number generator. The seed
1116** is written into the buffer zBuf[256]. The calling function must
1117** supply a sufficiently large buffer.
1118*/
1119int sqlite3OsRandomSeed(char *zBuf){
1120 /* We have to initialize zBuf to prevent valgrind from reporting
1121 ** errors. The reports issued by valgrind are incorrect - we would
1122 ** prefer that the randomness be increased by making use of the
1123 ** uninitialized space in zBuf - but valgrind errors tend to worry
1124 ** some users. Rather than argue, it seems easier just to initialize
1125 ** the whole array and silence valgrind, even if that means less randomness
1126 ** in the random seed.
1127 **
1128 ** When testing, initializing zBuf[] to zero is all we do. That means
1129 ** that we always use the same random number sequence.* This makes the
1130 ** tests repeatable.
1131 */
1132 memset(zBuf, 0, 256);
1133#if !defined(SQLITE_TEST)
1134 {
1135 int pid;
1136 time((time_t*)zBuf);
1137 pid = getpid();
1138 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1139 }
1140#endif
1141 return SQLITE_OK;
1142}
1143
1144/*
1145** Sleep for a little while. Return the amount of time slept.
1146*/
1147int sqlite3OsSleep(int ms){
1148#if defined(HAVE_USLEEP) && HAVE_USLEEP
1149 usleep(ms*1000);
1150 return ms;
1151#else
1152 sleep((ms+999)/1000);
1153 return 1000*((ms+999)/1000);
1154#endif
1155}
1156
1157/*
1158** Static variables used for thread synchronization
1159*/
1160static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001161#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +00001162static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +00001163#endif
drhbbd42a62004-05-22 17:41:58 +00001164
1165/*
1166** The following pair of routine implement mutual exclusion for
1167** multi-threaded processes. Only a single thread is allowed to
1168** executed code that is surrounded by EnterMutex() and LeaveMutex().
1169**
1170** SQLite uses only a single Mutex. There is not much critical
1171** code and what little there is executes quickly and without blocking.
1172*/
1173void sqlite3OsEnterMutex(){
1174#ifdef SQLITE_UNIX_THREADS
1175 pthread_mutex_lock(&mutex);
1176#endif
1177 assert( !inMutex );
1178 inMutex = 1;
1179}
1180void sqlite3OsLeaveMutex(){
1181 assert( inMutex );
1182 inMutex = 0;
1183#ifdef SQLITE_UNIX_THREADS
1184 pthread_mutex_unlock(&mutex);
1185#endif
1186}
1187
1188/*
1189** Turn a relative pathname into a full pathname. Return a pointer
1190** to the full pathname stored in space obtained from sqliteMalloc().
1191** The calling function is responsible for freeing this space once it
1192** is no longer needed.
1193*/
1194char *sqlite3OsFullPathname(const char *zRelative){
1195 char *zFull = 0;
1196 if( zRelative[0]=='/' ){
1197 sqlite3SetString(&zFull, zRelative, (char*)0);
1198 }else{
1199 char zBuf[5000];
1200 sqlite3SetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative,
1201 (char*)0);
1202 }
1203 return zFull;
1204}
1205
1206/*
1207** The following variable, if set to a non-zero value, becomes the result
1208** returned from sqlite3OsCurrentTime(). This is used for testing.
1209*/
1210#ifdef SQLITE_TEST
1211int sqlite3_current_time = 0;
1212#endif
1213
1214/*
1215** Find the current time (in Universal Coordinated Time). Write the
1216** current time and date as a Julian Day number into *prNow and
1217** return 0. Return 1 if the time and date cannot be found.
1218*/
1219int sqlite3OsCurrentTime(double *prNow){
1220 time_t t;
1221 time(&t);
1222 *prNow = t/86400.0 + 2440587.5;
1223#ifdef SQLITE_TEST
1224 if( sqlite3_current_time ){
1225 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1226 }
1227#endif
1228 return 0;
1229}
1230
drhfd69dd62004-06-29 11:08:19 +00001231#if 0 /* NOT USED */
drhbf9a7e42004-06-15 00:29:03 +00001232/*
1233** Find the time that the file was last modified. Write the
1234** modification time and date as a Julian Day number into *prNow and
1235** return SQLITE_OK. Return SQLITE_ERROR if the modification
1236** time cannot be found.
1237*/
1238int sqlite3OsFileModTime(OsFile *id, double *prNow){
1239 int rc;
1240 struct stat statbuf;
1241 if( fstat(id->h, &statbuf)==0 ){
1242 *prNow = statbuf.st_mtime/86400.0 + 2440587.5;
1243 rc = SQLITE_OK;
1244 }else{
1245 rc = SQLITE_ERROR;
1246 }
1247 return rc;
1248}
drhfd69dd62004-06-29 11:08:19 +00001249#endif /* NOT USED */
drhbf9a7e42004-06-15 00:29:03 +00001250
drhbbd42a62004-05-22 17:41:58 +00001251#endif /* OS_UNIX */