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_win.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_win.c` 5370 lines ยท 176147 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 code that is specific to Windows. 14 */ 15 #include "sqliteInt.h" 16 #if SQLITE_OS_WIN /* This file is used for Windows only */ 17 18 /* 19 ** Include code that is common to all os_*.c files 20 */ 21 #include "os_common.h" 22 23 /* 24 ** Include the header file for the Windows VFS. 25 */ 26 #include "os_win.h" 27 28 /* 29 ** This constant should already be defined (in the "WinDef.h" SDK file). 30 */ 31 #ifndef MAX_PATH 32 # define MAX_PATH (260) 33 #endif 34 35 /* 36 ** Maximum pathname length (in chars) for Win32. This should normally be 37 ** MAX_PATH. 38 */ 39 #ifndef SQLITE_WIN32_MAX_PATH_CHARS 40 # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH) 41 #endif 42 43 /* 44 ** This constant should already be defined (in the "WinNT.h" SDK file). 45 */ 46 #ifndef UNICODE_STRING_MAX_CHARS 47 # define UNICODE_STRING_MAX_CHARS (32767) 48 #endif 49 50 /* 51 ** Maximum pathname length (in chars) for WinNT. This should normally be 52 ** UNICODE_STRING_MAX_CHARS. 53 */ 54 #ifndef SQLITE_WINNT_MAX_PATH_CHARS 55 # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS) 56 #endif 57 58 /* 59 ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in 60 ** characters, so we allocate 4 bytes per character assuming worst-case of 61 ** 4-bytes-per-character for UTF8. 62 */ 63 #ifndef SQLITE_WIN32_MAX_PATH_BYTES 64 # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4) 65 #endif 66 67 /* 68 ** Maximum pathname length (in bytes) for WinNT. This should normally be 69 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR). 70 */ 71 #ifndef SQLITE_WINNT_MAX_PATH_BYTES 72 # define SQLITE_WINNT_MAX_PATH_BYTES \ 73 (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS) 74 #endif 75 76 /* 77 ** Maximum error message length (in chars) for WinRT. 78 */ 79 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS 80 # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024) 81 #endif 82 83 /* 84 ** Returns non-zero if the character should be treated as a directory 85 ** separator. 86 */ 87 #ifndef winIsDirSep 88 # define winIsDirSep(a) (((a) == '/') || ((a) == '\\')) 89 #endif 90 91 /* 92 ** This macro is used when a local variable is set to a value that is 93 ** [sometimes] not used by the code (e.g. via conditional compilation). 94 */ 95 #ifndef UNUSED_VARIABLE_VALUE 96 # define UNUSED_VARIABLE_VALUE(x) (void)(x) 97 #endif 98 99 /* 100 ** Returns the character that should be used as the directory separator. 101 */ 102 #ifndef winGetDirSep 103 # define winGetDirSep() '\\' 104 #endif 105 106 /* 107 ** Some older Microsoft compilers lack the following definition. 108 */ 109 #ifndef INVALID_FILE_ATTRIBUTES 110 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 111 #endif 112 113 #ifndef FILE_FLAG_MASK 114 # define FILE_FLAG_MASK (0xFF3C0000) 115 #endif 116 117 #ifndef FILE_ATTRIBUTE_MASK 118 # define FILE_ATTRIBUTE_MASK (0x0003FFF7) 119 #endif 120 121 #ifndef SQLITE_OMIT_WAL 122 /* Forward references to structures used for WAL */ 123 typedef struct winShm winShm; /* A connection to shared-memory */ 124 typedef struct winShmNode winShmNode; /* A region of shared-memory */ 125 #endif 126 127 /* 128 ** The winFile structure is a subclass of sqlite3_file* specific to the win32 129 ** portability layer. 130 */ 131 typedef struct winFile winFile; 132 struct winFile { 133 const sqlite3_io_methods *pMethod; /*** Must be first ***/ 134 sqlite3_vfs *pVfs; /* The VFS used to open this file */ 135 HANDLE h; /* Handle for accessing the file */ 136 u8 locktype; /* Type of lock currently held on this file */ 137 short sharedLockByte; /* Randomly chosen byte used as a shared lock */ 138 u8 ctrlFlags; /* Flags. See WINFILE_* below */ 139 DWORD lastErrno; /* The Windows errno from the last I/O error */ 140 #ifndef SQLITE_OMIT_WAL 141 winShm *pShm; /* Instance of shared memory on this file */ 142 #endif 143 const char *zPath; /* Full pathname of this file */ 144 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */ 145 #if SQLITE_MAX_MMAP_SIZE>0 146 int nFetchOut; /* Number of outstanding xFetch references */ 147 HANDLE hMap; /* Handle for accessing memory mapping */ 148 void *pMapRegion; /* Area memory mapped */ 149 sqlite3_int64 mmapSize; /* Size of mapped region */ 150 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ 151 #endif 152 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 153 DWORD iBusyTimeout; /* Wait this many millisec on locks */ 154 int bBlockOnConnect; 155 #endif 156 }; 157 158 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 159 # define winFileBusyTimeout(pDbFd) pDbFd->iBusyTimeout 160 #else 161 # define winFileBusyTimeout(pDbFd) 0 162 #endif 163 164 /* 165 ** The winVfsAppData structure is used for the pAppData member for all of the 166 ** Win32 VFS variants. 167 */ 168 typedef struct winVfsAppData winVfsAppData; 169 struct winVfsAppData { 170 const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */ 171 void *pAppData; /* The extra pAppData, if any. */ 172 BOOL bNoLock; /* Non-zero if locking is disabled. */ 173 }; 174 175 /* 176 ** Allowed values for winFile.ctrlFlags 177 */ 178 #define WINFILE_RDONLY 0x02 /* Connection is read only */ 179 #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */ 180 #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ 181 182 /* 183 * The size of the buffer used by sqlite3_win32_write_debug(). 184 */ 185 #ifndef SQLITE_WIN32_DBG_BUF_SIZE 186 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD))) 187 #endif 188 189 /* 190 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the 191 * various Win32 API heap functions instead of our own. 192 */ 193 #ifdef SQLITE_WIN32_MALLOC 194 195 /* 196 * If this is non-zero, an isolated heap will be created by the native Win32 197 * allocator subsystem; otherwise, the default process heap will be used. This 198 * setting has no effect when compiling for WinRT. By default, this is enabled 199 * and an isolated heap will be created to store all allocated data. 200 * 201 ****************************************************************************** 202 * WARNING: It is important to note that when this setting is non-zero and the 203 * winMemShutdown function is called (e.g. by the sqlite3_shutdown 204 * function), all data that was allocated using the isolated heap will 205 * be freed immediately and any attempt to access any of that freed 206 * data will almost certainly result in an immediate access violation. 207 ****************************************************************************** 208 */ 209 #ifndef SQLITE_WIN32_HEAP_CREATE 210 # define SQLITE_WIN32_HEAP_CREATE (TRUE) 211 #endif 212 213 /* 214 * This is the maximum possible initial size of the Win32-specific heap, in 215 * bytes. 216 */ 217 #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE 218 # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U) 219 #endif 220 221 /* 222 * This is the extra space for the initial size of the Win32-specific heap, 223 * in bytes. This value may be zero. 224 */ 225 #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA 226 # define SQLITE_WIN32_HEAP_INIT_EXTRA (`4194304`) 227 #endif 228 229 /* 230 * Calculate the maximum legal cache size, in pages, based on the maximum 231 * possible initial heap size and the default page size, setting aside the 232 * needed extra space. 233 */ 234 #ifndef SQLITE_WIN32_MAX_CACHE_SIZE 235 # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \ 236 (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \ 237 (SQLITE_DEFAULT_PAGE_SIZE)) 238 #endif 239 240 /* 241 * This is cache size used in the calculation of the initial size of the 242 * Win32-specific heap. It cannot be negative. 243 */ 244 #ifndef SQLITE_WIN32_CACHE_SIZE 245 # if SQLITE_DEFAULT_CACHE_SIZE>=0 246 # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE) 247 # else 248 # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE)) 249 # endif 250 #endif 251 252 /* 253 * Make sure that the calculated cache size, in pages, cannot cause the 254 * initial size of the Win32-specific heap to exceed the maximum amount 255 * of memory that can be specified in the call to HeapCreate. 256 */ 257 #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE 258 # undef SQLITE_WIN32_CACHE_SIZE 259 # define SQLITE_WIN32_CACHE_SIZE (2000) 260 #endif 261 262 /* 263 * The initial size of the Win32-specific heap. This value may be zero. 264 */ 265 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE 266 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \ 267 (SQLITE_DEFAULT_PAGE_SIZE) + \ 268 (SQLITE_WIN32_HEAP_INIT_EXTRA)) 269 #endif 270 271 /* 272 * The maximum size of the Win32-specific heap. This value may be zero. 273 */ 274 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE 275 # define SQLITE_WIN32_HEAP_MAX_SIZE (0) 276 #endif 277 278 /* 279 * The extra flags to use in calls to the Win32 heap APIs. This value may be 280 * zero for the default behavior. 281 */ 282 #ifndef SQLITE_WIN32_HEAP_FLAGS 283 # define SQLITE_WIN32_HEAP_FLAGS (0) 284 #endif 285 286 287 /* 288 ** The winMemData structure stores information required by the Win32-specific 289 ** sqlite3_mem_methods implementation. 290 */ 291 typedef struct winMemData winMemData; 292 struct winMemData { 293 #ifndef NDEBUG 294 u32 magic1; /* Magic number to detect structure corruption. */ 295 #endif 296 HANDLE hHeap; /* The handle to our heap. */ 297 BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */ 298 #ifndef NDEBUG 299 u32 magic2; /* Magic number to detect structure corruption. */ 300 #endif 301 }; 302 303 #ifndef NDEBUG 304 #define WINMEM_MAGIC1 0x42b2830b 305 #define WINMEM_MAGIC2 0xbd4d7cf4 306 #endif 307 308 static struct winMemData win_mem_data = { 309 #ifndef NDEBUG 310 WINMEM_MAGIC1, 311 #endif 312 NULL, FALSE 313 #ifndef NDEBUG 314 ,WINMEM_MAGIC2 315 #endif 316 }; 317 318 #ifndef NDEBUG 319 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 ) 320 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 ) 321 #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2(); 322 #else 323 #define winMemAssertMagic() 324 #endif 325 326 #define winMemGetDataPtr() &win_mem_data 327 #define winMemGetHeap() win_mem_data.hHeap 328 #define winMemGetOwned() win_mem_data.bOwned 329 330 static void *winMemMalloc(int nBytes); 331 static void winMemFree(void *pPrior); 332 static void *winMemRealloc(void *pPrior, int nBytes); 333 static int winMemSize(void *p); 334 static int winMemRoundup(int n); 335 static int winMemInit(void *pAppData); 336 static void winMemShutdown(void *pAppData); 337 338 const sqlite3_mem_methods *sqlite3MemGetWin32(void); 339 #endif /* SQLITE_WIN32_MALLOC */ 340 341 #ifndef SYSCALL 342 # define SYSCALL sqlite3_syscall_ptr 343 #endif 344 345 /* 346 ** Many system calls are accessed through pointer-to-functions so that 347 ** they may be overridden at runtime to facilitate fault injection during 348 ** testing and sandboxing. The following array holds the names and pointers 349 ** to all overrideable system calls. 350 */ 351 static struct win_syscall { 352 const char *zName; /* Name of the system call */ 353 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ 354 sqlite3_syscall_ptr pDefault; /* Default value */ 355 } aSyscall[] = { 356 { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 }, 357 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent) 358 359 { "CloseHandle", (SYSCALL)CloseHandle, 0 }, 360 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[1].pCurrent) 361 362 363 { "CreateFileW", (SYSCALL)CreateFileW, 0 }, 364 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \ 365 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[2].pCurrent) 366 367 #if defined(SQLITE_UWP) 368 { "CreateFileMappingFromApp",(SYSCALL)CreateFileMappingFromApp,0 }, 369 #else 370 { "CreateFileMappingFromApp",(SYSCALL)0, 0 }, 371 #endif 372 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE,\ 373 PSECURITY_ATTRIBUTES, \ 374 ULONG,ULONG64,PCWSTR))aSyscall[3].pCurrent) 375 376 #if !defined(SQLITE_UWP) 377 { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 }, 378 #else 379 { "CreateFileMappingW", (SYSCALL)0, 0 }, 380 #endif 381 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \ 382 DWORD,DWORD,DWORD,LPCWSTR))aSyscall[4].pCurrent) 383 384 { "DeleteFileW", (SYSCALL)DeleteFileW, 0 }, 385 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[5].pCurrent) 386 387 { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 }, 388 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[6].pCurrent) 389 390 { "FormatMessageW", (SYSCALL)FormatMessageW, 0 }, 391 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \ 392 DWORD,va_list*))aSyscall[7].pCurrent) 393 394 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_UWP) 395 { "FreeLibrary", (SYSCALL)FreeLibrary, 0 }, 396 #else 397 { "FreeLibrary", (SYSCALL)0, 0 }, 398 #endif 399 400 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[8].pCurrent) 401 402 { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 }, 403 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[9].pCurrent) 404 405 { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 }, 406 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent) 407 408 { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 }, 409 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \ 410 LPVOID))aSyscall[11].pCurrent) 411 412 { "GetFileSizeEx", (SYSCALL)GetFileSizeEx, 0 }, 413 #define osGetFileSizeEx ((BOOL(WINAPI*)(HANDLE, \ 414 PLARGE_INTEGER))aSyscall[12].pCurrent) 415 416 { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 }, 417 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \ 418 LPWSTR*))aSyscall[13].pCurrent) 419 420 { "GetLastError", (SYSCALL)GetLastError, 0 }, 421 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[14].pCurrent) 422 423 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_UWP) 424 { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 }, 425 #else 426 { "GetProcAddressA", (SYSCALL)0, 0 }, 427 #endif 428 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \ 429 LPCSTR))aSyscall[15].pCurrent) 430 431 { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 }, 432 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[16].pCurrent) 433 434 { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 }, 435 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \ 436 LPFILETIME))aSyscall[17].pCurrent) 437 438 #ifdef SQLITE_UWP 439 { "GetTempPathW", (SYSCALL)0, 0 }, 440 #else 441 { "GetTempPathW", (SYSCALL)GetTempPathW, 0 }, 442 #endif 443 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[18].pCurrent) 444 445 { "GetTickCount64", (SYSCALL)GetTickCount64, 0 }, 446 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[19].pCurrent) 447 448 #ifdef SQLITE_UWP 449 { "HeapAlloc", (SYSCALL)0, 0 }, 450 #else 451 { "HeapAlloc", (SYSCALL)HeapAlloc, 0 }, 452 #endif 453 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \ 454 SIZE_T))aSyscall[20].pCurrent) 455 456 #ifdef SQLITE_UWP 457 { "HeapCreate", (SYSCALL)0, 0 }, 458 #else 459 { "HeapCreate", (SYSCALL)HeapCreate, 0 }, 460 #endif 461 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \ 462 SIZE_T))aSyscall[21].pCurrent) 463 464 #ifdef SQLITE_UWP 465 { "HeapDestroy", (SYSCALL)0, 0 }, 466 #else 467 { "HeapDestroy", (SYSCALL)HeapDestroy, 0 }, 468 #endif 469 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[22].pCurrent) 470 471 #ifdef SQLITE_UWP 472 { "HeapFree", (SYSCALL)0, 0 }, 473 #else 474 { "HeapFree", (SYSCALL)HeapFree, 0 }, 475 #endif 476 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[23].pCurrent) 477 478 #ifdef SQLITE_UWP 479 { "HeapReAlloc", (SYSCALL)0, 0 }, 480 #else 481 { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 }, 482 #endif 483 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \ 484 SIZE_T))aSyscall[24].pCurrent) 485 486 #ifdef SQLITE_UWP 487 { "HeapSize", (SYSCALL)0, 0 }, 488 #else 489 { "HeapSize", (SYSCALL)HeapSize, 0 }, 490 #endif 491 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \ 492 LPCVOID))aSyscall[25].pCurrent) 493 494 #ifdef SQLITE_UWP 495 { "HeapValidate", (SYSCALL)0, 0 }, 496 #else 497 { "HeapValidate", (SYSCALL)HeapValidate, 0 }, 498 #endif 499 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \ 500 LPCVOID))aSyscall[26].pCurrent) 501 502 #ifdef SQLITE_UWP 503 { "HeapCompact", (SYSCALL)0, 0 }, 504 #else 505 { "HeapCompact", (SYSCALL)HeapCompact, 0 }, 506 #endif 507 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[27].pCurrent) 508 509 510 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_UWP) 511 { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 }, 512 #else 513 { "LoadLibraryW", (SYSCALL)0, 0 }, 514 #endif 515 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[28].pCurrent) 516 517 { "LocalFree", (SYSCALL)LocalFree, 0 }, 518 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[29].pCurrent) 519 520 { "LockFileEx", (SYSCALL)LockFileEx, 0 }, 521 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \ 522 LPOVERLAPPED))aSyscall[30].pCurrent) 523 524 #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \ 525 && !defined(SQLITE_UWP) 526 { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 }, 527 #else 528 { "MapViewOfFile", (SYSCALL)0, 0 }, 529 #endif 530 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ 531 SIZE_T))aSyscall[31].pCurrent) 532 533 #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \ 534 && defined(SQLITE_UWP) 535 { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 }, 536 #else 537 { "MapViewOfFileFromApp", (SYSCALL)0, 0 }, 538 #endif 539 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \ 540 SIZE_T))aSyscall[32].pCurrent) 541 542 { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 }, 543 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \ 544 int))aSyscall[33].pCurrent) 545 546 { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 }, 547 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \ 548 LARGE_INTEGER*))aSyscall[34].pCurrent) 549 550 { "ReadFile", (SYSCALL)ReadFile, 0 }, 551 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \ 552 LPOVERLAPPED))aSyscall[35].pCurrent) 553 554 { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 }, 555 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[36].pCurrent) 556 557 { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 }, 558 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER,\ 559 PLARGE_INTEGER,DWORD))aSyscall[37].pCurrent) 560 561 { "Sleep", (SYSCALL)Sleep, 0 }, 562 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[38].pCurrent) 563 564 { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 }, 565 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ 566 LPOVERLAPPED))aSyscall[39].pCurrent) 567 568 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 569 { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 }, 570 #else 571 { "UnmapViewOfFile", (SYSCALL)0, 0 }, 572 #endif 573 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[40].pCurrent) 574 575 { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 }, 576 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \ 577 LPCSTR,LPBOOL))aSyscall[41].pCurrent) 578 579 { "WriteFile", (SYSCALL)WriteFile, 0 }, 580 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \ 581 LPOVERLAPPED))aSyscall[42].pCurrent) 582 583 { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 }, 584 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \ 585 DWORD))aSyscall[43].pCurrent) 586 587 { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 }, 588 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \ 589 BOOL))aSyscall[44].pCurrent) 590 591 { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 }, 592 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[45].pCurrent) 593 594 { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 }, 595 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[46].pCurrent) 596 597 /* 598 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function" 599 ** is really just a macro that uses a compiler intrinsic (e.g. x64). 600 ** So do not try to make this is into a redefinable interface. 601 */ 602 #if defined(InterlockedCompareExchange) 603 { "InterlockedCompareExchange", (SYSCALL)0, 0 }, 604 #define osInterlockedCompareExchange InterlockedCompareExchange 605 #else 606 { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 }, 607 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG volatile*,\ 608 LONG,LONG))aSyscall[47].pCurrent) 609 #endif /* defined(InterlockedCompareExchange) */ 610 611 #if SQLITE_WIN32_USE_UUID 612 { "UuidCreate", (SYSCALL)UuidCreate, 0 }, 613 #else 614 { "UuidCreate", (SYSCALL)0, 0 }, 615 #endif 616 #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[48].pCurrent) 617 618 #if SQLITE_WIN32_USE_UUID 619 { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 }, 620 #else 621 { "UuidCreateSequential", (SYSCALL)0, 0 }, 622 #endif 623 #define osUuidCreateSequential \ 624 ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[49].pCurrent) 625 626 #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0 627 { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 }, 628 #else 629 { "FlushViewOfFile", (SYSCALL)0, 0 }, 630 #endif 631 #define osFlushViewOfFile \ 632 ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[50].pCurrent) 633 634 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 635 { "CreateEvent", (SYSCALL)CreateEvent, 0 }, 636 #else 637 { "CreateEvent", (SYSCALL)0, 0 }, 638 #endif 639 #define osCreateEvent ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \ 640 BOOL,LPCSTR))aSyscall[51].pCurrent) 641 642 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 643 { "CancelIo", (SYSCALL)CancelIo, 0 }, 644 #else 645 { "CancelIo", (SYSCALL)0, 0 }, 646 #endif 647 #define osCancelIo ((BOOL(WINAPI*)(HANDLE))aSyscall[52].pCurrent) 648 649 #ifndef _WIN32 650 { "getenv", (SYSCALL)getenv, 0 }, 651 #else 652 { "getenv", (SYSCALL)0, 0 }, 653 #endif 654 #define osGetenv ((const char *(*)(const char *))aSyscall[53].pCurrent) 655 656 #ifndef _WIN32 657 { "getcwd", (SYSCALL)getcwd, 0 }, 658 #else 659 { "getcwd", (SYSCALL)0, 0 }, 660 #endif 661 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[54].pCurrent) 662 663 #ifndef _WIN32 664 { "readlink", (SYSCALL)readlink, 0 }, 665 #else 666 { "readlink", (SYSCALL)0, 0 }, 667 #endif 668 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[55].pCurrent) 669 670 #ifndef _WIN32 671 { "lstat", (SYSCALL)lstat, 0 }, 672 #else 673 { "lstat", (SYSCALL)0, 0 }, 674 #endif 675 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[56].pCurrent) 676 677 #ifndef _WIN32 678 { "__errno", (SYSCALL)__errno, 0 }, 679 #else 680 { "__errno", (SYSCALL)0, 0 }, 681 #endif 682 #define osErrno (*((int*(*)(void))aSyscall[57].pCurrent)()) 683 684 #ifndef _WIN32 685 { "cygwin_conv_path", (SYSCALL)cygwin_conv_path, 0 }, 686 #else 687 { "cygwin_conv_path", (SYSCALL)0, 0 }, 688 #endif 689 #define osCygwin_conv_path ((size_t(*)(unsigned int, \ 690 const void *, void *, size_t))aSyscall[58].pCurrent) 691 692 { "GetDriveTypeW", (SYSCALL)GetDriveTypeW, 0 }, 693 #define osGetDriveTypeW ((UINT(WINAPI*)(LPCWSTR))aSyscall[59].pCurrent) 694 695 }; /* End of the overrideable system calls */ 696 697 /* 698 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the 699 ** "win32" VFSes. Return SQLITE_OK upon successfully updating the 700 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable 701 ** system call named zName. 702 */ 703 static int winSetSystemCall( 704 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ 705 const char *zName, /* Name of system call to override */ 706 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ 707 ){ 708 unsigned int i; 709 int rc = SQLITE_NOTFOUND; 710 711 UNUSED_PARAMETER(pNotUsed); 712 if( zName==0 ){ 713 /* If no zName is given, restore all system calls to their default 714 ** settings and return NULL 715 */ 716 rc = SQLITE_OK; 717 for(i=0; i0 ){ 882 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); 883 memcpy(zDbgBuf, zBuf, nMin); 884 osOutputDebugStringA(zDbgBuf); 885 }else{ 886 osOutputDebugStringA(zBuf); 887 } 888 } 889 890 void sqlite3_win32_sleep(DWORD milliseconds){ 891 osSleep(milliseconds); 892 } 893 894 #if SQLITE_MAX_WORKER_THREADS>0 && SQLITE_THREADSAFE>0 895 DWORD sqlite3Win32Wait(HANDLE hObject){ 896 DWORD rc; 897 while( (rc = osWaitForSingleObjectEx(hObject, INFINITE, 898 TRUE))==WAIT_IO_COMPLETION ){} 899 return rc; 900 } 901 #endif 902 #endif /* _WIN32 */ 903 904 #ifdef SQLITE_WIN32_MALLOC 905 /* 906 ** Allocate nBytes of memory. 907 */ 908 static void *winMemMalloc(int nBytes){ 909 HANDLE hHeap; 910 void *p; 911 912 winMemAssertMagic(); 913 hHeap = winMemGetHeap(); 914 assert( hHeap!=0 ); 915 assert( hHeap!=INVALID_HANDLE_VALUE ); 916 #if defined(SQLITE_WIN32_MALLOC_VALIDATE) 917 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); 918 #endif 919 assert( nBytes>=0 ); 920 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes); 921 if( !p ){ 922 sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p", 923 nBytes, osGetLastError(), (void*)hHeap); 924 } 925 return p; 926 } 927 928 /* 929 ** Free memory. 930 */ 931 static void winMemFree(void *pPrior){ 932 HANDLE hHeap; 933 934 winMemAssertMagic(); 935 hHeap = winMemGetHeap(); 936 assert( hHeap!=0 ); 937 assert( hHeap!=INVALID_HANDLE_VALUE ); 938 #if defined(SQLITE_WIN32_MALLOC_VALIDATE) 939 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); 940 #endif 941 if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */ 942 if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){ 943 sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p", 944 pPrior, osGetLastError(), (void*)hHeap); 945 } 946 } 947 948 /* 949 ** Change the size of an existing memory allocation 950 */ 951 static void *winMemRealloc(void *pPrior, int nBytes){ 952 HANDLE hHeap; 953 void *p; 954 955 winMemAssertMagic(); 956 hHeap = winMemGetHeap(); 957 assert( hHeap!=0 ); 958 assert( hHeap!=INVALID_HANDLE_VALUE ); 959 #if defined(SQLITE_WIN32_MALLOC_VALIDATE) 960 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); 961 #endif 962 assert( nBytes>=0 ); 963 if( !pPrior ){ 964 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes); 965 }else{ 966 p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes); 967 } 968 if( !p ){ 969 sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p", 970 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(), 971 (void*)hHeap); 972 } 973 return p; 974 } 975 976 /* 977 ** Return the size of an outstanding allocation, in bytes. 978 */ 979 static int winMemSize(void *p){ 980 HANDLE hHeap; 981 SIZE_T n; 982 983 winMemAssertMagic(); 984 hHeap = winMemGetHeap(); 985 assert( hHeap!=0 ); 986 assert( hHeap!=INVALID_HANDLE_VALUE ); 987 #if defined(SQLITE_WIN32_MALLOC_VALIDATE) 988 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) ); 989 #endif 990 if( !p ) return 0; 991 n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p); 992 if( n==(SIZE_T)-1 ){ 993 sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p", 994 p, osGetLastError(), (void*)hHeap); 995 return 0; 996 } 997 return (int)n; 998 } 999 1000 /* 1001 ** Round up a request size to the next valid allocation size. 1002 */ 1003 static int winMemRoundup(int n){ 1004 return n; 1005 } 1006 1007 /* 1008 ** Initialize this module. 1009 */ 1010 static int winMemInit(void *pAppData){ 1011 winMemData *pWinMemData = (winMemData *)pAppData; 1012 1013 if( !pWinMemData ) return SQLITE_ERROR; 1014 assert( pWinMemData->magic1==WINMEM_MAGIC1 ); 1015 assert( pWinMemData->magic2==WINMEM_MAGIC2 ); 1016 1017 #if SQLITE_WIN32_HEAP_CREATE 1018 if( !pWinMemData->hHeap ){ 1019 DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE; 1020 DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap; 1021 if( dwMaximumSize==0 ){ 1022 dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE; 1023 }else if( dwInitialSize>dwMaximumSize ){ 1024 dwInitialSize = dwMaximumSize; 1025 } 1026 pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS, 1027 dwInitialSize, dwMaximumSize); 1028 if( !pWinMemData->hHeap ){ 1029 sqlite3_log(SQLITE_NOMEM, 1030 "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu", 1031 osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize, 1032 dwMaximumSize); 1033 return SQLITE_NOMEM_BKPT; 1034 } 1035 pWinMemData->bOwned = TRUE; 1036 assert( pWinMemData->bOwned ); 1037 } 1038 #else 1039 pWinMemData->hHeap = osGetProcessHeap(); 1040 if( !pWinMemData->hHeap ){ 1041 sqlite3_log(SQLITE_NOMEM, 1042 "failed to GetProcessHeap (%lu)", osGetLastError()); 1043 return SQLITE_NOMEM_BKPT; 1044 } 1045 pWinMemData->bOwned = FALSE; 1046 assert( !pWinMemData->bOwned ); 1047 #endif 1048 assert( pWinMemData->hHeap!=0 ); 1049 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); 1050 #if defined(SQLITE_WIN32_MALLOC_VALIDATE) 1051 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); 1052 #endif 1053 return SQLITE_OK; 1054 } 1055 1056 /* 1057 ** Deinitialize this module. 1058 */ 1059 static void winMemShutdown(void *pAppData){ 1060 winMemData *pWinMemData = (winMemData *)pAppData; 1061 1062 if( !pWinMemData ) return; 1063 assert( pWinMemData->magic1==WINMEM_MAGIC1 ); 1064 assert( pWinMemData->magic2==WINMEM_MAGIC2 ); 1065 1066 if( pWinMemData->hHeap ){ 1067 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); 1068 #if defined(SQLITE_WIN32_MALLOC_VALIDATE) 1069 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); 1070 #endif 1071 if( pWinMemData->bOwned ){ 1072 if( !osHeapDestroy(pWinMemData->hHeap) ){ 1073 sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p", 1074 osGetLastError(), (void*)pWinMemData->hHeap); 1075 } 1076 pWinMemData->bOwned = FALSE; 1077 } 1078 pWinMemData->hHeap = NULL; 1079 } 1080 } 1081 1082 /* 1083 ** Populate the low-level memory allocation function pointers in 1084 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The 1085 ** arguments specify the block of memory to manage. 1086 ** 1087 ** This routine is only called by sqlite3_config(), and therefore 1088 ** is not required to be threadsafe (it is not). 1089 */ 1090 const sqlite3_mem_methods *sqlite3MemGetWin32(void){ 1091 static const sqlite3_mem_methods winMemMethods = { 1092 winMemMalloc, 1093 winMemFree, 1094 winMemRealloc, 1095 winMemSize, 1096 winMemRoundup, 1097 winMemInit, 1098 winMemShutdown, 1099 &win_mem_data 1100 }; 1101 return &winMemMethods; 1102 } 1103 1104 void sqlite3MemSetDefault(void){ 1105 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32()); 1106 } 1107 #endif /* SQLITE_WIN32_MALLOC */ 1108 1109 #ifdef _WIN32 1110 /* 1111 ** Convert a UTF-8 string to Microsoft Unicode. 1112 ** 1113 ** Space to hold the returned string is obtained from sqlite3_malloc(). 1114 */ 1115 static LPWSTR winUtf8ToUnicode(const char *zText){ 1116 int nChar; 1117 LPWSTR zWideText; 1118 1119 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0); 1120 if( nChar==0 ){ 1121 return 0; 1122 } 1123 zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) ); 1124 if( zWideText==0 ){ 1125 return 0; 1126 } 1127 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText, 1128 nChar); 1129 if( nChar==0 ){ 1130 sqlite3_free(zWideText); 1131 zWideText = 0; 1132 } 1133 return zWideText; 1134 } 1135 #endif /* _WIN32 */ 1136 1137 /* 1138 ** Convert a Microsoft Unicode string to UTF-8. 1139 ** 1140 ** Space to hold the returned string is obtained from sqlite3_malloc(). 1141 */ 1142 static char *winUnicodeToUtf8(LPCWSTR zWideText){ 1143 int nByte; 1144 char *zText; 1145 1146 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0); 1147 if( nByte == 0 ){ 1148 return 0; 1149 } 1150 zText = sqlite3MallocZero( nByte ); 1151 if( zText==0 ){ 1152 return 0; 1153 } 1154 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte, 1155 0, 0); 1156 if( nByte == 0 ){ 1157 sqlite3_free(zText); 1158 zText = 0; 1159 } 1160 return zText; 1161 } 1162 1163 #ifdef _WIN32 1164 /* 1165 ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM 1166 ** code page. 1167 ** 1168 ** Space to hold the returned string is obtained from sqlite3_malloc(). 1169 */ 1170 static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){ 1171 int nWideChar; 1172 LPWSTR zMbcsText; 1173 int codepage = useAnsi ? CP_ACP : CP_OEMCP; 1174 1175 nWideChar = osMultiByteToWideChar(codepage, 0, zText, -1, NULL, 1176 0); 1177 if( nWideChar==0 ){ 1178 return 0; 1179 } 1180 zMbcsText = sqlite3MallocZero( nWideChar*sizeof(WCHAR) ); 1181 if( zMbcsText==0 ){ 1182 return 0; 1183 } 1184 nWideChar = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText, 1185 nWideChar); 1186 if( nWideChar==0 ){ 1187 sqlite3_free(zMbcsText); 1188 zMbcsText = 0; 1189 } 1190 return zMbcsText; 1191 } 1192 1193 /* 1194 ** Convert a Microsoft Unicode string to a multi-byte character string, 1195 ** using the ANSI or OEM code page. 1196 ** 1197 ** Space to hold the returned string is obtained from sqlite3_malloc(). 1198 */ 1199 static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){ 1200 int nByte; 1201 char *zText; 1202 int codepage = useAnsi ? CP_ACP : CP_OEMCP; 1203 1204 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0); 1205 if( nByte == 0 ){ 1206 return 0; 1207 } 1208 zText = sqlite3MallocZero( nByte ); 1209 if( zText==0 ){ 1210 return 0; 1211 } 1212 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText, 1213 nByte, 0, 0); 1214 if( nByte == 0 ){ 1215 sqlite3_free(zText); 1216 zText = 0; 1217 } 1218 return zText; 1219 } 1220 1221 /* 1222 ** Convert a multi-byte character string to UTF-8. 1223 ** 1224 ** Space to hold the returned string is obtained from sqlite3_malloc(). 1225 */ 1226 static char *winMbcsToUtf8(const char *zText, int useAnsi){ 1227 char *zTextUtf8; 1228 LPWSTR zTmpWide; 1229 1230 zTmpWide = winMbcsToUnicode(zText, useAnsi); 1231 if( zTmpWide==0 ){ 1232 return 0; 1233 } 1234 zTextUtf8 = winUnicodeToUtf8(zTmpWide); 1235 sqlite3_free(zTmpWide); 1236 return zTextUtf8; 1237 } 1238 1239 /* 1240 ** Convert a UTF-8 string to a multi-byte character string. 1241 ** 1242 ** Space to hold the returned string is obtained from sqlite3_malloc(). 1243 */ 1244 static char *winUtf8ToMbcs(const char *zText, int useAnsi){ 1245 char *zTextMbcs; 1246 LPWSTR zTmpWide; 1247 1248 zTmpWide = winUtf8ToUnicode(zText); 1249 if( zTmpWide==0 ){ 1250 return 0; 1251 } 1252 zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi); 1253 sqlite3_free(zTmpWide); 1254 return zTextMbcs; 1255 } 1256 1257 /* 1258 ** This is a public wrapper for the winUtf8ToUnicode() function. 1259 */ 1260 LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){ 1261 #ifdef SQLITE_ENABLE_API_ARMOR 1262 if( !zText ){ 1263 (void)SQLITE_MISUSE_BKPT; 1264 return 0; 1265 } 1266 #endif 1267 #ifndef SQLITE_OMIT_AUTOINIT 1268 if( sqlite3_initialize() ) return 0; 1269 #endif 1270 return winUtf8ToUnicode(zText); 1271 } 1272 1273 /* 1274 ** This is a public wrapper for the winUnicodeToUtf8() function. 1275 */ 1276 char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){ 1277 #ifdef SQLITE_ENABLE_API_ARMOR 1278 if( !zWideText ){ 1279 (void)SQLITE_MISUSE_BKPT; 1280 return 0; 1281 } 1282 #endif 1283 #ifndef SQLITE_OMIT_AUTOINIT 1284 if( sqlite3_initialize() ) return 0; 1285 #endif 1286 return winUnicodeToUtf8(zWideText); 1287 } 1288 1289 /* 1290 ** This is a public wrapper for the winMbcsToUtf8() function. 1291 */ 1292 char *sqlite3_win32_mbcs_to_utf8(const char *zText){ 1293 #ifdef SQLITE_ENABLE_API_ARMOR 1294 if( !zText ){ 1295 (void)SQLITE_MISUSE_BKPT; 1296 return 0; 1297 } 1298 #endif 1299 #ifndef SQLITE_OMIT_AUTOINIT 1300 if( sqlite3_initialize() ) return 0; 1301 #endif 1302 return winMbcsToUtf8(zText, osAreFileApisANSI()); 1303 } 1304 1305 /* 1306 ** This is a public wrapper for the winMbcsToUtf8() function. 1307 */ 1308 char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){ 1309 #ifdef SQLITE_ENABLE_API_ARMOR 1310 if( !zText ){ 1311 (void)SQLITE_MISUSE_BKPT; 1312 return 0; 1313 } 1314 #endif 1315 #ifndef SQLITE_OMIT_AUTOINIT 1316 if( sqlite3_initialize() ) return 0; 1317 #endif 1318 return winMbcsToUtf8(zText, useAnsi); 1319 } 1320 1321 /* 1322 ** This is a public wrapper for the winUtf8ToMbcs() function. 1323 */ 1324 char *sqlite3_win32_utf8_to_mbcs(const char *zText){ 1325 #ifdef SQLITE_ENABLE_API_ARMOR 1326 if( !zText ){ 1327 (void)SQLITE_MISUSE_BKPT; 1328 return 0; 1329 } 1330 #endif 1331 #ifndef SQLITE_OMIT_AUTOINIT 1332 if( sqlite3_initialize() ) return 0; 1333 #endif 1334 return winUtf8ToMbcs(zText, osAreFileApisANSI()); 1335 } 1336 1337 /* 1338 ** This is a public wrapper for the winUtf8ToMbcs() function. 1339 */ 1340 char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){ 1341 #ifdef SQLITE_ENABLE_API_ARMOR 1342 if( !zText ){ 1343 (void)SQLITE_MISUSE_BKPT; 1344 return 0; 1345 } 1346 #endif 1347 #ifndef SQLITE_OMIT_AUTOINIT 1348 if( sqlite3_initialize() ) return 0; 1349 #endif 1350 return winUtf8ToMbcs(zText, useAnsi); 1351 } 1352 1353 /* 1354 ** This function is the same as sqlite3_win32_set_directory (below); however, 1355 ** it accepts a UTF-8 string. 1356 */ 1357 int sqlite3_win32_set_directory8( 1358 unsigned long type, /* Identifier for directory being set or reset */ 1359 const char *zValue /* New value for directory being set or reset */ 1360 ){ 1361 char **ppDirectory = 0; 1362 int rc; 1363 #ifndef SQLITE_OMIT_AUTOINIT 1364 rc = sqlite3_initialize(); 1365 if( rc ) return rc; 1366 #endif 1367 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR)); 1368 if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){ 1369 ppDirectory = &sqlite3_data_directory; 1370 }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){ 1371 ppDirectory = &sqlite3_temp_directory; 1372 } 1373 assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE 1374 || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE 1375 ); 1376 assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) ); 1377 if( ppDirectory ){ 1378 char *zCopy = 0; 1379 if( zValue && zValue[0] ){ 1380 zCopy = sqlite3_mprintf("%s", zValue); 1381 if ( zCopy==0 ){ 1382 rc = SQLITE_NOMEM_BKPT; 1383 goto set_directory8_done; 1384 } 1385 } 1386 sqlite3_free(*ppDirectory); 1387 *ppDirectory = zCopy; 1388 rc = SQLITE_OK; 1389 }else{ 1390 rc = SQLITE_ERROR; 1391 } 1392 set_directory8_done: 1393 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR)); 1394 return rc; 1395 } 1396 1397 /* 1398 ** This function is the same as sqlite3_win32_set_directory (below); however, 1399 ** it accepts a UTF-16 string. 1400 */ 1401 int sqlite3_win32_set_directory16( 1402 unsigned long type, /* Identifier for directory being set or reset */ 1403 const void *zValue /* New value for directory being set or reset */ 1404 ){ 1405 int rc; 1406 char *zUtf8 = 0; 1407 if( zValue ){ 1408 zUtf8 = sqlite3_win32_unicode_to_utf8(zValue); 1409 if( zUtf8==0 ) return SQLITE_NOMEM_BKPT; 1410 } 1411 rc = sqlite3_win32_set_directory8(type, zUtf8); 1412 if( zUtf8 ) sqlite3_free(zUtf8); 1413 return rc; 1414 } 1415 1416 /* 1417 ** This function sets the data directory or the temporary directory based on 1418 ** the provided arguments. The type argument must be 1 in order to set the 1419 ** data directory or 2 in order to set the temporary directory. The zValue 1420 ** argument is the name of the directory to use. The return value will be 1421 ** SQLITE_OK if successful. 1422 */ 1423 int sqlite3_win32_set_directory( 1424 unsigned long type, /* Identifier for directory being set or reset */ 1425 void *zValue /* New value for directory being set or reset */ 1426 ){ 1427 return sqlite3_win32_set_directory16(type, zValue); 1428 } 1429 #endif /* _WIN32 */ 1430 1431 /* 1432 ** The return value of winGetLastErrorMsg 1433 ** is zero if the error message fits in the buffer, or non-zero 1434 ** otherwise (if the message was truncated). 1435 */ 1436 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){ 1437 /* FormatMessage returns 0 on failure. Otherwise it 1438 ** returns the number of TCHARs written to the output 1439 ** buffer, excluding the terminating null char. 1440 */ 1441 DWORD dwLen = 0; 1442 char *zOut = 0; 1443 LPWSTR zTempWide = NULL; 1444 dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | 1445 FORMAT_MESSAGE_FROM_SYSTEM | 1446 FORMAT_MESSAGE_IGNORE_INSERTS, 1447 NULL, 1448 lastErrno, 1449 0, 1450 (LPWSTR) &zTempWide, 1451 0, 1452 0); 1453 if( dwLen > 0 ){ 1454 /* allocate a buffer and convert to UTF8 */ 1455 sqlite3BeginBenignMalloc(); 1456 zOut = winUnicodeToUtf8(zTempWide); 1457 sqlite3EndBenignMalloc(); 1458 /* free the system buffer allocated by FormatMessage */ 1459 osLocalFree(zTempWide); 1460 } 1461 if( 0 == dwLen ){ 1462 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno); 1463 }else{ 1464 /* copy a maximum of nBuf chars to output buffer */ 1465 sqlite3_snprintf(nBuf, zBuf, "%s", zOut); 1466 /* free the UTF8 buffer */ 1467 sqlite3_free(zOut); 1468 } 1469 return 0; 1470 } 1471 1472 /* 1473 ** 1474 ** This function - winLogErrorAtLine() - is only ever called via the macro 1475 ** winLogError(). 1476 ** 1477 ** This routine is invoked after an error occurs in an OS function. 1478 ** It logs a message using sqlite3_log() containing the current value of 1479 ** error code and, if possible, the human-readable equivalent from 1480 ** FormatMessage. 1481 ** 1482 ** The first argument passed to the macro should be the error code that 1483 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 1484 ** The two subsequent arguments should be the name of the OS function that 1485 ** failed and the associated file-system path, if any. 1486 */ 1487 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__) 1488 static int winLogErrorAtLine( 1489 int errcode, /* SQLite error code */ 1490 DWORD lastErrno, /* Win32 last error */ 1491 const char *zFunc, /* Name of OS function that failed */ 1492 const char *zPath, /* File path associated with error */ 1493 int iLine /* Source line number where error occurred */ 1494 ){ 1495 char zMsg[500]; /* Human readable error text */ 1496 int i; /* Loop counter */ 1497 1498 zMsg[0] = 0; 1499 winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg); 1500 assert( errcode!=SQLITE_OK ); 1501 if( zPath==0 ) zPath = ""; 1502 for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){} 1503 zMsg[i] = 0; 1504 sqlite3_log(errcode, 1505 "os_win.c:%d: (%lu) %s(%s) - %s", 1506 iLine, lastErrno, zFunc, zPath, zMsg 1507 ); 1508 1509 return errcode; 1510 } 1511 1512 /* 1513 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile() 1514 ** will be retried following a locking error - probably caused by 1515 ** antivirus software. Also the initial delay before the first retry. 1516 ** The delay increases linearly with each retry. 1517 */ 1518 #ifndef SQLITE_WIN32_IOERR_RETRY 1519 # define SQLITE_WIN32_IOERR_RETRY 10 1520 #endif 1521 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY 1522 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25 1523 #endif 1524 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY; 1525 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY; 1526 1527 /* 1528 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O 1529 ** error code obtained via GetLastError() is eligible to be retried. It 1530 ** must accept the error code DWORD as its only argument and should return 1531 ** non-zero if the error code is transient in nature and the operation 1532 ** responsible for generating the original error might succeed upon being 1533 ** retried. The argument to this macro should be a variable. 1534 ** 1535 ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it 1536 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1" 1537 ** returns zero. The "winIoerrCanRetry2" macro is completely optional and 1538 ** may be used to include additional error codes in the set that should 1539 ** result in the failing I/O operation being retried by the caller. If 1540 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics 1541 ** identical to those of the "winIoerrCanRetry1" macro. 1542 */ 1543 #if !defined(winIoerrCanRetry1) 1544 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \ 1545 ((a)==ERROR_SHARING_VIOLATION) || \ 1546 ((a)==ERROR_LOCK_VIOLATION) || \ 1547 ((a)==ERROR_DEV_NOT_EXIST) || \ 1548 ((a)==ERROR_NETNAME_DELETED) || \ 1549 ((a)==ERROR_SEM_TIMEOUT) || \ 1550 ((a)==ERROR_NETWORK_UNREACHABLE)) 1551 #endif 1552 1553 /* 1554 ** If a ReadFile() or WriteFile() error occurs, invoke this routine 1555 ** to see if it should be retried. Return TRUE to retry. Return FALSE 1556 ** to give up with an error. 1557 */ 1558 static int winRetryIoerr(int *pnRetry, DWORD *pError){ 1559 DWORD e = osGetLastError(); 1560 if( *pnRetry>=winIoerrRetry ){ 1561 if( pError ){ 1562 *pError = e; 1563 } 1564 return 0; 1565 } 1566 if( winIoerrCanRetry1(e) ){ 1567 osSleep(winIoerrRetryDelay*(1+*pnRetry)); 1568 ++*pnRetry; 1569 return 1; 1570 } 1571 #if defined(winIoerrCanRetry2) 1572 else if( winIoerrCanRetry2(e) ){ 1573 osSleep(winIoerrRetryDelay*(1+*pnRetry)); 1574 ++*pnRetry; 1575 return 1; 1576 } 1577 #endif 1578 if( pError ){ 1579 *pError = e; 1580 } 1581 return 0; 1582 } 1583 1584 /* 1585 ** Log a I/O error retry episode. 1586 */ 1587 static void winLogIoerr(int nRetry, int lineno){ 1588 if( nRetry ){ 1589 sqlite3_log(SQLITE_NOTICE, 1590 "delayed %dms for lock/sharing conflict at line %d", 1591 winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno 1592 ); 1593 } 1594 } 1595 1596 1597 /* 1598 ** Lock a file region. 1599 */ 1600 static BOOL winLockFile( 1601 LPHANDLE phFile, 1602 DWORD flags, 1603 DWORD offsetLow, 1604 DWORD offsetHigh, 1605 DWORD numBytesLow, 1606 DWORD numBytesHigh 1607 ){ 1608 OVERLAPPED ovlp; 1609 memset(&ovlp, 0, sizeof(OVERLAPPED)); 1610 ovlp.Offset = offsetLow; 1611 ovlp.OffsetHigh = offsetHigh; 1612 return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp); 1613 } 1614 1615 #ifndef SQLITE_OMIT_WAL 1616 /* 1617 ** Lock a region of nByte bytes starting at offset offset of file hFile. 1618 ** Take an EXCLUSIVE lock if parameter bExclusive is true, or a SHARED lock 1619 ** otherwise. If nMs is greater than zero and the lock cannot be obtained 1620 ** immediately, block for that many ms before giving up. 1621 ** 1622 ** This function returns SQLITE_OK if the lock is obtained successfully. If 1623 ** some other process holds the lock, SQLITE_BUSY is returned if nMs==0, or 1624 ** SQLITE_BUSY_TIMEOUT otherwise. Or, if an error occurs, SQLITE_IOERR. 1625 */ 1626 static int winHandleLockTimeout( 1627 HANDLE hFile, 1628 DWORD offset, 1629 DWORD nByte, 1630 int bExcl, 1631 DWORD nMs 1632 ){ 1633 DWORD flags = LOCKFILE_FAIL_IMMEDIATELY | (bExcl?LOCKFILE_EXCLUSIVE_LOCK:0); 1634 int rc = SQLITE_OK; 1635 BOOL ret; 1636 OVERLAPPED ovlp; 1637 memset(&ovlp, 0, sizeof(OVERLAPPED)); 1638 ovlp.Offset = offset; 1639 1640 #if defined(SQLITE_ENABLE_SETLK_TIMEOUT) 1641 if( nMs!=0 ){ 1642 flags &= ~LOCKFILE_FAIL_IMMEDIATELY; 1643 } 1644 ovlp.hEvent = osCreateEvent(NULL, TRUE, FALSE, NULL); 1645 if( ovlp.hEvent==NULL ){ 1646 return SQLITE_IOERR_LOCK; 1647 } 1648 #endif 1649 ret = osLockFileEx(hFile, flags, 0, nByte, 0, &ovlp); 1650 #if defined(SQLITE_ENABLE_SETLK_TIMEOUT) 1651 /* If SQLITE_ENABLE_SETLK_TIMEOUT is defined, then the file-handle was 1652 ** opened with FILE_FLAG_OVERHEAD specified. In this case, the call to 1653 ** LockFileEx() may fail because the request is still pending. This can 1654 ** happen even if LOCKFILE_FAIL_IMMEDIATELY was specified. 1655 ** 1656 ** If nMs is 0, then LOCKFILE_FAIL_IMMEDIATELY was set in the flags 1657 ** passed to LockFileEx(). In this case, if the operation is pending, 1658 ** block indefinitely until it is finished. 1659 ** 1660 ** Otherwise, wait for up to nMs ms for the operation to finish. nMs 1661 ** may be set to INFINITE. 1662 */ 1663 if( !ret && GetLastError()==ERROR_IO_PENDING ){ 1664 DWORD nDelay = (nMs==0 ? INFINITE : nMs); 1665 DWORD res = osWaitForSingleObject(ovlp.hEvent, nDelay); 1666 if( res==WAIT_OBJECT_0 ){ 1667 ret = TRUE; 1668 }else if( res==WAIT_TIMEOUT ){ 1669 #if SQLITE_ENABLE_SETLK_TIMEOUT==1 1670 rc = SQLITE_BUSY_TIMEOUT; 1671 #else 1672 rc = SQLITE_BUSY; 1673 #endif 1674 }else{ 1675 /* Some other error has occurred */ 1676 rc = SQLITE_IOERR_LOCK; 1677 } 1678 1679 /* If it is still pending, cancel the LockFileEx() call. */ 1680 osCancelIo(hFile); 1681 } 1682 1683 osCloseHandle(ovlp.hEvent); 1684 #endif /* defined(SQLITE_ENABLE_SETLK_TIMEOUT) */ 1685 1686 if( rc==SQLITE_OK && !ret ){ 1687 rc = SQLITE_BUSY; 1688 } 1689 return rc; 1690 } 1691 #endif /* #ifndef SQLITE_OMIT_WAL */ 1692 1693 /* 1694 ** Unlock a file region. 1695 */ 1696 static BOOL winUnlockFile( 1697 LPHANDLE phFile, 1698 DWORD offsetLow, 1699 DWORD offsetHigh, 1700 DWORD numBytesLow, 1701 DWORD numBytesHigh 1702 ){ 1703 OVERLAPPED ovlp; 1704 memset(&ovlp, 0, sizeof(OVERLAPPED)); 1705 ovlp.Offset = offsetLow; 1706 ovlp.OffsetHigh = offsetHigh; 1707 return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp); 1708 } 1709 1710 #ifndef SQLITE_OMIT_WAL 1711 /* 1712 ** Remove an nByte lock starting at offset iOff from HANDLE h. 1713 */ 1714 static int winHandleUnlock(HANDLE h, int iOff, int nByte){ 1715 BOOL ret = winUnlockFile(&h, iOff, 0, nByte, 0); 1716 return (ret ? SQLITE_OK : SQLITE_IOERR_UNLOCK); 1717 } 1718 #endif 1719 1720 /***************************************************************************** 1721 ** The next group of routines implement the I/O methods specified 1722 ** by the sqlite3_io_methods object. 1723 ******************************************************************************/ 1724 1725 /* 1726 ** Some Microsoft compilers lack this definition. 1727 */ 1728 #ifndef INVALID_SET_FILE_POINTER 1729 # define INVALID_SET_FILE_POINTER ((DWORD)-1) 1730 #endif 1731 1732 /* 1733 ** Seek the file handle h to offset nByte of the file. 1734 ** 1735 ** If successful, return SQLITE_OK. Or, if an error occurs, return an SQLite 1736 ** error code. 1737 */ 1738 static int winHandleSeek(HANDLE h, sqlite3_int64 iOffset){ 1739 int rc = SQLITE_OK; /* Return value */ 1740 LARGE_INTEGER x; /* The offset */ 1741 1742 x.QuadPart = iOffset; 1743 if( osSetFilePointerEx(h, x, 0, FILE_BEGIN)==0 ){ 1744 rc = SQLITE_IOERR_SEEK; 1745 } 1746 OSTRACE(("SEEK file=%p, offset=%lld rc=%s\n", h, iOffset,sqlite3ErrName(rc))); 1747 return rc; 1748 } 1749 1750 /* 1751 ** Move the current position of the file handle passed as the first 1752 ** argument to offset iOffset within the file. If successful, return 0. 1753 ** Otherwise, set pFile->lastErrno and return non-zero. 1754 */ 1755 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){ 1756 int rc; 1757 1758 rc = winHandleSeek(pFile->h, iOffset); 1759 if( rc!=SQLITE_OK ){ 1760 pFile->lastErrno = osGetLastError(); 1761 winLogError(rc, pFile->lastErrno, "winSeekFile", pFile->zPath); 1762 } 1763 return rc; 1764 } 1765 1766 1767 #if SQLITE_MAX_MMAP_SIZE>0 1768 /* Forward references to VFS helper methods used for memory mapped files */ 1769 static int winMapfile(winFile*, sqlite3_int64); 1770 static int winUnmapfile(winFile*); 1771 #endif 1772 1773 /* 1774 ** Close a file. 1775 ** 1776 ** It is reported that an attempt to close a handle might sometimes 1777 ** fail. This is a very unreasonable result, but Windows is notorious 1778 ** for being unreasonable so I do not doubt that it might happen. If 1779 ** the close fails, we pause for 100 milliseconds and try again. As 1780 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before 1781 ** giving up and returning an error. 1782 */ 1783 #define MX_CLOSE_ATTEMPT 3 1784 static int winClose(sqlite3_file *id){ 1785 int rc, cnt = 0; 1786 winFile *pFile = (winFile*)id; 1787 1788 assert( id!=0 ); 1789 #ifndef SQLITE_OMIT_WAL 1790 assert( pFile->pShm==0 ); 1791 #endif 1792 assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE ); 1793 OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n", 1794 osGetCurrentProcessId(), pFile, pFile->h)); 1795 1796 #if SQLITE_MAX_MMAP_SIZE>0 1797 winUnmapfile(pFile); 1798 #endif 1799 1800 do{ 1801 rc = osCloseHandle(pFile->h); 1802 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */ 1803 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (osSleep(100), 1) ); 1804 if( rc ){ 1805 pFile->h = NULL; 1806 } 1807 OpenCounter(-1); 1808 OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n", 1809 osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed")); 1810 return rc ? SQLITE_OK 1811 : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(), 1812 "winClose", pFile->zPath); 1813 } 1814 1815 /* 1816 ** Read data from a file into a buffer. Return SQLITE_OK if all 1817 ** bytes were read successfully and SQLITE_IOERR if anything goes 1818 ** wrong. 1819 */ 1820 static int winRead( 1821 sqlite3_file *id, /* File to read from */ 1822 void *pBuf, /* Write content into this buffer */ 1823 int amt, /* Number of bytes to read */ 1824 sqlite3_int64 offset /* Begin reading at this offset */ 1825 ){ 1826 #if !defined(SQLITE_WIN32_NO_OVERLAPPED) 1827 OVERLAPPED overlapped; /* The offset for ReadFile. */ 1828 #endif 1829 winFile *pFile = (winFile*)id; /* file handle */ 1830 DWORD nRead; /* Number of bytes actually read from file */ 1831 int nRetry = 0; /* Number of retrys */ 1832 1833 assert( id!=0 ); 1834 assert( amt>0 ); 1835 assert( offset>=0 ); 1836 SimulateIOError(return SQLITE_IOERR_READ); 1837 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, " 1838 "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile, 1839 pFile->h, pBuf, amt, offset, pFile->locktype)); 1840 1841 #if SQLITE_MAX_MMAP_SIZE>0 1842 /* Deal with as much of this read request as possible by transferring 1843 ** data from the memory mapping using memcpy(). */ 1844 if( offsetmmapSize ){ 1845 if( offset+amt <= pFile->mmapSize ){ 1846 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); 1847 OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", 1848 osGetCurrentProcessId(), pFile, pFile->h)); 1849 return SQLITE_OK; 1850 }else{ 1851 int nCopy = (int)(pFile->mmapSize - offset); 1852 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); 1853 pBuf = &((u8 *)pBuf)[nCopy]; 1854 amt -= nCopy; 1855 offset += nCopy; 1856 } 1857 } 1858 #endif 1859 1860 #if defined(SQLITE_WIN32_NO_OVERLAPPED) 1861 if( winSeekFile(pFile, offset) ){ 1862 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n", 1863 osGetCurrentProcessId(), pFile, pFile->h)); 1864 return SQLITE_FULL; 1865 } 1866 while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){ 1867 #else 1868 memset(&overlapped, 0, sizeof(OVERLAPPED)); 1869 overlapped.Offset = (LONG)(offset & 0xffffffff); 1870 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); 1871 while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) && 1872 osGetLastError()!=ERROR_HANDLE_EOF ){ 1873 #endif 1874 DWORD lastErrno; 1875 if( winRetryIoerr(&nRetry, &lastErrno) ) continue; 1876 pFile->lastErrno = lastErrno; 1877 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n", 1878 osGetCurrentProcessId(), pFile, pFile->h)); 1879 return winLogError(SQLITE_IOERR_READ, pFile->lastErrno, 1880 "winRead", pFile->zPath); 1881 } 1882 winLogIoerr(nRetry, __LINE__); 1883 if( nRead<(DWORD)amt ){ 1884 /* Unread parts of the buffer must be zero-filled */ 1885 memset(&((char*)pBuf)[nRead], 0, amt-nRead); 1886 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n", 1887 osGetCurrentProcessId(), pFile, pFile->h)); 1888 return SQLITE_IOERR_SHORT_READ; 1889 } 1890 1891 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", 1892 osGetCurrentProcessId(), pFile, pFile->h)); 1893 return SQLITE_OK; 1894 } 1895 1896 /* 1897 ** Write data from a buffer into a file. Return SQLITE_OK on success 1898 ** or some other error code on failure. 1899 */ 1900 static int winWrite( 1901 sqlite3_file *id, /* File to write into */ 1902 const void *pBuf, /* The bytes to be written */ 1903 int amt, /* Number of bytes to write */ 1904 sqlite3_int64 offset /* Offset into the file to begin writing at */ 1905 ){ 1906 int rc = 0; /* True if error has occurred, else false */ 1907 winFile *pFile = (winFile*)id; /* File handle */ 1908 int nRetry = 0; /* Number of retries */ 1909 1910 assert( amt>0 ); 1911 assert( pFile ); 1912 SimulateIOError(return SQLITE_IOERR_WRITE); 1913 SimulateDiskfullError(return SQLITE_FULL); 1914 1915 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, " 1916 "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile, 1917 pFile->h, pBuf, amt, offset, pFile->locktype)); 1918 1919 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0 1920 /* Deal with as much of this write request as possible by transferring 1921 ** data from the memory mapping using memcpy(). */ 1922 if( offsetmmapSize ){ 1923 if( offset+amt <= pFile->mmapSize ){ 1924 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); 1925 OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", 1926 osGetCurrentProcessId(), pFile, pFile->h)); 1927 return SQLITE_OK; 1928 }else{ 1929 int nCopy = (int)(pFile->mmapSize - offset); 1930 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); 1931 pBuf = &((u8 *)pBuf)[nCopy]; 1932 amt -= nCopy; 1933 offset += nCopy; 1934 } 1935 } 1936 #endif 1937 1938 #if defined(SQLITE_WIN32_NO_OVERLAPPED) 1939 rc = winSeekFile(pFile, offset); 1940 if( rc==0 ){ 1941 #else 1942 { 1943 #endif 1944 #if !defined(SQLITE_WIN32_NO_OVERLAPPED) 1945 OVERLAPPED overlapped; /* The offset for WriteFile. */ 1946 #endif 1947 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */ 1948 int nRem = amt; /* Number of bytes yet to be written */ 1949 DWORD nWrite; /* Bytes written by each WriteFile() call */ 1950 DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */ 1951 1952 #if !defined(SQLITE_WIN32_NO_OVERLAPPED) 1953 memset(&overlapped, 0, sizeof(OVERLAPPED)); 1954 overlapped.Offset = (LONG)(offset & 0xffffffff); 1955 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); 1956 #endif 1957 1958 while( nRem>0 ){ 1959 #if defined(SQLITE_WIN32_NO_OVERLAPPED) 1960 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){ 1961 #else 1962 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){ 1963 #endif 1964 if( winRetryIoerr(&nRetry, &lastErrno) ) continue; 1965 break; 1966 } 1967 assert( nWrite==0 || nWrite<=(DWORD)nRem ); 1968 if( nWrite==0 || nWrite>(DWORD)nRem ){ 1969 lastErrno = osGetLastError(); 1970 break; 1971 } 1972 #if !defined(SQLITE_WIN32_NO_OVERLAPPED) 1973 offset += nWrite; 1974 overlapped.Offset = (LONG)(offset & 0xffffffff); 1975 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); 1976 #endif 1977 aRem += nWrite; 1978 nRem -= nWrite; 1979 } 1980 if( nRem>0 ){ 1981 pFile->lastErrno = lastErrno; 1982 rc = 1; 1983 } 1984 } 1985 1986 if( rc ){ 1987 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ) 1988 || ( pFile->lastErrno==ERROR_DISK_FULL )){ 1989 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n", 1990 osGetCurrentProcessId(), pFile, pFile->h)); 1991 return winLogError(SQLITE_FULL, pFile->lastErrno, 1992 "winWrite1", pFile->zPath); 1993 } 1994 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n", 1995 osGetCurrentProcessId(), pFile, pFile->h)); 1996 return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno, 1997 "winWrite2", pFile->zPath); 1998 }else{ 1999 winLogIoerr(nRetry, __LINE__); 2000 } 2001 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", 2002 osGetCurrentProcessId(), pFile, pFile->h)); 2003 return SQLITE_OK; 2004 } 2005 2006 #ifndef SQLITE_OMIT_WAL 2007 /* 2008 ** Truncate the file opened by handle h to nByte bytes in size. 2009 */ 2010 static int winHandleTruncate(HANDLE h, sqlite3_int64 nByte){ 2011 int rc = SQLITE_OK; /* Return code */ 2012 rc = winHandleSeek(h, nByte); 2013 if( rc==SQLITE_OK ){ 2014 if( 0==osSetEndOfFile(h) ){ 2015 rc = SQLITE_IOERR_TRUNCATE; 2016 } 2017 } 2018 return rc; 2019 } 2020 2021 /* 2022 ** Determine the size in bytes of the file opened by the handle passed as 2023 ** the first argument. 2024 */ 2025 static int winHandleSize(HANDLE h, sqlite3_int64 *pnByte){ 2026 int rc = SQLITE_OK; 2027 LARGE_INTEGER x; 2028 assert( pnByte ); 2029 if( osGetFileSizeEx(h, &x)==0 ){ 2030 rc = SQLITE_IOERR_FSTAT; 2031 *pnByte = 0; 2032 }else{ 2033 *pnByte = x.QuadPart; 2034 } 2035 return rc; 2036 } 2037 2038 /* 2039 ** Close the handle passed as the only argument. 2040 */ 2041 static void winHandleClose(HANDLE h){ 2042 if( h!=INVALID_HANDLE_VALUE ){ 2043 osCloseHandle(h); 2044 } 2045 } 2046 #endif /* #ifndef SQLITE_OMIT_WAL */ 2047 2048 /* 2049 ** Truncate an open file to a specified size 2050 */ 2051 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){ 2052 winFile *pFile = (winFile*)id; /* File handle object */ 2053 int rc = SQLITE_OK; /* Return code for this function */ 2054 DWORD lastErrno; 2055 #if SQLITE_MAX_MMAP_SIZE>0 2056 sqlite3_int64 oldMmapSize; 2057 if( pFile->nFetchOut>0 ){ 2058 /* File truncation is a no-op if there are outstanding memory mapped 2059 ** pages. This is because truncating the file means temporarily unmapping 2060 ** the file, and that might delete memory out from under existing cursors. 2061 ** 2062 ** This can result in incremental vacuum not truncating the file, 2063 ** if there is an active read cursor when the incremental vacuum occurs. 2064 ** No real harm comes of this - the database file is not corrupted, 2065 ** though some folks might complain that the file is bigger than it 2066 ** needs to be. 2067 ** 2068 ** The only feasible work-around is to defer the truncation until after 2069 ** all references to memory-mapped content are closed. That is doable, 2070 ** but involves adding a few branches in the common write code path which 2071 ** could slow down normal operations slightly. Hence, we have decided for 2072 ** now to simply make transactions a no-op if there are pending reads. We 2073 ** can maybe revisit this decision in the future. 2074 */ 2075 return SQLITE_OK; 2076 } 2077 #endif 2078 2079 assert( pFile ); 2080 SimulateIOError(return SQLITE_IOERR_TRUNCATE); 2081 OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n", 2082 osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype)); 2083 2084 /* If the user has configured a chunk-size for this file, truncate the 2085 ** file so that it consists of an integer number of chunks (i.e. the 2086 ** actual file size after the operation may be larger than the requested 2087 ** size). 2088 */ 2089 if( pFile->szChunk>0 ){ 2090 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; 2091 } 2092 2093 #if SQLITE_MAX_MMAP_SIZE>0 2094 if( pFile->pMapRegion ){ 2095 oldMmapSize = pFile->mmapSize; 2096 }else{ 2097 oldMmapSize = 0; 2098 } 2099 winUnmapfile(pFile); 2100 #endif 2101 2102 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */ 2103 if( winSeekFile(pFile, nByte) ){ 2104 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno, 2105 "winTruncate1", pFile->zPath); 2106 }else if( 0==osSetEndOfFile(pFile->h) && 2107 ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){ 2108 pFile->lastErrno = lastErrno; 2109 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno, 2110 "winTruncate2", pFile->zPath); 2111 } 2112 2113 #if SQLITE_MAX_MMAP_SIZE>0 2114 if( rc==SQLITE_OK && oldMmapSize>0 ){ 2115 if( oldMmapSize>nByte ){ 2116 winMapfile(pFile, -1); 2117 }else{ 2118 winMapfile(pFile, oldMmapSize); 2119 } 2120 } 2121 #endif 2122 2123 OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n", 2124 osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc))); 2125 return rc; 2126 } 2127 2128 #ifdef SQLITE_TEST 2129 /* 2130 ** Count the number of fullsyncs and normal syncs. This is used to test 2131 ** that syncs and fullsyncs are occurring at the right times. 2132 */ 2133 int sqlite3_sync_count = 0; 2134 int sqlite3_fullsync_count = 0; 2135 #endif 2136 2137 /* 2138 ** Make sure all writes to a particular file are committed to disk. 2139 */ 2140 static int winSync(sqlite3_file *id, int flags){ 2141 #ifndef SQLITE_NO_SYNC 2142 /* 2143 ** Used only when SQLITE_NO_SYNC is not defined. 2144 */ 2145 BOOL rc; 2146 #endif 2147 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \ 2148 defined(SQLITE_HAVE_OS_TRACE) 2149 /* 2150 ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or 2151 ** OSTRACE() macros. 2152 */ 2153 winFile *pFile = (winFile*)id; 2154 #else 2155 UNUSED_PARAMETER(id); 2156 #endif 2157 2158 assert( pFile ); 2159 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ 2160 assert((flags&0x0F)==SQLITE_SYNC_NORMAL 2161 || (flags&0x0F)==SQLITE_SYNC_FULL 2162 ); 2163 2164 /* Unix cannot, but some systems may return SQLITE_FULL from here. This 2165 ** line is to test that doing so does not cause any problems. 2166 */ 2167 SimulateDiskfullError( return SQLITE_FULL ); 2168 2169 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n", 2170 osGetCurrentProcessId(), pFile, pFile->h, flags, 2171 pFile->locktype)); 2172 2173 #ifndef SQLITE_TEST 2174 UNUSED_PARAMETER(flags); 2175 #else 2176 if( (flags&0x0F)==SQLITE_SYNC_FULL ){ 2177 sqlite3_fullsync_count++; 2178 } 2179 sqlite3_sync_count++; 2180 #endif 2181 2182 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a 2183 ** no-op 2184 */ 2185 #ifdef SQLITE_NO_SYNC 2186 OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", 2187 osGetCurrentProcessId(), pFile, pFile->h)); 2188 return SQLITE_OK; 2189 #else 2190 #if SQLITE_MAX_MMAP_SIZE>0 2191 if( pFile->pMapRegion ){ 2192 if( osFlushViewOfFile(pFile->pMapRegion, 0) ){ 2193 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, " 2194 "rc=SQLITE_OK\n", osGetCurrentProcessId(), 2195 pFile, pFile->pMapRegion)); 2196 }else{ 2197 pFile->lastErrno = osGetLastError(); 2198 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, " 2199 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), 2200 pFile, pFile->pMapRegion)); 2201 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno, 2202 "winSync1", pFile->zPath); 2203 } 2204 } 2205 #endif 2206 rc = osFlushFileBuffers(pFile->h); 2207 SimulateIOError( rc=FALSE ); 2208 if( rc ){ 2209 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", 2210 osGetCurrentProcessId(), pFile, pFile->h)); 2211 return SQLITE_OK; 2212 }else{ 2213 pFile->lastErrno = osGetLastError(); 2214 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n", 2215 osGetCurrentProcessId(), pFile, pFile->h)); 2216 return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno, 2217 "winSync2", pFile->zPath); 2218 } 2219 #endif 2220 } 2221 2222 /* 2223 ** Determine the current size of a file in bytes 2224 */ 2225 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){ 2226 winFile *pFile = (winFile*)id; 2227 int rc = SQLITE_OK; 2228 2229 assert( id!=0 ); 2230 assert( pSize!=0 ); 2231 SimulateIOError(return SQLITE_IOERR_FSTAT); 2232 OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize)); 2233 { 2234 LARGE_INTEGER x; 2235 if( osGetFileSizeEx(pFile->h, &x)==0 ){ 2236 *pSize = 0; 2237 pFile->lastErrno = osGetLastError(); 2238 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno, 2239 "winFileSize", pFile->zPath); 2240 }else{ 2241 *pSize = x.QuadPart; 2242 } 2243 } 2244 OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n", 2245 pFile->h, pSize, *pSize, sqlite3ErrName(rc))); 2246 return rc; 2247 } 2248 2249 /* 2250 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems. 2251 */ 2252 #ifndef LOCKFILE_FAIL_IMMEDIATELY 2253 # define LOCKFILE_FAIL_IMMEDIATELY 1 2254 #endif 2255 2256 #ifndef LOCKFILE_EXCLUSIVE_LOCK 2257 # define LOCKFILE_EXCLUSIVE_LOCK 2 2258 #endif 2259 2260 /* 2261 ** Historically, SQLite has used both the LockFile and LockFileEx functions. 2262 ** When the LockFile function was used, it was always expected to fail 2263 ** immediately if the lock could not be obtained. Also, it always expected to 2264 ** obtain an exclusive lock. These flags are used with the LockFileEx function 2265 ** and reflect those expectations; therefore, they should not be changed. 2266 */ 2267 #ifndef SQLITE_LOCKFILE_FLAGS 2268 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \ 2269 LOCKFILE_EXCLUSIVE_LOCK) 2270 #endif 2271 2272 /* 2273 ** Currently, SQLite never calls the LockFileEx function without wanting the 2274 ** call to fail immediately if the lock cannot be obtained. 2275 */ 2276 #ifndef SQLITE_LOCKFILEEX_FLAGS 2277 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY) 2278 #endif 2279 2280 /* 2281 ** Acquire a reader lock. 2282 ** Different API routines are called depending on whether or not this 2283 ** is Win9x or WinNT. 2284 */ 2285 static int winGetReadLock(winFile *pFile, int bBlock){ 2286 int res; 2287 DWORD mask = ~(bBlock ? LOCKFILE_FAIL_IMMEDIATELY : 0); 2288 OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); 2289 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS&mask, SHARED_FIRST, 0, 2290 SHARED_SIZE, 0); 2291 if( res == 0 ){ 2292 pFile->lastErrno = osGetLastError(); 2293 /* No need to log a failure to lock */ 2294 } 2295 OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res)); 2296 return res; 2297 } 2298 2299 /* 2300 ** Undo a readlock 2301 */ 2302 static int winUnlockReadLock(winFile *pFile){ 2303 int res; 2304 DWORD lastErrno; 2305 OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); 2306 res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); 2307 if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){ 2308 pFile->lastErrno = lastErrno; 2309 winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno, 2310 "winUnlockReadLock", pFile->zPath); 2311 } 2312 OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res)); 2313 return res; 2314 } 2315 2316 /* 2317 ** Lock the file with the lock specified by parameter locktype - one 2318 ** of the following: 2319 ** 2320 ** (1) SHARED_LOCK 2321 ** (2) RESERVED_LOCK 2322 ** (3) PENDING_LOCK 2323 ** (4) EXCLUSIVE_LOCK 2324 ** 2325 ** Sometimes when requesting one lock state, additional lock states 2326 ** are inserted in between. The locking might fail on one of the later 2327 ** transitions leaving the lock state different from what it started but 2328 ** still short of its goal. The following chart shows the allowed 2329 ** transitions and the inserted intermediate states: 2330 ** 2331 ** UNLOCKED -> SHARED 2332 ** SHARED -> RESERVED 2333 ** SHARED -> (PENDING) -> EXCLUSIVE 2334 ** RESERVED -> (PENDING) -> EXCLUSIVE 2335 ** PENDING -> EXCLUSIVE 2336 ** 2337 ** This routine will only increase a lock. The winUnlock() routine 2338 ** erases all locks at once and returns us immediately to locking level 0. 2339 ** It is not possible to lower the locking level one step at a time. You 2340 ** must go straight to locking level 0. 2341 */ 2342 static int winLock(sqlite3_file *id, int locktype){ 2343 int rc = SQLITE_OK; /* Return code from subroutines */ 2344 int res = 1; /* Result of a Windows lock call */ 2345 int newLocktype; /* Set pFile->locktype to this value before exiting */ 2346 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */ 2347 winFile *pFile = (winFile*)id; 2348 DWORD lastErrno = NO_ERROR; 2349 2350 assert( id!=0 ); 2351 OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n", 2352 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype)); 2353 2354 /* If there is already a lock of this type or more restrictive on the 2355 ** OsFile, do nothing. Don't use the end_lock: exit path, as 2356 ** sqlite3OsEnterMutex() hasn't been called yet. 2357 */ 2358 if( pFile->locktype>=locktype ){ 2359 OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h)); 2360 return SQLITE_OK; 2361 } 2362 2363 /* Do not allow any kind of write-lock on a read-only database 2364 */ 2365 if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){ 2366 return SQLITE_IOERR_LOCK; 2367 } 2368 2369 /* Make sure the locking sequence is correct 2370 */ 2371 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK ); 2372 assert( locktype!=PENDING_LOCK ); 2373 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK ); 2374 2375 /* Lock the PENDING_LOCK byte if we need to acquire an EXCLUSIVE lock or 2376 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of 2377 ** the PENDING_LOCK byte is temporary. 2378 */ 2379 newLocktype = pFile->locktype; 2380 if( locktype==SHARED_LOCK 2381 || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK) 2382 ){ 2383 int cnt = 3; 2384 2385 /* Flags for the LockFileEx() call. This should be an exclusive lock if 2386 ** this call is to obtain EXCLUSIVE, or a shared lock if this call is to 2387 ** obtain SHARED. */ 2388 int flags = LOCKFILE_FAIL_IMMEDIATELY; 2389 if( locktype==EXCLUSIVE_LOCK ){ 2390 flags |= LOCKFILE_EXCLUSIVE_LOCK; 2391 } 2392 while( cnt>0 ){ 2393 /* Try 3 times to get the pending lock. This is needed to work 2394 ** around problems caused by indexing and/or anti-virus software on 2395 ** Windows systems. 2396 ** 2397 ** If you are using this code as a model for alternative VFSes, do not 2398 ** copy this retry logic. It is a hack intended for Windows only. */ 2399 res = winLockFile(&pFile->h, flags, PENDING_BYTE, 0, 1, 0); 2400 if( res ) break; 2401 2402 lastErrno = osGetLastError(); 2403 OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n", 2404 pFile->h, cnt, res 2405 )); 2406 2407 if( lastErrno==ERROR_INVALID_HANDLE ){ 2408 pFile->lastErrno = lastErrno; 2409 rc = SQLITE_IOERR_LOCK; 2410 OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n", 2411 pFile->h, cnt, sqlite3ErrName(rc) 2412 )); 2413 return rc; 2414 } 2415 2416 cnt--; 2417 if( cnt>0 ) osSleep(1); 2418 } 2419 gotPendingLock = res; 2420 } 2421 2422 /* Acquire a shared lock 2423 */ 2424 if( locktype==SHARED_LOCK && res ){ 2425 assert( pFile->locktype==NO_LOCK ); 2426 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 2427 res = winGetReadLock(pFile, pFile->bBlockOnConnect); 2428 #else 2429 res = winGetReadLock(pFile, 0); 2430 #endif 2431 if( res ){ 2432 newLocktype = SHARED_LOCK; 2433 }else{ 2434 lastErrno = osGetLastError(); 2435 } 2436 } 2437 2438 /* Acquire a RESERVED lock 2439 */ 2440 if( locktype==RESERVED_LOCK && res ){ 2441 assert( pFile->locktype==SHARED_LOCK ); 2442 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0); 2443 if( res ){ 2444 newLocktype = RESERVED_LOCK; 2445 }else{ 2446 lastErrno = osGetLastError(); 2447 } 2448 } 2449 2450 /* Acquire a PENDING lock 2451 */ 2452 if( locktype==EXCLUSIVE_LOCK && res ){ 2453 newLocktype = PENDING_LOCK; 2454 gotPendingLock = 0; 2455 } 2456 2457 /* Acquire an EXCLUSIVE lock 2458 */ 2459 if( locktype==EXCLUSIVE_LOCK && res ){ 2460 assert( pFile->locktype>=SHARED_LOCK ); 2461 (void)winUnlockReadLock(pFile); 2462 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0, 2463 SHARED_SIZE, 0); 2464 if( res ){ 2465 newLocktype = EXCLUSIVE_LOCK; 2466 }else{ 2467 lastErrno = osGetLastError(); 2468 winGetReadLock(pFile, 0); 2469 } 2470 } 2471 2472 /* If we are holding a PENDING lock that ought to be released, then 2473 ** release it now. 2474 */ 2475 if( gotPendingLock && locktype==SHARED_LOCK ){ 2476 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0); 2477 } 2478 2479 /* Update the state of the lock has held in the file descriptor then 2480 ** return the appropriate result code. 2481 */ 2482 if( res ){ 2483 rc = SQLITE_OK; 2484 }else{ 2485 pFile->lastErrno = lastErrno; 2486 rc = SQLITE_BUSY; 2487 OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n", 2488 pFile->h, locktype, newLocktype)); 2489 } 2490 pFile->locktype = (u8)newLocktype; 2491 OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n", 2492 pFile->h, pFile->locktype, sqlite3ErrName(rc))); 2493 return rc; 2494 } 2495 2496 /* 2497 ** This routine checks if there is a RESERVED lock held on the specified 2498 ** file by this or any other process. If such a lock is held, return 2499 ** non-zero, otherwise zero. 2500 */ 2501 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){ 2502 int res; 2503 winFile *pFile = (winFile*)id; 2504 2505 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 2506 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut)); 2507 2508 assert( id!=0 ); 2509 if( pFile->locktype>=RESERVED_LOCK ){ 2510 res = 1; 2511 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res)); 2512 }else{ 2513 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0); 2514 if( res ){ 2515 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0); 2516 } 2517 res = !res; 2518 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res)); 2519 } 2520 *pResOut = res; 2521 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", 2522 pFile->h, pResOut, *pResOut)); 2523 return SQLITE_OK; 2524 } 2525 2526 /* 2527 ** Lower the locking level on file descriptor id to locktype. locktype 2528 ** must be either NO_LOCK or SHARED_LOCK. 2529 ** 2530 ** If the locking level of the file descriptor is already at or below 2531 ** the requested locking level, this routine is a no-op. 2532 ** 2533 ** It is not possible for this routine to fail if the second argument 2534 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine 2535 ** might return SQLITE_IOERR; 2536 */ 2537 static int winUnlock(sqlite3_file *id, int locktype){ 2538 int type; 2539 winFile *pFile = (winFile*)id; 2540 int rc = SQLITE_OK; 2541 assert( pFile!=0 ); 2542 assert( locktype<=SHARED_LOCK ); 2543 OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n", 2544 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype)); 2545 type = pFile->locktype; 2546 if( type>=EXCLUSIVE_LOCK ){ 2547 winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); 2548 if( locktype==SHARED_LOCK && !winGetReadLock(pFile, 0) ){ 2549 /* This should never happen. We should always be able to 2550 ** reacquire the read lock */ 2551 rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(), 2552 "winUnlock", pFile->zPath); 2553 } 2554 } 2555 if( type>=RESERVED_LOCK ){ 2556 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0); 2557 } 2558 if( locktype==NO_LOCK && type>=SHARED_LOCK ){ 2559 winUnlockReadLock(pFile); 2560 } 2561 if( type>=PENDING_LOCK ){ 2562 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0); 2563 } 2564 pFile->locktype = (u8)locktype; 2565 OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n", 2566 pFile->h, pFile->locktype, sqlite3ErrName(rc))); 2567 return rc; 2568 } 2569 2570 /****************************************************************************** 2571 ****************************** No-op Locking ********************************** 2572 ** 2573 ** Of the various locking implementations available, this is by far the 2574 ** simplest: locking is ignored. No attempt is made to lock the database 2575 ** file for reading or writing. 2576 ** 2577 ** This locking mode is appropriate for use on read-only databases 2578 ** (ex: databases that are burned into CD-ROM, for example.) It can 2579 ** also be used if the application employs some external mechanism to 2580 ** prevent simultaneous access of the same database by two or more 2581 ** database connections. But there is a serious risk of database 2582 ** corruption if this locking mode is used in situations where multiple 2583 ** database connections are accessing the same database file at the same 2584 ** time and one or more of those connections are writing. 2585 */ 2586 2587 static int winNolockLock(sqlite3_file *id, int locktype){ 2588 UNUSED_PARAMETER(id); 2589 UNUSED_PARAMETER(locktype); 2590 return SQLITE_OK; 2591 } 2592 2593 static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){ 2594 UNUSED_PARAMETER(id); 2595 UNUSED_PARAMETER(pResOut); 2596 return SQLITE_OK; 2597 } 2598 2599 static int winNolockUnlock(sqlite3_file *id, int locktype){ 2600 UNUSED_PARAMETER(id); 2601 UNUSED_PARAMETER(locktype); 2602 return SQLITE_OK; 2603 } 2604 2605 /******************* End of the no-op lock implementation ********************* 2606 ******************************************************************************/ 2607 2608 /* 2609 ** If *pArg is initially negative then this is a query. Set *pArg to 2610 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set. 2611 ** 2612 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. 2613 */ 2614 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){ 2615 if( *pArg<0 ){ 2616 *pArg = (pFile->ctrlFlags & mask)!=0; 2617 }else if( (*pArg)==0 ){ 2618 pFile->ctrlFlags &= ~mask; 2619 }else{ 2620 pFile->ctrlFlags |= mask; 2621 } 2622 } 2623 2624 /* Forward references to VFS helper methods used for temporary files */ 2625 static int winGetTempname(sqlite3_vfs *, char **); 2626 static int winIsDir(LPCWSTR); 2627 static BOOL winIsLongPathPrefix(const char *); 2628 static BOOL winIsDriveLetterAndColon(const char *); 2629 2630 /* 2631 ** Control and query of the open file handle. 2632 */ 2633 static int winFileControl(sqlite3_file *id, int op, void *pArg){ 2634 winFile *pFile = (winFile*)id; 2635 OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg)); 2636 switch( op ){ 2637 case SQLITE_FCNTL_LOCKSTATE: { 2638 *(int*)pArg = pFile->locktype; 2639 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); 2640 return SQLITE_OK; 2641 } 2642 case SQLITE_FCNTL_LAST_ERRNO: { 2643 *(int*)pArg = (int)pFile->lastErrno; 2644 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); 2645 return SQLITE_OK; 2646 } 2647 case SQLITE_FCNTL_CHUNK_SIZE: { 2648 pFile->szChunk = *(int *)pArg; 2649 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); 2650 return SQLITE_OK; 2651 } 2652 case SQLITE_FCNTL_SIZE_HINT: { 2653 if( pFile->szChunk>0 ){ 2654 sqlite3_int64 oldSz; 2655 int rc = winFileSize(id, &oldSz); 2656 if( rc==SQLITE_OK ){ 2657 sqlite3_int64 newSz = *(sqlite3_int64*)pArg; 2658 if( newSz>oldSz ){ 2659 SimulateIOErrorBenign(1); 2660 rc = winTruncate(id, newSz); 2661 SimulateIOErrorBenign(0); 2662 } 2663 } 2664 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); 2665 return rc; 2666 } 2667 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); 2668 return SQLITE_OK; 2669 } 2670 case SQLITE_FCNTL_PERSIST_WAL: { 2671 winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg); 2672 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); 2673 return SQLITE_OK; 2674 } 2675 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { 2676 winModeBit(pFile, WINFILE_PSOW, (int*)pArg); 2677 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); 2678 return SQLITE_OK; 2679 } 2680 case SQLITE_FCNTL_VFSNAME: { 2681 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); 2682 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); 2683 return SQLITE_OK; 2684 } 2685 case SQLITE_FCNTL_WIN32_AV_RETRY: { 2686 int *a = (int*)pArg; 2687 if( a[0]>0 ){ 2688 winIoerrRetry = a[0]; 2689 }else{ 2690 a[0] = winIoerrRetry; 2691 } 2692 if( a[1]>0 ){ 2693 winIoerrRetryDelay = a[1]; 2694 }else{ 2695 a[1] = winIoerrRetryDelay; 2696 } 2697 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); 2698 return SQLITE_OK; 2699 } 2700 case SQLITE_FCNTL_WIN32_GET_HANDLE: { 2701 LPHANDLE phFile = (LPHANDLE)pArg; 2702 *phFile = pFile->h; 2703 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); 2704 return SQLITE_OK; 2705 } 2706 #ifdef SQLITE_TEST 2707 case SQLITE_FCNTL_WIN32_SET_HANDLE: { 2708 LPHANDLE phFile = (LPHANDLE)pArg; 2709 HANDLE hOldFile = pFile->h; 2710 pFile->h = *phFile; 2711 *phFile = hOldFile; 2712 OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n", 2713 hOldFile, pFile->h)); 2714 return SQLITE_OK; 2715 } 2716 #endif 2717 case SQLITE_FCNTL_NULL_IO: { 2718 (void)osCloseHandle(pFile->h); 2719 pFile->h = NULL; 2720 return SQLITE_OK; 2721 } 2722 case SQLITE_FCNTL_TEMPFILENAME: { 2723 char *zTFile = 0; 2724 int rc = winGetTempname(pFile->pVfs, &zTFile); 2725 if( rc==SQLITE_OK ){ 2726 *(char**)pArg = zTFile; 2727 } 2728 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); 2729 return rc; 2730 } 2731 #if SQLITE_MAX_MMAP_SIZE>0 2732 case SQLITE_FCNTL_MMAP_SIZE: { 2733 i64 newLimit = *(i64*)pArg; 2734 int rc = SQLITE_OK; 2735 if( newLimit>sqlite3GlobalConfig.mxMmap ){ 2736 newLimit = sqlite3GlobalConfig.mxMmap; 2737 } 2738 2739 /* The value of newLimit may be eventually cast to (SIZE_T) and passed 2740 ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at 2741 ** least a 64-bit type. */ 2742 if( newLimit>0 && sizeof(SIZE_T)<8 ){ 2743 newLimit = (newLimit & 0x7FFFFFFF); 2744 } 2745 2746 *(i64*)pArg = pFile->mmapSizeMax; 2747 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ 2748 pFile->mmapSizeMax = newLimit; 2749 if( pFile->mmapSize>0 ){ 2750 winUnmapfile(pFile); 2751 rc = winMapfile(pFile, -1); 2752 } 2753 } 2754 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); 2755 return rc; 2756 } 2757 #endif 2758 2759 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 2760 case SQLITE_FCNTL_LOCK_TIMEOUT: { 2761 int iOld = pFile->iBusyTimeout; 2762 int iNew = *(int*)pArg; 2763 #if SQLITE_ENABLE_SETLK_TIMEOUT==1 2764 pFile->iBusyTimeout = (iNew < 0) ? INFINITE : (DWORD)iNew; 2765 #elif SQLITE_ENABLE_SETLK_TIMEOUT==2 2766 pFile->iBusyTimeout = (DWORD)(!!iNew); 2767 #else 2768 # error "SQLITE_ENABLE_SETLK_TIMEOUT must be set to 1 or 2" 2769 #endif 2770 *(int*)pArg = iOld; 2771 return SQLITE_OK; 2772 } 2773 case SQLITE_FCNTL_BLOCK_ON_CONNECT: { 2774 int iNew = *(int*)pArg; 2775 pFile->bBlockOnConnect = iNew; 2776 return SQLITE_OK; 2777 } 2778 #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */ 2779 2780 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) 2781 case SQLITE_FCNTL_FILESTAT: { 2782 sqlite3_str *pStr = (sqlite3_str*)pArg; 2783 sqlite3_str_appendf(pStr, "{\"h\":%llu", (sqlite3_uint64)pFile->h); 2784 sqlite3_str_appendf(pStr, ",\"vfs\":\"%s\"", pFile->pVfs->zName); 2785 if( pFile->locktype ){ 2786 static const char *azLock[] = { "SHARED", "RESERVED", 2787 "PENDING", "EXCLUSIVE" }; 2788 sqlite3_str_appendf(pStr, ",\"locktype\":\"%s\"", 2789 azLock[pFile->locktype-1]); 2790 } 2791 #if SQLITE_MAX_MMAP_SIZE>0 2792 if( pFile->mmapSize ){ 2793 sqlite3_str_appendf(pStr, ",\"mmapSize\":%lld", pFile->mmapSize); 2794 sqlite3_str_appendf(pStr, ",\"nFetchOut\":%d", pFile->nFetchOut); 2795 } 2796 #endif 2797 sqlite3_str_append(pStr, "}", 1); 2798 return SQLITE_OK; 2799 } 2800 #endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */ 2801 2802 } 2803 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h)); 2804 return SQLITE_NOTFOUND; 2805 } 2806 2807 /* 2808 ** Return the sector size in bytes of the underlying block device for 2809 ** the specified file. This is almost always 512 bytes, but may be 2810 ** larger for some devices. 2811 ** 2812 ** SQLite code assumes this function cannot fail. It also assumes that 2813 ** if two files are created in the same file-system directory (i.e. 2814 ** a database and its journal file) that the sector size will be the 2815 ** same for both. 2816 */ 2817 static int winSectorSize(sqlite3_file *id){ 2818 (void)id; 2819 return SQLITE_DEFAULT_SECTOR_SIZE; 2820 } 2821 2822 /* 2823 ** Return a vector of device characteristics. 2824 */ 2825 static int winDeviceCharacteristics(sqlite3_file *id){ 2826 winFile *p = (winFile*)id; 2827 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | SQLITE_IOCAP_SUBPAGE_READ | 2828 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0); 2829 } 2830 2831 /* 2832 ** Windows will only let you create file view mappings 2833 ** on allocation size granularity boundaries. 2834 ** During sqlite3_os_init() we do a GetSystemInfo() 2835 ** to get the granularity size. 2836 */ 2837 static SYSTEM_INFO winSysInfo; 2838 2839 /* 2840 ** Convert a UTF-8 filename into whatever form the underlying 2841 ** operating system wants filenames in. Space to hold the result 2842 ** is obtained from malloc and must be freed by the calling 2843 ** function 2844 ** 2845 ** On Cygwin, 3 possible input forms are accepted: 2846 ** - If the filename starts with ":/" or ":\", 2847 ** it is converted to UTF-16 as-is. 2848 ** - If the filename contains '/', it is assumed to be a 2849 ** Cygwin absolute path, it is converted to a win32 2850 ** absolute path in UTF-16. 2851 ** - Otherwise it must be a filename only, the win32 filename 2852 ** is returned in UTF-16. 2853 ** Note: If the function cygwin_conv_path() fails, only 2854 ** UTF-8 -> UTF-16 conversion will be done. This can only 2855 ** happen when the file path >32k, in which case winUtf8ToUnicode() 2856 ** will fail too. 2857 */ 2858 static LPWSTR winConvertFromUtf8Filename(const char *zFilename){ 2859 LPWSTR zConverted = 0; 2860 #ifdef __CYGWIN__ 2861 int nChar; 2862 2863 if( osCygwin_conv_path && !(winIsDriveLetterAndColon(zFilename) 2864 && winIsDirSep(zFilename[2])) ){ 2865 i64 nByte; 2866 int convertflag = CCP_POSIX_TO_WIN_W; 2867 if( !strchr(zFilename, '/') ) convertflag |= CCP_RELATIVE; 2868 nByte = (i64)osCygwin_conv_path(convertflag, 2869 zFilename, 0, 0); 2870 if( nByte>0 ){ 2871 zConverted = sqlite3MallocZero(12+(u64)nByte); 2872 if ( zConverted==0 ){ 2873 return zConverted; 2874 } 2875 /* Filenames should be prefixed, except when converted 2876 * full path already starts with "\\?\". */ 2877 if( osCygwin_conv_path(convertflag, zFilename, 2878 zConverted+4, nByte)==0 ){ 2879 if( (convertflag&CCP_RELATIVE) ){ 2880 memmove(zConverted, zConverted+4, nByte); 2881 }else if( memcmp(zConverted+4, L"\\\\", 4) ){ 2882 memcpy(zConverted, L"\\\\?\\", 8); 2883 }else if( zConverted[6]!='?' ){ 2884 memmove(zConverted+6, zConverted+4, nByte); 2885 memcpy(zConverted, L"\\\\?\\UNC", 14); 2886 }else{ 2887 memmove(zConverted, zConverted+4, nByte); 2888 } 2889 return zConverted; 2890 } 2891 sqlite3_free(zConverted); 2892 } 2893 } 2894 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0); 2895 if( nChar==0 ){ 2896 return 0; 2897 } 2898 zConverted = sqlite3MallocZero( ((u64)nChar+6)*sizeof(WCHAR) ); 2899 if( zConverted==0 ){ 2900 return 0; 2901 } 2902 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, 2903 zConverted, nChar); 2904 if( nChar==0 ){ 2905 sqlite3_free(zConverted); 2906 zConverted = 0; 2907 }else if( nChar>MAX_PATH 2908 && winIsDriveLetterAndColon(zFilename) 2909 && winIsDirSep(zFilename[2]) ){ 2910 memmove(zConverted+4, zConverted, nChar*sizeof(WCHAR)); 2911 zConverted[2] = '\\'; 2912 memcpy(zConverted, L"\\\\?\\", 8); 2913 }else if( nChar>MAX_PATH 2914 && winIsDirSep(zFilename[0]) && winIsDirSep(zFilename[1]) 2915 && zFilename[2] != '?' ){ 2916 memmove(zConverted+6, zConverted, nChar*sizeof(WCHAR)); 2917 memcpy(zConverted, L"\\\\?\\UNC", 14); 2918 } 2919 #else /* if !defined(__CYGWIN__) */ 2920 zConverted = winUtf8ToUnicode(zFilename); 2921 #endif /* __CYGWIN__ */ 2922 /* caller will handle out of memory */ 2923 return zConverted; 2924 } 2925 2926 #ifndef SQLITE_OMIT_WAL 2927 2928 /* 2929 ** Helper functions to obtain and relinquish the global mutex. The 2930 ** global mutex is used to protect the winLockInfo objects used by 2931 ** this file, all of which may be shared by multiple threads. 2932 ** 2933 ** Function winShmMutexHeld() is used to assert() that the global mutex 2934 ** is held when required. This function is only used as part of assert() 2935 ** statements. e.g. 2936 ** 2937 ** winShmEnterMutex() 2938 ** assert( winShmMutexHeld() ); 2939 ** winShmLeaveMutex() 2940 */ 2941 static sqlite3_mutex *winBigLock = 0; 2942 static void winShmEnterMutex(void){ 2943 sqlite3_mutex_enter(winBigLock); 2944 } 2945 static void winShmLeaveMutex(void){ 2946 sqlite3_mutex_leave(winBigLock); 2947 } 2948 #ifndef NDEBUG 2949 static int winShmMutexHeld(void) { 2950 return sqlite3_mutex_held(winBigLock); 2951 } 2952 #endif 2953 2954 /* 2955 ** Object used to represent a single file opened and mmapped to provide 2956 ** shared memory. When multiple threads all reference the same 2957 ** log-summary, each thread has its own winFile object, but they all 2958 ** point to a single instance of this object. In other words, each 2959 ** log-summary is opened only once per process. 2960 ** 2961 ** winShmMutexHeld() must be true when creating or destroying 2962 ** this object, or while editing the global linked list that starts 2963 ** at winShmNodeList. 2964 ** 2965 ** When reading or writing the linked list starting at winShmNode.pWinShmList, 2966 ** pShmNode->mutex must be held. 2967 ** 2968 ** The following fields are constant after the object is created: 2969 ** 2970 ** zFilename 2971 ** hSharedShm 2972 ** mutex 2973 ** bUseSharedLockHandle 2974 ** 2975 ** Either winShmNode.mutex must be held or winShmNode.pWinShmList==0 and 2976 ** winShmMutexHeld() is true when reading or writing any other field 2977 ** in this structure. 2978 ** 2979 ** File-handle hSharedShm is always used to (a) take the DMS lock, (b) 2980 ** truncate the *-shm file if the DMS-locking protocol demands it, and 2981 ** (c) map regions of the *-shm file into memory using MapViewOfFile() 2982 ** or similar. If bUseSharedLockHandle is true, then other locks are also 2983 ** taken on hSharedShm. Or, if bUseSharedLockHandle is false, then other 2984 ** locks are taken using each connection's winShm.hShm handles. 2985 */ 2986 struct winShmNode { 2987 sqlite3_mutex *mutex; /* Mutex to access this object */ 2988 char *zFilename; /* Name of the file */ 2989 HANDLE hSharedShm; /* File handle open on zFilename */ 2990 int bUseSharedLockHandle; /* True to use hSharedShm for everything */ 2991 2992 int isUnlocked; /* DMS lock has not yet been obtained */ 2993 int isReadonly; /* True if read-only */ 2994 int szRegion; /* Size of shared-memory regions */ 2995 int nRegion; /* Size of array apRegion */ 2996 2997 struct ShmRegion { 2998 HANDLE hMap; /* File handle from CreateFileMapping */ 2999 void *pMap; 3000 } *aRegion; 3001 DWORD lastErrno; /* The Windows errno from the last I/O error */ 3002 3003 winShm *pWinShmList; /* List of winShm objects with ptrs to this */ 3004 3005 winShmNode *pNext; /* Next in list of all winShmNode objects */ 3006 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) 3007 u8 nextShmId; /* Next available winShm.id value */ 3008 #endif 3009 }; 3010 3011 /* 3012 ** A global array of all winShmNode objects. 3013 ** 3014 ** The winShmMutexHeld() must be true while reading or writing this list. 3015 */ 3016 static winShmNode *winShmNodeList = 0; 3017 3018 /* 3019 ** Structure used internally by this VFS to record the state of an 3020 ** open shared memory connection. There is one such structure for each 3021 ** winFile open on a wal mode database. 3022 */ 3023 struct winShm { 3024 winShmNode *pShmNode; /* The underlying winShmNode object */ 3025 u16 sharedMask; /* Mask of shared locks held */ 3026 u16 exclMask; /* Mask of exclusive locks held */ 3027 HANDLE hShm; /* File-handle on *-shm file. For locking. */ 3028 int bReadonly; /* True if hShm is opened read-only */ 3029 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) 3030 u8 id; /* Id of this connection with its winShmNode */ 3031 #endif 3032 winShm *pWinShmNext; /* Next winShm object on same winShmNode */ 3033 }; 3034 3035 /* 3036 ** Constants used for locking 3037 */ 3038 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */ 3039 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */ 3040 3041 /* Forward references to VFS methods */ 3042 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*); 3043 static int winDelete(sqlite3_vfs *,const char*,int); 3044 3045 /* 3046 ** Purge the winShmNodeList list of all entries with winShmNode.pWinShmList==0. 3047 ** 3048 ** This is not a VFS shared-memory method; it is a utility function called 3049 ** by VFS shared-memory methods. 3050 */ 3051 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ 3052 winShmNode **pp; 3053 winShmNode *p; 3054 assert( winShmMutexHeld() ); 3055 OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n", 3056 osGetCurrentProcessId(), deleteFlag)); 3057 pp = &winShmNodeList; 3058 while( (p = *pp)!=0 ){ 3059 if( p->pWinShmList==0 ){ 3060 int i; 3061 if( p->mutex ){ sqlite3_mutex_free(p->mutex); } 3062 for(i=0; inRegion; i++){ 3063 BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap); 3064 OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n", 3065 osGetCurrentProcessId(), i, bRc ? "ok" : "failed")); 3066 UNUSED_VARIABLE_VALUE(bRc); 3067 bRc = osCloseHandle(p->aRegion[i].hMap); 3068 OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n", 3069 osGetCurrentProcessId(), i, bRc ? "ok" : "failed")); 3070 UNUSED_VARIABLE_VALUE(bRc); 3071 } 3072 winHandleClose(p->hSharedShm); 3073 if( deleteFlag ){ 3074 SimulateIOErrorBenign(1); 3075 sqlite3BeginBenignMalloc(); 3076 winDelete(pVfs, p->zFilename, 0); 3077 sqlite3EndBenignMalloc(); 3078 SimulateIOErrorBenign(0); 3079 } 3080 *pp = p->pNext; 3081 sqlite3_free(p->aRegion); 3082 sqlite3_free(p); 3083 }else{ 3084 pp = &p->pNext; 3085 } 3086 } 3087 } 3088 3089 /* 3090 ** Handle h is open on the *-shm file. This function zeroes the first 3091 ** 8 bytes of the file. If SQLITE_ENABLE_SETLK_TIMEOUT is defined, h may 3092 ** have been opened with FILE_FLAG_OVERLAPPED. 3093 */ 3094 static int winZeroSharedMemory(HANDLE h){ 3095 u8 aZero[8] = {0,0,0,0,0,0,0,0}; 3096 DWORD nWrite = 0; 3097 OVERLAPPED ovlp; 3098 memset(&ovlp, 0, sizeof(OVERLAPPED)); 3099 if( !osWriteFile(h, aZero, sizeof(aZero), &nWrite, &ovlp) ){ 3100 /* If the file was opened with FILE_FLAG_OVERLAPPED, the write may still 3101 ** be pending. Wait for it with GetOverlappedResult(). */ 3102 if( osGetLastError()!=ERROR_IO_PENDING 3103 || !GetOverlappedResult(h, &ovlp, &nWrite, TRUE) 3104 ){ 3105 nWrite = 0; 3106 } 3107 } 3108 return (nWrite==sizeof(aZero) ? SQLITE_OK : SQLITE_IOERR_WRITE); 3109 } 3110 3111 /* 3112 ** The DMS lock has not yet been taken on the shm file associated with 3113 ** pShmNode. Take the lock. Truncate the *-shm file if required. 3114 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. 3115 */ 3116 static int winLockSharedMemory(winShmNode *pShmNode, DWORD nMs){ 3117 HANDLE h = pShmNode->hSharedShm; 3118 int rc = SQLITE_OK; 3119 3120 assert( sqlite3_mutex_held(pShmNode->mutex) ); 3121 rc = winHandleLockTimeout(h, WIN_SHM_DMS, 1, 1, 0); 3122 if( rc==SQLITE_OK ){ 3123 /* We have an EXCLUSIVE lock on the DMS byte. This means that this 3124 ** is the first process to open the file. Truncate it to zero bytes 3125 ** in this case. */ 3126 if( pShmNode->isReadonly ){ 3127 rc = SQLITE_READONLY_CANTINIT; 3128 }else{ 3129 if( SQLITE_OK!=winHandleTruncate(h, 0) ){ 3130 /* Sometimes the truncate operation may fail because some other 3131 ** process is still holding an open mapping. So try to write 3132 ** zeroes into the start of the file instead. */ 3133 rc = winZeroSharedMemory(h); 3134 } 3135 } 3136 3137 /* Release the EXCLUSIVE lock acquired above. */ 3138 winUnlockFile(&h, WIN_SHM_DMS, 0, 1, 0); 3139 }else if( (rc & 0xFF)==SQLITE_BUSY ){ 3140 rc = SQLITE_OK; 3141 } 3142 3143 if( rc==SQLITE_OK ){ 3144 /* Take a SHARED lock on the DMS byte. */ 3145 rc = winHandleLockTimeout(h, WIN_SHM_DMS, 1, 0, nMs); 3146 if( rc==SQLITE_OK ){ 3147 pShmNode->isUnlocked = 0; 3148 } 3149 } 3150 3151 return rc; 3152 } 3153 3154 3155 /* 3156 ** This function is used to open a handle on a *-shm file. 3157 ** 3158 ** If SQLITE_ENABLE_SETLK_TIMEOUT is defined at build time, then the file 3159 ** is opened with FILE_FLAG_OVERLAPPED specified. If not, it is not. 3160 */ 3161 static int winHandleOpen( 3162 const char *zUtf8, /* File to open */ 3163 int *pbReadonly, /* IN/OUT: True for readonly handle */ 3164 HANDLE *ph /* OUT: New HANDLE for file */ 3165 ){ 3166 int rc = SQLITE_OK; 3167 LPWSTR zConverted = 0; 3168 int bReadonly = *pbReadonly; 3169 HANDLE h = INVALID_HANDLE_VALUE; 3170 3171 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT 3172 const DWORD flag_overlapped = FILE_FLAG_OVERLAPPED; 3173 #else 3174 const DWORD flag_overlapped = 0; 3175 #endif 3176 3177 /* Convert the filename to the system encoding. */ 3178 zConverted = winConvertFromUtf8Filename(zUtf8); 3179 if( zConverted==0 ){ 3180 OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8)); 3181 rc = SQLITE_IOERR_NOMEM_BKPT; 3182 goto winopenfile_out; 3183 } 3184 3185 /* Ensure the file we are trying to open is not actually a directory. */ 3186 if( winIsDir(zConverted) ){ 3187 OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8)); 3188 rc = SQLITE_CANTOPEN_ISDIR; 3189 goto winopenfile_out; 3190 } 3191 3192 /* TODO: platforms. 3193 ** TODO: retry-on-ioerr. 3194 */ 3195 h = osCreateFileW(zConverted, /* lpFileName */ 3196 (GENERIC_READ | (bReadonly ? 0 : GENERIC_WRITE)), /* dwDesiredAccess */ 3197 FILE_SHARE_READ | FILE_SHARE_WRITE, /* dwShareMode */ 3198 NULL, /* lpSecurityAttributes */ 3199 OPEN_ALWAYS, /* dwCreationDisposition */ 3200 FILE_ATTRIBUTE_NORMAL|flag_overlapped, 3201 NULL 3202 ); 3203 3204 if( h==INVALID_HANDLE_VALUE ){ 3205 if( bReadonly==0 ){ 3206 bReadonly = 1; 3207 rc = winHandleOpen(zUtf8, &bReadonly, &h); 3208 }else{ 3209 rc = SQLITE_CANTOPEN_BKPT; 3210 } 3211 } 3212 3213 winopenfile_out: 3214 sqlite3_free(zConverted); 3215 *pbReadonly = bReadonly; 3216 *ph = h; 3217 return rc; 3218 } 3219 3220 /* 3221 ** Close pDbFd's connection to shared-memory. Delete the underlying 3222 ** *-shm file if deleteFlag is true. 3223 */ 3224 static int winCloseSharedMemory(winFile *pDbFd, int deleteFlag){ 3225 winShm *p; /* The connection to be closed */ 3226 winShm **pp; /* Iterator for pShmNode->pWinShmList */ 3227 winShmNode *pShmNode; /* The underlying shared-memory file */ 3228 3229 p = pDbFd->pShm; 3230 if( p==0 ) return SQLITE_OK; 3231 if( p->hShm!=INVALID_HANDLE_VALUE ){ 3232 osCloseHandle(p->hShm); 3233 } 3234 3235 winShmEnterMutex(); 3236 pShmNode = p->pShmNode; 3237 3238 /* Remove this connection from the winShmNode.pWinShmList list */ 3239 sqlite3_mutex_enter(pShmNode->mutex); 3240 for(pp=&pShmNode->pWinShmList; *pp!=p; pp=&(*pp)->pWinShmNext){} 3241 *pp = p->pWinShmNext; 3242 sqlite3_mutex_leave(pShmNode->mutex); 3243 3244 winShmPurge(pDbFd->pVfs, deleteFlag); 3245 winShmLeaveMutex(); 3246 3247 /* Free the connection p */ 3248 sqlite3_free(p); 3249 pDbFd->pShm = 0; 3250 return SQLITE_OK; 3251 } 3252 3253 /* 3254 ** testfixture builds may set this global variable to true via a 3255 ** Tcl interface. This forces the VFS to use the locking normally 3256 ** only used for UNC paths for all files. 3257 */ 3258 #ifdef SQLITE_TEST 3259 int sqlite3_win_test_unc_locking = 0; 3260 #else 3261 # define sqlite3_win_test_unc_locking 0 3262 #endif 3263 3264 /* 3265 ** Return true if the string passed as the only argument is likely 3266 ** to be a UNC path. Return false if not. 3267 ** 3268 ** Return true if: 3269 ** 3270 ** (1) The name begins with "\\" 3271 ** (2) But does not begin with "\\?\C:\" where C can be any alphabetic 3272 ** character. 3273 ** 3274 ** For testing, also return true in all cases if the global variable 3275 ** sqlite3_win_test_unc_locking is true. 3276 */ 3277 static int winIsUNCPath(const char *zFile){ 3278 if( zFile[0]=='\\' && zFile[1]=='\\' ){ 3279 if( zFile[2]=='?' 3280 && zFile[3]=='\\' 3281 && sqlite3Isalpha(zFile[4]) 3282 && zFile[5]==':' 3283 && winIsDirSep(zFile[6]) 3284 ){ 3285 return sqlite3_win_test_unc_locking; 3286 }else{ 3287 return 1; 3288 } 3289 } 3290 return sqlite3_win_test_unc_locking; 3291 } 3292 3293 /* 3294 ** Return true if the string passed in is the name of a file on a 3295 ** remote (network-mounted) volume. 3296 */ 3297 static int winIsRemoteVolume(const char *zFile){ 3298 WCHAR zRoot[4]; 3299 if( strncmp(zFile, "\\\\?\\",4)==0 ) zFile += 4; 3300 if( !sqlite3Isalpha(zFile[0]) ) return 0; 3301 if( zFile[1]!=':' ) return 0; 3302 if( !winIsDirSep(zFile[2]) ) return 0; 3303 zRoot[0] = (WCHAR)zFile[0]; 3304 zRoot[1] = ':'; 3305 zRoot[2] = '\\'; 3306 zRoot[3] = 0; 3307 return osGetDriveTypeW(zRoot)==DRIVE_REMOTE; 3308 } 3309 3310 /* 3311 ** Open the shared-memory area associated with database file pDbFd. 3312 */ 3313 static int winOpenSharedMemory(winFile *pDbFd){ 3314 struct winShm *p; /* The connection to be opened */ 3315 winShmNode *pShmNode = 0; /* The underlying mmapped file */ 3316 int rc = SQLITE_OK; /* Result code */ 3317 winShmNode *pNew; /* Newly allocated winShmNode */ 3318 int nName; /* Size of zName in bytes */ 3319 3320 assert( pDbFd->pShm==0 ); /* Not previously opened */ 3321 3322 /* Allocate space for the new sqlite3_shm object. Also speculatively 3323 ** allocate space for a new winShmNode and filename. */ 3324 p = sqlite3MallocZero( sizeof(*p) ); 3325 if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT; 3326 nName = sqlite3Strlen30(pDbFd->zPath); 3327 pNew = sqlite3MallocZero( sizeof(*pShmNode) + (i64)nName + 17 ); 3328 if( pNew==0 ){ 3329 sqlite3_free(p); 3330 return SQLITE_IOERR_NOMEM_BKPT; 3331 } 3332 pNew->zFilename = (char*)&pNew[1]; 3333 pNew->hSharedShm = INVALID_HANDLE_VALUE; 3334 pNew->isUnlocked = 1; 3335 if( winIsUNCPath(pDbFd->zPath) || winIsRemoteVolume(pDbFd->zPath) ){ 3336 pNew->bUseSharedLockHandle = 1; 3337 }else{ 3338 pNew->bUseSharedLockHandle = 0; 3339 } 3340 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath); 3341 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); 3342 3343 /* Look to see if there is an existing winShmNode that can be used. 3344 ** If no matching winShmNode currently exists, then create a new one. */ 3345 winShmEnterMutex(); 3346 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){ 3347 /* TBD need to come up with better match here. Perhaps 3348 ** use FILE_ID_BOTH_DIR_INFO Structure. */ 3349 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break; 3350 } 3351 if( pShmNode==0 ){ 3352 pShmNode = pNew; 3353 3354 /* Allocate a mutex for this winShmNode object, if one is required. */ 3355 if( sqlite3GlobalConfig.bCoreMutex ){ 3356 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); 3357 if( pShmNode->mutex==0 ) rc = SQLITE_IOERR_NOMEM_BKPT; 3358 } 3359 3360 /* Open a file-handle to use for mappings, and for the DMS lock. */ 3361 if( rc==SQLITE_OK ){ 3362 HANDLE h = INVALID_HANDLE_VALUE; 3363 pShmNode->isReadonly = sqlite3_uri_boolean(pDbFd->zPath,"readonly_shm",0); 3364 rc = winHandleOpen(pNew->zFilename, &pShmNode->isReadonly, &h); 3365 pShmNode->hSharedShm = h; 3366 } 3367 3368 /* If successful, link the new winShmNode into the global list. If an 3369 ** error occurred, free the object. */ 3370 if( rc==SQLITE_OK ){ 3371 pShmNode->pNext = winShmNodeList; 3372 winShmNodeList = pShmNode; 3373 pNew = 0; 3374 }else{ 3375 sqlite3_mutex_free(pShmNode->mutex); 3376 if( pShmNode->hSharedShm!=INVALID_HANDLE_VALUE ){ 3377 osCloseHandle(pShmNode->hSharedShm); 3378 } 3379 } 3380 } 3381 3382 /* If no error has occurred, link the winShm object to the winShmNode and 3383 ** the winShm to pDbFd. */ 3384 if( rc==SQLITE_OK ){ 3385 sqlite3_mutex_enter(pShmNode->mutex); 3386 p->pShmNode = pShmNode; 3387 p->pWinShmNext = pShmNode->pWinShmList; 3388 pShmNode->pWinShmList = p; 3389 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) 3390 p->id = pShmNode->nextShmId++; 3391 #endif 3392 pDbFd->pShm = p; 3393 sqlite3_mutex_leave(pShmNode->mutex); 3394 }else if( p ){ 3395 sqlite3_free(p); 3396 } 3397 3398 assert( rc!=SQLITE_OK || pShmNode->isUnlocked==0 || pShmNode->nRegion==0 ); 3399 winShmLeaveMutex(); 3400 sqlite3_free(pNew); 3401 3402 /* Open a file-handle on the *-shm file for this connection. This file-handle 3403 ** is only used for locking. The mapping of the *-shm file is created using 3404 ** the shared file handle in winShmNode.hSharedShm. */ 3405 if( rc==SQLITE_OK && pShmNode->bUseSharedLockHandle==0 ){ 3406 p->bReadonly = sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0); 3407 rc = winHandleOpen(pShmNode->zFilename, &p->bReadonly, &p->hShm); 3408 if( rc!=SQLITE_OK ){ 3409 assert( p->hShm==INVALID_HANDLE_VALUE ); 3410 winCloseSharedMemory(pDbFd, 0); 3411 } 3412 } 3413 3414 return rc; 3415 } 3416 3417 /* 3418 ** Close a connection to shared-memory. Delete the underlying 3419 ** storage if deleteFlag is true. 3420 */ 3421 static int winShmUnmap( 3422 sqlite3_file *fd, /* Database holding shared memory */ 3423 int deleteFlag /* Delete after closing if true */ 3424 ){ 3425 return winCloseSharedMemory((winFile*)fd, deleteFlag); 3426 } 3427 3428 /* 3429 ** Change the lock state for a shared-memory segment. 3430 */ 3431 static int winShmLock( 3432 sqlite3_file *fd, /* Database file holding the shared memory */ 3433 int ofst, /* First lock to acquire or release */ 3434 int n, /* Number of locks to acquire or release */ 3435 int flags /* What to do with the lock */ 3436 ){ 3437 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */ 3438 winShm *p = pDbFd->pShm; /* The shared memory being locked */ 3439 winShmNode *pShmNode; 3440 int rc = SQLITE_OK; /* Result code */ 3441 u16 mask = (u16)((1U<<(ofst+n)) - (1U<pShmNode; 3445 if( NEVER(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK; 3446 3447 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK ); 3448 assert( n>=1 ); 3449 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED) 3450 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE) 3451 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED) 3452 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) ); 3453 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 ); 3454 3455 /* Check that, if this to be a blocking lock, no locks that occur later 3456 ** in the following list than the lock being obtained are already held: 3457 ** 3458 ** 1. Recovery lock (ofst==2). 3459 ** 2. Checkpointer lock (ofst==1). 3460 ** 3. Write lock (ofst==0). 3461 ** 4. Read locks (ofst>=3 && ofstexclMask|p->sharedMask); 3470 assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || ( 3471 (ofst!=2 || lockMask==0) 3472 && (ofst!=1 || lockMask==0 || lockMask==2) 3473 && (ofst!=0 || lockMask<3) 3474 && (ofst<3 || lockMask<(1<exclMask & mask) 3489 ); 3490 if( ((flags & SQLITE_SHM_UNLOCK) && ((p->exclMask|p->sharedMask) & mask)) 3491 || (flags==(SQLITE_SHM_SHARED|SQLITE_SHM_LOCK) && 0==(p->sharedMask & mask)) 3492 || (flags==(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK)) 3493 ){ 3494 HANDLE h = p->hShm; 3495 3496 if( flags & SQLITE_SHM_UNLOCK ){ 3497 /* Case (a) - unlock. */ 3498 3499 assert( (p->exclMask & p->sharedMask)==0 ); 3500 assert( !(flags & SQLITE_SHM_EXCLUSIVE) || (p->exclMask & mask)==mask ); 3501 assert( !(flags & SQLITE_SHM_SHARED) || (p->sharedMask & mask)==mask ); 3502 3503 assert( !(flags & SQLITE_SHM_SHARED) || n==1 ); 3504 if( pShmNode->bUseSharedLockHandle ){ 3505 h = pShmNode->hSharedShm; 3506 if( flags & SQLITE_SHM_SHARED ){ 3507 winShm *pShm; 3508 sqlite3_mutex_enter(pShmNode->mutex); 3509 for(pShm=pShmNode->pWinShmList; pShm; pShm=pShm->pWinShmNext){ 3510 if( pShm!=p && (pShm->sharedMask & mask) ){ 3511 /* Another connection within this process is also holding this 3512 ** SHARED lock. So do not actually release the OS lock. */ 3513 h = INVALID_HANDLE_VALUE; 3514 break; 3515 } 3516 } 3517 sqlite3_mutex_leave(pShmNode->mutex); 3518 } 3519 } 3520 3521 if( h!=INVALID_HANDLE_VALUE ){ 3522 rc = winHandleUnlock(h, ofst+WIN_SHM_BASE, n); 3523 } 3524 3525 /* If successful, also clear the bits in sharedMask/exclMask */ 3526 if( rc==SQLITE_OK ){ 3527 p->exclMask = (p->exclMask & ~mask); 3528 p->sharedMask = (p->sharedMask & ~mask); 3529 } 3530 }else{ 3531 int bExcl = ((flags & SQLITE_SHM_EXCLUSIVE) ? 1 : 0); 3532 DWORD nMs = winFileBusyTimeout(pDbFd); 3533 3534 if( pShmNode->bUseSharedLockHandle ){ 3535 winShm *pShm; 3536 h = pShmNode->hSharedShm; 3537 sqlite3_mutex_enter(pShmNode->mutex); 3538 for(pShm=pShmNode->pWinShmList; pShm; pShm=pShm->pWinShmNext){ 3539 if( bExcl ){ 3540 if( (pShm->sharedMask|pShm->exclMask) & mask ){ 3541 rc = SQLITE_BUSY; 3542 h = INVALID_HANDLE_VALUE; 3543 } 3544 }else{ 3545 if( pShm->sharedMask & mask ){ 3546 h = INVALID_HANDLE_VALUE; 3547 }else if( pShm->exclMask & mask ){ 3548 rc = SQLITE_BUSY; 3549 h = INVALID_HANDLE_VALUE; 3550 } 3551 } 3552 } 3553 sqlite3_mutex_leave(pShmNode->mutex); 3554 } 3555 3556 if( h!=INVALID_HANDLE_VALUE ){ 3557 rc = winHandleLockTimeout(h, ofst+WIN_SHM_BASE, n, bExcl, nMs); 3558 } 3559 if( rc==SQLITE_OK ){ 3560 if( bExcl ){ 3561 p->exclMask = (p->exclMask | mask); 3562 }else{ 3563 p->sharedMask = (p->sharedMask | mask); 3564 } 3565 } 3566 } 3567 } 3568 3569 OSTRACE(( 3570 "SHM-LOCK(%d,%d,%d) pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x," 3571 " rc=%s\n", 3572 ofst, n, flags, 3573 osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask, 3574 sqlite3ErrName(rc)) 3575 ); 3576 return rc; 3577 } 3578 3579 /* 3580 ** Implement a memory barrier or memory fence on shared memory. 3581 ** 3582 ** All loads and stores begun before the barrier must complete before 3583 ** any load or store begun after the barrier. 3584 */ 3585 static void winShmBarrier( 3586 sqlite3_file *fd /* Database holding the shared memory */ 3587 ){ 3588 UNUSED_PARAMETER(fd); 3589 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */ 3590 winShmEnterMutex(); /* Also mutex, for redundancy */ 3591 winShmLeaveMutex(); 3592 } 3593 3594 /* 3595 ** This function is called to obtain a pointer to region iRegion of the 3596 ** shared-memory associated with the database file fd. Shared-memory regions 3597 ** are numbered starting from zero. Each shared-memory region is szRegion 3598 ** bytes in size. 3599 ** 3600 ** If an error occurs, an error code is returned and *pp is set to NULL. 3601 ** 3602 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory 3603 ** region has not been allocated (by any client, including one running in a 3604 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 3605 ** isWrite is non-zero and the requested shared-memory region has not yet 3606 ** been allocated, it is allocated by this function. 3607 ** 3608 ** If the shared-memory region has already been allocated or is allocated by 3609 ** this call as described above, then it is mapped into this processes 3610 ** address space (if it is not already), *pp is set to point to the mapped 3611 ** memory and SQLITE_OK returned. 3612 */ 3613 static int winShmMap( 3614 sqlite3_file *fd, /* Handle open on database file */ 3615 int iRegion, /* Region to retrieve */ 3616 int szRegion, /* Size of regions */ 3617 int isWrite, /* True to extend file if necessary */ 3618 void volatile **pp /* OUT: Mapped memory */ 3619 ){ 3620 winFile *pDbFd = (winFile*)fd; 3621 winShm *pShm = pDbFd->pShm; 3622 winShmNode *pShmNode; 3623 DWORD protect = PAGE_READWRITE; 3624 DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ; 3625 int rc = SQLITE_OK; 3626 3627 if( !pShm ){ 3628 rc = winOpenSharedMemory(pDbFd); 3629 if( rc!=SQLITE_OK ) return rc; 3630 pShm = pDbFd->pShm; 3631 assert( pShm!=0 ); 3632 } 3633 pShmNode = pShm->pShmNode; 3634 3635 sqlite3_mutex_enter(pShmNode->mutex); 3636 if( pShmNode->isUnlocked ){ 3637 /* Take the DMS lock. */ 3638 assert( pShmNode->nRegion==0 ); 3639 rc = winLockSharedMemory(pShmNode, winFileBusyTimeout(pDbFd)); 3640 if( rc!=SQLITE_OK ) goto shmpage_out; 3641 } 3642 3643 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); 3644 if( pShmNode->nRegion<=iRegion ){ 3645 HANDLE hShared = pShmNode->hSharedShm; 3646 struct ShmRegion *apNew; /* New aRegion[] array */ 3647 i64 nByte = ((i64)iRegion+1)*(i64)szRegion; /* Minimum file size */ 3648 sqlite3_int64 sz; /* Current size of wal-index file */ 3649 3650 pShmNode->szRegion = szRegion; 3651 3652 /* The requested region is not mapped into this processes address space. 3653 ** Check to see if it has been allocated (i.e. if the wal-index file is 3654 ** large enough to contain the requested region). 3655 */ 3656 rc = winHandleSize(hShared, &sz); 3657 if( rc!=SQLITE_OK ){ 3658 rc = winLogError(rc, osGetLastError(), "winShmMap1", pDbFd->zPath); 3659 goto shmpage_out; 3660 } 3661 3662 if( szzPath); 3672 goto shmpage_out; 3673 } 3674 } 3675 3676 /* Map the requested memory region into this processes address space. */ 3677 apNew = (struct ShmRegion*)sqlite3_realloc64( 3678 pShmNode->aRegion, ((i64)iRegion+1)*sizeof(apNew[0]) 3679 ); 3680 if( !apNew ){ 3681 rc = SQLITE_IOERR_NOMEM_BKPT; 3682 goto shmpage_out; 3683 } 3684 pShmNode->aRegion = apNew; 3685 3686 if( pShmNode->isReadonly ){ 3687 protect = PAGE_READONLY; 3688 flags = FILE_MAP_READ; 3689 } 3690 3691 while( pShmNode->nRegion<=iRegion ){ 3692 HANDLE hMap = NULL; /* file-mapping handle */ 3693 void *pMap = 0; /* Mapped memory region */ 3694 3695 #ifdef SQLITE_UWP 3696 hMap = osCreateFileMappingFromApp(hShared, NULL, protect, nByte, NULL); 3697 #else 3698 hMap = osCreateFileMappingW(hShared, NULL, protect, 0, nByte, NULL); 3699 #endif 3700 OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%lld, rc=%s\n", 3701 osGetCurrentProcessId(), pShmNode->nRegion, nByte, 3702 hMap ? "ok" : "failed")); 3703 if( hMap ){ 3704 i64 iOffset = pShmNode->nRegion*szRegion; 3705 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; 3706 #ifdef SQLITE_UWP 3707 pMap = osMapViewOfFileFromApp(hMap, flags, 3708 iOffset - iOffsetShift, (i64)szRegion + iOffsetShift 3709 ); 3710 #else 3711 pMap = osMapViewOfFile(hMap, flags, 3712 0, iOffset - iOffsetShift, (i64)szRegion + iOffsetShift 3713 ); 3714 #endif 3715 OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n", 3716 osGetCurrentProcessId(), pShmNode->nRegion, iOffset, 3717 szRegion, pMap ? "ok" : "failed")); 3718 } 3719 if( !pMap ){ 3720 pShmNode->lastErrno = osGetLastError(); 3721 rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno, 3722 "winShmMap3", pDbFd->zPath); 3723 if( hMap ) osCloseHandle(hMap); 3724 goto shmpage_out; 3725 } 3726 3727 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap; 3728 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap; 3729 pShmNode->nRegion++; 3730 } 3731 } 3732 3733 shmpage_out: 3734 if( pShmNode->nRegion>iRegion ){ 3735 i64 iOffset = (i64)iRegion*(i64)szRegion; 3736 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; 3737 char *p = (char *)pShmNode->aRegion[iRegion].pMap; 3738 *pp = (void *)&p[iOffsetShift]; 3739 }else{ 3740 *pp = 0; 3741 } 3742 if( pShmNode->isReadonly && rc==SQLITE_OK ){ 3743 rc = SQLITE_READONLY; 3744 } 3745 sqlite3_mutex_leave(pShmNode->mutex); 3746 return rc; 3747 } 3748 3749 #else 3750 # define winShmMap 0 3751 # define winShmLock 0 3752 # define winShmBarrier 0 3753 # define winShmUnmap 0 3754 #endif /* #ifndef SQLITE_OMIT_WAL */ 3755 3756 /* 3757 ** Cleans up the mapped region of the specified file, if any. 3758 */ 3759 #if SQLITE_MAX_MMAP_SIZE>0 3760 static int winUnmapfile(winFile *pFile){ 3761 assert( pFile!=0 ); 3762 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, " 3763 "mmapSize=%lld, mmapSizeMax=%lld\n", 3764 osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion, 3765 pFile->mmapSize, pFile->mmapSizeMax)); 3766 if( pFile->pMapRegion ){ 3767 if( !osUnmapViewOfFile(pFile->pMapRegion) ){ 3768 pFile->lastErrno = osGetLastError(); 3769 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, " 3770 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile, 3771 pFile->pMapRegion)); 3772 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno, 3773 "winUnmapfile1", pFile->zPath); 3774 } 3775 pFile->pMapRegion = 0; 3776 pFile->mmapSize = 0; 3777 } 3778 if( pFile->hMap!=NULL ){ 3779 if( !osCloseHandle(pFile->hMap) ){ 3780 pFile->lastErrno = osGetLastError(); 3781 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n", 3782 osGetCurrentProcessId(), pFile, pFile->hMap)); 3783 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno, 3784 "winUnmapfile2", pFile->zPath); 3785 } 3786 pFile->hMap = NULL; 3787 } 3788 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n", 3789 osGetCurrentProcessId(), pFile)); 3790 return SQLITE_OK; 3791 } 3792 3793 /* 3794 ** Memory map or remap the file opened by file-descriptor pFd (if the file 3795 ** is already mapped, the existing mapping is replaced by the new). Or, if 3796 ** there already exists a mapping for this file, and there are still 3797 ** outstanding xFetch() references to it, this function is a no-op. 3798 ** 3799 ** If parameter nByte is non-negative, then it is the requested size of 3800 ** the mapping to create. Otherwise, if nByte is less than zero, then the 3801 ** requested size is the size of the file on disk. The actual size of the 3802 ** created mapping is either the requested size or the value configured 3803 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller. 3804 ** 3805 ** SQLITE_OK is returned if no error occurs (even if the mapping is not 3806 ** recreated as a result of outstanding references) or an SQLite error 3807 ** code otherwise. 3808 */ 3809 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ 3810 sqlite3_int64 nMap = nByte; 3811 int rc; 3812 3813 assert( nMap>=0 || pFd->nFetchOut==0 ); 3814 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n", 3815 osGetCurrentProcessId(), pFd, nByte)); 3816 3817 if( pFd->nFetchOut>0 ) return SQLITE_OK; 3818 3819 if( nMap<0 ){ 3820 rc = winFileSize((sqlite3_file*)pFd, &nMap); 3821 if( rc ){ 3822 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n", 3823 osGetCurrentProcessId(), pFd)); 3824 return SQLITE_IOERR_FSTAT; 3825 } 3826 } 3827 if( nMap>pFd->mmapSizeMax ){ 3828 nMap = pFd->mmapSizeMax; 3829 } 3830 nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1); 3831 3832 if( nMap==0 && pFd->mmapSize>0 ){ 3833 winUnmapfile(pFd); 3834 } 3835 if( nMap!=pFd->mmapSize ){ 3836 void *pNew = 0; 3837 DWORD protect = PAGE_READONLY; 3838 DWORD flags = FILE_MAP_READ; 3839 3840 winUnmapfile(pFd); 3841 #ifdef SQLITE_MMAP_READWRITE 3842 if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){ 3843 protect = PAGE_READWRITE; 3844 flags |= FILE_MAP_WRITE; 3845 } 3846 #endif 3847 #ifdef SQLITE_UWP 3848 pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL); 3849 #else 3850 pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect, 3851 (DWORD)((nMap>>32) & 0xffffffff), 3852 (DWORD)(nMap & 0xffffffff), NULL); 3853 #endif 3854 if( pFd->hMap==NULL ){ 3855 pFd->lastErrno = osGetLastError(); 3856 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno, 3857 "winMapfile1", pFd->zPath); 3858 /* Log the error, but continue normal operation using xRead/xWrite */ 3859 OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n", 3860 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); 3861 return SQLITE_OK; 3862 } 3863 assert( (nMap % winSysInfo.dwPageSize)==0 ); 3864 assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff ); 3865 #ifdef SQLITE_UWP 3866 pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap); 3867 #else 3868 pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap); 3869 #endif 3870 if( pNew==NULL ){ 3871 osCloseHandle(pFd->hMap); 3872 pFd->hMap = NULL; 3873 pFd->lastErrno = osGetLastError(); 3874 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno, 3875 "winMapfile2", pFd->zPath); 3876 /* Log the error, but continue normal operation using xRead/xWrite */ 3877 OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n", 3878 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); 3879 return SQLITE_OK; 3880 } 3881 pFd->pMapRegion = pNew; 3882 pFd->mmapSize = nMap; 3883 } 3884 3885 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n", 3886 osGetCurrentProcessId(), pFd)); 3887 return SQLITE_OK; 3888 } 3889 #endif /* SQLITE_MAX_MMAP_SIZE>0 */ 3890 3891 /* 3892 ** If possible, return a pointer to a mapping of file fd starting at offset 3893 ** iOff. The mapping must be valid for at least nAmt bytes. 3894 ** 3895 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. 3896 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. 3897 ** Finally, if an error does occur, return an SQLite error code. The final 3898 ** value of *pp is undefined in this case. 3899 ** 3900 ** If this function does return a pointer, the caller must eventually 3901 ** release the reference by calling winUnfetch(). 3902 */ 3903 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ 3904 #if SQLITE_MAX_MMAP_SIZE>0 3905 winFile *pFd = (winFile*)fd; /* The underlying database file */ 3906 #endif 3907 *pp = 0; 3908 3909 OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n", 3910 osGetCurrentProcessId(), fd, iOff, nAmt, pp)); 3911 3912 #if SQLITE_MAX_MMAP_SIZE>0 3913 if( pFd->mmapSizeMax>0 ){ 3914 /* Ensure that there is always at least a 256 byte buffer of addressable 3915 ** memory following the returned page. If the database is corrupt, 3916 ** SQLite may overread the page slightly (in practice only a few bytes, 3917 ** but 256 is safe, round, number). */ 3918 const int nEofBuffer = 256; 3919 if( pFd->pMapRegion==0 ){ 3920 int rc = winMapfile(pFd, -1); 3921 if( rc!=SQLITE_OK ){ 3922 OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n", 3923 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); 3924 return rc; 3925 } 3926 } 3927 if( pFd->mmapSize >= (iOff+nAmt+nEofBuffer) ){ 3928 assert( pFd->pMapRegion!=0 ); 3929 *pp = &((u8 *)pFd->pMapRegion)[iOff]; 3930 pFd->nFetchOut++; 3931 } 3932 } 3933 #endif 3934 3935 OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n", 3936 osGetCurrentProcessId(), fd, pp, *pp)); 3937 return SQLITE_OK; 3938 } 3939 3940 /* 3941 ** If the third argument is non-NULL, then this function releases a 3942 ** reference obtained by an earlier call to winFetch(). The second 3943 ** argument passed to this function must be the same as the corresponding 3944 ** argument that was passed to the winFetch() invocation. 3945 ** 3946 ** Or, if the third argument is NULL, then this function is being called 3947 ** to inform the VFS layer that, according to POSIX, any existing mapping 3948 ** may now be invalid and should be unmapped. 3949 */ 3950 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){ 3951 #if SQLITE_MAX_MMAP_SIZE>0 3952 winFile *pFd = (winFile*)fd; /* The underlying database file */ 3953 3954 /* If p==0 (unmap the entire file) then there must be no outstanding 3955 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference), 3956 ** then there must be at least one outstanding. */ 3957 assert( (p==0)==(pFd->nFetchOut==0) ); 3958 3959 /* If p!=0, it must match the iOff value. */ 3960 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] ); 3961 3962 OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n", 3963 osGetCurrentProcessId(), pFd, iOff, p)); 3964 3965 if( p ){ 3966 pFd->nFetchOut--; 3967 }else{ 3968 /* FIXME: If Windows truly always prevents truncating or deleting a 3969 ** file while a mapping is held, then the following winUnmapfile() call 3970 ** is unnecessary can be omitted - potentially improving 3971 ** performance. */ 3972 winUnmapfile(pFd); 3973 } 3974 3975 assert( pFd->nFetchOut>=0 ); 3976 #endif 3977 3978 OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n", 3979 osGetCurrentProcessId(), fd)); 3980 return SQLITE_OK; 3981 } 3982 3983 /* 3984 ** Here ends the implementation of all sqlite3_file methods. 3985 ** 3986 ********************** End sqlite3_file Methods ******************************* 3987 ******************************************************************************/ 3988 3989 /* 3990 ** This vector defines all the methods that can operate on an 3991 ** sqlite3_file for win32. 3992 */ 3993 static const sqlite3_io_methods winIoMethod = { 3994 3, /* iVersion */ 3995 winClose, /* xClose */ 3996 winRead, /* xRead */ 3997 winWrite, /* xWrite */ 3998 winTruncate, /* xTruncate */ 3999 winSync, /* xSync */ 4000 winFileSize, /* xFileSize */ 4001 winLock, /* xLock */ 4002 winUnlock, /* xUnlock */ 4003 winCheckReservedLock, /* xCheckReservedLock */ 4004 winFileControl, /* xFileControl */ 4005 winSectorSize, /* xSectorSize */ 4006 winDeviceCharacteristics, /* xDeviceCharacteristics */ 4007 winShmMap, /* xShmMap */ 4008 winShmLock, /* xShmLock */ 4009 winShmBarrier, /* xShmBarrier */ 4010 winShmUnmap, /* xShmUnmap */ 4011 winFetch, /* xFetch */ 4012 winUnfetch /* xUnfetch */ 4013 }; 4014 4015 /* 4016 ** This vector defines all the methods that can operate on an 4017 ** sqlite3_file for win32 without performing any locking. 4018 */ 4019 static const sqlite3_io_methods winIoNolockMethod = { 4020 3, /* iVersion */ 4021 winClose, /* xClose */ 4022 winRead, /* xRead */ 4023 winWrite, /* xWrite */ 4024 winTruncate, /* xTruncate */ 4025 winSync, /* xSync */ 4026 winFileSize, /* xFileSize */ 4027 winNolockLock, /* xLock */ 4028 winNolockUnlock, /* xUnlock */ 4029 winNolockCheckReservedLock, /* xCheckReservedLock */ 4030 winFileControl, /* xFileControl */ 4031 winSectorSize, /* xSectorSize */ 4032 winDeviceCharacteristics, /* xDeviceCharacteristics */ 4033 winShmMap, /* xShmMap */ 4034 winShmLock, /* xShmLock */ 4035 winShmBarrier, /* xShmBarrier */ 4036 winShmUnmap, /* xShmUnmap */ 4037 winFetch, /* xFetch */ 4038 winUnfetch /* xUnfetch */ 4039 }; 4040 4041 static winVfsAppData winAppData = { 4042 &winIoMethod, /* pMethod */ 4043 0, /* pAppData */ 4044 0 /* bNoLock */ 4045 }; 4046 4047 static winVfsAppData winNolockAppData = { 4048 &winIoNolockMethod, /* pMethod */ 4049 0, /* pAppData */ 4050 1 /* bNoLock */ 4051 }; 4052 4053 /**************************************************************************** 4054 **************************** sqlite3_vfs methods **************************** 4055 ** 4056 ** This division contains the implementation of methods on the 4057 ** sqlite3_vfs object. 4058 */ 4059 4060 /* 4061 ** This function returns non-zero if the specified UTF-8 string buffer 4062 ** ends with a directory separator character or one was successfully 4063 ** added to it. 4064 */ 4065 static int winMakeEndInDirSep(int nBuf, char *zBuf){ 4066 if( zBuf ){ 4067 int nLen = sqlite3Strlen30(zBuf); 4068 if( nLen>0 ){ 4069 if( winIsDirSep(zBuf[nLen-1]) ){ 4070 return 1; 4071 }else if( nLen+1mxPathname; 4126 nBuf = 2 + (i64)nMax; 4127 zBuf = sqlite3MallocZero( nBuf ); 4128 if( !zBuf ){ 4129 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); 4130 return SQLITE_IOERR_NOMEM_BKPT; 4131 } 4132 4133 /* Figure out the effective temporary directory. First, check if one 4134 ** has been explicitly set by the application; otherwise, use the one 4135 ** configured by the operating system. 4136 */ 4137 nDir = nMax - (nPre + 15); 4138 assert( nDir>0 ); 4139 if( winTempDirDefined() ){ 4140 int nDirLen = sqlite3Strlen30(sqlite3_temp_directory); 4141 if( nDirLen>0 ){ 4142 if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){ 4143 nDirLen++; 4144 } 4145 if( nDirLen>nDir ){ 4146 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR)); 4147 sqlite3_free(zBuf); 4148 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); 4149 return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0); 4150 } 4151 sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory); 4152 } 4153 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR)); 4154 } 4155 4156 #if defined(__CYGWIN__) 4157 else if( osGetenv!=NULL ){ 4158 static const char *azDirs[] = { 4159 0, /* getenv("SQLITE_TMPDIR") */ 4160 0, /* getenv("TMPDIR") */ 4161 0, /* getenv("TMP") */ 4162 0, /* getenv("TEMP") */ 4163 0, /* getenv("USERPROFILE") */ 4164 "/var/tmp", 4165 "/usr/tmp", 4166 "/tmp", 4167 ".", 4168 0 /* List terminator */ 4169 }; 4170 unsigned int i; 4171 const char *zDir = 0; 4172 4173 if( !azDirs[0] ) azDirs[0] = osGetenv("SQLITE_TMPDIR"); 4174 if( !azDirs[1] ) azDirs[1] = osGetenv("TMPDIR"); 4175 if( !azDirs[2] ) azDirs[2] = osGetenv("TMP"); 4176 if( !azDirs[3] ) azDirs[3] = osGetenv("TEMP"); 4177 if( !azDirs[4] ) azDirs[4] = osGetenv("USERPROFILE"); 4178 for(i=0; i/etilqs_XXXXXXXXXXXXXXX\0\0" 4247 ** 4248 ** If not, return SQLITE_ERROR. The number 17 is used here in order to 4249 ** account for the space used by the 15 character random suffix and the 4250 ** two trailing NUL characters. The final directory separator character 4251 ** has already added if it was not already present. 4252 */ 4253 nLen = sqlite3Strlen30(zBuf); 4254 if( (nLen + nPre + 17) > nBuf ){ 4255 sqlite3_free(zBuf); 4256 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); 4257 return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0); 4258 } 4259 4260 sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX); 4261 4262 j = sqlite3Strlen30(zBuf); 4263 sqlite3_randomness(15, &zBuf[j]); 4264 pid = osGetCurrentProcessId(); 4265 for(i=0; i<15; i++, j++){ 4266 zBuf[j] += pid & 0xff; 4267 pid >>= 8; 4268 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; 4269 } 4270 zBuf[j] = 0; 4271 zBuf[j+1] = 0; 4272 *pzBuf = zBuf; 4273 4274 OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf)); 4275 return SQLITE_OK; 4276 } 4277 4278 /* 4279 ** Return TRUE if the named file is really a directory. Return false if 4280 ** it is something other than a directory, or if there is any kind of memory 4281 ** allocation failure. 4282 */ 4283 static int winIsDir(LPCWSTR zConverted){ 4284 DWORD attr; 4285 int rc = 0; 4286 DWORD lastErrno; 4287 int cnt = 0; 4288 WIN32_FILE_ATTRIBUTE_DATA sAttrData; 4289 memset(&sAttrData, 0, sizeof(sAttrData)); 4290 while( !(rc = osGetFileAttributesExW(zConverted, 4291 GetFileExInfoStandard, 4292 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} 4293 if( !rc ){ 4294 return 0; /* Invalid name? */ 4295 } 4296 attr = sAttrData.dwFileAttributes; 4297 return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY); 4298 } 4299 4300 /* forward reference */ 4301 static int winAccess( 4302 sqlite3_vfs *pVfs, /* Not used on win32 */ 4303 const char *zFilename, /* Name of file to check */ 4304 int flags, /* Type of test to make on this file */ 4305 int *pResOut /* OUT: Result */ 4306 ); 4307 4308 /* 4309 ** The Windows version of xAccess() accepts an extra bit in the flags 4310 ** parameter that prevents an anti-virus retry loop. 4311 */ 4312 #define NORETRY 0x4000 4313 4314 /* 4315 ** Open a file. 4316 */ 4317 static int winOpen( 4318 sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */ 4319 const char *zName, /* Name of the file (UTF-8) */ 4320 sqlite3_file *id, /* Write the SQLite file handle here */ 4321 int flags, /* Open mode flags */ 4322 int *pOutFlags /* Status return flags */ 4323 ){ 4324 HANDLE h; 4325 DWORD lastErrno = 0; 4326 DWORD dwDesiredAccess; 4327 DWORD dwShareMode; 4328 DWORD dwCreationDisposition; 4329 DWORD dwFlagsAndAttributes = 0; 4330 winVfsAppData *pAppData; 4331 winFile *pFile = (winFile*)id; 4332 LPWSTR zConverted; /* Filename in OS encoding */ 4333 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */ 4334 int cnt = 0; 4335 int isRO = 0; /* file is known to be accessible readonly */ 4336 4337 /* If argument zPath is a NULL pointer, this function is required to open 4338 ** a temporary file. Use this buffer to store the file name in. 4339 */ 4340 char *zTmpname = 0; /* For temporary filename, if necessary. */ 4341 4342 int rc = SQLITE_OK; /* Function Return Code */ 4343 #if !defined(NDEBUG) 4344 int eType = flags&0x0FFF00; /* Type of file to open */ 4345 #endif 4346 4347 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); 4348 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); 4349 int isCreate = (flags & SQLITE_OPEN_CREATE); 4350 int isReadonly = (flags & SQLITE_OPEN_READONLY); 4351 int isReadWrite = (flags & SQLITE_OPEN_READWRITE); 4352 4353 #ifndef NDEBUG 4354 int isOpenJournal = (isCreate && ( 4355 eType==SQLITE_OPEN_SUPER_JOURNAL 4356 || eType==SQLITE_OPEN_MAIN_JOURNAL 4357 || eType==SQLITE_OPEN_WAL 4358 )); 4359 #endif 4360 4361 OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n", 4362 zUtf8Name, id, flags, pOutFlags)); 4363 4364 /* Check the following statements are true: 4365 ** 4366 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and 4367 ** (b) if CREATE is set, then READWRITE must also be set, and 4368 ** (c) if EXCLUSIVE is set, then CREATE must also be set. 4369 ** (d) if DELETEONCLOSE is set, then CREATE must also be set. 4370 */ 4371 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); 4372 assert(isCreate==0 || isReadWrite); 4373 assert(isExclusive==0 || isCreate); 4374 assert(isDelete==0 || isCreate); 4375 4376 /* The main DB, main journal, WAL file and super-journal are never 4377 ** automatically deleted. Nor are they ever temporary files. */ 4378 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); 4379 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); 4380 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL ); 4381 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL ); 4382 4383 /* Assert that the upper layer has set one of the "file-type" flags. */ 4384 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB 4385 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 4386 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_SUPER_JOURNAL 4387 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL 4388 ); 4389 4390 assert( pFile!=0 ); 4391 memset(pFile, 0, sizeof(winFile)); 4392 pFile->h = INVALID_HANDLE_VALUE; 4393 4394 /* If the second argument to this function is NULL, generate a 4395 ** temporary file name to use 4396 */ 4397 if( !zUtf8Name ){ 4398 assert( isDelete && !isOpenJournal ); 4399 rc = winGetTempname(pVfs, &zTmpname); 4400 if( rc!=SQLITE_OK ){ 4401 OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc))); 4402 return rc; 4403 } 4404 zUtf8Name = zTmpname; 4405 } 4406 4407 /* Database filenames are double-zero terminated if they are not 4408 ** URIs with parameters. Hence, they can always be passed into 4409 ** sqlite3_uri_parameter(). 4410 */ 4411 assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) || 4412 zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 ); 4413 4414 /* Convert the filename to the system encoding. */ 4415 zConverted = winConvertFromUtf8Filename(zUtf8Name); 4416 if( zConverted==0 ){ 4417 sqlite3_free(zTmpname); 4418 OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name)); 4419 return SQLITE_IOERR_NOMEM_BKPT; 4420 } 4421 4422 if( winIsDir(zConverted) ){ 4423 sqlite3_free(zConverted); 4424 sqlite3_free(zTmpname); 4425 OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name)); 4426 return SQLITE_CANTOPEN_ISDIR; 4427 } 4428 4429 if( isReadWrite ){ 4430 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; 4431 }else{ 4432 dwDesiredAccess = GENERIC_READ; 4433 } 4434 4435 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 4436 ** created. SQLite doesn't use it to indicate "exclusive access" 4437 ** as it is usually understood. 4438 */ 4439 if( isExclusive ){ 4440 /* Creates a new file, only if it does not already exist. */ 4441 /* If the file exists, it fails. */ 4442 dwCreationDisposition = CREATE_NEW; 4443 }else if( isCreate ){ 4444 /* Open existing file, or create if it doesn't exist */ 4445 dwCreationDisposition = OPEN_ALWAYS; 4446 }else{ 4447 /* Opens a file, only if it exists. */ 4448 dwCreationDisposition = OPEN_EXISTING; 4449 } 4450 4451 if( 0==sqlite3_uri_boolean(zName, "exclusive", 0) ){ 4452 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; 4453 }else{ 4454 dwShareMode = 0; 4455 } 4456 4457 if( isDelete ){ 4458 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY 4459 | FILE_ATTRIBUTE_HIDDEN 4460 | FILE_FLAG_DELETE_ON_CLOSE; 4461 }else{ 4462 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; 4463 } 4464 do{ 4465 h = osCreateFileW(zConverted, 4466 dwDesiredAccess, 4467 dwShareMode, NULL, 4468 dwCreationDisposition, 4469 dwFlagsAndAttributes, 4470 NULL); 4471 if( h!=INVALID_HANDLE_VALUE ) break; 4472 if( isReadWrite ){ 4473 int rc2; 4474 sqlite3BeginBenignMalloc(); 4475 rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ|NORETRY, &isRO); 4476 sqlite3EndBenignMalloc(); 4477 if( rc2==SQLITE_OK && isRO ) break; 4478 } 4479 }while( winRetryIoerr(&cnt, &lastErrno) ); 4480 winLogIoerr(cnt, __LINE__); 4481 4482 OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name, 4483 dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); 4484 4485 if( h==INVALID_HANDLE_VALUE ){ 4486 sqlite3_free(zConverted); 4487 sqlite3_free(zTmpname); 4488 if( isReadWrite && isRO && !isExclusive ){ 4489 return winOpen(pVfs, zName, id, 4490 ((flags|SQLITE_OPEN_READONLY) & 4491 ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), 4492 pOutFlags); 4493 }else{ 4494 pFile->lastErrno = lastErrno; 4495 winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name); 4496 return SQLITE_CANTOPEN_BKPT; 4497 } 4498 } 4499 4500 if( pOutFlags ){ 4501 if( isReadWrite ){ 4502 *pOutFlags = SQLITE_OPEN_READWRITE; 4503 }else{ 4504 *pOutFlags = SQLITE_OPEN_READONLY; 4505 } 4506 } 4507 4508 OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, " 4509 "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ? 4510 *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); 4511 4512 pAppData = (winVfsAppData*)pVfs->pAppData; 4513 4514 sqlite3_free(zConverted); 4515 sqlite3_free(zTmpname); 4516 id->pMethods = pAppData ? pAppData->pMethod : &winIoMethod; 4517 pFile->pVfs = pVfs; 4518 pFile->h = h; 4519 if( isReadonly ){ 4520 pFile->ctrlFlags |= WINFILE_RDONLY; 4521 } 4522 if( (flags & SQLITE_OPEN_MAIN_DB) 4523 && sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) 4524 ){ 4525 pFile->ctrlFlags |= WINFILE_PSOW; 4526 } 4527 pFile->lastErrno = NO_ERROR; 4528 pFile->zPath = zName; 4529 #if SQLITE_MAX_MMAP_SIZE>0 4530 pFile->hMap = NULL; 4531 pFile->pMapRegion = 0; 4532 pFile->mmapSize = 0; 4533 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap; 4534 #endif 4535 4536 OpenCounter(+1); 4537 return rc; 4538 } 4539 4540 /* 4541 ** Delete the named file. 4542 ** 4543 ** Note that Windows does not allow a file to be deleted if some other 4544 ** process has it open. Sometimes a virus scanner or indexing program 4545 ** will open a journal file shortly after it is created in order to do 4546 ** whatever it does. While this other process is holding the 4547 ** file open, we will be unable to delete it. To work around this 4548 ** problem, we delay 100 milliseconds and try to delete again. Up 4549 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving 4550 ** up and returning an error. 4551 */ 4552 static int winDelete( 4553 sqlite3_vfs *pVfs, /* Not used on win32 */ 4554 const char *zFilename, /* Name of file to delete */ 4555 int syncDir /* Not used on win32 */ 4556 ){ 4557 int cnt = 0; 4558 int rc; 4559 DWORD attr; 4560 DWORD lastErrno = 0; 4561 LPWSTR zConverted; 4562 UNUSED_PARAMETER(pVfs); 4563 UNUSED_PARAMETER(syncDir); 4564 4565 SimulateIOError(return SQLITE_IOERR_DELETE); 4566 OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir)); 4567 4568 zConverted = winConvertFromUtf8Filename(zFilename); 4569 if( zConverted==0 ){ 4570 OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); 4571 return SQLITE_IOERR_NOMEM_BKPT; 4572 } 4573 do { 4574 attr = osGetFileAttributesW(zConverted); 4575 if ( attr==INVALID_FILE_ATTRIBUTES ){ 4576 lastErrno = osGetLastError(); 4577 if( lastErrno==ERROR_FILE_NOT_FOUND 4578 || lastErrno==ERROR_PATH_NOT_FOUND ){ 4579 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ 4580 }else{ 4581 rc = SQLITE_ERROR; 4582 } 4583 break; 4584 } 4585 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ 4586 rc = SQLITE_ERROR; /* Files only. */ 4587 break; 4588 } 4589 if ( osDeleteFileW(zConverted) ){ 4590 rc = SQLITE_OK; /* Deleted OK. */ 4591 break; 4592 } 4593 if ( !winRetryIoerr(&cnt, &lastErrno) ){ 4594 rc = SQLITE_ERROR; /* No more retries. */ 4595 break; 4596 } 4597 } while(1); 4598 if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){ 4599 rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename); 4600 }else{ 4601 winLogIoerr(cnt, __LINE__); 4602 } 4603 sqlite3_free(zConverted); 4604 OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc))); 4605 return rc; 4606 } 4607 4608 /* 4609 ** Check the existence and status of a file. 4610 */ 4611 static int winAccess( 4612 sqlite3_vfs *pVfs, /* Not used on win32 */ 4613 const char *zFilename, /* Name of file to check */ 4614 int flags, /* Type of test to make on this file */ 4615 int *pResOut /* OUT: Result */ 4616 ){ 4617 DWORD attr; 4618 int rc = 0; 4619 int cnt = 0; 4620 DWORD lastErrno = 0; 4621 LPWSTR zConverted; 4622 int noRetry = 0; /* Do not use winRetryIoerr() */ 4623 WIN32_FILE_ATTRIBUTE_DATA sAttrData; 4624 UNUSED_PARAMETER(pVfs); 4625 4626 if( (flags & NORETRY)!=0 ){ 4627 noRetry = 1; 4628 flags &= ~NORETRY; 4629 } 4630 4631 SimulateIOError( return SQLITE_IOERR_ACCESS; ); 4632 OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n", 4633 zFilename, flags, pResOut)); 4634 4635 if( zFilename==0 ){ 4636 *pResOut = 0; 4637 OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", 4638 zFilename, pResOut, *pResOut)); 4639 return SQLITE_OK; 4640 } 4641 4642 zConverted = winConvertFromUtf8Filename(zFilename); 4643 if( zConverted==0 ){ 4644 OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); 4645 return SQLITE_IOERR_NOMEM_BKPT; 4646 } 4647 memset(&sAttrData, 0, sizeof(sAttrData)); 4648 while( !(rc = osGetFileAttributesExW(zConverted, 4649 GetFileExInfoStandard, 4650 &sAttrData)) 4651 && !noRetry 4652 && winRetryIoerr(&cnt, &lastErrno) 4653 ){ /* Loop until true */} 4654 if( rc ){ 4655 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file 4656 ** as if it does not exist. 4657 */ 4658 if( flags==SQLITE_ACCESS_EXISTS 4659 && sAttrData.nFileSizeHigh==0 4660 && sAttrData.nFileSizeLow==0 ){ 4661 attr = INVALID_FILE_ATTRIBUTES; 4662 }else{ 4663 attr = sAttrData.dwFileAttributes; 4664 } 4665 }else{ 4666 if( noRetry ) lastErrno = osGetLastError(); 4667 winLogIoerr(cnt, __LINE__); 4668 if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){ 4669 sqlite3_free(zConverted); 4670 return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", 4671 zFilename); 4672 }else{ 4673 attr = INVALID_FILE_ATTRIBUTES; 4674 } 4675 } 4676 sqlite3_free(zConverted); 4677 switch( flags ){ 4678 case SQLITE_ACCESS_READ: 4679 case SQLITE_ACCESS_EXISTS: 4680 rc = attr!=INVALID_FILE_ATTRIBUTES; 4681 break; 4682 case SQLITE_ACCESS_READWRITE: 4683 rc = attr!=INVALID_FILE_ATTRIBUTES && 4684 (attr & FILE_ATTRIBUTE_READONLY)==0; 4685 break; 4686 default: 4687 assert(!"Invalid flags argument"); 4688 } 4689 *pResOut = rc; 4690 OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", 4691 zFilename, pResOut, *pResOut)); 4692 return SQLITE_OK; 4693 } 4694 4695 /* 4696 ** Returns non-zero if the specified path name starts with the "long path" 4697 ** prefix. 4698 */ 4699 static BOOL winIsLongPathPrefix( 4700 const char *zPathname 4701 ){ 4702 return ( zPathname[0]=='\\' && zPathname[1]=='\\' 4703 && zPathname[2]=='?' && zPathname[3]=='\\' ); 4704 } 4705 4706 /* 4707 ** Returns non-zero if the specified path name starts with a drive letter 4708 ** followed by a colon character. 4709 */ 4710 static BOOL winIsDriveLetterAndColon( 4711 const char *zPathname 4712 ){ 4713 return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ); 4714 } 4715 4716 #ifdef _WIN32 4717 /* 4718 ** Returns non-zero if the specified path name should be used verbatim. If 4719 ** non-zero is returned from this function, the calling function must simply 4720 ** use the provided path name verbatim -OR- resolve it into a full path name 4721 ** using the GetFullPathName Win32 API function (if available). 4722 */ 4723 static BOOL winIsVerbatimPathname( 4724 const char *zPathname 4725 ){ 4726 /* 4727 ** If the path name starts with a forward slash or a backslash, it is either 4728 ** a legal UNC name, a volume relative path, or an absolute path name in the 4729 ** "Unix" format on Windows. There is no easy way to differentiate between 4730 ** the final two cases; therefore, we return the safer return value of TRUE 4731 ** so that callers of this function will simply use it verbatim. 4732 */ 4733 if ( winIsDirSep(zPathname[0]) ){ 4734 return TRUE; 4735 } 4736 4737 /* 4738 ** If the path name starts with a letter and a colon it is either a volume 4739 ** relative path or an absolute path. Callers of this function must not 4740 ** attempt to treat it as a relative path name (i.e. they should simply use 4741 ** it verbatim). 4742 */ 4743 if ( winIsDriveLetterAndColon(zPathname) ){ 4744 return TRUE; 4745 } 4746 4747 /* 4748 ** If we get to this point, the path name should almost certainly be a purely 4749 ** relative one (i.e. not a UNC name, not absolute, and not volume relative). 4750 */ 4751 return FALSE; 4752 } 4753 #endif /* _WIN32 */ 4754 4755 #ifdef __CYGWIN__ 4756 /* 4757 ** Simplify a filename into its canonical form 4758 ** by making the following changes: 4759 ** 4760 ** * convert any '/' to '\' (win32) or reverse (Cygwin) 4761 ** * removing any trailing and duplicate / (except for UNC paths) 4762 ** * convert /./ into just / 4763 ** 4764 ** Changes are made in-place. Return the new name length. 4765 ** 4766 ** The original filename is in z[0..]. If the path is shortened, 4767 ** no-longer used bytes will be written by '\0'. 4768 */ 4769 static void winSimplifyName(char *z){ 4770 int i, j; 4771 for(i=j=0; z[i]; ++i){ 4772 if( winIsDirSep(z[i]) ){ 4773 #if !defined(SQLITE_TEST) 4774 /* Some test-cases assume that "./foo" and "foo" are different */ 4775 if( z[i+1]=='.' && winIsDirSep(z[i+2]) ){ 4776 ++i; 4777 continue; 4778 } 4779 #endif 4780 if( !z[i+1] || (winIsDirSep(z[i+1]) && (i!=0)) ){ 4781 continue; 4782 } 4783 z[j++] = osGetenv?'/':'\\'; 4784 }else{ 4785 z[j++] = z[i]; 4786 } 4787 } 4788 while(jnOut ){ 4808 /* SQLite assumes that xFullPathname() nul-terminates the output buffer 4809 ** even if it returns an error. */ 4810 zOut[iOff] = '\0'; 4811 return SQLITE_CANTOPEN_BKPT; 4812 } 4813 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath); 4814 return SQLITE_OK; 4815 } 4816 #endif /* __CYGWIN__ */ 4817 4818 /* 4819 ** Turn a relative pathname into a full pathname. Write the full 4820 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname 4821 ** bytes in size. 4822 */ 4823 static int winFullPathnameNoMutex( 4824 sqlite3_vfs *pVfs, /* Pointer to vfs object */ 4825 const char *zRelative, /* Possibly relative input path */ 4826 int nFull, /* Size of output buffer in bytes */ 4827 char *zFull /* Output buffer */ 4828 ){ 4829 int nByte; 4830 LPWSTR zConverted; 4831 char *zOut; 4832 4833 /* If this path name begins with "/X:" or "\\?\", where "X" is any 4834 ** alphabetic character, discard the initial "/" from the pathname. 4835 */ 4836 if( zRelative[0]=='/' && (winIsDriveLetterAndColon(zRelative+1) 4837 || winIsLongPathPrefix(zRelative+1)) ){ 4838 zRelative++; 4839 } 4840 4841 SimulateIOError( return SQLITE_ERROR ); 4842 4843 #ifdef __CYGWIN__ 4844 if( osGetcwd ){ 4845 zFull[nFull-1] = '\0'; 4846 if( !winIsDriveLetterAndColon(zRelative) || !winIsDirSep(zRelative[2]) ){ 4847 int rc = SQLITE_OK; 4848 int nLink = 1; /* Number of symbolic links followed so far */ 4849 const char *zIn = zRelative; /* Input path for each iteration of loop */ 4850 char *zDel = 0; 4851 struct stat buf; 4852 4853 UNUSED_PARAMETER(pVfs); 4854 4855 do { 4856 /* Call lstat() on path zIn. Set bLink to true if the path 4857 ** is a symbolic link, or false otherwise. */ 4858 int bLink = 0; 4859 if( osLstat && osReadlink ) { 4860 if( osLstat(zIn, &buf)!=0 ){ 4861 int myErrno = osErrno; 4862 if( myErrno!=ENOENT ){ 4863 rc = winLogError(SQLITE_CANTOPEN_BKPT, (DWORD)myErrno, 4864 "lstat", zIn); 4865 } 4866 }else{ 4867 bLink = ((buf.st_mode & `0170000`) == `0120000`); 4868 } 4869 4870 if( bLink ){ 4871 if( zDel==0 ){ 4872 zDel = sqlite3MallocZero(nFull); 4873 if( zDel==0 ) rc = SQLITE_NOMEM; 4874 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){ 4875 rc = SQLITE_CANTOPEN_BKPT; 4876 } 4877 4878 if( rc==SQLITE_OK ){ 4879 nByte = osReadlink(zIn, zDel, nFull-1); 4880 if( nByte ==(DWORD)-1 ){ 4881 rc = winLogError(SQLITE_CANTOPEN_BKPT, (DWORD)osErrno, 4882 "readlink", zIn); 4883 }else{ 4884 if( zDel[0]!='/' ){ 4885 int n; 4886 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--); 4887 if( nByte+n+1>nFull ){ 4888 rc = SQLITE_CANTOPEN_BKPT; 4889 }else{ 4890 memmove(&zDel[n], zDel, nByte+1); 4891 memcpy(zDel, zIn, n); 4892 nByte += n; 4893 } 4894 } 4895 zDel[nByte] = '\0'; 4896 } 4897 } 4898 4899 zIn = zDel; 4900 } 4901 } 4902 4903 assert( rc!=SQLITE_OK || zIn!=zFull || zIn[0]=='/' ); 4904 if( rc==SQLITE_OK && zIn!=zFull ){ 4905 rc = mkFullPathname(zIn, zFull, nFull); 4906 } 4907 if( bLink==0 ) break; 4908 zIn = zFull; 4909 }while( rc==SQLITE_OK ); 4910 4911 sqlite3_free(zDel); 4912 winSimplifyName(zFull); 4913 return rc; 4914 } 4915 } 4916 #endif /* __CYGWIN__ */ 4917 4918 #if defined(_WIN32) 4919 /* It's odd to simulate an io-error here, but really this is just 4920 ** using the io-error infrastructure to test that SQLite handles this 4921 ** function failing. This function could fail if, for example, the 4922 ** current working directory has been unlinked. 4923 */ 4924 SimulateIOError( return SQLITE_ERROR ); 4925 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ 4926 /* 4927 ** NOTE: We are dealing with a relative path name and the data 4928 ** directory has been set. Therefore, use it as the basis 4929 ** for converting the relative path name to an absolute 4930 ** one by prepending the data directory and a backslash. 4931 */ 4932 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", 4933 sqlite3_data_directory, winGetDirSep(), zRelative); 4934 return SQLITE_OK; 4935 } 4936 #endif 4937 zConverted = winConvertFromUtf8Filename(zRelative); 4938 if( zConverted==0 ){ 4939 return SQLITE_IOERR_NOMEM_BKPT; 4940 } 4941 { 4942 LPWSTR zTemp; 4943 nByte = osGetFullPathNameW(zConverted, 0, 0, 0); 4944 if( nByte==0 ){ 4945 sqlite3_free(zConverted); 4946 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), 4947 "winFullPathname1", zRelative); 4948 } 4949 nByte += 3; 4950 zTemp = sqlite3MallocZero( (u64)nByte*sizeof(WCHAR) ); 4951 if( zTemp==0 ){ 4952 sqlite3_free(zConverted); 4953 return SQLITE_IOERR_NOMEM_BKPT; 4954 } 4955 nByte = osGetFullPathNameW(zConverted, nByte, zTemp, 0); 4956 if( nByte==0 ){ 4957 sqlite3_free(zConverted); 4958 sqlite3_free(zTemp); 4959 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), 4960 "winFullPathname2", zRelative); 4961 } 4962 sqlite3_free(zConverted); 4963 zOut = winUnicodeToUtf8(zTemp); 4964 sqlite3_free(zTemp); 4965 } 4966 if( zOut ){ 4967 #ifdef __CYGWIN__ 4968 if( memcmp(zOut, "\\\\?\\", 4) ){ 4969 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut); 4970 }else if( memcmp(zOut+4, "UNC\\", 4) ){ 4971 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut+4); 4972 }else{ 4973 char *p = zOut+6; 4974 *p = '\\'; 4975 if( osGetcwd ){ 4976 /* On Cygwin, UNC paths use forward slashes */ 4977 while( *p ){ 4978 if( *p=='\\' ) *p = '/'; 4979 ++p; 4980 } 4981 } 4982 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut+6); 4983 } 4984 #else 4985 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut); 4986 #endif /* __CYGWIN__ */ 4987 sqlite3_free(zOut); 4988 return SQLITE_OK; 4989 }else{ 4990 return SQLITE_IOERR_NOMEM_BKPT; 4991 } 4992 } 4993 static int winFullPathname( 4994 sqlite3_vfs *pVfs, /* Pointer to vfs object */ 4995 const char *zRelative, /* Possibly relative input path */ 4996 int nFull, /* Size of output buffer in bytes */ 4997 char *zFull /* Output buffer */ 4998 ){ 4999 int rc; 5000 MUTEX_LOGIC( sqlite3_mutex *pMutex; ) 5001 MUTEX_LOGIC( pMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR); ) 5002 sqlite3_mutex_enter(pMutex); 5003 rc = winFullPathnameNoMutex(pVfs, zRelative, nFull, zFull); 5004 sqlite3_mutex_leave(pMutex); 5005 return rc; 5006 } 5007 5008 #ifndef SQLITE_OMIT_LOAD_EXTENSION 5009 /* 5010 ** Interfaces for opening a shared library, finding entry points 5011 ** within the shared library, and closing the shared library. 5012 */ 5013 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){ 5014 HANDLE h = 0; 5015 LPWSTR zConverted = winConvertFromUtf8Filename(zFilename); 5016 UNUSED_PARAMETER(pVfs); 5017 if( zConverted==0 ){ 5018 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); 5019 return 0; 5020 } 5021 h = osLoadLibraryW ? osLoadLibraryW(zConverted) : 0; 5022 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h)); 5023 sqlite3_free(zConverted); 5024 return (void*)h; 5025 } 5026 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){ 5027 UNUSED_PARAMETER(pVfs); 5028 winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut); 5029 } 5030 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){ 5031 FARPROC proc = 0; 5032 UNUSED_PARAMETER(pVfs); 5033 proc = osGetProcAddressA ? osGetProcAddressA((HANDLE)pH, zSym) : 0; 5034 OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n", 5035 (void*)pH, zSym, (void*)proc)); 5036 return (void(*)(void))proc; 5037 } 5038 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){ 5039 UNUSED_PARAMETER(pVfs); 5040 if( osFreeLibrary!=0 ) osFreeLibrary((HANDLE)pHandle); 5041 OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle)); 5042 } 5043 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ 5044 #define winDlOpen 0 5045 #define winDlError 0 5046 #define winDlSym 0 5047 #define winDlClose 0 5048 #endif 5049 5050 /* State information for the randomness gatherer. */ 5051 typedef struct EntropyGatherer EntropyGatherer; 5052 struct EntropyGatherer { 5053 unsigned char *a; /* Gather entropy into this buffer */ 5054 int na; /* Size of a[] in bytes */ 5055 int i; /* XOR next input into a[i] */ 5056 int nXor; /* Number of XOR operations done */ 5057 }; 5058 5059 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) 5060 /* Mix sz bytes of entropy into p. */ 5061 static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){ 5062 int j, k; 5063 for(j=0, k=p->i; ja[k++] ^= x[j]; 5065 if( k>=p->na ) k = 0; 5066 } 5067 p->i = k; 5068 p->nXor += sz; 5069 } 5070 #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */ 5071 5072 /* 5073 ** Write up to nBuf bytes of randomness into zBuf. 5074 */ 5075 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ 5076 #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) 5077 UNUSED_PARAMETER(pVfs); 5078 memset(zBuf, 0, nBuf); 5079 return nBuf; 5080 #else 5081 EntropyGatherer e; 5082 UNUSED_PARAMETER(pVfs); 5083 memset(zBuf, 0, nBuf); 5084 e.a = (unsigned char*)zBuf; 5085 e.na = nBuf; 5086 e.nXor = 0; 5087 e.i = 0; 5088 { 5089 FILETIME x; 5090 osGetSystemTimeAsFileTime(&x); 5091 xorMemory(&e, (unsigned char*)&x, sizeof(x)); 5092 } 5093 { 5094 DWORD pid = osGetCurrentProcessId(); 5095 xorMemory(&e, (unsigned char*)&pid, sizeof(pid)); 5096 } 5097 { 5098 ULONGLONG cnt = osGetTickCount64(); 5099 xorMemory(&e, (unsigned char*)&cnt, sizeof(cnt)); 5100 } 5101 { 5102 LARGE_INTEGER i; 5103 osQueryPerformanceCounter(&i); 5104 xorMemory(&e, (unsigned char*)&i, sizeof(i)); 5105 } 5106 #if SQLITE_WIN32_USE_UUID 5107 #ifdef SQLITE_UWP 5108 # error SQLITE_WIN32_USE_UUID is incompatible with SQLITE_UWP 5109 #endif 5110 { 5111 UUID id; 5112 memset(&id, 0, sizeof(id)); 5113 osUuidCreate(&id); 5114 xorMemory(&e, (unsigned char*)&id, sizeof(id)); 5115 memset(&id, 0, sizeof(UUID)); 5116 osUuidCreateSequential(&id); 5117 xorMemory(&e, (unsigned char*)&id, sizeof(id)); 5118 } 5119 #endif /* SQLITE_WIN32_USE_UUID */ 5120 return e.nXor>nBuf ? nBuf : e.nXor; 5121 #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */ 5122 } 5123 5124 5125 /* 5126 ** Sleep for a little while. Return the amount of time slept. 5127 */ 5128 static int winSleep(sqlite3_vfs *pVfs, int microsec){ 5129 osSleep((microsec+999)/1000); 5130 UNUSED_PARAMETER(pVfs); 5131 return ((microsec+999)/1000)*1000; 5132 } 5133 5134 /* 5135 ** The following variable, if set to a non-zero value, is interpreted as 5136 ** the number of seconds since 1970 and is used to set the result of 5137 ** sqlite3OsCurrentTime() during testing. 5138 */ 5139 #ifdef SQLITE_TEST 5140 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ 5141 #endif 5142 5143 /* 5144 ** Find the current time (in Universal Coordinated Time). Write into *piNow 5145 ** the current time and date as a Julian Day number times 86_400_000. In 5146 ** other words, write into *piNow the number of milliseconds since the Julian 5147 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the 5148 ** proleptic Gregorian calendar. 5149 ** 5150 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date 5151 ** cannot be found. 5152 */ 5153 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){ 5154 /* FILETIME structure is a 64-bit value representing the number of 5155 100-nanosecond intervals since January 1, 1601 (= JD `2305813`.5). 5156 */ 5157 FILETIME ft; 5158 static const sqlite3_int64 winFiletimeEpoch = `23058135`*(sqlite3_int64)`8640000`; 5159 #ifdef SQLITE_TEST 5160 static const sqlite3_int64 unixEpoch = `24405875`*(sqlite3_int64)`8640000`; 5161 #endif 5162 /* 2^32 - to avoid use of LL and warnings in gcc */ 5163 static const sqlite3_int64 max32BitValue = 5164 (sqlite3_int64)`2000000000` + (sqlite3_int64)`2000000000` + 5165 (sqlite3_int64)`294967296`; 5166 5167 osGetSystemTimeAsFileTime( &ft ); 5168 *piNow = winFiletimeEpoch + 5169 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 5170 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000; 5171 5172 #ifdef SQLITE_TEST 5173 if( sqlite3_current_time ){ 5174 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; 5175 } 5176 #endif 5177 UNUSED_PARAMETER(pVfs); 5178 return SQLITE_OK; 5179 } 5180 5181 /* 5182 ** Find the current time (in Universal Coordinated Time). Write the 5183 ** current time and date as a Julian Day number into *prNow and 5184 ** return 0. Return 1 if the time and date cannot be found. 5185 */ 5186 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){ 5187 int rc; 5188 sqlite3_int64 i; 5189 rc = winCurrentTimeInt64(pVfs, &i); 5190 if( !rc ){ 5191 *prNow = i/`86400000`.0; 5192 } 5193 return rc; 5194 } 5195 5196 /* 5197 ** The idea is that this function works like a combination of 5198 ** GetLastError() and FormatMessage() on Windows (or errno and 5199 ** strerror_r() on Unix). After an error is returned by an OS 5200 ** function, SQLite calls this function with zBuf pointing to 5201 ** a buffer of nBuf bytes. The OS layer should populate the 5202 ** buffer with a nul-terminated UTF-8 encoded error message 5203 ** describing the last IO error to have occurred within the calling 5204 ** thread. 5205 ** 5206 ** If the error message is too large for the supplied buffer, 5207 ** it should be truncated. The return value of xGetLastError 5208 ** is zero if the error message fits in the buffer, or non-zero 5209 ** otherwise (if the message was truncated). If non-zero is returned, 5210 ** then it is not necessary to include the nul-terminator character 5211 ** in the output buffer. 5212 ** 5213 ** Not supplying an error message will have no adverse effect 5214 ** on SQLite. It is fine to have an implementation that never 5215 ** returns an error message: 5216 ** 5217 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ 5218 ** assert(zBuf[0]=='\0'); 5219 ** return 0; 5220 ** } 5221 ** 5222 ** However if an error message is supplied, it will be incorporated 5223 ** by sqlite into the error message available to the user using 5224 ** sqlite3_errmsg(), possibly making IO errors easier to debug. 5225 */ 5226 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ 5227 DWORD e = osGetLastError(); 5228 UNUSED_PARAMETER(pVfs); 5229 if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf); 5230 return e; 5231 } 5232 5233 /* 5234 ** Initialize and deinitialize the operating system interface. 5235 */ 5236 int sqlite3_os_init(void){ 5237 static sqlite3_vfs winVfs = { 5238 3, /* iVersion */ 5239 sizeof(winFile), /* szOsFile */ 5240 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ 5241 0, /* pNext */ 5242 "win32", /* zName */ 5243 &winAppData, /* pAppData */ 5244 winOpen, /* xOpen */ 5245 winDelete, /* xDelete */ 5246 winAccess, /* xAccess */ 5247 winFullPathname, /* xFullPathname */ 5248 winDlOpen, /* xDlOpen */ 5249 winDlError, /* xDlError */ 5250 winDlSym, /* xDlSym */ 5251 winDlClose, /* xDlClose */ 5252 winRandomness, /* xRandomness */ 5253 winSleep, /* xSleep */ 5254 winCurrentTime, /* xCurrentTime */ 5255 winGetLastError, /* xGetLastError */ 5256 winCurrentTimeInt64, /* xCurrentTimeInt64 */ 5257 winSetSystemCall, /* xSetSystemCall */ 5258 winGetSystemCall, /* xGetSystemCall */ 5259 winNextSystemCall, /* xNextSystemCall */ 5260 }; 5261 static sqlite3_vfs winLongPathVfs = { 5262 3, /* iVersion */ 5263 sizeof(winFile), /* szOsFile */ 5264 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ 5265 0, /* pNext */ 5266 "win32-longpath", /* zName */ 5267 &winAppData, /* pAppData */ 5268 winOpen, /* xOpen */ 5269 winDelete, /* xDelete */ 5270 winAccess, /* xAccess */ 5271 winFullPathname, /* xFullPathname */ 5272 winDlOpen, /* xDlOpen */ 5273 winDlError, /* xDlError */ 5274 winDlSym, /* xDlSym */ 5275 winDlClose, /* xDlClose */ 5276 winRandomness, /* xRandomness */ 5277 winSleep, /* xSleep */ 5278 winCurrentTime, /* xCurrentTime */ 5279 winGetLastError, /* xGetLastError */ 5280 winCurrentTimeInt64, /* xCurrentTimeInt64 */ 5281 winSetSystemCall, /* xSetSystemCall */ 5282 winGetSystemCall, /* xGetSystemCall */ 5283 winNextSystemCall, /* xNextSystemCall */ 5284 }; 5285 static sqlite3_vfs winNolockVfs = { 5286 3, /* iVersion */ 5287 sizeof(winFile), /* szOsFile */ 5288 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ 5289 0, /* pNext */ 5290 "win32-none", /* zName */ 5291 &winNolockAppData, /* pAppData */ 5292 winOpen, /* xOpen */ 5293 winDelete, /* xDelete */ 5294 winAccess, /* xAccess */ 5295 winFullPathname, /* xFullPathname */ 5296 winDlOpen, /* xDlOpen */ 5297 winDlError, /* xDlError */ 5298 winDlSym, /* xDlSym */ 5299 winDlClose, /* xDlClose */ 5300 winRandomness, /* xRandomness */ 5301 winSleep, /* xSleep */ 5302 winCurrentTime, /* xCurrentTime */ 5303 winGetLastError, /* xGetLastError */ 5304 winCurrentTimeInt64, /* xCurrentTimeInt64 */ 5305 winSetSystemCall, /* xSetSystemCall */ 5306 winGetSystemCall, /* xGetSystemCall */ 5307 winNextSystemCall, /* xNextSystemCall */ 5308 }; 5309 static sqlite3_vfs winLongPathNolockVfs = { 5310 3, /* iVersion */ 5311 sizeof(winFile), /* szOsFile */ 5312 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ 5313 0, /* pNext */ 5314 "win32-longpath-none", /* zName */ 5315 &winNolockAppData, /* pAppData */ 5316 winOpen, /* xOpen */ 5317 winDelete, /* xDelete */ 5318 winAccess, /* xAccess */ 5319 winFullPathname, /* xFullPathname */ 5320 winDlOpen, /* xDlOpen */ 5321 winDlError, /* xDlError */ 5322 winDlSym, /* xDlSym */ 5323 winDlClose, /* xDlClose */ 5324 winRandomness, /* xRandomness */ 5325 winSleep, /* xSleep */ 5326 winCurrentTime, /* xCurrentTime */ 5327 winGetLastError, /* xGetLastError */ 5328 winCurrentTimeInt64, /* xCurrentTimeInt64 */ 5329 winSetSystemCall, /* xSetSystemCall */ 5330 winGetSystemCall, /* xGetSystemCall */ 5331 winNextSystemCall, /* xNextSystemCall */ 5332 }; 5333 5334 /* Double-check that the aSyscall[] array has been constructed 5335 ** correctly. See ticket [`bb3a86e890c8e96ab`] */ 5336 assert( ArraySize(aSyscall)==60 ); 5337 assert( strcmp(aSyscall[0].zName,"AreFileApisANSI")==0 ); 5338 assert( strcmp(aSyscall[8].zName,"FreeLibrary")==0 ); 5339 assert( strcmp(aSyscall[16].zName,"GetSystemInfo")==0 ); 5340 assert( strcmp(aSyscall[24].zName,"HeapReAlloc")==0 ); 5341 assert( strcmp(aSyscall[32].zName,"MapViewOfFileFromApp")==0 ); 5342 assert( strcmp(aSyscall[40].zName,"UnmapViewOfFile")==0 ); 5343 assert( strcmp(aSyscall[48].zName,"UuidCreate")==0 ); 5344 assert( strcmp(aSyscall[56].zName,"lstat")==0 ); 5345 5346 /* get memory map allocation granularity */ 5347 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO)); 5348 osGetSystemInfo(&winSysInfo); 5349 assert( winSysInfo.dwAllocationGranularity>0 ); 5350 assert( winSysInfo.dwPageSize>0 ); 5351 5352 sqlite3_vfs_register(&winVfs, 1); 5353 sqlite3_vfs_register(&winLongPathVfs, 0); 5354 sqlite3_vfs_register(&winNolockVfs, 0); 5355 sqlite3_vfs_register(&winLongPathNolockVfs, 0); 5356 #ifndef SQLITE_OMIT_WAL 5357 winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1); 5358 #endif 5359 5360 return SQLITE_OK; 5361 } 5362 5363 int sqlite3_os_end(void){ 5364 #ifndef SQLITE_OMIT_WAL 5365 winBigLock = 0; 5366 #endif 5367 return SQLITE_OK; 5368 } 5369 5370 #endif /* SQLITE_OS_WIN */