Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/src/os_unix.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / src / os_unix.c` 8604 lines ยท 296433 bytes Raw Blame History 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 the VFS implementation for unix-like operating systems 14 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others. 15 ** 16 ** There are actually several different VFS implementations in this file. 17 ** The differences are in the way that file locking is done. The default 18 ** implementation uses Posix Advisory Locks. Alternative implementations 19 ** use flock(), dot-files, various proprietary locking schemas, or simply 20 ** skip locking all together. 21 ** 22 ** This source file is organized into divisions where the logic for various 23 ** subfunctions is contained within the appropriate division. PLEASE 24 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed 25 ** in the correct division and should be clearly labelled. 26 ** 27 ** The layout of divisions is as follows: 28 ** 29 ** * General-purpose declarations and utility functions. 30 ** * Unique file ID logic used by VxWorks. 31 ** * Various locking primitive implementations (all except proxy locking): 32 ** + for Posix Advisory Locks 33 ** + for no-op locks 34 ** + for dot-file locks 35 ** + for flock() locking 36 ** + for named semaphore locks (VxWorks only) 37 ** + for AFP filesystem locks (MacOSX only) 38 ** * sqlite3_file methods not associated with locking. 39 ** * Definitions of sqlite3_io_methods objects for all locking 40 ** methods plus "finder" functions for each locking method. 41 ** * sqlite3_vfs method implementations. 42 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only) 43 ** * Definitions of sqlite3_vfs objects for all locking methods 44 ** plus implementations of sqlite3_os_init() and sqlite3_os_end(). 45 */ 46 #include "sqliteInt.h" 47 #if SQLITE_OS_UNIX /* This file is used on unix only */ 48 49 /* 50 ** There are various methods for file locking used for concurrency 51 ** control: 52 ** 53 ** 1. POSIX locking (the default), 54 ** 2. No locking, 55 ** 3. Dot-file locking, 56 ** 4. flock() locking, 57 ** 5. AFP locking (OSX only), 58 ** 6. Named POSIX semaphores (VXWorks only), 59 ** 7. proxy locking. (OSX only) 60 ** 61 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE 62 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic 63 ** selection of the appropriate locking style based on the filesystem 64 ** where the database is located. 65 */ 66 #if !defined(SQLITE_ENABLE_LOCKING_STYLE) 67 # if defined(__APPLE__) 68 # define SQLITE_ENABLE_LOCKING_STYLE 1 69 # else 70 # define SQLITE_ENABLE_LOCKING_STYLE 0 71 # endif 72 #endif 73 74 /* Use pread() and pwrite() if they are available */ 75 #if defined(__APPLE__) || defined(__linux__) 76 # define HAVE_PREAD 1 77 # define HAVE_PWRITE 1 78 #endif 79 #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64) 80 # undef USE_PREAD 81 # define USE_PREAD64 1 82 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE) 83 # undef USE_PREAD64 84 # define USE_PREAD 1 85 #endif 86 87 /* 88 ** standard include files. 89 */ 90 #include /* amalgamator: keep */ 91 #include /* amalgamator: keep */ 92 #include 93 #include 94 #include /* amalgamator: keep */ 95 #include 96 #include /* amalgamator: keep */ 97 #include 98 #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \ 99 && !defined(SQLITE_WASI) 100 # include 101 #endif 102 103 #if SQLITE_ENABLE_LOCKING_STYLE 104 # include 105 # include 106 # include 107 #endif /* SQLITE_ENABLE_LOCKING_STYLE */ 108 109 /* 110 ** Try to determine if gethostuuid() is available based on standard 111 ** macros. This might sometimes compute the wrong value for some 112 ** obscure platforms. For those cases, simply compile with one of 113 ** the following: 114 ** 115 ** -DHAVE_GETHOSTUUID=0 116 ** -DHAVE_GETHOSTUUID=1 117 ** 118 ** None if this matters except when building on Apple products with 119 ** -DSQLITE_ENABLE_LOCKING_STYLE. 120 */ 121 #ifndef HAVE_GETHOSTUUID 122 # define HAVE_GETHOSTUUID 0 123 # if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \ 124 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000)) 125 # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \ 126 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))\ 127 && (!defined(TARGET_OS_MACCATALYST) || (TARGET_OS_MACCATALYST==0)) 128 # undef HAVE_GETHOSTUUID 129 # define HAVE_GETHOSTUUID 1 130 # else 131 # warning "gethostuuid() is disabled." 132 # endif 133 # endif 134 #endif 135 136 137 #if OS_VXWORKS 138 # include 139 # include 140 # include 141 #endif /* OS_VXWORKS */ 142 143 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE 144 # include 145 #endif 146 147 #ifdef HAVE_UTIME 148 # include 149 #endif 150 151 /* 152 ** Allowed values of unixFile.fsFlags 153 */ 154 #define SQLITE_FSFLAGS_IS_MSDOS 0x1 155 156 /* 157 ** If we are to be thread-safe, include the pthreads header. 158 */ 159 #if SQLITE_THREADSAFE 160 # include 161 #endif 162 163 /* 164 ** Default permissions when creating a new file 165 */ 166 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS 167 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644 168 #endif 169 170 /* 171 ** Default permissions when creating auto proxy dir 172 */ 173 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 174 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755 175 #endif 176 177 /* 178 ** Maximum supported path-length. 179 */ 180 #define MAX_PATHNAME 512 181 182 /* 183 ** Maximum supported symbolic links 184 */ 185 #define SQLITE_MAX_SYMLINKS 100 186 187 /* 188 ** Remove and stub certain info for WASI (WebAssembly System 189 ** Interface) builds. 190 */ 191 #ifdef SQLITE_WASI 192 # undef HAVE_FCHMOD 193 # undef HAVE_FCHOWN 194 # undef HAVE_MREMAP 195 # define HAVE_MREMAP 0 196 # ifndef SQLITE_DEFAULT_UNIX_VFS 197 # define SQLITE_DEFAULT_UNIX_VFS "unix-dotfile" 198 /* ^^^ should SQLITE_DEFAULT_UNIX_VFS be "unix-none"? */ 199 # endif 200 # ifndef F_RDLCK 201 # define F_RDLCK 0 202 # define F_WRLCK 1 203 # define F_UNLCK 2 204 # if __LONG_MAX == 0x7fffffffL 205 # define F_GETLK 12 206 # define F_SETLK 13 207 # define F_SETLKW 14 208 # else 209 # define F_GETLK 5 210 # define F_SETLK 6 211 # define F_SETLKW 7 212 # endif 213 # endif 214 #else /* !SQLITE_WASI */ 215 # ifndef HAVE_FCHMOD 216 # define HAVE_FCHMOD 1 217 # endif 218 #endif /* SQLITE_WASI */ 219 220 #ifdef SQLITE_WASI 221 # define osGetpid(X) (pid_t)1 222 #else 223 /* Always cast the getpid() return type for compatibility with 224 ** kernel modules in VxWorks. */ 225 # define osGetpid(X) (pid_t)getpid() 226 #endif 227 228 /* 229 ** Only set the lastErrno if the error code is a real error and not 230 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK 231 */ 232 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY)) 233 234 /* Forward references */ 235 typedef struct unixShm unixShm; /* Connection shared memory */ 236 typedef struct unixShmNode unixShmNode; /* Shared memory instance */ 237 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */ 238 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */ 239 240 /* 241 ** Sometimes, after a file handle is closed by SQLite, the file descriptor 242 ** cannot be closed immediately. In these cases, instances of the following 243 ** structure are used to store the file descriptor while waiting for an 244 ** opportunity to either close or reuse it. 245 */ 246 struct UnixUnusedFd { 247 int fd; /* File descriptor to close */ 248 int flags; /* Flags this file descriptor was opened with */ 249 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */ 250 }; 251 252 /* 253 ** The unixFile structure is subclass of sqlite3_file specific to the unix 254 ** VFS implementations. 255 */ 256 typedef struct unixFile unixFile; 257 struct unixFile { 258 sqlite3_io_methods const *pMethod; /* Always the first entry */ 259 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */ 260 unixInodeInfo *pInode; /* Info about locks on this inode */ 261 int h; /* The file descriptor */ 262 unsigned char eFileLock; /* The type of lock held on this fd */ 263 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */ 264 int lastErrno; /* The unix errno from last I/O error */ 265 void *lockingContext; /* Locking style specific state */ 266 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */ 267 const char *zPath; /* Name of the file */ 268 unixShm *pShm; /* Shared memory segment information */ 269 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */ 270 #if SQLITE_MAX_MMAP_SIZE>0 271 int nFetchOut; /* Number of outstanding xFetch refs */ 272 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */ 273 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */ 274 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ 275 void *pMapRegion; /* Memory mapped region */ 276 #endif 277 int sectorSize; /* Device sector size */ 278 int deviceCharacteristics; /* Precomputed device characteristics */ 279 #if SQLITE_ENABLE_LOCKING_STYLE 280 int openFlags; /* The flags specified at open() */ 281 #endif 282 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__) 283 unsigned fsFlags; /* cached details from statfs() */ 284 #endif 285 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 286 unsigned iBusyTimeout; /* Wait this many millisec on locks */ 287 int bBlockOnConnect; /* True to block for SHARED locks */ 288 #endif 289 #if OS_VXWORKS 290 struct vxworksFileId *pId; /* Unique file ID */ 291 #endif 292 #ifdef SQLITE_DEBUG 293 /* The next group of variables are used to track whether or not the 294 ** transaction counter in bytes 24-27 of database files are updated 295 ** whenever any part of the database changes. An assertion fault will 296 ** occur if a file is updated without also updating the transaction 297 ** counter. This test is made to avoid new problems similar to the 298 ** one described by ticket #3584. 299 */ 300 unsigned char transCntrChng; /* True if the transaction counter changed */ 301 unsigned char dbUpdate; /* True if any part of database file changed */ 302 unsigned char inNormalWrite; /* True if in a normal write operation */ 303 304 #endif 305 306 #ifdef SQLITE_TEST 307 /* In test mode, increase the size of this structure a bit so that 308 ** it is larger than the struct CrashFile defined in test6.c. 309 */ 310 char aPadding[32]; 311 #endif 312 }; 313 314 /* This variable holds the process id (pid) from when the xRandomness() 315 ** method was called. If xOpen() is called from a different process id, 316 ** indicating that a fork() has occurred, the PRNG will be reset. 317 */ 318 static pid_t randomnessPid = 0; 319 320 /* 321 ** Allowed values for the unixFile.ctrlFlags bitmask: 322 */ 323 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */ 324 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */ 325 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */ 326 #if !defined(SQLITE_DISABLE_DIRSYNC) && !defined(_AIX) 327 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */ 328 #else 329 # define UNIXFILE_DIRSYNC 0x00 330 #endif 331 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ 332 #define UNIXFILE_DELETE 0x20 /* Delete on close */ 333 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */ 334 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */ 335 336 /* 337 ** Include code that is common to all os_*.c files 338 */ 339 #include "os_common.h" 340 341 /* 342 ** Define various macros that are missing from some systems. 343 */ 344 #ifndef O_LARGEFILE 345 # define O_LARGEFILE 0 346 #endif 347 #ifdef SQLITE_DISABLE_LFS 348 # undef O_LARGEFILE 349 # define O_LARGEFILE 0 350 #endif 351 #ifndef O_NOFOLLOW 352 # define O_NOFOLLOW 0 353 #endif 354 #ifndef O_BINARY 355 # define O_BINARY 0 356 #endif 357 358 /* 359 ** The threadid macro resolves to the thread-id or to 0. Used for 360 ** testing and debugging only. 361 */ 362 #if SQLITE_THREADSAFE 363 #define threadid pthread_self() 364 #else 365 #define threadid 0 366 #endif 367 368 /* 369 ** HAVE_MREMAP defaults to true on Linux and false everywhere else. 370 */ 371 #if !defined(HAVE_MREMAP) 372 # if defined(__linux__) && defined(_GNU_SOURCE) 373 # define HAVE_MREMAP 1 374 # else 375 # define HAVE_MREMAP 0 376 # endif 377 #endif 378 379 /* 380 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek() 381 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined. 382 */ 383 #ifdef __ANDROID__ 384 # define lseek lseek64 385 #endif 386 387 #ifdef __linux__ 388 /* 389 ** Linux-specific IOCTL magic numbers used for controlling F2FS 390 */ 391 #define F2FS_IOCTL_MAGIC 0xf5 392 #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1) 393 #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2) 394 #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3) 395 #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5) 396 #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32) 397 #define F2FS_FEATURE_ATOMIC_WRITE 0x0004 398 #endif /* __linux__ */ 399 400 401 /* 402 ** Different Unix systems declare open() in different ways. Same use 403 ** open(const char*,int,mode_t). Others use open(const char*,int,...). 404 ** The difference is important when using a pointer to the function. 405 ** 406 ** The safest way to deal with the problem is to always use this wrapper 407 ** which always has the same well-defined interface. 408 */ 409 static int posixOpen(const char *zFile, int flags, int mode){ 410 return open(zFile, flags, mode); 411 } 412 413 /* Forward reference */ 414 static int openDirectory(const char*, int*); 415 static int unixGetpagesize(void); 416 417 /* 418 ** Many system calls are accessed through pointer-to-functions so that 419 ** they may be overridden at runtime to facilitate fault injection during 420 ** testing and sandboxing. The following array holds the names and pointers 421 ** to all overrideable system calls. 422 */ 423 static struct unix_syscall { 424 const char *zName; /* Name of the system call */ 425 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ 426 sqlite3_syscall_ptr pDefault; /* Default value */ 427 } aSyscall[] = { 428 { "open", (sqlite3_syscall_ptr)posixOpen, 0 }, 429 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent) 430 431 { "close", (sqlite3_syscall_ptr)close, 0 }, 432 #define osClose ((int(*)(int))aSyscall[1].pCurrent) 433 434 { "access", (sqlite3_syscall_ptr)access, 0 }, 435 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent) 436 437 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 }, 438 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent) 439 440 { "stat", (sqlite3_syscall_ptr)stat, 0 }, 441 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent) 442 443 /* 444 ** The DJGPP compiler environment looks mostly like Unix, but it 445 ** lacks the fcntl() system call. So redefine fcntl() to be something 446 ** that always succeeds. This means that locking does not occur under 447 ** DJGPP. But it is DOS - what did you expect? 448 */ 449 #ifdef __DJGPP__ 450 { "fstat", 0, 0 }, 451 #define osFstat(a,b,c) 0 452 #else 453 { "fstat", (sqlite3_syscall_ptr)fstat, 0 }, 454 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent) 455 #endif 456 457 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 }, 458 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent) 459 460 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 }, 461 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent) 462 463 { "read", (sqlite3_syscall_ptr)read, 0 }, 464 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent) 465 466 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE 467 { "pread", (sqlite3_syscall_ptr)pread, 0 }, 468 #else 469 { "pread", (sqlite3_syscall_ptr)0, 0 }, 470 #endif 471 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent) 472 473 #if defined(USE_PREAD64) 474 { "pread64", (sqlite3_syscall_ptr)pread64, 0 }, 475 #else 476 { "pread64", (sqlite3_syscall_ptr)0, 0 }, 477 #endif 478 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent) 479 480 { "write", (sqlite3_syscall_ptr)write, 0 }, 481 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent) 482 483 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE 484 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 }, 485 #else 486 { "pwrite", (sqlite3_syscall_ptr)0, 0 }, 487 #endif 488 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\ 489 aSyscall[12].pCurrent) 490 491 #if defined(USE_PREAD64) 492 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 }, 493 #else 494 { "pwrite64", (sqlite3_syscall_ptr)0, 0 }, 495 #endif 496 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\ 497 aSyscall[13].pCurrent) 498 499 #if defined(HAVE_FCHMOD) 500 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 }, 501 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent) 502 #else 503 { "fchmod", (sqlite3_syscall_ptr)0, 0 }, 504 #define osFchmod(FID,MODE) 0 505 #endif 506 507 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE 508 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 }, 509 #else 510 { "fallocate", (sqlite3_syscall_ptr)0, 0 }, 511 #endif 512 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent) 513 514 { "unlink", (sqlite3_syscall_ptr)unlink, 0 }, 515 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent) 516 517 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 }, 518 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent) 519 520 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 }, 521 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent) 522 523 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 }, 524 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent) 525 526 #if defined(HAVE_FCHOWN) 527 { "fchown", (sqlite3_syscall_ptr)fchown, 0 }, 528 #else 529 { "fchown", (sqlite3_syscall_ptr)0, 0 }, 530 #endif 531 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent) 532 533 #if defined(HAVE_FCHOWN) 534 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 }, 535 #else 536 { "geteuid", (sqlite3_syscall_ptr)0, 0 }, 537 #endif 538 #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent) 539 540 #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \ 541 && !defined(SQLITE_WASI) 542 { "mmap", (sqlite3_syscall_ptr)mmap, 0 }, 543 #else 544 { "mmap", (sqlite3_syscall_ptr)0, 0 }, 545 #endif 546 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent) 547 548 #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \ 549 && !defined(SQLITE_WASI) 550 { "munmap", (sqlite3_syscall_ptr)munmap, 0 }, 551 #else 552 { "munmap", (sqlite3_syscall_ptr)0, 0 }, 553 #endif 554 #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent) 555 556 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) 557 { "mremap", (sqlite3_syscall_ptr)mremap, 0 }, 558 #else 559 { "mremap", (sqlite3_syscall_ptr)0, 0 }, 560 #endif 561 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent) 562 563 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 564 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 }, 565 #else 566 { "getpagesize", (sqlite3_syscall_ptr)0, 0 }, 567 #endif 568 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent) 569 570 #if defined(HAVE_READLINK) 571 { "readlink", (sqlite3_syscall_ptr)readlink, 0 }, 572 #else 573 { "readlink", (sqlite3_syscall_ptr)0, 0 }, 574 #endif 575 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent) 576 577 #if defined(HAVE_LSTAT) 578 { "lstat", (sqlite3_syscall_ptr)lstat, 0 }, 579 #else 580 { "lstat", (sqlite3_syscall_ptr)0, 0 }, 581 #endif 582 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent) 583 584 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) 585 # ifdef __ANDROID__ 586 { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 }, 587 #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent) 588 # else 589 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 }, 590 #define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent) 591 # endif 592 #else 593 { "ioctl", (sqlite3_syscall_ptr)0, 0 }, 594 #endif 595 596 }; /* End of the overrideable system calls */ 597 598 599 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) 600 /* 601 ** Extract Posix Advisory Locking information about file description fd 602 ** from the /proc/PID/fdinfo/FD pseudo-file. Fill the string buffer a[16] 603 ** with characters to indicate which SQLite-relevant locks are held. 604 ** a[16] will be a 15-character zero-terminated string with the following 605 ** schema: 606 ** 607 ** AAA/B.DDD.DDDDD 608 ** 609 ** Each of character A-D will be "w" or "r" or "-" to indicate either a 610 ** write-lock, a read-lock, or no-lock, respectively. The "." and "/" 611 ** characters are delimiters intended to make the string more easily 612 ** readable by humans. Here are the meaning of the specific letters: 613 ** 614 ** AAA -> The main database locks. PENDING_BYTE, RESERVED_BYTE, 615 ** and SHARED_FIRST, respectively. 616 ** 617 ** B -> The deadman switch lock. Offset 128 of the -shm file. 618 ** 619 ** CCC -> WAL locks: WRITE, CKPT, RECOVER 620 ** 621 ** DDDDD -> WAL read-locks 0 through 5 622 ** 623 ** Note that elements before the "/" apply to the main database file and 624 ** elements after the "/" apply to the -shm file in WAL mode. 625 ** 626 ** Here is another way of thinking about the meaning of the result string: 627 ** 628 ** AAA/B.CCC.DDDDD 629 ** ||| | ||| \___/ 630 ** PENDING--'|| | ||| `----- READ 0-5 631 ** RESERVED--'| | ||`---- RECOVER 632 ** SHARED ----' | |`----- CKPT 633 ** DMS ------' `------ WRITE 634 ** 635 ** Return SQLITE_OK on success and SQLITE_ERROR_UNABLE if the /proc 636 ** pseudo-filesystem is unavailable. 637 */ 638 static int unixPosixAdvisoryLocks( 639 int fd, /* The file descriptor to analyze */ 640 char a[16] /* Write a text description of PALs here */ 641 ){ 642 int in; 643 ssize_t n; 644 char *p, *pNext, *x; 645 char z[2000]; 646 647 /* 1 */ 648 /* 012 4 678 01234 */ 649 memcpy(a, "---/-.---.-----", 16); 650 sqlite3_snprintf(sizeof(z), z, "/proc/%d/fdinfo/%d", getpid(), fd); 651 in = osOpen(z, O_RDONLY, 0); 652 if( in<0 ){ 653 return SQLITE_ERROR_UNABLE; 654 } 655 n = osRead(in, z, sizeof(z)-1); 656 osClose(in); 657 if( n<=0 ) return SQLITE_ERROR_UNABLE; 658 z[n] = 0; 659 660 /* We are looking for lines that begin with "lock:\t". Examples: 661 ** 662 ** lock: 1: POSIX ADVISORY READ 494716 08:02:`5277597` `1073741826` `1073742335` 663 ** lock: 1: POSIX ADVISORY WRITE 494716 08:02:`5282282` 120 120 664 ** lock: 2: POSIX ADVISORY READ 494716 08:02:`5282282` 123 123 665 ** lock: 3: POSIX ADVISORY READ 494716 08:02:`5282282` 128 128 666 */ 667 pNext = strstr(z, "lock:\t"); 668 while( pNext ){ 669 char cType = 0; 670 sqlite3_int64 iFirst, iLast; 671 p = pNext+6; 672 pNext = strstr(p, "lock:\t"); 673 if( pNext ) pNext[-1] = 0; 674 if( (x = strstr(p, " READ "))!=0 ){ 675 cType = 'r'; 676 x += 6; 677 }else if( (x = strstr(p, " WRITE "))!=0 ){ 678 cType = 'w'; 679 x += 7; 680 }else{ 681 continue; 682 } 683 x = strrchr(x, ' '); 684 if( x==0 ) continue; 685 iLast = strtoll(x+1, 0, 10); 686 *x = 0; 687 x = strrchr(p, ' '); 688 if( x==0 ) continue; 689 iFirst = strtoll(x+1, 0, 10); 690 if( iLast>=PENDING_BYTE ){ 691 if( iFirst<=PENDING_BYTE && iLast>=PENDING_BYTE ) a[0] = cType; 692 if( iFirst<=PENDING_BYTE+1 && iLast>=PENDING_BYTE+1 ) a[1] = cType; 693 if( iFirst<=PENDING_BYTE+2 && iLast>=PENDING_BYTE+510 ) a[2] = cType; 694 }else if( iLast<=128 ){ 695 if( iFirst<=128 && iLast>=128 ) a[4] = cType; 696 if( iFirst<=120 && iLast>=120 ) a[6] = cType; 697 if( iFirst<=121 && iLast>=121 ) a[7] = cType; 698 if( iFirst<=122 && iLast>=122 ) a[8] = cType; 699 if( iFirst<=123 && iLast>=123 ) a[10] = cType; 700 if( iFirst<=124 && iLast>=124 ) a[11] = cType; 701 if( iFirst<=125 && iLast>=125 ) a[12] = cType; 702 if( iFirst<=126 && iLast>=126 ) a[13] = cType; 703 if( iFirst<=127 && iLast>=127 ) a[14] = cType; 704 } 705 } 706 return SQLITE_OK; 707 } 708 #else 709 # define unixPosixAdvisoryLocks(A,B) SQLITE_ERROR_UNABLE 710 #endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */ 711 712 /* 713 ** On some systems, calls to fchown() will trigger a message in a security 714 ** log if they come from non-root processes. So avoid calling fchown() if 715 ** we are not running as root. 716 */ 717 static int robustFchown(int fd, uid_t uid, gid_t gid){ 718 #if defined(HAVE_FCHOWN) 719 return osGeteuid() ? 0 : osFchown(fd,uid,gid); 720 #else 721 return 0; 722 #endif 723 } 724 725 /* 726 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the 727 ** "unix" VFSes. Return SQLITE_OK upon successfully updating the 728 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable 729 ** system call named zName. 730 */ 731 static int unixSetSystemCall( 732 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ 733 const char *zName, /* Name of system call to override */ 734 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ 735 ){ 736 unsigned int i; 737 int rc = SQLITE_NOTFOUND; 738 739 UNUSED_PARAMETER(pNotUsed); 740 if( zName==0 ){ 741 /* If no zName is given, restore all system calls to their default 742 ** settings and return NULL 743 */ 744 rc = SQLITE_OK; 745 for(i=0; i=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break; 848 if( (f & (O_EXCL|O_CREAT))==(O_EXCL|O_CREAT) ){ 849 (void)osUnlink(z); 850 } 851 osClose(fd); 852 sqlite3_log(SQLITE_WARNING, 853 "attempt to open \"%s\" as file descriptor %d", z, fd); 854 fd = -1; 855 if( osOpen("/dev/null", O_RDONLY, m)<0 ) break; 856 } 857 if( fd>=0 ){ 858 if( m!=0 ){ 859 struct stat statbuf; 860 if( osFstat(fd, &statbuf)==0 861 && statbuf.st_size==0 862 && (statbuf.st_mode&0777)!=m 863 ){ 864 osFchmod(fd, m); 865 } 866 } 867 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0) 868 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC); 869 #endif 870 } 871 return fd; 872 } 873 874 /* 875 ** Helper functions to obtain and relinquish the global mutex. The 876 ** global mutex is used to protect the unixInodeInfo objects used by 877 ** this file, all of which may be shared by multiple threads. 878 ** 879 ** Function unixMutexHeld() is used to assert() that the global mutex 880 ** is held when required. This function is only used as part of assert() 881 ** statements. e.g. 882 ** 883 ** unixEnterMutex() 884 ** assert( unixMutexHeld() ); 885 ** unixEnterLeave() 886 ** 887 ** To prevent deadlock, the global unixBigLock must must be acquired 888 ** before the unixInodeInfo.pLockMutex mutex, if both are held. It is 889 ** OK to get the pLockMutex without holding unixBigLock first, but if 890 ** that happens, the unixBigLock mutex must not be acquired until after 891 ** pLockMutex is released. 892 ** 893 ** OK: enter(unixBigLock), enter(pLockInfo) 894 ** OK: enter(unixBigLock) 895 ** OK: enter(pLockInfo) 896 ** ERROR: enter(pLockInfo), enter(unixBigLock) 897 */ 898 static sqlite3_mutex *unixBigLock = 0; 899 static void unixEnterMutex(void){ 900 assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */ 901 sqlite3_mutex_enter(unixBigLock); 902 } 903 static void unixLeaveMutex(void){ 904 assert( sqlite3_mutex_held(unixBigLock) ); 905 sqlite3_mutex_leave(unixBigLock); 906 } 907 #ifdef SQLITE_DEBUG 908 static int unixMutexHeld(void) { 909 return sqlite3_mutex_held(unixBigLock); 910 } 911 #endif 912 913 914 #ifdef SQLITE_HAVE_OS_TRACE 915 /* 916 ** Helper function for printing out trace information from debugging 917 ** binaries. This returns the string representation of the supplied 918 ** integer lock-type. 919 */ 920 static const char *azFileLock(int eFileLock){ 921 switch( eFileLock ){ 922 case NO_LOCK: return "NONE"; 923 case SHARED_LOCK: return "SHARED"; 924 case RESERVED_LOCK: return "RESERVED"; 925 case PENDING_LOCK: return "PENDING"; 926 case EXCLUSIVE_LOCK: return "EXCLUSIVE"; 927 } 928 return "ERROR"; 929 } 930 #endif 931 932 #ifdef SQLITE_LOCK_TRACE 933 /* 934 ** Print out information about all locking operations. 935 ** 936 ** This routine is used for troubleshooting locks on multithreaded 937 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE 938 ** command-line option on the compiler. This code is normally 939 ** turned off. 940 */ 941 static int lockTrace(int fd, int op, struct flock *p){ 942 char *zOpName, *zType; 943 int s; 944 int savedErrno; 945 if( op==F_GETLK ){ 946 zOpName = "GETLK"; 947 }else if( op==F_SETLK ){ 948 zOpName = "SETLK"; 949 }else{ 950 s = osFcntl(fd, op, p); 951 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s); 952 return s; 953 } 954 if( p->l_type==F_RDLCK ){ 955 zType = "RDLCK"; 956 }else if( p->l_type==F_WRLCK ){ 957 zType = "WRLCK"; 958 }else if( p->l_type==F_UNLCK ){ 959 zType = "UNLCK"; 960 }else{ 961 assert( 0 ); 962 } 963 assert( p->l_whence==SEEK_SET ); 964 s = osFcntl(fd, op, p); 965 savedErrno = errno; 966 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n", 967 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len, 968 (int)p->l_pid, s); 969 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){ 970 struct flock l2; 971 l2 = *p; 972 osFcntl(fd, F_GETLK, &l2); 973 if( l2.l_type==F_RDLCK ){ 974 zType = "RDLCK"; 975 }else if( l2.l_type==F_WRLCK ){ 976 zType = "WRLCK"; 977 }else if( l2.l_type==F_UNLCK ){ 978 zType = "UNLCK"; 979 }else{ 980 assert( 0 ); 981 } 982 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n", 983 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid); 984 } 985 errno = savedErrno; 986 return s; 987 } 988 #undef osFcntl 989 #define osFcntl lockTrace 990 #endif /* SQLITE_LOCK_TRACE */ 991 992 /* 993 ** Retry ftruncate() calls that fail due to EINTR 994 ** 995 ** All calls to ftruncate() within this file should be made through 996 ** this wrapper. On the Android platform, bypassing the logic below 997 ** could lead to a corrupt database. 998 */ 999 static int robust_ftruncate(int h, sqlite3_int64 sz){ 1000 int rc; 1001 #ifdef __ANDROID__ 1002 /* On Android, ftruncate() always uses 32-bit offsets, even if 1003 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to 1004 ** truncate a file to any size larger than 2GiB. Silently ignore any 1005 ** such attempts. */ 1006 if( sz>(sqlite3_int64)0x7FFFFFFF ){ 1007 rc = SQLITE_OK; 1008 }else 1009 #endif 1010 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR ); 1011 return rc; 1012 } 1013 1014 /* 1015 ** This routine translates a standard POSIX errno code into something 1016 ** useful to the clients of the sqlite3 functions. Specifically, it is 1017 ** intended to translate a variety of "try again" errors into SQLITE_BUSY 1018 ** and a variety of "please close the file descriptor NOW" errors into 1019 ** SQLITE_IOERR 1020 ** 1021 ** Errors during initialization of locks, or file system support for locks, 1022 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately. 1023 */ 1024 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) { 1025 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) || 1026 (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 1027 (sqliteIOErr == SQLITE_IOERR_RDLOCK) || 1028 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ); 1029 switch (posixError) { 1030 case EACCES: 1031 case EAGAIN: 1032 case ETIMEDOUT: 1033 case EBUSY: 1034 case EINTR: 1035 case ENOLCK: 1036 /* random NFS retry error, unless during file system support 1037 * introspection, in which it actually means what it says */ 1038 return SQLITE_BUSY; 1039 1040 case EPERM: 1041 return SQLITE_PERM; 1042 1043 default: 1044 return sqliteIOErr; 1045 } 1046 } 1047 1048 1049 /****************************************************************************** 1050 ****************** Begin Unique File ID Utility Used By VxWorks *************** 1051 ** 1052 ** On most versions of unix, we can get a unique ID for a file by concatenating 1053 ** the device number and the inode number. But this does not work on VxWorks. 1054 ** On VxWorks, a unique file id must be based on the canonical filename. 1055 ** 1056 ** A pointer to an instance of the following structure can be used as a 1057 ** unique file ID in VxWorks. Each instance of this structure contains 1058 ** a copy of the canonical filename. There is also a reference count. 1059 ** The structure is reclaimed when the number of pointers to it drops to 1060 ** zero. 1061 ** 1062 ** There are never very many files open at one time and lookups are not 1063 ** a performance-critical path, so it is sufficient to put these 1064 ** structures on a linked list. 1065 */ 1066 struct vxworksFileId { 1067 struct vxworksFileId *pNext; /* Next in a list of them all */ 1068 int nRef; /* Number of references to this one */ 1069 int nName; /* Length of the zCanonicalName[] string */ 1070 char *zCanonicalName; /* Canonical filename */ 1071 }; 1072 1073 #if OS_VXWORKS 1074 /* 1075 ** All unique filenames are held on a linked list headed by this 1076 ** variable: 1077 */ 1078 static struct vxworksFileId *vxworksFileList = 0; 1079 static sqlite3_mutex *vxworksMutex = 0; 1080 1081 /* 1082 ** Simplify a filename into its canonical form 1083 ** by making the following changes: 1084 ** 1085 ** * removing any trailing and duplicate / 1086 ** * convert /./ into just / 1087 ** * convert /A/../ where A is any simple name into just / 1088 ** 1089 ** Changes are made in-place. Return the new name length. 1090 ** 1091 ** The original filename is in z[0..n-1]. Return the number of 1092 ** characters in the simplified name. 1093 */ 1094 static int vxworksSimplifyName(char *z, int n){ 1095 int i, j; 1096 while( n>1 && z[n-1]=='/' ){ n--; } 1097 for(i=j=0; i0 && z[j-1]!='/' ){ j--; } 1106 if( j>0 ){ j--; } 1107 i += 2; 1108 continue; 1109 } 1110 } 1111 z[j++] = z[i]; 1112 } 1113 z[j] = 0; 1114 return j; 1115 } 1116 1117 /* 1118 ** Find a unique file ID for the given absolute pathname. Return 1119 ** a pointer to the vxworksFileId object. This pointer is the unique 1120 ** file ID. 1121 ** 1122 ** The nRef field of the vxworksFileId object is incremented before 1123 ** the object is returned. A new vxworksFileId object is created 1124 ** and added to the global list if necessary. 1125 ** 1126 ** If a memory allocation error occurs, return NULL. 1127 */ 1128 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){ 1129 struct vxworksFileId *pNew; /* search key and new file ID */ 1130 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */ 1131 int n; /* Length of zAbsoluteName string */ 1132 1133 if( zAbsoluteName==0 || zAbsoluteName[0]=='/' ); 1134 n = (int)strlen(zAbsoluteName); 1135 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) ); 1136 if( pNew==0 ) return 0; 1137 pNew->zCanonicalName = (char*)&pNew[1]; 1138 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1); 1139 n = vxworksSimplifyName(pNew->zCanonicalName, n); 1140 1141 /* Search for an existing entry that matching the canonical name. 1142 ** If found, increment the reference count and return a pointer to 1143 ** the existing file ID. 1144 */ 1145 sqlite3_mutex_enter(vxworksMutex); 1146 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){ 1147 if( pCandidate->nName==n 1148 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0 1149 ){ 1150 sqlite3_free(pNew); 1151 pCandidate->nRef++; 1152 sqlite3_mutex_leave(vxworksMutex); 1153 return pCandidate; 1154 } 1155 } 1156 1157 /* No match was found. We will make a new file ID */ 1158 pNew->nRef = 1; 1159 pNew->nName = n; 1160 pNew->pNext = vxworksFileList; 1161 vxworksFileList = pNew; 1162 sqlite3_mutex_leave(vxworksMutex); 1163 return pNew; 1164 } 1165 1166 /* 1167 ** Decrement the reference count on a vxworksFileId object. Free 1168 ** the object when the reference count reaches zero. 1169 */ 1170 static void vxworksReleaseFileId(struct vxworksFileId *pId){ 1171 sqlite3_mutex_enter(vxworksMutex); 1172 assert( pId->nRef>0 ); 1173 pId->nRef--; 1174 if( pId->nRef==0 ){ 1175 struct vxworksFileId **pp; 1176 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){} 1177 assert( *pp==pId ); 1178 *pp = pId->pNext; 1179 sqlite3_free(pId); 1180 } 1181 sqlite3_mutex_leave(vxworksMutex); 1182 } 1183 #endif /* OS_VXWORKS */ 1184 /*************** End of Unique File ID Utility Used By VxWorks **************** 1185 ******************************************************************************/ 1186 1187 1188 /****************************************************************************** 1189 *************************** Posix Advisory Locking **************************** 1190 ** 1191 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996) 1192 ** section 6.5.2.2 lines 483 through 490 specify that when a process 1193 ** sets or clears a lock, that operation overrides any prior locks set 1194 ** by the same process. It does not explicitly say so, but this implies 1195 ** that it overrides locks set by the same process using a different 1196 ** file descriptor. Consider this test case: 1197 ** 1198 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644); 1199 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644); 1200 ** 1201 ** Suppose ./file1 and ./file2 are really the same file (because 1202 ** one is a hard or symbolic link to the other) then if you set 1203 ** an exclusive lock on fd1, then try to get an exclusive lock 1204 ** on fd2, it works. I would have expected the second lock to 1205 ** fail since there was already a lock on the file due to fd1. 1206 ** But not so. Since both locks came from the same process, the 1207 ** second overrides the first, even though they were on different 1208 ** file descriptors opened on different file names. 1209 ** 1210 ** This means that we cannot use POSIX locks to synchronize file access 1211 ** among competing threads of the same process. POSIX locks will work fine 1212 ** to synchronize access for threads in separate processes, but not 1213 ** threads within the same process. 1214 ** 1215 ** To work around the problem, SQLite has to manage file locks internally 1216 ** on its own. Whenever a new database is opened, we have to find the 1217 ** specific inode of the database file (the inode is determined by the 1218 ** st_dev and st_ino fields of the stat structure that fstat() fills in) 1219 ** and check for locks already existing on that inode. When locks are 1220 ** created or removed, we have to look at our own internal record of the 1221 ** locks to see if another thread has previously set a lock on that same 1222 ** inode. 1223 ** 1224 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks. 1225 ** For VxWorks, we have to use the alternative unique ID system based on 1226 ** canonical filename and implemented in the previous division.) 1227 ** 1228 ** The sqlite3_file structure for POSIX is no longer just an integer file 1229 ** descriptor. It is now a structure that holds the integer file 1230 ** descriptor and a pointer to a structure that describes the internal 1231 ** locks on the corresponding inode. There is one locking structure 1232 ** per inode, so if the same inode is opened twice, both unixFile structures 1233 ** point to the same locking structure. The locking structure keeps 1234 ** a reference count (so we will know when to delete it) and a "cnt" 1235 ** field that tells us its internal lock status. cnt==0 means the 1236 ** file is unlocked. cnt==-1 means the file has an exclusive lock. 1237 ** cnt>0 means there are cnt shared locks on the file. 1238 ** 1239 ** Any attempt to lock or unlock a file first checks the locking 1240 ** structure. The fcntl() system call is only invoked to set a 1241 ** POSIX lock if the internal lock structure transitions between 1242 ** a locked and an unlocked state. 1243 ** 1244 ** But wait: there are yet more problems with POSIX advisory locks. 1245 ** 1246 ** If you close a file descriptor that points to a file that has locks, 1247 ** all locks on that file that are owned by the current process are 1248 ** released. To work around this problem, each unixInodeInfo object 1249 ** maintains a count of the number of pending locks on the inode. 1250 ** When an attempt is made to close an unixFile, if there are 1251 ** other unixFile open on the same inode that are holding locks, the call 1252 ** to close() the file descriptor is deferred until all of the locks clear. 1253 ** The unixInodeInfo structure keeps a list of file descriptors that need to 1254 ** be closed and that list is walked (and cleared) when the last lock 1255 ** clears. 1256 ** 1257 ** Yet another problem: LinuxThreads do not play well with posix locks. 1258 ** 1259 ** Many older versions of linux use the LinuxThreads library which is 1260 ** not posix compliant. Under LinuxThreads, a lock created by thread 1261 ** A cannot be modified or overridden by a different thread B. 1262 ** Only thread A can modify the lock. Locking behavior is correct 1263 ** if the application uses the newer Native Posix Thread Library (NPTL) 1264 ** on linux - with NPTL a lock created by thread A can override locks 1265 ** in thread B. But there is no way to know at compile-time which 1266 ** threading library is being used. So there is no way to know at 1267 ** compile-time whether or not thread A can override locks on thread B. 1268 ** One has to do a run-time check to discover the behavior of the 1269 ** current process. 1270 ** 1271 ** SQLite used to support LinuxThreads. But support for LinuxThreads 1272 ** was dropped beginning with version 3.7.0. SQLite will still work with 1273 ** LinuxThreads provided that (1) there is no more than one connection 1274 ** per database file in the same process and (2) database connections 1275 ** do not move across threads. 1276 */ 1277 1278 /* 1279 ** An instance of the following structure serves as the key used 1280 ** to locate a particular unixInodeInfo object. 1281 */ 1282 struct unixFileId { 1283 dev_t dev; /* Device number */ 1284 #if OS_VXWORKS 1285 struct vxworksFileId *pId; /* Unique file ID for vxworks. */ 1286 #else 1287 /* We are told that some versions of Android contain a bug that 1288 ** sizes ino_t at only 32-bits instead of 64-bits. (See 1289 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c) 1290 ** To work around this, always allocate 64-bits for the inode number. 1291 ** On small machines that only have 32-bit inodes, this wastes 4 bytes, 1292 ** but that should not be a big deal. */ 1293 /* WAS: ino_t ino; */ 1294 u64 ino; /* Inode number */ 1295 #endif 1296 }; 1297 1298 /* 1299 ** An instance of the following structure is allocated for each open 1300 ** inode. 1301 ** 1302 ** A single inode can have multiple file descriptors, so each unixFile 1303 ** structure contains a pointer to an instance of this object and this 1304 ** object keeps a count of the number of unixFile pointing to it. 1305 ** 1306 ** Mutex rules: 1307 ** 1308 ** (1) Only the pLockMutex mutex must be held in order to read or write 1309 ** any of the locking fields: 1310 ** nShared, nLock, eFileLock, bProcessLock, pUnused 1311 ** 1312 ** (2) When nRef>0, then the following fields are unchanging and can 1313 ** be read (but not written) without holding any mutex: 1314 ** fileId, pLockMutex 1315 ** 1316 ** (3) With the exceptions above, all the fields may only be read 1317 ** or written while holding the global unixBigLock mutex. 1318 ** 1319 ** Deadlock prevention: The global unixBigLock mutex may not 1320 ** be acquired while holding the pLockMutex mutex. If both unixBigLock 1321 ** and pLockMutex are needed, then unixBigLock must be acquired first. 1322 */ 1323 struct unixInodeInfo { 1324 struct unixFileId fileId; /* The lookup key */ 1325 sqlite3_mutex *pLockMutex; /* Hold this mutex for... */ 1326 int nShared; /* Number of SHARED locks held */ 1327 int nLock; /* Number of outstanding file locks */ 1328 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */ 1329 unsigned char bProcessLock; /* An exclusive process lock is held */ 1330 UnixUnusedFd *pUnused; /* Unused file descriptors to close */ 1331 int nRef; /* Number of pointers to this structure */ 1332 unixShmNode *pShmNode; /* Shared memory associated with this inode */ 1333 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */ 1334 unixInodeInfo *pPrev; /* .... doubly linked */ 1335 #if SQLITE_ENABLE_LOCKING_STYLE 1336 unsigned long long sharedByte; /* for AFP simulated shared lock */ 1337 #endif 1338 #if OS_VXWORKS 1339 sem_t *pSem; /* Named POSIX semaphore */ 1340 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */ 1341 #endif 1342 }; 1343 1344 /* 1345 ** A lists of all unixInodeInfo objects. 1346 ** 1347 ** Must hold unixBigLock in order to read or write this variable. 1348 */ 1349 static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */ 1350 1351 #ifdef SQLITE_DEBUG 1352 /* 1353 ** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not. 1354 ** This routine is used only within assert() to help verify correct mutex 1355 ** usage. 1356 */ 1357 int unixFileMutexHeld(unixFile *pFile){ 1358 assert( pFile->pInode ); 1359 return sqlite3_mutex_held(pFile->pInode->pLockMutex); 1360 } 1361 int unixFileMutexNotheld(unixFile *pFile){ 1362 assert( pFile->pInode ); 1363 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex); 1364 } 1365 #endif 1366 1367 /* 1368 ** 1369 ** This function - unixLogErrorAtLine(), is only ever called via the macro 1370 ** unixLogError(). 1371 ** 1372 ** It is invoked after an error occurs in an OS function and errno has been 1373 ** set. It logs a message using sqlite3_log() containing the current value of 1374 ** errno and, if possible, the human-readable equivalent from strerror() or 1375 ** strerror_r(). 1376 ** 1377 ** The first argument passed to the macro should be the error code that 1378 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 1379 ** The two subsequent arguments should be the name of the OS function that 1380 ** failed (e.g. "unlink", "open") and the associated file-system path, 1381 ** if any. 1382 */ 1383 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__) 1384 static int unixLogErrorAtLine( 1385 int errcode, /* SQLite error code */ 1386 const char *zFunc, /* Name of OS function that failed */ 1387 const char *zPath, /* File path associated with error */ 1388 int iLine /* Source line number where error occurred */ 1389 ){ 1390 char *zErr; /* Message from strerror() or equivalent */ 1391 int iErrno = errno; /* Saved syscall error number */ 1392 1393 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use 1394 ** the strerror() function to obtain the human-readable error message 1395 ** equivalent to errno. Otherwise, use strerror_r(). 1396 */ 1397 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R) 1398 char aErr[80]; 1399 memset(aErr, 0, sizeof(aErr)); 1400 zErr = aErr; 1401 1402 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined, 1403 ** assume that the system provides the GNU version of strerror_r() that 1404 ** returns a pointer to a buffer containing the error message. That pointer 1405 ** may point to aErr[], or it may point to some static storage somewhere. 1406 ** Otherwise, assume that the system provides the POSIX version of 1407 ** strerror_r(), which always writes an error message into aErr[]. 1408 ** 1409 ** If the code incorrectly assumes that it is the POSIX version that is 1410 ** available, the error message will often be an empty string. Not a 1411 ** huge problem. Incorrectly concluding that the GNU version is available 1412 ** could lead to a segfault though. 1413 ** 1414 ** Forum post `3f13857fa4062301` reports that the Android SDK may use 1415 ** int-type return, depending on its version. 1416 */ 1417 #if (defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)) \ 1418 && !defined(ANDROID) && !defined(__ANDROID__) 1419 zErr = 1420 # endif 1421 strerror_r(iErrno, aErr, sizeof(aErr)-1); 1422 1423 #elif SQLITE_THREADSAFE 1424 /* This is a threadsafe build, but strerror_r() is not available. */ 1425 zErr = ""; 1426 #else 1427 /* Non-threadsafe build, use strerror(). */ 1428 zErr = strerror(iErrno); 1429 #endif 1430 1431 if( zPath==0 ) zPath = ""; 1432 sqlite3_log(errcode, 1433 "os_unix.c:%d: (%d) %s(%s) - %s", 1434 iLine, iErrno, zFunc, zPath, zErr 1435 ); 1436 1437 return errcode; 1438 } 1439 1440 /* 1441 ** Close a file descriptor. 1442 ** 1443 ** We assume that close() almost always works, since it is only in a 1444 ** very sick application or on a very sick platform that it might fail. 1445 ** If it does fail, simply leak the file descriptor, but do log the 1446 ** error. 1447 ** 1448 ** Note that it is not safe to retry close() after EINTR since the 1449 ** file descriptor might have already been reused by another thread. 1450 ** So we don't even try to recover from an EINTR. Just log the error 1451 ** and move on. 1452 */ 1453 static void robust_close(unixFile *pFile, int h, int lineno){ 1454 if( osClose(h) ){ 1455 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close", 1456 pFile ? pFile->zPath : 0, lineno); 1457 } 1458 } 1459 1460 /* 1461 ** Set the pFile->lastErrno. Do this in a subroutine as that provides 1462 ** a convenient place to set a breakpoint. 1463 */ 1464 static void storeLastErrno(unixFile *pFile, int error){ 1465 pFile->lastErrno = error; 1466 } 1467 1468 /* 1469 ** Close all file descriptors accumulated in the unixInodeInfo->pUnused list. 1470 */ 1471 static void closePendingFds(unixFile *pFile){ 1472 unixInodeInfo *pInode = pFile->pInode; 1473 UnixUnusedFd *p; 1474 UnixUnusedFd *pNext; 1475 assert( unixFileMutexHeld(pFile) ); 1476 for(p=pInode->pUnused; p; p=pNext){ 1477 pNext = p->pNext; 1478 robust_close(pFile, p->fd, __LINE__); 1479 sqlite3_free(p); 1480 } 1481 pInode->pUnused = 0; 1482 } 1483 1484 /* 1485 ** Release a unixInodeInfo structure previously allocated by findInodeInfo(). 1486 ** 1487 ** The global mutex must be held when this routine is called, but the mutex 1488 ** on the inode being deleted must NOT be held. 1489 */ 1490 static void releaseInodeInfo(unixFile *pFile){ 1491 unixInodeInfo *pInode = pFile->pInode; 1492 assert( unixMutexHeld() ); 1493 assert( unixFileMutexNotheld(pFile) ); 1494 if( ALWAYS(pInode) ){ 1495 pInode->nRef--; 1496 if( pInode->nRef==0 ){ 1497 assert( pInode->pShmNode==0 ); 1498 sqlite3_mutex_enter(pInode->pLockMutex); 1499 closePendingFds(pFile); 1500 sqlite3_mutex_leave(pInode->pLockMutex); 1501 if( pInode->pPrev ){ 1502 assert( pInode->pPrev->pNext==pInode ); 1503 pInode->pPrev->pNext = pInode->pNext; 1504 }else{ 1505 assert( inodeList==pInode ); 1506 inodeList = pInode->pNext; 1507 } 1508 if( pInode->pNext ){ 1509 assert( pInode->pNext->pPrev==pInode ); 1510 pInode->pNext->pPrev = pInode->pPrev; 1511 } 1512 sqlite3_mutex_free(pInode->pLockMutex); 1513 sqlite3_free(pInode); 1514 } 1515 } 1516 } 1517 1518 /* 1519 ** Given a file descriptor, locate the unixInodeInfo object that 1520 ** describes that file descriptor. Create a new one if necessary. The 1521 ** return value might be uninitialized if an error occurs. 1522 ** 1523 ** The global mutex must held when calling this routine. 1524 ** 1525 ** Return an appropriate error code. 1526 */ 1527 static int findInodeInfo( 1528 unixFile *pFile, /* Unix file with file desc used in the key */ 1529 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */ 1530 ){ 1531 int rc; /* System call return code */ 1532 int fd; /* The file descriptor for pFile */ 1533 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */ 1534 struct stat statbuf; /* Low-level file information */ 1535 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */ 1536 1537 assert( unixMutexHeld() ); 1538 1539 /* Get low-level information about the file that we can used to 1540 ** create a unique name for the file. 1541 */ 1542 fd = pFile->h; 1543 rc = osFstat(fd, &statbuf); 1544 if( rc!=0 ){ 1545 storeLastErrno(pFile, errno); 1546 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS) 1547 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS; 1548 #endif 1549 return SQLITE_IOERR; 1550 } 1551 1552 #ifdef __APPLE__ 1553 /* On OS X on an msdos filesystem, the inode number is reported 1554 ** incorrectly for zero-size files. See ticket #3260. To work 1555 ** around this problem (we consider it a bug in OS X, not SQLite) 1556 ** we always increase the file size to 1 by writing a single byte 1557 ** prior to accessing the inode number. The one byte written is 1558 ** an ASCII 'S' character which also happens to be the first byte 1559 ** in the header of every SQLite database. In this way, if there 1560 ** is a race condition such that another thread has already populated 1561 ** the first page of the database, no damage is done. 1562 */ 1563 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){ 1564 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR ); 1565 if( rc!=1 ){ 1566 storeLastErrno(pFile, errno); 1567 return SQLITE_IOERR; 1568 } 1569 if( fsync(fd) ){ 1570 storeLastErrno(pFile, errno); 1571 return SQLITE_IOERR_FSYNC; 1572 } 1573 rc = osFstat(fd, &statbuf); 1574 if( rc!=0 ){ 1575 storeLastErrno(pFile, errno); 1576 return SQLITE_IOERR; 1577 } 1578 } 1579 #endif 1580 1581 memset(&fileId, 0, sizeof(fileId)); 1582 fileId.dev = statbuf.st_dev; 1583 #if OS_VXWORKS 1584 fileId.pId = pFile->pId; 1585 #else 1586 fileId.ino = (u64)statbuf.st_ino; 1587 #endif 1588 assert( unixMutexHeld() ); 1589 pInode = inodeList; 1590 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){ 1591 pInode = pInode->pNext; 1592 } 1593 if( pInode==0 ){ 1594 pInode = sqlite3_malloc64( sizeof(*pInode) ); 1595 if( pInode==0 ){ 1596 return SQLITE_NOMEM_BKPT; 1597 } 1598 memset(pInode, 0, sizeof(*pInode)); 1599 memcpy(&pInode->fileId, &fileId, sizeof(fileId)); 1600 if( sqlite3GlobalConfig.bCoreMutex ){ 1601 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); 1602 if( pInode->pLockMutex==0 ){ 1603 sqlite3_free(pInode); 1604 return SQLITE_NOMEM_BKPT; 1605 } 1606 } 1607 pInode->nRef = 1; 1608 assert( unixMutexHeld() ); 1609 pInode->pNext = inodeList; 1610 pInode->pPrev = 0; 1611 if( inodeList ) inodeList->pPrev = pInode; 1612 inodeList = pInode; 1613 }else{ 1614 pInode->nRef++; 1615 } 1616 *ppInode = pInode; 1617 return SQLITE_OK; 1618 } 1619 1620 /* 1621 ** Return TRUE if pFile has been renamed or unlinked since it was first opened. 1622 */ 1623 static int fileHasMoved(unixFile *pFile){ 1624 #if OS_VXWORKS 1625 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId; 1626 #else 1627 struct stat buf; 1628 return pFile->pInode!=0 && 1629 (osStat(pFile->zPath, &buf)!=0 1630 || (u64)buf.st_ino!=pFile->pInode->fileId.ino); 1631 #endif 1632 } 1633 1634 1635 /* 1636 ** Check a unixFile that is a database. Verify the following: 1637 ** 1638 ** (1) There is exactly one hard link on the file 1639 ** (2) The file is not a symbolic link 1640 ** (3) The file has not been renamed or unlinked 1641 ** 1642 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right. 1643 */ 1644 static void verifyDbFile(unixFile *pFile){ 1645 struct stat buf; 1646 int rc; 1647 1648 /* These verifications occurs for the main database only */ 1649 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return; 1650 1651 rc = osFstat(pFile->h, &buf); 1652 if( rc!=0 ){ 1653 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath); 1654 return; 1655 } 1656 if( buf.st_nlink==0 ){ 1657 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath); 1658 return; 1659 } 1660 if( buf.st_nlink>1 ){ 1661 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath); 1662 return; 1663 } 1664 if( fileHasMoved(pFile) ){ 1665 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath); 1666 return; 1667 } 1668 } 1669 1670 1671 /* 1672 ** This routine checks if there is a RESERVED lock held on the specified 1673 ** file by this or any other process. If such a lock is held, set *pResOut 1674 ** to a non-zero value otherwise *pResOut is set to zero. The return value 1675 ** is set to SQLITE_OK unless an I/O error occurs during lock checking. 1676 */ 1677 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){ 1678 int rc = SQLITE_OK; 1679 int reserved = 0; 1680 unixFile *pFile = (unixFile*)id; 1681 1682 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 1683 1684 assert( pFile ); 1685 assert( pFile->eFileLock<=SHARED_LOCK ); 1686 sqlite3_mutex_enter(pFile->pInode->pLockMutex); 1687 1688 /* Check if a thread in this process holds such a lock */ 1689 if( pFile->pInode->eFileLock>SHARED_LOCK ){ 1690 reserved = 1; 1691 } 1692 1693 /* Otherwise see if some other process holds it. 1694 */ 1695 #ifndef __DJGPP__ 1696 if( !reserved && !pFile->pInode->bProcessLock ){ 1697 struct flock lock; 1698 lock.l_whence = SEEK_SET; 1699 lock.l_start = RESERVED_BYTE; 1700 lock.l_len = 1; 1701 lock.l_type = F_WRLCK; 1702 if( osFcntl(pFile->h, F_GETLK, &lock) ){ 1703 rc = SQLITE_IOERR_CHECKRESERVEDLOCK; 1704 storeLastErrno(pFile, errno); 1705 } else if( lock.l_type!=F_UNLCK ){ 1706 reserved = 1; 1707 } 1708 } 1709 #endif 1710 1711 sqlite3_mutex_leave(pFile->pInode->pLockMutex); 1712 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved)); 1713 1714 *pResOut = reserved; 1715 return rc; 1716 } 1717 1718 /* Forward declaration*/ 1719 static int unixSleep(sqlite3_vfs*,int); 1720 1721 /* 1722 ** Set a posix-advisory-lock. 1723 ** 1724 ** There are two versions of this routine. If compiled with 1725 ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter 1726 ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout 1727 ** value is set, then it is the number of milliseconds to wait before 1728 ** failing the lock. The iBusyTimeout value is always reset back to 1729 ** zero on each call. 1730 ** 1731 ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking 1732 ** attempt to set the lock. 1733 */ 1734 #ifndef SQLITE_ENABLE_SETLK_TIMEOUT 1735 # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x) 1736 #else 1737 static int osSetPosixAdvisoryLock( 1738 int h, /* The file descriptor on which to take the lock */ 1739 struct flock *pLock, /* The description of the lock */ 1740 unixFile *pFile /* Structure holding timeout value */ 1741 ){ 1742 int rc = 0; 1743 1744 if( pFile->iBusyTimeout==0 ){ 1745 /* unixFile->iBusyTimeout is set to 0. In this case, attempt a 1746 ** non-blocking lock. */ 1747 rc = osFcntl(h,F_SETLK,pLock); 1748 }else{ 1749 /* unixFile->iBusyTimeout is set to greater than zero. In this case, 1750 ** attempt a blocking-lock with a unixFile->iBusyTimeout ms timeout. 1751 ** 1752 ** On systems that support some kind of blocking file lock operation, 1753 ** this block should be replaced by code to attempt a blocking lock 1754 ** with a timeout of unixFile->iBusyTimeout ms. The code below is 1755 ** placeholder code. If SQLITE_TEST is defined, the placeholder code 1756 ** retries the lock once every 1ms until it succeeds or the timeout 1757 ** is reached. Or, if SQLITE_TEST is not defined, the placeholder 1758 ** code attempts a non-blocking lock and sets unixFile->iBusyTimeout 1759 ** to 0. This causes the caller to return SQLITE_BUSY, instead of 1760 ** SQLITE_BUSY_TIMEOUT to SQLite - as required by a VFS that does not 1761 ** support blocking locks. 1762 */ 1763 #ifdef SQLITE_TEST 1764 int tm = pFile->iBusyTimeout; 1765 while( tm>0 ){ 1766 rc = osFcntl(h,F_SETLK,pLock); 1767 if( rc==0 ) break; 1768 unixSleep(0,1000); 1769 tm--; 1770 } 1771 #else 1772 rc = osFcntl(h,F_SETLK,pLock); 1773 pFile->iBusyTimeout = 0; 1774 #endif 1775 /* End of code to replace with real blocking-locks code. */ 1776 } 1777 1778 return rc; 1779 } 1780 #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */ 1781 1782 1783 /* 1784 ** Attempt to set a system-lock on the file pFile. The lock is 1785 ** described by pLock. 1786 ** 1787 ** If the pFile was opened read/write from unix-excl, then the only lock 1788 ** ever obtained is an exclusive lock, and it is obtained exactly once 1789 ** the first time any lock is attempted. All subsequent system locking 1790 ** operations become no-ops. Locking operations still happen internally, 1791 ** in order to coordinate access between separate database connections 1792 ** within this process, but all of that is handled in memory and the 1793 ** operating system does not participate. 1794 ** 1795 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using 1796 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl" 1797 ** and is read-only. 1798 ** 1799 ** Zero is returned if the call completes successfully, or -1 if a call 1800 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()). 1801 */ 1802 static int unixFileLock(unixFile *pFile, struct flock *pLock){ 1803 int rc; 1804 unixInodeInfo *pInode = pFile->pInode; 1805 assert( pInode!=0 ); 1806 assert( sqlite3_mutex_held(pInode->pLockMutex) ); 1807 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){ 1808 if( pInode->bProcessLock==0 ){ 1809 struct flock lock; 1810 /* assert( pInode->nLock==0 ); <-- Not true if unix-excl READONLY used */ 1811 lock.l_whence = SEEK_SET; 1812 lock.l_start = SHARED_FIRST; 1813 lock.l_len = SHARED_SIZE; 1814 lock.l_type = F_WRLCK; 1815 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile); 1816 if( rc<0 ) return rc; 1817 pInode->bProcessLock = 1; 1818 pInode->nLock++; 1819 }else{ 1820 rc = 0; 1821 } 1822 }else{ 1823 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 1824 if( pFile->bBlockOnConnect && pLock->l_type==F_RDLCK 1825 && pLock->l_start==SHARED_FIRST && pLock->l_len==SHARED_SIZE 1826 ){ 1827 rc = osFcntl(pFile->h, F_SETLKW, pLock); 1828 }else 1829 #endif 1830 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile); 1831 } 1832 return rc; 1833 } 1834 1835 #if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL) 1836 /* Forward reference */ 1837 static int unixIsSharingShmNode(unixFile*); 1838 #else 1839 #define unixIsSharingShmNode(pFile) (0) 1840 #endif 1841 1842 /* 1843 ** Lock the file with the lock specified by parameter eFileLock - one 1844 ** of the following: 1845 ** 1846 ** (1) SHARED_LOCK 1847 ** (2) RESERVED_LOCK 1848 ** (3) PENDING_LOCK 1849 ** (4) EXCLUSIVE_LOCK 1850 ** 1851 ** Sometimes when requesting one lock state, additional lock states 1852 ** are inserted in between. The locking might fail on one of the later 1853 ** transitions leaving the lock state different from what it started but 1854 ** still short of its goal. The following chart shows the allowed 1855 ** transitions and the inserted intermediate states: 1856 ** 1857 ** UNLOCKED -> SHARED 1858 ** SHARED -> RESERVED 1859 ** SHARED -> EXCLUSIVE 1860 ** RESERVED -> (PENDING) -> EXCLUSIVE 1861 ** PENDING -> EXCLUSIVE 1862 ** 1863 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 1864 ** routine to lower a locking level. 1865 */ 1866 static int unixLock(sqlite3_file *id, int eFileLock){ 1867 /* The following describes the implementation of the various locks and 1868 ** lock transitions in terms of the POSIX advisory shared and exclusive 1869 ** lock primitives (called read-locks and write-locks below, to avoid 1870 ** confusion with SQLite lock names). The algorithms are complicated 1871 ** slightly in order to be compatible with Windows95 systems simultaneously 1872 ** accessing the same database file, in case that is ever required. 1873 ** 1874 ** Symbols defined in os.h identify the 'pending byte' and the 'reserved 1875 ** byte', each single bytes at well known offsets, and the 'shared byte 1876 ** range', a range of 510 bytes at a well known offset. 1877 ** 1878 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending 1879 ** byte'. If this is successful, 'shared byte range' is read-locked 1880 ** and the lock on the 'pending byte' released. (Legacy note: When 1881 ** SQLite was first developed, Windows95 systems were still very common, 1882 ** and Windows95 lacks a shared-lock capability. So on Windows95, a 1883 ** single randomly selected by from the 'shared byte range' is locked. 1884 ** Windows95 is now pretty much extinct, but this work-around for the 1885 ** lack of shared-locks on Windows95 lives on, for backwards 1886 ** compatibility.) 1887 ** 1888 ** A process may only obtain a RESERVED lock after it has a SHARED lock. 1889 ** A RESERVED lock is implemented by grabbing a write-lock on the 1890 ** 'reserved byte'. 1891 ** 1892 ** An EXCLUSIVE lock may only be requested after either a SHARED or 1893 ** RESERVED lock is held. An EXCLUSIVE lock is implemented by obtaining 1894 ** a write-lock on the entire 'shared byte range'. Since all other locks 1895 ** require a read-lock on one of the bytes within this range, this ensures 1896 ** that no other locks are held on the database. 1897 ** 1898 ** If a process that holds a RESERVED lock requests an EXCLUSIVE, then 1899 ** a PENDING lock is obtained first. A PENDING lock is implemented by 1900 ** obtaining a write-lock on the 'pending byte'. This ensures that no new 1901 ** SHARED locks can be obtained, but existing SHARED locks are allowed to 1902 ** persist. If the call to this function fails to obtain the EXCLUSIVE 1903 ** lock in this case, it holds the PENDING lock instead. The client may 1904 ** then re-attempt the EXCLUSIVE lock later on, after existing SHARED 1905 ** locks have cleared. 1906 */ 1907 int rc = SQLITE_OK; 1908 unixFile *pFile = (unixFile*)id; 1909 unixInodeInfo *pInode; 1910 struct flock lock; 1911 int tErrno = 0; 1912 1913 assert( pFile ); 1914 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h, 1915 azFileLock(eFileLock), azFileLock(pFile->eFileLock), 1916 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared, 1917 osGetpid(0))); 1918 1919 /* If there is already a lock of this type or more restrictive on the 1920 ** unixFile, do nothing. Don't use the end_lock: exit path, as 1921 ** unixEnterMutex() hasn't been called yet. 1922 */ 1923 if( pFile->eFileLock>=eFileLock ){ 1924 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h, 1925 azFileLock(eFileLock))); 1926 return SQLITE_OK; 1927 } 1928 1929 /* Make sure the locking sequence is correct. 1930 ** (1) We never move from unlocked to anything higher than shared lock. 1931 ** (2) SQLite never explicitly requests a pending lock. 1932 ** (3) A shared lock is always held when a reserve lock is requested. 1933 */ 1934 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK ); 1935 assert( eFileLock!=PENDING_LOCK ); 1936 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK ); 1937 1938 /* This mutex is needed because pFile->pInode is shared across threads 1939 */ 1940 pInode = pFile->pInode; 1941 sqlite3_mutex_enter(pInode->pLockMutex); 1942 1943 /* If some thread using this PID has a lock via a different unixFile* 1944 ** handle that precludes the requested lock, return BUSY. 1945 */ 1946 if( (pFile->eFileLock!=pInode->eFileLock && 1947 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK)) 1948 ){ 1949 rc = SQLITE_BUSY; 1950 goto end_lock; 1951 } 1952 1953 /* If a SHARED lock is requested, and some thread using this PID already 1954 ** has a SHARED or RESERVED lock, then increment reference counts and 1955 ** return SQLITE_OK. 1956 */ 1957 if( eFileLock==SHARED_LOCK && 1958 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){ 1959 assert( eFileLock==SHARED_LOCK ); 1960 assert( pFile->eFileLock==0 ); 1961 assert( pInode->nShared>0 ); 1962 pFile->eFileLock = SHARED_LOCK; 1963 pInode->nShared++; 1964 pInode->nLock++; 1965 goto end_lock; 1966 } 1967 1968 1969 /* A PENDING lock is needed before acquiring a SHARED lock and before 1970 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will 1971 ** be released. 1972 */ 1973 lock.l_len = 1L; 1974 lock.l_whence = SEEK_SET; 1975 if( eFileLock==SHARED_LOCK 1976 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock==RESERVED_LOCK) 1977 ){ 1978 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK); 1979 lock.l_start = PENDING_BYTE; 1980 if( unixFileLock(pFile, &lock) ){ 1981 tErrno = errno; 1982 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 1983 if( rc!=SQLITE_BUSY ){ 1984 storeLastErrno(pFile, tErrno); 1985 } 1986 goto end_lock; 1987 }else if( eFileLock==EXCLUSIVE_LOCK ){ 1988 pFile->eFileLock = PENDING_LOCK; 1989 pInode->eFileLock = PENDING_LOCK; 1990 } 1991 } 1992 1993 1994 /* If control gets to this point, then actually go ahead and make 1995 ** operating system calls for the specified lock. 1996 */ 1997 if( eFileLock==SHARED_LOCK ){ 1998 assert( pInode->nShared==0 ); 1999 assert( pInode->eFileLock==0 ); 2000 assert( rc==SQLITE_OK ); 2001 2002 /* Now get the read-lock */ 2003 lock.l_start = SHARED_FIRST; 2004 lock.l_len = SHARED_SIZE; 2005 if( unixFileLock(pFile, &lock) ){ 2006 tErrno = errno; 2007 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 2008 } 2009 2010 /* Drop the temporary PENDING lock */ 2011 lock.l_start = PENDING_BYTE; 2012 lock.l_len = 1L; 2013 lock.l_type = F_UNLCK; 2014 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){ 2015 /* This could happen with a network mount */ 2016 tErrno = errno; 2017 rc = SQLITE_IOERR_UNLOCK; 2018 } 2019 2020 if( rc ){ 2021 if( rc!=SQLITE_BUSY ){ 2022 storeLastErrno(pFile, tErrno); 2023 } 2024 goto end_lock; 2025 }else{ 2026 pFile->eFileLock = SHARED_LOCK; 2027 pInode->nLock++; 2028 pInode->nShared = 1; 2029 } 2030 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){ 2031 /* We are trying for an exclusive lock but another thread in this 2032 ** same process is still holding a shared lock. */ 2033 rc = SQLITE_BUSY; 2034 }else if( unixIsSharingShmNode(pFile) ){ 2035 /* We are in WAL mode and attempting to delete the SHM and WAL 2036 ** files due to closing the connection or changing out of WAL mode, 2037 ** but another process still holds locks on the SHM file, thus 2038 ** indicating that database locks have been broken, perhaps due 2039 ** to a rogue close(open(dbFile)) or similar. 2040 */ 2041 rc = SQLITE_BUSY; 2042 }else{ 2043 /* The request was for a RESERVED or EXCLUSIVE lock. It is 2044 ** assumed that there is a SHARED or greater lock on the file 2045 ** already. 2046 */ 2047 assert( 0!=pFile->eFileLock ); 2048 lock.l_type = F_WRLCK; 2049 2050 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK ); 2051 if( eFileLock==RESERVED_LOCK ){ 2052 lock.l_start = RESERVED_BYTE; 2053 lock.l_len = 1L; 2054 }else{ 2055 lock.l_start = SHARED_FIRST; 2056 lock.l_len = SHARED_SIZE; 2057 } 2058 2059 if( unixFileLock(pFile, &lock) ){ 2060 tErrno = errno; 2061 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 2062 if( rc!=SQLITE_BUSY ){ 2063 storeLastErrno(pFile, tErrno); 2064 } 2065 } 2066 } 2067 2068 2069 #ifdef SQLITE_DEBUG 2070 /* Set up the transaction-counter change checking flags when 2071 ** transitioning from a SHARED to a RESERVED lock. The change 2072 ** from SHARED to RESERVED marks the beginning of a normal 2073 ** write operation (not a hot journal rollback). 2074 */ 2075 if( rc==SQLITE_OK 2076 && pFile->eFileLock<=SHARED_LOCK 2077 && eFileLock==RESERVED_LOCK 2078 ){ 2079 pFile->transCntrChng = 0; 2080 pFile->dbUpdate = 0; 2081 pFile->inNormalWrite = 1; 2082 } 2083 #endif 2084 2085 if( rc==SQLITE_OK ){ 2086 pFile->eFileLock = eFileLock; 2087 pInode->eFileLock = eFileLock; 2088 } 2089 2090 end_lock: 2091 sqlite3_mutex_leave(pInode->pLockMutex); 2092 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 2093 rc==SQLITE_OK ? "ok" : "failed")); 2094 return rc; 2095 } 2096 2097 /* 2098 ** Add the file descriptor used by file handle pFile to the corresponding 2099 ** pUnused list. 2100 */ 2101 static void setPendingFd(unixFile *pFile){ 2102 unixInodeInfo *pInode = pFile->pInode; 2103 UnixUnusedFd *p = pFile->pPreallocatedUnused; 2104 assert( unixFileMutexHeld(pFile) ); 2105 p->pNext = pInode->pUnused; 2106 pInode->pUnused = p; 2107 pFile->h = -1; 2108 pFile->pPreallocatedUnused = 0; 2109 } 2110 2111 /* 2112 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock 2113 ** must be either NO_LOCK or SHARED_LOCK. 2114 ** 2115 ** If the locking level of the file descriptor is already at or below 2116 ** the requested locking level, this routine is a no-op. 2117 ** 2118 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED 2119 ** the byte range is divided into 2 parts and the first part is unlocked then 2120 ** set to a read lock, then the other part is simply unlocked. This works 2121 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 2122 ** remove the write lock on a region when a read lock is set. 2123 */ 2124 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){ 2125 unixFile *pFile = (unixFile*)id; 2126 unixInodeInfo *pInode; 2127 struct flock lock; 2128 int rc = SQLITE_OK; 2129 2130 assert( pFile ); 2131 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock, 2132 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared, 2133 osGetpid(0))); 2134 2135 assert( eFileLock<=SHARED_LOCK ); 2136 if( pFile->eFileLock<=eFileLock ){ 2137 return SQLITE_OK; 2138 } 2139 pInode = pFile->pInode; 2140 sqlite3_mutex_enter(pInode->pLockMutex); 2141 assert( pInode->nShared!=0 ); 2142 if( pFile->eFileLock>SHARED_LOCK ){ 2143 assert( pInode->eFileLock==pFile->eFileLock ); 2144 2145 #ifdef SQLITE_DEBUG 2146 /* When reducing a lock such that other processes can start 2147 ** reading the database file again, make sure that the 2148 ** transaction counter was updated if any part of the database 2149 ** file changed. If the transaction counter is not updated, 2150 ** other connections to the same file might not realize that 2151 ** the file has changed and hence might not know to flush their 2152 ** cache. The use of a stale cache can lead to database corruption. 2153 */ 2154 pFile->inNormalWrite = 0; 2155 #endif 2156 2157 /* downgrading to a shared lock on NFS involves clearing the write lock 2158 ** before establishing the readlock - to avoid a race condition we downgrade 2159 ** the lock in 2 blocks, so that part of the range will be covered by a 2160 ** write lock until the rest is covered by a read lock: 2161 ** 1: [WWWWW] 2162 ** 2: [....W] 2163 ** 3: [RRRRW] 2164 ** 4: [RRRR.] 2165 */ 2166 if( eFileLock==SHARED_LOCK ){ 2167 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE 2168 (void)handleNFSUnlock; 2169 assert( handleNFSUnlock==0 ); 2170 #endif 2171 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 2172 if( handleNFSUnlock ){ 2173 int tErrno; /* Error code from system call errors */ 2174 off_t divSize = SHARED_SIZE - 1; 2175 2176 lock.l_type = F_UNLCK; 2177 lock.l_whence = SEEK_SET; 2178 lock.l_start = SHARED_FIRST; 2179 lock.l_len = divSize; 2180 if( unixFileLock(pFile, &lock)==(-1) ){ 2181 tErrno = errno; 2182 rc = SQLITE_IOERR_UNLOCK; 2183 storeLastErrno(pFile, tErrno); 2184 goto end_unlock; 2185 } 2186 lock.l_type = F_RDLCK; 2187 lock.l_whence = SEEK_SET; 2188 lock.l_start = SHARED_FIRST; 2189 lock.l_len = divSize; 2190 if( unixFileLock(pFile, &lock)==(-1) ){ 2191 tErrno = errno; 2192 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK); 2193 if( IS_LOCK_ERROR(rc) ){ 2194 storeLastErrno(pFile, tErrno); 2195 } 2196 goto end_unlock; 2197 } 2198 lock.l_type = F_UNLCK; 2199 lock.l_whence = SEEK_SET; 2200 lock.l_start = SHARED_FIRST+divSize; 2201 lock.l_len = SHARED_SIZE-divSize; 2202 if( unixFileLock(pFile, &lock)==(-1) ){ 2203 tErrno = errno; 2204 rc = SQLITE_IOERR_UNLOCK; 2205 storeLastErrno(pFile, tErrno); 2206 goto end_unlock; 2207 } 2208 }else 2209 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ 2210 { 2211 lock.l_type = F_RDLCK; 2212 lock.l_whence = SEEK_SET; 2213 lock.l_start = SHARED_FIRST; 2214 lock.l_len = SHARED_SIZE; 2215 if( unixFileLock(pFile, &lock) ){ 2216 /* In theory, the call to unixFileLock() cannot fail because another 2217 ** process is holding an incompatible lock. If it does, this 2218 ** indicates that the other process is not following the locking 2219 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning 2220 ** SQLITE_BUSY would confuse the upper layer (in practice it causes 2221 ** an assert to fail). */ 2222 rc = SQLITE_IOERR_RDLOCK; 2223 storeLastErrno(pFile, errno); 2224 goto end_unlock; 2225 } 2226 } 2227 } 2228 lock.l_type = F_UNLCK; 2229 lock.l_whence = SEEK_SET; 2230 lock.l_start = PENDING_BYTE; 2231 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE ); 2232 if( unixFileLock(pFile, &lock)==0 ){ 2233 pInode->eFileLock = SHARED_LOCK; 2234 }else{ 2235 rc = SQLITE_IOERR_UNLOCK; 2236 storeLastErrno(pFile, errno); 2237 goto end_unlock; 2238 } 2239 } 2240 if( eFileLock==NO_LOCK ){ 2241 /* Decrement the shared lock counter. Release the lock using an 2242 ** OS call only when all threads in this same process have released 2243 ** the lock. 2244 */ 2245 pInode->nShared--; 2246 if( pInode->nShared==0 ){ 2247 lock.l_type = F_UNLCK; 2248 lock.l_whence = SEEK_SET; 2249 lock.l_start = lock.l_len = 0L; 2250 if( unixFileLock(pFile, &lock)==0 ){ 2251 pInode->eFileLock = NO_LOCK; 2252 }else{ 2253 rc = SQLITE_IOERR_UNLOCK; 2254 storeLastErrno(pFile, errno); 2255 pInode->eFileLock = NO_LOCK; 2256 pFile->eFileLock = NO_LOCK; 2257 } 2258 } 2259 2260 /* Decrement the count of locks against this same file. When the 2261 ** count reaches zero, close any other file descriptors whose close 2262 ** was deferred because of outstanding locks. 2263 */ 2264 pInode->nLock--; 2265 assert( pInode->nLock>=0 ); 2266 if( pInode->nLock==0 ) closePendingFds(pFile); 2267 } 2268 2269 end_unlock: 2270 sqlite3_mutex_leave(pInode->pLockMutex); 2271 if( rc==SQLITE_OK ){ 2272 pFile->eFileLock = eFileLock; 2273 } 2274 return rc; 2275 } 2276 2277 /* 2278 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock 2279 ** must be either NO_LOCK or SHARED_LOCK. 2280 ** 2281 ** If the locking level of the file descriptor is already at or below 2282 ** the requested locking level, this routine is a no-op. 2283 */ 2284 static int unixUnlock(sqlite3_file *id, int eFileLock){ 2285 #if SQLITE_MAX_MMAP_SIZE>0 2286 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 ); 2287 #endif 2288 return posixUnlock(id, eFileLock, 0); 2289 } 2290 2291 #if SQLITE_MAX_MMAP_SIZE>0 2292 static int unixMapfile(unixFile *pFd, i64 nByte); 2293 static void unixUnmapfile(unixFile *pFd); 2294 #endif 2295 2296 /* 2297 ** This function performs the parts of the "close file" operation 2298 ** common to all locking schemes. It closes the directory and file 2299 ** handles, if they are valid, and sets all fields of the unixFile 2300 ** structure to 0. 2301 ** 2302 ** It is *not* necessary to hold the mutex when this routine is called, 2303 ** even on VxWorks. A mutex will be acquired on VxWorks by the 2304 ** vxworksReleaseFileId() routine. 2305 */ 2306 static int closeUnixFile(sqlite3_file *id){ 2307 unixFile *pFile = (unixFile*)id; 2308 #if SQLITE_MAX_MMAP_SIZE>0 2309 unixUnmapfile(pFile); 2310 #endif 2311 if( pFile->h>=0 ){ 2312 robust_close(pFile, pFile->h, __LINE__); 2313 pFile->h = -1; 2314 } 2315 #if OS_VXWORKS 2316 if( pFile->pId ){ 2317 if( pFile->ctrlFlags & UNIXFILE_DELETE ){ 2318 osUnlink(pFile->pId->zCanonicalName); 2319 } 2320 vxworksReleaseFileId(pFile->pId); 2321 pFile->pId = 0; 2322 } 2323 #endif 2324 #ifdef SQLITE_UNLINK_AFTER_CLOSE 2325 if( pFile->ctrlFlags & UNIXFILE_DELETE ){ 2326 osUnlink(pFile->zPath); 2327 sqlite3_free(*(char**)&pFile->zPath); 2328 pFile->zPath = 0; 2329 } 2330 #endif 2331 OSTRACE(("CLOSE %-3d\n", pFile->h)); 2332 OpenCounter(-1); 2333 sqlite3_free(pFile->pPreallocatedUnused); 2334 memset(pFile, 0, sizeof(unixFile)); 2335 return SQLITE_OK; 2336 } 2337 2338 /* 2339 ** Close a file. 2340 */ 2341 static int unixClose(sqlite3_file *id){ 2342 int rc = SQLITE_OK; 2343 unixFile *pFile = (unixFile *)id; 2344 unixInodeInfo *pInode = pFile->pInode; 2345 2346 assert( pInode!=0 ); 2347 verifyDbFile(pFile); 2348 unixUnlock(id, NO_LOCK); 2349 assert( unixFileMutexNotheld(pFile) ); 2350 unixEnterMutex(); 2351 2352 /* unixFile.pInode is always valid here. Otherwise, a different close 2353 ** routine (e.g. nolockClose()) would be called instead. 2354 */ 2355 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 ); 2356 sqlite3_mutex_enter(pInode->pLockMutex); 2357 if( pInode->nLock ){ 2358 /* If there are outstanding locks, do not actually close the file just 2359 ** yet because that would clear those locks. Instead, add the file 2360 ** descriptor to pInode->pUnused list. It will be automatically closed 2361 ** when the last lock is cleared. 2362 */ 2363 setPendingFd(pFile); 2364 } 2365 sqlite3_mutex_leave(pInode->pLockMutex); 2366 releaseInodeInfo(pFile); 2367 assert( pFile->pShm==0 ); 2368 rc = closeUnixFile(id); 2369 unixLeaveMutex(); 2370 return rc; 2371 } 2372 2373 /************** End of the posix advisory lock implementation ***************** 2374 ******************************************************************************/ 2375 2376 /****************************************************************************** 2377 ****************************** No-op Locking ********************************** 2378 ** 2379 ** Of the various locking implementations available, this is by far the 2380 ** simplest: locking is ignored. No attempt is made to lock the database 2381 ** file for reading or writing. 2382 ** 2383 ** This locking mode is appropriate for use on read-only databases 2384 ** (ex: databases that are burned into CD-ROM, for example.) It can 2385 ** also be used if the application employs some external mechanism to 2386 ** prevent simultaneous access of the same database by two or more 2387 ** database connections. But there is a serious risk of database 2388 ** corruption if this locking mode is used in situations where multiple 2389 ** database connections are accessing the same database file at the same 2390 ** time and one or more of those connections are writing. 2391 */ 2392 2393 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){ 2394 UNUSED_PARAMETER(NotUsed); 2395 *pResOut = 0; 2396 return SQLITE_OK; 2397 } 2398 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){ 2399 UNUSED_PARAMETER2(NotUsed, NotUsed2); 2400 return SQLITE_OK; 2401 } 2402 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){ 2403 UNUSED_PARAMETER2(NotUsed, NotUsed2); 2404 return SQLITE_OK; 2405 } 2406 2407 /* 2408 ** Close the file. 2409 */ 2410 static int nolockClose(sqlite3_file *id) { 2411 return closeUnixFile(id); 2412 } 2413 2414 /******************* End of the no-op lock implementation ********************* 2415 ******************************************************************************/ 2416 2417 /****************************************************************************** 2418 ************************* Begin dot-file Locking ****************************** 2419 ** 2420 ** The dotfile locking implementation uses the existence of separate lock 2421 ** files (really a directory) to control access to the database. This works 2422 ** on just about every filesystem imaginable. But there are serious downsides: 2423 ** 2424 ** (1) There is zero concurrency. A single reader blocks all other 2425 ** connections from reading or writing the database. 2426 ** 2427 ** (2) An application crash or power loss can leave stale lock files 2428 ** sitting around that need to be cleared manually. 2429 ** 2430 ** Nevertheless, a dotlock is an appropriate locking mode for use if no 2431 ** other locking strategy is available. 2432 ** 2433 ** Dotfile locking works by creating a subdirectory in the same directory as 2434 ** the database and with the same name but with a ".lock" extension added. 2435 ** The existence of a lock directory implies an EXCLUSIVE lock. All other 2436 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE. 2437 */ 2438 2439 /* 2440 ** The file suffix added to the data base filename in order to create the 2441 ** lock directory. 2442 */ 2443 #define DOTLOCK_SUFFIX ".lock" 2444 2445 /* 2446 ** This routine checks if there is a RESERVED lock held on the specified 2447 ** file by this or any other process. If the caller holds a SHARED 2448 ** or greater lock when it is called, then it is assumed that no other 2449 ** client may hold RESERVED. Or, if the caller holds no lock, then it 2450 ** is assumed another client holds RESERVED if the lock-file exists. 2451 */ 2452 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) { 2453 unixFile *pFile = (unixFile*)id; 2454 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 2455 2456 if( pFile->eFileLock>=SHARED_LOCK ){ 2457 *pResOut = 0; 2458 }else{ 2459 *pResOut = osAccess((const char*)pFile->lockingContext, 0)==0; 2460 } 2461 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, 0, *pResOut)); 2462 return SQLITE_OK; 2463 } 2464 2465 /* 2466 ** Lock the file with the lock specified by parameter eFileLock - one 2467 ** of the following: 2468 ** 2469 ** (1) SHARED_LOCK 2470 ** (2) RESERVED_LOCK 2471 ** (3) PENDING_LOCK 2472 ** (4) EXCLUSIVE_LOCK 2473 ** 2474 ** Sometimes when requesting one lock state, additional lock states 2475 ** are inserted in between. The locking might fail on one of the later 2476 ** transitions leaving the lock state different from what it started but 2477 ** still short of its goal. The following chart shows the allowed 2478 ** transitions and the inserted intermediate states: 2479 ** 2480 ** UNLOCKED -> SHARED 2481 ** SHARED -> RESERVED 2482 ** SHARED -> (PENDING) -> EXCLUSIVE 2483 ** RESERVED -> (PENDING) -> EXCLUSIVE 2484 ** PENDING -> EXCLUSIVE 2485 ** 2486 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 2487 ** routine to lower a locking level. 2488 ** 2489 ** With dotfile locking, we really only support state (4): EXCLUSIVE. 2490 ** But we track the other locking levels internally. 2491 */ 2492 static int dotlockLock(sqlite3_file *id, int eFileLock) { 2493 unixFile *pFile = (unixFile*)id; 2494 char *zLockFile = (char *)pFile->lockingContext; 2495 int rc = SQLITE_OK; 2496 2497 2498 /* If we have any lock, then the lock file already exists. All we have 2499 ** to do is adjust our internal record of the lock level. 2500 */ 2501 if( pFile->eFileLock > NO_LOCK ){ 2502 pFile->eFileLock = eFileLock; 2503 /* Always update the timestamp on the old file */ 2504 #ifdef HAVE_UTIME 2505 utime(zLockFile, NULL); 2506 #else 2507 utimes(zLockFile, NULL); 2508 #endif 2509 return SQLITE_OK; 2510 } 2511 2512 /* grab an exclusive lock */ 2513 rc = osMkdir(zLockFile, 0777); 2514 if( rc<0 ){ 2515 /* failed to open/create the lock directory */ 2516 int tErrno = errno; 2517 if( EEXIST == tErrno ){ 2518 rc = SQLITE_BUSY; 2519 } else { 2520 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 2521 if( rc!=SQLITE_BUSY ){ 2522 storeLastErrno(pFile, tErrno); 2523 } 2524 } 2525 return rc; 2526 } 2527 2528 /* got it, set the type and return ok */ 2529 pFile->eFileLock = eFileLock; 2530 return rc; 2531 } 2532 2533 /* 2534 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock 2535 ** must be either NO_LOCK or SHARED_LOCK. 2536 ** 2537 ** If the locking level of the file descriptor is already at or below 2538 ** the requested locking level, this routine is a no-op. 2539 ** 2540 ** When the locking level reaches NO_LOCK, delete the lock file. 2541 */ 2542 static int dotlockUnlock(sqlite3_file *id, int eFileLock) { 2543 unixFile *pFile = (unixFile*)id; 2544 char *zLockFile = (char *)pFile->lockingContext; 2545 int rc; 2546 2547 assert( pFile ); 2548 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock, 2549 pFile->eFileLock, osGetpid(0))); 2550 assert( eFileLock<=SHARED_LOCK ); 2551 2552 /* no-op if possible */ 2553 if( pFile->eFileLock==eFileLock ){ 2554 return SQLITE_OK; 2555 } 2556 2557 /* To downgrade to shared, simply update our internal notion of the 2558 ** lock state. No need to mess with the file on disk. 2559 */ 2560 if( eFileLock==SHARED_LOCK ){ 2561 pFile->eFileLock = SHARED_LOCK; 2562 return SQLITE_OK; 2563 } 2564 2565 /* To fully unlock the database, delete the lock file */ 2566 assert( eFileLock==NO_LOCK ); 2567 rc = osRmdir(zLockFile); 2568 if( rc<0 ){ 2569 int tErrno = errno; 2570 if( tErrno==ENOENT ){ 2571 rc = SQLITE_OK; 2572 }else{ 2573 rc = SQLITE_IOERR_UNLOCK; 2574 storeLastErrno(pFile, tErrno); 2575 } 2576 return rc; 2577 } 2578 pFile->eFileLock = NO_LOCK; 2579 return SQLITE_OK; 2580 } 2581 2582 /* 2583 ** Close a file. Make sure the lock has been released before closing. 2584 */ 2585 static int dotlockClose(sqlite3_file *id) { 2586 unixFile *pFile = (unixFile*)id; 2587 assert( id!=0 ); 2588 dotlockUnlock(id, NO_LOCK); 2589 sqlite3_free(pFile->lockingContext); 2590 return closeUnixFile(id); 2591 } 2592 /****************** End of the dot-file lock implementation ******************* 2593 ******************************************************************************/ 2594 2595 /****************************************************************************** 2596 ************************** Begin flock Locking ******************************** 2597 ** 2598 ** Use the flock() system call to do file locking. 2599 ** 2600 ** flock() locking is like dot-file locking in that the various 2601 ** fine-grain locking levels supported by SQLite are collapsed into 2602 ** a single exclusive lock. In other words, SHARED, RESERVED, and 2603 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite 2604 ** still works when you do this, but concurrency is reduced since 2605 ** only a single process can be reading the database at a time. 2606 ** 2607 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off 2608 */ 2609 #if SQLITE_ENABLE_LOCKING_STYLE 2610 2611 /* 2612 ** Retry flock() calls that fail with EINTR 2613 */ 2614 #ifdef EINTR 2615 static int robust_flock(int fd, int op){ 2616 int rc; 2617 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR ); 2618 return rc; 2619 } 2620 #else 2621 # define robust_flock(a,b) flock(a,b) 2622 #endif 2623 2624 2625 /* 2626 ** This routine checks if there is a RESERVED lock held on the specified 2627 ** file by this or any other process. If such a lock is held, set *pResOut 2628 ** to a non-zero value otherwise *pResOut is set to zero. The return value 2629 ** is set to SQLITE_OK unless an I/O error occurs during lock checking. 2630 */ 2631 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){ 2632 #ifdef SQLITE_DEBUG 2633 unixFile *pFile = (unixFile*)id; 2634 #else 2635 UNUSED_PARAMETER(id); 2636 #endif 2637 2638 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 2639 2640 assert( pFile ); 2641 assert( pFile->eFileLock<=SHARED_LOCK ); 2642 2643 /* The flock VFS only ever takes exclusive locks (see function flockLock). 2644 ** Therefore, if this connection is holding any lock at all, no other 2645 ** connection may be holding a RESERVED lock. So set *pResOut to 0 2646 ** in this case. 2647 ** 2648 ** Or, this connection may be holding no lock. In that case, set *pResOut to 2649 ** 0 as well. The caller will then attempt to take an EXCLUSIVE lock on the 2650 ** db in order to roll the hot journal back. If there is another connection 2651 ** holding a lock, that attempt will fail and an SQLITE_BUSY returned to 2652 ** the user. With other VFS, we try to avoid this, in order to allow a reader 2653 ** to proceed while a writer is preparing its transaction. But that won't 2654 ** work with the flock VFS - as it always takes EXCLUSIVE locks - so it is 2655 ** not a problem in this case. */ 2656 *pResOut = 0; 2657 2658 return SQLITE_OK; 2659 } 2660 2661 /* 2662 ** Lock the file with the lock specified by parameter eFileLock - one 2663 ** of the following: 2664 ** 2665 ** (1) SHARED_LOCK 2666 ** (2) RESERVED_LOCK 2667 ** (3) PENDING_LOCK 2668 ** (4) EXCLUSIVE_LOCK 2669 ** 2670 ** Sometimes when requesting one lock state, additional lock states 2671 ** are inserted in between. The locking might fail on one of the later 2672 ** transitions leaving the lock state different from what it started but 2673 ** still short of its goal. The following chart shows the allowed 2674 ** transitions and the inserted intermediate states: 2675 ** 2676 ** UNLOCKED -> SHARED 2677 ** SHARED -> RESERVED 2678 ** SHARED -> (PENDING) -> EXCLUSIVE 2679 ** RESERVED -> (PENDING) -> EXCLUSIVE 2680 ** PENDING -> EXCLUSIVE 2681 ** 2682 ** flock() only really support EXCLUSIVE locks. We track intermediate 2683 ** lock states in the sqlite3_file structure, but all locks SHARED or 2684 ** above are really EXCLUSIVE locks and exclude all other processes from 2685 ** access the file. 2686 ** 2687 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 2688 ** routine to lower a locking level. 2689 */ 2690 static int flockLock(sqlite3_file *id, int eFileLock) { 2691 int rc = SQLITE_OK; 2692 unixFile *pFile = (unixFile*)id; 2693 2694 assert( pFile ); 2695 2696 /* if we already have a lock, it is exclusive. 2697 ** Just adjust level and punt on outta here. */ 2698 if (pFile->eFileLock > NO_LOCK) { 2699 pFile->eFileLock = eFileLock; 2700 return SQLITE_OK; 2701 } 2702 2703 /* grab an exclusive lock */ 2704 2705 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) { 2706 int tErrno = errno; 2707 /* didn't get, must be busy */ 2708 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 2709 if( IS_LOCK_ERROR(rc) ){ 2710 storeLastErrno(pFile, tErrno); 2711 } 2712 } else { 2713 /* got it, set the type and return ok */ 2714 pFile->eFileLock = eFileLock; 2715 } 2716 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 2717 rc==SQLITE_OK ? "ok" : "failed")); 2718 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS 2719 if( (rc & 0xff) == SQLITE_IOERR ){ 2720 rc = SQLITE_BUSY; 2721 } 2722 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ 2723 return rc; 2724 } 2725 2726 2727 /* 2728 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock 2729 ** must be either NO_LOCK or SHARED_LOCK. 2730 ** 2731 ** If the locking level of the file descriptor is already at or below 2732 ** the requested locking level, this routine is a no-op. 2733 */ 2734 static int flockUnlock(sqlite3_file *id, int eFileLock) { 2735 unixFile *pFile = (unixFile*)id; 2736 2737 assert( pFile ); 2738 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock, 2739 pFile->eFileLock, osGetpid(0))); 2740 assert( eFileLock<=SHARED_LOCK ); 2741 2742 /* no-op if possible */ 2743 if( pFile->eFileLock==eFileLock ){ 2744 return SQLITE_OK; 2745 } 2746 2747 /* shared can just be set because we always have an exclusive */ 2748 if (eFileLock==SHARED_LOCK) { 2749 pFile->eFileLock = eFileLock; 2750 return SQLITE_OK; 2751 } 2752 2753 /* no, really, unlock. */ 2754 if( robust_flock(pFile->h, LOCK_UN) ){ 2755 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS 2756 return SQLITE_OK; 2757 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ 2758 return SQLITE_IOERR_UNLOCK; 2759 }else{ 2760 pFile->eFileLock = NO_LOCK; 2761 return SQLITE_OK; 2762 } 2763 } 2764 2765 /* 2766 ** Close a file. 2767 */ 2768 static int flockClose(sqlite3_file *id) { 2769 assert( id!=0 ); 2770 flockUnlock(id, NO_LOCK); 2771 return closeUnixFile(id); 2772 } 2773 2774 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */ 2775 2776 /******************* End of the flock lock implementation ********************* 2777 ******************************************************************************/ 2778 2779 /****************************************************************************** 2780 ************************ Begin Named Semaphore Locking ************************ 2781 ** 2782 ** Named semaphore locking is only supported on VxWorks. 2783 ** 2784 ** Semaphore locking is like dot-lock and flock in that it really only 2785 ** supports EXCLUSIVE locking. Only a single process can read or write 2786 ** the database file at a time. This reduces potential concurrency, but 2787 ** makes the lock implementation much easier. 2788 */ 2789 #if OS_VXWORKS 2790 2791 /* 2792 ** This routine checks if there is a RESERVED lock held on the specified 2793 ** file by this or any other process. If such a lock is held, set *pResOut 2794 ** to a non-zero value otherwise *pResOut is set to zero. The return value 2795 ** is set to SQLITE_OK unless an I/O error occurs during lock checking. 2796 */ 2797 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) { 2798 int rc = SQLITE_OK; 2799 int reserved = 0; 2800 unixFile *pFile = (unixFile*)id; 2801 2802 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 2803 2804 assert( pFile ); 2805 2806 /* Check if a thread in this process holds such a lock */ 2807 if( pFile->eFileLock>SHARED_LOCK ){ 2808 reserved = 1; 2809 } 2810 2811 /* Otherwise see if some other process holds it. */ 2812 if( !reserved ){ 2813 sem_t *pSem = pFile->pInode->pSem; 2814 2815 if( sem_trywait(pSem)==-1 ){ 2816 int tErrno = errno; 2817 if( EAGAIN != tErrno ){ 2818 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK); 2819 storeLastErrno(pFile, tErrno); 2820 } else { 2821 /* someone else has the lock when we are in NO_LOCK */ 2822 reserved = (pFile->eFileLock < SHARED_LOCK); 2823 } 2824 }else{ 2825 /* we could have it if we want it */ 2826 sem_post(pSem); 2827 } 2828 } 2829 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved)); 2830 2831 *pResOut = reserved; 2832 return rc; 2833 } 2834 2835 /* 2836 ** Lock the file with the lock specified by parameter eFileLock - one 2837 ** of the following: 2838 ** 2839 ** (1) SHARED_LOCK 2840 ** (2) RESERVED_LOCK 2841 ** (3) PENDING_LOCK 2842 ** (4) EXCLUSIVE_LOCK 2843 ** 2844 ** Sometimes when requesting one lock state, additional lock states 2845 ** are inserted in between. The locking might fail on one of the later 2846 ** transitions leaving the lock state different from what it started but 2847 ** still short of its goal. The following chart shows the allowed 2848 ** transitions and the inserted intermediate states: 2849 ** 2850 ** UNLOCKED -> SHARED 2851 ** SHARED -> RESERVED 2852 ** SHARED -> (PENDING) -> EXCLUSIVE 2853 ** RESERVED -> (PENDING) -> EXCLUSIVE 2854 ** PENDING -> EXCLUSIVE 2855 ** 2856 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate 2857 ** lock states in the sqlite3_file structure, but all locks SHARED or 2858 ** above are really EXCLUSIVE locks and exclude all other processes from 2859 ** access the file. 2860 ** 2861 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 2862 ** routine to lower a locking level. 2863 */ 2864 static int semXLock(sqlite3_file *id, int eFileLock) { 2865 unixFile *pFile = (unixFile*)id; 2866 sem_t *pSem = pFile->pInode->pSem; 2867 int rc = SQLITE_OK; 2868 2869 /* if we already have a lock, it is exclusive. 2870 ** Just adjust level and punt on outta here. */ 2871 if (pFile->eFileLock > NO_LOCK) { 2872 pFile->eFileLock = eFileLock; 2873 rc = SQLITE_OK; 2874 goto sem_end_lock; 2875 } 2876 2877 /* lock semaphore now but bail out when already locked. */ 2878 if( sem_trywait(pSem)==-1 ){ 2879 rc = SQLITE_BUSY; 2880 goto sem_end_lock; 2881 } 2882 2883 /* got it, set the type and return ok */ 2884 pFile->eFileLock = eFileLock; 2885 2886 sem_end_lock: 2887 return rc; 2888 } 2889 2890 /* 2891 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock 2892 ** must be either NO_LOCK or SHARED_LOCK. 2893 ** 2894 ** If the locking level of the file descriptor is already at or below 2895 ** the requested locking level, this routine is a no-op. 2896 */ 2897 static int semXUnlock(sqlite3_file *id, int eFileLock) { 2898 unixFile *pFile = (unixFile*)id; 2899 sem_t *pSem = pFile->pInode->pSem; 2900 2901 assert( pFile ); 2902 assert( pSem ); 2903 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock, 2904 pFile->eFileLock, osGetpid(0))); 2905 assert( eFileLock<=SHARED_LOCK ); 2906 2907 /* no-op if possible */ 2908 if( pFile->eFileLock==eFileLock ){ 2909 return SQLITE_OK; 2910 } 2911 2912 /* shared can just be set because we always have an exclusive */ 2913 if (eFileLock==SHARED_LOCK) { 2914 pFile->eFileLock = eFileLock; 2915 return SQLITE_OK; 2916 } 2917 2918 /* no, really unlock. */ 2919 if ( sem_post(pSem)==-1 ) { 2920 int rc, tErrno = errno; 2921 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 2922 if( IS_LOCK_ERROR(rc) ){ 2923 storeLastErrno(pFile, tErrno); 2924 } 2925 return rc; 2926 } 2927 pFile->eFileLock = NO_LOCK; 2928 return SQLITE_OK; 2929 } 2930 2931 /* 2932 ** Close a file. 2933 */ 2934 static int semXClose(sqlite3_file *id) { 2935 if( id ){ 2936 unixFile *pFile = (unixFile*)id; 2937 semXUnlock(id, NO_LOCK); 2938 assert( pFile ); 2939 assert( unixFileMutexNotheld(pFile) ); 2940 unixEnterMutex(); 2941 releaseInodeInfo(pFile); 2942 unixLeaveMutex(); 2943 closeUnixFile(id); 2944 } 2945 return SQLITE_OK; 2946 } 2947 2948 #endif /* OS_VXWORKS */ 2949 /* 2950 ** Named semaphore locking is only available on VxWorks. 2951 ** 2952 *************** End of the named semaphore lock implementation **************** 2953 ******************************************************************************/ 2954 2955 2956 /****************************************************************************** 2957 *************************** Begin AFP Locking ********************************* 2958 ** 2959 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found 2960 ** on Apple Macintosh computers - both OS9 and OSX. 2961 ** 2962 ** Third-party implementations of AFP are available. But this code here 2963 ** only works on OSX. 2964 */ 2965 2966 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 2967 /* 2968 ** The afpLockingContext structure contains all afp lock specific state 2969 */ 2970 typedef struct afpLockingContext afpLockingContext; 2971 struct afpLockingContext { 2972 int reserved; 2973 const char *dbPath; /* Name of the open file */ 2974 }; 2975 2976 struct ByteRangeLockPB2 2977 { 2978 unsigned long long offset; /* offset to first byte to lock */ 2979 unsigned long long length; /* nbr of bytes to lock */ 2980 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */ 2981 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */ 2982 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */ 2983 int fd; /* file desc to assoc this lock with */ 2984 }; 2985 2986 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2) 2987 2988 /* 2989 ** This is a utility for setting or clearing a bit-range lock on an 2990 ** AFP filesystem. 2991 ** 2992 ** Return SQLITE_OK on success, SQLITE_BUSY on failure. 2993 */ 2994 static int afpSetLock( 2995 const char *path, /* Name of the file to be locked or unlocked */ 2996 unixFile *pFile, /* Open file descriptor on path */ 2997 unsigned long long offset, /* First byte to be locked */ 2998 unsigned long long length, /* Number of bytes to lock */ 2999 int setLockFlag /* True to set lock. False to clear lock */ 3000 ){ 3001 struct ByteRangeLockPB2 pb; 3002 int err; 3003 3004 pb.unLockFlag = setLockFlag ? 0 : 1; 3005 pb.startEndFlag = 0; 3006 pb.offset = offset; 3007 pb.length = length; 3008 pb.fd = pFile->h; 3009 3010 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 3011 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""), 3012 offset, length)); 3013 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0); 3014 if ( err==-1 ) { 3015 int rc; 3016 int tErrno = errno; 3017 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n", 3018 path, tErrno, strerror(tErrno))); 3019 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS 3020 rc = SQLITE_BUSY; 3021 #else 3022 rc = sqliteErrorFromPosixError(tErrno, 3023 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK); 3024 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */ 3025 if( IS_LOCK_ERROR(rc) ){ 3026 storeLastErrno(pFile, tErrno); 3027 } 3028 return rc; 3029 } else { 3030 return SQLITE_OK; 3031 } 3032 } 3033 3034 /* 3035 ** This routine checks if there is a RESERVED lock held on the specified 3036 ** file by this or any other process. If such a lock is held, set *pResOut 3037 ** to a non-zero value otherwise *pResOut is set to zero. The return value 3038 ** is set to SQLITE_OK unless an I/O error occurs during lock checking. 3039 */ 3040 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){ 3041 int rc = SQLITE_OK; 3042 int reserved = 0; 3043 unixFile *pFile = (unixFile*)id; 3044 afpLockingContext *context; 3045 3046 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 3047 3048 assert( pFile ); 3049 context = (afpLockingContext *) pFile->lockingContext; 3050 if( context->reserved ){ 3051 *pResOut = 1; 3052 return SQLITE_OK; 3053 } 3054 sqlite3_mutex_enter(pFile->pInode->pLockMutex); 3055 /* Check if a thread in this process holds such a lock */ 3056 if( pFile->pInode->eFileLock>SHARED_LOCK ){ 3057 reserved = 1; 3058 } 3059 3060 /* Otherwise see if some other process holds it. 3061 */ 3062 if( !reserved ){ 3063 /* lock the RESERVED byte */ 3064 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); 3065 if( SQLITE_OK==lrc ){ 3066 /* if we succeeded in taking the reserved lock, unlock it to restore 3067 ** the original state */ 3068 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0); 3069 } else { 3070 /* if we failed to get the lock then someone else must have it */ 3071 reserved = 1; 3072 } 3073 if( IS_LOCK_ERROR(lrc) ){ 3074 rc=lrc; 3075 } 3076 } 3077 3078 sqlite3_mutex_leave(pFile->pInode->pLockMutex); 3079 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved)); 3080 3081 *pResOut = reserved; 3082 return rc; 3083 } 3084 3085 /* 3086 ** Lock the file with the lock specified by parameter eFileLock - one 3087 ** of the following: 3088 ** 3089 ** (1) SHARED_LOCK 3090 ** (2) RESERVED_LOCK 3091 ** (3) PENDING_LOCK 3092 ** (4) EXCLUSIVE_LOCK 3093 ** 3094 ** Sometimes when requesting one lock state, additional lock states 3095 ** are inserted in between. The locking might fail on one of the later 3096 ** transitions leaving the lock state different from what it started but 3097 ** still short of its goal. The following chart shows the allowed 3098 ** transitions and the inserted intermediate states: 3099 ** 3100 ** UNLOCKED -> SHARED 3101 ** SHARED -> RESERVED 3102 ** SHARED -> (PENDING) -> EXCLUSIVE 3103 ** RESERVED -> (PENDING) -> EXCLUSIVE 3104 ** PENDING -> EXCLUSIVE 3105 ** 3106 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 3107 ** routine to lower a locking level. 3108 */ 3109 static int afpLock(sqlite3_file *id, int eFileLock){ 3110 int rc = SQLITE_OK; 3111 unixFile *pFile = (unixFile*)id; 3112 unixInodeInfo *pInode = pFile->pInode; 3113 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; 3114 3115 assert( pFile ); 3116 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h, 3117 azFileLock(eFileLock), azFileLock(pFile->eFileLock), 3118 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0))); 3119 3120 /* If there is already a lock of this type or more restrictive on the 3121 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as 3122 ** unixEnterMutex() hasn't been called yet. 3123 */ 3124 if( pFile->eFileLock>=eFileLock ){ 3125 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h, 3126 azFileLock(eFileLock))); 3127 return SQLITE_OK; 3128 } 3129 3130 /* Make sure the locking sequence is correct 3131 ** (1) We never move from unlocked to anything higher than shared lock. 3132 ** (2) SQLite never explicitly requests a pending lock. 3133 ** (3) A shared lock is always held when a reserve lock is requested. 3134 */ 3135 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK ); 3136 assert( eFileLock!=PENDING_LOCK ); 3137 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK ); 3138 3139 /* This mutex is needed because pFile->pInode is shared across threads 3140 */ 3141 pInode = pFile->pInode; 3142 sqlite3_mutex_enter(pInode->pLockMutex); 3143 3144 /* If some thread using this PID has a lock via a different unixFile* 3145 ** handle that precludes the requested lock, return BUSY. 3146 */ 3147 if( (pFile->eFileLock!=pInode->eFileLock && 3148 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK)) 3149 ){ 3150 rc = SQLITE_BUSY; 3151 goto afp_end_lock; 3152 } 3153 3154 /* If a SHARED lock is requested, and some thread using this PID already 3155 ** has a SHARED or RESERVED lock, then increment reference counts and 3156 ** return SQLITE_OK. 3157 */ 3158 if( eFileLock==SHARED_LOCK && 3159 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){ 3160 assert( eFileLock==SHARED_LOCK ); 3161 assert( pFile->eFileLock==0 ); 3162 assert( pInode->nShared>0 ); 3163 pFile->eFileLock = SHARED_LOCK; 3164 pInode->nShared++; 3165 pInode->nLock++; 3166 goto afp_end_lock; 3167 } 3168 3169 /* A PENDING lock is needed before acquiring a SHARED lock and before 3170 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will 3171 ** be released. 3172 */ 3173 if( eFileLock==SHARED_LOCK 3174 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLockdbPath, pFile, PENDING_BYTE, 1, 1); 3178 if (failed) { 3179 rc = failed; 3180 goto afp_end_lock; 3181 } 3182 } 3183 3184 /* If control gets to this point, then actually go ahead and make 3185 ** operating system calls for the specified lock. 3186 */ 3187 if( eFileLock==SHARED_LOCK ){ 3188 int lrc1, lrc2, lrc1Errno = 0; 3189 long lk, mask; 3190 3191 assert( pInode->nShared==0 ); 3192 assert( pInode->eFileLock==0 ); 3193 3194 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff; 3195 /* Now get the read-lock SHARED_LOCK */ 3196 /* note that the quality of the randomness doesn't matter that much */ 3197 lk = random(); 3198 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1); 3199 lrc1 = afpSetLock(context->dbPath, pFile, 3200 SHARED_FIRST+pInode->sharedByte, 1, 1); 3201 if( IS_LOCK_ERROR(lrc1) ){ 3202 lrc1Errno = pFile->lastErrno; 3203 } 3204 /* Drop the temporary PENDING lock */ 3205 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); 3206 3207 if( IS_LOCK_ERROR(lrc1) ) { 3208 storeLastErrno(pFile, lrc1Errno); 3209 rc = lrc1; 3210 goto afp_end_lock; 3211 } else if( IS_LOCK_ERROR(lrc2) ){ 3212 rc = lrc2; 3213 goto afp_end_lock; 3214 } else if( lrc1 != SQLITE_OK ) { 3215 rc = lrc1; 3216 } else { 3217 pFile->eFileLock = SHARED_LOCK; 3218 pInode->nLock++; 3219 pInode->nShared = 1; 3220 } 3221 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){ 3222 /* We are trying for an exclusive lock but another thread in this 3223 ** same process is still holding a shared lock. */ 3224 rc = SQLITE_BUSY; 3225 }else{ 3226 /* The request was for a RESERVED or EXCLUSIVE lock. It is 3227 ** assumed that there is a SHARED or greater lock on the file 3228 ** already. 3229 */ 3230 int failed = 0; 3231 assert( 0!=pFile->eFileLock ); 3232 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) { 3233 /* Acquire a RESERVED lock */ 3234 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); 3235 if( !failed ){ 3236 context->reserved = 1; 3237 } 3238 } 3239 if (!failed && eFileLock == EXCLUSIVE_LOCK) { 3240 /* Acquire an EXCLUSIVE lock */ 3241 3242 /* Remove the shared lock before trying the range. we'll need to 3243 ** reestablish the shared lock if we can't get the afpUnlock 3244 */ 3245 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST + 3246 pInode->sharedByte, 1, 0)) ){ 3247 int failed2 = SQLITE_OK; 3248 /* now attempt to get the exclusive lock range */ 3249 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 3250 SHARED_SIZE, 1); 3251 if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 3252 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){ 3253 /* Can't reestablish the shared lock. Sqlite can't deal, this is 3254 ** a critical I/O error 3255 */ 3256 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 : 3257 SQLITE_IOERR_LOCK; 3258 goto afp_end_lock; 3259 } 3260 }else{ 3261 rc = failed; 3262 } 3263 } 3264 if( failed ){ 3265 rc = failed; 3266 } 3267 } 3268 3269 if( rc==SQLITE_OK ){ 3270 pFile->eFileLock = eFileLock; 3271 pInode->eFileLock = eFileLock; 3272 }else if( eFileLock==EXCLUSIVE_LOCK ){ 3273 pFile->eFileLock = PENDING_LOCK; 3274 pInode->eFileLock = PENDING_LOCK; 3275 } 3276 3277 afp_end_lock: 3278 sqlite3_mutex_leave(pInode->pLockMutex); 3279 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 3280 rc==SQLITE_OK ? "ok" : "failed")); 3281 return rc; 3282 } 3283 3284 /* 3285 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock 3286 ** must be either NO_LOCK or SHARED_LOCK. 3287 ** 3288 ** If the locking level of the file descriptor is already at or below 3289 ** the requested locking level, this routine is a no-op. 3290 */ 3291 static int afpUnlock(sqlite3_file *id, int eFileLock) { 3292 int rc = SQLITE_OK; 3293 unixFile *pFile = (unixFile*)id; 3294 unixInodeInfo *pInode; 3295 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; 3296 int skipShared = 0; 3297 3298 assert( pFile ); 3299 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock, 3300 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared, 3301 osGetpid(0))); 3302 3303 assert( eFileLock<=SHARED_LOCK ); 3304 if( pFile->eFileLock<=eFileLock ){ 3305 return SQLITE_OK; 3306 } 3307 pInode = pFile->pInode; 3308 sqlite3_mutex_enter(pInode->pLockMutex); 3309 assert( pInode->nShared!=0 ); 3310 if( pFile->eFileLock>SHARED_LOCK ){ 3311 assert( pInode->eFileLock==pFile->eFileLock ); 3312 3313 #ifdef SQLITE_DEBUG 3314 /* When reducing a lock such that other processes can start 3315 ** reading the database file again, make sure that the 3316 ** transaction counter was updated if any part of the database 3317 ** file changed. If the transaction counter is not updated, 3318 ** other connections to the same file might not realize that 3319 ** the file has changed and hence might not know to flush their 3320 ** cache. The use of a stale cache can lead to database corruption. 3321 */ 3322 assert( pFile->inNormalWrite==0 3323 || pFile->dbUpdate==0 3324 || pFile->transCntrChng==1 ); 3325 pFile->inNormalWrite = 0; 3326 #endif 3327 3328 if( pFile->eFileLock==EXCLUSIVE_LOCK ){ 3329 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0); 3330 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){ 3331 /* only re-establish the shared lock if necessary */ 3332 int sharedLockByte = SHARED_FIRST+pInode->sharedByte; 3333 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1); 3334 } else { 3335 skipShared = 1; 3336 } 3337 } 3338 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){ 3339 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); 3340 } 3341 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){ 3342 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0); 3343 if( !rc ){ 3344 context->reserved = 0; 3345 } 3346 } 3347 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){ 3348 pInode->eFileLock = SHARED_LOCK; 3349 } 3350 } 3351 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){ 3352 3353 /* Decrement the shared lock counter. Release the lock using an 3354 ** OS call only when all threads in this same process have released 3355 ** the lock. 3356 */ 3357 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte; 3358 pInode->nShared--; 3359 if( pInode->nShared==0 ){ 3360 if( !skipShared ){ 3361 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0); 3362 } 3363 if( !rc ){ 3364 pInode->eFileLock = NO_LOCK; 3365 pFile->eFileLock = NO_LOCK; 3366 } 3367 } 3368 if( rc==SQLITE_OK ){ 3369 pInode->nLock--; 3370 assert( pInode->nLock>=0 ); 3371 if( pInode->nLock==0 ) closePendingFds(pFile); 3372 } 3373 } 3374 3375 sqlite3_mutex_leave(pInode->pLockMutex); 3376 if( rc==SQLITE_OK ){ 3377 pFile->eFileLock = eFileLock; 3378 } 3379 return rc; 3380 } 3381 3382 /* 3383 ** Close a file & cleanup AFP specific locking context 3384 */ 3385 static int afpClose(sqlite3_file *id) { 3386 int rc = SQLITE_OK; 3387 unixFile *pFile = (unixFile*)id; 3388 assert( id!=0 ); 3389 afpUnlock(id, NO_LOCK); 3390 assert( unixFileMutexNotheld(pFile) ); 3391 unixEnterMutex(); 3392 if( pFile->pInode ){ 3393 unixInodeInfo *pInode = pFile->pInode; 3394 sqlite3_mutex_enter(pInode->pLockMutex); 3395 if( pInode->nLock ){ 3396 /* If there are outstanding locks, do not actually close the file just 3397 ** yet because that would clear those locks. Instead, add the file 3398 ** descriptor to pInode->aPending. It will be automatically closed when 3399 ** the last lock is cleared. 3400 */ 3401 setPendingFd(pFile); 3402 } 3403 sqlite3_mutex_leave(pInode->pLockMutex); 3404 } 3405 releaseInodeInfo(pFile); 3406 sqlite3_free(pFile->lockingContext); 3407 rc = closeUnixFile(id); 3408 unixLeaveMutex(); 3409 return rc; 3410 } 3411 3412 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ 3413 /* 3414 ** The code above is the AFP lock implementation. The code is specific 3415 ** to MacOSX and does not work on other unix platforms. No alternative 3416 ** is available. If you don't compile for a mac, then the "unix-afp" 3417 ** VFS is not available. 3418 ** 3419 ********************* End of the AFP lock implementation ********************** 3420 ******************************************************************************/ 3421 3422 /****************************************************************************** 3423 *************************** Begin NFS Locking ********************************/ 3424 3425 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 3426 /* 3427 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock 3428 ** must be either NO_LOCK or SHARED_LOCK. 3429 ** 3430 ** If the locking level of the file descriptor is already at or below 3431 ** the requested locking level, this routine is a no-op. 3432 */ 3433 static int nfsUnlock(sqlite3_file *id, int eFileLock){ 3434 return posixUnlock(id, eFileLock, 1); 3435 } 3436 3437 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ 3438 /* 3439 ** The code above is the NFS lock implementation. The code is specific 3440 ** to MacOSX and does not work on other unix platforms. No alternative 3441 ** is available. 3442 ** 3443 ********************* End of the NFS lock implementation ********************** 3444 ******************************************************************************/ 3445 3446 /****************************************************************************** 3447 **************** Non-locking sqlite3_file methods ***************************** 3448 ** 3449 ** The next division contains implementations for all methods of the 3450 ** sqlite3_file object other than the locking methods. The locking 3451 ** methods were defined in divisions above (one locking method per 3452 ** division). Those methods that are common to all locking modes 3453 ** are gather together into this division. 3454 */ 3455 3456 /* 3457 ** Seek to the offset passed as the second argument, then read cnt 3458 ** bytes into pBuf. Return the number of bytes actually read. 3459 ** 3460 ** To avoid stomping the errno value on a failed read the lastErrno value 3461 ** is set before returning. 3462 */ 3463 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ 3464 int got; 3465 int prior = 0; 3466 #if (!defined(USE_PREAD) && !defined(USE_PREAD64)) 3467 i64 newOffset; 3468 #endif 3469 TIMER_START; 3470 assert( cnt==(cnt&0x1ffff) ); 3471 assert( id->h>2 ); 3472 do{ 3473 #if defined(USE_PREAD) 3474 got = osPread(id->h, pBuf, cnt, offset); 3475 SimulateIOError( got = -1 ); 3476 #elif defined(USE_PREAD64) 3477 got = osPread64(id->h, pBuf, cnt, offset); 3478 SimulateIOError( got = -1 ); 3479 #else 3480 newOffset = lseek(id->h, offset, SEEK_SET); 3481 SimulateIOError( newOffset = -1 ); 3482 if( newOffset<0 ){ 3483 storeLastErrno((unixFile*)id, errno); 3484 return -1; 3485 } 3486 got = osRead(id->h, pBuf, cnt); 3487 #endif 3488 if( got==cnt ) break; 3489 if( got<0 ){ 3490 if( errno==EINTR ){ got = 1; continue; } 3491 prior = 0; 3492 storeLastErrno((unixFile*)id, errno); 3493 break; 3494 }else if( got>0 ){ 3495 cnt -= got; 3496 offset += got; 3497 prior += got; 3498 pBuf = (void*)(got + (char*)pBuf); 3499 } 3500 }while( got>0 ); 3501 TIMER_END; 3502 OSTRACE(("READ %-3d %5d %7lld %llu\n", 3503 id->h, got+prior, offset-prior, TIMER_ELAPSED)); 3504 return got+prior; 3505 } 3506 3507 /* 3508 ** Read data from a file into a buffer. Return SQLITE_OK if all 3509 ** bytes were read successfully and SQLITE_IOERR if anything goes 3510 ** wrong. 3511 */ 3512 static int unixRead( 3513 sqlite3_file *id, 3514 void *pBuf, 3515 int amt, 3516 sqlite3_int64 offset 3517 ){ 3518 unixFile *pFile = (unixFile *)id; 3519 int got; 3520 assert( id ); 3521 assert( offset>=0 ); 3522 assert( amt>0 ); 3523 3524 /* If this is a database file (not a journal, super-journal or temp 3525 ** file), the bytes in the locking range should never be read or written. */ 3526 #if 0 3527 assert( pFile->pPreallocatedUnused==0 3528 || offset>=PENDING_BYTE+512 3529 || offset+amt<=PENDING_BYTE 3530 ); 3531 #endif 3532 3533 #if SQLITE_MAX_MMAP_SIZE>0 3534 /* Deal with as much of this read request as possible by transferring 3535 ** data from the memory mapping using memcpy(). */ 3536 if( offsetmmapSize ){ 3537 if( offset+amt <= pFile->mmapSize ){ 3538 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); 3539 return SQLITE_OK; 3540 }else{ 3541 int nCopy = pFile->mmapSize - offset; 3542 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); 3543 pBuf = &((u8 *)pBuf)[nCopy]; 3544 amt -= nCopy; 3545 offset += nCopy; 3546 } 3547 } 3548 #endif 3549 3550 got = seekAndRead(pFile, offset, pBuf, amt); 3551 if( got==amt ){ 3552 return SQLITE_OK; 3553 }else if( got<0 ){ 3554 /* pFile->lastErrno has been set by seekAndRead(). 3555 ** Usually we return SQLITE_IOERR_READ here, though for some 3556 ** kinds of errors we return SQLITE_IOERR_CORRUPTFS. The 3557 ** SQLITE_IOERR_CORRUPTFS will be converted into SQLITE_CORRUPT 3558 ** prior to returning to the application by the sqlite3ApiExit() 3559 ** routine. 3560 */ 3561 switch( pFile->lastErrno ){ 3562 case ERANGE: 3563 case EIO: 3564 #ifdef ENXIO 3565 case ENXIO: 3566 #endif 3567 #ifdef EDEVERR 3568 case EDEVERR: 3569 #endif 3570 return SQLITE_IOERR_CORRUPTFS; 3571 } 3572 return SQLITE_IOERR_READ; 3573 }else{ 3574 storeLastErrno(pFile, 0); /* not a system error */ 3575 /* Unread parts of the buffer must be zero-filled */ 3576 memset(&((char*)pBuf)[got], 0, amt-got); 3577 return SQLITE_IOERR_SHORT_READ; 3578 } 3579 } 3580 3581 /* 3582 ** Attempt to seek the file-descriptor passed as the first argument to 3583 ** absolute offset iOff, then attempt to write nBuf bytes of data from 3584 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, 3585 ** return the actual number of bytes written (which may be less than 3586 ** nBuf). 3587 */ 3588 static int seekAndWriteFd( 3589 int fd, /* File descriptor to write to */ 3590 i64 iOff, /* File offset to begin writing at */ 3591 const void *pBuf, /* Copy data from this buffer to the file */ 3592 int nBuf, /* Size of buffer pBuf in bytes */ 3593 int *piErrno /* OUT: Error number if error occurs */ 3594 ){ 3595 int rc = 0; /* Value returned by system call */ 3596 3597 assert( nBuf==(nBuf&0x1ffff) ); 3598 assert( fd>2 ); 3599 assert( piErrno!=0 ); 3600 nBuf &= 0x1ffff; 3601 TIMER_START; 3602 3603 #if defined(USE_PREAD) 3604 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR ); 3605 #elif defined(USE_PREAD64) 3606 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR); 3607 #else 3608 do{ 3609 i64 iSeek = lseek(fd, iOff, SEEK_SET); 3610 SimulateIOError( iSeek = -1 ); 3611 if( iSeek<0 ){ 3612 rc = -1; 3613 break; 3614 } 3615 rc = osWrite(fd, pBuf, nBuf); 3616 }while( rc<0 && errno==EINTR ); 3617 #endif 3618 3619 TIMER_END; 3620 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED)); 3621 3622 if( rc<0 ) *piErrno = errno; 3623 return rc; 3624 } 3625 3626 3627 /* 3628 ** Seek to the offset in id->offset then read cnt bytes into pBuf. 3629 ** Return the number of bytes actually read. Update the offset. 3630 ** 3631 ** To avoid stomping the errno value on a failed write the lastErrno value 3632 ** is set before returning. 3633 */ 3634 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){ 3635 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno); 3636 } 3637 3638 3639 /* 3640 ** Write data from a buffer into a file. Return SQLITE_OK on success 3641 ** or some other error code on failure. 3642 */ 3643 static int unixWrite( 3644 sqlite3_file *id, 3645 const void *pBuf, 3646 int amt, 3647 sqlite3_int64 offset 3648 ){ 3649 unixFile *pFile = (unixFile*)id; 3650 int wrote = 0; 3651 assert( id ); 3652 assert( amt>0 ); 3653 3654 /* If this is a database file (not a journal, super-journal or temp 3655 ** file), the bytes in the locking range should never be read or written. */ 3656 #if 0 3657 assert( pFile->pPreallocatedUnused==0 3658 || offset>=PENDING_BYTE+512 3659 || offset+amt<=PENDING_BYTE 3660 ); 3661 #endif 3662 3663 #ifdef SQLITE_DEBUG 3664 /* If we are doing a normal write to a database file (as opposed to 3665 ** doing a hot-journal rollback or a write to some file other than a 3666 ** normal database file) then record the fact that the database 3667 ** has changed. If the transaction counter is modified, record that 3668 ** fact too. 3669 */ 3670 if( pFile->inNormalWrite ){ 3671 pFile->dbUpdate = 1; /* The database has been modified */ 3672 if( offset<=24 && offset+amt>=27 ){ 3673 int rc; 3674 char oldCntr[4]; 3675 SimulateIOErrorBenign(1); 3676 rc = seekAndRead(pFile, 24, oldCntr, 4); 3677 SimulateIOErrorBenign(0); 3678 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){ 3679 pFile->transCntrChng = 1; /* The transaction counter has changed */ 3680 } 3681 } 3682 } 3683 #endif 3684 3685 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0 3686 /* Deal with as much of this write request as possible by transferring 3687 ** data from the memory mapping using memcpy(). */ 3688 if( offsetmmapSize ){ 3689 if( offset+amt <= pFile->mmapSize ){ 3690 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); 3691 return SQLITE_OK; 3692 }else{ 3693 int nCopy = pFile->mmapSize - offset; 3694 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); 3695 pBuf = &((u8 *)pBuf)[nCopy]; 3696 amt -= nCopy; 3697 offset += nCopy; 3698 } 3699 } 3700 #endif 3701 3702 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))0 ){ 3703 amt -= wrote; 3704 offset += wrote; 3705 pBuf = &((char*)pBuf)[wrote]; 3706 } 3707 SimulateIOError(( wrote=(-1), amt=1 )); 3708 SimulateDiskfullError(( wrote=0, amt=1 )); 3709 3710 if( amt>wrote ){ 3711 if( wrote<0 && pFile->lastErrno!=ENOSPC ){ 3712 /* lastErrno set by seekAndWrite */ 3713 return SQLITE_IOERR_WRITE; 3714 }else{ 3715 storeLastErrno(pFile, 0); /* not a system error */ 3716 return SQLITE_FULL; 3717 } 3718 } 3719 3720 return SQLITE_OK; 3721 } 3722 3723 #ifdef SQLITE_TEST 3724 /* 3725 ** Count the number of fullsyncs and normal syncs. This is used to test 3726 ** that syncs and fullsyncs are occurring at the right times. 3727 */ 3728 int sqlite3_sync_count = 0; 3729 int sqlite3_fullsync_count = 0; 3730 #endif 3731 3732 /* 3733 ** We do not trust systems to provide a working fdatasync(). Some do. 3734 ** Others do no. To be safe, we will stick with the (slightly slower) 3735 ** fsync(). If you know that your system does support fdatasync() correctly, 3736 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC 3737 */ 3738 #if !defined(fdatasync) && !HAVE_FDATASYNC 3739 # define fdatasync fsync 3740 #endif 3741 3742 /* 3743 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not 3744 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently 3745 ** only available on Mac OS X. But that could change. 3746 */ 3747 #ifdef F_FULLFSYNC 3748 # define HAVE_FULLFSYNC 1 3749 #else 3750 # define HAVE_FULLFSYNC 0 3751 #endif 3752 3753 3754 /* 3755 ** The fsync() system call does not work as advertised on many 3756 ** unix systems. The following procedure is an attempt to make 3757 ** it work better. 3758 ** 3759 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful 3760 ** for testing when we want to run through the test suite quickly. 3761 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC 3762 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash 3763 ** or power failure will likely corrupt the database file. 3764 ** 3765 ** SQLite sets the dataOnly flag if the size of the file is unchanged. 3766 ** The idea behind dataOnly is that it should only write the file content 3767 ** to disk, not the inode. We only set dataOnly if the file size is 3768 ** unchanged since the file size is part of the inode. However, 3769 ** Ted Ts'o tells us that fdatasync() will also write the inode if the 3770 ** file size has changed. The only real difference between fdatasync() 3771 ** and fsync(), Ted tells us, is that fdatasync() will not flush the 3772 ** inode if the mtime or owner or other inode attributes have changed. 3773 ** We only care about the file size, not the other file attributes, so 3774 ** as far as SQLite is concerned, an fdatasync() is always adequate. 3775 ** So, we always use fdatasync() if it is available, regardless of 3776 ** the value of the dataOnly flag. 3777 */ 3778 static int full_fsync(int fd, int fullSync, int dataOnly){ 3779 int rc; 3780 3781 /* The following "ifdef/elif/else/" block has the same structure as 3782 ** the one below. It is replicated here solely to avoid cluttering 3783 ** up the real code with the UNUSED_PARAMETER() macros. 3784 */ 3785 #ifdef SQLITE_NO_SYNC 3786 UNUSED_PARAMETER(fd); 3787 UNUSED_PARAMETER(fullSync); 3788 UNUSED_PARAMETER(dataOnly); 3789 #elif HAVE_FULLFSYNC 3790 UNUSED_PARAMETER(dataOnly); 3791 #else 3792 UNUSED_PARAMETER(fullSync); 3793 UNUSED_PARAMETER(dataOnly); 3794 #endif 3795 3796 /* Record the number of times that we do a normal fsync() and 3797 ** FULLSYNC. This is used during testing to verify that this procedure 3798 ** gets called with the correct arguments. 3799 */ 3800 #ifdef SQLITE_TEST 3801 if( fullSync ) sqlite3_fullsync_count++; 3802 sqlite3_sync_count++; 3803 #endif 3804 3805 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a 3806 ** no-op. But go ahead and call fstat() to validate the file 3807 ** descriptor as we need a method to provoke a failure during 3808 ** coverage testing. 3809 */ 3810 #ifdef SQLITE_NO_SYNC 3811 { 3812 struct stat buf; 3813 rc = osFstat(fd, &buf); 3814 } 3815 #elif HAVE_FULLFSYNC 3816 if( fullSync ){ 3817 rc = osFcntl(fd, F_FULLFSYNC, 0); 3818 }else{ 3819 rc = 1; 3820 } 3821 /* If the FULLFSYNC failed, fall back to attempting an fsync(). 3822 ** It shouldn't be possible for fullfsync to fail on the local 3823 ** file system (on OSX), so failure indicates that FULLFSYNC 3824 ** isn't supported for this file system. So, attempt an fsync 3825 ** and (for now) ignore the overhead of a superfluous fcntl call. 3826 ** It'd be better to detect fullfsync support once and avoid 3827 ** the fcntl call every time sync is called. 3828 */ 3829 if( rc ) rc = fsync(fd); 3830 3831 #elif defined(__APPLE__) 3832 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly 3833 ** so currently we default to the macro that redefines fdatasync to fsync 3834 */ 3835 rc = fsync(fd); 3836 #else 3837 rc = fdatasync(fd); 3838 #if OS_VXWORKS 3839 if( rc==-1 && errno==ENOTSUP ){ 3840 rc = fsync(fd); 3841 } 3842 #endif /* OS_VXWORKS */ 3843 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */ 3844 3845 if( OS_VXWORKS && rc!= -1 ){ 3846 rc = 0; 3847 } 3848 return rc; 3849 } 3850 3851 /* 3852 ** Open a file descriptor to the directory containing file zFilename. 3853 ** If successful, *pFd is set to the opened file descriptor and 3854 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM 3855 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined 3856 ** value. 3857 ** 3858 ** The directory file descriptor is used for only one thing - to 3859 ** fsync() a directory to make sure file creation and deletion events 3860 ** are flushed to disk. Such fsyncs are not needed on newer 3861 ** journaling filesystems, but are required on older filesystems. 3862 ** 3863 ** This routine can be overridden using the xSetSysCall interface. 3864 ** The ability to override this routine was added in support of the 3865 ** chromium sandbox. Opening a directory is a security risk (we are 3866 ** told) so making it overrideable allows the chromium sandbox to 3867 ** replace this routine with a harmless no-op. To make this routine 3868 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves 3869 ** *pFd set to a negative number. 3870 ** 3871 ** If SQLITE_OK is returned, the caller is responsible for closing 3872 ** the file descriptor *pFd using close(). 3873 */ 3874 static int openDirectory(const char *zFilename, int *pFd){ 3875 int ii; 3876 int fd = -1; 3877 char zDirname[MAX_PATHNAME+1]; 3878 3879 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename); 3880 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--); 3881 if( ii>0 ){ 3882 zDirname[ii] = '\0'; 3883 }else{ 3884 if( zDirname[0]!='/' ) zDirname[0] = '.'; 3885 zDirname[1] = 0; 3886 } 3887 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0); 3888 if( fd>=0 ){ 3889 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname)); 3890 } 3891 *pFd = fd; 3892 if( fd>=0 ) return SQLITE_OK; 3893 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname); 3894 } 3895 3896 /* 3897 ** Make sure all writes to a particular file are committed to disk. 3898 ** 3899 ** If dataOnly==0 then both the file itself and its metadata (file 3900 ** size, access time, etc) are synced. If dataOnly!=0 then only the 3901 ** file data is synced. 3902 ** 3903 ** Under Unix, also make sure that the directory entry for the file 3904 ** has been created by fsync-ing the directory that contains the file. 3905 ** If we do not do this and we encounter a power failure, the directory 3906 ** entry for the journal might not exist after we reboot. The next 3907 ** SQLite to access the file will not know that the journal exists (because 3908 ** the directory entry for the journal was never created) and the transaction 3909 ** will not roll back - possibly leading to database corruption. 3910 */ 3911 static int unixSync(sqlite3_file *id, int flags){ 3912 int rc; 3913 unixFile *pFile = (unixFile*)id; 3914 3915 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY); 3916 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL; 3917 3918 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ 3919 assert((flags&0x0F)==SQLITE_SYNC_NORMAL 3920 || (flags&0x0F)==SQLITE_SYNC_FULL 3921 ); 3922 3923 /* Unix cannot, but some systems may return SQLITE_FULL from here. This 3924 ** line is to test that doing so does not cause any problems. 3925 */ 3926 SimulateDiskfullError( return SQLITE_FULL ); 3927 3928 assert( pFile ); 3929 OSTRACE(("SYNC %-3d\n", pFile->h)); 3930 rc = full_fsync(pFile->h, isFullsync, isDataOnly); 3931 SimulateIOError( rc=1 ); 3932 if( rc ){ 3933 storeLastErrno(pFile, errno); 3934 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath); 3935 } 3936 3937 /* Also fsync the directory containing the file if the DIRSYNC flag 3938 ** is set. This is a one-time occurrence. Many systems (examples: AIX) 3939 ** are unable to fsync a directory, so ignore errors on the fsync. 3940 */ 3941 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){ 3942 int dirfd; 3943 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath, 3944 HAVE_FULLFSYNC, isFullsync)); 3945 rc = osOpenDirectory(pFile->zPath, &dirfd); 3946 if( rc==SQLITE_OK ){ 3947 full_fsync(dirfd, 0, 0); 3948 robust_close(pFile, dirfd, __LINE__); 3949 }else{ 3950 assert( rc==SQLITE_CANTOPEN ); 3951 rc = SQLITE_OK; 3952 } 3953 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC; 3954 } 3955 return rc; 3956 } 3957 3958 /* 3959 ** Truncate an open file to a specified size 3960 */ 3961 static int unixTruncate(sqlite3_file *id, i64 nByte){ 3962 unixFile *pFile = (unixFile *)id; 3963 int rc; 3964 assert( pFile ); 3965 SimulateIOError( return SQLITE_IOERR_TRUNCATE ); 3966 3967 /* If the user has configured a chunk-size for this file, truncate the 3968 ** file so that it consists of an integer number of chunks (i.e. the 3969 ** actual file size after the operation may be larger than the requested 3970 ** size). 3971 */ 3972 if( pFile->szChunk>0 ){ 3973 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; 3974 } 3975 3976 rc = robust_ftruncate(pFile->h, nByte); 3977 if( rc ){ 3978 storeLastErrno(pFile, errno); 3979 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); 3980 }else{ 3981 #ifdef SQLITE_DEBUG 3982 /* If we are doing a normal write to a database file (as opposed to 3983 ** doing a hot-journal rollback or a write to some file other than a 3984 ** normal database file) and we truncate the file to zero length, 3985 ** that effectively updates the change counter. This might happen 3986 ** when restoring a database using the backup API from a zero-length 3987 ** source. 3988 */ 3989 if( pFile->inNormalWrite && nByte==0 ){ 3990 pFile->transCntrChng = 1; 3991 } 3992 #endif 3993 3994 #if SQLITE_MAX_MMAP_SIZE>0 3995 /* If the file was just truncated to a size smaller than the currently 3996 ** mapped region, reduce the effective mapping size as well. SQLite will 3997 ** use read() and write() to access data beyond this point from now on. 3998 */ 3999 if( nBytemmapSize ){ 4000 pFile->mmapSize = nByte; 4001 } 4002 #endif 4003 4004 return SQLITE_OK; 4005 } 4006 } 4007 4008 /* 4009 ** Determine the current size of a file in bytes 4010 */ 4011 static int unixFileSize(sqlite3_file *id, i64 *pSize){ 4012 int rc; 4013 struct stat buf; 4014 assert( id ); 4015 rc = osFstat(((unixFile*)id)->h, &buf); 4016 SimulateIOError( rc=1 ); 4017 if( rc!=0 ){ 4018 storeLastErrno((unixFile*)id, errno); 4019 return SQLITE_IOERR_FSTAT; 4020 } 4021 *pSize = buf.st_size; 4022 4023 /* When opening a zero-size database, the findInodeInfo() procedure 4024 ** writes a single byte into that file in order to work around a bug 4025 ** in the OS-X msdos filesystem. In order to avoid problems with upper 4026 ** layers, we need to report this file size as zero even though it is 4027 ** really 1. Ticket #3260. 4028 */ 4029 if( *pSize==1 ) *pSize = 0; 4030 4031 4032 return SQLITE_OK; 4033 } 4034 4035 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) 4036 /* 4037 ** Handler for proxy-locking file-control verbs. Defined below in the 4038 ** proxying locking division. 4039 */ 4040 static int proxyFileControl(sqlite3_file*,int,void*); 4041 #endif 4042 4043 /* 4044 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 4045 ** file-control operation. Enlarge the database to nBytes in size 4046 ** (rounded up to the next chunk-size). If the database is already 4047 ** nBytes or larger, this routine is a no-op. 4048 */ 4049 static int fcntlSizeHint(unixFile *pFile, i64 nByte){ 4050 if( pFile->szChunk>0 ){ 4051 i64 nSize; /* Required file size */ 4052 struct stat buf; /* Used to hold return values of fstat() */ 4053 4054 if( osFstat(pFile->h, &buf) ){ 4055 return SQLITE_IOERR_FSTAT; 4056 } 4057 4058 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk; 4059 if( nSize>(i64)buf.st_size ){ 4060 4061 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE 4062 /* The code below is handling the return value of osFallocate() 4063 ** correctly. posix_fallocate() is defined to "returns zero on success, 4064 ** or an error number on failure". See the manpage for details. */ 4065 int err; 4066 do{ 4067 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size); 4068 }while( err==EINTR ); 4069 if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE; 4070 #else 4071 /* If the OS does not have posix_fallocate(), fake it. Write a 4072 ** single byte to the last byte in each block that falls entirely 4073 ** within the extended region. Then, if required, a single byte 4074 ** at offset (nSize-1), to set the size of the file correctly. 4075 ** This is a similar technique to that used by glibc on systems 4076 ** that do not have a real fallocate() call. 4077 */ 4078 int nBlk = buf.st_blksize; /* File-system block size */ 4079 int nWrite = 0; /* Number of bytes written by seekAndWrite */ 4080 i64 iWrite; /* Next offset to write to */ 4081 4082 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1; 4083 assert( iWrite>=buf.st_size ); 4084 assert( ((iWrite+1)%nBlk)==0 ); 4085 for(/*no-op*/; iWrite=nSize ) iWrite = nSize - 1; 4087 nWrite = seekAndWrite(pFile, iWrite, "", 1); 4088 if( nWrite!=1 ) return SQLITE_IOERR_WRITE; 4089 } 4090 #endif 4091 } 4092 } 4093 4094 #if SQLITE_MAX_MMAP_SIZE>0 4095 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){ 4096 int rc; 4097 if( pFile->szChunk<=0 ){ 4098 if( robust_ftruncate(pFile->h, nByte) ){ 4099 storeLastErrno(pFile, errno); 4100 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); 4101 } 4102 } 4103 4104 rc = unixMapfile(pFile, nByte); 4105 return rc; 4106 } 4107 #endif 4108 4109 return SQLITE_OK; 4110 } 4111 4112 /* 4113 ** If *pArg is initially negative then this is a query. Set *pArg to 4114 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set. 4115 ** 4116 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. 4117 */ 4118 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){ 4119 if( *pArg<0 ){ 4120 *pArg = (pFile->ctrlFlags & mask)!=0; 4121 }else if( (*pArg)==0 ){ 4122 pFile->ctrlFlags &= ~mask; 4123 }else{ 4124 pFile->ctrlFlags |= mask; 4125 } 4126 } 4127 4128 /* Forward declaration */ 4129 static int unixGetTempname(int nBuf, char *zBuf); 4130 #if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL) 4131 static int unixFcntlExternalReader(unixFile*, int*); 4132 #endif 4133 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) 4134 static void unixDescribeShm(sqlite3_str*,unixShm*); 4135 #endif 4136 4137 4138 /* 4139 ** Information and control of an open file handle. 4140 */ 4141 static int unixFileControl(sqlite3_file *id, int op, void *pArg){ 4142 unixFile *pFile = (unixFile*)id; 4143 switch( op ){ 4144 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) 4145 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: { 4146 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE); 4147 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK; 4148 } 4149 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: { 4150 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE); 4151 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK; 4152 } 4153 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: { 4154 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE); 4155 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK; 4156 } 4157 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */ 4158 4159 case SQLITE_FCNTL_NULL_IO: { 4160 osClose(pFile->h); 4161 pFile->h = -1; 4162 return SQLITE_OK; 4163 } 4164 case SQLITE_FCNTL_LOCKSTATE: { 4165 *(int*)pArg = pFile->eFileLock; 4166 return SQLITE_OK; 4167 } 4168 case SQLITE_FCNTL_LAST_ERRNO: { 4169 *(int*)pArg = pFile->lastErrno; 4170 return SQLITE_OK; 4171 } 4172 case SQLITE_FCNTL_CHUNK_SIZE: { 4173 pFile->szChunk = *(int *)pArg; 4174 return SQLITE_OK; 4175 } 4176 case SQLITE_FCNTL_SIZE_HINT: { 4177 int rc; 4178 SimulateIOErrorBenign(1); 4179 rc = fcntlSizeHint(pFile, *(i64 *)pArg); 4180 SimulateIOErrorBenign(0); 4181 return rc; 4182 } 4183 case SQLITE_FCNTL_PERSIST_WAL: { 4184 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg); 4185 return SQLITE_OK; 4186 } 4187 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { 4188 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg); 4189 return SQLITE_OK; 4190 } 4191 case SQLITE_FCNTL_VFSNAME: { 4192 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); 4193 return SQLITE_OK; 4194 } 4195 case SQLITE_FCNTL_TEMPFILENAME: { 4196 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname ); 4197 if( zTFile ){ 4198 unixGetTempname(pFile->pVfs->mxPathname, zTFile); 4199 *(char**)pArg = zTFile; 4200 } 4201 return SQLITE_OK; 4202 } 4203 case SQLITE_FCNTL_HAS_MOVED: { 4204 *(int*)pArg = fileHasMoved(pFile); 4205 return SQLITE_OK; 4206 } 4207 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 4208 case SQLITE_FCNTL_LOCK_TIMEOUT: { 4209 int iOld = pFile->iBusyTimeout; 4210 int iNew = *(int*)pArg; 4211 #if SQLITE_ENABLE_SETLK_TIMEOUT==1 4212 pFile->iBusyTimeout = iNew<0 ? 0x7FFFFFFF : (unsigned)iNew; 4213 #elif SQLITE_ENABLE_SETLK_TIMEOUT==2 4214 pFile->iBusyTimeout = !!(*(int*)pArg); 4215 #else 4216 # error "SQLITE_ENABLE_SETLK_TIMEOUT must be set to 1 or 2" 4217 #endif 4218 *(int*)pArg = iOld; 4219 return SQLITE_OK; 4220 } 4221 case SQLITE_FCNTL_BLOCK_ON_CONNECT: { 4222 int iNew = *(int*)pArg; 4223 pFile->bBlockOnConnect = iNew; 4224 return SQLITE_OK; 4225 } 4226 #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */ 4227 #if SQLITE_MAX_MMAP_SIZE>0 4228 case SQLITE_FCNTL_MMAP_SIZE: { 4229 i64 newLimit = *(i64*)pArg; 4230 int rc = SQLITE_OK; 4231 if( newLimit>sqlite3GlobalConfig.mxMmap ){ 4232 newLimit = sqlite3GlobalConfig.mxMmap; 4233 } 4234 4235 /* The value of newLimit may be eventually cast to (size_t) and passed 4236 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a 4237 ** 64-bit type. */ 4238 if( newLimit>0 && sizeof(size_t)<8 ){ 4239 newLimit = (newLimit & 0x7FFFFFFF); 4240 } 4241 4242 *(i64*)pArg = pFile->mmapSizeMax; 4243 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ 4244 pFile->mmapSizeMax = newLimit; 4245 if( pFile->mmapSize>0 ){ 4246 unixUnmapfile(pFile); 4247 rc = unixMapfile(pFile, -1); 4248 } 4249 } 4250 return rc; 4251 } 4252 #endif 4253 #ifdef SQLITE_DEBUG 4254 /* The pager calls this method to signal that it has done 4255 ** a rollback and that the database is therefore unchanged and 4256 ** it hence it is OK for the transaction change counter to be 4257 ** unchanged. 4258 */ 4259 case SQLITE_FCNTL_DB_UNCHANGED: { 4260 ((unixFile*)id)->dbUpdate = 0; 4261 return SQLITE_OK; 4262 } 4263 #endif 4264 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) 4265 case SQLITE_FCNTL_SET_LOCKPROXYFILE: 4266 case SQLITE_FCNTL_GET_LOCKPROXYFILE: { 4267 return proxyFileControl(id,op,pArg); 4268 } 4269 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */ 4270 4271 case SQLITE_FCNTL_EXTERNAL_READER: { 4272 #if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL) 4273 return unixFcntlExternalReader((unixFile*)id, (int*)pArg); 4274 #else 4275 *(int*)pArg = 0; 4276 return SQLITE_OK; 4277 #endif 4278 } 4279 4280 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) 4281 case SQLITE_FCNTL_FILESTAT: { 4282 sqlite3_str *pStr = (sqlite3_str*)pArg; 4283 char aLck[16]; 4284 unixInodeInfo *pInode; 4285 static const char *azLock[] = { "SHARED", "RESERVED", 4286 "PENDING", "EXCLUSIVE" }; 4287 sqlite3_str_appendf(pStr, "{\"h\":%d", pFile->h); 4288 sqlite3_str_appendf(pStr, ",\"vfs\":\"%s\"", pFile->pVfs->zName); 4289 if( pFile->eFileLock ){ 4290 sqlite3_str_appendf(pStr, ",\"eFileLock\":\"%s\"", 4291 azLock[pFile->eFileLock-1]); 4292 if( unixPosixAdvisoryLocks(pFile->h, aLck)==SQLITE_OK ){ 4293 sqlite3_str_appendf(pStr, ",\"pal\":\"%s\"", aLck); 4294 } 4295 } 4296 unixEnterMutex(); 4297 if( pFile->pShm ){ 4298 sqlite3_str_appendall(pStr, ",\"shm\":"); 4299 unixDescribeShm(pStr, pFile->pShm); 4300 } 4301 #if SQLITE_MAX_MMAP_SIZE>0 4302 if( pFile->mmapSize ){ 4303 sqlite3_str_appendf(pStr, ",\"mmapSize\":%lld", pFile->mmapSize); 4304 sqlite3_str_appendf(pStr, ",\"nFetchOut\":%d", pFile->nFetchOut); 4305 } 4306 #endif 4307 if( (pInode = pFile->pInode)!=0 ){ 4308 sqlite3_str_appendf(pStr, ",\"inode\":{\"nRef\":%d",pInode->nRef); 4309 sqlite3_mutex_enter(pInode->pLockMutex); 4310 sqlite3_str_appendf(pStr, ",\"nShared\":%d", pInode->nShared); 4311 if( pInode->eFileLock ){ 4312 sqlite3_str_appendf(pStr, ",\"eFileLock\":\"%s\"", 4313 azLock[pInode->eFileLock-1]); 4314 } 4315 if( pInode->pUnused ){ 4316 char cSep = '['; 4317 UnixUnusedFd *pUFd = pFile->pInode->pUnused; 4318 sqlite3_str_appendall(pStr, ",\"unusedFd\":"); 4319 while( pUFd ){ 4320 sqlite3_str_appendf(pStr, "%c{\"fd\":%d,\"flags\":%d", 4321 cSep, pUFd->fd, pUFd->flags); 4322 cSep = ','; 4323 if( unixPosixAdvisoryLocks(pUFd->fd, aLck)==SQLITE_OK ){ 4324 sqlite3_str_appendf(pStr, ",\"pal\":\"%s\"", aLck); 4325 } 4326 sqlite3_str_append(pStr, "}", 1); 4327 pUFd = pUFd->pNext; 4328 } 4329 sqlite3_str_append(pStr, "]", 1); 4330 } 4331 sqlite3_mutex_leave(pInode->pLockMutex); 4332 sqlite3_str_append(pStr, "}", 1); 4333 } 4334 unixLeaveMutex(); 4335 sqlite3_str_append(pStr, "}", 1); 4336 return SQLITE_OK; 4337 } 4338 #endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */ 4339 } 4340 return SQLITE_NOTFOUND; 4341 } 4342 4343 /* 4344 ** If pFd->sectorSize is non-zero when this function is called, it is a 4345 ** no-op. Otherwise, the values of pFd->sectorSize and 4346 ** pFd->deviceCharacteristics are set according to the file-system 4347 ** characteristics. 4348 ** 4349 ** There are two versions of this function. One for QNX and one for all 4350 ** other systems. 4351 */ 4352 #ifndef __QNXNTO__ 4353 static void setDeviceCharacteristics(unixFile *pFd){ 4354 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 ); 4355 if( pFd->sectorSize==0 ){ 4356 #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) 4357 int res; 4358 u32 f = 0; 4359 4360 /* Check for support for F2FS atomic batch writes. */ 4361 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f); 4362 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){ 4363 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC; 4364 } 4365 #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */ 4366 4367 /* Set the POWERSAFE_OVERWRITE flag if requested. */ 4368 if( pFd->ctrlFlags & UNIXFILE_PSOW ){ 4369 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE; 4370 } 4371 pFd->deviceCharacteristics |= SQLITE_IOCAP_SUBPAGE_READ; 4372 4373 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; 4374 } 4375 } 4376 #else 4377 #include 4378 #include 4379 static void setDeviceCharacteristics(unixFile *pFile){ 4380 if( pFile->sectorSize == 0 ){ 4381 struct statvfs fsInfo; 4382 4383 /* Set defaults for non-supported filesystems */ 4384 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; 4385 pFile->deviceCharacteristics = 0; 4386 if( fstatvfs(pFile->h, &fsInfo) == -1 ) { 4387 return; 4388 } 4389 4390 if( !strcmp(fsInfo.f_basetype, "tmp") ) { 4391 pFile->sectorSize = fsInfo.f_bsize; 4392 pFile->deviceCharacteristics = 4393 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */ 4394 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until 4395 ** the write succeeds */ 4396 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind 4397 ** so it is ordered */ 4398 0; 4399 }else if( strstr(fsInfo.f_basetype, "etfs") ){ 4400 pFile->sectorSize = fsInfo.f_bsize; 4401 pFile->deviceCharacteristics = 4402 /* etfs cluster size writes are atomic */ 4403 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) | 4404 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until 4405 ** the write succeeds */ 4406 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind 4407 ** so it is ordered */ 4408 0; 4409 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){ 4410 pFile->sectorSize = fsInfo.f_bsize; 4411 pFile->deviceCharacteristics = 4412 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */ 4413 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until 4414 ** the write succeeds */ 4415 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind 4416 ** so it is ordered */ 4417 0; 4418 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){ 4419 pFile->sectorSize = fsInfo.f_bsize; 4420 pFile->deviceCharacteristics = 4421 /* full bitset of atomics from max sector size and smaller */ 4422 (((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2) | 4423 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind 4424 ** so it is ordered */ 4425 0; 4426 }else if( strstr(fsInfo.f_basetype, "dos") ){ 4427 pFile->sectorSize = fsInfo.f_bsize; 4428 pFile->deviceCharacteristics = 4429 /* full bitset of atomics from max sector size and smaller */ 4430 (((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2) | 4431 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind 4432 ** so it is ordered */ 4433 0; 4434 }else{ 4435 pFile->deviceCharacteristics = 4436 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */ 4437 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until 4438 ** the write succeeds */ 4439 0; 4440 } 4441 } 4442 /* Last chance verification. If the sector size isn't a multiple of 512 4443 ** then it isn't valid.*/ 4444 if( pFile->sectorSize % 512 != 0 ){ 4445 pFile->deviceCharacteristics = 0; 4446 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; 4447 } 4448 } 4449 #endif 4450 4451 /* 4452 ** Return the sector size in bytes of the underlying block device for 4453 ** the specified file. This is almost always 512 bytes, but may be 4454 ** larger for some devices. 4455 ** 4456 ** SQLite code assumes this function cannot fail. It also assumes that 4457 ** if two files are created in the same file-system directory (i.e. 4458 ** a database and its journal file) that the sector size will be the 4459 ** same for both. 4460 */ 4461 static int unixSectorSize(sqlite3_file *id){ 4462 unixFile *pFd = (unixFile*)id; 4463 setDeviceCharacteristics(pFd); 4464 return pFd->sectorSize; 4465 } 4466 4467 /* 4468 ** Return the device characteristics for the file. 4469 ** 4470 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default. 4471 ** However, that choice is controversial since technically the underlying 4472 ** file system does not always provide powersafe overwrites. (In other 4473 ** words, after a power-loss event, parts of the file that were never 4474 ** written might end up being altered.) However, non-PSOW behavior is very, 4475 ** very rare. And asserting PSOW makes a large reduction in the amount 4476 ** of required I/O for journaling, since a lot of padding is eliminated. 4477 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control 4478 ** available to turn it off and URI query parameter available to turn it off. 4479 */ 4480 static int unixDeviceCharacteristics(sqlite3_file *id){ 4481 unixFile *pFd = (unixFile*)id; 4482 setDeviceCharacteristics(pFd); 4483 return pFd->deviceCharacteristics; 4484 } 4485 4486 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 4487 4488 /* 4489 ** Return the system page size. 4490 ** 4491 ** This function should not be called directly by other code in this file. 4492 ** Instead, it should be called via macro osGetpagesize(). 4493 */ 4494 static int unixGetpagesize(void){ 4495 #if OS_VXWORKS 4496 return 1024; 4497 #elif defined(_BSD_SOURCE) 4498 return getpagesize(); 4499 #else 4500 return (int)sysconf(_SC_PAGESIZE); 4501 #endif 4502 } 4503 4504 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */ 4505 4506 #if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL) 4507 4508 /* 4509 ** Object used to represent an shared memory buffer. 4510 ** 4511 ** When multiple threads all reference the same wal-index, each thread 4512 ** has its own unixShm object, but they all point to a single instance 4513 ** of this unixShmNode object. In other words, each wal-index is opened 4514 ** only once per process. 4515 ** 4516 ** Each unixShmNode object is connected to a single unixInodeInfo object. 4517 ** We could coalesce this object into unixInodeInfo, but that would mean 4518 ** every open file that does not use shared memory (in other words, most 4519 ** open files) would have to carry around this extra information. So 4520 ** the unixInodeInfo object contains a pointer to this unixShmNode object 4521 ** and the unixShmNode object is created only when needed. 4522 ** 4523 ** unixMutexHeld() must be true when creating or destroying 4524 ** this object or while reading or writing the following fields: 4525 ** 4526 ** nRef 4527 ** 4528 ** The following fields are read-only after the object is created: 4529 ** 4530 ** hShm 4531 ** zFilename 4532 ** 4533 ** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and 4534 ** unixMutexHeld() is true when reading or writing any other field 4535 ** in this structure. 4536 ** 4537 ** aLock[SQLITE_SHM_NLOCK]: 4538 ** This array records the various locks held by clients on each of the 4539 ** SQLITE_SHM_NLOCK slots. If the aLock[] entry is set to 0, then no 4540 ** locks are held by the process on this slot. If it is set to -1, then 4541 ** some client holds an EXCLUSIVE lock on the locking slot. If the aLock[] 4542 ** value is set to a positive value, then it is the number of shared 4543 ** locks currently held on the slot. 4544 ** 4545 ** aMutex[SQLITE_SHM_NLOCK]: 4546 ** Normally, when SQLITE_ENABLE_SETLK_TIMEOUT is not defined, mutex 4547 ** pShmMutex is used to protect the aLock[] array and the right to 4548 ** call fcntl() on unixShmNode.hShm to obtain or release locks. 4549 ** 4550 ** If SQLITE_ENABLE_SETLK_TIMEOUT is defined though, we use an array 4551 ** of mutexes - one for each locking slot. To read or write locking 4552 ** slot aLock[iSlot], the caller must hold the corresponding mutex 4553 ** aMutex[iSlot]. Similarly, to call fcntl() to obtain or release a 4554 ** lock corresponding to slot iSlot, mutex aMutex[iSlot] must be held. 4555 */ 4556 struct unixShmNode { 4557 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */ 4558 sqlite3_mutex *pShmMutex; /* Mutex to access this object */ 4559 char *zFilename; /* Name of the mmapped file */ 4560 int hShm; /* Open file descriptor */ 4561 int szRegion; /* Size of shared-memory regions */ 4562 int nRegion; /* Size of array apRegion */ 4563 int nRef; /* Number of unixShm objects pointing to this */ 4564 u8 isReadonly; /* True if read-only */ 4565 u8 isUnlocked; /* True if no DMS lock held */ 4566 #ifdef SQLITE_DEBUG 4567 u8 nextShmId; /* Next available unixShm.id value */ 4568 #endif 4569 char **apRegion; /* Array of mapped shared-memory regions */ 4570 unixShm *pFirst; /* All unixShm objects pointing to this */ 4571 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 4572 sqlite3_mutex *aMutex[SQLITE_SHM_NLOCK]; 4573 #endif 4574 int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */ 4575 }; 4576 4577 /* 4578 ** Structure used internally by this VFS to record the state of an 4579 ** open shared memory connection. 4580 ** 4581 ** The following fields are initialized when this object is created and 4582 ** are read-only thereafter: 4583 ** 4584 ** unixShm.pShmNode 4585 ** unixShm.id 4586 ** 4587 ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must 4588 ** be held while accessing any read/write fields. 4589 */ 4590 struct unixShm { 4591 unixShmNode *pShmNode; /* The underlying unixShmNode object */ 4592 unixShm *pNext; /* Next unixShm with the same unixShmNode */ 4593 u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */ 4594 u8 id; /* Id of this connection within its unixShmNode */ 4595 u16 sharedMask; /* Mask of shared locks held */ 4596 u16 exclMask; /* Mask of exclusive locks held */ 4597 }; 4598 4599 /* 4600 ** Constants used for locking 4601 */ 4602 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */ 4603 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */ 4604 4605 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) 4606 /* 4607 ** Describe the pShm object using JSON. Used for diagnostics only. 4608 */ 4609 static void unixDescribeShm(sqlite3_str *pStr, unixShm *pShm){ 4610 unixShmNode *pNode = pShm->pShmNode; 4611 char aLck[16]; 4612 sqlite3_str_appendf(pStr, "{\"h\":%d", pNode->hShm); 4613 assert( unixMutexHeld() ); 4614 sqlite3_str_appendf(pStr, ",\"nRef\":%d", pNode->nRef); 4615 sqlite3_str_appendf(pStr, ",\"id\":%d", pShm->id); 4616 sqlite3_str_appendf(pStr, ",\"sharedMask\":%d", pShm->sharedMask); 4617 sqlite3_str_appendf(pStr, ",\"exclMask\":%d", pShm->exclMask); 4618 if( unixPosixAdvisoryLocks(pNode->hShm, aLck)==SQLITE_OK ){ 4619 sqlite3_str_appendf(pStr, ",\"pal\":\"%s\"", aLck); 4620 } 4621 sqlite3_str_append(pStr, "}", 1); 4622 } 4623 #endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */ 4624 4625 /* 4626 ** Use F_GETLK to check whether or not there are any readers with open 4627 ** wal-mode transactions in other processes on database file pFile. If 4628 ** no error occurs, return SQLITE_OK and set (*piOut) to 1 if there are 4629 ** such transactions, or 0 otherwise. If an error occurs, return an 4630 ** SQLite error code. The final value of *piOut is undefined in this 4631 ** case. 4632 */ 4633 static int unixFcntlExternalReader(unixFile *pFile, int *piOut){ 4634 int rc = SQLITE_OK; 4635 *piOut = 0; 4636 if( pFile->pShm){ 4637 unixShmNode *pShmNode = pFile->pShm->pShmNode; 4638 struct flock f; 4639 4640 memset(&f, 0, sizeof(f)); 4641 f.l_type = F_WRLCK; 4642 f.l_whence = SEEK_SET; 4643 f.l_start = UNIX_SHM_BASE + 3; 4644 f.l_len = SQLITE_SHM_NLOCK - 3; 4645 4646 sqlite3_mutex_enter(pShmNode->pShmMutex); 4647 if( osFcntl(pShmNode->hShm, F_GETLK, &f)<0 ){ 4648 rc = SQLITE_IOERR_LOCK; 4649 }else{ 4650 *piOut = (f.l_type!=F_UNLCK); 4651 } 4652 sqlite3_mutex_leave(pShmNode->pShmMutex); 4653 } 4654 4655 return rc; 4656 } 4657 4658 /* 4659 ** If pFile has a -shm file open and it is sharing that file with some 4660 ** other connection, either in the same process or in a separate process, 4661 ** then return true. Return false if either pFile does not have a -shm 4662 ** file open or if it is the only connection to that -shm file across the 4663 ** entire system. 4664 ** 4665 ** This routine is not required for correct operation. It can always return 4666 ** false and SQLite will continue to operate according to spec. However, 4667 ** when this routine does its job, it adds extra robustness in cases 4668 ** where database file locks have been erroneously deleted in a WAL-mode 4669 ** database by doing close(open(DATABASE_PATHNAME)) or similar. 4670 ** 4671 ** With false negatives, SQLite still operates to spec, though with less 4672 ** robustness. With false positives, the last database connection on a 4673 ** WAL-mode database will fail to unlink the -wal and -shm files, which 4674 ** is annoying but harmless. False positives will also prevent a database 4675 ** connection from running "PRAGMA journal_mode=DELETE" in order to take 4676 ** the database out of WAL mode, which is perhaps more serious, but is 4677 ** still not a disaster. 4678 */ 4679 static int unixIsSharingShmNode(unixFile *pFile){ 4680 unixShmNode *pShmNode; 4681 struct flock lock; 4682 if( pFile->pShm==0 ) return 0; 4683 if( pFile->ctrlFlags & UNIXFILE_EXCL ) return 0; 4684 pShmNode = pFile->pShm->pShmNode; 4685 #if SQLITE_ATOMIC_INTRINSICS 4686 assert( AtomicLoad(&pShmNode->nRef)==1 ); 4687 #endif 4688 memset(&lock, 0, sizeof(lock)); 4689 lock.l_whence = SEEK_SET; 4690 lock.l_start = UNIX_SHM_DMS; 4691 lock.l_len = 1; 4692 lock.l_type = F_WRLCK; 4693 osFcntl(pShmNode->hShm, F_GETLK, &lock); 4694 return (lock.l_type!=F_UNLCK); 4695 } 4696 4697 /* 4698 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1. 4699 ** 4700 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking 4701 ** otherwise. 4702 */ 4703 static int unixShmSystemLock( 4704 unixFile *pFile, /* Open connection to the WAL file */ 4705 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */ 4706 int ofst, /* First byte of the locking range */ 4707 int n /* Number of bytes to lock */ 4708 ){ 4709 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */ 4710 struct flock f; /* The posix advisory locking structure */ 4711 int rc = SQLITE_OK; /* Result code form fcntl() */ 4712 4713 pShmNode = pFile->pInode->pShmNode; 4714 4715 /* Assert that the parameters are within expected range and that the 4716 ** correct mutex or mutexes are held. */ 4717 assert( pShmNode->nRef>=0 ); 4718 assert( (ofst==UNIX_SHM_DMS && n==1) 4719 || (ofst>=UNIX_SHM_BASE && ofst+n<=(UNIX_SHM_BASE+SQLITE_SHM_NLOCK)) 4720 ); 4721 if( ofst==UNIX_SHM_DMS ){ 4722 assert( pShmNode->nRef>0 || unixMutexHeld() ); 4723 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) ); 4724 }else{ 4725 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 4726 int ii; 4727 for(ii=ofst-UNIX_SHM_BASE; iiaMutex[ii]) ); 4729 } 4730 #else 4731 assert( sqlite3_mutex_held(pShmNode->pShmMutex) ); 4732 assert( pShmNode->nRef>0 ); 4733 #endif 4734 } 4735 4736 /* Shared locks never span more than one byte */ 4737 assert( n==1 || lockType!=F_RDLCK ); 4738 4739 /* Locks are within range */ 4740 assert( n>=1 && n<=SQLITE_SHM_NLOCK ); 4741 assert( ofst>=UNIX_SHM_BASE && ofst<=UNIX_SHM_DMS ); 4742 assert( ofst+n-1<=UNIX_SHM_DMS ); 4743 4744 if( pShmNode->hShm>=0 ){ 4745 int res; 4746 /* Initialize the locking parameters */ 4747 f.l_type = lockType; 4748 f.l_whence = SEEK_SET; 4749 f.l_start = ofst; 4750 f.l_len = n; 4751 res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile); 4752 if( res==-1 ){ 4753 #if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && SQLITE_ENABLE_SETLK_TIMEOUT==1 4754 rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY); 4755 #else 4756 rc = SQLITE_BUSY; 4757 #endif 4758 } 4759 } 4760 4761 /* Do debug tracing */ 4762 #ifdef SQLITE_DEBUG 4763 OSTRACE(("SHM-LOCK ")); 4764 if( rc==SQLITE_OK ){ 4765 if( lockType==F_UNLCK ){ 4766 OSTRACE(("unlock %d..%d ok\n", ofst, ofst+n-1)); 4767 }else if( lockType==F_RDLCK ){ 4768 OSTRACE(("read-lock %d..%d ok\n", ofst, ofst+n-1)); 4769 }else{ 4770 assert( lockType==F_WRLCK ); 4771 OSTRACE(("write-lock %d..%d ok\n", ofst, ofst+n-1)); 4772 } 4773 }else{ 4774 if( lockType==F_UNLCK ){ 4775 OSTRACE(("unlock %d..%d failed\n", ofst, ofst+n-1)); 4776 }else if( lockType==F_RDLCK ){ 4777 OSTRACE(("read-lock %d..%d failed\n", ofst, ofst+n-1)); 4778 }else{ 4779 assert( lockType==F_WRLCK ); 4780 OSTRACE(("write-lock %d..%d failed\n", ofst, ofst+n-1)); 4781 } 4782 } 4783 #endif 4784 4785 return rc; 4786 } 4787 4788 /* 4789 ** Return the minimum number of 32KB shm regions that should be mapped at 4790 ** a time, assuming that each mapping must be an integer multiple of the 4791 ** current system page-size. 4792 ** 4793 ** Usually, this is 1. The exception seems to be systems that are configured 4794 ** to use 64KB pages - in this case each mapping must cover at least two 4795 ** shm regions. 4796 */ 4797 static int unixShmRegionPerMap(void){ 4798 int shmsz = 32*1024; /* SHM region size */ 4799 int pgsz = osGetpagesize(); /* System page size */ 4800 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */ 4801 if( pgszpInode->pShmNode; 4813 assert( unixMutexHeld() ); 4814 if( p && ALWAYS(p->nRef==0) ){ 4815 int nShmPerMap = unixShmRegionPerMap(); 4816 int i; 4817 assert( p->pInode==pFd->pInode ); 4818 sqlite3_mutex_free(p->pShmMutex); 4819 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 4820 for(i=0; iaMutex[i]); 4822 } 4823 #endif 4824 for(i=0; inRegion; i+=nShmPerMap){ 4825 if( p->hShm>=0 ){ 4826 osMunmap(p->apRegion[i], p->szRegion); 4827 }else{ 4828 sqlite3_free(p->apRegion[i]); 4829 } 4830 } 4831 sqlite3_free(p->apRegion); 4832 if( p->hShm>=0 ){ 4833 robust_close(pFd, p->hShm, __LINE__); 4834 p->hShm = -1; 4835 } 4836 p->pInode->pShmNode = 0; 4837 sqlite3_free(p); 4838 } 4839 } 4840 4841 /* 4842 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to 4843 ** take it now. Return SQLITE_OK if successful, or an SQLite error 4844 ** code otherwise. 4845 ** 4846 ** If the DMS cannot be locked because this is a readonly_shm=1 4847 ** connection and no other process already holds a lock, return 4848 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1. 4849 */ 4850 static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){ 4851 struct flock lock; 4852 int rc = SQLITE_OK; 4853 4854 /* Use F_GETLK to determine the locks other processes are holding 4855 ** on the DMS byte. If it indicates that another process is holding 4856 ** a SHARED lock, then this process may also take a SHARED lock 4857 ** and proceed with opening the *-shm file. 4858 ** 4859 ** Or, if no other process is holding any lock, then this process 4860 ** is the first to open it. In this case take an EXCLUSIVE lock on the 4861 ** DMS byte and truncate the *-shm file to zero bytes in size. Then 4862 ** downgrade to a SHARED lock on the DMS byte. 4863 ** 4864 ** If another process is holding an EXCLUSIVE lock on the DMS byte, 4865 ** return SQLITE_BUSY to the caller (it will try again). An earlier 4866 ** version of this code attempted the SHARED lock at this point. But 4867 ** this introduced a subtle race condition: if the process holding 4868 ** EXCLUSIVE failed just before truncating the *-shm file, then this 4869 ** process might open and use the *-shm file without truncating it. 4870 ** And if the *-shm file has been corrupted by a power failure or 4871 ** system crash, the database itself may also become corrupt. */ 4872 lock.l_whence = SEEK_SET; 4873 lock.l_start = UNIX_SHM_DMS; 4874 lock.l_len = 1; 4875 lock.l_type = F_WRLCK; 4876 if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) { 4877 rc = SQLITE_IOERR_LOCK; 4878 }else if( lock.l_type==F_UNLCK ){ 4879 if( pShmNode->isReadonly ){ 4880 pShmNode->isUnlocked = 1; 4881 rc = SQLITE_READONLY_CANTINIT; 4882 }else{ 4883 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 4884 /* Do not use a blocking lock here. If the lock cannot be obtained 4885 ** immediately, it means some other connection is truncating the 4886 ** *-shm file. And after it has done so, it will not release its 4887 ** lock, but only downgrade it to a shared lock. So no point in 4888 ** blocking here. The call below to obtain the shared DMS lock may 4889 ** use a blocking lock. */ 4890 int iSaveTimeout = pDbFd->iBusyTimeout; 4891 pDbFd->iBusyTimeout = 0; 4892 #endif 4893 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1); 4894 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 4895 pDbFd->iBusyTimeout = iSaveTimeout; 4896 #endif 4897 /* The first connection to attach must truncate the -shm file. We 4898 ** truncate to 3 bytes (an arbitrary small number, less than the 4899 ** -shm header size) rather than 0 as a system debugging aid, to 4900 ** help detect if a -shm file truncation is legitimate or is the work 4901 ** or a rogue process. */ 4902 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){ 4903 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename); 4904 } 4905 } 4906 }else if( lock.l_type==F_WRLCK ){ 4907 rc = SQLITE_BUSY; 4908 } 4909 4910 if( rc==SQLITE_OK ){ 4911 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK ); 4912 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1); 4913 } 4914 return rc; 4915 } 4916 4917 /* 4918 ** Open a shared-memory area associated with open database file pDbFd. 4919 ** This particular implementation uses mmapped files. 4920 ** 4921 ** The file used to implement shared-memory is in the same directory 4922 ** as the open database file and has the same name as the open database 4923 ** file with the "-shm" suffix added. For example, if the database file 4924 ** is "/home/user1/config.db" then the file that is created and mmapped 4925 ** for shared memory will be called "/home/user1/config.db-shm". 4926 ** 4927 ** Another approach to is to use files in /dev/shm or /dev/tmp or an 4928 ** some other tmpfs mount. But if a file in a different directory 4929 ** from the database file is used, then differing access permissions 4930 ** or a chroot() might cause two different processes on the same 4931 ** database to end up using different files for shared memory - 4932 ** meaning that their memory would not really be shared - resulting 4933 ** in database corruption. Nevertheless, this tmpfs file usage 4934 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm" 4935 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time 4936 ** option results in an incompatible build of SQLite; builds of SQLite 4937 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the 4938 ** same database file at the same time, database corruption will likely 4939 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered 4940 ** "unsupported" and may go away in a future SQLite release. 4941 ** 4942 ** When opening a new shared-memory file, if no other instances of that 4943 ** file are currently open, in this process or in other processes, then 4944 ** the file must be truncated to zero length or have its header cleared. 4945 ** 4946 ** If the original database file (pDbFd) is using the "unix-excl" VFS 4947 ** that means that an exclusive lock is held on the database file and 4948 ** that no other processes are able to read or write the database. In 4949 ** that case, we do not really need shared memory. No shared memory 4950 ** file is created. The shared memory will be simulated with heap memory. 4951 */ 4952 static int unixOpenSharedMemory(unixFile *pDbFd){ 4953 struct unixShm *p = 0; /* The connection to be opened */ 4954 struct unixShmNode *pShmNode; /* The underlying mmapped file */ 4955 int rc = SQLITE_OK; /* Result code */ 4956 unixInodeInfo *pInode; /* The inode of fd */ 4957 char *zShm; /* Name of the file used for SHM */ 4958 int nShmFilename; /* Size of the SHM filename in bytes */ 4959 4960 /* Allocate space for the new unixShm object. */ 4961 p = sqlite3_malloc64( sizeof(*p) ); 4962 if( p==0 ) return SQLITE_NOMEM_BKPT; 4963 memset(p, 0, sizeof(*p)); 4964 assert( pDbFd->pShm==0 ); 4965 4966 /* Check to see if a unixShmNode object already exists. Reuse an existing 4967 ** one if present. Create a new one if necessary. 4968 */ 4969 assert( unixFileMutexNotheld(pDbFd) ); 4970 unixEnterMutex(); 4971 pInode = pDbFd->pInode; 4972 pShmNode = pInode->pShmNode; 4973 if( pShmNode==0 ){ 4974 struct stat sStat; /* fstat() info for database file */ 4975 #ifndef SQLITE_SHM_DIRECTORY 4976 const char *zBasePath = pDbFd->zPath; 4977 #endif 4978 4979 /* Call fstat() to figure out the permissions on the database file. If 4980 ** a new *-shm file is created, an attempt will be made to create it 4981 ** with the same permissions. 4982 */ 4983 if( osFstat(pDbFd->h, &sStat) ){ 4984 rc = SQLITE_IOERR_FSTAT; 4985 goto shm_open_err; 4986 } 4987 4988 #ifdef SQLITE_SHM_DIRECTORY 4989 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31; 4990 #else 4991 nShmFilename = 6 + (int)strlen(zBasePath); 4992 #endif 4993 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename ); 4994 if( pShmNode==0 ){ 4995 rc = SQLITE_NOMEM_BKPT; 4996 goto shm_open_err; 4997 } 4998 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename); 4999 zShm = pShmNode->zFilename = (char*)&pShmNode[1]; 5000 #ifdef SQLITE_SHM_DIRECTORY 5001 sqlite3_snprintf(nShmFilename, zShm, 5002 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x", 5003 (u32)sStat.st_ino, (u32)sStat.st_dev); 5004 #else 5005 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath); 5006 sqlite3FileSuffix3(pDbFd->zPath, zShm); 5007 #endif 5008 pShmNode->hShm = -1; 5009 pDbFd->pInode->pShmNode = pShmNode; 5010 pShmNode->pInode = pDbFd->pInode; 5011 if( sqlite3GlobalConfig.bCoreMutex ){ 5012 pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); 5013 if( pShmNode->pShmMutex==0 ){ 5014 rc = SQLITE_NOMEM_BKPT; 5015 goto shm_open_err; 5016 } 5017 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 5018 { 5019 int ii; 5020 for(ii=0; iiaMutex[ii] = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); 5022 if( pShmNode->aMutex[ii]==0 ){ 5023 rc = SQLITE_NOMEM_BKPT; 5024 goto shm_open_err; 5025 } 5026 } 5027 } 5028 #endif 5029 } 5030 5031 if( pInode->bProcessLock==0 ){ 5032 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){ 5033 pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW, 5034 (sStat.st_mode&0777)); 5035 } 5036 if( pShmNode->hShm<0 ){ 5037 pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW, 5038 (sStat.st_mode&0777)); 5039 if( pShmNode->hShm<0 ){ 5040 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm); 5041 goto shm_open_err; 5042 } 5043 pShmNode->isReadonly = 1; 5044 } 5045 5046 /* If this process is running as root, make sure that the SHM file 5047 ** is owned by the same user that owns the original database. Otherwise, 5048 ** the original owner will not be able to connect. 5049 */ 5050 robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid); 5051 5052 rc = unixLockSharedMemory(pDbFd, pShmNode); 5053 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err; 5054 } 5055 } 5056 5057 /* Make the new connection a child of the unixShmNode */ 5058 p->pShmNode = pShmNode; 5059 #ifdef SQLITE_DEBUG 5060 p->id = pShmNode->nextShmId++; 5061 #endif 5062 pShmNode->nRef++; 5063 pDbFd->pShm = p; 5064 unixLeaveMutex(); 5065 5066 /* The reference count on pShmNode has already been incremented under 5067 ** the cover of the unixEnterMutex() mutex and the pointer from the 5068 ** new (struct unixShm) object to the pShmNode has been set. All that is 5069 ** left to do is to link the new object into the linked list starting 5070 ** at pShmNode->pFirst. This must be done while holding the 5071 ** pShmNode->pShmMutex. 5072 */ 5073 sqlite3_mutex_enter(pShmNode->pShmMutex); 5074 p->pNext = pShmNode->pFirst; 5075 pShmNode->pFirst = p; 5076 sqlite3_mutex_leave(pShmNode->pShmMutex); 5077 return rc; 5078 5079 /* Jump here on any error */ 5080 shm_open_err: 5081 unixShmPurge(pDbFd); /* This call frees pShmNode if required */ 5082 sqlite3_free(p); 5083 unixLeaveMutex(); 5084 return rc; 5085 } 5086 5087 /* 5088 ** This function is called to obtain a pointer to region iRegion of the 5089 ** shared-memory associated with the database file fd. Shared-memory regions 5090 ** are numbered starting from zero. Each shared-memory region is szRegion 5091 ** bytes in size. 5092 ** 5093 ** If an error occurs, an error code is returned and *pp is set to NULL. 5094 ** 5095 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory 5096 ** region has not been allocated (by any client, including one running in a 5097 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 5098 ** bExtend is non-zero and the requested shared-memory region has not yet 5099 ** been allocated, it is allocated by this function. 5100 ** 5101 ** If the shared-memory region has already been allocated or is allocated by 5102 ** this call as described above, then it is mapped into this processes 5103 ** address space (if it is not already), *pp is set to point to the mapped 5104 ** memory and SQLITE_OK returned. 5105 */ 5106 static int unixShmMap( 5107 sqlite3_file *fd, /* Handle open on database file */ 5108 int iRegion, /* Region to retrieve */ 5109 int szRegion, /* Size of regions */ 5110 int bExtend, /* True to extend file if necessary */ 5111 void volatile **pp /* OUT: Mapped memory */ 5112 ){ 5113 unixFile *pDbFd = (unixFile*)fd; 5114 unixShm *p; 5115 unixShmNode *pShmNode; 5116 int rc = SQLITE_OK; 5117 int nShmPerMap = unixShmRegionPerMap(); 5118 int nReqRegion; 5119 5120 /* If the shared-memory file has not yet been opened, open it now. */ 5121 if( pDbFd->pShm==0 ){ 5122 rc = unixOpenSharedMemory(pDbFd); 5123 if( rc!=SQLITE_OK ) return rc; 5124 } 5125 5126 p = pDbFd->pShm; 5127 pShmNode = p->pShmNode; 5128 sqlite3_mutex_enter(pShmNode->pShmMutex); 5129 if( pShmNode->isUnlocked ){ 5130 rc = unixLockSharedMemory(pDbFd, pShmNode); 5131 if( rc!=SQLITE_OK ) goto shmpage_out; 5132 pShmNode->isUnlocked = 0; 5133 } 5134 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); 5135 assert( pShmNode->pInode==pDbFd->pInode ); 5136 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 ); 5137 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 ); 5138 5139 /* Minimum number of regions required to be mapped. */ 5140 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap; 5141 5142 if( pShmNode->nRegionszRegion = szRegion; 5148 5149 if( pShmNode->hShm>=0 ){ 5150 /* The requested region is not mapped into this processes address space. 5151 ** Check to see if it has been allocated (i.e. if the wal-index file is 5152 ** large enough to contain the requested region). 5153 */ 5154 if( osFstat(pShmNode->hShm, &sStat) ){ 5155 rc = SQLITE_IOERR_SHMSIZE; 5156 goto shmpage_out; 5157 } 5158 5159 if( sStat.st_sizehShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){ 5183 const char *zFile = pShmNode->zFilename; 5184 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile); 5185 goto shmpage_out; 5186 } 5187 } 5188 } 5189 } 5190 } 5191 5192 /* Map the requested memory region into this processes address space. */ 5193 apNew = (char **)sqlite3_realloc64( 5194 pShmNode->apRegion, nReqRegion*sizeof(char *) 5195 ); 5196 if( !apNew ){ 5197 rc = SQLITE_IOERR_NOMEM_BKPT; 5198 goto shmpage_out; 5199 } 5200 pShmNode->apRegion = apNew; 5201 while( pShmNode->nRegionhShm>=0 ){ 5206 pMem = osMmap(0, nMap, 5207 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 5208 MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion 5209 ); 5210 if( pMem==MAP_FAILED ){ 5211 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename); 5212 goto shmpage_out; 5213 } 5214 }else{ 5215 pMem = sqlite3_malloc64(nMap); 5216 if( pMem==0 ){ 5217 rc = SQLITE_NOMEM_BKPT; 5218 goto shmpage_out; 5219 } 5220 memset(pMem, 0, nMap); 5221 } 5222 5223 for(i=0; iapRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i]; 5225 } 5226 pShmNode->nRegion += nShmPerMap; 5227 } 5228 } 5229 5230 shmpage_out: 5231 if( pShmNode->nRegion>iRegion ){ 5232 *pp = pShmNode->apRegion[iRegion]; 5233 }else{ 5234 *pp = 0; 5235 } 5236 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY; 5237 sqlite3_mutex_leave(pShmNode->pShmMutex); 5238 return rc; 5239 } 5240 5241 /* 5242 ** Check that the pShmNode->aLock[] array comports with the locking bitmasks 5243 ** held by each client. Return true if it does, or false otherwise. This 5244 ** is to be used in an assert(). e.g. 5245 ** 5246 ** assert( assertLockingArrayOk(pShmNode) ); 5247 */ 5248 #ifdef SQLITE_DEBUG 5249 static int assertLockingArrayOk(unixShmNode *pShmNode){ 5250 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 5251 return 1; 5252 #else 5253 unixShm *pX; 5254 int aLock[SQLITE_SHM_NLOCK]; 5255 5256 memset(aLock, 0, sizeof(aLock)); 5257 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ 5258 int i; 5259 for(i=0; iexclMask & (1<sharedMask & (1<=0 ); 5265 aLock[i]++; 5266 } 5267 } 5268 } 5269 5270 assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) ); 5271 return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0); 5272 #endif 5273 } 5274 #endif /* !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL) */ 5275 5276 /* 5277 ** Change the lock state for a shared-memory segment. 5278 ** 5279 ** Note that the relationship between SHARED and EXCLUSIVE locks is a little 5280 ** different here than in posix. In xShmLock(), one can go from unlocked 5281 ** to shared and back or from unlocked to exclusive and back. But one may 5282 ** not go from shared to exclusive or from exclusive to shared. 5283 */ 5284 static int unixShmLock( 5285 sqlite3_file *fd, /* Database file holding the shared memory */ 5286 int ofst, /* First lock to acquire or release */ 5287 int n, /* Number of locks to acquire or release */ 5288 int flags /* What to do with the lock */ 5289 ){ 5290 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */ 5291 unixShm *p; /* The shared memory being locked */ 5292 unixShmNode *pShmNode; /* The underlying file iNode */ 5293 int rc = SQLITE_OK; /* Result code */ 5294 u16 mask = (1<<(ofst+n)) - (1<pShm; 5298 if( p==0 ) return SQLITE_IOERR_SHMLOCK; 5299 pShmNode = p->pShmNode; 5300 if( NEVER(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK; 5301 aLock = pShmNode->aLock; 5302 5303 assert( pShmNode==pDbFd->pInode->pShmNode ); 5304 assert( pShmNode->pInode==pDbFd->pInode ); 5305 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK ); 5306 assert( n>=1 ); 5307 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED) 5308 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE) 5309 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED) 5310 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) ); 5311 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 ); 5312 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 ); 5313 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 ); 5314 5315 /* Check that, if this to be a blocking lock, no locks that occur later 5316 ** in the following list than the lock being obtained are already held: 5317 ** 5318 ** 1. Recovery lock (ofst==2). 5319 ** 2. Checkpointer lock (ofst==1). 5320 ** 3. Write lock (ofst==0). 5321 ** 4. Read locks (ofst>=3 && ofstexclMask|p->sharedMask); 5330 assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || ( 5331 (ofst!=2 || lockMask==0) 5332 && (ofst!=1 || lockMask==0 || lockMask==2) 5333 && (ofst!=0 || lockMask<3) 5334 && (ofst<3 || lockMask<(1<exclMask & mask) 5350 ); 5351 if( ((flags & SQLITE_SHM_UNLOCK) && ((p->exclMask|p->sharedMask) & mask)) 5352 || (flags==(SQLITE_SHM_SHARED|SQLITE_SHM_LOCK) && 0==(p->sharedMask & mask)) 5353 || (flags==(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK)) 5354 ){ 5355 5356 /* Take the required mutexes. In SETLK_TIMEOUT mode (blocking locks), if 5357 ** this is an attempt on an exclusive lock use sqlite3_mutex_try(). If any 5358 ** other thread is holding this mutex, then it is either holding or about 5359 ** to hold a lock exclusive to the one being requested, and we may 5360 ** therefore return SQLITE_BUSY to the caller. 5361 ** 5362 ** Doing this prevents some deadlock scenarios. For example, thread 1 may 5363 ** be a checkpointer blocked waiting on the WRITER lock. And thread 2 5364 ** may be a normal SQL client upgrading to a write transaction. In this 5365 ** case thread 2 does a non-blocking request for the WRITER lock. But - 5366 ** if it were to use sqlite3_mutex_enter() then it would effectively 5367 ** become a (doomed) blocking request, as thread 2 would block until thread 5368 ** 1 obtained WRITER and released the mutex. Since thread 2 already holds 5369 ** a lock on a read-locking slot at this point, this breaks the 5370 ** anti-deadlock rules (see above). */ 5371 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 5372 int iMutex; 5373 for(iMutex=ofst; iMutexaMutex[iMutex]); 5376 if( rc!=SQLITE_OK ) goto leave_shmnode_mutexes; 5377 }else{ 5378 sqlite3_mutex_enter(pShmNode->aMutex[iMutex]); 5379 } 5380 } 5381 #else 5382 sqlite3_mutex_enter(pShmNode->pShmMutex); 5383 #endif 5384 5385 if( ALWAYS(rc==SQLITE_OK) ){ 5386 if( flags & SQLITE_SHM_UNLOCK ){ 5387 /* Case (a) - unlock. */ 5388 int bUnlock = 1; 5389 assert( (p->exclMask & p->sharedMask)==0 ); 5390 assert( !(flags & SQLITE_SHM_EXCLUSIVE) || (p->exclMask & mask)==mask ); 5391 assert( !(flags & SQLITE_SHM_SHARED) || (p->sharedMask & mask)==mask ); 5392 5393 /* If this is a SHARED lock being unlocked, it is possible that other 5394 ** clients within this process are holding the same SHARED lock. In 5395 ** this case, set bUnlock to 0 so that the posix lock is not removed 5396 ** from the file-descriptor below. */ 5397 if( flags & SQLITE_SHM_SHARED ){ 5398 assert( n==1 ); 5399 assert( aLock[ofst]>=1 ); 5400 if( aLock[ofst]>1 ){ 5401 bUnlock = 0; 5402 aLock[ofst]--; 5403 p->sharedMask &= ~mask; 5404 } 5405 } 5406 5407 if( bUnlock ){ 5408 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n); 5409 if( rc==SQLITE_OK ){ 5410 memset(&aLock[ofst], 0, sizeof(int)*n); 5411 p->sharedMask &= ~mask; 5412 p->exclMask &= ~mask; 5413 } 5414 } 5415 }else if( flags & SQLITE_SHM_SHARED ){ 5416 /* Case (b) - a shared lock. */ 5417 5418 if( aLock[ofst]<0 ){ 5419 /* An exclusive lock is held by some other connection. BUSY. */ 5420 rc = SQLITE_BUSY; 5421 }else if( aLock[ofst]==0 ){ 5422 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n); 5423 } 5424 5425 /* Get the local shared locks */ 5426 if( rc==SQLITE_OK ){ 5427 p->sharedMask |= mask; 5428 aLock[ofst]++; 5429 } 5430 }else{ 5431 /* Case (c) - an exclusive lock. */ 5432 int ii; 5433 5434 assert( flags==(SQLITE_SHM_LOCK|SQLITE_SHM_EXCLUSIVE) ); 5435 assert( (p->sharedMask & mask)==0 ); 5436 assert( (p->exclMask & mask)==0 ); 5437 5438 /* Make sure no sibling connections hold locks that will block this 5439 ** lock. If any do, return SQLITE_BUSY right away. */ 5440 for(ii=ofst; iiexclMask |= mask; 5453 for(ii=ofst; ii=ofst; iMutex--){ 5466 sqlite3_mutex_leave(pShmNode->aMutex[iMutex]); 5467 } 5468 #else 5469 sqlite3_mutex_leave(pShmNode->pShmMutex); 5470 #endif 5471 } 5472 5473 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n", 5474 p->id, osGetpid(0), p->sharedMask, p->exclMask)); 5475 return rc; 5476 } 5477 5478 /* 5479 ** Implement a memory barrier or memory fence on shared memory. 5480 ** 5481 ** All loads and stores begun before the barrier must complete before 5482 ** any load or store begun after the barrier. 5483 */ 5484 static void unixShmBarrier( 5485 sqlite3_file *fd /* Database file holding the shared memory */ 5486 ){ 5487 UNUSED_PARAMETER(fd); 5488 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */ 5489 assert( fd->pMethods->xLock==nolockLock 5490 || unixFileMutexNotheld((unixFile*)fd) 5491 ); 5492 unixEnterMutex(); /* Also mutex, for redundancy */ 5493 unixLeaveMutex(); 5494 } 5495 5496 /* 5497 ** Close a connection to shared-memory. Delete the underlying 5498 ** storage if deleteFlag is true. 5499 ** 5500 ** If there is no shared memory associated with the connection then this 5501 ** routine is a harmless no-op. 5502 */ 5503 static int unixShmUnmap( 5504 sqlite3_file *fd, /* The underlying database file */ 5505 int deleteFlag /* Delete shared-memory if true */ 5506 ){ 5507 unixShm *p; /* The connection to be closed */ 5508 unixShmNode *pShmNode; /* The underlying shared-memory file */ 5509 unixShm **pp; /* For looping over sibling connections */ 5510 unixFile *pDbFd; /* The underlying database file */ 5511 5512 pDbFd = (unixFile*)fd; 5513 p = pDbFd->pShm; 5514 if( p==0 ) return SQLITE_OK; 5515 pShmNode = p->pShmNode; 5516 5517 assert( pShmNode==pDbFd->pInode->pShmNode ); 5518 assert( pShmNode->pInode==pDbFd->pInode ); 5519 5520 /* Remove connection p from the set of connections associated 5521 ** with pShmNode */ 5522 sqlite3_mutex_enter(pShmNode->pShmMutex); 5523 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){} 5524 *pp = p->pNext; 5525 5526 /* Free the connection p */ 5527 sqlite3_free(p); 5528 pDbFd->pShm = 0; 5529 sqlite3_mutex_leave(pShmNode->pShmMutex); 5530 5531 /* If pShmNode->nRef has reached 0, then close the underlying 5532 ** shared-memory file, too */ 5533 assert( unixFileMutexNotheld(pDbFd) ); 5534 unixEnterMutex(); 5535 assert( pShmNode->nRef>0 ); 5536 pShmNode->nRef--; 5537 if( pShmNode->nRef==0 ){ 5538 if( deleteFlag && pShmNode->hShm>=0 ){ 5539 osUnlink(pShmNode->zFilename); 5540 } 5541 unixShmPurge(pDbFd); 5542 } 5543 unixLeaveMutex(); 5544 5545 return SQLITE_OK; 5546 } 5547 5548 5549 #else 5550 # define unixShmMap 0 5551 # define unixShmLock 0 5552 # define unixShmBarrier 0 5553 # define unixShmUnmap 0 5554 #endif /* #ifndef SQLITE_OMIT_WAL */ 5555 5556 #if SQLITE_MAX_MMAP_SIZE>0 5557 /* 5558 ** If it is currently memory mapped, unmap file pFd. 5559 */ 5560 static void unixUnmapfile(unixFile *pFd){ 5561 assert( pFd->nFetchOut==0 ); 5562 if( pFd->pMapRegion ){ 5563 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual); 5564 pFd->pMapRegion = 0; 5565 pFd->mmapSize = 0; 5566 pFd->mmapSizeActual = 0; 5567 } 5568 } 5569 5570 /* 5571 ** Attempt to set the size of the memory mapping maintained by file 5572 ** descriptor pFd to nNew bytes. Any existing mapping is discarded. 5573 ** 5574 ** If successful, this function sets the following variables: 5575 ** 5576 ** unixFile.pMapRegion 5577 ** unixFile.mmapSize 5578 ** unixFile.mmapSizeActual 5579 ** 5580 ** If unsuccessful, an error message is logged via sqlite3_log() and 5581 ** the three variables above are zeroed. In this case SQLite should 5582 ** continue accessing the database using the xRead() and xWrite() 5583 ** methods. 5584 */ 5585 static void unixRemapfile( 5586 unixFile *pFd, /* File descriptor object */ 5587 i64 nNew /* Required mapping size */ 5588 ){ 5589 const char *zErr = "mmap"; 5590 int h = pFd->h; /* File descriptor open on db file */ 5591 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */ 5592 u8 *pNew = 0; /* Location of new mapping */ 5593 int flags = PROT_READ; /* Flags to pass to mmap() */ 5594 5595 assert( pFd->nFetchOut==0 ); 5596 assert( nNew>pFd->mmapSize ); 5597 assert( nNew<=pFd->mmapSizeMax ); 5598 assert( nNew>0 ); 5599 assert( pFd->mmapSizeActual>=pFd->mmapSize ); 5600 assert( MAP_FAILED!=0 ); 5601 5602 #ifdef SQLITE_MMAP_READWRITE 5603 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE; 5604 #endif 5605 5606 if( pOrig ){ 5607 i64 nReuse = pFd->mmapSize & ~((int)osGetpagesize()-1); 5608 5609 /* Unmap any part of the current mapping that will not be reused */ 5610 if( nReusemmapSizeActual ){ 5611 osMunmap(&pOrig[nReuse], pFd->mmapSizeActual - nReuse); 5612 } 5613 5614 /* If nReuse is now zero, then the entire mapping was unmapped by the 5615 ** call above. In this case do not attempt to extend pOrig. */ 5616 if( nReuse>0 ){ 5617 #if HAVE_MREMAP 5618 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE); 5619 zErr = "mremap"; 5620 #else 5621 pNew = osMmap(&pOrig[nReuse], nNew-nReuse, flags, MAP_SHARED, h, nReuse); 5622 if( pNew!=MAP_FAILED ){ 5623 if( pNew!=&pOrig[nReuse] ){ 5624 osMunmap(pNew, nNew - nReuse); 5625 pNew = 0; 5626 }else{ 5627 pNew = pOrig; 5628 } 5629 } 5630 #endif 5631 5632 /* The attempt to extend the existing mapping failed. Free it. */ 5633 if( pNew==MAP_FAILED || pNew==0 ){ 5634 osMunmap(pOrig, nReuse); 5635 } 5636 } 5637 } 5638 5639 /* If pNew is still NULL, try to create an entirely new mapping. */ 5640 if( pNew==0 ){ 5641 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0); 5642 } 5643 5644 if( pNew==MAP_FAILED ){ 5645 pNew = 0; 5646 nNew = 0; 5647 unixLogError(SQLITE_OK, zErr, pFd->zPath); 5648 5649 /* If the mmap() above failed, assume that all subsequent mmap() calls 5650 ** will probably fail too. Fall back to using xRead/xWrite exclusively 5651 ** in this case. */ 5652 pFd->mmapSizeMax = 0; 5653 } 5654 pFd->pMapRegion = (void *)pNew; 5655 pFd->mmapSize = pFd->mmapSizeActual = nNew; 5656 } 5657 5658 /* 5659 ** Memory map or remap the file opened by file-descriptor pFd (if the file 5660 ** is already mapped, the existing mapping is replaced by the new). Or, if 5661 ** there already exists a mapping for this file, and there are still 5662 ** outstanding xFetch() references to it, this function is a no-op. 5663 ** 5664 ** If parameter nByte is non-negative, then it is the requested size of 5665 ** the mapping to create. Otherwise, if nByte is less than zero, then the 5666 ** requested size is the size of the file on disk. The actual size of the 5667 ** created mapping is either the requested size or the value configured 5668 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller. 5669 ** 5670 ** SQLITE_OK is returned if no error occurs (even if the mapping is not 5671 ** recreated as a result of outstanding references) or an SQLite error 5672 ** code otherwise. 5673 */ 5674 static int unixMapfile(unixFile *pFd, i64 nMap){ 5675 assert( nMap>=0 || pFd->nFetchOut==0 ); 5676 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) ); 5677 if( pFd->nFetchOut>0 ) return SQLITE_OK; 5678 5679 if( nMap<0 ){ 5680 struct stat statbuf; /* Low-level file information */ 5681 if( osFstat(pFd->h, &statbuf) ){ 5682 return SQLITE_IOERR_FSTAT; 5683 } 5684 nMap = statbuf.st_size; 5685 } 5686 if( nMap>pFd->mmapSizeMax ){ 5687 nMap = pFd->mmapSizeMax; 5688 } 5689 5690 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) ); 5691 if( nMap!=pFd->mmapSize ){ 5692 unixRemapfile(pFd, nMap); 5693 } 5694 5695 return SQLITE_OK; 5696 } 5697 #endif /* SQLITE_MAX_MMAP_SIZE>0 */ 5698 5699 /* 5700 ** If possible, return a pointer to a mapping of file fd starting at offset 5701 ** iOff. The mapping must be valid for at least nAmt bytes. 5702 ** 5703 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. 5704 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. 5705 ** Finally, if an error does occur, return an SQLite error code. The final 5706 ** value of *pp is undefined in this case. 5707 ** 5708 ** If this function does return a pointer, the caller must eventually 5709 ** release the reference by calling unixUnfetch(). 5710 */ 5711 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ 5712 #if SQLITE_MAX_MMAP_SIZE>0 5713 unixFile *pFd = (unixFile *)fd; /* The underlying database file */ 5714 #endif 5715 *pp = 0; 5716 5717 #if SQLITE_MAX_MMAP_SIZE>0 5718 if( pFd->mmapSizeMax>0 ){ 5719 /* Ensure that there is always at least a 256 byte buffer of addressable 5720 ** memory following the returned page. If the database is corrupt, 5721 ** SQLite may overread the page slightly (in practice only a few bytes, 5722 ** but 256 is safe, round, number). */ 5723 const int nEofBuffer = 256; 5724 if( pFd->pMapRegion==0 ){ 5725 int rc = unixMapfile(pFd, -1); 5726 if( rc!=SQLITE_OK ) return rc; 5727 } 5728 if( pFd->mmapSize >= (iOff+nAmt+nEofBuffer) ){ 5729 *pp = &((u8 *)pFd->pMapRegion)[iOff]; 5730 pFd->nFetchOut++; 5731 } 5732 } 5733 #endif 5734 return SQLITE_OK; 5735 } 5736 5737 /* 5738 ** If the third argument is non-NULL, then this function releases a 5739 ** reference obtained by an earlier call to unixFetch(). The second 5740 ** argument passed to this function must be the same as the corresponding 5741 ** argument that was passed to the unixFetch() invocation. 5742 ** 5743 ** Or, if the third argument is NULL, then this function is being called 5744 ** to inform the VFS layer that, according to POSIX, any existing mapping 5745 ** may now be invalid and should be unmapped. 5746 */ 5747 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){ 5748 #if SQLITE_MAX_MMAP_SIZE>0 5749 unixFile *pFd = (unixFile *)fd; /* The underlying database file */ 5750 UNUSED_PARAMETER(iOff); 5751 5752 /* If p==0 (unmap the entire file) then there must be no outstanding 5753 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference), 5754 ** then there must be at least one outstanding. */ 5755 assert( (p==0)==(pFd->nFetchOut==0) ); 5756 5757 /* If p!=0, it must match the iOff value. */ 5758 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] ); 5759 5760 if( p ){ 5761 pFd->nFetchOut--; 5762 }else{ 5763 unixUnmapfile(pFd); 5764 } 5765 5766 assert( pFd->nFetchOut>=0 ); 5767 #else 5768 UNUSED_PARAMETER(fd); 5769 UNUSED_PARAMETER(p); 5770 UNUSED_PARAMETER(iOff); 5771 #endif 5772 return SQLITE_OK; 5773 } 5774 5775 /* 5776 ** Here ends the implementation of all sqlite3_file methods. 5777 ** 5778 ********************** End sqlite3_file Methods ******************************* 5779 ******************************************************************************/ 5780 5781 /* 5782 ** This division contains definitions of sqlite3_io_methods objects that 5783 ** implement various file locking strategies. It also contains definitions 5784 ** of "finder" functions. A finder-function is used to locate the appropriate 5785 ** sqlite3_io_methods object for a particular database file. The pAppData 5786 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to 5787 ** the correct finder-function for that VFS. 5788 ** 5789 ** Most finder functions return a pointer to a fixed sqlite3_io_methods 5790 ** object. The only interesting finder-function is autolockIoFinder, which 5791 ** looks at the filesystem type and tries to guess the best locking 5792 ** strategy from that. 5793 ** 5794 ** For finder-function F, two objects are created: 5795 ** 5796 ** (1) The real finder-function named "FImpt()". 5797 ** 5798 ** (2) A constant pointer to this function named just "F". 5799 ** 5800 ** 5801 ** A pointer to the F pointer is used as the pAppData value for VFS 5802 ** objects. We have to do this instead of letting pAppData point 5803 ** directly at the finder-function since C90 rules prevent a void* 5804 ** from be cast into a function pointer. 5805 ** 5806 ** 5807 ** Each instance of this macro generates two objects: 5808 ** 5809 ** * A constant sqlite3_io_methods object call METHOD that has locking 5810 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK. 5811 ** 5812 ** * An I/O method finder function called FINDER that returns a pointer 5813 ** to the METHOD object in the previous bullet. 5814 */ 5815 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \ 5816 static const sqlite3_io_methods METHOD = { \ 5817 VERSION, /* iVersion */ \ 5818 CLOSE, /* xClose */ \ 5819 unixRead, /* xRead */ \ 5820 unixWrite, /* xWrite */ \ 5821 unixTruncate, /* xTruncate */ \ 5822 unixSync, /* xSync */ \ 5823 unixFileSize, /* xFileSize */ \ 5824 LOCK, /* xLock */ \ 5825 UNLOCK, /* xUnlock */ \ 5826 CKLOCK, /* xCheckReservedLock */ \ 5827 unixFileControl, /* xFileControl */ \ 5828 unixSectorSize, /* xSectorSize */ \ 5829 unixDeviceCharacteristics, /* xDeviceCapabilities */ \ 5830 SHMMAP, /* xShmMap */ \ 5831 unixShmLock, /* xShmLock */ \ 5832 unixShmBarrier, /* xShmBarrier */ \ 5833 unixShmUnmap, /* xShmUnmap */ \ 5834 unixFetch, /* xFetch */ \ 5835 unixUnfetch, /* xUnfetch */ \ 5836 }; \ 5837 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \ 5838 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \ 5839 return &METHOD; \ 5840 } \ 5841 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \ 5842 = FINDER##Impl; 5843 5844 /* 5845 ** Here are all of the sqlite3_io_methods objects for each of the 5846 ** locking strategies. Functions that return pointers to these methods 5847 ** are also created. 5848 */ 5849 IOMETHODS( 5850 posixIoFinder, /* Finder function name */ 5851 posixIoMethods, /* sqlite3_io_methods object name */ 5852 3, /* shared memory and mmap are enabled */ 5853 unixClose, /* xClose method */ 5854 unixLock, /* xLock method */ 5855 unixUnlock, /* xUnlock method */ 5856 unixCheckReservedLock, /* xCheckReservedLock method */ 5857 unixShmMap /* xShmMap method */ 5858 ) 5859 IOMETHODS( 5860 nolockIoFinder, /* Finder function name */ 5861 nolockIoMethods, /* sqlite3_io_methods object name */ 5862 3, /* shared memory and mmap are enabled */ 5863 nolockClose, /* xClose method */ 5864 nolockLock, /* xLock method */ 5865 nolockUnlock, /* xUnlock method */ 5866 nolockCheckReservedLock, /* xCheckReservedLock method */ 5867 0 /* xShmMap method */ 5868 ) 5869 IOMETHODS( 5870 dotlockIoFinder, /* Finder function name */ 5871 dotlockIoMethods, /* sqlite3_io_methods object name */ 5872 1, /* shared memory is disabled */ 5873 dotlockClose, /* xClose method */ 5874 dotlockLock, /* xLock method */ 5875 dotlockUnlock, /* xUnlock method */ 5876 dotlockCheckReservedLock, /* xCheckReservedLock method */ 5877 0 /* xShmMap method */ 5878 ) 5879 5880 #if SQLITE_ENABLE_LOCKING_STYLE 5881 IOMETHODS( 5882 flockIoFinder, /* Finder function name */ 5883 flockIoMethods, /* sqlite3_io_methods object name */ 5884 1, /* shared memory is disabled */ 5885 flockClose, /* xClose method */ 5886 flockLock, /* xLock method */ 5887 flockUnlock, /* xUnlock method */ 5888 flockCheckReservedLock, /* xCheckReservedLock method */ 5889 0 /* xShmMap method */ 5890 ) 5891 #endif 5892 5893 #if OS_VXWORKS 5894 IOMETHODS( 5895 semIoFinder, /* Finder function name */ 5896 semIoMethods, /* sqlite3_io_methods object name */ 5897 1, /* shared memory is disabled */ 5898 semXClose, /* xClose method */ 5899 semXLock, /* xLock method */ 5900 semXUnlock, /* xUnlock method */ 5901 semXCheckReservedLock, /* xCheckReservedLock method */ 5902 0 /* xShmMap method */ 5903 ) 5904 #endif 5905 5906 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 5907 IOMETHODS( 5908 afpIoFinder, /* Finder function name */ 5909 afpIoMethods, /* sqlite3_io_methods object name */ 5910 1, /* shared memory is disabled */ 5911 afpClose, /* xClose method */ 5912 afpLock, /* xLock method */ 5913 afpUnlock, /* xUnlock method */ 5914 afpCheckReservedLock, /* xCheckReservedLock method */ 5915 0 /* xShmMap method */ 5916 ) 5917 #endif 5918 5919 /* 5920 ** The proxy locking method is a "super-method" in the sense that it 5921 ** opens secondary file descriptors for the conch and lock files and 5922 ** it uses proxy, dot-file, AFP, and flock() locking methods on those 5923 ** secondary files. For this reason, the division that implements 5924 ** proxy locking is located much further down in the file. But we need 5925 ** to go ahead and define the sqlite3_io_methods and finder function 5926 ** for proxy locking here. So we forward declare the I/O methods. 5927 */ 5928 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 5929 static int proxyClose(sqlite3_file*); 5930 static int proxyLock(sqlite3_file*, int); 5931 static int proxyUnlock(sqlite3_file*, int); 5932 static int proxyCheckReservedLock(sqlite3_file*, int*); 5933 IOMETHODS( 5934 proxyIoFinder, /* Finder function name */ 5935 proxyIoMethods, /* sqlite3_io_methods object name */ 5936 1, /* shared memory is disabled */ 5937 proxyClose, /* xClose method */ 5938 proxyLock, /* xLock method */ 5939 proxyUnlock, /* xUnlock method */ 5940 proxyCheckReservedLock, /* xCheckReservedLock method */ 5941 0 /* xShmMap method */ 5942 ) 5943 #endif 5944 5945 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */ 5946 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 5947 IOMETHODS( 5948 nfsIoFinder, /* Finder function name */ 5949 nfsIoMethods, /* sqlite3_io_methods object name */ 5950 1, /* shared memory is disabled */ 5951 unixClose, /* xClose method */ 5952 unixLock, /* xLock method */ 5953 nfsUnlock, /* xUnlock method */ 5954 unixCheckReservedLock, /* xCheckReservedLock method */ 5955 0 /* xShmMap method */ 5956 ) 5957 #endif 5958 5959 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 5960 /* 5961 ** This "finder" function attempts to determine the best locking strategy 5962 ** for the database file "filePath". It then returns the sqlite3_io_methods 5963 ** object that implements that strategy. 5964 ** 5965 ** This is for MacOSX only. 5966 */ 5967 static const sqlite3_io_methods *autolockIoFinderImpl( 5968 const char *filePath, /* name of the database file */ 5969 unixFile *pNew /* open file object for the database file */ 5970 ){ 5971 static const struct Mapping { 5972 const char *zFilesystem; /* Filesystem type name */ 5973 const sqlite3_io_methods *pMethods; /* Appropriate locking method */ 5974 } aMap[] = { 5975 { "hfs", &posixIoMethods }, 5976 { "ufs", &posixIoMethods }, 5977 { "afpfs", &afpIoMethods }, 5978 { "smbfs", &afpIoMethods }, 5979 { "webdav", &nolockIoMethods }, 5980 { 0, 0 } 5981 }; 5982 int i; 5983 struct statfs fsInfo; 5984 struct flock lockInfo; 5985 5986 if( !filePath ){ 5987 /* If filePath==NULL that means we are dealing with a transient file 5988 ** that does not need to be locked. */ 5989 return &nolockIoMethods; 5990 } 5991 if( statfs(filePath, &fsInfo) != -1 ){ 5992 if( fsInfo.f_flags & MNT_RDONLY ){ 5993 return &nolockIoMethods; 5994 } 5995 for(i=0; aMap[i].zFilesystem; i++){ 5996 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){ 5997 return aMap[i].pMethods; 5998 } 5999 } 6000 } 6001 6002 /* Default case. Handles, amongst others, "nfs". 6003 ** Test byte-range lock using fcntl(). If the call succeeds, 6004 ** assume that the file-system supports POSIX style locks. 6005 */ 6006 lockInfo.l_len = 1; 6007 lockInfo.l_start = 0; 6008 lockInfo.l_whence = SEEK_SET; 6009 lockInfo.l_type = F_RDLCK; 6010 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { 6011 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){ 6012 return &nfsIoMethods; 6013 } else { 6014 return &posixIoMethods; 6015 } 6016 }else{ 6017 return &dotlockIoMethods; 6018 } 6019 } 6020 static const sqlite3_io_methods 6021 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl; 6022 6023 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ 6024 6025 #if OS_VXWORKS 6026 /* 6027 ** This "finder" function for VxWorks checks to see if posix advisory 6028 ** locking works. If it does, then that is what is used. If it does not 6029 ** work, then fallback to named semaphore locking. 6030 */ 6031 static const sqlite3_io_methods *vxworksIoFinderImpl( 6032 const char *filePath, /* name of the database file */ 6033 unixFile *pNew /* the open file object */ 6034 ){ 6035 struct flock lockInfo; 6036 6037 if( !filePath ){ 6038 /* If filePath==NULL that means we are dealing with a transient file 6039 ** that does not need to be locked. */ 6040 return &nolockIoMethods; 6041 } 6042 6043 /* Test if fcntl() is supported and use POSIX style locks. 6044 ** Otherwise fall back to the named semaphore method. 6045 */ 6046 lockInfo.l_len = 1; 6047 lockInfo.l_start = 0; 6048 lockInfo.l_whence = SEEK_SET; 6049 lockInfo.l_type = F_RDLCK; 6050 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { 6051 return &posixIoMethods; 6052 }else{ 6053 return &semIoMethods; 6054 } 6055 } 6056 static const sqlite3_io_methods 6057 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl; 6058 6059 #endif /* OS_VXWORKS */ 6060 6061 /* 6062 ** An abstract type for a pointer to an IO method finder function: 6063 */ 6064 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*); 6065 6066 6067 /**************************************************************************** 6068 **************************** sqlite3_vfs methods **************************** 6069 ** 6070 ** This division contains the implementation of methods on the 6071 ** sqlite3_vfs object. 6072 */ 6073 6074 /* 6075 ** Initialize the contents of the unixFile structure pointed to by pId. 6076 */ 6077 static int fillInUnixFile( 6078 sqlite3_vfs *pVfs, /* Pointer to vfs object */ 6079 int h, /* Open file descriptor of file being opened */ 6080 sqlite3_file *pId, /* Write to the unixFile structure here */ 6081 const char *zFilename, /* Name of the file being opened */ 6082 int ctrlFlags /* Zero or more UNIXFILE_* values */ 6083 ){ 6084 const sqlite3_io_methods *pLockingStyle; 6085 unixFile *pNew = (unixFile *)pId; 6086 int rc = SQLITE_OK; 6087 6088 assert( pNew->pInode==NULL ); 6089 6090 /* No locking occurs in temporary files */ 6091 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 ); 6092 6093 OSTRACE(("OPEN %-3d %s\n", h, zFilename)); 6094 pNew->h = h; 6095 pNew->pVfs = pVfs; 6096 pNew->zPath = zFilename; 6097 pNew->ctrlFlags = (u8)ctrlFlags; 6098 #if SQLITE_MAX_MMAP_SIZE>0 6099 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap; 6100 #endif 6101 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0), 6102 "psow", SQLITE_POWERSAFE_OVERWRITE) ){ 6103 pNew->ctrlFlags |= UNIXFILE_PSOW; 6104 } 6105 if( strcmp(pVfs->zName,"unix-excl")==0 ){ 6106 pNew->ctrlFlags |= UNIXFILE_EXCL; 6107 } 6108 6109 #if OS_VXWORKS 6110 if( zFilename ){ 6111 pNew->pId = vxworksFindFileId(zFilename); 6112 if( pNew->pId==0 ){ 6113 ctrlFlags |= UNIXFILE_NOLOCK; 6114 rc = SQLITE_NOMEM_BKPT; 6115 } 6116 }else{ 6117 pNew->pId = 0; 6118 } 6119 #endif 6120 6121 if( ctrlFlags & UNIXFILE_NOLOCK ){ 6122 pLockingStyle = &nolockIoMethods; 6123 }else{ 6124 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew); 6125 #if SQLITE_ENABLE_LOCKING_STYLE 6126 /* Cache zFilename in the locking context (AFP and dotlock override) for 6127 ** proxyLock activation is possible (remote proxy is based on db name) 6128 ** zFilename remains valid until file is closed, to support */ 6129 pNew->lockingContext = (void*)zFilename; 6130 #endif 6131 } 6132 6133 if( pLockingStyle == &posixIoMethods 6134 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 6135 || pLockingStyle == &nfsIoMethods 6136 #endif 6137 ){ 6138 unixEnterMutex(); 6139 rc = findInodeInfo(pNew, &pNew->pInode); 6140 if( rc!=SQLITE_OK ){ 6141 /* If an error occurred in findInodeInfo(), close the file descriptor 6142 ** immediately, before releasing the mutex. findInodeInfo() may fail 6143 ** in two scenarios: 6144 ** 6145 ** (a) A call to fstat() failed. 6146 ** (b) A malloc failed. 6147 ** 6148 ** Scenario (b) may only occur if the process is holding no other 6149 ** file descriptors open on the same file. If there were other file 6150 ** descriptors on this file, then no malloc would be required by 6151 ** findInodeInfo(). If this is the case, it is quite safe to close 6152 ** handle h - as it is guaranteed that no posix locks will be released 6153 ** by doing so. 6154 ** 6155 ** If scenario (a) caused the error then things are not so safe. The 6156 ** implicit assumption here is that if fstat() fails, things are in 6157 ** such bad shape that dropping a lock or two doesn't matter much. 6158 */ 6159 robust_close(pNew, h, __LINE__); 6160 h = -1; 6161 } 6162 unixLeaveMutex(); 6163 } 6164 6165 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) 6166 else if( pLockingStyle == &afpIoMethods ){ 6167 /* AFP locking uses the file path so it needs to be included in 6168 ** the afpLockingContext. 6169 */ 6170 afpLockingContext *pCtx; 6171 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) ); 6172 if( pCtx==0 ){ 6173 rc = SQLITE_NOMEM_BKPT; 6174 }else{ 6175 /* NB: zFilename exists and remains valid until the file is closed 6176 ** according to requirement F11141. So we do not need to make a 6177 ** copy of the filename. */ 6178 pCtx->dbPath = zFilename; 6179 pCtx->reserved = 0; 6180 srandomdev(); 6181 unixEnterMutex(); 6182 rc = findInodeInfo(pNew, &pNew->pInode); 6183 if( rc!=SQLITE_OK ){ 6184 sqlite3_free(pNew->lockingContext); 6185 robust_close(pNew, h, __LINE__); 6186 h = -1; 6187 } 6188 unixLeaveMutex(); 6189 } 6190 } 6191 #endif 6192 6193 else if( pLockingStyle == &dotlockIoMethods ){ 6194 /* Dotfile locking uses the file path so it needs to be included in 6195 ** the dotlockLockingContext 6196 */ 6197 char *zLockFile; 6198 int nFilename; 6199 assert( zFilename!=0 ); 6200 nFilename = (int)strlen(zFilename) + 6; 6201 zLockFile = (char *)sqlite3_malloc64(nFilename); 6202 if( zLockFile==0 ){ 6203 rc = SQLITE_NOMEM_BKPT; 6204 }else{ 6205 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename); 6206 } 6207 pNew->lockingContext = zLockFile; 6208 } 6209 6210 #if OS_VXWORKS 6211 else if( pLockingStyle == &semIoMethods ){ 6212 /* Named semaphore locking uses the file path so it needs to be 6213 ** included in the semLockingContext 6214 */ 6215 unixEnterMutex(); 6216 rc = findInodeInfo(pNew, &pNew->pInode); 6217 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){ 6218 char *zSemName = pNew->pInode->aSemName; 6219 int n; 6220 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem", 6221 pNew->pId->zCanonicalName); 6222 for(n=1; zSemName[n]; n++){ 6223 if( zSemName[n]=='/' && !sqlite3FaultSim(801) ) zSemName[n] = '_'; 6224 } 6225 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1); 6226 if( pNew->pInode->pSem == SEM_FAILED ){ 6227 rc = SQLITE_NOMEM_BKPT; 6228 pNew->pInode->aSemName[0] = '\0'; 6229 releaseInodeInfo(pNew); 6230 pNew->pInode = 0; 6231 } 6232 } 6233 unixLeaveMutex(); 6234 } 6235 #endif 6236 6237 storeLastErrno(pNew, 0); 6238 #if OS_VXWORKS 6239 if( rc!=SQLITE_OK ){ 6240 if( h>=0 ){ 6241 robust_close(pNew, h, __LINE__); 6242 h = -1; 6243 } 6244 if( pNew->ctrlFlags & UNIXFILE_DELETE ){ 6245 osUnlink(zFilename); 6246 } 6247 if( pNew->pId ){ 6248 vxworksReleaseFileId(pNew->pId); 6249 pNew->pId = 0; 6250 } 6251 } 6252 #endif 6253 if( rc!=SQLITE_OK ){ 6254 if( h>=0 ) robust_close(pNew, h, __LINE__); 6255 }else{ 6256 pId->pMethods = pLockingStyle; 6257 OpenCounter(+1); 6258 verifyDbFile(pNew); 6259 } 6260 return rc; 6261 } 6262 6263 /* 6264 ** Return the name of a directory in which to put temporary files. 6265 ** If no suitable temporary file directory can be found, return NULL. 6266 ** 6267 ** The return value might be a string obtained from getenv() and so 6268 ** the return value should not be used after any call to setenv() or 6269 ** putenv() as that value might have been freed. 6270 */ 6271 static const char *unixTempFileDir(void){ 6272 unsigned int i; 6273 struct stat buf; 6274 const char *zDir; 6275 6276 for(i=0; i<7; i++){ 6277 switch( i ){ 6278 case 0: zDir = sqlite3_temp_directory; break; 6279 case 1: zDir = getenv("SQLITE_TMPDIR"); break; 6280 case 2: zDir = getenv("TMPDIR"); break; 6281 case 3: zDir = "/var/tmp"; break; 6282 case 4: zDir = "/usr/tmp"; break; 6283 case 5: zDir = "/tmp"; break; 6284 default: zDir = "."; break; 6285 } 6286 if( zDir!=0 6287 #if OS_VXWORKS 6288 && zDir[0]=='/' 6289 #endif 6290 && osStat(zDir, &buf)==0 6291 && S_ISDIR(buf.st_mode) 6292 && osAccess(zDir, 03)==0 6293 ){ 6294 return zDir; 6295 } 6296 } 6297 return 0; 6298 } 6299 6300 /* 6301 ** Create a temporary file name in zBuf. zBuf must be allocated 6302 ** by the calling process and must be big enough to hold at least 6303 ** pVfs->mxPathname bytes. 6304 */ 6305 static int unixGetTempname(int nBuf, char *zBuf){ 6306 const char *zDir; 6307 int iLimit = 0; 6308 int rc = SQLITE_OK; 6309 6310 /* It's odd to simulate an io-error here, but really this is just 6311 ** using the io-error infrastructure to test that SQLite handles this 6312 ** function failing. 6313 */ 6314 zBuf[0] = 0; 6315 SimulateIOError( return SQLITE_IOERR ); 6316 6317 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR)); 6318 zDir = unixTempFileDir(); 6319 if( zDir==0 ){ 6320 rc = SQLITE_IOERR_GETTEMPPATH; 6321 }else{ 6322 do{ 6323 u64 r; 6324 sqlite3_randomness(sizeof(r), &r); 6325 assert( nBuf>2 ); 6326 zBuf[nBuf-2] = 0; 6327 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c", 6328 zDir, r, 0); 6329 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ){ 6330 rc = SQLITE_ERROR; 6331 break; 6332 } 6333 }while( osAccess(zBuf,0)==0 ); 6334 } 6335 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR)); 6336 return rc; 6337 } 6338 6339 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) 6340 /* 6341 ** Routine to transform a unixFile into a proxy-locking unixFile. 6342 ** Implementation in the proxy-lock division, but used by unixOpen() 6343 ** if SQLITE_PREFER_PROXY_LOCKING is defined. 6344 */ 6345 static int proxyTransformUnixFile(unixFile*, const char*); 6346 #endif 6347 6348 /* 6349 ** Search for an unused file descriptor that was opened on the database 6350 ** file (not a journal or super-journal file) identified by pathname 6351 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second 6352 ** argument to this function. 6353 ** 6354 ** Such a file descriptor may exist if a database connection was closed 6355 ** but the associated file descriptor could not be closed because some 6356 ** other file descriptor open on the same file is holding a file-lock. 6357 ** Refer to comments in the unixClose() function and the lengthy comment 6358 ** describing "Posix Advisory Locking" at the start of this file for 6359 ** further details. Also, ticket #4018. 6360 ** 6361 ** If a suitable file descriptor is found, then it is returned. If no 6362 ** such file descriptor is located, -1 is returned. 6363 */ 6364 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){ 6365 UnixUnusedFd *pUnused = 0; 6366 6367 /* Do not search for an unused file descriptor on vxworks. Not because 6368 ** vxworks would not benefit from the change (it might, we're not sure), 6369 ** but because no way to test it is currently available. It is better 6370 ** not to risk breaking vxworks support for the sake of such an obscure 6371 ** feature. */ 6372 #if !OS_VXWORKS 6373 struct stat sStat; /* Results of stat() call */ 6374 6375 unixEnterMutex(); 6376 6377 /* A stat() call may fail for various reasons. If this happens, it is 6378 ** almost certain that an open() call on the same path will also fail. 6379 ** For this reason, if an error occurs in the stat() call here, it is 6380 ** ignored and -1 is returned. The caller will try to open a new file 6381 ** descriptor on the same path, fail, and return an error to SQLite. 6382 ** 6383 ** Even if a subsequent open() call does succeed, the consequences of 6384 ** not searching for a reusable file descriptor are not dire. */ 6385 if( inodeList!=0 && 0==osStat(zPath, &sStat) ){ 6386 unixInodeInfo *pInode; 6387 6388 pInode = inodeList; 6389 while( pInode && (pInode->fileId.dev!=sStat.st_dev 6390 || pInode->fileId.ino!=(u64)sStat.st_ino) ){ 6391 pInode = pInode->pNext; 6392 } 6393 if( pInode ){ 6394 UnixUnusedFd **pp; 6395 assert( sqlite3_mutex_notheld(pInode->pLockMutex) ); 6396 sqlite3_mutex_enter(pInode->pLockMutex); 6397 flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE); 6398 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext)); 6399 pUnused = *pp; 6400 if( pUnused ){ 6401 *pp = pUnused->pNext; 6402 } 6403 sqlite3_mutex_leave(pInode->pLockMutex); 6404 } 6405 } 6406 unixLeaveMutex(); 6407 #endif /* if !OS_VXWORKS */ 6408 return pUnused; 6409 } 6410 6411 /* 6412 ** Find the mode, uid and gid of file zFile. 6413 */ 6414 static int getFileMode( 6415 const char *zFile, /* File name */ 6416 mode_t *pMode, /* OUT: Permissions of zFile */ 6417 uid_t *pUid, /* OUT: uid of zFile. */ 6418 gid_t *pGid /* OUT: gid of zFile. */ 6419 ){ 6420 struct stat sStat; /* Output of stat() on database file */ 6421 int rc = SQLITE_OK; 6422 if( 0==osStat(zFile, &sStat) ){ 6423 *pMode = sStat.st_mode & 0777; 6424 *pUid = sStat.st_uid; 6425 *pGid = sStat.st_gid; 6426 }else{ 6427 rc = SQLITE_IOERR_FSTAT; 6428 } 6429 return rc; 6430 } 6431 6432 /* 6433 ** This function is called by unixOpen() to determine the unix permissions 6434 ** to create new files with. If no error occurs, then SQLITE_OK is returned 6435 ** and a value suitable for passing as the third argument to open(2) is 6436 ** written to *pMode. If an IO error occurs, an SQLite error code is 6437 ** returned and the value of *pMode is not modified. 6438 ** 6439 ** In most cases, this routine sets *pMode to 0, which will become 6440 ** an indication to robust_open() to create the file using 6441 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask. 6442 ** But if the file being opened is a WAL or regular journal file, then 6443 ** this function queries the file-system for the permissions on the 6444 ** corresponding database file and sets *pMode to this value. Whenever 6445 ** possible, WAL and journal files are created using the same permissions 6446 ** as the associated database file. 6447 ** 6448 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the 6449 ** original filename is unavailable. But 8_3_NAMES is only used for 6450 ** FAT filesystems and permissions do not matter there, so just use 6451 ** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero. 6452 */ 6453 static int findCreateFileMode( 6454 const char *zPath, /* Path of file (possibly) being created */ 6455 int flags, /* Flags passed as 4th argument to xOpen() */ 6456 mode_t *pMode, /* OUT: Permissions to open file with */ 6457 uid_t *pUid, /* OUT: uid to set on the file */ 6458 gid_t *pGid /* OUT: gid to set on the file */ 6459 ){ 6460 int rc = SQLITE_OK; /* Return Code */ 6461 *pMode = 0; 6462 *pUid = 0; 6463 *pGid = 0; 6464 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){ 6465 char zDb[MAX_PATHNAME+1]; /* Database file path */ 6466 int nDb; /* Number of valid bytes in zDb */ 6467 6468 /* zPath is a path to a WAL or journal file. The following block derives 6469 ** the path to the associated database file from zPath. This block handles 6470 ** the following naming conventions: 6471 ** 6472 ** "-journal" 6473 ** "-wal" 6474 ** "-journalNN" 6475 ** "-walNN" 6476 ** 6477 ** where NN is a decimal number. The NN naming schemes are 6478 ** used by the test_multiplex.c module. 6479 ** 6480 ** In normal operation, the journal file name will always contain 6481 ** a '-' character. However in 8+3 filename mode, or if a corrupt 6482 ** rollback journal specifies a super-journal with a goofy name, then 6483 ** the '-' might be missing or the '-' might be the first character in 6484 ** the filename. In that case, just return SQLITE_OK with *pMode==0. 6485 */ 6486 nDb = sqlite3Strlen30(zPath) - 1; 6487 while( nDb>0 && zPath[nDb]!='.' ){ 6488 if( zPath[nDb]=='-' ){ 6489 memcpy(zDb, zPath, nDb); 6490 zDb[nDb] = '\0'; 6491 rc = getFileMode(zDb, pMode, pUid, pGid); 6492 break; 6493 } 6494 nDb--; 6495 } 6496 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){ 6497 *pMode = 0600; 6498 }else if( flags & SQLITE_OPEN_URI ){ 6499 /* If this is a main database file and the file was opened using a URI 6500 ** filename, check for the "modeof" parameter. If present, interpret 6501 ** its value as a filename and try to copy the mode, uid and gid from 6502 ** that file. */ 6503 const char *z = sqlite3_uri_parameter(zPath, "modeof"); 6504 if( z ){ 6505 rc = getFileMode(z, pMode, pUid, pGid); 6506 } 6507 } 6508 return rc; 6509 } 6510 6511 /* 6512 ** Open the file zPath. 6513 ** 6514 ** Previously, the SQLite OS layer used three functions in place of this 6515 ** one: 6516 ** 6517 ** sqlite3OsOpenReadWrite(); 6518 ** sqlite3OsOpenReadOnly(); 6519 ** sqlite3OsOpenExclusive(); 6520 ** 6521 ** These calls correspond to the following combinations of flags: 6522 ** 6523 ** ReadWrite() -> (READWRITE | CREATE) 6524 ** ReadOnly() -> (READONLY) 6525 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE) 6526 ** 6527 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If 6528 ** true, the file was configured to be automatically deleted when the 6529 ** file handle closed. To achieve the same effect using this new 6530 ** interface, add the DELETEONCLOSE flag to those specified above for 6531 ** OpenExclusive(). 6532 */ 6533 static int unixOpen( 6534 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */ 6535 const char *zPath, /* Pathname of file to be opened */ 6536 sqlite3_file *pFile, /* The file descriptor to be filled in */ 6537 int flags, /* Input flags to control the opening */ 6538 int *pOutFlags /* Output flags returned to SQLite core */ 6539 ){ 6540 unixFile *p = (unixFile *)pFile; 6541 int fd = -1; /* File descriptor returned by open() */ 6542 int openFlags = 0; /* Flags to pass to open() */ 6543 int eType = flags&0x0FFF00; /* Type of file to open */ 6544 int noLock; /* True to omit locking primitives */ 6545 int rc = SQLITE_OK; /* Function Return Code */ 6546 int ctrlFlags = 0; /* UNIXFILE_* flags */ 6547 6548 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); 6549 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); 6550 int isCreate = (flags & SQLITE_OPEN_CREATE); 6551 int isReadonly = (flags & SQLITE_OPEN_READONLY); 6552 int isReadWrite = (flags & SQLITE_OPEN_READWRITE); 6553 #if SQLITE_ENABLE_LOCKING_STYLE 6554 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY); 6555 #endif 6556 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE 6557 struct statfs fsInfo; 6558 #endif 6559 6560 /* If creating a super- or main-file journal, this function will open 6561 ** a file-descriptor on the directory too. The first time unixSync() 6562 ** is called the directory file descriptor will be fsync()ed and close()d. 6563 */ 6564 int isNewJrnl = (isCreate && ( 6565 eType==SQLITE_OPEN_SUPER_JOURNAL 6566 || eType==SQLITE_OPEN_MAIN_JOURNAL 6567 || eType==SQLITE_OPEN_WAL 6568 )); 6569 6570 /* If argument zPath is a NULL pointer, this function is required to open 6571 ** a temporary file. Use this buffer to store the file name in. 6572 */ 6573 char zTmpname[MAX_PATHNAME+2]; 6574 const char *zName = zPath; 6575 6576 /* Check the following statements are true: 6577 ** 6578 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and 6579 ** (b) if CREATE is set, then READWRITE must also be set, and 6580 ** (c) if EXCLUSIVE is set, then CREATE must also be set. 6581 ** (d) if DELETEONCLOSE is set, then CREATE must also be set. 6582 */ 6583 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); 6584 assert(isCreate==0 || isReadWrite); 6585 assert(isExclusive==0 || isCreate); 6586 assert(isDelete==0 || isCreate); 6587 6588 /* The main DB, main journal, WAL file and super-journal are never 6589 ** automatically deleted. Nor are they ever temporary files. */ 6590 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); 6591 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); 6592 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL ); 6593 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL ); 6594 6595 /* Assert that the upper layer has set one of the "file-type" flags. */ 6596 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB 6597 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 6598 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_SUPER_JOURNAL 6599 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL 6600 ); 6601 6602 #if OS_VXWORKS 6603 /* The file-ID mechanism used in Vxworks requires that all pathnames 6604 ** provided to unixOpen must be absolute pathnames. */ 6605 if( zPath!=0 && zPath[0]!='/' ){ return SQLITE_CANTOPEN; } 6606 #endif 6607 6608 /* Detect a pid change and reset the PRNG. There is a race condition 6609 ** here such that two or more threads all trying to open databases at 6610 ** the same instant might all reset the PRNG. But multiple resets 6611 ** are harmless. 6612 */ 6613 if( randomnessPid!=osGetpid(0) ){ 6614 randomnessPid = osGetpid(0); 6615 sqlite3_randomness(0,0); 6616 } 6617 memset(p, 0, sizeof(unixFile)); 6618 6619 #ifdef SQLITE_ASSERT_NO_FILES 6620 /* Applications that never read or write a persistent disk files */ 6621 assert( zName==0 ); 6622 #endif 6623 6624 if( eType==SQLITE_OPEN_MAIN_DB ){ 6625 UnixUnusedFd *pUnused; 6626 pUnused = findReusableFd(zName, flags); 6627 if( pUnused ){ 6628 fd = pUnused->fd; 6629 }else{ 6630 pUnused = sqlite3_malloc64(sizeof(*pUnused)); 6631 if( !pUnused ){ 6632 return SQLITE_NOMEM_BKPT; 6633 } 6634 } 6635 p->pPreallocatedUnused = pUnused; 6636 6637 /* Database filenames are double-zero terminated if they are not 6638 ** URIs with parameters. Hence, they can always be passed into 6639 ** sqlite3_uri_parameter(). */ 6640 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 ); 6641 6642 }else if( !zName ){ 6643 /* If zName is NULL, the upper layer is requesting a temp file. */ 6644 assert( isDelete ); 6645 assert( !isNewJrnl ); 6646 assert( isExclusive ); 6647 assert( isReadWrite ); 6648 #if defined(__linux__) && defined(O_TMPFILE) 6649 /* On systems that support O_TMPFILE, use that flag to create a more 6650 ** secure temporary file that cannot be accessed by other processes 6651 */ 6652 zName = unixTempFileDir(); 6653 if( zName 6654 && (fd = robust_open(zName, O_RDWR|O_EXCL|O_TMPFILE, 0600))>=0 6655 ){ 6656 if( pOutFlags ){ 6657 *pOutFlags = flags; 6658 } 6659 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags|UNIXFILE_NOLOCK); 6660 goto open_finished; 6661 } 6662 #endif 6663 rc = unixGetTempname(pVfs->mxPathname, zTmpname); 6664 if( rc!=SQLITE_OK ){ 6665 return rc; 6666 } 6667 zName = zTmpname; 6668 6669 /* Generated temporary filenames are always double-zero terminated 6670 ** for use by sqlite3_uri_parameter(). */ 6671 assert( zName[strlen(zName)+1]==0 ); 6672 } 6673 6674 /* Determine the value of the flags parameter passed to POSIX function 6675 ** open(). These must be calculated even if open() is not called, as 6676 ** they may be stored as part of the file handle and used by the 6677 ** 'conch file' locking functions later on. */ 6678 if( isReadonly ) openFlags |= O_RDONLY; 6679 if( isReadWrite ) openFlags |= O_RDWR; 6680 if( isCreate ) openFlags |= O_CREAT; 6681 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW); 6682 openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW); 6683 6684 if( fd<0 ){ 6685 mode_t openMode; /* Permissions to create file with */ 6686 uid_t uid; /* Userid for the file */ 6687 gid_t gid; /* Groupid for the file */ 6688 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid); 6689 if( rc!=SQLITE_OK ){ 6690 assert( !p->pPreallocatedUnused ); 6691 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL ); 6692 return rc; 6693 } 6694 fd = robust_open(zName, openFlags, openMode); 6695 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags)); 6696 assert( !isExclusive || (openFlags & O_CREAT)!=0 ); 6697 if( fd<0 ){ 6698 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){ 6699 /* If unable to create a journal because the directory is not 6700 ** writable, change the error code to indicate that. */ 6701 rc = SQLITE_READONLY_DIRECTORY; 6702 }else if( errno!=EISDIR && isReadWrite ){ 6703 /* Failed to open the file for read/write access. Try read-only. */ 6704 UnixUnusedFd *pReadonly = 0; 6705 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); 6706 openFlags &= ~(O_RDWR|O_CREAT); 6707 flags |= SQLITE_OPEN_READONLY; 6708 openFlags |= O_RDONLY; 6709 isReadonly = 1; 6710 pReadonly = findReusableFd(zName, flags); 6711 if( pReadonly ){ 6712 fd = pReadonly->fd; 6713 sqlite3_free(pReadonly); 6714 }else{ 6715 fd = robust_open(zName, openFlags, openMode); 6716 } 6717 } 6718 } 6719 if( fd<0 ){ 6720 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName); 6721 if( rc==SQLITE_OK ) rc = rc2; 6722 goto open_finished; 6723 } 6724 6725 /* The owner of the rollback journal or WAL file should always be the 6726 ** same as the owner of the database file. Try to ensure that this is 6727 ** the case. The chown() system call will be a no-op if the current 6728 ** process lacks root privileges, be we should at least try. Without 6729 ** this step, if a root process opens a database file, it can leave 6730 ** behinds a journal/WAL that is owned by root and hence make the 6731 ** database inaccessible to unprivileged processes. 6732 ** 6733 ** If openMode==0, then that means uid and gid are not set correctly 6734 ** (probably because SQLite is configured to use 8+3 filename mode) and 6735 ** in that case we do not want to attempt the chown(). 6736 */ 6737 if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){ 6738 robustFchown(fd, uid, gid); 6739 } 6740 } 6741 assert( fd>=0 ); 6742 if( pOutFlags ){ 6743 *pOutFlags = flags; 6744 } 6745 6746 if( p->pPreallocatedUnused ){ 6747 p->pPreallocatedUnused->fd = fd; 6748 p->pPreallocatedUnused->flags = 6749 flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE); 6750 } 6751 6752 if( isDelete ){ 6753 #if OS_VXWORKS 6754 zPath = zName; 6755 #elif defined(SQLITE_UNLINK_AFTER_CLOSE) 6756 zPath = sqlite3_mprintf("%s", zName); 6757 if( zPath==0 ){ 6758 robust_close(p, fd, __LINE__); 6759 return SQLITE_NOMEM_BKPT; 6760 } 6761 #else 6762 osUnlink(zName); 6763 #endif 6764 } 6765 #if SQLITE_ENABLE_LOCKING_STYLE 6766 else{ 6767 p->openFlags = openFlags; 6768 } 6769 #endif 6770 6771 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE 6772 if( fstatfs(fd, &fsInfo) == -1 ){ 6773 storeLastErrno(p, errno); 6774 robust_close(p, fd, __LINE__); 6775 return SQLITE_IOERR_ACCESS; 6776 } 6777 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) { 6778 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS; 6779 } 6780 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) { 6781 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS; 6782 } 6783 #endif 6784 6785 /* Set up appropriate ctrlFlags */ 6786 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE; 6787 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY; 6788 noLock = eType!=SQLITE_OPEN_MAIN_DB; 6789 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK; 6790 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC; 6791 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI; 6792 6793 #if SQLITE_ENABLE_LOCKING_STYLE 6794 #if SQLITE_PREFER_PROXY_LOCKING 6795 isAutoProxy = 1; 6796 #endif 6797 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){ 6798 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING"); 6799 int useProxy = 0; 6800 6801 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 6802 ** never use proxy, NULL means use proxy for non-local files only. */ 6803 if( envforce!=NULL ){ 6804 useProxy = atoi(envforce)>0; 6805 }else{ 6806 useProxy = !(fsInfo.f_flags&MNT_LOCAL); 6807 } 6808 if( useProxy ){ 6809 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); 6810 if( rc==SQLITE_OK ){ 6811 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:"); 6812 if( rc!=SQLITE_OK ){ 6813 /* Use unixClose to clean up the resources added in fillInUnixFile 6814 ** and clear all the structure's references. Specifically, 6815 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 6816 */ 6817 unixClose(pFile); 6818 return rc; 6819 } 6820 } 6821 goto open_finished; 6822 } 6823 } 6824 #endif 6825 6826 assert( zPath==0 6827 || zPath[0]=='/' 6828 || eType==SQLITE_OPEN_SUPER_JOURNAL 6829 || eType==SQLITE_OPEN_MAIN_JOURNAL 6830 || eType==SQLITE_OPEN_TEMP_JOURNAL 6831 ); 6832 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); 6833 6834 open_finished: 6835 if( rc!=SQLITE_OK ){ 6836 sqlite3_free(p->pPreallocatedUnused); 6837 } 6838 return rc; 6839 } 6840 6841 6842 /* 6843 ** Delete the file at zPath. If the dirSync argument is true, fsync() 6844 ** the directory after deleting the file. 6845 */ 6846 static int unixDelete( 6847 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */ 6848 const char *zPath, /* Name of file to be deleted */ 6849 int dirSync /* If true, fsync() directory after deleting file */ 6850 ){ 6851 int rc = SQLITE_OK; 6852 UNUSED_PARAMETER(NotUsed); 6853 SimulateIOError(return SQLITE_IOERR_DELETE); 6854 if( osUnlink(zPath)==(-1) ){ 6855 if( errno==ENOENT 6856 #if OS_VXWORKS 6857 || osAccess(zPath,0)!=0 6858 #endif 6859 ){ 6860 rc = SQLITE_IOERR_DELETE_NOENT; 6861 }else{ 6862 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath); 6863 } 6864 return rc; 6865 } 6866 #ifndef SQLITE_DISABLE_DIRSYNC 6867 if( (dirSync & 1)!=0 ){ 6868 int fd; 6869 rc = osOpenDirectory(zPath, &fd); 6870 if( rc==SQLITE_OK ){ 6871 if( full_fsync(fd,0,0) ){ 6872 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath); 6873 } 6874 robust_close(0, fd, __LINE__); 6875 }else{ 6876 assert( rc==SQLITE_CANTOPEN ); 6877 rc = SQLITE_OK; 6878 } 6879 } 6880 #endif 6881 return rc; 6882 } 6883 6884 /* 6885 ** Test the existence of or access permissions of file zPath. The 6886 ** test performed depends on the value of flags: 6887 ** 6888 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists 6889 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable. 6890 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable. 6891 ** 6892 ** Otherwise return 0. 6893 */ 6894 static int unixAccess( 6895 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */ 6896 const char *zPath, /* Path of the file to examine */ 6897 int flags, /* What do we want to learn about the zPath file? */ 6898 int *pResOut /* Write result boolean here */ 6899 ){ 6900 UNUSED_PARAMETER(NotUsed); 6901 SimulateIOError( return SQLITE_IOERR_ACCESS; ); 6902 assert( pResOut!=0 ); 6903 6904 /* The spec says there are three possible values for flags. But only 6905 ** two of them are actually used */ 6906 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE ); 6907 6908 if( flags==SQLITE_ACCESS_EXISTS ){ 6909 struct stat buf; 6910 *pResOut = 0==osStat(zPath, &buf) && 6911 (!S_ISREG(buf.st_mode) || buf.st_size>0); 6912 }else{ 6913 *pResOut = osAccess(zPath, W_OK|R_OK)==0; 6914 } 6915 return SQLITE_OK; 6916 } 6917 6918 /* 6919 ** A pathname under construction 6920 */ 6921 typedef struct DbPath DbPath; 6922 struct DbPath { 6923 int rc; /* Non-zero following any error */ 6924 int nSymlink; /* Number of symlinks resolved */ 6925 char *zOut; /* Write the pathname here */ 6926 int nOut; /* Bytes of space available to zOut[] */ 6927 int nUsed; /* Bytes of zOut[] currently being used */ 6928 }; 6929 6930 /* Forward reference */ 6931 static void appendAllPathElements(DbPath*,const char*); 6932 6933 /* 6934 ** Append a single path element to the DbPath under construction 6935 */ 6936 static void appendOnePathElement( 6937 DbPath *pPath, /* Path under construction, to which to append zName */ 6938 const char *zName, /* Name to append to pPath. Not zero-terminated */ 6939 int nName /* Number of significant bytes in zName */ 6940 ){ 6941 assert( nName>0 ); 6942 assert( zName!=0 ); 6943 if( zName[0]=='.' ){ 6944 if( nName==1 ) return; 6945 if( zName[1]=='.' && nName==2 ){ 6946 if( pPath->nUsed>1 ){ 6947 assert( pPath->zOut[0]=='/' ); 6948 while( pPath->zOut[--pPath->nUsed]!='/' ){} 6949 } 6950 return; 6951 } 6952 } 6953 if( pPath->nUsed + nName + 2 >= pPath->nOut ){ 6954 pPath->rc = SQLITE_ERROR; 6955 return; 6956 } 6957 pPath->zOut[pPath->nUsed++] = '/'; 6958 memcpy(&pPath->zOut[pPath->nUsed], zName, nName); 6959 pPath->nUsed += nName; 6960 #if defined(HAVE_READLINK) && defined(HAVE_LSTAT) 6961 if( pPath->rc==SQLITE_OK ){ 6962 const char *zIn; 6963 struct stat buf; 6964 pPath->zOut[pPath->nUsed] = 0; 6965 zIn = pPath->zOut; 6966 if( osLstat(zIn, &buf)!=0 ){ 6967 if( errno!=ENOENT ){ 6968 pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn); 6969 } 6970 }else if( S_ISLNK(buf.st_mode) ){ 6971 ssize_t got; 6972 char zLnk[SQLITE_MAX_PATHLEN+2]; 6973 if( pPath->nSymlink++ > SQLITE_MAX_SYMLINK ){ 6974 pPath->rc = SQLITE_CANTOPEN_BKPT; 6975 return; 6976 } 6977 got = osReadlink(zIn, zLnk, sizeof(zLnk)-2); 6978 if( got<=0 || got>=(ssize_t)sizeof(zLnk)-2 ){ 6979 pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn); 6980 return; 6981 } 6982 zLnk[got] = 0; 6983 if( zLnk[0]=='/' ){ 6984 pPath->nUsed = 0; 6985 }else{ 6986 pPath->nUsed -= nName + 1; 6987 } 6988 appendAllPathElements(pPath, zLnk); 6989 } 6990 } 6991 #endif 6992 } 6993 6994 /* 6995 ** Append all path elements in zPath to the DbPath under construction. 6996 */ 6997 static void appendAllPathElements( 6998 DbPath *pPath, /* Path under construction, to which to append zName */ 6999 const char *zPath /* Path to append to pPath. Is zero-terminated */ 7000 ){ 7001 int i = 0; 7002 int j = 0; 7003 do{ 7004 while( zPath[i] && zPath[i]!='/' ){ i++; } 7005 if( i>j ){ 7006 appendOnePathElement(pPath, &zPath[j], i-j); 7007 } 7008 j = i+1; 7009 }while( zPath[i++] ); 7010 } 7011 7012 /* 7013 ** Turn a relative pathname into a full pathname. The relative path 7014 ** is stored as a nul-terminated string in the buffer pointed to by 7015 ** zPath. 7016 ** 7017 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 7018 ** (in this case, MAX_PATHNAME bytes). The full-path is written to 7019 ** this buffer before returning. 7020 */ 7021 static int unixFullPathname( 7022 sqlite3_vfs *pVfs, /* Pointer to vfs object */ 7023 const char *zPath, /* Possibly relative input path */ 7024 int nOut, /* Size of output buffer in bytes */ 7025 char *zOut /* Output buffer */ 7026 ){ 7027 DbPath path; 7028 UNUSED_PARAMETER(pVfs); 7029 path.rc = 0; 7030 path.nUsed = 0; 7031 path.nSymlink = 0; 7032 path.nOut = nOut; 7033 path.zOut = zOut; 7034 if( zPath[0]!='/' ){ 7035 char zPwd[SQLITE_MAX_PATHLEN+2]; 7036 if( osGetcwd(zPwd, sizeof(zPwd)-2)==0 ){ 7037 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath); 7038 } 7039 appendAllPathElements(&path, zPwd); 7040 } 7041 appendAllPathElements(&path, zPath); 7042 zOut[path.nUsed] = 0; 7043 if( path.rc || path.nUsed<2 ) return SQLITE_CANTOPEN_BKPT; 7044 if( path.nSymlink ) return SQLITE_OK_SYMLINK; 7045 return SQLITE_OK; 7046 } 7047 7048 #ifndef SQLITE_OMIT_LOAD_EXTENSION 7049 /* 7050 ** Interfaces for opening a shared library, finding entry points 7051 ** within the shared library, and closing the shared library. 7052 */ 7053 #include 7054 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){ 7055 UNUSED_PARAMETER(NotUsed); 7056 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL); 7057 } 7058 7059 /* 7060 ** SQLite calls this function immediately after a call to unixDlSym() or 7061 ** unixDlOpen() fails (returns a null pointer). If a more detailed error 7062 ** message is available, it is written to zBufOut. If no error message 7063 ** is available, zBufOut is left unmodified and SQLite uses a default 7064 ** error message. 7065 */ 7066 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){ 7067 const char *zErr; 7068 UNUSED_PARAMETER(NotUsed); 7069 unixEnterMutex(); 7070 zErr = dlerror(); 7071 if( zErr ){ 7072 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr); 7073 } 7074 unixLeaveMutex(); 7075 } 7076 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){ 7077 /* 7078 ** GCC with -pedantic-errors says that C90 does not allow a void* to be 7079 ** cast into a pointer to a function. And yet the library dlsym() routine 7080 ** returns a void* which is really a pointer to a function. So how do we 7081 ** use dlsym() with -pedantic-errors? 7082 ** 7083 ** Variable x below is defined to be a pointer to a function taking 7084 ** parameters void* and const char* and returning a pointer to a function. 7085 ** We initialize x by assigning it a pointer to the dlsym() function. 7086 ** (That assignment requires a cast.) Then we call the function that 7087 ** x points to. 7088 ** 7089 ** This work-around is unlikely to work correctly on any system where 7090 ** you really cannot cast a function pointer into void*. But then, on the 7091 ** other hand, dlsym() will not work on such a system either, so we have 7092 ** not really lost anything. 7093 */ 7094 void (*(*x)(void*,const char*))(void); 7095 UNUSED_PARAMETER(NotUsed); 7096 x = (void(*(*)(void*,const char*))(void))dlsym; 7097 return (*x)(p, zSym); 7098 } 7099 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){ 7100 UNUSED_PARAMETER(NotUsed); 7101 dlclose(pHandle); 7102 } 7103 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ 7104 #define unixDlOpen 0 7105 #define unixDlError 0 7106 #define unixDlSym 0 7107 #define unixDlClose 0 7108 #endif 7109 7110 /* 7111 ** Write nBuf bytes of random data to the supplied buffer zBuf. 7112 */ 7113 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ 7114 UNUSED_PARAMETER(NotUsed); 7115 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int))); 7116 7117 /* We have to initialize zBuf to prevent valgrind from reporting 7118 ** errors. The reports issued by valgrind are incorrect - we would 7119 ** prefer that the randomness be increased by making use of the 7120 ** uninitialized space in zBuf - but valgrind errors tend to worry 7121 ** some users. Rather than argue, it seems easier just to initialize 7122 ** the whole array and silence valgrind, even if that means less randomness 7123 ** in the random seed. 7124 ** 7125 ** When testing, initializing zBuf[] to zero is all we do. That means 7126 ** that we always use the same random number sequence. This makes the 7127 ** tests repeatable. 7128 */ 7129 memset(zBuf, 0, nBuf); 7130 randomnessPid = osGetpid(0); 7131 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) 7132 { 7133 int fd, got; 7134 fd = robust_open("/dev/urandom", O_RDONLY, 0); 7135 if( fd<0 ){ 7136 time_t t; 7137 time(&t); 7138 memcpy(zBuf, &t, sizeof(t)); 7139 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid)); 7140 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf ); 7141 nBuf = sizeof(t) + sizeof(randomnessPid); 7142 }else{ 7143 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR ); 7144 robust_close(0, fd, __LINE__); 7145 } 7146 } 7147 #endif 7148 return nBuf; 7149 } 7150 7151 7152 /* 7153 ** Sleep for a little while. Return the amount of time slept. 7154 ** The argument is the number of microseconds we want to sleep. 7155 ** The return value is the number of microseconds of sleep actually 7156 ** requested from the underlying operating system, a number which 7157 ** might be greater than or equal to the argument, but not less 7158 ** than the argument. 7159 */ 7160 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){ 7161 #if !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP+0 7162 struct timespec sp; 7163 sp.tv_sec = microseconds / `1000000`; 7164 sp.tv_nsec = (microseconds % `1000000`) * 1000; 7165 7166 /* Almost all modern unix systems support nanosleep(). But if you are 7167 ** compiling for one of the rare exceptions, you can use 7168 ** -DHAVE_NANOSLEEP=0 (perhaps in conjunction with -DHAVE_USLEEP if 7169 ** usleep() is available) in order to bypass the use of nanosleep() */ 7170 nanosleep(&sp, NULL); 7171 7172 UNUSED_PARAMETER(NotUsed); 7173 return microseconds; 7174 #elif defined(HAVE_USLEEP) && HAVE_USLEEP 7175 if( microseconds>=`1000000` ) sleep(microseconds/`1000000`); 7176 if( microseconds%`1000000` ) usleep(microseconds%`1000000`); 7177 UNUSED_PARAMETER(NotUsed); 7178 return microseconds; 7179 #else 7180 int seconds; 7181 if( microseconds>`2146000000` ){ 7182 seconds = 2147; 7183 }else{ 7184 seconds = (microseconds+999999)/`1000000`; 7185 } 7186 sleep(seconds); 7187 UNUSED_PARAMETER(NotUsed); 7188 return seconds*`1000000`; 7189 #endif 7190 } 7191 7192 /* 7193 ** The following variable, if set to a non-zero value, is interpreted as 7194 ** the number of seconds since 1970 and is used to set the result of 7195 ** sqlite3OsCurrentTime() during testing. 7196 */ 7197 #ifdef SQLITE_TEST 7198 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ 7199 #endif 7200 7201 /* 7202 ** Find the current time (in Universal Coordinated Time). Write into *piNow 7203 ** the current time and date as a Julian Day number times 86_400_000. In 7204 ** other words, write into *piNow the number of milliseconds since the Julian 7205 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the 7206 ** proleptic Gregorian calendar. 7207 ** 7208 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date 7209 ** cannot be found. 7210 */ 7211 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){ 7212 static const sqlite3_int64 unixEpoch = `24405875`*(sqlite3_int64)`8640000`; 7213 int rc = SQLITE_OK; 7214 #if defined(NO_GETTOD) 7215 time_t t; 7216 time(&t); 7217 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch; 7218 #elif OS_VXWORKS 7219 struct timespec sNow; 7220 clock_gettime(CLOCK_REALTIME, &sNow); 7221 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/`1000000`; 7222 #else 7223 struct timeval sNow; 7224 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */ 7225 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000; 7226 #endif 7227 7228 #ifdef SQLITE_TEST 7229 if( sqlite3_current_time ){ 7230 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; 7231 } 7232 #endif 7233 UNUSED_PARAMETER(NotUsed); 7234 return rc; 7235 } 7236 7237 #ifndef SQLITE_OMIT_DEPRECATED 7238 /* 7239 ** Find the current time (in Universal Coordinated Time). Write the 7240 ** current time and date as a Julian Day number into *prNow and 7241 ** return 0. Return 1 if the time and date cannot be found. 7242 */ 7243 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){ 7244 sqlite3_int64 i = 0; 7245 int rc; 7246 UNUSED_PARAMETER(NotUsed); 7247 rc = unixCurrentTimeInt64(0, &i); 7248 *prNow = i/`86400000`.0; 7249 return rc; 7250 } 7251 #else 7252 # define unixCurrentTime 0 7253 #endif 7254 7255 /* 7256 ** The xGetLastError() method is designed to return a better 7257 ** low-level error message when operating-system problems come up 7258 ** during SQLite operation. Only the integer return code is currently 7259 ** used. 7260 */ 7261 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){ 7262 UNUSED_PARAMETER(NotUsed); 7263 UNUSED_PARAMETER(NotUsed2); 7264 UNUSED_PARAMETER(NotUsed3); 7265 return errno; 7266 } 7267 7268 7269 /* 7270 ************************ End of sqlite3_vfs methods *************************** 7271 ******************************************************************************/ 7272 7273 /****************************************************************************** 7274 ************************** Begin Proxy Locking ******************************** 7275 ** 7276 ** Proxy locking is a "uber-locking-method" in this sense: It uses the 7277 ** other locking methods on secondary lock files. Proxy locking is a 7278 ** meta-layer over top of the primitive locking implemented above. For 7279 ** this reason, the division that implements of proxy locking is deferred 7280 ** until late in the file (here) after all of the other I/O methods have 7281 ** been defined - so that the primitive locking methods are available 7282 ** as services to help with the implementation of proxy locking. 7283 ** 7284 **** 7285 ** 7286 ** The default locking schemes in SQLite use byte-range locks on the 7287 ** database file to coordinate safe, concurrent access by multiple readers 7288 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking 7289 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented 7290 ** as POSIX read & write locks over fixed set of locations (via fsctl), 7291 ** on AFP and SMB only exclusive byte-range locks are available via fsctl 7292 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states. 7293 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected 7294 ** address in the shared range is taken for a SHARED lock, the entire 7295 ** shared range is taken for an EXCLUSIVE lock): 7296 ** 7297 ** PENDING_BYTE 0x40000000 7298 ** RESERVED_BYTE 0x40000001 7299 ** SHARED_RANGE 0x40000002 -> 0x40000200 7300 ** 7301 ** This works well on the local file system, but shows a nearly 100x 7302 ** slowdown in read performance on AFP because the AFP client disables 7303 ** the read cache when byte-range locks are present. Enabling the read 7304 ** cache exposes a cache coherency problem that is present on all OS X 7305 ** supported network file systems. NFS and AFP both observe the 7306 ** close-to-open semantics for ensuring cache coherency 7307 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively 7308 ** address the requirements for concurrent database access by multiple 7309 ** readers and writers 7310 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html]. 7311 ** 7312 ** To address the performance and cache coherency issues, proxy file locking 7313 ** changes the way database access is controlled by limiting access to a 7314 ** single host at a time and moving file locks off of the database file 7315 ** and onto a proxy file on the local file system. 7316 ** 7317 ** 7318 ** Using proxy locks 7319 ** ----------------- 7320 ** 7321 ** C APIs 7322 ** 7323 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE, 7324 ** | ":auto:"); 7325 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE, 7326 ** &); 7327 ** 7328 ** 7329 ** SQL pragmas 7330 ** 7331 ** PRAGMA [database.]lock_proxy_file= | :auto: 7332 ** PRAGMA [database.]lock_proxy_file 7333 ** 7334 ** Specifying ":auto:" means that if there is a conch file with a matching 7335 ** host ID in it, the proxy path in the conch file will be used, otherwise 7336 ** a proxy path based on the user's temp dir 7337 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the 7338 ** actual proxy file name is generated from the name and path of the 7339 ** database file. For example: 7340 ** 7341 ** For database path "/Users/me/foo.db" 7342 ** The lock path will be "/sqliteplocks/_Users_me_foo.db:auto:") 7343 ** 7344 ** Once a lock proxy is configured for a database connection, it can not 7345 ** be removed, however it may be switched to a different proxy path via 7346 ** the above APIs (assuming the conch file is not being held by another 7347 ** connection or process). 7348 ** 7349 ** 7350 ** How proxy locking works 7351 ** ----------------------- 7352 ** 7353 ** Proxy file locking relies primarily on two new supporting files: 7354 ** 7355 ** * conch file to limit access to the database file to a single host 7356 ** at a time 7357 ** 7358 ** * proxy file to act as a proxy for the advisory locks normally 7359 ** taken on the database 7360 ** 7361 ** The conch file - to use a proxy file, sqlite must first "hold the conch" 7362 ** by taking an sqlite-style shared lock on the conch file, reading the 7363 ** contents and comparing the host's unique host ID (see below) and lock 7364 ** proxy path against the values stored in the conch. The conch file is 7365 ** stored in the same directory as the database file and the file name 7366 ** is patterned after the database file name as ".-conch". 7367 ** If the conch file does not exist, or its contents do not match the 7368 ** host ID and/or proxy path, then the lock is escalated to an exclusive 7369 ** lock and the conch file contents is updated with the host ID and proxy 7370 ** path and the lock is downgraded to a shared lock again. If the conch 7371 ** is held by another process (with a shared lock), the exclusive lock 7372 ** will fail and SQLITE_BUSY is returned. 7373 ** 7374 ** The proxy file - a single-byte file used for all advisory file locks 7375 ** normally taken on the database file. This allows for safe sharing 7376 ** of the database file for multiple readers and writers on the same 7377 ** host (the conch ensures that they all use the same local lock file). 7378 ** 7379 ** Requesting the lock proxy does not immediately take the conch, it is 7380 ** only taken when the first request to lock database file is made. 7381 ** This matches the semantics of the traditional locking behavior, where 7382 ** opening a connection to a database file does not take a lock on it. 7383 ** The shared lock and an open file descriptor are maintained until 7384 ** the connection to the database is closed. 7385 ** 7386 ** The proxy file and the lock file are never deleted so they only need 7387 ** to be created the first time they are used. 7388 ** 7389 ** Configuration options 7390 ** --------------------- 7391 ** 7392 ** SQLITE_PREFER_PROXY_LOCKING 7393 ** 7394 ** Database files accessed on non-local file systems are 7395 ** automatically configured for proxy locking, lock files are 7396 ** named automatically using the same logic as 7397 ** PRAGMA lock_proxy_file=":auto:" 7398 ** 7399 ** SQLITE_PROXY_DEBUG 7400 ** 7401 ** Enables the logging of error messages during host id file 7402 ** retrieval and creation 7403 ** 7404 ** LOCKPROXYDIR 7405 ** 7406 ** Overrides the default directory used for lock proxy files that 7407 ** are named automatically via the ":auto:" setting 7408 ** 7409 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 7410 ** 7411 ** Permissions to use when creating a directory for storing the 7412 ** lock proxy files, only used when LOCKPROXYDIR is not set. 7413 ** 7414 ** 7415 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING, 7416 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will 7417 ** force proxy locking to be used for every database file opened, and 0 7418 ** will force automatic proxy locking to be disabled for all database 7419 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or 7420 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING). 7421 */ 7422 7423 /* 7424 ** Proxy locking is only available on MacOSX 7425 */ 7426 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 7427 7428 /* 7429 ** The proxyLockingContext has the path and file structures for the remote 7430 ** and local proxy files in it 7431 */ 7432 typedef struct proxyLockingContext proxyLockingContext; 7433 struct proxyLockingContext { 7434 unixFile *conchFile; /* Open conch file */ 7435 char *conchFilePath; /* Name of the conch file */ 7436 unixFile *lockProxy; /* Open proxy lock file */ 7437 char *lockProxyPath; /* Name of the proxy lock file */ 7438 char *dbPath; /* Name of the open file */ 7439 int conchHeld; /* 1 if the conch is held, -1 if lockless */ 7440 int nFails; /* Number of conch taking failures */ 7441 void *oldLockingContext; /* Original lockingcontext to restore on close */ 7442 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */ 7443 }; 7444 7445 /* 7446 ** The proxy lock file path for the database at dbPath is written into lPath, 7447 ** which must point to valid, writable memory large enough for a maxLen length 7448 ** file path. 7449 */ 7450 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){ 7451 int len; 7452 int dbLen; 7453 int i; 7454 7455 #ifdef LOCKPROXYDIR 7456 len = strlcpy(lPath, LOCKPROXYDIR, maxLen); 7457 #else 7458 # ifdef _CS_DARWIN_USER_TEMP_DIR 7459 { 7460 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){ 7461 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n", 7462 lPath, errno, osGetpid(0))); 7463 return SQLITE_IOERR_LOCK; 7464 } 7465 len = strlcat(lPath, "sqliteplocks", maxLen); 7466 } 7467 # else 7468 len = strlcpy(lPath, "/tmp/", maxLen); 7469 # endif 7470 #endif 7471 7472 if( lPath[len-1]!='/' ){ 7473 len = strlcat(lPath, "/", maxLen); 7474 } 7475 7476 /* transform the db path to a unique cache name */ 7477 dbLen = (int)strlen(dbPath); 7478 for( i=0; i 0) ){ 7502 /* only mkdir if leaf dir != "." or "/" or ".." */ 7503 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 7504 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){ 7505 buf[i]='\0'; 7506 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){ 7507 int err=errno; 7508 if( err!=EEXIST ) { 7509 OSTRACE(("CREATELOCKPATH FAILED creating %s, " 7510 "'%s' proxy lock path=%s pid=%d\n", 7511 buf, strerror(err), lockPath, osGetpid(0))); 7512 return err; 7513 } 7514 } 7515 } 7516 start=i+1; 7517 } 7518 buf[i] = lockPath[i]; 7519 } 7520 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0))); 7521 return 0; 7522 } 7523 7524 /* 7525 ** Create a new VFS file descriptor (stored in memory obtained from 7526 ** sqlite3_malloc) and open the file named "path" in the file descriptor. 7527 ** 7528 ** The caller is responsible not only for closing the file descriptor 7529 ** but also for freeing the memory associated with the file descriptor. 7530 */ 7531 static int proxyCreateUnixFile( 7532 const char *path, /* path for the new unixFile */ 7533 unixFile **ppFile, /* unixFile created and returned by ref */ 7534 int islockfile /* if non zero missing dirs will be created */ 7535 ) { 7536 int fd = -1; 7537 unixFile *pNew; 7538 int rc = SQLITE_OK; 7539 int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW; 7540 sqlite3_vfs dummyVfs; 7541 int terrno = 0; 7542 UnixUnusedFd *pUnused = NULL; 7543 7544 /* 1. first try to open/create the file 7545 ** 2. if that fails, and this is a lock file (not-conch), try creating 7546 ** the parent directories and then try again. 7547 ** 3. if that fails, try to open the file read-only 7548 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file 7549 */ 7550 pUnused = findReusableFd(path, openFlags); 7551 if( pUnused ){ 7552 fd = pUnused->fd; 7553 }else{ 7554 pUnused = sqlite3_malloc64(sizeof(*pUnused)); 7555 if( !pUnused ){ 7556 return SQLITE_NOMEM_BKPT; 7557 } 7558 } 7559 if( fd<0 ){ 7560 fd = robust_open(path, openFlags, 0); 7561 terrno = errno; 7562 if( fd<0 && errno==ENOENT && islockfile ){ 7563 if( proxyCreateLockPath(path) == SQLITE_OK ){ 7564 fd = robust_open(path, openFlags, 0); 7565 } 7566 } 7567 } 7568 if( fd<0 ){ 7569 openFlags = O_RDONLY | O_NOFOLLOW; 7570 fd = robust_open(path, openFlags, 0); 7571 terrno = errno; 7572 } 7573 if( fd<0 ){ 7574 if( islockfile ){ 7575 return SQLITE_BUSY; 7576 } 7577 switch (terrno) { 7578 case EACCES: 7579 return SQLITE_PERM; 7580 case EIO: 7581 return SQLITE_IOERR_LOCK; /* even though it is the conch */ 7582 default: 7583 return SQLITE_CANTOPEN_BKPT; 7584 } 7585 } 7586 7587 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew)); 7588 if( pNew==NULL ){ 7589 rc = SQLITE_NOMEM_BKPT; 7590 goto end_create_proxy; 7591 } 7592 memset(pNew, 0, sizeof(unixFile)); 7593 pNew->openFlags = openFlags; 7594 memset(&dummyVfs, 0, sizeof(dummyVfs)); 7595 dummyVfs.pAppData = (void*)&autolockIoFinder; 7596 dummyVfs.zName = "dummy"; 7597 pUnused->fd = fd; 7598 pUnused->flags = openFlags; 7599 pNew->pPreallocatedUnused = pUnused; 7600 7601 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0); 7602 if( rc==SQLITE_OK ){ 7603 *ppFile = pNew; 7604 return SQLITE_OK; 7605 } 7606 end_create_proxy: 7607 robust_close(pNew, fd, __LINE__); 7608 sqlite3_free(pNew); 7609 sqlite3_free(pUnused); 7610 return rc; 7611 } 7612 7613 #ifdef SQLITE_TEST 7614 /* simulate multiple hosts by creating unique hostid file paths */ 7615 int sqlite3_hostid_num = 0; 7616 #endif 7617 7618 #define PROXY_HOSTIDLEN 16 /* conch file host id length */ 7619 7620 #if HAVE_GETHOSTUUID 7621 /* Not always defined in the headers as it ought to be */ 7622 extern int gethostuuid(uuid_t id, const struct timespec *wait); 7623 #endif 7624 7625 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 7626 ** bytes of writable memory. 7627 */ 7628 static int proxyGetHostID(unsigned char *pHostID, int *pError){ 7629 assert(PROXY_HOSTIDLEN == sizeof(uuid_t)); 7630 memset(pHostID, 0, PROXY_HOSTIDLEN); 7631 #if HAVE_GETHOSTUUID 7632 { 7633 struct timespec timeout = {1, 0}; /* 1 sec timeout */ 7634 if( gethostuuid(pHostID, &timeout) ){ 7635 int err = errno; 7636 if( pError ){ 7637 *pError = err; 7638 } 7639 return SQLITE_IOERR; 7640 } 7641 } 7642 #else 7643 UNUSED_PARAMETER(pError); 7644 #endif 7645 #ifdef SQLITE_TEST 7646 /* simulate multiple hosts by creating unique hostid file paths */ 7647 if( sqlite3_hostid_num != 0){ 7648 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF)); 7649 } 7650 #endif 7651 7652 return SQLITE_OK; 7653 } 7654 7655 /* The conch file contains the header, host id and lock file path 7656 */ 7657 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */ 7658 #define PROXY_HEADERLEN 1 /* conch file header length */ 7659 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN) 7660 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN) 7661 7662 /* 7663 ** Takes an open conch file, copies the contents to a new path and then moves 7664 ** it back. The newly created file's file descriptor is assigned to the 7665 ** conch file structure and finally the original conch file descriptor is 7666 ** closed. Returns zero if successful. 7667 */ 7668 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){ 7669 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 7670 unixFile *conchFile = pCtx->conchFile; 7671 char tPath[MAXPATHLEN]; 7672 char buf[PROXY_MAXCONCHLEN]; 7673 char *cPath = pCtx->conchFilePath; 7674 size_t readLen = 0; 7675 size_t pathLen = 0; 7676 char errmsg[64] = ""; 7677 int fd = -1; 7678 int rc = -1; 7679 UNUSED_PARAMETER(myHostID); 7680 7681 /* create a new path by replace the trailing '-conch' with '-break' */ 7682 pathLen = strlcpy(tPath, cPath, MAXPATHLEN); 7683 if( pathLen>MAXPATHLEN || pathLen<6 || 7684 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){ 7685 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen); 7686 goto end_breaklock; 7687 } 7688 /* read the conch content */ 7689 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0); 7690 if( readLenh, __LINE__); 7711 conchFile->h = fd; 7712 conchFile->openFlags = O_RDWR | O_CREAT; 7713 7714 end_breaklock: 7715 if( rc ){ 7716 if( fd>=0 ){ 7717 osUnlink(tPath); 7718 robust_close(pFile, fd, __LINE__); 7719 } 7720 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg); 7721 } 7722 return rc; 7723 } 7724 7725 /* Take the requested lock on the conch file and break a stale lock if the 7726 ** host id matches. 7727 */ 7728 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){ 7729 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 7730 unixFile *conchFile = pCtx->conchFile; 7731 int rc = SQLITE_OK; 7732 int nTries = 0; 7733 struct timespec conchModTime; 7734 7735 memset(&conchModTime, 0, sizeof(conchModTime)); 7736 do { 7737 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); 7738 nTries ++; 7739 if( rc==SQLITE_BUSY ){ 7740 /* If the lock failed (busy): 7741 * 1st try: get the mod time of the conch, wait 0.5s and try again. 7742 * 2nd try: fail if the mod time changed or host id is different, wait 7743 * 10 sec and try again 7744 * 3rd try: break the lock unless the mod time has changed. 7745 */ 7746 struct stat buf; 7747 if( osFstat(conchFile->h, &buf) ){ 7748 storeLastErrno(pFile, errno); 7749 return SQLITE_IOERR_LOCK; 7750 } 7751 7752 if( nTries==1 ){ 7753 conchModTime = buf.st_mtimespec; 7754 unixSleep(0,500000); /* wait 0.5 sec and try the lock again*/ 7755 continue; 7756 } 7757 7758 assert( nTries>1 ); 7759 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 7760 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){ 7761 return SQLITE_BUSY; 7762 } 7763 7764 if( nTries==2 ){ 7765 char tBuf[PROXY_MAXCONCHLEN]; 7766 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0); 7767 if( len<0 ){ 7768 storeLastErrno(pFile, errno); 7769 return SQLITE_IOERR_LOCK; 7770 } 7771 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){ 7772 /* don't break the lock if the host id doesn't match */ 7773 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){ 7774 return SQLITE_BUSY; 7775 } 7776 }else{ 7777 /* don't break the lock on short read or a version mismatch */ 7778 return SQLITE_BUSY; 7779 } 7780 unixSleep(0,`10000000`); /* wait 10 sec and try the lock again */ 7781 continue; 7782 } 7783 7784 assert( nTries==3 ); 7785 if( 0==proxyBreakConchLock(pFile, myHostID) ){ 7786 rc = SQLITE_OK; 7787 if( lockType==EXCLUSIVE_LOCK ){ 7788 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK); 7789 } 7790 if( !rc ){ 7791 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); 7792 } 7793 } 7794 } 7795 } while( rc==SQLITE_BUSY && nTries<3 ); 7796 7797 return rc; 7798 } 7799 7800 /* Takes the conch by taking a shared lock and read the contents conch, if 7801 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL 7802 ** lockPath means that the lockPath in the conch file will be used if the 7803 ** host IDs match, or a new lock path will be generated automatically 7804 ** and written to the conch file. 7805 */ 7806 static int proxyTakeConch(unixFile *pFile){ 7807 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 7808 7809 if( pCtx->conchHeld!=0 ){ 7810 return SQLITE_OK; 7811 }else{ 7812 unixFile *conchFile = pCtx->conchFile; 7813 uuid_t myHostID; 7814 int pError = 0; 7815 char readBuf[PROXY_MAXCONCHLEN]; 7816 char lockPath[MAXPATHLEN]; 7817 char *tempLockPath = NULL; 7818 int rc = SQLITE_OK; 7819 int createConch = 0; 7820 int hostIdMatch = 0; 7821 int readLen = 0; 7822 int tryOldLockPath = 0; 7823 int forceNewLockPath = 0; 7824 7825 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h, 7826 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 7827 osGetpid(0))); 7828 7829 rc = proxyGetHostID(myHostID, &pError); 7830 if( (rc&0xff)==SQLITE_IOERR ){ 7831 storeLastErrno(pFile, pError); 7832 goto end_takeconch; 7833 } 7834 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK); 7835 if( rc!=SQLITE_OK ){ 7836 goto end_takeconch; 7837 } 7838 /* read the existing conch file */ 7839 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN); 7840 if( readLen<0 ){ 7841 /* I/O error: lastErrno set by seekAndRead */ 7842 storeLastErrno(pFile, conchFile->lastErrno); 7843 rc = SQLITE_IOERR_READ; 7844 goto end_takeconch; 7845 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 7846 readBuf[0]!=(char)PROXY_CONCHVERSION ){ 7847 /* a short read or version format mismatch means we need to create a new 7848 ** conch file. 7849 */ 7850 createConch = 1; 7851 } 7852 /* if the host id matches and the lock path already exists in the conch 7853 ** we'll try to use the path there, if we can't open that path, we'll 7854 ** retry with a new auto-generated path 7855 */ 7856 do { /* in case we need to try again for an :auto: named lock file */ 7857 7858 if( !createConch && !forceNewLockPath ){ 7859 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 7860 PROXY_HOSTIDLEN); 7861 /* if the conch has data compare the contents */ 7862 if( !pCtx->lockProxyPath ){ 7863 /* for auto-named local lock file, just check the host ID and we'll 7864 ** use the local lock file path that's already in there 7865 */ 7866 if( hostIdMatch ){ 7867 size_t pathLen = (readLen - PROXY_PATHINDEX); 7868 7869 if( pathLen>=MAXPATHLEN ){ 7870 pathLen=MAXPATHLEN-1; 7871 } 7872 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen); 7873 lockPath[pathLen] = 0; 7874 tempLockPath = lockPath; 7875 tryOldLockPath = 1; 7876 /* create a copy of the lock path if the conch is taken */ 7877 goto end_takeconch; 7878 } 7879 }else if( hostIdMatch 7880 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX], 7881 readLen-PROXY_PATHINDEX) 7882 ){ 7883 /* conch host and lock path match */ 7884 goto end_takeconch; 7885 } 7886 } 7887 7888 /* if the conch isn't writable and doesn't match, we can't take it */ 7889 if( (conchFile->openFlags&O_RDWR) == 0 ){ 7890 rc = SQLITE_BUSY; 7891 goto end_takeconch; 7892 } 7893 7894 /* either the conch didn't match or we need to create a new one */ 7895 if( !pCtx->lockProxyPath ){ 7896 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN); 7897 tempLockPath = lockPath; 7898 /* create a copy of the lock path _only_ if the conch is taken */ 7899 } 7900 7901 /* update conch with host and path (this will fail if other process 7902 ** has a shared lock already), if the host id matches, use the big 7903 ** stick. 7904 */ 7905 futimes(conchFile->h, NULL); 7906 if( hostIdMatch && !createConch ){ 7907 if( conchFile->pInode && conchFile->pInode->nShared>1 ){ 7908 /* We are trying for an exclusive lock but another thread in this 7909 ** same process is still holding a shared lock. */ 7910 rc = SQLITE_BUSY; 7911 } else { 7912 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK); 7913 } 7914 }else{ 7915 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK); 7916 } 7917 if( rc==SQLITE_OK ){ 7918 char writeBuffer[PROXY_MAXCONCHLEN]; 7919 int writeSize = 0; 7920 7921 writeBuffer[0] = (char)PROXY_CONCHVERSION; 7922 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN); 7923 if( pCtx->lockProxyPath!=NULL ){ 7924 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, 7925 MAXPATHLEN); 7926 }else{ 7927 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN); 7928 } 7929 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]); 7930 robust_ftruncate(conchFile->h, writeSize); 7931 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0); 7932 full_fsync(conchFile->h,0,0); 7933 /* If we created a new conch file (not just updated the contents of a 7934 ** valid conch file), try to match the permissions of the database 7935 */ 7936 if( rc==SQLITE_OK && createConch ){ 7937 struct stat buf; 7938 int err = osFstat(pFile->h, &buf); 7939 if( err==0 ){ 7940 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP | 7941 S_IROTH|S_IWOTH); 7942 /* try to match the database file R/W permissions, ignore failure */ 7943 #ifndef SQLITE_PROXY_DEBUG 7944 osFchmod(conchFile->h, cmode); 7945 #else 7946 do{ 7947 rc = osFchmod(conchFile->h, cmode); 7948 }while( rc==(-1) && errno==EINTR ); 7949 if( rc!=0 ){ 7950 int code = errno; 7951 fprintf(stderr, "fchmod %o FAILED with %d %s\n", 7952 cmode, code, strerror(code)); 7953 } else { 7954 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode); 7955 } 7956 }else{ 7957 int code = errno; 7958 fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 7959 err, code, strerror(code)); 7960 #endif 7961 } 7962 } 7963 } 7964 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK); 7965 7966 end_takeconch: 7967 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h)); 7968 if( rc==SQLITE_OK && pFile->openFlags ){ 7969 int fd; 7970 if( pFile->h>=0 ){ 7971 robust_close(pFile, pFile->h, __LINE__); 7972 } 7973 pFile->h = -1; 7974 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0); 7975 OSTRACE(("TRANSPROXY: OPEN %d\n", fd)); 7976 if( fd>=0 ){ 7977 pFile->h = fd; 7978 }else{ 7979 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called 7980 during locking */ 7981 } 7982 } 7983 if( rc==SQLITE_OK && !pCtx->lockProxy ){ 7984 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath; 7985 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1); 7986 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){ 7987 /* we couldn't create the proxy lock file with the old lock file path 7988 ** so try again via auto-naming 7989 */ 7990 forceNewLockPath = 1; 7991 tryOldLockPath = 0; 7992 continue; /* go back to the do {} while start point, try again */ 7993 } 7994 } 7995 if( rc==SQLITE_OK ){ 7996 /* Need to make a copy of path if we extracted the value 7997 ** from the conch file or the path was allocated on the stack 7998 */ 7999 if( tempLockPath ){ 8000 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath); 8001 if( !pCtx->lockProxyPath ){ 8002 rc = SQLITE_NOMEM_BKPT; 8003 } 8004 } 8005 } 8006 if( rc==SQLITE_OK ){ 8007 pCtx->conchHeld = 1; 8008 8009 if( pCtx->lockProxy->pMethod == &afpIoMethods ){ 8010 afpLockingContext *afpCtx; 8011 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext; 8012 afpCtx->dbPath = pCtx->lockProxyPath; 8013 } 8014 } else { 8015 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); 8016 } 8017 OSTRACE(("TAKECONCH %d %s\n", conchFile->h, 8018 rc==SQLITE_OK?"ok":"failed")); 8019 return rc; 8020 } while (1); /* in case we need to retry the :auto: lock file - 8021 ** we should never get here except via the 'continue' call. */ 8022 } 8023 } 8024 8025 /* 8026 ** If pFile holds a lock on a conch file, then release that lock. 8027 */ 8028 static int proxyReleaseConch(unixFile *pFile){ 8029 int rc = SQLITE_OK; /* Subroutine return code */ 8030 proxyLockingContext *pCtx; /* The locking context for the proxy lock */ 8031 unixFile *conchFile; /* Name of the conch file */ 8032 8033 pCtx = (proxyLockingContext *)pFile->lockingContext; 8034 conchFile = pCtx->conchFile; 8035 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h, 8036 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 8037 osGetpid(0))); 8038 if( pCtx->conchHeld>0 ){ 8039 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); 8040 } 8041 pCtx->conchHeld = 0; 8042 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h, 8043 (rc==SQLITE_OK ? "ok" : "failed"))); 8044 return rc; 8045 } 8046 8047 /* 8048 ** Given the name of a database file, compute the name of its conch file. 8049 ** Store the conch filename in memory obtained from sqlite3_malloc64(). 8050 ** Make *pConchPath point to the new name. Return SQLITE_OK on success 8051 ** or SQLITE_NOMEM if unable to obtain memory. 8052 ** 8053 ** The caller is responsible for ensuring that the allocated memory 8054 ** space is eventually freed. 8055 ** 8056 ** *pConchPath is set to NULL if a memory allocation error occurs. 8057 */ 8058 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){ 8059 int i; /* Loop counter */ 8060 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */ 8061 char *conchPath; /* buffer in which to construct conch name */ 8062 8063 /* Allocate space for the conch filename and initialize the name to 8064 ** the name of the original database file. */ 8065 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8); 8066 if( conchPath==0 ){ 8067 return SQLITE_NOMEM_BKPT; 8068 } 8069 memcpy(conchPath, dbPath, len+1); 8070 8071 /* now insert a "." before the last / character */ 8072 for( i=(len-1); i>=0; i-- ){ 8073 if( conchPath[i]=='/' ){ 8074 i++; 8075 break; 8076 } 8077 } 8078 conchPath[i]='.'; 8079 while ( ilockingContext; 8097 char *oldPath = pCtx->lockProxyPath; 8098 int rc = SQLITE_OK; 8099 8100 if( pFile->eFileLock!=NO_LOCK ){ 8101 return SQLITE_BUSY; 8102 } 8103 8104 /* nothing to do if the path is NULL, :auto: or matches the existing path */ 8105 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") || 8106 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){ 8107 return SQLITE_OK; 8108 }else{ 8109 unixFile *lockProxy = pCtx->lockProxy; 8110 pCtx->lockProxy=NULL; 8111 pCtx->conchHeld = 0; 8112 if( lockProxy!=NULL ){ 8113 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy); 8114 if( rc ) return rc; 8115 sqlite3_free(lockProxy); 8116 } 8117 sqlite3_free(oldPath); 8118 pCtx->lockProxyPath = sqlite3DbStrDup(0, path); 8119 } 8120 8121 return rc; 8122 } 8123 8124 /* 8125 ** pFile is a file that has been opened by a prior xOpen call. dbPath 8126 ** is a string buffer at least MAXPATHLEN+1 characters in size. 8127 ** 8128 ** This routine find the filename associated with pFile and writes it 8129 ** int dbPath. 8130 */ 8131 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){ 8132 #if defined(__APPLE__) 8133 if( pFile->pMethod == &afpIoMethods ){ 8134 /* afp style keeps a reference to the db path in the filePath field 8135 ** of the struct */ 8136 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); 8137 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, 8138 MAXPATHLEN); 8139 } else 8140 #endif 8141 if( pFile->pMethod == &dotlockIoMethods ){ 8142 /* dot lock style uses the locking context to store the dot lock 8143 ** file path */ 8144 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX); 8145 memcpy(dbPath, (char *)pFile->lockingContext, len + 1); 8146 }else{ 8147 /* all other styles use the locking context to store the db file path */ 8148 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); 8149 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN); 8150 } 8151 return SQLITE_OK; 8152 } 8153 8154 /* 8155 ** Takes an already filled in unix file and alters it so all file locking 8156 ** will be performed on the local proxy lock file. The following fields 8157 ** are preserved in the locking context so that they can be restored and 8158 ** the unix structure properly cleaned up at close time: 8159 ** ->lockingContext 8160 ** ->pMethod 8161 */ 8162 static int proxyTransformUnixFile(unixFile *pFile, const char *path) { 8163 proxyLockingContext *pCtx; 8164 char dbPath[MAXPATHLEN+1]; /* Name of the database file */ 8165 char *lockPath=NULL; 8166 int rc = SQLITE_OK; 8167 8168 if( pFile->eFileLock!=NO_LOCK ){ 8169 return SQLITE_BUSY; 8170 } 8171 proxyGetDbPathForUnixFile(pFile, dbPath); 8172 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){ 8173 lockPath=NULL; 8174 }else{ 8175 lockPath=(char *)path; 8176 } 8177 8178 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h, 8179 (lockPath ? lockPath : ":auto:"), osGetpid(0))); 8180 8181 pCtx = sqlite3_malloc64( sizeof(*pCtx) ); 8182 if( pCtx==0 ){ 8183 return SQLITE_NOMEM_BKPT; 8184 } 8185 memset(pCtx, 0, sizeof(*pCtx)); 8186 8187 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath); 8188 if( rc==SQLITE_OK ){ 8189 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0); 8190 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){ 8191 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and 8192 ** (c) the file system is read-only, then enable no-locking access. 8193 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts 8194 ** that openFlags will have only one of O_RDONLY or O_RDWR. 8195 */ 8196 struct statfs fsInfo; 8197 struct stat conchInfo; 8198 int goLockless = 0; 8199 8200 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) { 8201 int err = errno; 8202 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){ 8203 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY; 8204 } 8205 } 8206 if( goLockless ){ 8207 pCtx->conchHeld = -1; /* read only FS/ lockless */ 8208 rc = SQLITE_OK; 8209 } 8210 } 8211 } 8212 if( rc==SQLITE_OK && lockPath ){ 8213 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath); 8214 } 8215 8216 if( rc==SQLITE_OK ){ 8217 pCtx->dbPath = sqlite3DbStrDup(0, dbPath); 8218 if( pCtx->dbPath==NULL ){ 8219 rc = SQLITE_NOMEM_BKPT; 8220 } 8221 } 8222 if( rc==SQLITE_OK ){ 8223 /* all memory is allocated, proxys are created and assigned, 8224 ** switch the locking context and pMethod then return. 8225 */ 8226 pCtx->oldLockingContext = pFile->lockingContext; 8227 pFile->lockingContext = pCtx; 8228 pCtx->pOldMethod = pFile->pMethod; 8229 pFile->pMethod = &proxyIoMethods; 8230 }else{ 8231 if( pCtx->conchFile ){ 8232 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile); 8233 sqlite3_free(pCtx->conchFile); 8234 } 8235 sqlite3DbFree(0, pCtx->lockProxyPath); 8236 sqlite3_free(pCtx->conchFilePath); 8237 sqlite3_free(pCtx); 8238 } 8239 OSTRACE(("TRANSPROXY %d %s\n", pFile->h, 8240 (rc==SQLITE_OK ? "ok" : "failed"))); 8241 return rc; 8242 } 8243 8244 8245 /* 8246 ** This routine handles sqlite3_file_control() calls that are specific 8247 ** to proxy locking. 8248 */ 8249 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){ 8250 switch( op ){ 8251 case SQLITE_FCNTL_GET_LOCKPROXYFILE: { 8252 unixFile *pFile = (unixFile*)id; 8253 if( pFile->pMethod == &proxyIoMethods ){ 8254 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; 8255 proxyTakeConch(pFile); 8256 if( pCtx->lockProxyPath ){ 8257 *(const char **)pArg = pCtx->lockProxyPath; 8258 }else{ 8259 *(const char **)pArg = ":auto: (not held)"; 8260 } 8261 } else { 8262 *(const char **)pArg = NULL; 8263 } 8264 return SQLITE_OK; 8265 } 8266 case SQLITE_FCNTL_SET_LOCKPROXYFILE: { 8267 unixFile *pFile = (unixFile*)id; 8268 int rc = SQLITE_OK; 8269 int isProxyStyle = (pFile->pMethod == &proxyIoMethods); 8270 if( pArg==NULL || (const char *)pArg==0 ){ 8271 if( isProxyStyle ){ 8272 /* turn off proxy locking - not supported. If support is added for 8273 ** switching proxy locking mode off then it will need to fail if 8274 ** the journal mode is WAL mode. 8275 */ 8276 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/; 8277 }else{ 8278 /* turn off proxy locking - already off - NOOP */ 8279 rc = SQLITE_OK; 8280 } 8281 }else{ 8282 const char *proxyPath = (const char *)pArg; 8283 if( isProxyStyle ){ 8284 proxyLockingContext *pCtx = 8285 (proxyLockingContext*)pFile->lockingContext; 8286 if( !strcmp(pArg, ":auto:") 8287 || (pCtx->lockProxyPath && 8288 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN)) 8289 ){ 8290 rc = SQLITE_OK; 8291 }else{ 8292 rc = switchLockProxyPath(pFile, proxyPath); 8293 } 8294 }else{ 8295 /* turn on proxy file locking */ 8296 rc = proxyTransformUnixFile(pFile, proxyPath); 8297 } 8298 } 8299 return rc; 8300 } 8301 default: { 8302 assert( 0 ); /* The call assures that only valid opcodes are sent */ 8303 } 8304 } 8305 /*NOTREACHED*/ assert(0); 8306 return SQLITE_ERROR; 8307 } 8308 8309 /* 8310 ** Within this division (the proxying locking implementation) the procedures 8311 ** above this point are all utilities. The lock-related methods of the 8312 ** proxy-locking sqlite3_io_method object follow. 8313 */ 8314 8315 8316 /* 8317 ** This routine checks if there is a RESERVED lock held on the specified 8318 ** file by this or any other process. If such a lock is held, set *pResOut 8319 ** to a non-zero value otherwise *pResOut is set to zero. The return value 8320 ** is set to SQLITE_OK unless an I/O error occurs during lock checking. 8321 */ 8322 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) { 8323 unixFile *pFile = (unixFile*)id; 8324 int rc = proxyTakeConch(pFile); 8325 if( rc==SQLITE_OK ){ 8326 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 8327 if( pCtx->conchHeld>0 ){ 8328 unixFile *proxy = pCtx->lockProxy; 8329 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut); 8330 }else{ /* conchHeld < 0 is lockless */ 8331 pResOut=0; 8332 } 8333 } 8334 return rc; 8335 } 8336 8337 /* 8338 ** Lock the file with the lock specified by parameter eFileLock - one 8339 ** of the following: 8340 ** 8341 ** (1) SHARED_LOCK 8342 ** (2) RESERVED_LOCK 8343 ** (3) PENDING_LOCK 8344 ** (4) EXCLUSIVE_LOCK 8345 ** 8346 ** Sometimes when requesting one lock state, additional lock states 8347 ** are inserted in between. The locking might fail on one of the later 8348 ** transitions leaving the lock state different from what it started but 8349 ** still short of its goal. The following chart shows the allowed 8350 ** transitions and the inserted intermediate states: 8351 ** 8352 ** UNLOCKED -> SHARED 8353 ** SHARED -> RESERVED 8354 ** SHARED -> (PENDING) -> EXCLUSIVE 8355 ** RESERVED -> (PENDING) -> EXCLUSIVE 8356 ** PENDING -> EXCLUSIVE 8357 ** 8358 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 8359 ** routine to lower a locking level. 8360 */ 8361 static int proxyLock(sqlite3_file *id, int eFileLock) { 8362 unixFile *pFile = (unixFile*)id; 8363 int rc = proxyTakeConch(pFile); 8364 if( rc==SQLITE_OK ){ 8365 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 8366 if( pCtx->conchHeld>0 ){ 8367 unixFile *proxy = pCtx->lockProxy; 8368 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock); 8369 pFile->eFileLock = proxy->eFileLock; 8370 }else{ 8371 /* conchHeld < 0 is lockless */ 8372 } 8373 } 8374 return rc; 8375 } 8376 8377 8378 /* 8379 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock 8380 ** must be either NO_LOCK or SHARED_LOCK. 8381 ** 8382 ** If the locking level of the file descriptor is already at or below 8383 ** the requested locking level, this routine is a no-op. 8384 */ 8385 static int proxyUnlock(sqlite3_file *id, int eFileLock) { 8386 unixFile *pFile = (unixFile*)id; 8387 int rc = proxyTakeConch(pFile); 8388 if( rc==SQLITE_OK ){ 8389 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 8390 if( pCtx->conchHeld>0 ){ 8391 unixFile *proxy = pCtx->lockProxy; 8392 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock); 8393 pFile->eFileLock = proxy->eFileLock; 8394 }else{ 8395 /* conchHeld < 0 is lockless */ 8396 } 8397 } 8398 return rc; 8399 } 8400 8401 /* 8402 ** Close a file that uses proxy locks. 8403 */ 8404 static int proxyClose(sqlite3_file *id) { 8405 if( ALWAYS(id) ){ 8406 unixFile *pFile = (unixFile*)id; 8407 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 8408 unixFile *lockProxy = pCtx->lockProxy; 8409 unixFile *conchFile = pCtx->conchFile; 8410 int rc = SQLITE_OK; 8411 8412 if( lockProxy ){ 8413 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK); 8414 if( rc ) return rc; 8415 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy); 8416 if( rc ) return rc; 8417 sqlite3_free(lockProxy); 8418 pCtx->lockProxy = 0; 8419 } 8420 if( conchFile ){ 8421 if( pCtx->conchHeld ){ 8422 rc = proxyReleaseConch(pFile); 8423 if( rc ) return rc; 8424 } 8425 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile); 8426 if( rc ) return rc; 8427 sqlite3_free(conchFile); 8428 } 8429 sqlite3DbFree(0, pCtx->lockProxyPath); 8430 sqlite3_free(pCtx->conchFilePath); 8431 sqlite3DbFree(0, pCtx->dbPath); 8432 /* restore the original locking context and pMethod then close it */ 8433 pFile->lockingContext = pCtx->oldLockingContext; 8434 pFile->pMethod = pCtx->pOldMethod; 8435 sqlite3_free(pCtx); 8436 return pFile->pMethod->xClose(id); 8437 } 8438 return SQLITE_OK; 8439 } 8440 8441 8442 8443 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ 8444 /* 8445 ** The proxy locking style is intended for use with AFP filesystems. 8446 ** And since AFP is only supported on MacOSX, the proxy locking is also 8447 ** restricted to MacOSX. 8448 ** 8449 ** 8450 ******************* End of the proxy lock implementation ********************** 8451 ******************************************************************************/ 8452 8453 /* 8454 ** Initialize the operating system interface. 8455 ** 8456 ** This routine registers all VFS implementations for unix-like operating 8457 ** systems. This routine, and the sqlite3_os_end() routine that follows, 8458 ** should be the only routines in this file that are visible from other 8459 ** files. 8460 ** 8461 ** This routine is called once during SQLite initialization and by a 8462 ** single thread. The memory allocation and mutex subsystems have not 8463 ** necessarily been initialized when this routine is called, and so they 8464 ** should not be used. 8465 */ 8466 int sqlite3_os_init(void){ 8467 /* 8468 ** The following macro defines an initializer for an sqlite3_vfs object. 8469 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer 8470 ** to the "finder" function. (pAppData is a pointer to a pointer because 8471 ** silly C90 rules prohibit a void* from being cast to a function pointer 8472 ** and so we have to go through the intermediate pointer to avoid problems 8473 ** when compiling with -pedantic-errors on GCC.) 8474 ** 8475 ** The FINDER parameter to this macro is the name of the pointer to the 8476 ** finder-function. The finder-function returns a pointer to the 8477 ** sqlite_io_methods object that implements the desired locking 8478 ** behaviors. See the division above that contains the IOMETHODS 8479 ** macro for addition information on finder-functions. 8480 ** 8481 ** Most finders simply return a pointer to a fixed sqlite3_io_methods 8482 ** object. But the "autolockIoFinder" available on MacOSX does a little 8483 ** more than that; it looks at the filesystem type that hosts the 8484 ** database file and tries to choose an locking method appropriate for 8485 ** that filesystem time. 8486 */ 8487 #define UNIXVFS(VFSNAME, FINDER) { \ 8488 3, /* iVersion */ \ 8489 sizeof(unixFile), /* szOsFile */ \ 8490 MAX_PATHNAME, /* mxPathname */ \ 8491 0, /* pNext */ \ 8492 VFSNAME, /* zName */ \ 8493 (void*)&FINDER, /* pAppData */ \ 8494 unixOpen, /* xOpen */ \ 8495 unixDelete, /* xDelete */ \ 8496 unixAccess, /* xAccess */ \ 8497 unixFullPathname, /* xFullPathname */ \ 8498 unixDlOpen, /* xDlOpen */ \ 8499 unixDlError, /* xDlError */ \ 8500 unixDlSym, /* xDlSym */ \ 8501 unixDlClose, /* xDlClose */ \ 8502 unixRandomness, /* xRandomness */ \ 8503 unixSleep, /* xSleep */ \ 8504 unixCurrentTime, /* xCurrentTime */ \ 8505 unixGetLastError, /* xGetLastError */ \ 8506 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \ 8507 unixSetSystemCall, /* xSetSystemCall */ \ 8508 unixGetSystemCall, /* xGetSystemCall */ \ 8509 unixNextSystemCall, /* xNextSystemCall */ \ 8510 } 8511 8512 /* 8513 ** All default VFSes for unix are contained in the following array. 8514 ** 8515 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified 8516 ** by the SQLite core when the VFS is registered. So the following 8517 ** array cannot be const. 8518 */ 8519 static sqlite3_vfs aVfs[] = { 8520 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) 8521 UNIXVFS("unix", autolockIoFinder ), 8522 #elif OS_VXWORKS 8523 UNIXVFS("unix", vxworksIoFinder ), 8524 #else 8525 UNIXVFS("unix", posixIoFinder ), 8526 #endif 8527 UNIXVFS("unix-none", nolockIoFinder ), 8528 UNIXVFS("unix-dotfile", dotlockIoFinder ), 8529 UNIXVFS("unix-excl", posixIoFinder ), 8530 #if OS_VXWORKS 8531 UNIXVFS("unix-namedsem", semIoFinder ), 8532 #endif 8533 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS 8534 UNIXVFS("unix-posix", posixIoFinder ), 8535 #endif 8536 #if SQLITE_ENABLE_LOCKING_STYLE 8537 UNIXVFS("unix-flock", flockIoFinder ), 8538 #endif 8539 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) 8540 UNIXVFS("unix-afp", afpIoFinder ), 8541 UNIXVFS("unix-nfs", nfsIoFinder ), 8542 UNIXVFS("unix-proxy", proxyIoFinder ), 8543 #endif 8544 }; 8545 unsigned int i; /* Loop counter */ 8546 8547 /* Double-check that the aSyscall[] array has been constructed 8548 ** correctly. See ticket [`bb3a86e890c8e96ab`] */ 8549 assert( ArraySize(aSyscall)==29 ); 8550 8551 /* Register all VFSes defined in the aVfs[] array */ 8552 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){ 8553 #ifdef SQLITE_DEFAULT_UNIX_VFS 8554 sqlite3_vfs_register(&aVfs[i], 8555 0==strcmp(aVfs[i].zName,SQLITE_DEFAULT_UNIX_VFS)); 8556 #else 8557 sqlite3_vfs_register(&aVfs[i], i==0); 8558 #endif 8559 } 8560 #ifdef SQLITE_OS_KV_OPTIONAL 8561 sqlite3KvvfsInit(); 8562 #endif 8563 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1); 8564 #if OS_VXWORKS 8565 vxworksMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS2); 8566 #endif 8567 8568 #ifndef SQLITE_OMIT_WAL 8569 /* Validate lock assumptions */ 8570 assert( SQLITE_SHM_NLOCK==8 ); /* Number of available locks */ 8571 assert( UNIX_SHM_BASE==120 ); /* Start of locking area */ 8572 /* Locks: 8573 ** WRITE UNIX_SHM_BASE 120 8574 ** CKPT UNIX_SHM_BASE+1 121 8575 ** RECOVER UNIX_SHM_BASE+2 122 8576 ** READ-0 UNIX_SHM_BASE+3 123 8577 ** READ-1 UNIX_SHM_BASE+4 124 8578 ** READ-2 UNIX_SHM_BASE+5 125 8579 ** READ-3 UNIX_SHM_BASE+6 126 8580 ** READ-4 UNIX_SHM_BASE+7 127 8581 ** DMS UNIX_SHM_BASE+8 128 8582 */ 8583 assert( UNIX_SHM_DMS==128 ); /* Byte offset of the deadman-switch */ 8584 #endif 8585 8586 return SQLITE_OK; 8587 } 8588 8589 /* 8590 ** Shutdown the operating system interface. 8591 ** 8592 ** Some operating systems might need to do some cleanup in this routine, 8593 ** to release dynamically allocated objects. But not on unix. 8594 ** This routine is a no-op for unix. 8595 */ 8596 int sqlite3_os_end(void){ 8597 unixBigLock = 0; 8598 #if OS_VXWORKS 8599 vxworksMutex = 0; 8600 #endif 8601 return SQLITE_OK; 8602 } 8603 8604 #endif /* SQLITE_OS_UNIX */