drh | bbd42a6 | 2004-05-22 17:41:58 +0000 | [diff] [blame] | 1 | /* |
| 2 | ** 2004 May 22 |
| 3 | ** |
| 4 | ** The author disclaims copyright to this source code. In place of |
| 5 | ** a legal notice, here is a blessing: |
| 6 | ** |
| 7 | ** May you do good and not evil. |
| 8 | ** May you find forgiveness for yourself and forgive others. |
| 9 | ** May you share freely, never taking more than you give. |
| 10 | ** |
| 11 | ****************************************************************************** |
| 12 | ** |
| 13 | ** This file contains code that is specific to Unix systems. |
| 14 | */ |
| 15 | #include "os.h" /* Must be first to enable large file support */ |
| 16 | #if OS_UNIX /* This file is used on unix only */ |
| 17 | #include "sqliteInt.h" |
| 18 | |
| 19 | |
| 20 | #include <time.h> |
| 21 | #include <errno.h> |
| 22 | #include <unistd.h> |
| 23 | #ifndef O_LARGEFILE |
| 24 | # define O_LARGEFILE 0 |
| 25 | #endif |
| 26 | #ifdef SQLITE_DISABLE_LFS |
| 27 | # undef O_LARGEFILE |
| 28 | # define O_LARGEFILE 0 |
| 29 | #endif |
| 30 | #ifndef O_NOFOLLOW |
| 31 | # define O_NOFOLLOW 0 |
| 32 | #endif |
| 33 | #ifndef O_BINARY |
| 34 | # define O_BINARY 0 |
| 35 | #endif |
| 36 | |
| 37 | /* |
| 38 | ** The DJGPP compiler environment looks mostly like Unix, but it |
| 39 | ** lacks the fcntl() system call. So redefine fcntl() to be something |
| 40 | ** that always succeeds. This means that locking does not occur under |
| 41 | ** DJGPP. But its DOS - what did you expect? |
| 42 | */ |
| 43 | #ifdef __DJGPP__ |
| 44 | # define fcntl(A,B,C) 0 |
| 45 | #endif |
| 46 | |
| 47 | /* |
| 48 | ** Macros used to determine whether or not to use threads. The |
| 49 | ** SQLITE_UNIX_THREADS macro is defined if we are synchronizing for |
| 50 | ** Posix threads and SQLITE_W32_THREADS is defined if we are |
| 51 | ** synchronizing using Win32 threads. |
| 52 | */ |
| 53 | #if defined(THREADSAFE) && THREADSAFE |
| 54 | # include <pthread.h> |
| 55 | # define SQLITE_UNIX_THREADS 1 |
| 56 | #endif |
| 57 | |
| 58 | |
| 59 | /* |
| 60 | ** Include code that is common to all os_*.c files |
| 61 | */ |
| 62 | #include "os_common.h" |
| 63 | |
| 64 | |
| 65 | /* |
| 66 | ** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996) |
| 67 | ** section 6.5.2.2 lines 483 through 490 specify that when a process |
| 68 | ** sets or clears a lock, that operation overrides any prior locks set |
| 69 | ** by the same process. It does not explicitly say so, but this implies |
| 70 | ** that it overrides locks set by the same process using a different |
| 71 | ** file descriptor. Consider this test case: |
| 72 | ** |
| 73 | ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644); |
| 74 | ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644); |
| 75 | ** |
| 76 | ** Suppose ./file1 and ./file2 are really the same file (because |
| 77 | ** one is a hard or symbolic link to the other) then if you set |
| 78 | ** an exclusive lock on fd1, then try to get an exclusive lock |
| 79 | ** on fd2, it works. I would have expected the second lock to |
| 80 | ** fail since there was already a lock on the file due to fd1. |
| 81 | ** But not so. Since both locks came from the same process, the |
| 82 | ** second overrides the first, even though they were on different |
| 83 | ** file descriptors opened on different file names. |
| 84 | ** |
| 85 | ** Bummer. If you ask me, this is broken. Badly broken. It means |
| 86 | ** that we cannot use POSIX locks to synchronize file access among |
| 87 | ** competing threads of the same process. POSIX locks will work fine |
| 88 | ** to synchronize access for threads in separate processes, but not |
| 89 | ** threads within the same process. |
| 90 | ** |
| 91 | ** To work around the problem, SQLite has to manage file locks internally |
| 92 | ** on its own. Whenever a new database is opened, we have to find the |
| 93 | ** specific inode of the database file (the inode is determined by the |
| 94 | ** st_dev and st_ino fields of the stat structure that fstat() fills in) |
| 95 | ** and check for locks already existing on that inode. When locks are |
| 96 | ** created or removed, we have to look at our own internal record of the |
| 97 | ** locks to see if another thread has previously set a lock on that same |
| 98 | ** inode. |
| 99 | ** |
| 100 | ** The OsFile structure for POSIX is no longer just an integer file |
| 101 | ** descriptor. It is now a structure that holds the integer file |
| 102 | ** descriptor and a pointer to a structure that describes the internal |
| 103 | ** locks on the corresponding inode. There is one locking structure |
| 104 | ** per inode, so if the same inode is opened twice, both OsFile structures |
| 105 | ** point to the same locking structure. The locking structure keeps |
| 106 | ** a reference count (so we will know when to delete it) and a "cnt" |
| 107 | ** field that tells us its internal lock status. cnt==0 means the |
| 108 | ** file is unlocked. cnt==-1 means the file has an exclusive lock. |
| 109 | ** cnt>0 means there are cnt shared locks on the file. |
| 110 | ** |
| 111 | ** Any attempt to lock or unlock a file first checks the locking |
| 112 | ** structure. The fcntl() system call is only invoked to set a |
| 113 | ** POSIX lock if the internal lock structure transitions between |
| 114 | ** a locked and an unlocked state. |
| 115 | ** |
| 116 | ** 2004-Jan-11: |
| 117 | ** More recent discoveries about POSIX advisory locks. (The more |
| 118 | ** I discover, the more I realize the a POSIX advisory locks are |
| 119 | ** an abomination.) |
| 120 | ** |
| 121 | ** If you close a file descriptor that points to a file that has locks, |
| 122 | ** all locks on that file that are owned by the current process are |
| 123 | ** released. To work around this problem, each OsFile structure contains |
| 124 | ** a pointer to an openCnt structure. There is one openCnt structure |
| 125 | ** per open inode, which means that multiple OsFiles can point to a single |
| 126 | ** openCnt. When an attempt is made to close an OsFile, if there are |
| 127 | ** other OsFiles open on the same inode that are holding locks, the call |
| 128 | ** to close() the file descriptor is deferred until all of the locks clear. |
| 129 | ** The openCnt structure keeps a list of file descriptors that need to |
| 130 | ** be closed and that list is walked (and cleared) when the last lock |
| 131 | ** clears. |
| 132 | ** |
| 133 | ** First, under Linux threads, because each thread has a separate |
| 134 | ** process ID, lock operations in one thread do not override locks |
| 135 | ** to the same file in other threads. Linux threads behave like |
| 136 | ** separate processes in this respect. But, if you close a file |
| 137 | ** descriptor in linux threads, all locks are cleared, even locks |
| 138 | ** on other threads and even though the other threads have different |
| 139 | ** process IDs. Linux threads is inconsistent in this respect. |
| 140 | ** (I'm beginning to think that linux threads is an abomination too.) |
| 141 | ** The consequence of this all is that the hash table for the lockInfo |
| 142 | ** structure has to include the process id as part of its key because |
| 143 | ** locks in different threads are treated as distinct. But the |
| 144 | ** openCnt structure should not include the process id in its |
| 145 | ** key because close() clears lock on all threads, not just the current |
| 146 | ** thread. Were it not for this goofiness in linux threads, we could |
| 147 | ** combine the lockInfo and openCnt structures into a single structure. |
| 148 | */ |
| 149 | |
| 150 | /* |
| 151 | ** An instance of the following structure serves as the key used |
| 152 | ** to locate a particular lockInfo structure given its inode. Note |
| 153 | ** that we have to include the process ID as part of the key. On some |
| 154 | ** threading implementations (ex: linux), each thread has a separate |
| 155 | ** process ID. |
| 156 | */ |
| 157 | struct lockKey { |
| 158 | dev_t dev; /* Device number */ |
| 159 | ino_t ino; /* Inode number */ |
| 160 | pid_t pid; /* Process ID */ |
| 161 | }; |
| 162 | |
| 163 | /* |
| 164 | ** An instance of the following structure is allocated for each open |
| 165 | ** inode on each thread with a different process ID. (Threads have |
| 166 | ** different process IDs on linux, but not on most other unixes.) |
| 167 | ** |
| 168 | ** A single inode can have multiple file descriptors, so each OsFile |
| 169 | ** structure contains a pointer to an instance of this object and this |
| 170 | ** object keeps a count of the number of OsFiles pointing to it. |
| 171 | */ |
| 172 | struct lockInfo { |
| 173 | struct lockKey key; /* The lookup key */ |
| 174 | int cnt; /* 0: unlocked. -1: write lock. 1...: read lock. */ |
| 175 | int nRef; /* Number of pointers to this structure */ |
| 176 | }; |
| 177 | |
| 178 | /* |
| 179 | ** An instance of the following structure serves as the key used |
| 180 | ** to locate a particular openCnt structure given its inode. This |
| 181 | ** is the same as the lockKey except that the process ID is omitted. |
| 182 | */ |
| 183 | struct openKey { |
| 184 | dev_t dev; /* Device number */ |
| 185 | ino_t ino; /* Inode number */ |
| 186 | }; |
| 187 | |
| 188 | /* |
| 189 | ** An instance of the following structure is allocated for each open |
| 190 | ** inode. This structure keeps track of the number of locks on that |
| 191 | ** inode. If a close is attempted against an inode that is holding |
| 192 | ** locks, the close is deferred until all locks clear by adding the |
| 193 | ** file descriptor to be closed to the pending list. |
| 194 | */ |
| 195 | struct openCnt { |
| 196 | struct openKey key; /* The lookup key */ |
| 197 | int nRef; /* Number of pointers to this structure */ |
| 198 | int nLock; /* Number of outstanding locks */ |
| 199 | int nPending; /* Number of pending close() operations */ |
| 200 | int *aPending; /* Malloced space holding fd's awaiting a close() */ |
| 201 | }; |
| 202 | |
| 203 | /* |
| 204 | ** These hash table maps inodes and process IDs into lockInfo and openCnt |
| 205 | ** structures. Access to these hash tables must be protected by a mutex. |
| 206 | */ |
| 207 | static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 }; |
| 208 | static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 }; |
| 209 | |
| 210 | /* |
| 211 | ** Release a lockInfo structure previously allocated by findLockInfo(). |
| 212 | */ |
| 213 | static void releaseLockInfo(struct lockInfo *pLock){ |
| 214 | pLock->nRef--; |
| 215 | if( pLock->nRef==0 ){ |
| 216 | sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0); |
| 217 | sqliteFree(pLock); |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | /* |
| 222 | ** Release a openCnt structure previously allocated by findLockInfo(). |
| 223 | */ |
| 224 | static void releaseOpenCnt(struct openCnt *pOpen){ |
| 225 | pOpen->nRef--; |
| 226 | if( pOpen->nRef==0 ){ |
| 227 | sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0); |
| 228 | sqliteFree(pOpen->aPending); |
| 229 | sqliteFree(pOpen); |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | /* |
| 234 | ** Given a file descriptor, locate lockInfo and openCnt structures that |
| 235 | ** describes that file descriptor. Create a new ones if necessary. The |
| 236 | ** return values might be unset if an error occurs. |
| 237 | ** |
| 238 | ** Return the number of errors. |
| 239 | */ |
| 240 | int findLockInfo( |
| 241 | int fd, /* The file descriptor used in the key */ |
| 242 | struct lockInfo **ppLock, /* Return the lockInfo structure here */ |
| 243 | struct openCnt **ppOpen /* Return the openCnt structure here */ |
| 244 | ){ |
| 245 | int rc; |
| 246 | struct lockKey key1; |
| 247 | struct openKey key2; |
| 248 | struct stat statbuf; |
| 249 | struct lockInfo *pLock; |
| 250 | struct openCnt *pOpen; |
| 251 | rc = fstat(fd, &statbuf); |
| 252 | if( rc!=0 ) return 1; |
| 253 | memset(&key1, 0, sizeof(key1)); |
| 254 | key1.dev = statbuf.st_dev; |
| 255 | key1.ino = statbuf.st_ino; |
| 256 | key1.pid = getpid(); |
| 257 | memset(&key2, 0, sizeof(key2)); |
| 258 | key2.dev = statbuf.st_dev; |
| 259 | key2.ino = statbuf.st_ino; |
| 260 | pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1)); |
| 261 | if( pLock==0 ){ |
| 262 | struct lockInfo *pOld; |
| 263 | pLock = sqliteMallocRaw( sizeof(*pLock) ); |
| 264 | if( pLock==0 ) return 1; |
| 265 | pLock->key = key1; |
| 266 | pLock->nRef = 1; |
| 267 | pLock->cnt = 0; |
| 268 | pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock); |
| 269 | if( pOld!=0 ){ |
| 270 | assert( pOld==pLock ); |
| 271 | sqliteFree(pLock); |
| 272 | return 1; |
| 273 | } |
| 274 | }else{ |
| 275 | pLock->nRef++; |
| 276 | } |
| 277 | *ppLock = pLock; |
| 278 | pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2)); |
| 279 | if( pOpen==0 ){ |
| 280 | struct openCnt *pOld; |
| 281 | pOpen = sqliteMallocRaw( sizeof(*pOpen) ); |
| 282 | if( pOpen==0 ){ |
| 283 | releaseLockInfo(pLock); |
| 284 | return 1; |
| 285 | } |
| 286 | pOpen->key = key2; |
| 287 | pOpen->nRef = 1; |
| 288 | pOpen->nLock = 0; |
| 289 | pOpen->nPending = 0; |
| 290 | pOpen->aPending = 0; |
| 291 | pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen); |
| 292 | if( pOld!=0 ){ |
| 293 | assert( pOld==pOpen ); |
| 294 | sqliteFree(pOpen); |
| 295 | releaseLockInfo(pLock); |
| 296 | return 1; |
| 297 | } |
| 298 | }else{ |
| 299 | pOpen->nRef++; |
| 300 | } |
| 301 | *ppOpen = pOpen; |
| 302 | return 0; |
| 303 | } |
| 304 | |
| 305 | /* |
| 306 | ** Delete the named file |
| 307 | */ |
| 308 | int sqlite3OsDelete(const char *zFilename){ |
| 309 | unlink(zFilename); |
| 310 | return SQLITE_OK; |
| 311 | } |
| 312 | |
| 313 | /* |
| 314 | ** Return TRUE if the named file exists. |
| 315 | */ |
| 316 | int sqlite3OsFileExists(const char *zFilename){ |
| 317 | return access(zFilename, 0)==0; |
| 318 | } |
| 319 | |
| 320 | /* |
| 321 | ** Attempt to open a file for both reading and writing. If that |
| 322 | ** fails, try opening it read-only. If the file does not exist, |
| 323 | ** try to create it. |
| 324 | ** |
| 325 | ** On success, a handle for the open file is written to *id |
| 326 | ** and *pReadonly is set to 0 if the file was opened for reading and |
| 327 | ** writing or 1 if the file was opened read-only. The function returns |
| 328 | ** SQLITE_OK. |
| 329 | ** |
| 330 | ** On failure, the function returns SQLITE_CANTOPEN and leaves |
| 331 | ** *id and *pReadonly unchanged. |
| 332 | */ |
| 333 | int sqlite3OsOpenReadWrite( |
| 334 | const char *zFilename, |
| 335 | OsFile *id, |
| 336 | int *pReadonly |
| 337 | ){ |
| 338 | int rc; |
| 339 | id->dirfd = -1; |
| 340 | id->fd = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY, 0644); |
| 341 | if( id->fd<0 ){ |
| 342 | id->fd = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY); |
| 343 | if( id->fd<0 ){ |
| 344 | return SQLITE_CANTOPEN; |
| 345 | } |
| 346 | *pReadonly = 1; |
| 347 | }else{ |
| 348 | *pReadonly = 0; |
| 349 | } |
| 350 | sqlite3OsEnterMutex(); |
| 351 | rc = findLockInfo(id->fd, &id->pLock, &id->pOpen); |
| 352 | sqlite3OsLeaveMutex(); |
| 353 | if( rc ){ |
| 354 | close(id->fd); |
| 355 | return SQLITE_NOMEM; |
| 356 | } |
| 357 | id->locked = 0; |
| 358 | TRACE3("OPEN %-3d %s\n", id->fd, zFilename); |
| 359 | OpenCounter(+1); |
| 360 | return SQLITE_OK; |
| 361 | } |
| 362 | |
| 363 | |
| 364 | /* |
| 365 | ** Attempt to open a new file for exclusive access by this process. |
| 366 | ** The file will be opened for both reading and writing. To avoid |
| 367 | ** a potential security problem, we do not allow the file to have |
| 368 | ** previously existed. Nor do we allow the file to be a symbolic |
| 369 | ** link. |
| 370 | ** |
| 371 | ** If delFlag is true, then make arrangements to automatically delete |
| 372 | ** the file when it is closed. |
| 373 | ** |
| 374 | ** On success, write the file handle into *id and return SQLITE_OK. |
| 375 | ** |
| 376 | ** On failure, return SQLITE_CANTOPEN. |
| 377 | */ |
| 378 | int sqlite3OsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){ |
| 379 | int rc; |
| 380 | if( access(zFilename, 0)==0 ){ |
| 381 | return SQLITE_CANTOPEN; |
| 382 | } |
| 383 | id->dirfd = -1; |
| 384 | id->fd = open(zFilename, |
| 385 | O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY, 0600); |
| 386 | if( id->fd<0 ){ |
| 387 | return SQLITE_CANTOPEN; |
| 388 | } |
| 389 | sqlite3OsEnterMutex(); |
| 390 | rc = findLockInfo(id->fd, &id->pLock, &id->pOpen); |
| 391 | sqlite3OsLeaveMutex(); |
| 392 | if( rc ){ |
| 393 | close(id->fd); |
| 394 | unlink(zFilename); |
| 395 | return SQLITE_NOMEM; |
| 396 | } |
| 397 | id->locked = 0; |
| 398 | if( delFlag ){ |
| 399 | unlink(zFilename); |
| 400 | } |
| 401 | TRACE3("OPEN-EX %-3d %s\n", id->fd, zFilename); |
| 402 | OpenCounter(+1); |
| 403 | return SQLITE_OK; |
| 404 | } |
| 405 | |
| 406 | /* |
| 407 | ** Attempt to open a new file for read-only access. |
| 408 | ** |
| 409 | ** On success, write the file handle into *id and return SQLITE_OK. |
| 410 | ** |
| 411 | ** On failure, return SQLITE_CANTOPEN. |
| 412 | */ |
| 413 | int sqlite3OsOpenReadOnly(const char *zFilename, OsFile *id){ |
| 414 | int rc; |
| 415 | id->dirfd = -1; |
| 416 | id->fd = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY); |
| 417 | if( id->fd<0 ){ |
| 418 | return SQLITE_CANTOPEN; |
| 419 | } |
| 420 | sqlite3OsEnterMutex(); |
| 421 | rc = findLockInfo(id->fd, &id->pLock, &id->pOpen); |
| 422 | sqlite3OsLeaveMutex(); |
| 423 | if( rc ){ |
| 424 | close(id->fd); |
| 425 | return SQLITE_NOMEM; |
| 426 | } |
| 427 | id->locked = 0; |
| 428 | TRACE3("OPEN-RO %-3d %s\n", id->fd, zFilename); |
| 429 | OpenCounter(+1); |
| 430 | return SQLITE_OK; |
| 431 | } |
| 432 | |
| 433 | /* |
| 434 | ** Attempt to open a file descriptor for the directory that contains a |
| 435 | ** file. This file descriptor can be used to fsync() the directory |
| 436 | ** in order to make sure the creation of a new file is actually written |
| 437 | ** to disk. |
| 438 | ** |
| 439 | ** This routine is only meaningful for Unix. It is a no-op under |
| 440 | ** windows since windows does not support hard links. |
| 441 | ** |
| 442 | ** On success, a handle for a previously open file is at *id is |
| 443 | ** updated with the new directory file descriptor and SQLITE_OK is |
| 444 | ** returned. |
| 445 | ** |
| 446 | ** On failure, the function returns SQLITE_CANTOPEN and leaves |
| 447 | ** *id unchanged. |
| 448 | */ |
| 449 | int sqlite3OsOpenDirectory( |
| 450 | const char *zDirname, |
| 451 | OsFile *id |
| 452 | ){ |
| 453 | if( id->fd<0 ){ |
| 454 | /* Do not open the directory if the corresponding file is not already |
| 455 | ** open. */ |
| 456 | return SQLITE_CANTOPEN; |
| 457 | } |
| 458 | assert( id->dirfd<0 ); |
| 459 | id->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0644); |
| 460 | if( id->dirfd<0 ){ |
| 461 | return SQLITE_CANTOPEN; |
| 462 | } |
| 463 | TRACE3("OPENDIR %-3d %s\n", id->dirfd, zDirname); |
| 464 | return SQLITE_OK; |
| 465 | } |
| 466 | |
| 467 | /* |
| 468 | ** Create a temporary file name in zBuf. zBuf must be big enough to |
| 469 | ** hold at least SQLITE_TEMPNAME_SIZE characters. |
| 470 | */ |
| 471 | int sqlite3OsTempFileName(char *zBuf){ |
| 472 | static const char *azDirs[] = { |
| 473 | "/var/tmp", |
| 474 | "/usr/tmp", |
| 475 | "/tmp", |
| 476 | ".", |
| 477 | }; |
| 478 | static unsigned char zChars[] = |
| 479 | "abcdefghijklmnopqrstuvwxyz" |
| 480 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" |
| 481 | "0123456789"; |
| 482 | int i, j; |
| 483 | struct stat buf; |
| 484 | const char *zDir = "."; |
| 485 | for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){ |
| 486 | if( stat(azDirs[i], &buf) ) continue; |
| 487 | if( !S_ISDIR(buf.st_mode) ) continue; |
| 488 | if( access(azDirs[i], 07) ) continue; |
| 489 | zDir = azDirs[i]; |
| 490 | break; |
| 491 | } |
| 492 | do{ |
| 493 | sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir); |
| 494 | j = strlen(zBuf); |
| 495 | sqlite3Randomness(15, &zBuf[j]); |
| 496 | for(i=0; i<15; i++, j++){ |
| 497 | zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; |
| 498 | } |
| 499 | zBuf[j] = 0; |
| 500 | }while( access(zBuf,0)==0 ); |
| 501 | return SQLITE_OK; |
| 502 | } |
| 503 | |
| 504 | /* |
| 505 | ** Close a file. |
| 506 | */ |
| 507 | int sqlite3OsClose(OsFile *id){ |
| 508 | sqlite3OsUnlock(id); |
| 509 | if( id->dirfd>=0 ) close(id->dirfd); |
| 510 | id->dirfd = -1; |
| 511 | sqlite3OsEnterMutex(); |
| 512 | if( id->pOpen->nLock ){ |
| 513 | /* If there are outstanding locks, do not actually close the file just |
| 514 | ** yet because that would clear those locks. Instead, add the file |
| 515 | ** descriptor to pOpen->aPending. It will be automatically closed when |
| 516 | ** the last lock is cleared. |
| 517 | */ |
| 518 | int *aNew; |
| 519 | struct openCnt *pOpen = id->pOpen; |
| 520 | pOpen->nPending++; |
| 521 | aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) ); |
| 522 | if( aNew==0 ){ |
| 523 | /* If a malloc fails, just leak the file descriptor */ |
| 524 | }else{ |
| 525 | pOpen->aPending = aNew; |
| 526 | pOpen->aPending[pOpen->nPending-1] = id->fd; |
| 527 | } |
| 528 | }else{ |
| 529 | /* There are no outstanding locks so we can close the file immediately */ |
| 530 | close(id->fd); |
| 531 | } |
| 532 | releaseLockInfo(id->pLock); |
| 533 | releaseOpenCnt(id->pOpen); |
| 534 | sqlite3OsLeaveMutex(); |
| 535 | TRACE2("CLOSE %-3d\n", id->fd); |
| 536 | OpenCounter(-1); |
| 537 | return SQLITE_OK; |
| 538 | } |
| 539 | |
| 540 | /* |
| 541 | ** Read data from a file into a buffer. Return SQLITE_OK if all |
| 542 | ** bytes were read successfully and SQLITE_IOERR if anything goes |
| 543 | ** wrong. |
| 544 | */ |
| 545 | int sqlite3OsRead(OsFile *id, void *pBuf, int amt){ |
| 546 | int got; |
| 547 | SimulateIOError(SQLITE_IOERR); |
| 548 | TIMER_START; |
| 549 | got = read(id->fd, pBuf, amt); |
| 550 | TIMER_END; |
| 551 | TRACE4("READ %-3d %7d %d\n", id->fd, last_page, elapse); |
| 552 | SEEK(0); |
| 553 | /* if( got<0 ) got = 0; */ |
| 554 | if( got==amt ){ |
| 555 | return SQLITE_OK; |
| 556 | }else{ |
| 557 | return SQLITE_IOERR; |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | /* |
| 562 | ** Write data from a buffer into a file. Return SQLITE_OK on success |
| 563 | ** or some other error code on failure. |
| 564 | */ |
| 565 | int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){ |
| 566 | int wrote = 0; |
| 567 | SimulateIOError(SQLITE_IOERR); |
| 568 | TIMER_START; |
| 569 | while( amt>0 && (wrote = write(id->fd, pBuf, amt))>0 ){ |
| 570 | amt -= wrote; |
| 571 | pBuf = &((char*)pBuf)[wrote]; |
| 572 | } |
| 573 | TIMER_END; |
| 574 | TRACE4("WRITE %-3d %7d %d\n", id->fd, last_page, elapse); |
| 575 | SEEK(0); |
| 576 | if( amt>0 ){ |
| 577 | return SQLITE_FULL; |
| 578 | } |
| 579 | return SQLITE_OK; |
| 580 | } |
| 581 | |
| 582 | /* |
| 583 | ** Move the read/write pointer in a file. |
| 584 | */ |
| 585 | int sqlite3OsSeek(OsFile *id, off_t offset){ |
| 586 | SEEK(offset/1024 + 1); |
| 587 | lseek(id->fd, offset, SEEK_SET); |
| 588 | return SQLITE_OK; |
| 589 | } |
| 590 | |
| 591 | /* |
| 592 | ** Make sure all writes to a particular file are committed to disk. |
| 593 | ** |
| 594 | ** Under Unix, also make sure that the directory entry for the file |
| 595 | ** has been created by fsync-ing the directory that contains the file. |
| 596 | ** If we do not do this and we encounter a power failure, the directory |
| 597 | ** entry for the journal might not exist after we reboot. The next |
| 598 | ** SQLite to access the file will not know that the journal exists (because |
| 599 | ** the directory entry for the journal was never created) and the transaction |
| 600 | ** will not roll back - possibly leading to database corruption. |
| 601 | */ |
| 602 | int sqlite3OsSync(OsFile *id){ |
| 603 | SimulateIOError(SQLITE_IOERR); |
| 604 | TRACE2("SYNC %-3d\n", id->fd); |
| 605 | if( fsync(id->fd) ){ |
| 606 | return SQLITE_IOERR; |
| 607 | }else{ |
| 608 | if( id->dirfd>=0 ){ |
| 609 | TRACE2("DIRSYNC %-3d\n", id->dirfd); |
| 610 | fsync(id->dirfd); |
| 611 | close(id->dirfd); /* Only need to sync once, so close the directory */ |
| 612 | id->dirfd = -1; /* when we are done. */ |
| 613 | } |
| 614 | return SQLITE_OK; |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | /* |
| 619 | ** Truncate an open file to a specified size |
| 620 | */ |
| 621 | int sqlite3OsTruncate(OsFile *id, off_t nByte){ |
| 622 | SimulateIOError(SQLITE_IOERR); |
| 623 | return ftruncate(id->fd, nByte)==0 ? SQLITE_OK : SQLITE_IOERR; |
| 624 | } |
| 625 | |
| 626 | /* |
| 627 | ** Determine the current size of a file in bytes |
| 628 | */ |
| 629 | int sqlite3OsFileSize(OsFile *id, off_t *pSize){ |
| 630 | struct stat buf; |
| 631 | SimulateIOError(SQLITE_IOERR); |
| 632 | if( fstat(id->fd, &buf)!=0 ){ |
| 633 | return SQLITE_IOERR; |
| 634 | } |
| 635 | *pSize = buf.st_size; |
| 636 | return SQLITE_OK; |
| 637 | } |
| 638 | |
| 639 | |
| 640 | /* |
| 641 | ** Change the status of the lock on the file "id" to be a readlock. |
| 642 | ** If the file was write locked, then this reduces the lock to a read. |
| 643 | ** If the file was read locked, then this acquires a new read lock. |
| 644 | ** |
| 645 | ** Return SQLITE_OK on success and SQLITE_BUSY on failure. If this |
| 646 | ** library was compiled with large file support (LFS) but LFS is not |
| 647 | ** available on the host, then an SQLITE_NOLFS is returned. |
| 648 | */ |
| 649 | int sqlite3OsReadLock(OsFile *id){ |
| 650 | int rc; |
| 651 | sqlite3OsEnterMutex(); |
| 652 | if( id->pLock->cnt>0 ){ |
| 653 | if( !id->locked ){ |
| 654 | id->pLock->cnt++; |
| 655 | id->locked = 1; |
| 656 | id->pOpen->nLock++; |
| 657 | } |
| 658 | rc = SQLITE_OK; |
| 659 | }else if( id->locked || id->pLock->cnt==0 ){ |
| 660 | struct flock lock; |
| 661 | int s; |
| 662 | lock.l_type = F_RDLCK; |
| 663 | lock.l_whence = SEEK_SET; |
| 664 | lock.l_start = lock.l_len = 0L; |
| 665 | s = fcntl(id->fd, F_SETLK, &lock); |
| 666 | if( s!=0 ){ |
| 667 | rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY; |
| 668 | }else{ |
| 669 | rc = SQLITE_OK; |
| 670 | if( !id->locked ){ |
| 671 | id->pOpen->nLock++; |
| 672 | id->locked = 1; |
| 673 | } |
| 674 | id->pLock->cnt = 1; |
| 675 | } |
| 676 | }else{ |
| 677 | rc = SQLITE_BUSY; |
| 678 | } |
| 679 | sqlite3OsLeaveMutex(); |
| 680 | return rc; |
| 681 | } |
| 682 | |
| 683 | /* |
| 684 | ** Change the lock status to be an exclusive or write lock. Return |
| 685 | ** SQLITE_OK on success and SQLITE_BUSY on a failure. If this |
| 686 | ** library was compiled with large file support (LFS) but LFS is not |
| 687 | ** available on the host, then an SQLITE_NOLFS is returned. |
| 688 | */ |
| 689 | int sqlite3OsWriteLock(OsFile *id){ |
| 690 | int rc; |
| 691 | sqlite3OsEnterMutex(); |
| 692 | if( id->pLock->cnt==0 || (id->pLock->cnt==1 && id->locked==1) ){ |
| 693 | struct flock lock; |
| 694 | int s; |
| 695 | lock.l_type = F_WRLCK; |
| 696 | lock.l_whence = SEEK_SET; |
| 697 | lock.l_start = lock.l_len = 0L; |
| 698 | s = fcntl(id->fd, F_SETLK, &lock); |
| 699 | if( s!=0 ){ |
| 700 | rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY; |
| 701 | }else{ |
| 702 | rc = SQLITE_OK; |
| 703 | if( !id->locked ){ |
| 704 | id->pOpen->nLock++; |
| 705 | id->locked = 1; |
| 706 | } |
| 707 | id->pLock->cnt = -1; |
| 708 | } |
| 709 | }else{ |
| 710 | rc = SQLITE_BUSY; |
| 711 | } |
| 712 | sqlite3OsLeaveMutex(); |
| 713 | return rc; |
| 714 | } |
| 715 | |
| 716 | /* |
| 717 | ** Unlock the given file descriptor. If the file descriptor was |
| 718 | ** not previously locked, then this routine is a no-op. If this |
| 719 | ** library was compiled with large file support (LFS) but LFS is not |
| 720 | ** available on the host, then an SQLITE_NOLFS is returned. |
| 721 | */ |
| 722 | int sqlite3OsUnlock(OsFile *id){ |
| 723 | int rc; |
| 724 | if( !id->locked ) return SQLITE_OK; |
| 725 | sqlite3OsEnterMutex(); |
| 726 | assert( id->pLock->cnt!=0 ); |
| 727 | if( id->pLock->cnt>1 ){ |
| 728 | id->pLock->cnt--; |
| 729 | rc = SQLITE_OK; |
| 730 | }else{ |
| 731 | struct flock lock; |
| 732 | int s; |
| 733 | lock.l_type = F_UNLCK; |
| 734 | lock.l_whence = SEEK_SET; |
| 735 | lock.l_start = lock.l_len = 0L; |
| 736 | s = fcntl(id->fd, F_SETLK, &lock); |
| 737 | if( s!=0 ){ |
| 738 | rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY; |
| 739 | }else{ |
| 740 | rc = SQLITE_OK; |
| 741 | id->pLock->cnt = 0; |
| 742 | } |
| 743 | } |
| 744 | if( rc==SQLITE_OK ){ |
| 745 | /* Decrement the count of locks against this same file. When the |
| 746 | ** count reaches zero, close any other file descriptors whose close |
| 747 | ** was deferred because of outstanding locks. |
| 748 | */ |
| 749 | struct openCnt *pOpen = id->pOpen; |
| 750 | pOpen->nLock--; |
| 751 | assert( pOpen->nLock>=0 ); |
| 752 | if( pOpen->nLock==0 && pOpen->nPending>0 ){ |
| 753 | int i; |
| 754 | for(i=0; i<pOpen->nPending; i++){ |
| 755 | close(pOpen->aPending[i]); |
| 756 | } |
| 757 | sqliteFree(pOpen->aPending); |
| 758 | pOpen->nPending = 0; |
| 759 | pOpen->aPending = 0; |
| 760 | } |
| 761 | } |
| 762 | sqlite3OsLeaveMutex(); |
| 763 | id->locked = 0; |
| 764 | return rc; |
| 765 | } |
| 766 | |
| 767 | /* |
| 768 | ** Get information to seed the random number generator. The seed |
| 769 | ** is written into the buffer zBuf[256]. The calling function must |
| 770 | ** supply a sufficiently large buffer. |
| 771 | */ |
| 772 | int sqlite3OsRandomSeed(char *zBuf){ |
| 773 | /* We have to initialize zBuf to prevent valgrind from reporting |
| 774 | ** errors. The reports issued by valgrind are incorrect - we would |
| 775 | ** prefer that the randomness be increased by making use of the |
| 776 | ** uninitialized space in zBuf - but valgrind errors tend to worry |
| 777 | ** some users. Rather than argue, it seems easier just to initialize |
| 778 | ** the whole array and silence valgrind, even if that means less randomness |
| 779 | ** in the random seed. |
| 780 | ** |
| 781 | ** When testing, initializing zBuf[] to zero is all we do. That means |
| 782 | ** that we always use the same random number sequence.* This makes the |
| 783 | ** tests repeatable. |
| 784 | */ |
| 785 | memset(zBuf, 0, 256); |
| 786 | #if !defined(SQLITE_TEST) |
| 787 | { |
| 788 | int pid; |
| 789 | time((time_t*)zBuf); |
| 790 | pid = getpid(); |
| 791 | memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid)); |
| 792 | } |
| 793 | #endif |
| 794 | return SQLITE_OK; |
| 795 | } |
| 796 | |
| 797 | /* |
| 798 | ** Sleep for a little while. Return the amount of time slept. |
| 799 | */ |
| 800 | int sqlite3OsSleep(int ms){ |
| 801 | #if defined(HAVE_USLEEP) && HAVE_USLEEP |
| 802 | usleep(ms*1000); |
| 803 | return ms; |
| 804 | #else |
| 805 | sleep((ms+999)/1000); |
| 806 | return 1000*((ms+999)/1000); |
| 807 | #endif |
| 808 | } |
| 809 | |
| 810 | /* |
| 811 | ** Static variables used for thread synchronization |
| 812 | */ |
| 813 | static int inMutex = 0; |
| 814 | static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; |
| 815 | |
| 816 | /* |
| 817 | ** The following pair of routine implement mutual exclusion for |
| 818 | ** multi-threaded processes. Only a single thread is allowed to |
| 819 | ** executed code that is surrounded by EnterMutex() and LeaveMutex(). |
| 820 | ** |
| 821 | ** SQLite uses only a single Mutex. There is not much critical |
| 822 | ** code and what little there is executes quickly and without blocking. |
| 823 | */ |
| 824 | void sqlite3OsEnterMutex(){ |
| 825 | #ifdef SQLITE_UNIX_THREADS |
| 826 | pthread_mutex_lock(&mutex); |
| 827 | #endif |
| 828 | assert( !inMutex ); |
| 829 | inMutex = 1; |
| 830 | } |
| 831 | void sqlite3OsLeaveMutex(){ |
| 832 | assert( inMutex ); |
| 833 | inMutex = 0; |
| 834 | #ifdef SQLITE_UNIX_THREADS |
| 835 | pthread_mutex_unlock(&mutex); |
| 836 | #endif |
| 837 | } |
| 838 | |
| 839 | /* |
| 840 | ** Turn a relative pathname into a full pathname. Return a pointer |
| 841 | ** to the full pathname stored in space obtained from sqliteMalloc(). |
| 842 | ** The calling function is responsible for freeing this space once it |
| 843 | ** is no longer needed. |
| 844 | */ |
| 845 | char *sqlite3OsFullPathname(const char *zRelative){ |
| 846 | char *zFull = 0; |
| 847 | if( zRelative[0]=='/' ){ |
| 848 | sqlite3SetString(&zFull, zRelative, (char*)0); |
| 849 | }else{ |
| 850 | char zBuf[5000]; |
| 851 | sqlite3SetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative, |
| 852 | (char*)0); |
| 853 | } |
| 854 | return zFull; |
| 855 | } |
| 856 | |
| 857 | /* |
| 858 | ** The following variable, if set to a non-zero value, becomes the result |
| 859 | ** returned from sqlite3OsCurrentTime(). This is used for testing. |
| 860 | */ |
| 861 | #ifdef SQLITE_TEST |
| 862 | int sqlite3_current_time = 0; |
| 863 | #endif |
| 864 | |
| 865 | /* |
| 866 | ** Find the current time (in Universal Coordinated Time). Write the |
| 867 | ** current time and date as a Julian Day number into *prNow and |
| 868 | ** return 0. Return 1 if the time and date cannot be found. |
| 869 | */ |
| 870 | int sqlite3OsCurrentTime(double *prNow){ |
| 871 | time_t t; |
| 872 | time(&t); |
| 873 | *prNow = t/86400.0 + 2440587.5; |
| 874 | #ifdef SQLITE_TEST |
| 875 | if( sqlite3_current_time ){ |
| 876 | *prNow = sqlite3_current_time/86400.0 + 2440587.5; |
| 877 | } |
| 878 | #endif |
| 879 | return 0; |
| 880 | } |
| 881 | |
| 882 | #endif /* OS_UNIX */ |