You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1820 lines
50 KiB

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