monotone

monotone Mtn Source Tree

Root/sqlite/os.c

1/*
2** 2001 September 16
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 particular operating
14** systems. The purpose of this file is to provide a uniform abstraction
15** on which the rest of SQLite can operate.
16*/
17#include "os.h" /* Must be first to enable large file support */
18#include "sqliteInt.h"
19
20#if OS_UNIX
21# include <time.h>
22# include <errno.h>
23# include <unistd.h>
24# ifndef O_LARGEFILE
25# define O_LARGEFILE 0
26# endif
27# ifdef SQLITE_DISABLE_LFS
28# undef O_LARGEFILE
29# define O_LARGEFILE 0
30# endif
31# ifndef O_NOFOLLOW
32# define O_NOFOLLOW 0
33# endif
34# ifndef O_BINARY
35# define O_BINARY 0
36# endif
37#endif
38
39
40#if OS_WIN
41# include <winbase.h>
42#endif
43
44#if OS_MAC
45# include <extras.h>
46# include <path2fss.h>
47# include <TextUtils.h>
48# include <FinderRegistry.h>
49# include <Folders.h>
50# include <Timer.h>
51# include <OSUtils.h>
52#endif
53
54/*
55** The DJGPP compiler environment looks mostly like Unix, but it
56** lacks the fcntl() system call. So redefine fcntl() to be something
57** that always succeeds. This means that locking does not occur under
58** DJGPP. But its DOS - what did you expect?
59*/
60#ifdef __DJGPP__
61# define fcntl(A,B,C) 0
62#endif
63
64/*
65** Macros for performance tracing. Normally turned off
66*/
67#if 0
68static int last_page = 0;
69__inline__ unsigned long long int hwtime(void){
70 unsigned long long int x;
71 __asm__("rdtsc\n\t"
72 "mov %%edx, %%ecx\n\t"
73 :"=A" (x));
74 return x;
75}
76static unsigned long long int g_start;
77static unsigned int elapse;
78#define TIMER_START g_start=hwtime()
79#define TIMER_END elapse=hwtime()-g_start
80#define SEEK(X) last_page=(X)
81#define TRACE1(X) fprintf(stderr,X)
82#define TRACE2(X,Y) fprintf(stderr,X,Y)
83#define TRACE3(X,Y,Z) fprintf(stderr,X,Y,Z)
84#define TRACE4(X,Y,Z,A) fprintf(stderr,X,Y,Z,A)
85#define TRACE5(X,Y,Z,A,B) fprintf(stderr,X,Y,Z,A,B)
86#else
87#define TIMER_START
88#define TIMER_END
89#define SEEK(X)
90#define TRACE1(X)
91#define TRACE2(X,Y)
92#define TRACE3(X,Y,Z)
93#define TRACE4(X,Y,Z,A)
94#define TRACE5(X,Y,Z,A,B)
95#endif
96
97
98#if OS_UNIX
99/*
100** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
101** section 6.5.2.2 lines 483 through 490 specify that when a process
102** sets or clears a lock, that operation overrides any prior locks set
103** by the same process. It does not explicitly say so, but this implies
104** that it overrides locks set by the same process using a different
105** file descriptor. Consider this test case:
106**
107** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
108** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
109**
110** Suppose ./file1 and ./file2 are really be the same file (because
111** one is a hard or symbolic link to the other) then if you set
112** an exclusive lock on fd1, then try to get an exclusive lock
113** on fd2, it works. I would have expected the second lock to
114** fail since there was already a lock on the file due to fd1.
115** But not so. Since both locks came from the same process, the
116** second overrides the first, even though they were on different
117** file descriptors opened on different file names.
118**
119** Bummer. If you ask me, this is broken. Badly broken. It means
120** that we cannot use POSIX locks to synchronize file access among
121** competing threads of the same process. POSIX locks will work fine
122** to synchronize access for threads in separate processes, but not
123** threads within the same process.
124**
125** To work around the problem, SQLite has to manage file locks internally
126** on its own. Whenever a new database is opened, we have to find the
127** specific inode of the database file (the inode is determined by the
128** st_dev and st_ino fields of the stat structure that fstat() fills in)
129** and check for locks already existing on that inode. When locks are
130** created or removed, we have to look at our own internal record of the
131** locks to see if another thread has previously set a lock on that same
132** inode.
133**
134** The OsFile structure for POSIX is no longer just an integer file
135** descriptor. It is now a structure that holds the integer file
136** descriptor and a pointer to a structure that describes the internal
137** locks on the corresponding inode. There is one locking structure
138** per inode, so if the same inode is opened twice, both OsFile structures
139** point to the same locking structure. The locking structure keeps
140** a reference count (so we will know when to delete it) and a "cnt"
141** field that tells us its internal lock status. cnt==0 means the
142** file is unlocked. cnt==-1 means the file has an exclusive lock.
143** cnt>0 means there are cnt shared locks on the file.
144**
145** Any attempt to lock or unlock a file first checks the locking
146** structure. The fcntl() system call is only invoked to set a
147** POSIX lock if the internal lock structure transitions between
148** a locked and an unlocked state.
149*/
150
151/*
152** An instance of the following structure serves as the key used
153** to locate a particular lockInfo structure given its inode.
154*/
155struct inodeKey {
156 dev_t dev; /* Device number */
157 ino_t ino; /* Inode number */
158};
159
160/*
161** An instance of the following structure is allocated for each inode.
162** A single inode can have multiple file descriptors, so each OsFile
163** structure contains a pointer to an instance of this object and this
164** object keeps a count of the number of OsFiles pointing to it.
165*/
166struct lockInfo {
167 struct inodeKey key; /* The lookup key */
168 int cnt; /* 0: unlocked. -1: write lock. 1...: read lock. */
169 int nRef; /* Number of pointers to this structure */
170};
171
172/*
173** This hash table maps inodes (in the form of inodeKey structures) into
174** pointers to lockInfo structures.
175*/
176static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
177
178/*
179** Given a file descriptor, locate a lockInfo structure that describes
180** that file descriptor. Create a new one if necessary. NULL might
181** be returned if malloc() fails.
182*/
183static struct lockInfo *findLockInfo(int fd){
184 int rc;
185 struct inodeKey key;
186 struct stat statbuf;
187 struct lockInfo *pInfo;
188 rc = fstat(fd, &statbuf);
189 if( rc!=0 ) return 0;
190 memset(&key, 0, sizeof(key));
191 key.dev = statbuf.st_dev;
192 key.ino = statbuf.st_ino;
193 pInfo = (struct lockInfo*)sqliteHashFind(&lockHash, &key, sizeof(key));
194 if( pInfo==0 ){
195 struct lockInfo *pOld;
196 pInfo = sqliteMalloc( sizeof(*pInfo) );
197 if( pInfo==0 ) return 0;
198 pInfo->key = key;
199 pInfo->nRef = 1;
200 pInfo->cnt = 0;
201 pOld = sqliteHashInsert(&lockHash, &pInfo->key, sizeof(key), pInfo);
202 if( pOld!=0 ){
203 assert( pOld==pInfo );
204 sqliteFree(pInfo);
205 pInfo = 0;
206 }
207 }else{
208 pInfo->nRef++;
209 }
210 return pInfo;
211}
212
213/*
214** Release a lockInfo structure previously allocated by findLockInfo().
215*/
216static void releaseLockInfo(struct lockInfo *pInfo){
217 pInfo->nRef--;
218 if( pInfo->nRef==0 ){
219 sqliteHashInsert(&lockHash, &pInfo->key, sizeof(pInfo->key), 0);
220 sqliteFree(pInfo);
221 }
222}
223#endif /** POSIX advisory lock work-around **/
224
225/*
226** If we compile with the SQLITE_TEST macro set, then the following block
227** of code will give us the ability to simulate a disk I/O error. This
228** is used for testing the I/O recovery logic.
229*/
230#ifdef SQLITE_TEST
231int sqlite_io_error_pending = 0;
232#define SimulateIOError(A) \
233 if( sqlite_io_error_pending ) \
234 if( sqlite_io_error_pending-- == 1 ){ local_ioerr(); return A; }
235static void local_ioerr(){
236 sqlite_io_error_pending = 0; /* Really just a place to set a breakpoint */
237}
238#else
239#define SimulateIOError(A)
240#endif
241
242/*
243** When testing, keep a count of the number of open files.
244*/
245#ifdef SQLITE_TEST
246int sqlite_open_file_count = 0;
247#define OpenCounter(X) sqlite_open_file_count+=(X)
248#else
249#define OpenCounter(X)
250#endif
251
252
253/*
254** Delete the named file
255*/
256int sqliteOsDelete(const char *zFilename){
257#if OS_UNIX
258 unlink(zFilename);
259#endif
260#if OS_WIN
261 DeleteFile(zFilename);
262#endif
263#if OS_MAC
264 unlink(zFilename);
265#endif
266 return SQLITE_OK;
267}
268
269/*
270** Return TRUE if the named file exists.
271*/
272int sqliteOsFileExists(const char *zFilename){
273#if OS_UNIX
274 return access(zFilename, 0)==0;
275#endif
276#if OS_WIN
277 return GetFileAttributes(zFilename) != 0xffffffff;
278#endif
279#if OS_MAC
280 return access(zFilename, 0)==0;
281#endif
282}
283
284
285#if 0 /* NOT USED */
286/*
287** Change the name of an existing file.
288*/
289int sqliteOsFileRename(const char *zOldName, const char *zNewName){
290#if OS_UNIX
291 if( link(zOldName, zNewName) ){
292 return SQLITE_ERROR;
293 }
294 unlink(zOldName);
295 return SQLITE_OK;
296#endif
297#if OS_WIN
298 if( !MoveFile(zOldName, zNewName) ){
299 return SQLITE_ERROR;
300 }
301 return SQLITE_OK;
302#endif
303#if OS_MAC
304 /**** FIX ME ***/
305 return SQLITE_ERROR;
306#endif
307}
308#endif /* NOT USED */
309
310/*
311** Attempt to open a file for both reading and writing. If that
312** fails, try opening it read-only. If the file does not exist,
313** try to create it.
314**
315** On success, a handle for the open file is written to *id
316** and *pReadonly is set to 0 if the file was opened for reading and
317** writing or 1 if the file was opened read-only. The function returns
318** SQLITE_OK.
319**
320** On failure, the function returns SQLITE_CANTOPEN and leaves
321** *id and *pReadonly unchanged.
322*/
323int sqliteOsOpenReadWrite(
324 const char *zFilename,
325 OsFile *id,
326 int *pReadonly
327){
328#if OS_UNIX
329 id->fd = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY, 0644);
330 if( id->fd<0 ){
331 id->fd = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
332 if( id->fd<0 ){
333 return SQLITE_CANTOPEN;
334 }
335 *pReadonly = 1;
336 }else{
337 *pReadonly = 0;
338 }
339 sqliteOsEnterMutex();
340 id->pLock = findLockInfo(id->fd);
341 sqliteOsLeaveMutex();
342 if( id->pLock==0 ){
343 close(id->fd);
344 return SQLITE_NOMEM;
345 }
346 id->locked = 0;
347 TRACE3("OPEN %-3d %s\n", id->fd, zFilename);
348 OpenCounter(+1);
349 return SQLITE_OK;
350#endif
351#if OS_WIN
352 HANDLE h = CreateFile(zFilename,
353 GENERIC_READ | GENERIC_WRITE,
354 FILE_SHARE_READ | FILE_SHARE_WRITE,
355 NULL,
356 OPEN_ALWAYS,
357 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
358 NULL
359 );
360 if( h==INVALID_HANDLE_VALUE ){
361 h = CreateFile(zFilename,
362 GENERIC_READ,
363 FILE_SHARE_READ,
364 NULL,
365 OPEN_ALWAYS,
366 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
367 NULL
368 );
369 if( h==INVALID_HANDLE_VALUE ){
370 return SQLITE_CANTOPEN;
371 }
372 *pReadonly = 1;
373 }else{
374 *pReadonly = 0;
375 }
376 id->h = h;
377 id->locked = 0;
378 OpenCounter(+1);
379 return SQLITE_OK;
380#endif
381#if OS_MAC
382 FSSpec fsSpec;
383# ifdef _LARGE_FILE
384 HFSUniStr255 dfName;
385 FSRef fsRef;
386 if( __path2fss(zFilename, &fsSpec) != noErr ){
387 if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
388 return SQLITE_CANTOPEN;
389 }
390 if( FSpMakeFSRef(&fsSpec, &fsRef) != noErr )
391 return SQLITE_CANTOPEN;
392 FSGetDataForkName(&dfName);
393 if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
394 fsRdWrShPerm, &(id->refNum)) != noErr ){
395 if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
396 fsRdWrPerm, &(id->refNum)) != noErr ){
397 if (FSOpenFork(&fsRef, dfName.length, dfName.unicode,
398 fsRdPerm, &(id->refNum)) != noErr )
399 return SQLITE_CANTOPEN;
400 else
401 *pReadonly = 1;
402 } else
403 *pReadonly = 0;
404 } else
405 *pReadonly = 0;
406# else
407 __path2fss(zFilename, &fsSpec);
408 if( !sqliteOsFileExists(zFilename) ){
409 if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
410 return SQLITE_CANTOPEN;
411 }
412 if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrShPerm, &(id->refNum)) != noErr ){
413 if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrPerm, &(id->refNum)) != noErr ){
414 if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdPerm, &(id->refNum)) != noErr )
415 return SQLITE_CANTOPEN;
416 else
417 *pReadonly = 1;
418 } else
419 *pReadonly = 0;
420 } else
421 *pReadonly = 0;
422# endif
423 if( HOpenRF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrShPerm, &(id->refNumRF)) != noErr){
424 id->refNumRF = -1;
425 }
426 id->locked = 0;
427 id->delOnClose = 0;
428 OpenCounter(+1);
429 return SQLITE_OK;
430#endif
431}
432
433
434/*
435** Attempt to open a new file for exclusive access by this process.
436** The file will be opened for both reading and writing. To avoid
437** a potential security problem, we do not allow the file to have
438** previously existed. Nor do we allow the file to be a symbolic
439** link.
440**
441** If delFlag is true, then make arrangements to automatically delete
442** the file when it is closed.
443**
444** On success, write the file handle into *id and return SQLITE_OK.
445**
446** On failure, return SQLITE_CANTOPEN.
447*/
448int sqliteOsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){
449#if OS_UNIX
450 if( access(zFilename, 0)==0 ){
451 return SQLITE_CANTOPEN;
452 }
453 id->fd = open(zFilename,
454 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY, 0600);
455 if( id->fd<0 ){
456 return SQLITE_CANTOPEN;
457 }
458 sqliteOsEnterMutex();
459 id->pLock = findLockInfo(id->fd);
460 sqliteOsLeaveMutex();
461 if( id->pLock==0 ){
462 close(id->fd);
463 unlink(zFilename);
464 return SQLITE_NOMEM;
465 }
466 id->locked = 0;
467 if( delFlag ){
468 unlink(zFilename);
469 }
470 TRACE3("OPEN-EX %-3d %s\n", id->fd, zFilename);
471 OpenCounter(+1);
472 return SQLITE_OK;
473#endif
474#if OS_WIN
475 HANDLE h;
476 int fileflags;
477 if( delFlag ){
478 fileflags = FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_RANDOM_ACCESS
479 | FILE_FLAG_DELETE_ON_CLOSE;
480 }else{
481 fileflags = FILE_FLAG_RANDOM_ACCESS;
482 }
483 h = CreateFile(zFilename,
484 GENERIC_READ | GENERIC_WRITE,
485 0,
486 NULL,
487 CREATE_ALWAYS,
488 fileflags,
489 NULL
490 );
491 if( h==INVALID_HANDLE_VALUE ){
492 return SQLITE_CANTOPEN;
493 }
494 id->h = h;
495 id->locked = 0;
496 OpenCounter(+1);
497 return SQLITE_OK;
498#endif
499#if OS_MAC
500 FSSpec fsSpec;
501# ifdef _LARGE_FILE
502 HFSUniStr255 dfName;
503 FSRef fsRef;
504 __path2fss(zFilename, &fsSpec);
505 if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
506 return SQLITE_CANTOPEN;
507 if( FSpMakeFSRef(&fsSpec, &fsRef) != noErr )
508 return SQLITE_CANTOPEN;
509 FSGetDataForkName(&dfName);
510 if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
511 fsRdWrPerm, &(id->refNum)) != noErr )
512 return SQLITE_CANTOPEN;
513# else
514 __path2fss(zFilename, &fsSpec);
515 if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
516 return SQLITE_CANTOPEN;
517 if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrPerm, &(id->refNum)) != noErr )
518 return SQLITE_CANTOPEN;
519# endif
520 id->refNumRF = -1;
521 id->locked = 0;
522 id->delOnClose = delFlag;
523 if (delFlag)
524 id->pathToDel = sqliteOsFullPathname(zFilename);
525 OpenCounter(+1);
526 return SQLITE_OK;
527#endif
528}
529
530/*
531** Attempt to open a new file for read-only access.
532**
533** On success, write the file handle into *id and return SQLITE_OK.
534**
535** On failure, return SQLITE_CANTOPEN.
536*/
537int sqliteOsOpenReadOnly(const char *zFilename, OsFile *id){
538#if OS_UNIX
539 id->fd = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
540 if( id->fd<0 ){
541 return SQLITE_CANTOPEN;
542 }
543 sqliteOsEnterMutex();
544 id->pLock = findLockInfo(id->fd);
545 sqliteOsLeaveMutex();
546 if( id->pLock==0 ){
547 close(id->fd);
548 return SQLITE_NOMEM;
549 }
550 id->locked = 0;
551 TRACE3("OPEN-RO %-3d %s\n", id->fd, zFilename);
552 OpenCounter(+1);
553 return SQLITE_OK;
554#endif
555#if OS_WIN
556 HANDLE h = CreateFile(zFilename,
557 GENERIC_READ,
558 0,
559 NULL,
560 OPEN_EXISTING,
561 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
562 NULL
563 );
564 if( h==INVALID_HANDLE_VALUE ){
565 return SQLITE_CANTOPEN;
566 }
567 id->h = h;
568 id->locked = 0;
569 OpenCounter(+1);
570 return SQLITE_OK;
571#endif
572#if OS_MAC
573 FSSpec fsSpec;
574# ifdef _LARGE_FILE
575 HFSUniStr255 dfName;
576 FSRef fsRef;
577 if( __path2fss(zFilename, &fsSpec) != noErr )
578 return SQLITE_CANTOPEN;
579 if( FSpMakeFSRef(&fsSpec, &fsRef) != noErr )
580 return SQLITE_CANTOPEN;
581 FSGetDataForkName(&dfName);
582 if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
583 fsRdPerm, &(id->refNum)) != noErr )
584 return SQLITE_CANTOPEN;
585# else
586 __path2fss(zFilename, &fsSpec);
587 if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdPerm, &(id->refNum)) != noErr )
588 return SQLITE_CANTOPEN;
589# endif
590 if( HOpenRF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrShPerm, &(id->refNumRF)) != noErr){
591 id->refNumRF = -1;
592 }
593 id->locked = 0;
594 id->delOnClose = 0;
595 OpenCounter(+1);
596 return SQLITE_OK;
597#endif
598}
599
600/*
601** Create a temporary file name in zBuf. zBuf must be big enough to
602** hold at least SQLITE_TEMPNAME_SIZE characters.
603*/
604int sqliteOsTempFileName(char *zBuf){
605#if OS_UNIX
606 static const char *azDirs[] = {
607 "/var/tmp",
608 "/usr/tmp",
609 "/tmp",
610 ".",
611 };
612 static char zChars[] =
613 "abcdefghijklmnopqrstuvwxyz"
614 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
615 "0123456789";
616 int i, j;
617 struct stat buf;
618 const char *zDir = ".";
619 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
620 if( stat(azDirs[i], &buf) ) continue;
621 if( !S_ISDIR(buf.st_mode) ) continue;
622 if( access(azDirs[i], 07) ) continue;
623 zDir = azDirs[i];
624 break;
625 }
626 do{
627 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
628 j = strlen(zBuf);
629 for(i=0; i<15; i++){
630 int n = sqliteRandomByte() % (sizeof(zChars)-1);
631 zBuf[j++] = zChars[n];
632 }
633 zBuf[j] = 0;
634 }while( access(zBuf,0)==0 );
635#endif
636#if OS_WIN
637 static char zChars[] =
638 "abcdefghijklmnopqrstuvwxyz"
639 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
640 "0123456789";
641 int i, j;
642 char zTempPath[SQLITE_TEMPNAME_SIZE];
643 GetTempPath(SQLITE_TEMPNAME_SIZE-30, zTempPath);
644 for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
645 zTempPath[i] = 0;
646 for(;;){
647 sprintf(zBuf, "%s\\"TEMP_FILE_PREFIX, zTempPath);
648 j = strlen(zBuf);
649 for(i=0; i<15; i++){
650 int n = sqliteRandomByte() % sizeof(zChars);
651 zBuf[j++] = zChars[n];
652 }
653 zBuf[j] = 0;
654 if( !sqliteOsFileExists(zBuf) ) break;
655 }
656#endif
657#if OS_MAC
658 static char zChars[] =
659 "abcdefghijklmnopqrstuvwxyz"
660 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
661 "0123456789";
662 int i, j;
663 char zTempPath[SQLITE_TEMPNAME_SIZE];
664 char zdirName[32];
665 CInfoPBRec infoRec;
666 Str31 dirName;
667 memset(&infoRec, 0, sizeof(infoRec));
668 memset(zTempPath, 0, SQLITE_TEMPNAME_SIZE);
669 if( FindFolder(kOnSystemDisk, kTemporaryFolderType, kCreateFolder,
670 &(infoRec.dirInfo.ioVRefNum), &(infoRec.dirInfo.ioDrParID)) == noErr ){
671 infoRec.dirInfo.ioNamePtr = dirName;
672 do{
673 infoRec.dirInfo.ioFDirIndex = -1;
674 infoRec.dirInfo.ioDrDirID = infoRec.dirInfo.ioDrParID;
675 if( PBGetCatInfoSync(&infoRec) == noErr ){
676 CopyPascalStringToC(dirName, zdirName);
677 i = strlen(zdirName);
678 memmove(&(zTempPath[i+1]), zTempPath, strlen(zTempPath));
679 strcpy(zTempPath, zdirName);
680 zTempPath[i] = ':';
681 }else{
682 *zTempPath = 0;
683 break;
684 }
685 } while( infoRec.dirInfo.ioDrDirID != fsRtDirID );
686 }
687 if( *zTempPath == 0 )
688 getcwd(zTempPath, SQLITE_TEMPNAME_SIZE-24);
689 for(;;){
690 sprintf(zBuf, "%s"TEMP_FILE_PREFIX, zTempPath);
691 j = strlen(zBuf);
692 for(i=0; i<15; i++){
693 int n = sqliteRandomByte() % sizeof(zChars);
694 zBuf[j++] = zChars[n];
695 }
696 zBuf[j] = 0;
697 if( !sqliteOsFileExists(zBuf) ) break;
698 }
699#endif
700 return SQLITE_OK;
701}
702
703/*
704** Close a file
705*/
706int sqliteOsClose(OsFile *id){
707#if OS_UNIX
708 close(id->fd);
709 sqliteOsEnterMutex();
710 releaseLockInfo(id->pLock);
711 sqliteOsLeaveMutex();
712 TRACE2("CLOSE %-3d\n", id->fd);
713 OpenCounter(-1);
714 return SQLITE_OK;
715#endif
716#if OS_WIN
717 CloseHandle(id->h);
718 OpenCounter(-1);
719 return SQLITE_OK;
720#endif
721#if OS_MAC
722 if( id->refNumRF!=-1 )
723 FSClose(id->refNumRF);
724# ifdef _LARGE_FILE
725 FSCloseFork(id->refNum);
726# else
727 FSClose(id->refNum);
728# endif
729 if( id->delOnClose ){
730 unlink(id->pathToDel);
731 sqliteFree(id->pathToDel);
732 }
733 OpenCounter(-1);
734 return SQLITE_OK;
735#endif
736}
737
738/*
739** Read data from a file into a buffer. Return SQLITE_OK if all
740** bytes were read successfully and SQLITE_IOERR if anything goes
741** wrong.
742*/
743int sqliteOsRead(OsFile *id, void *pBuf, int amt){
744#if OS_UNIX
745 int got;
746 SimulateIOError(SQLITE_IOERR);
747 TIMER_START;
748 got = read(id->fd, pBuf, amt);
749 TIMER_END;
750 TRACE4("READ %-3d %7d %d\n", id->fd, last_page, elapse);
751 SEEK(0);
752 /* if( got<0 ) got = 0; */
753 if( got==amt ){
754 return SQLITE_OK;
755 }else{
756 return SQLITE_IOERR;
757 }
758#endif
759#if OS_WIN
760 DWORD got;
761 SimulateIOError(SQLITE_IOERR);
762 TRACE2("READ %d\n", last_page);
763 if( !ReadFile(id->h, pBuf, amt, &got, 0) ){
764 got = 0;
765 }
766 if( got==(DWORD)amt ){
767 return SQLITE_OK;
768 }else{
769 return SQLITE_IOERR;
770 }
771#endif
772#if OS_MAC
773 int got;
774 SimulateIOError(SQLITE_IOERR);
775 TRACE2("READ %d\n", last_page);
776# ifdef _LARGE_FILE
777 FSReadFork(id->refNum, fsAtMark, 0, (ByteCount)amt, pBuf, (ByteCount*)&got);
778# else
779 got = amt;
780 FSRead(id->refNum, &got, pBuf);
781# endif
782 if( got==amt ){
783 return SQLITE_OK;
784 }else{
785 return SQLITE_IOERR;
786 }
787#endif
788}
789
790/*
791** Write data from a buffer into a file. Return SQLITE_OK on success
792** or some other error code on failure.
793*/
794int sqliteOsWrite(OsFile *id, const void *pBuf, int amt){
795#if OS_UNIX
796 int wrote = 0;
797 SimulateIOError(SQLITE_IOERR);
798 TIMER_START;
799 while( amt>0 && (wrote = write(id->fd, pBuf, amt))>0 ){
800 amt -= wrote;
801 pBuf = &((char*)pBuf)[wrote];
802 }
803 TIMER_END;
804 TRACE4("WRITE %-3d %7d %d\n", id->fd, last_page, elapse);
805 SEEK(0);
806 if( amt>0 ){
807 return SQLITE_FULL;
808 }
809 return SQLITE_OK;
810#endif
811#if OS_WIN
812 int rc;
813 DWORD wrote;
814 SimulateIOError(SQLITE_IOERR);
815 TRACE2("WRITE %d\n", last_page);
816 while( amt>0 && (rc = WriteFile(id->h, pBuf, amt, &wrote, 0))!=0 && wrote>0 ){
817 amt -= wrote;
818 pBuf = &((char*)pBuf)[wrote];
819 }
820 if( !rc || amt>(int)wrote ){
821 return SQLITE_FULL;
822 }
823 return SQLITE_OK;
824#endif
825#if OS_MAC
826 OSErr oserr;
827 int wrote = 0;
828 SimulateIOError(SQLITE_IOERR);
829 TRACE2("WRITE %d\n", last_page);
830 while( amt>0 ){
831# ifdef _LARGE_FILE
832 oserr = FSWriteFork(id->refNum, fsAtMark, 0,
833 (ByteCount)amt, pBuf, (ByteCount*)&wrote);
834# else
835 wrote = amt;
836 oserr = FSWrite(id->refNum, &wrote, pBuf);
837# endif
838 if( wrote == 0 || oserr != noErr)
839 break;
840 amt -= wrote;
841 pBuf = &((char*)pBuf)[wrote];
842 }
843 if( oserr != noErr || amt>wrote ){
844 return SQLITE_FULL;
845 }
846 return SQLITE_OK;
847#endif
848}
849
850/*
851** Move the read/write pointer in a file.
852*/
853int sqliteOsSeek(OsFile *id, off_t offset){
854 SEEK(offset/1024 + 1);
855#if OS_UNIX
856 lseek(id->fd, offset, SEEK_SET);
857 return SQLITE_OK;
858#endif
859#if OS_WIN
860 {
861 LONG upperBits = offset>>32;
862 LONG lowerBits = offset & 0xffffffff;
863 DWORD rc;
864 rc = SetFilePointer(id->h, lowerBits, &upperBits, FILE_BEGIN);
865 /* TRACE3("SEEK rc=0x%x upper=0x%x\n", rc, upperBits); */
866 }
867 return SQLITE_OK;
868#endif
869#if OS_MAC
870 {
871 off_t curSize;
872 if( sqliteOsFileSize(id, &curSize) != SQLITE_OK ){
873 return SQLITE_IOERR;
874 }
875 if( offset >= curSize ){
876 if( sqliteOsTruncate(id, offset+1) != SQLITE_OK ){
877 return SQLITE_IOERR;
878 }
879 }
880# ifdef _LARGE_FILE
881 if( FSSetForkPosition(id->refNum, fsFromStart, offset) != noErr ){
882# else
883 if( SetFPos(id->refNum, fsFromStart, offset) != noErr ){
884# endif
885 return SQLITE_IOERR;
886 }else{
887 return SQLITE_OK;
888 }
889 }
890#endif
891}
892
893/*
894** Make sure all writes to a particular file are committed to disk.
895*/
896int sqliteOsSync(OsFile *id){
897#if OS_UNIX
898 SimulateIOError(SQLITE_IOERR);
899 TRACE2("SYNC %-3d\n", id->fd);
900 if( fsync(id->fd) ){
901 return SQLITE_IOERR;
902 }else{
903 return SQLITE_OK;
904 }
905#endif
906#if OS_WIN
907 if( FlushFileBuffers(id->h) ){
908 return SQLITE_OK;
909 }else{
910 return SQLITE_IOERR;
911 }
912#endif
913#if OS_MAC
914# ifdef _LARGE_FILE
915 if( FSFlushFork(id->refNum) != noErr ){
916# else
917 ParamBlockRec params;
918 memset(&params, 0, sizeof(ParamBlockRec));
919 params.ioParam.ioRefNum = id->refNum;
920 if( PBFlushFileSync(&params) != noErr ){
921# endif
922 return SQLITE_IOERR;
923 }else{
924 return SQLITE_OK;
925 }
926#endif
927}
928
929/*
930** Truncate an open file to a specified size
931*/
932int sqliteOsTruncate(OsFile *id, off_t nByte){
933 SimulateIOError(SQLITE_IOERR);
934#if OS_UNIX
935 return ftruncate(id->fd, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
936#endif
937#if OS_WIN
938 {
939 LONG upperBits = nByte>>32;
940 SetFilePointer(id->h, nByte, &upperBits, FILE_BEGIN);
941 SetEndOfFile(id->h);
942 }
943 return SQLITE_OK;
944#endif
945#if OS_MAC
946# ifdef _LARGE_FILE
947 if( FSSetForkSize(id->refNum, fsFromStart, nByte) != noErr){
948# else
949 if( SetEOF(id->refNum, nByte) != noErr ){
950# endif
951 return SQLITE_IOERR;
952 }else{
953 return SQLITE_OK;
954 }
955#endif
956}
957
958/*
959** Determine the current size of a file in bytes
960*/
961int sqliteOsFileSize(OsFile *id, off_t *pSize){
962#if OS_UNIX
963 struct stat buf;
964 SimulateIOError(SQLITE_IOERR);
965 if( fstat(id->fd, &buf)!=0 ){
966 return SQLITE_IOERR;
967 }
968 *pSize = buf.st_size;
969 return SQLITE_OK;
970#endif
971#if OS_WIN
972 DWORD upperBits, lowerBits;
973 SimulateIOError(SQLITE_IOERR);
974 lowerBits = GetFileSize(id->h, &upperBits);
975 *pSize = (((off_t)upperBits)<<32) + lowerBits;
976 return SQLITE_OK;
977#endif
978#if OS_MAC
979# ifdef _LARGE_FILE
980 if( FSGetForkSize(id->refNum, pSize) != noErr){
981# else
982 if( GetEOF(id->refNum, pSize) != noErr ){
983# endif
984 return SQLITE_IOERR;
985 }else{
986 return SQLITE_OK;
987 }
988#endif
989}
990
991#if OS_WIN
992/*
993** Return true (non-zero) if we are running under WinNT, Win2K or WinXP.
994** Return false (zero) for Win95, Win98, or WinME.
995**
996** Here is an interesting observation: Win95, Win98, and WinME lack
997** the LockFileEx() API. But we can still statically link against that
998** API as long as we don't call it win running Win95/98/ME. A call to
999** this routine is used to determine if the host is Win95/98/ME or
1000** WinNT/2K/XP so that we will know whether or not we can safely call
1001** the LockFileEx() API.
1002*/
1003int isNT(void){
1004 static osType = 0; /* 0=unknown 1=win95 2=winNT */
1005 if( osType==0 ){
1006 int tmpOsType;
1007 OSVERSIONINFO sInfo;
1008 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
1009 GetVersionEx(&sInfo);
1010 osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
1011 }
1012 return osType==2;
1013}
1014#endif
1015
1016/*
1017** Windows file locking notes: [similar issues apply to MacOS]
1018**
1019** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
1020** those functions are not available. So we use only LockFile() and
1021** UnlockFile().
1022**
1023** LockFile() prevents not just writing but also reading by other processes.
1024** (This is a design error on the part of Windows, but there is nothing
1025** we can do about that.) So the region used for locking is at the
1026** end of the file where it is unlikely to ever interfere with an
1027** actual read attempt.
1028**
1029** A database read lock is obtained by locking a single randomly-chosen
1030** byte out of a specific range of bytes. The lock byte is obtained at
1031** random so two separate readers can probably access the file at the
1032** same time, unless they are unlucky and choose the same lock byte.
1033** A database write lock is obtained by locking all bytes in the range.
1034** There can only be one writer.
1035**
1036** A lock is obtained on the first byte of the lock range before acquiring
1037** either a read lock or a write lock. This prevents two processes from
1038** attempting to get a lock at a same time. The semantics of
1039** sqliteOsReadLock() require that if there is already a write lock, that
1040** lock is converted into a read lock atomically. The lock on the first
1041** byte allows us to drop the old write lock and get the read lock without
1042** another process jumping into the middle and messing us up. The same
1043** argument applies to sqliteOsWriteLock().
1044**
1045** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
1046** which means we can use reader/writer locks. When reader writer locks
1047** are used, the lock is placed on the same range of bytes that is used
1048** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
1049** will support two or more Win95 readers or two or more WinNT readers.
1050** But a single Win95 reader will lock out all WinNT readers and a single
1051** WinNT reader will lock out all other Win95 readers.
1052**
1053** Note: On MacOS we use the resource fork for locking.
1054**
1055** The following #defines specify the range of bytes used for locking.
1056** N_LOCKBYTE is the number of bytes available for doing the locking.
1057** The first byte used to hold the lock while the lock is changing does
1058** not count toward this number. FIRST_LOCKBYTE is the address of
1059** the first byte in the range of bytes used for locking.
1060*/
1061#define N_LOCKBYTE 10239
1062#if OS_MAC
1063# define FIRST_LOCKBYTE (0x000fffff - N_LOCKBYTE)
1064#else
1065# define FIRST_LOCKBYTE (0xffffffff - N_LOCKBYTE)
1066#endif
1067
1068/*
1069** Change the status of the lock on the file "id" to be a readlock.
1070** If the file was write locked, then this reduces the lock to a read.
1071** If the file was read locked, then this acquires a new read lock.
1072**
1073** Return SQLITE_OK on success and SQLITE_BUSY on failure. If this
1074** library was compiled with large file support (LFS) but LFS is not
1075** available on the host, then an SQLITE_NOLFS is returned.
1076*/
1077int sqliteOsReadLock(OsFile *id){
1078#if OS_UNIX
1079 int rc;
1080 sqliteOsEnterMutex();
1081 if( id->pLock->cnt>0 ){
1082 if( !id->locked ){
1083 id->pLock->cnt++;
1084 id->locked = 1;
1085 }
1086 rc = SQLITE_OK;
1087 }else if( id->locked || id->pLock->cnt==0 ){
1088 struct flock lock;
1089 int s;
1090 lock.l_type = F_RDLCK;
1091 lock.l_whence = SEEK_SET;
1092 lock.l_start = lock.l_len = 0L;
1093 s = fcntl(id->fd, F_SETLK, &lock);
1094 if( s!=0 ){
1095 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1096 }else{
1097 rc = SQLITE_OK;
1098 id->pLock->cnt = 1;
1099 id->locked = 1;
1100 }
1101 }else{
1102 rc = SQLITE_BUSY;
1103 }
1104 sqliteOsLeaveMutex();
1105 return rc;
1106#endif
1107#if OS_WIN
1108 int rc;
1109 if( id->locked>0 ){
1110 rc = SQLITE_OK;
1111 }else{
1112 int lk = (sqliteRandomInteger() & 0x7ffffff)%N_LOCKBYTE+1;
1113 int res;
1114 int cnt = 100;
1115 while( cnt-->0 && (res = LockFile(id->h, FIRST_LOCKBYTE, 0, 1, 0))==0 ){
1116 Sleep(1);
1117 }
1118 if( res ){
1119 UnlockFile(id->h, FIRST_LOCKBYTE+1, 0, N_LOCKBYTE, 0);
1120 if( isNT() ){
1121 OVERLAPPED ovlp;
1122 ovlp.Offset = FIRST_LOCKBYTE+1;
1123 ovlp.OffsetHigh = 0;
1124 ovlp.hEvent = 0;
1125 res = LockFileEx(id->h, LOCKFILE_FAIL_IMMEDIATELY,
1126 0, N_LOCKBYTE, 0, &ovlp);
1127 }else{
1128 res = LockFile(id->h, FIRST_LOCKBYTE+lk, 0, 1, 0);
1129 }
1130 UnlockFile(id->h, FIRST_LOCKBYTE, 0, 1, 0);
1131 }
1132 if( res ){
1133 id->locked = lk;
1134 rc = SQLITE_OK;
1135 }else{
1136 rc = SQLITE_BUSY;
1137 }
1138 }
1139 return rc;
1140#endif
1141#if OS_MAC
1142 int rc;
1143 if( id->locked>0 || id->refNumRF == -1 ){
1144 rc = SQLITE_OK;
1145 }else{
1146 int lk = (sqliteRandomInteger() & 0x7ffffff)%N_LOCKBYTE+1;
1147 OSErr res;
1148 int cnt = 5;
1149 ParamBlockRec params;
1150 memset(&params, 0, sizeof(params));
1151 params.ioParam.ioRefNum = id->refNumRF;
1152 params.ioParam.ioPosMode = fsFromStart;
1153 params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
1154 params.ioParam.ioReqCount = 1;
1155 while( cnt-->0 && (res = PBLockRangeSync(&params))!=noErr ){
1156 UInt32 finalTicks;
1157 Delay(1, &finalTicks); /* 1/60 sec */
1158 }
1159 if( res == noErr ){
1160 params.ioParam.ioPosOffset = FIRST_LOCKBYTE+1;
1161 params.ioParam.ioReqCount = N_LOCKBYTE;
1162 PBUnlockRangeSync(&params);
1163 params.ioParam.ioPosOffset = FIRST_LOCKBYTE+lk;
1164 params.ioParam.ioReqCount = 1;
1165 res = PBLockRangeSync(&params);
1166 params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
1167 params.ioParam.ioReqCount = 1;
1168 PBUnlockRangeSync(&params);
1169 }
1170 if( res == noErr ){
1171 id->locked = lk;
1172 rc = SQLITE_OK;
1173 }else{
1174 rc = SQLITE_BUSY;
1175 }
1176 }
1177 return rc;
1178#endif
1179}
1180
1181/*
1182** Change the lock status to be an exclusive or write lock. Return
1183** SQLITE_OK on success and SQLITE_BUSY on a failure. If this
1184** library was compiled with large file support (LFS) but LFS is not
1185** available on the host, then an SQLITE_NOLFS is returned.
1186*/
1187int sqliteOsWriteLock(OsFile *id){
1188#if OS_UNIX
1189 int rc;
1190 sqliteOsEnterMutex();
1191 if( id->pLock->cnt==0 || (id->pLock->cnt==1 && id->locked==1) ){
1192 struct flock lock;
1193 int s;
1194 lock.l_type = F_WRLCK;
1195 lock.l_whence = SEEK_SET;
1196 lock.l_start = lock.l_len = 0L;
1197 s = fcntl(id->fd, F_SETLK, &lock);
1198 if( s!=0 ){
1199 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1200 }else{
1201 rc = SQLITE_OK;
1202 id->pLock->cnt = -1;
1203 id->locked = 1;
1204 }
1205 }else{
1206 rc = SQLITE_BUSY;
1207 }
1208 sqliteOsLeaveMutex();
1209 return rc;
1210#endif
1211#if OS_WIN
1212 int rc;
1213 if( id->locked<0 ){
1214 rc = SQLITE_OK;
1215 }else{
1216 int res;
1217 int cnt = 100;
1218 while( cnt-->0 && (res = LockFile(id->h, FIRST_LOCKBYTE, 0, 1, 0))==0 ){
1219 Sleep(1);
1220 }
1221 if( res ){
1222 if( id->locked>0 ){
1223 if( isNT() ){
1224 UnlockFile(id->h, FIRST_LOCKBYTE+1, 0, N_LOCKBYTE, 0);
1225 }else{
1226 res = UnlockFile(id->h, FIRST_LOCKBYTE + id->locked, 0, 1, 0);
1227 }
1228 }
1229 if( res ){
1230 res = LockFile(id->h, FIRST_LOCKBYTE+1, 0, N_LOCKBYTE, 0);
1231 }else{
1232 res = 0;
1233 }
1234 UnlockFile(id->h, FIRST_LOCKBYTE, 0, 1, 0);
1235 }
1236 if( res ){
1237 id->locked = -1;
1238 rc = SQLITE_OK;
1239 }else{
1240 rc = SQLITE_BUSY;
1241 }
1242 }
1243 return rc;
1244#endif
1245#if OS_MAC
1246 int rc;
1247 if( id->locked<0 || id->refNumRF == -1 ){
1248 rc = SQLITE_OK;
1249 }else{
1250 OSErr res;
1251 int cnt = 5;
1252 ParamBlockRec params;
1253 memset(&params, 0, sizeof(params));
1254 params.ioParam.ioRefNum = id->refNumRF;
1255 params.ioParam.ioPosMode = fsFromStart;
1256 params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
1257 params.ioParam.ioReqCount = 1;
1258 while( cnt-->0 && (res = PBLockRangeSync(&params))!=noErr ){
1259 UInt32 finalTicks;
1260 Delay(1, &finalTicks); /* 1/60 sec */
1261 }
1262 if( res == noErr ){
1263 params.ioParam.ioPosOffset = FIRST_LOCKBYTE + id->locked;
1264 params.ioParam.ioReqCount = 1;
1265 if( id->locked==0
1266 || PBUnlockRangeSync(&params)==noErr ){
1267 params.ioParam.ioPosOffset = FIRST_LOCKBYTE+1;
1268 params.ioParam.ioReqCount = N_LOCKBYTE;
1269 res = PBLockRangeSync(&params);
1270 }else{
1271 res = afpRangeNotLocked;
1272 }
1273 params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
1274 params.ioParam.ioReqCount = 1;
1275 PBUnlockRangeSync(&params);
1276 }
1277 if( res == noErr ){
1278 id->locked = -1;
1279 rc = SQLITE_OK;
1280 }else{
1281 rc = SQLITE_BUSY;
1282 }
1283 }
1284 return rc;
1285#endif
1286}
1287
1288/*
1289** Unlock the given file descriptor. If the file descriptor was
1290** not previously locked, then this routine is a no-op. If this
1291** library was compiled with large file support (LFS) but LFS is not
1292** available on the host, then an SQLITE_NOLFS is returned.
1293*/
1294int sqliteOsUnlock(OsFile *id){
1295#if OS_UNIX
1296 int rc;
1297 if( !id->locked ) return SQLITE_OK;
1298 sqliteOsEnterMutex();
1299 assert( id->pLock->cnt!=0 );
1300 if( id->pLock->cnt>1 ){
1301 id->pLock->cnt--;
1302 rc = SQLITE_OK;
1303 }else{
1304 struct flock lock;
1305 int s;
1306 lock.l_type = F_UNLCK;
1307 lock.l_whence = SEEK_SET;
1308 lock.l_start = lock.l_len = 0L;
1309 s = fcntl(id->fd, F_SETLK, &lock);
1310 if( s!=0 ){
1311 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1312 }else{
1313 rc = SQLITE_OK;
1314 id->pLock->cnt = 0;
1315 }
1316 }
1317 sqliteOsLeaveMutex();
1318 id->locked = 0;
1319 return rc;
1320#endif
1321#if OS_WIN
1322 int rc;
1323 if( id->locked==0 ){
1324 rc = SQLITE_OK;
1325 }else if( isNT() || id->locked<0 ){
1326 UnlockFile(id->h, FIRST_LOCKBYTE+1, 0, N_LOCKBYTE, 0);
1327 rc = SQLITE_OK;
1328 id->locked = 0;
1329 }else{
1330 UnlockFile(id->h, FIRST_LOCKBYTE+id->locked, 0, 1, 0);
1331 rc = SQLITE_OK;
1332 id->locked = 0;
1333 }
1334 return rc;
1335#endif
1336#if OS_MAC
1337 int rc;
1338 ParamBlockRec params;
1339 memset(&params, 0, sizeof(params));
1340 params.ioParam.ioRefNum = id->refNumRF;
1341 params.ioParam.ioPosMode = fsFromStart;
1342 if( id->locked==0 || id->refNumRF == -1 ){
1343 rc = SQLITE_OK;
1344 }else if( id->locked<0 ){
1345 params.ioParam.ioPosOffset = FIRST_LOCKBYTE+1;
1346 params.ioParam.ioReqCount = N_LOCKBYTE;
1347 PBUnlockRangeSync(&params);
1348 rc = SQLITE_OK;
1349 id->locked = 0;
1350 }else{
1351 params.ioParam.ioPosOffset = FIRST_LOCKBYTE+id->locked;
1352 params.ioParam.ioReqCount = 1;
1353 PBUnlockRangeSync(&params);
1354 rc = SQLITE_OK;
1355 id->locked = 0;
1356 }
1357 return rc;
1358#endif
1359}
1360
1361/*
1362** Get information to seed the random number generator. The seed
1363** is written into the buffer zBuf[256]. The calling function must
1364** supply a sufficiently large buffer.
1365*/
1366int sqliteOsRandomSeed(char *zBuf){
1367 memset(zBuf, 0, 256);
1368#ifdef SQLITE_TEST
1369 /* When testing, always use the same random number sequence.
1370 ** This makes the tests repeatable.
1371 */
1372 memset(zBuf, 0, 256);
1373#endif
1374#if OS_UNIX && !defined(SQLITE_TEST)
1375 int pid;
1376 time((time_t*)zBuf);
1377 pid = getpid();
1378 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1379#endif
1380#if OS_WIN && !defined(SQLITE_TEST)
1381 GetSystemTime((LPSYSTEMTIME)zBuf);
1382#endif
1383#if OS_MAC
1384 int pid;
1385 Microseconds((UnsignedWide*)zBuf);
1386 pid = getpid();
1387 memcpy(&zBuf[sizeof(UnsignedWide)], &pid, sizeof(pid));
1388#endif
1389 return SQLITE_OK;
1390}
1391
1392/*
1393** Sleep for a little while. Return the amount of time slept.
1394*/
1395int sqliteOsSleep(int ms){
1396#if OS_UNIX
1397#if defined(HAVE_USLEEP) && HAVE_USLEEP
1398 usleep(ms*1000);
1399 return ms;
1400#else
1401 sleep((ms+999)/1000);
1402 return 1000*((ms+999)/1000);
1403#endif
1404#endif
1405#if OS_WIN
1406 Sleep(ms);
1407 return ms;
1408#endif
1409#if OS_MAC
1410 UInt32 finalTicks;
1411 UInt32 ticks = (((UInt32)ms+16)*3)/50; /* 1/60 sec per tick */
1412 Delay(ticks, &finalTicks);
1413 return (int)((ticks*50)/3);
1414#endif
1415}
1416
1417/*
1418** Macros used to determine whether or not to use threads. The
1419** SQLITE_UNIX_THREADS macro is defined if we are synchronizing for
1420** Posix threads and SQLITE_W32_THREADS is defined if we are
1421** synchronizing using Win32 threads.
1422*/
1423#if OS_UNIX && defined(THREADSAFE) && THREADSAFE
1424# include <pthread.h>
1425# define SQLITE_UNIX_THREADS 1
1426#endif
1427#if OS_WIN && defined(THREADSAFE) && THREADSAFE
1428# define SQLITE_W32_THREADS 1
1429#endif
1430#if OS_MAC && defined(THREADSAFE) && THREADSAFE
1431# include <Multiprocessing.h>
1432# define SQLITE_MACOS_MULTITASKING 1
1433#endif
1434
1435/*
1436** Static variables used for thread synchronization
1437*/
1438static int inMutex = 0;
1439#ifdef SQLITE_UNIX_THREADS
1440 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
1441#endif
1442#ifdef SQLITE_W32_THREADS
1443 static CRITICAL_SECTION cs;
1444#endif
1445#ifdef SQLITE_MACOS_MULTITASKING
1446 static MPCriticalRegionID criticalRegion;
1447#endif
1448
1449/*
1450** The following pair of routine implement mutual exclusion for
1451** multi-threaded processes. Only a single thread is allowed to
1452** executed code that is surrounded by EnterMutex() and LeaveMutex().
1453**
1454** SQLite uses only a single Mutex. There is not much critical
1455** code and what little there is executes quickly and without blocking.
1456*/
1457void sqliteOsEnterMutex(){
1458#ifdef SQLITE_UNIX_THREADS
1459 pthread_mutex_lock(&mutex);
1460#endif
1461#ifdef SQLITE_W32_THREADS
1462 static int isInit = 0;
1463 while( !isInit ){
1464 static long lock = 0;
1465 if( InterlockedIncrement(&lock)==1 ){
1466 InitializeCriticalSection(&cs);
1467 isInit = 1;
1468 }else{
1469 Sleep(1);
1470 }
1471 }
1472 EnterCriticalSection(&cs);
1473#endif
1474#ifdef SQLITE_MACOS_MULTITASKING
1475 static volatile int notInit = 1;
1476 if( notInit ){
1477 if( notInit == 2 ) /* as close as you can get to thread safe init */
1478 MPYield();
1479 else{
1480 notInit = 2;
1481 MPCreateCriticalRegion(&criticalRegion);
1482 notInit = 0;
1483 }
1484 }
1485 MPEnterCriticalRegion(criticalRegion, kDurationForever);
1486#endif
1487 assert( !inMutex );
1488 inMutex = 1;
1489}
1490void sqliteOsLeaveMutex(){
1491 assert( inMutex );
1492 inMutex = 0;
1493#ifdef SQLITE_UNIX_THREADS
1494 pthread_mutex_unlock(&mutex);
1495#endif
1496#ifdef SQLITE_W32_THREADS
1497 LeaveCriticalSection(&cs);
1498#endif
1499#ifdef SQLITE_MACOS_MULTITASKING
1500 MPExitCriticalRegion(criticalRegion);
1501#endif
1502}
1503
1504/*
1505** Turn a relative pathname into a full pathname. Return a pointer
1506** to the full pathname stored in space obtained from sqliteMalloc().
1507** The calling function is responsible for freeing this space once it
1508** is no longer needed.
1509*/
1510char *sqliteOsFullPathname(const char *zRelative){
1511#if OS_UNIX
1512 char *zFull = 0;
1513 if( zRelative[0]=='/' ){
1514 sqliteSetString(&zFull, zRelative, 0);
1515 }else{
1516 char zBuf[5000];
1517 sqliteSetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative, 0);
1518 }
1519 return zFull;
1520#endif
1521#if OS_WIN
1522 char *zNotUsed;
1523 char *zFull;
1524 int nByte;
1525 nByte = GetFullPathName(zRelative, 0, 0, &zNotUsed) + 1;
1526 zFull = sqliteMalloc( nByte );
1527 if( zFull==0 ) return 0;
1528 GetFullPathName(zRelative, nByte, zFull, &zNotUsed);
1529 return zFull;
1530#endif
1531#if OS_MAC
1532 char *zFull = 0;
1533 if( zRelative[0]==':' ){
1534 char zBuf[_MAX_PATH+1];
1535 sqliteSetString(&zFull, getcwd(zBuf, sizeof(zBuf)), &(zRelative[1]), 0);
1536 }else{
1537 if( strchr(zRelative, ':') ){
1538 sqliteSetString(&zFull, zRelative, 0);
1539 }else{
1540 char zBuf[_MAX_PATH+1];
1541 sqliteSetString(&zFull, getcwd(zBuf, sizeof(zBuf)), zRelative, 0);
1542 }
1543 }
1544 return zFull;
1545#endif
1546}

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status