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