downgrade memory unlock failures to info level and fix function name in log output
[sqlcipher.git] / src / os_win.c
blob442c108e9df373ad5340cb9158463ea0acfb21ff
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.
11 ******************************************************************************
13 ** This file contains code that is specific to Windows.
15 #include "sqliteInt.h"
16 #if SQLITE_OS_WIN /* This file is used for Windows only */
19 ** Include code that is common to all os_*.c files
21 #include "os_common.h"
24 ** Include the header file for the Windows VFS.
26 #include "os_win.h"
29 ** Compiling and using WAL mode requires several APIs that are only
30 ** available in Windows platforms based on the NT kernel.
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
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
43 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
44 ** based on the sub-platform)?
46 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
47 # define SQLITE_WIN32_HAS_ANSI
48 #endif
51 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
52 ** based on the sub-platform)?
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
60 ** Make sure at least one set of Win32 APIs is available.
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
68 ** Define the required Windows SDK version constants if they are not
69 ** already available.
71 #ifndef NTDDI_WIN8
72 # define NTDDI_WIN8 0x06020000
73 #endif
75 #ifndef NTDDI_WINBLUE
76 # define NTDDI_WINBLUE 0x06030000
77 #endif
79 #ifndef NTDDI_WINTHRESHOLD
80 # define NTDDI_WINTHRESHOLD 0x06040000
81 #endif
84 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
85 ** target system. GetVersionEx was first deprecated in Win8.1.
87 #ifndef SQLITE_WIN32_GETVERSIONEX
88 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
89 # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
90 # else
91 # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
92 # endif
93 #endif
96 ** Check to see if the CreateFileMappingA function is supported on the
97 ** target system. It is unavailable when using "mincore.lib" on Win10.
98 ** When compiling for Windows 10, always assume "mincore.lib" is in use.
100 #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
101 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
102 # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
103 # else
104 # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
105 # endif
106 #endif
109 ** This constant should already be defined (in the "WinDef.h" SDK file).
111 #ifndef MAX_PATH
112 # define MAX_PATH (260)
113 #endif
116 ** Maximum pathname length (in chars) for Win32. This should normally be
117 ** MAX_PATH.
119 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
120 # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
121 #endif
124 ** This constant should already be defined (in the "WinNT.h" SDK file).
126 #ifndef UNICODE_STRING_MAX_CHARS
127 # define UNICODE_STRING_MAX_CHARS (32767)
128 #endif
131 ** Maximum pathname length (in chars) for WinNT. This should normally be
132 ** UNICODE_STRING_MAX_CHARS.
134 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
135 # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
136 #endif
139 ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
140 ** characters, so we allocate 4 bytes per character assuming worst-case of
141 ** 4-bytes-per-character for UTF8.
143 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
144 # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
145 #endif
148 ** Maximum pathname length (in bytes) for WinNT. This should normally be
149 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
151 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
152 # define SQLITE_WINNT_MAX_PATH_BYTES \
153 (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
154 #endif
157 ** Maximum error message length (in chars) for WinRT.
159 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
160 # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
161 #endif
164 ** Returns non-zero if the character should be treated as a directory
165 ** separator.
167 #ifndef winIsDirSep
168 # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
169 #endif
172 ** This macro is used when a local variable is set to a value that is
173 ** [sometimes] not used by the code (e.g. via conditional compilation).
175 #ifndef UNUSED_VARIABLE_VALUE
176 # define UNUSED_VARIABLE_VALUE(x) (void)(x)
177 #endif
180 ** Returns the character that should be used as the directory separator.
182 #ifndef winGetDirSep
183 # define winGetDirSep() '\\'
184 #endif
187 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
188 ** mode or memory mapped files (e.g. these APIs are available in the Windows
189 ** CE SDK; however, they are not present in the header file)?
191 #if SQLITE_WIN32_FILEMAPPING_API && \
192 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
194 ** Two of the file mapping APIs are different under WinRT. Figure out which
195 ** set we need.
197 #if SQLITE_OS_WINRT
198 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
199 LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
201 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
202 #else
203 #if defined(SQLITE_WIN32_HAS_ANSI)
204 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
205 DWORD, DWORD, DWORD, LPCSTR);
206 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
208 #if defined(SQLITE_WIN32_HAS_WIDE)
209 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
210 DWORD, DWORD, DWORD, LPCWSTR);
211 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
213 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
214 #endif /* SQLITE_OS_WINRT */
217 ** These file mapping APIs are common to both Win32 and WinRT.
220 WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
221 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
222 #endif /* SQLITE_WIN32_FILEMAPPING_API */
225 ** Some Microsoft compilers lack this definition.
227 #ifndef INVALID_FILE_ATTRIBUTES
228 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
229 #endif
231 #ifndef FILE_FLAG_MASK
232 # define FILE_FLAG_MASK (0xFF3C0000)
233 #endif
235 #ifndef FILE_ATTRIBUTE_MASK
236 # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
237 #endif
239 #ifndef SQLITE_OMIT_WAL
240 /* Forward references to structures used for WAL */
241 typedef struct winShm winShm; /* A connection to shared-memory */
242 typedef struct winShmNode winShmNode; /* A region of shared-memory */
243 #endif
246 ** WinCE lacks native support for file locking so we have to fake it
247 ** with some code of our own.
249 #if SQLITE_OS_WINCE
250 typedef struct winceLock {
251 int nReaders; /* Number of reader locks obtained */
252 BOOL bPending; /* Indicates a pending lock has been obtained */
253 BOOL bReserved; /* Indicates a reserved lock has been obtained */
254 BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
255 } winceLock;
256 #endif
259 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
260 ** portability layer.
262 typedef struct winFile winFile;
263 struct winFile {
264 const sqlite3_io_methods *pMethod; /*** Must be first ***/
265 sqlite3_vfs *pVfs; /* The VFS used to open this file */
266 HANDLE h; /* Handle for accessing the file */
267 u8 locktype; /* Type of lock currently held on this file */
268 short sharedLockByte; /* Randomly chosen byte used as a shared lock */
269 u8 ctrlFlags; /* Flags. See WINFILE_* below */
270 DWORD lastErrno; /* The Windows errno from the last I/O error */
271 #ifndef SQLITE_OMIT_WAL
272 winShm *pShm; /* Instance of shared memory on this file */
273 #endif
274 const char *zPath; /* Full pathname of this file */
275 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
276 #if SQLITE_OS_WINCE
277 LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
278 HANDLE hMutex; /* Mutex used to control access to shared lock */
279 HANDLE hShared; /* Shared memory segment used for locking */
280 winceLock local; /* Locks obtained by this instance of winFile */
281 winceLock *shared; /* Global shared lock memory for the file */
282 #endif
283 #if SQLITE_MAX_MMAP_SIZE>0
284 int nFetchOut; /* Number of outstanding xFetch references */
285 HANDLE hMap; /* Handle for accessing memory mapping */
286 void *pMapRegion; /* Area memory mapped */
287 sqlite3_int64 mmapSize; /* Size of mapped region */
288 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
289 #endif
293 ** The winVfsAppData structure is used for the pAppData member for all of the
294 ** Win32 VFS variants.
296 typedef struct winVfsAppData winVfsAppData;
297 struct winVfsAppData {
298 const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
299 void *pAppData; /* The extra pAppData, if any. */
300 BOOL bNoLock; /* Non-zero if locking is disabled. */
304 ** Allowed values for winFile.ctrlFlags
306 #define WINFILE_RDONLY 0x02 /* Connection is read only */
307 #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
308 #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
311 * The size of the buffer used by sqlite3_win32_write_debug().
313 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
314 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
315 #endif
318 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
319 * various Win32 API heap functions instead of our own.
321 #ifdef SQLITE_WIN32_MALLOC
324 * If this is non-zero, an isolated heap will be created by the native Win32
325 * allocator subsystem; otherwise, the default process heap will be used. This
326 * setting has no effect when compiling for WinRT. By default, this is enabled
327 * and an isolated heap will be created to store all allocated data.
329 ******************************************************************************
330 * WARNING: It is important to note that when this setting is non-zero and the
331 * winMemShutdown function is called (e.g. by the sqlite3_shutdown
332 * function), all data that was allocated using the isolated heap will
333 * be freed immediately and any attempt to access any of that freed
334 * data will almost certainly result in an immediate access violation.
335 ******************************************************************************
337 #ifndef SQLITE_WIN32_HEAP_CREATE
338 # define SQLITE_WIN32_HEAP_CREATE (TRUE)
339 #endif
342 * This is the maximum possible initial size of the Win32-specific heap, in
343 * bytes.
345 #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
346 # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
347 #endif
350 * This is the extra space for the initial size of the Win32-specific heap,
351 * in bytes. This value may be zero.
353 #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
354 # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
355 #endif
358 * Calculate the maximum legal cache size, in pages, based on the maximum
359 * possible initial heap size and the default page size, setting aside the
360 * needed extra space.
362 #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
363 # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
364 (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
365 (SQLITE_DEFAULT_PAGE_SIZE))
366 #endif
369 * This is cache size used in the calculation of the initial size of the
370 * Win32-specific heap. It cannot be negative.
372 #ifndef SQLITE_WIN32_CACHE_SIZE
373 # if SQLITE_DEFAULT_CACHE_SIZE>=0
374 # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
375 # else
376 # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
377 # endif
378 #endif
381 * Make sure that the calculated cache size, in pages, cannot cause the
382 * initial size of the Win32-specific heap to exceed the maximum amount
383 * of memory that can be specified in the call to HeapCreate.
385 #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
386 # undef SQLITE_WIN32_CACHE_SIZE
387 # define SQLITE_WIN32_CACHE_SIZE (2000)
388 #endif
391 * The initial size of the Win32-specific heap. This value may be zero.
393 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
394 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
395 (SQLITE_DEFAULT_PAGE_SIZE) + \
396 (SQLITE_WIN32_HEAP_INIT_EXTRA))
397 #endif
400 * The maximum size of the Win32-specific heap. This value may be zero.
402 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
403 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
404 #endif
407 * The extra flags to use in calls to the Win32 heap APIs. This value may be
408 * zero for the default behavior.
410 #ifndef SQLITE_WIN32_HEAP_FLAGS
411 # define SQLITE_WIN32_HEAP_FLAGS (0)
412 #endif
416 ** The winMemData structure stores information required by the Win32-specific
417 ** sqlite3_mem_methods implementation.
419 typedef struct winMemData winMemData;
420 struct winMemData {
421 #ifndef NDEBUG
422 u32 magic1; /* Magic number to detect structure corruption. */
423 #endif
424 HANDLE hHeap; /* The handle to our heap. */
425 BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
426 #ifndef NDEBUG
427 u32 magic2; /* Magic number to detect structure corruption. */
428 #endif
431 #ifndef NDEBUG
432 #define WINMEM_MAGIC1 0x42b2830b
433 #define WINMEM_MAGIC2 0xbd4d7cf4
434 #endif
436 static struct winMemData win_mem_data = {
437 #ifndef NDEBUG
438 WINMEM_MAGIC1,
439 #endif
440 NULL, FALSE
441 #ifndef NDEBUG
442 ,WINMEM_MAGIC2
443 #endif
446 #ifndef NDEBUG
447 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
448 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
449 #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
450 #else
451 #define winMemAssertMagic()
452 #endif
454 #define winMemGetDataPtr() &win_mem_data
455 #define winMemGetHeap() win_mem_data.hHeap
456 #define winMemGetOwned() win_mem_data.bOwned
458 static void *winMemMalloc(int nBytes);
459 static void winMemFree(void *pPrior);
460 static void *winMemRealloc(void *pPrior, int nBytes);
461 static int winMemSize(void *p);
462 static int winMemRoundup(int n);
463 static int winMemInit(void *pAppData);
464 static void winMemShutdown(void *pAppData);
466 const sqlite3_mem_methods *sqlite3MemGetWin32(void);
467 #endif /* SQLITE_WIN32_MALLOC */
470 ** The following variable is (normally) set once and never changes
471 ** thereafter. It records whether the operating system is Win9x
472 ** or WinNT.
474 ** 0: Operating system unknown.
475 ** 1: Operating system is Win9x.
476 ** 2: Operating system is WinNT.
478 ** In order to facilitate testing on a WinNT system, the test fixture
479 ** can manually set this value to 1 to emulate Win98 behavior.
481 #ifdef SQLITE_TEST
482 LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
483 #else
484 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
485 #endif
487 #ifndef SYSCALL
488 # define SYSCALL sqlite3_syscall_ptr
489 #endif
492 ** This function is not available on Windows CE or WinRT.
495 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
496 # define osAreFileApisANSI() 1
497 #endif
500 ** Many system calls are accessed through pointer-to-functions so that
501 ** they may be overridden at runtime to facilitate fault injection during
502 ** testing and sandboxing. The following array holds the names and pointers
503 ** to all overrideable system calls.
505 static struct win_syscall {
506 const char *zName; /* Name of the system call */
507 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
508 sqlite3_syscall_ptr pDefault; /* Default value */
509 } aSyscall[] = {
510 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
511 { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
512 #else
513 { "AreFileApisANSI", (SYSCALL)0, 0 },
514 #endif
516 #ifndef osAreFileApisANSI
517 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
518 #endif
520 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
521 { "CharLowerW", (SYSCALL)CharLowerW, 0 },
522 #else
523 { "CharLowerW", (SYSCALL)0, 0 },
524 #endif
526 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
528 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
529 { "CharUpperW", (SYSCALL)CharUpperW, 0 },
530 #else
531 { "CharUpperW", (SYSCALL)0, 0 },
532 #endif
534 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
536 { "CloseHandle", (SYSCALL)CloseHandle, 0 },
538 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
540 #if defined(SQLITE_WIN32_HAS_ANSI)
541 { "CreateFileA", (SYSCALL)CreateFileA, 0 },
542 #else
543 { "CreateFileA", (SYSCALL)0, 0 },
544 #endif
546 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
547 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
549 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
550 { "CreateFileW", (SYSCALL)CreateFileW, 0 },
551 #else
552 { "CreateFileW", (SYSCALL)0, 0 },
553 #endif
555 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
556 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
558 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
559 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
560 SQLITE_WIN32_CREATEFILEMAPPINGA
561 { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
562 #else
563 { "CreateFileMappingA", (SYSCALL)0, 0 },
564 #endif
566 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
567 DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
569 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
570 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
571 { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
572 #else
573 { "CreateFileMappingW", (SYSCALL)0, 0 },
574 #endif
576 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
577 DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
579 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
580 { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
581 #else
582 { "CreateMutexW", (SYSCALL)0, 0 },
583 #endif
585 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
586 LPCWSTR))aSyscall[8].pCurrent)
588 #if defined(SQLITE_WIN32_HAS_ANSI)
589 { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
590 #else
591 { "DeleteFileA", (SYSCALL)0, 0 },
592 #endif
594 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
596 #if defined(SQLITE_WIN32_HAS_WIDE)
597 { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
598 #else
599 { "DeleteFileW", (SYSCALL)0, 0 },
600 #endif
602 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
604 #if SQLITE_OS_WINCE
605 { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
606 #else
607 { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
608 #endif
610 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
611 LPFILETIME))aSyscall[11].pCurrent)
613 #if SQLITE_OS_WINCE
614 { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
615 #else
616 { "FileTimeToSystemTime", (SYSCALL)0, 0 },
617 #endif
619 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
620 LPSYSTEMTIME))aSyscall[12].pCurrent)
622 { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
624 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
626 #if defined(SQLITE_WIN32_HAS_ANSI)
627 { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
628 #else
629 { "FormatMessageA", (SYSCALL)0, 0 },
630 #endif
632 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
633 DWORD,va_list*))aSyscall[14].pCurrent)
635 #if defined(SQLITE_WIN32_HAS_WIDE)
636 { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
637 #else
638 { "FormatMessageW", (SYSCALL)0, 0 },
639 #endif
641 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
642 DWORD,va_list*))aSyscall[15].pCurrent)
644 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
645 { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
646 #else
647 { "FreeLibrary", (SYSCALL)0, 0 },
648 #endif
650 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
652 { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
654 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
656 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
657 { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
658 #else
659 { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
660 #endif
662 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
663 LPDWORD))aSyscall[18].pCurrent)
665 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
666 { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
667 #else
668 { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
669 #endif
671 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
672 LPDWORD))aSyscall[19].pCurrent)
674 #if defined(SQLITE_WIN32_HAS_ANSI)
675 { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
676 #else
677 { "GetFileAttributesA", (SYSCALL)0, 0 },
678 #endif
680 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
682 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
683 { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
684 #else
685 { "GetFileAttributesW", (SYSCALL)0, 0 },
686 #endif
688 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
690 #if defined(SQLITE_WIN32_HAS_WIDE)
691 { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
692 #else
693 { "GetFileAttributesExW", (SYSCALL)0, 0 },
694 #endif
696 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
697 LPVOID))aSyscall[22].pCurrent)
699 #if !SQLITE_OS_WINRT
700 { "GetFileSize", (SYSCALL)GetFileSize, 0 },
701 #else
702 { "GetFileSize", (SYSCALL)0, 0 },
703 #endif
705 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
707 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
708 { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
709 #else
710 { "GetFullPathNameA", (SYSCALL)0, 0 },
711 #endif
713 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
714 LPSTR*))aSyscall[24].pCurrent)
716 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
717 { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
718 #else
719 { "GetFullPathNameW", (SYSCALL)0, 0 },
720 #endif
722 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
723 LPWSTR*))aSyscall[25].pCurrent)
725 { "GetLastError", (SYSCALL)GetLastError, 0 },
727 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
729 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
730 #if SQLITE_OS_WINCE
731 /* The GetProcAddressA() routine is only available on Windows CE. */
732 { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
733 #else
734 /* All other Windows platforms expect GetProcAddress() to take
735 ** an ANSI string regardless of the _UNICODE setting */
736 { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
737 #endif
738 #else
739 { "GetProcAddressA", (SYSCALL)0, 0 },
740 #endif
742 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
743 LPCSTR))aSyscall[27].pCurrent)
745 #if !SQLITE_OS_WINRT
746 { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
747 #else
748 { "GetSystemInfo", (SYSCALL)0, 0 },
749 #endif
751 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
753 { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
755 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
757 #if !SQLITE_OS_WINCE
758 { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
759 #else
760 { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
761 #endif
763 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
764 LPFILETIME))aSyscall[30].pCurrent)
766 #if defined(SQLITE_WIN32_HAS_ANSI)
767 { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
768 #else
769 { "GetTempPathA", (SYSCALL)0, 0 },
770 #endif
772 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
774 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
775 { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
776 #else
777 { "GetTempPathW", (SYSCALL)0, 0 },
778 #endif
780 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
782 #if !SQLITE_OS_WINRT
783 { "GetTickCount", (SYSCALL)GetTickCount, 0 },
784 #else
785 { "GetTickCount", (SYSCALL)0, 0 },
786 #endif
788 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
790 #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
791 { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
792 #else
793 { "GetVersionExA", (SYSCALL)0, 0 },
794 #endif
796 #define osGetVersionExA ((BOOL(WINAPI*)( \
797 LPOSVERSIONINFOA))aSyscall[34].pCurrent)
799 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
800 SQLITE_WIN32_GETVERSIONEX
801 { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
802 #else
803 { "GetVersionExW", (SYSCALL)0, 0 },
804 #endif
806 #define osGetVersionExW ((BOOL(WINAPI*)( \
807 LPOSVERSIONINFOW))aSyscall[35].pCurrent)
809 { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
811 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
812 SIZE_T))aSyscall[36].pCurrent)
814 #if !SQLITE_OS_WINRT
815 { "HeapCreate", (SYSCALL)HeapCreate, 0 },
816 #else
817 { "HeapCreate", (SYSCALL)0, 0 },
818 #endif
820 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
821 SIZE_T))aSyscall[37].pCurrent)
823 #if !SQLITE_OS_WINRT
824 { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
825 #else
826 { "HeapDestroy", (SYSCALL)0, 0 },
827 #endif
829 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
831 { "HeapFree", (SYSCALL)HeapFree, 0 },
833 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
835 { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
837 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
838 SIZE_T))aSyscall[40].pCurrent)
840 { "HeapSize", (SYSCALL)HeapSize, 0 },
842 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
843 LPCVOID))aSyscall[41].pCurrent)
845 #if !SQLITE_OS_WINRT
846 { "HeapValidate", (SYSCALL)HeapValidate, 0 },
847 #else
848 { "HeapValidate", (SYSCALL)0, 0 },
849 #endif
851 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
852 LPCVOID))aSyscall[42].pCurrent)
854 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
855 { "HeapCompact", (SYSCALL)HeapCompact, 0 },
856 #else
857 { "HeapCompact", (SYSCALL)0, 0 },
858 #endif
860 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
862 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
863 { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
864 #else
865 { "LoadLibraryA", (SYSCALL)0, 0 },
866 #endif
868 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
870 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
871 !defined(SQLITE_OMIT_LOAD_EXTENSION)
872 { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
873 #else
874 { "LoadLibraryW", (SYSCALL)0, 0 },
875 #endif
877 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
879 #if !SQLITE_OS_WINRT
880 { "LocalFree", (SYSCALL)LocalFree, 0 },
881 #else
882 { "LocalFree", (SYSCALL)0, 0 },
883 #endif
885 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
887 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
888 { "LockFile", (SYSCALL)LockFile, 0 },
889 #else
890 { "LockFile", (SYSCALL)0, 0 },
891 #endif
893 #ifndef osLockFile
894 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
895 DWORD))aSyscall[47].pCurrent)
896 #endif
898 #if !SQLITE_OS_WINCE
899 { "LockFileEx", (SYSCALL)LockFileEx, 0 },
900 #else
901 { "LockFileEx", (SYSCALL)0, 0 },
902 #endif
904 #ifndef osLockFileEx
905 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
906 LPOVERLAPPED))aSyscall[48].pCurrent)
907 #endif
909 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
910 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
911 { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
912 #else
913 { "MapViewOfFile", (SYSCALL)0, 0 },
914 #endif
916 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
917 SIZE_T))aSyscall[49].pCurrent)
919 { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
921 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
922 int))aSyscall[50].pCurrent)
924 { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
926 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
927 LARGE_INTEGER*))aSyscall[51].pCurrent)
929 { "ReadFile", (SYSCALL)ReadFile, 0 },
931 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
932 LPOVERLAPPED))aSyscall[52].pCurrent)
934 { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
936 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
938 #if !SQLITE_OS_WINRT
939 { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
940 #else
941 { "SetFilePointer", (SYSCALL)0, 0 },
942 #endif
944 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
945 DWORD))aSyscall[54].pCurrent)
947 #if !SQLITE_OS_WINRT
948 { "Sleep", (SYSCALL)Sleep, 0 },
949 #else
950 { "Sleep", (SYSCALL)0, 0 },
951 #endif
953 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
955 { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
957 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
958 LPFILETIME))aSyscall[56].pCurrent)
960 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
961 { "UnlockFile", (SYSCALL)UnlockFile, 0 },
962 #else
963 { "UnlockFile", (SYSCALL)0, 0 },
964 #endif
966 #ifndef osUnlockFile
967 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
968 DWORD))aSyscall[57].pCurrent)
969 #endif
971 #if !SQLITE_OS_WINCE
972 { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
973 #else
974 { "UnlockFileEx", (SYSCALL)0, 0 },
975 #endif
977 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
978 LPOVERLAPPED))aSyscall[58].pCurrent)
980 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
981 { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
982 #else
983 { "UnmapViewOfFile", (SYSCALL)0, 0 },
984 #endif
986 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
988 { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
990 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
991 LPCSTR,LPBOOL))aSyscall[60].pCurrent)
993 { "WriteFile", (SYSCALL)WriteFile, 0 },
995 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
996 LPOVERLAPPED))aSyscall[61].pCurrent)
998 #if SQLITE_OS_WINRT
999 { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
1000 #else
1001 { "CreateEventExW", (SYSCALL)0, 0 },
1002 #endif
1004 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
1005 DWORD,DWORD))aSyscall[62].pCurrent)
1007 #if !SQLITE_OS_WINRT
1008 { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
1009 #else
1010 { "WaitForSingleObject", (SYSCALL)0, 0 },
1011 #endif
1013 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
1014 DWORD))aSyscall[63].pCurrent)
1016 #if !SQLITE_OS_WINCE
1017 { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
1018 #else
1019 { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
1020 #endif
1022 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
1023 BOOL))aSyscall[64].pCurrent)
1025 #if SQLITE_OS_WINRT
1026 { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
1027 #else
1028 { "SetFilePointerEx", (SYSCALL)0, 0 },
1029 #endif
1031 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
1032 PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
1034 #if SQLITE_OS_WINRT
1035 { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
1036 #else
1037 { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
1038 #endif
1040 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
1041 FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
1043 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
1044 { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
1045 #else
1046 { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
1047 #endif
1049 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
1050 SIZE_T))aSyscall[67].pCurrent)
1052 #if SQLITE_OS_WINRT
1053 { "CreateFile2", (SYSCALL)CreateFile2, 0 },
1054 #else
1055 { "CreateFile2", (SYSCALL)0, 0 },
1056 #endif
1058 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
1059 LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
1061 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
1062 { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
1063 #else
1064 { "LoadPackagedLibrary", (SYSCALL)0, 0 },
1065 #endif
1067 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
1068 DWORD))aSyscall[69].pCurrent)
1070 #if SQLITE_OS_WINRT
1071 { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
1072 #else
1073 { "GetTickCount64", (SYSCALL)0, 0 },
1074 #endif
1076 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
1078 #if SQLITE_OS_WINRT
1079 { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
1080 #else
1081 { "GetNativeSystemInfo", (SYSCALL)0, 0 },
1082 #endif
1084 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
1085 LPSYSTEM_INFO))aSyscall[71].pCurrent)
1087 #if defined(SQLITE_WIN32_HAS_ANSI)
1088 { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
1089 #else
1090 { "OutputDebugStringA", (SYSCALL)0, 0 },
1091 #endif
1093 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
1095 #if defined(SQLITE_WIN32_HAS_WIDE)
1096 { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
1097 #else
1098 { "OutputDebugStringW", (SYSCALL)0, 0 },
1099 #endif
1101 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
1103 { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
1105 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
1107 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
1108 { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
1109 #else
1110 { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
1111 #endif
1113 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
1114 LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
1117 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
1118 ** is really just a macro that uses a compiler intrinsic (e.g. x64).
1119 ** So do not try to make this is into a redefinable interface.
1121 #if defined(InterlockedCompareExchange)
1122 { "InterlockedCompareExchange", (SYSCALL)0, 0 },
1124 #define osInterlockedCompareExchange InterlockedCompareExchange
1125 #else
1126 { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
1128 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
1129 SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
1130 #endif /* defined(InterlockedCompareExchange) */
1132 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
1133 { "UuidCreate", (SYSCALL)UuidCreate, 0 },
1134 #else
1135 { "UuidCreate", (SYSCALL)0, 0 },
1136 #endif
1138 #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
1140 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
1141 { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
1142 #else
1143 { "UuidCreateSequential", (SYSCALL)0, 0 },
1144 #endif
1146 #define osUuidCreateSequential \
1147 ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
1149 #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
1150 { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
1151 #else
1152 { "FlushViewOfFile", (SYSCALL)0, 0 },
1153 #endif
1155 #define osFlushViewOfFile \
1156 ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
1158 }; /* End of the overrideable system calls */
1161 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
1162 ** "win32" VFSes. Return SQLITE_OK upon successfully updating the
1163 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
1164 ** system call named zName.
1166 static int winSetSystemCall(
1167 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
1168 const char *zName, /* Name of system call to override */
1169 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
1171 unsigned int i;
1172 int rc = SQLITE_NOTFOUND;
1174 UNUSED_PARAMETER(pNotUsed);
1175 if( zName==0 ){
1176 /* If no zName is given, restore all system calls to their default
1177 ** settings and return NULL
1179 rc = SQLITE_OK;
1180 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
1181 if( aSyscall[i].pDefault ){
1182 aSyscall[i].pCurrent = aSyscall[i].pDefault;
1185 }else{
1186 /* If zName is specified, operate on only the one system call
1187 ** specified.
1189 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
1190 if( strcmp(zName, aSyscall[i].zName)==0 ){
1191 if( aSyscall[i].pDefault==0 ){
1192 aSyscall[i].pDefault = aSyscall[i].pCurrent;
1194 rc = SQLITE_OK;
1195 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
1196 aSyscall[i].pCurrent = pNewFunc;
1197 break;
1201 return rc;
1205 ** Return the value of a system call. Return NULL if zName is not a
1206 ** recognized system call name. NULL is also returned if the system call
1207 ** is currently undefined.
1209 static sqlite3_syscall_ptr winGetSystemCall(
1210 sqlite3_vfs *pNotUsed,
1211 const char *zName
1213 unsigned int i;
1215 UNUSED_PARAMETER(pNotUsed);
1216 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
1217 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
1219 return 0;
1223 ** Return the name of the first system call after zName. If zName==NULL
1224 ** then return the name of the first system call. Return NULL if zName
1225 ** is the last system call or if zName is not the name of a valid
1226 ** system call.
1228 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
1229 int i = -1;
1231 UNUSED_PARAMETER(p);
1232 if( zName ){
1233 for(i=0; i<ArraySize(aSyscall)-1; i++){
1234 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
1237 for(i++; i<ArraySize(aSyscall); i++){
1238 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
1240 return 0;
1243 #ifdef SQLITE_WIN32_MALLOC
1245 ** If a Win32 native heap has been configured, this function will attempt to
1246 ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
1247 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
1248 ** "pnLargest" argument, if non-zero, will be used to return the size of the
1249 ** largest committed free block in the heap, in bytes.
1251 int sqlite3_win32_compact_heap(LPUINT pnLargest){
1252 int rc = SQLITE_OK;
1253 UINT nLargest = 0;
1254 HANDLE hHeap;
1256 winMemAssertMagic();
1257 hHeap = winMemGetHeap();
1258 assert( hHeap!=0 );
1259 assert( hHeap!=INVALID_HANDLE_VALUE );
1260 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1261 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1262 #endif
1263 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
1264 if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
1265 DWORD lastErrno = osGetLastError();
1266 if( lastErrno==NO_ERROR ){
1267 sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
1268 (void*)hHeap);
1269 rc = SQLITE_NOMEM_BKPT;
1270 }else{
1271 sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
1272 osGetLastError(), (void*)hHeap);
1273 rc = SQLITE_ERROR;
1276 #else
1277 sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
1278 (void*)hHeap);
1279 rc = SQLITE_NOTFOUND;
1280 #endif
1281 if( pnLargest ) *pnLargest = nLargest;
1282 return rc;
1286 ** If a Win32 native heap has been configured, this function will attempt to
1287 ** destroy and recreate it. If the Win32 native heap is not isolated and/or
1288 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
1289 ** be returned and no changes will be made to the Win32 native heap.
1291 int sqlite3_win32_reset_heap(){
1292 int rc;
1293 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */
1294 MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
1295 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
1296 MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
1297 sqlite3_mutex_enter(pMainMtx);
1298 sqlite3_mutex_enter(pMem);
1299 winMemAssertMagic();
1300 if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
1302 ** At this point, there should be no outstanding memory allocations on
1303 ** the heap. Also, since both the main and memsys locks are currently
1304 ** being held by us, no other function (i.e. from another thread) should
1305 ** be able to even access the heap. Attempt to destroy and recreate our
1306 ** isolated Win32 native heap now.
1308 assert( winMemGetHeap()!=NULL );
1309 assert( winMemGetOwned() );
1310 assert( sqlite3_memory_used()==0 );
1311 winMemShutdown(winMemGetDataPtr());
1312 assert( winMemGetHeap()==NULL );
1313 assert( !winMemGetOwned() );
1314 assert( sqlite3_memory_used()==0 );
1315 rc = winMemInit(winMemGetDataPtr());
1316 assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
1317 assert( rc!=SQLITE_OK || winMemGetOwned() );
1318 assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
1319 }else{
1321 ** The Win32 native heap cannot be modified because it may be in use.
1323 rc = SQLITE_BUSY;
1325 sqlite3_mutex_leave(pMem);
1326 sqlite3_mutex_leave(pMainMtx);
1327 return rc;
1329 #endif /* SQLITE_WIN32_MALLOC */
1332 ** This function outputs the specified (ANSI) string to the Win32 debugger
1333 ** (if available).
1336 void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
1337 char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
1338 int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
1339 if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
1340 assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
1341 #ifdef SQLITE_ENABLE_API_ARMOR
1342 if( !zBuf ){
1343 (void)SQLITE_MISUSE_BKPT;
1344 return;
1346 #endif
1347 #if defined(SQLITE_WIN32_HAS_ANSI)
1348 if( nMin>0 ){
1349 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
1350 memcpy(zDbgBuf, zBuf, nMin);
1351 osOutputDebugStringA(zDbgBuf);
1352 }else{
1353 osOutputDebugStringA(zBuf);
1355 #elif defined(SQLITE_WIN32_HAS_WIDE)
1356 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
1357 if ( osMultiByteToWideChar(
1358 osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
1359 nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
1360 return;
1362 osOutputDebugStringW((LPCWSTR)zDbgBuf);
1363 #else
1364 if( nMin>0 ){
1365 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
1366 memcpy(zDbgBuf, zBuf, nMin);
1367 fprintf(stderr, "%s", zDbgBuf);
1368 }else{
1369 fprintf(stderr, "%s", zBuf);
1371 #endif
1375 ** The following routine suspends the current thread for at least ms
1376 ** milliseconds. This is equivalent to the Win32 Sleep() interface.
1378 #if SQLITE_OS_WINRT
1379 static HANDLE sleepObj = NULL;
1380 #endif
1382 void sqlite3_win32_sleep(DWORD milliseconds){
1383 #if SQLITE_OS_WINRT
1384 if ( sleepObj==NULL ){
1385 sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
1386 SYNCHRONIZE);
1388 assert( sleepObj!=NULL );
1389 osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
1390 #else
1391 osSleep(milliseconds);
1392 #endif
1395 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
1396 SQLITE_THREADSAFE>0
1397 DWORD sqlite3Win32Wait(HANDLE hObject){
1398 DWORD rc;
1399 while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
1400 TRUE))==WAIT_IO_COMPLETION ){}
1401 return rc;
1403 #endif
1406 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
1407 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
1409 ** Here is an interesting observation: Win95, Win98, and WinME lack
1410 ** the LockFileEx() API. But we can still statically link against that
1411 ** API as long as we don't call it when running Win95/98/ME. A call to
1412 ** this routine is used to determine if the host is Win95/98/ME or
1413 ** WinNT/2K/XP so that we will know whether or not we can safely call
1414 ** the LockFileEx() API.
1417 #if !SQLITE_WIN32_GETVERSIONEX
1418 # define osIsNT() (1)
1419 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
1420 # define osIsNT() (1)
1421 #elif !defined(SQLITE_WIN32_HAS_WIDE)
1422 # define osIsNT() (0)
1423 #else
1424 # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
1425 #endif
1428 ** This function determines if the machine is running a version of Windows
1429 ** based on the NT kernel.
1431 int sqlite3_win32_is_nt(void){
1432 #if SQLITE_OS_WINRT
1434 ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
1435 ** kernel.
1437 return 1;
1438 #elif SQLITE_WIN32_GETVERSIONEX
1439 if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
1440 #if defined(SQLITE_WIN32_HAS_ANSI)
1441 OSVERSIONINFOA sInfo;
1442 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
1443 osGetVersionExA(&sInfo);
1444 osInterlockedCompareExchange(&sqlite3_os_type,
1445 (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
1446 #elif defined(SQLITE_WIN32_HAS_WIDE)
1447 OSVERSIONINFOW sInfo;
1448 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
1449 osGetVersionExW(&sInfo);
1450 osInterlockedCompareExchange(&sqlite3_os_type,
1451 (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
1452 #endif
1454 return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
1455 #elif SQLITE_TEST
1456 return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
1457 #else
1459 ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
1460 ** deprecated are always assumed to be based on the NT kernel.
1462 return 1;
1463 #endif
1466 #ifdef SQLITE_WIN32_MALLOC
1468 ** Allocate nBytes of memory.
1470 static void *winMemMalloc(int nBytes){
1471 HANDLE hHeap;
1472 void *p;
1474 winMemAssertMagic();
1475 hHeap = winMemGetHeap();
1476 assert( hHeap!=0 );
1477 assert( hHeap!=INVALID_HANDLE_VALUE );
1478 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1479 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1480 #endif
1481 assert( nBytes>=0 );
1482 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
1483 if( !p ){
1484 sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
1485 nBytes, osGetLastError(), (void*)hHeap);
1487 return p;
1491 ** Free memory.
1493 static void winMemFree(void *pPrior){
1494 HANDLE hHeap;
1496 winMemAssertMagic();
1497 hHeap = winMemGetHeap();
1498 assert( hHeap!=0 );
1499 assert( hHeap!=INVALID_HANDLE_VALUE );
1500 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1501 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
1502 #endif
1503 if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
1504 if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
1505 sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
1506 pPrior, osGetLastError(), (void*)hHeap);
1511 ** Change the size of an existing memory allocation
1513 static void *winMemRealloc(void *pPrior, int nBytes){
1514 HANDLE hHeap;
1515 void *p;
1517 winMemAssertMagic();
1518 hHeap = winMemGetHeap();
1519 assert( hHeap!=0 );
1520 assert( hHeap!=INVALID_HANDLE_VALUE );
1521 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1522 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
1523 #endif
1524 assert( nBytes>=0 );
1525 if( !pPrior ){
1526 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
1527 }else{
1528 p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
1530 if( !p ){
1531 sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
1532 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
1533 (void*)hHeap);
1535 return p;
1539 ** Return the size of an outstanding allocation, in bytes.
1541 static int winMemSize(void *p){
1542 HANDLE hHeap;
1543 SIZE_T n;
1545 winMemAssertMagic();
1546 hHeap = winMemGetHeap();
1547 assert( hHeap!=0 );
1548 assert( hHeap!=INVALID_HANDLE_VALUE );
1549 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1550 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
1551 #endif
1552 if( !p ) return 0;
1553 n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
1554 if( n==(SIZE_T)-1 ){
1555 sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
1556 p, osGetLastError(), (void*)hHeap);
1557 return 0;
1559 return (int)n;
1563 ** Round up a request size to the next valid allocation size.
1565 static int winMemRoundup(int n){
1566 return n;
1570 ** Initialize this module.
1572 static int winMemInit(void *pAppData){
1573 winMemData *pWinMemData = (winMemData *)pAppData;
1575 if( !pWinMemData ) return SQLITE_ERROR;
1576 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
1577 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
1579 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
1580 if( !pWinMemData->hHeap ){
1581 DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
1582 DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
1583 if( dwMaximumSize==0 ){
1584 dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
1585 }else if( dwInitialSize>dwMaximumSize ){
1586 dwInitialSize = dwMaximumSize;
1588 pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
1589 dwInitialSize, dwMaximumSize);
1590 if( !pWinMemData->hHeap ){
1591 sqlite3_log(SQLITE_NOMEM,
1592 "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
1593 osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
1594 dwMaximumSize);
1595 return SQLITE_NOMEM_BKPT;
1597 pWinMemData->bOwned = TRUE;
1598 assert( pWinMemData->bOwned );
1600 #else
1601 pWinMemData->hHeap = osGetProcessHeap();
1602 if( !pWinMemData->hHeap ){
1603 sqlite3_log(SQLITE_NOMEM,
1604 "failed to GetProcessHeap (%lu)", osGetLastError());
1605 return SQLITE_NOMEM_BKPT;
1607 pWinMemData->bOwned = FALSE;
1608 assert( !pWinMemData->bOwned );
1609 #endif
1610 assert( pWinMemData->hHeap!=0 );
1611 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
1612 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1613 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1614 #endif
1615 return SQLITE_OK;
1619 ** Deinitialize this module.
1621 static void winMemShutdown(void *pAppData){
1622 winMemData *pWinMemData = (winMemData *)pAppData;
1624 if( !pWinMemData ) return;
1625 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
1626 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
1628 if( pWinMemData->hHeap ){
1629 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
1630 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1631 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1632 #endif
1633 if( pWinMemData->bOwned ){
1634 if( !osHeapDestroy(pWinMemData->hHeap) ){
1635 sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
1636 osGetLastError(), (void*)pWinMemData->hHeap);
1638 pWinMemData->bOwned = FALSE;
1640 pWinMemData->hHeap = NULL;
1645 ** Populate the low-level memory allocation function pointers in
1646 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
1647 ** arguments specify the block of memory to manage.
1649 ** This routine is only called by sqlite3_config(), and therefore
1650 ** is not required to be threadsafe (it is not).
1652 const sqlite3_mem_methods *sqlite3MemGetWin32(void){
1653 static const sqlite3_mem_methods winMemMethods = {
1654 winMemMalloc,
1655 winMemFree,
1656 winMemRealloc,
1657 winMemSize,
1658 winMemRoundup,
1659 winMemInit,
1660 winMemShutdown,
1661 &win_mem_data
1663 return &winMemMethods;
1666 void sqlite3MemSetDefault(void){
1667 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
1669 #endif /* SQLITE_WIN32_MALLOC */
1672 ** Convert a UTF-8 string to Microsoft Unicode.
1674 ** Space to hold the returned string is obtained from sqlite3_malloc().
1676 static LPWSTR winUtf8ToUnicode(const char *zText){
1677 int nChar;
1678 LPWSTR zWideText;
1680 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
1681 if( nChar==0 ){
1682 return 0;
1684 zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
1685 if( zWideText==0 ){
1686 return 0;
1688 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
1689 nChar);
1690 if( nChar==0 ){
1691 sqlite3_free(zWideText);
1692 zWideText = 0;
1694 return zWideText;
1698 ** Convert a Microsoft Unicode string to UTF-8.
1700 ** Space to hold the returned string is obtained from sqlite3_malloc().
1702 static char *winUnicodeToUtf8(LPCWSTR zWideText){
1703 int nByte;
1704 char *zText;
1706 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
1707 if( nByte == 0 ){
1708 return 0;
1710 zText = sqlite3MallocZero( nByte );
1711 if( zText==0 ){
1712 return 0;
1714 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
1715 0, 0);
1716 if( nByte == 0 ){
1717 sqlite3_free(zText);
1718 zText = 0;
1720 return zText;
1724 ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
1725 ** code page.
1727 ** Space to hold the returned string is obtained from sqlite3_malloc().
1729 static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
1730 int nByte;
1731 LPWSTR zMbcsText;
1732 int codepage = useAnsi ? CP_ACP : CP_OEMCP;
1734 nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
1735 0)*sizeof(WCHAR);
1736 if( nByte==0 ){
1737 return 0;
1739 zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
1740 if( zMbcsText==0 ){
1741 return 0;
1743 nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
1744 nByte);
1745 if( nByte==0 ){
1746 sqlite3_free(zMbcsText);
1747 zMbcsText = 0;
1749 return zMbcsText;
1753 ** Convert a Microsoft Unicode string to a multi-byte character string,
1754 ** using the ANSI or OEM code page.
1756 ** Space to hold the returned string is obtained from sqlite3_malloc().
1758 static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
1759 int nByte;
1760 char *zText;
1761 int codepage = useAnsi ? CP_ACP : CP_OEMCP;
1763 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
1764 if( nByte == 0 ){
1765 return 0;
1767 zText = sqlite3MallocZero( nByte );
1768 if( zText==0 ){
1769 return 0;
1771 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
1772 nByte, 0, 0);
1773 if( nByte == 0 ){
1774 sqlite3_free(zText);
1775 zText = 0;
1777 return zText;
1781 ** Convert a multi-byte character string to UTF-8.
1783 ** Space to hold the returned string is obtained from sqlite3_malloc().
1785 static char *winMbcsToUtf8(const char *zText, int useAnsi){
1786 char *zTextUtf8;
1787 LPWSTR zTmpWide;
1789 zTmpWide = winMbcsToUnicode(zText, useAnsi);
1790 if( zTmpWide==0 ){
1791 return 0;
1793 zTextUtf8 = winUnicodeToUtf8(zTmpWide);
1794 sqlite3_free(zTmpWide);
1795 return zTextUtf8;
1799 ** Convert a UTF-8 string to a multi-byte character string.
1801 ** Space to hold the returned string is obtained from sqlite3_malloc().
1803 static char *winUtf8ToMbcs(const char *zText, int useAnsi){
1804 char *zTextMbcs;
1805 LPWSTR zTmpWide;
1807 zTmpWide = winUtf8ToUnicode(zText);
1808 if( zTmpWide==0 ){
1809 return 0;
1811 zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
1812 sqlite3_free(zTmpWide);
1813 return zTextMbcs;
1817 ** This is a public wrapper for the winUtf8ToUnicode() function.
1819 LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
1820 #ifdef SQLITE_ENABLE_API_ARMOR
1821 if( !zText ){
1822 (void)SQLITE_MISUSE_BKPT;
1823 return 0;
1825 #endif
1826 #ifndef SQLITE_OMIT_AUTOINIT
1827 if( sqlite3_initialize() ) return 0;
1828 #endif
1829 return winUtf8ToUnicode(zText);
1833 ** This is a public wrapper for the winUnicodeToUtf8() function.
1835 char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
1836 #ifdef SQLITE_ENABLE_API_ARMOR
1837 if( !zWideText ){
1838 (void)SQLITE_MISUSE_BKPT;
1839 return 0;
1841 #endif
1842 #ifndef SQLITE_OMIT_AUTOINIT
1843 if( sqlite3_initialize() ) return 0;
1844 #endif
1845 return winUnicodeToUtf8(zWideText);
1849 ** This is a public wrapper for the winMbcsToUtf8() function.
1851 char *sqlite3_win32_mbcs_to_utf8(const char *zText){
1852 #ifdef SQLITE_ENABLE_API_ARMOR
1853 if( !zText ){
1854 (void)SQLITE_MISUSE_BKPT;
1855 return 0;
1857 #endif
1858 #ifndef SQLITE_OMIT_AUTOINIT
1859 if( sqlite3_initialize() ) return 0;
1860 #endif
1861 return winMbcsToUtf8(zText, osAreFileApisANSI());
1865 ** This is a public wrapper for the winMbcsToUtf8() function.
1867 char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
1868 #ifdef SQLITE_ENABLE_API_ARMOR
1869 if( !zText ){
1870 (void)SQLITE_MISUSE_BKPT;
1871 return 0;
1873 #endif
1874 #ifndef SQLITE_OMIT_AUTOINIT
1875 if( sqlite3_initialize() ) return 0;
1876 #endif
1877 return winMbcsToUtf8(zText, useAnsi);
1881 ** This is a public wrapper for the winUtf8ToMbcs() function.
1883 char *sqlite3_win32_utf8_to_mbcs(const char *zText){
1884 #ifdef SQLITE_ENABLE_API_ARMOR
1885 if( !zText ){
1886 (void)SQLITE_MISUSE_BKPT;
1887 return 0;
1889 #endif
1890 #ifndef SQLITE_OMIT_AUTOINIT
1891 if( sqlite3_initialize() ) return 0;
1892 #endif
1893 return winUtf8ToMbcs(zText, osAreFileApisANSI());
1897 ** This is a public wrapper for the winUtf8ToMbcs() function.
1899 char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
1900 #ifdef SQLITE_ENABLE_API_ARMOR
1901 if( !zText ){
1902 (void)SQLITE_MISUSE_BKPT;
1903 return 0;
1905 #endif
1906 #ifndef SQLITE_OMIT_AUTOINIT
1907 if( sqlite3_initialize() ) return 0;
1908 #endif
1909 return winUtf8ToMbcs(zText, useAnsi);
1913 ** This function is the same as sqlite3_win32_set_directory (below); however,
1914 ** it accepts a UTF-8 string.
1916 int sqlite3_win32_set_directory8(
1917 unsigned long type, /* Identifier for directory being set or reset */
1918 const char *zValue /* New value for directory being set or reset */
1920 char **ppDirectory = 0;
1921 int rc;
1922 #ifndef SQLITE_OMIT_AUTOINIT
1923 rc = sqlite3_initialize();
1924 if( rc ) return rc;
1925 #endif
1926 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1927 if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
1928 ppDirectory = &sqlite3_data_directory;
1929 }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
1930 ppDirectory = &sqlite3_temp_directory;
1932 assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
1933 || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
1935 assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
1936 if( ppDirectory ){
1937 char *zCopy = 0;
1938 if( zValue && zValue[0] ){
1939 zCopy = sqlite3_mprintf("%s", zValue);
1940 if ( zCopy==0 ){
1941 rc = SQLITE_NOMEM_BKPT;
1942 goto set_directory8_done;
1945 sqlite3_free(*ppDirectory);
1946 *ppDirectory = zCopy;
1947 rc = SQLITE_OK;
1948 }else{
1949 rc = SQLITE_ERROR;
1951 set_directory8_done:
1952 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
1953 return rc;
1957 ** This function is the same as sqlite3_win32_set_directory (below); however,
1958 ** it accepts a UTF-16 string.
1960 int sqlite3_win32_set_directory16(
1961 unsigned long type, /* Identifier for directory being set or reset */
1962 const void *zValue /* New value for directory being set or reset */
1964 int rc;
1965 char *zUtf8 = 0;
1966 if( zValue ){
1967 zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);
1968 if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;
1970 rc = sqlite3_win32_set_directory8(type, zUtf8);
1971 if( zUtf8 ) sqlite3_free(zUtf8);
1972 return rc;
1976 ** This function sets the data directory or the temporary directory based on
1977 ** the provided arguments. The type argument must be 1 in order to set the
1978 ** data directory or 2 in order to set the temporary directory. The zValue
1979 ** argument is the name of the directory to use. The return value will be
1980 ** SQLITE_OK if successful.
1982 int sqlite3_win32_set_directory(
1983 unsigned long type, /* Identifier for directory being set or reset */
1984 void *zValue /* New value for directory being set or reset */
1986 return sqlite3_win32_set_directory16(type, zValue);
1990 ** The return value of winGetLastErrorMsg
1991 ** is zero if the error message fits in the buffer, or non-zero
1992 ** otherwise (if the message was truncated).
1994 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
1995 /* FormatMessage returns 0 on failure. Otherwise it
1996 ** returns the number of TCHARs written to the output
1997 ** buffer, excluding the terminating null char.
1999 DWORD dwLen = 0;
2000 char *zOut = 0;
2002 if( osIsNT() ){
2003 #if SQLITE_OS_WINRT
2004 WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
2005 dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
2006 FORMAT_MESSAGE_IGNORE_INSERTS,
2007 NULL,
2008 lastErrno,
2010 zTempWide,
2011 SQLITE_WIN32_MAX_ERRMSG_CHARS,
2013 #else
2014 LPWSTR zTempWide = NULL;
2015 dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2016 FORMAT_MESSAGE_FROM_SYSTEM |
2017 FORMAT_MESSAGE_IGNORE_INSERTS,
2018 NULL,
2019 lastErrno,
2021 (LPWSTR) &zTempWide,
2024 #endif
2025 if( dwLen > 0 ){
2026 /* allocate a buffer and convert to UTF8 */
2027 sqlite3BeginBenignMalloc();
2028 zOut = winUnicodeToUtf8(zTempWide);
2029 sqlite3EndBenignMalloc();
2030 #if !SQLITE_OS_WINRT
2031 /* free the system buffer allocated by FormatMessage */
2032 osLocalFree(zTempWide);
2033 #endif
2036 #ifdef SQLITE_WIN32_HAS_ANSI
2037 else{
2038 char *zTemp = NULL;
2039 dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2040 FORMAT_MESSAGE_FROM_SYSTEM |
2041 FORMAT_MESSAGE_IGNORE_INSERTS,
2042 NULL,
2043 lastErrno,
2045 (LPSTR) &zTemp,
2048 if( dwLen > 0 ){
2049 /* allocate a buffer and convert to UTF8 */
2050 sqlite3BeginBenignMalloc();
2051 zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
2052 sqlite3EndBenignMalloc();
2053 /* free the system buffer allocated by FormatMessage */
2054 osLocalFree(zTemp);
2057 #endif
2058 if( 0 == dwLen ){
2059 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
2060 }else{
2061 /* copy a maximum of nBuf chars to output buffer */
2062 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
2063 /* free the UTF8 buffer */
2064 sqlite3_free(zOut);
2066 return 0;
2071 ** This function - winLogErrorAtLine() - is only ever called via the macro
2072 ** winLogError().
2074 ** This routine is invoked after an error occurs in an OS function.
2075 ** It logs a message using sqlite3_log() containing the current value of
2076 ** error code and, if possible, the human-readable equivalent from
2077 ** FormatMessage.
2079 ** The first argument passed to the macro should be the error code that
2080 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
2081 ** The two subsequent arguments should be the name of the OS function that
2082 ** failed and the associated file-system path, if any.
2084 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
2085 static int winLogErrorAtLine(
2086 int errcode, /* SQLite error code */
2087 DWORD lastErrno, /* Win32 last error */
2088 const char *zFunc, /* Name of OS function that failed */
2089 const char *zPath, /* File path associated with error */
2090 int iLine /* Source line number where error occurred */
2092 char zMsg[500]; /* Human readable error text */
2093 int i; /* Loop counter */
2095 zMsg[0] = 0;
2096 winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
2097 assert( errcode!=SQLITE_OK );
2098 if( zPath==0 ) zPath = "";
2099 for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
2100 zMsg[i] = 0;
2101 sqlite3_log(errcode,
2102 "os_win.c:%d: (%lu) %s(%s) - %s",
2103 iLine, lastErrno, zFunc, zPath, zMsg
2106 return errcode;
2110 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
2111 ** will be retried following a locking error - probably caused by
2112 ** antivirus software. Also the initial delay before the first retry.
2113 ** The delay increases linearly with each retry.
2115 #ifndef SQLITE_WIN32_IOERR_RETRY
2116 # define SQLITE_WIN32_IOERR_RETRY 10
2117 #endif
2118 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
2119 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
2120 #endif
2121 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
2122 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
2125 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
2126 ** error code obtained via GetLastError() is eligible to be retried. It
2127 ** must accept the error code DWORD as its only argument and should return
2128 ** non-zero if the error code is transient in nature and the operation
2129 ** responsible for generating the original error might succeed upon being
2130 ** retried. The argument to this macro should be a variable.
2132 ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
2133 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
2134 ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
2135 ** may be used to include additional error codes in the set that should
2136 ** result in the failing I/O operation being retried by the caller. If
2137 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
2138 ** identical to those of the "winIoerrCanRetry1" macro.
2140 #if !defined(winIoerrCanRetry1)
2141 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
2142 ((a)==ERROR_SHARING_VIOLATION) || \
2143 ((a)==ERROR_LOCK_VIOLATION) || \
2144 ((a)==ERROR_DEV_NOT_EXIST) || \
2145 ((a)==ERROR_NETNAME_DELETED) || \
2146 ((a)==ERROR_SEM_TIMEOUT) || \
2147 ((a)==ERROR_NETWORK_UNREACHABLE))
2148 #endif
2151 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
2152 ** to see if it should be retried. Return TRUE to retry. Return FALSE
2153 ** to give up with an error.
2155 static int winRetryIoerr(int *pnRetry, DWORD *pError){
2156 DWORD e = osGetLastError();
2157 if( *pnRetry>=winIoerrRetry ){
2158 if( pError ){
2159 *pError = e;
2161 return 0;
2163 if( winIoerrCanRetry1(e) ){
2164 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
2165 ++*pnRetry;
2166 return 1;
2168 #if defined(winIoerrCanRetry2)
2169 else if( winIoerrCanRetry2(e) ){
2170 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
2171 ++*pnRetry;
2172 return 1;
2174 #endif
2175 if( pError ){
2176 *pError = e;
2178 return 0;
2182 ** Log a I/O error retry episode.
2184 static void winLogIoerr(int nRetry, int lineno){
2185 if( nRetry ){
2186 sqlite3_log(SQLITE_NOTICE,
2187 "delayed %dms for lock/sharing conflict at line %d",
2188 winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
2194 ** This #if does not rely on the SQLITE_OS_WINCE define because the
2195 ** corresponding section in "date.c" cannot use it.
2197 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
2198 (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
2200 ** The MSVC CRT on Windows CE may not have a localtime() function.
2201 ** So define a substitute.
2203 # include <time.h>
2204 struct tm *__cdecl localtime(const time_t *t)
2206 static struct tm y;
2207 FILETIME uTm, lTm;
2208 SYSTEMTIME pTm;
2209 sqlite3_int64 t64;
2210 t64 = *t;
2211 t64 = (t64 + 11644473600)*10000000;
2212 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
2213 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
2214 osFileTimeToLocalFileTime(&uTm,&lTm);
2215 osFileTimeToSystemTime(&lTm,&pTm);
2216 y.tm_year = pTm.wYear - 1900;
2217 y.tm_mon = pTm.wMonth - 1;
2218 y.tm_wday = pTm.wDayOfWeek;
2219 y.tm_mday = pTm.wDay;
2220 y.tm_hour = pTm.wHour;
2221 y.tm_min = pTm.wMinute;
2222 y.tm_sec = pTm.wSecond;
2223 return &y;
2225 #endif
2227 #if SQLITE_OS_WINCE
2228 /*************************************************************************
2229 ** This section contains code for WinCE only.
2231 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
2234 ** Acquire a lock on the handle h
2236 static void winceMutexAcquire(HANDLE h){
2237 DWORD dwErr;
2238 do {
2239 dwErr = osWaitForSingleObject(h, INFINITE);
2240 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
2243 ** Release a lock acquired by winceMutexAcquire()
2245 #define winceMutexRelease(h) ReleaseMutex(h)
2248 ** Create the mutex and shared memory used for locking in the file
2249 ** descriptor pFile
2251 static int winceCreateLock(const char *zFilename, winFile *pFile){
2252 LPWSTR zTok;
2253 LPWSTR zName;
2254 DWORD lastErrno;
2255 BOOL bLogged = FALSE;
2256 BOOL bInit = TRUE;
2258 zName = winUtf8ToUnicode(zFilename);
2259 if( zName==0 ){
2260 /* out of memory */
2261 return SQLITE_IOERR_NOMEM_BKPT;
2264 /* Initialize the local lockdata */
2265 memset(&pFile->local, 0, sizeof(pFile->local));
2267 /* Replace the backslashes from the filename and lowercase it
2268 ** to derive a mutex name. */
2269 zTok = osCharLowerW(zName);
2270 for (;*zTok;zTok++){
2271 if (*zTok == '\\') *zTok = '_';
2274 /* Create/open the named mutex */
2275 pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
2276 if (!pFile->hMutex){
2277 pFile->lastErrno = osGetLastError();
2278 sqlite3_free(zName);
2279 return winLogError(SQLITE_IOERR, pFile->lastErrno,
2280 "winceCreateLock1", zFilename);
2283 /* Acquire the mutex before continuing */
2284 winceMutexAcquire(pFile->hMutex);
2286 /* Since the names of named mutexes, semaphores, file mappings etc are
2287 ** case-sensitive, take advantage of that by uppercasing the mutex name
2288 ** and using that as the shared filemapping name.
2290 osCharUpperW(zName);
2291 pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
2292 PAGE_READWRITE, 0, sizeof(winceLock),
2293 zName);
2295 /* Set a flag that indicates we're the first to create the memory so it
2296 ** must be zero-initialized */
2297 lastErrno = osGetLastError();
2298 if (lastErrno == ERROR_ALREADY_EXISTS){
2299 bInit = FALSE;
2302 sqlite3_free(zName);
2304 /* If we succeeded in making the shared memory handle, map it. */
2305 if( pFile->hShared ){
2306 pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
2307 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
2308 /* If mapping failed, close the shared memory handle and erase it */
2309 if( !pFile->shared ){
2310 pFile->lastErrno = osGetLastError();
2311 winLogError(SQLITE_IOERR, pFile->lastErrno,
2312 "winceCreateLock2", zFilename);
2313 bLogged = TRUE;
2314 osCloseHandle(pFile->hShared);
2315 pFile->hShared = NULL;
2319 /* If shared memory could not be created, then close the mutex and fail */
2320 if( pFile->hShared==NULL ){
2321 if( !bLogged ){
2322 pFile->lastErrno = lastErrno;
2323 winLogError(SQLITE_IOERR, pFile->lastErrno,
2324 "winceCreateLock3", zFilename);
2325 bLogged = TRUE;
2327 winceMutexRelease(pFile->hMutex);
2328 osCloseHandle(pFile->hMutex);
2329 pFile->hMutex = NULL;
2330 return SQLITE_IOERR;
2333 /* Initialize the shared memory if we're supposed to */
2334 if( bInit ){
2335 memset(pFile->shared, 0, sizeof(winceLock));
2338 winceMutexRelease(pFile->hMutex);
2339 return SQLITE_OK;
2343 ** Destroy the part of winFile that deals with wince locks
2345 static void winceDestroyLock(winFile *pFile){
2346 if (pFile->hMutex){
2347 /* Acquire the mutex */
2348 winceMutexAcquire(pFile->hMutex);
2350 /* The following blocks should probably assert in debug mode, but they
2351 are to cleanup in case any locks remained open */
2352 if (pFile->local.nReaders){
2353 pFile->shared->nReaders --;
2355 if (pFile->local.bReserved){
2356 pFile->shared->bReserved = FALSE;
2358 if (pFile->local.bPending){
2359 pFile->shared->bPending = FALSE;
2361 if (pFile->local.bExclusive){
2362 pFile->shared->bExclusive = FALSE;
2365 /* De-reference and close our copy of the shared memory handle */
2366 osUnmapViewOfFile(pFile->shared);
2367 osCloseHandle(pFile->hShared);
2369 /* Done with the mutex */
2370 winceMutexRelease(pFile->hMutex);
2371 osCloseHandle(pFile->hMutex);
2372 pFile->hMutex = NULL;
2377 ** An implementation of the LockFile() API of Windows for CE
2379 static BOOL winceLockFile(
2380 LPHANDLE phFile,
2381 DWORD dwFileOffsetLow,
2382 DWORD dwFileOffsetHigh,
2383 DWORD nNumberOfBytesToLockLow,
2384 DWORD nNumberOfBytesToLockHigh
2386 winFile *pFile = HANDLE_TO_WINFILE(phFile);
2387 BOOL bReturn = FALSE;
2389 UNUSED_PARAMETER(dwFileOffsetHigh);
2390 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
2392 if (!pFile->hMutex) return TRUE;
2393 winceMutexAcquire(pFile->hMutex);
2395 /* Wanting an exclusive lock? */
2396 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
2397 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
2398 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
2399 pFile->shared->bExclusive = TRUE;
2400 pFile->local.bExclusive = TRUE;
2401 bReturn = TRUE;
2405 /* Want a read-only lock? */
2406 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
2407 nNumberOfBytesToLockLow == 1){
2408 if (pFile->shared->bExclusive == 0){
2409 pFile->local.nReaders ++;
2410 if (pFile->local.nReaders == 1){
2411 pFile->shared->nReaders ++;
2413 bReturn = TRUE;
2417 /* Want a pending lock? */
2418 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
2419 && nNumberOfBytesToLockLow == 1){
2420 /* If no pending lock has been acquired, then acquire it */
2421 if (pFile->shared->bPending == 0) {
2422 pFile->shared->bPending = TRUE;
2423 pFile->local.bPending = TRUE;
2424 bReturn = TRUE;
2428 /* Want a reserved lock? */
2429 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
2430 && nNumberOfBytesToLockLow == 1){
2431 if (pFile->shared->bReserved == 0) {
2432 pFile->shared->bReserved = TRUE;
2433 pFile->local.bReserved = TRUE;
2434 bReturn = TRUE;
2438 winceMutexRelease(pFile->hMutex);
2439 return bReturn;
2443 ** An implementation of the UnlockFile API of Windows for CE
2445 static BOOL winceUnlockFile(
2446 LPHANDLE phFile,
2447 DWORD dwFileOffsetLow,
2448 DWORD dwFileOffsetHigh,
2449 DWORD nNumberOfBytesToUnlockLow,
2450 DWORD nNumberOfBytesToUnlockHigh
2452 winFile *pFile = HANDLE_TO_WINFILE(phFile);
2453 BOOL bReturn = FALSE;
2455 UNUSED_PARAMETER(dwFileOffsetHigh);
2456 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
2458 if (!pFile->hMutex) return TRUE;
2459 winceMutexAcquire(pFile->hMutex);
2461 /* Releasing a reader lock or an exclusive lock */
2462 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
2463 /* Did we have an exclusive lock? */
2464 if (pFile->local.bExclusive){
2465 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
2466 pFile->local.bExclusive = FALSE;
2467 pFile->shared->bExclusive = FALSE;
2468 bReturn = TRUE;
2471 /* Did we just have a reader lock? */
2472 else if (pFile->local.nReaders){
2473 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
2474 || nNumberOfBytesToUnlockLow == 1);
2475 pFile->local.nReaders --;
2476 if (pFile->local.nReaders == 0)
2478 pFile->shared->nReaders --;
2480 bReturn = TRUE;
2484 /* Releasing a pending lock */
2485 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
2486 && nNumberOfBytesToUnlockLow == 1){
2487 if (pFile->local.bPending){
2488 pFile->local.bPending = FALSE;
2489 pFile->shared->bPending = FALSE;
2490 bReturn = TRUE;
2493 /* Releasing a reserved lock */
2494 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
2495 && nNumberOfBytesToUnlockLow == 1){
2496 if (pFile->local.bReserved) {
2497 pFile->local.bReserved = FALSE;
2498 pFile->shared->bReserved = FALSE;
2499 bReturn = TRUE;
2503 winceMutexRelease(pFile->hMutex);
2504 return bReturn;
2507 ** End of the special code for wince
2508 *****************************************************************************/
2509 #endif /* SQLITE_OS_WINCE */
2512 ** Lock a file region.
2514 static BOOL winLockFile(
2515 LPHANDLE phFile,
2516 DWORD flags,
2517 DWORD offsetLow,
2518 DWORD offsetHigh,
2519 DWORD numBytesLow,
2520 DWORD numBytesHigh
2522 #if SQLITE_OS_WINCE
2524 ** NOTE: Windows CE is handled differently here due its lack of the Win32
2525 ** API LockFile.
2527 return winceLockFile(phFile, offsetLow, offsetHigh,
2528 numBytesLow, numBytesHigh);
2529 #else
2530 if( osIsNT() ){
2531 OVERLAPPED ovlp;
2532 memset(&ovlp, 0, sizeof(OVERLAPPED));
2533 ovlp.Offset = offsetLow;
2534 ovlp.OffsetHigh = offsetHigh;
2535 return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
2536 }else{
2537 return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
2538 numBytesHigh);
2540 #endif
2544 ** Unlock a file region.
2546 static BOOL winUnlockFile(
2547 LPHANDLE phFile,
2548 DWORD offsetLow,
2549 DWORD offsetHigh,
2550 DWORD numBytesLow,
2551 DWORD numBytesHigh
2553 #if SQLITE_OS_WINCE
2555 ** NOTE: Windows CE is handled differently here due its lack of the Win32
2556 ** API UnlockFile.
2558 return winceUnlockFile(phFile, offsetLow, offsetHigh,
2559 numBytesLow, numBytesHigh);
2560 #else
2561 if( osIsNT() ){
2562 OVERLAPPED ovlp;
2563 memset(&ovlp, 0, sizeof(OVERLAPPED));
2564 ovlp.Offset = offsetLow;
2565 ovlp.OffsetHigh = offsetHigh;
2566 return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
2567 }else{
2568 return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
2569 numBytesHigh);
2571 #endif
2574 /*****************************************************************************
2575 ** The next group of routines implement the I/O methods specified
2576 ** by the sqlite3_io_methods object.
2577 ******************************************************************************/
2580 ** Some Microsoft compilers lack this definition.
2582 #ifndef INVALID_SET_FILE_POINTER
2583 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
2584 #endif
2587 ** Move the current position of the file handle passed as the first
2588 ** argument to offset iOffset within the file. If successful, return 0.
2589 ** Otherwise, set pFile->lastErrno and return non-zero.
2591 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
2592 #if !SQLITE_OS_WINRT
2593 LONG upperBits; /* Most sig. 32 bits of new offset */
2594 LONG lowerBits; /* Least sig. 32 bits of new offset */
2595 DWORD dwRet; /* Value returned by SetFilePointer() */
2596 DWORD lastErrno; /* Value returned by GetLastError() */
2598 OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
2600 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
2601 lowerBits = (LONG)(iOffset & 0xffffffff);
2603 /* API oddity: If successful, SetFilePointer() returns a dword
2604 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
2605 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
2606 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
2607 ** whether an error has actually occurred, it is also necessary to call
2608 ** GetLastError().
2610 dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
2612 if( (dwRet==INVALID_SET_FILE_POINTER
2613 && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
2614 pFile->lastErrno = lastErrno;
2615 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
2616 "winSeekFile", pFile->zPath);
2617 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
2618 return 1;
2621 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
2622 return 0;
2623 #else
2625 ** Same as above, except that this implementation works for WinRT.
2628 LARGE_INTEGER x; /* The new offset */
2629 BOOL bRet; /* Value returned by SetFilePointerEx() */
2631 x.QuadPart = iOffset;
2632 bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
2634 if(!bRet){
2635 pFile->lastErrno = osGetLastError();
2636 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
2637 "winSeekFile", pFile->zPath);
2638 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
2639 return 1;
2642 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
2643 return 0;
2644 #endif
2647 #if SQLITE_MAX_MMAP_SIZE>0
2648 /* Forward references to VFS helper methods used for memory mapped files */
2649 static int winMapfile(winFile*, sqlite3_int64);
2650 static int winUnmapfile(winFile*);
2651 #endif
2654 ** Close a file.
2656 ** It is reported that an attempt to close a handle might sometimes
2657 ** fail. This is a very unreasonable result, but Windows is notorious
2658 ** for being unreasonable so I do not doubt that it might happen. If
2659 ** the close fails, we pause for 100 milliseconds and try again. As
2660 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
2661 ** giving up and returning an error.
2663 #define MX_CLOSE_ATTEMPT 3
2664 static int winClose(sqlite3_file *id){
2665 int rc, cnt = 0;
2666 winFile *pFile = (winFile*)id;
2668 assert( id!=0 );
2669 #ifndef SQLITE_OMIT_WAL
2670 assert( pFile->pShm==0 );
2671 #endif
2672 assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
2673 OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
2674 osGetCurrentProcessId(), pFile, pFile->h));
2676 #if SQLITE_MAX_MMAP_SIZE>0
2677 winUnmapfile(pFile);
2678 #endif
2681 rc = osCloseHandle(pFile->h);
2682 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
2683 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
2684 #if SQLITE_OS_WINCE
2685 #define WINCE_DELETION_ATTEMPTS 3
2687 winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
2688 if( pAppData==NULL || !pAppData->bNoLock ){
2689 winceDestroyLock(pFile);
2692 if( pFile->zDeleteOnClose ){
2693 int cnt = 0;
2694 while(
2695 osDeleteFileW(pFile->zDeleteOnClose)==0
2696 && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
2697 && cnt++ < WINCE_DELETION_ATTEMPTS
2699 sqlite3_win32_sleep(100); /* Wait a little before trying again */
2701 sqlite3_free(pFile->zDeleteOnClose);
2703 #endif
2704 if( rc ){
2705 pFile->h = NULL;
2707 OpenCounter(-1);
2708 OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
2709 osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
2710 return rc ? SQLITE_OK
2711 : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
2712 "winClose", pFile->zPath);
2716 ** Read data from a file into a buffer. Return SQLITE_OK if all
2717 ** bytes were read successfully and SQLITE_IOERR if anything goes
2718 ** wrong.
2720 static int winRead(
2721 sqlite3_file *id, /* File to read from */
2722 void *pBuf, /* Write content into this buffer */
2723 int amt, /* Number of bytes to read */
2724 sqlite3_int64 offset /* Begin reading at this offset */
2726 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2727 OVERLAPPED overlapped; /* The offset for ReadFile. */
2728 #endif
2729 winFile *pFile = (winFile*)id; /* file handle */
2730 DWORD nRead; /* Number of bytes actually read from file */
2731 int nRetry = 0; /* Number of retrys */
2733 assert( id!=0 );
2734 assert( amt>0 );
2735 assert( offset>=0 );
2736 SimulateIOError(return SQLITE_IOERR_READ);
2737 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
2738 "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
2739 pFile->h, pBuf, amt, offset, pFile->locktype));
2741 #if SQLITE_MAX_MMAP_SIZE>0
2742 /* Deal with as much of this read request as possible by transferring
2743 ** data from the memory mapping using memcpy(). */
2744 if( offset<pFile->mmapSize ){
2745 if( offset+amt <= pFile->mmapSize ){
2746 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
2747 OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2748 osGetCurrentProcessId(), pFile, pFile->h));
2749 return SQLITE_OK;
2750 }else{
2751 int nCopy = (int)(pFile->mmapSize - offset);
2752 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
2753 pBuf = &((u8 *)pBuf)[nCopy];
2754 amt -= nCopy;
2755 offset += nCopy;
2758 #endif
2760 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
2761 if( winSeekFile(pFile, offset) ){
2762 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
2763 osGetCurrentProcessId(), pFile, pFile->h));
2764 return SQLITE_FULL;
2766 while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
2767 #else
2768 memset(&overlapped, 0, sizeof(OVERLAPPED));
2769 overlapped.Offset = (LONG)(offset & 0xffffffff);
2770 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
2771 while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
2772 osGetLastError()!=ERROR_HANDLE_EOF ){
2773 #endif
2774 DWORD lastErrno;
2775 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
2776 pFile->lastErrno = lastErrno;
2777 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
2778 osGetCurrentProcessId(), pFile, pFile->h));
2779 return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
2780 "winRead", pFile->zPath);
2782 winLogIoerr(nRetry, __LINE__);
2783 if( nRead<(DWORD)amt ){
2784 /* Unread parts of the buffer must be zero-filled */
2785 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
2786 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
2787 osGetCurrentProcessId(), pFile, pFile->h));
2788 return SQLITE_IOERR_SHORT_READ;
2791 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2792 osGetCurrentProcessId(), pFile, pFile->h));
2793 return SQLITE_OK;
2797 ** Write data from a buffer into a file. Return SQLITE_OK on success
2798 ** or some other error code on failure.
2800 static int winWrite(
2801 sqlite3_file *id, /* File to write into */
2802 const void *pBuf, /* The bytes to be written */
2803 int amt, /* Number of bytes to write */
2804 sqlite3_int64 offset /* Offset into the file to begin writing at */
2806 int rc = 0; /* True if error has occurred, else false */
2807 winFile *pFile = (winFile*)id; /* File handle */
2808 int nRetry = 0; /* Number of retries */
2810 assert( amt>0 );
2811 assert( pFile );
2812 SimulateIOError(return SQLITE_IOERR_WRITE);
2813 SimulateDiskfullError(return SQLITE_FULL);
2815 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
2816 "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
2817 pFile->h, pBuf, amt, offset, pFile->locktype));
2819 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
2820 /* Deal with as much of this write request as possible by transferring
2821 ** data from the memory mapping using memcpy(). */
2822 if( offset<pFile->mmapSize ){
2823 if( offset+amt <= pFile->mmapSize ){
2824 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
2825 OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2826 osGetCurrentProcessId(), pFile, pFile->h));
2827 return SQLITE_OK;
2828 }else{
2829 int nCopy = (int)(pFile->mmapSize - offset);
2830 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
2831 pBuf = &((u8 *)pBuf)[nCopy];
2832 amt -= nCopy;
2833 offset += nCopy;
2836 #endif
2838 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
2839 rc = winSeekFile(pFile, offset);
2840 if( rc==0 ){
2841 #else
2843 #endif
2844 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2845 OVERLAPPED overlapped; /* The offset for WriteFile. */
2846 #endif
2847 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
2848 int nRem = amt; /* Number of bytes yet to be written */
2849 DWORD nWrite; /* Bytes written by each WriteFile() call */
2850 DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
2852 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2853 memset(&overlapped, 0, sizeof(OVERLAPPED));
2854 overlapped.Offset = (LONG)(offset & 0xffffffff);
2855 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
2856 #endif
2858 while( nRem>0 ){
2859 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
2860 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
2861 #else
2862 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
2863 #endif
2864 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
2865 break;
2867 assert( nWrite==0 || nWrite<=(DWORD)nRem );
2868 if( nWrite==0 || nWrite>(DWORD)nRem ){
2869 lastErrno = osGetLastError();
2870 break;
2872 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2873 offset += nWrite;
2874 overlapped.Offset = (LONG)(offset & 0xffffffff);
2875 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
2876 #endif
2877 aRem += nWrite;
2878 nRem -= nWrite;
2880 if( nRem>0 ){
2881 pFile->lastErrno = lastErrno;
2882 rc = 1;
2886 if( rc ){
2887 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
2888 || ( pFile->lastErrno==ERROR_DISK_FULL )){
2889 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
2890 osGetCurrentProcessId(), pFile, pFile->h));
2891 return winLogError(SQLITE_FULL, pFile->lastErrno,
2892 "winWrite1", pFile->zPath);
2894 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
2895 osGetCurrentProcessId(), pFile, pFile->h));
2896 return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
2897 "winWrite2", pFile->zPath);
2898 }else{
2899 winLogIoerr(nRetry, __LINE__);
2901 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2902 osGetCurrentProcessId(), pFile, pFile->h));
2903 return SQLITE_OK;
2907 ** Truncate an open file to a specified size
2909 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
2910 winFile *pFile = (winFile*)id; /* File handle object */
2911 int rc = SQLITE_OK; /* Return code for this function */
2912 DWORD lastErrno;
2913 #if SQLITE_MAX_MMAP_SIZE>0
2914 sqlite3_int64 oldMmapSize;
2915 if( pFile->nFetchOut>0 ){
2916 /* File truncation is a no-op if there are outstanding memory mapped
2917 ** pages. This is because truncating the file means temporarily unmapping
2918 ** the file, and that might delete memory out from under existing cursors.
2920 ** This can result in incremental vacuum not truncating the file,
2921 ** if there is an active read cursor when the incremental vacuum occurs.
2922 ** No real harm comes of this - the database file is not corrupted,
2923 ** though some folks might complain that the file is bigger than it
2924 ** needs to be.
2926 ** The only feasible work-around is to defer the truncation until after
2927 ** all references to memory-mapped content are closed. That is doable,
2928 ** but involves adding a few branches in the common write code path which
2929 ** could slow down normal operations slightly. Hence, we have decided for
2930 ** now to simply make transactions a no-op if there are pending reads. We
2931 ** can maybe revisit this decision in the future.
2933 return SQLITE_OK;
2935 #endif
2937 assert( pFile );
2938 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
2939 OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
2940 osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
2942 /* If the user has configured a chunk-size for this file, truncate the
2943 ** file so that it consists of an integer number of chunks (i.e. the
2944 ** actual file size after the operation may be larger than the requested
2945 ** size).
2947 if( pFile->szChunk>0 ){
2948 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
2951 #if SQLITE_MAX_MMAP_SIZE>0
2952 if( pFile->pMapRegion ){
2953 oldMmapSize = pFile->mmapSize;
2954 }else{
2955 oldMmapSize = 0;
2957 winUnmapfile(pFile);
2958 #endif
2960 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
2961 if( winSeekFile(pFile, nByte) ){
2962 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
2963 "winTruncate1", pFile->zPath);
2964 }else if( 0==osSetEndOfFile(pFile->h) &&
2965 ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
2966 pFile->lastErrno = lastErrno;
2967 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
2968 "winTruncate2", pFile->zPath);
2971 #if SQLITE_MAX_MMAP_SIZE>0
2972 if( rc==SQLITE_OK && oldMmapSize>0 ){
2973 if( oldMmapSize>nByte ){
2974 winMapfile(pFile, -1);
2975 }else{
2976 winMapfile(pFile, oldMmapSize);
2979 #endif
2981 OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
2982 osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
2983 return rc;
2986 #ifdef SQLITE_TEST
2988 ** Count the number of fullsyncs and normal syncs. This is used to test
2989 ** that syncs and fullsyncs are occurring at the right times.
2991 int sqlite3_sync_count = 0;
2992 int sqlite3_fullsync_count = 0;
2993 #endif
2996 ** Make sure all writes to a particular file are committed to disk.
2998 static int winSync(sqlite3_file *id, int flags){
2999 #ifndef SQLITE_NO_SYNC
3001 ** Used only when SQLITE_NO_SYNC is not defined.
3003 BOOL rc;
3004 #endif
3005 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
3006 defined(SQLITE_HAVE_OS_TRACE)
3008 ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
3009 ** OSTRACE() macros.
3011 winFile *pFile = (winFile*)id;
3012 #else
3013 UNUSED_PARAMETER(id);
3014 #endif
3016 assert( pFile );
3017 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3018 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3019 || (flags&0x0F)==SQLITE_SYNC_FULL
3022 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3023 ** line is to test that doing so does not cause any problems.
3025 SimulateDiskfullError( return SQLITE_FULL );
3027 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
3028 osGetCurrentProcessId(), pFile, pFile->h, flags,
3029 pFile->locktype));
3031 #ifndef SQLITE_TEST
3032 UNUSED_PARAMETER(flags);
3033 #else
3034 if( (flags&0x0F)==SQLITE_SYNC_FULL ){
3035 sqlite3_fullsync_count++;
3037 sqlite3_sync_count++;
3038 #endif
3040 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3041 ** no-op
3043 #ifdef SQLITE_NO_SYNC
3044 OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
3045 osGetCurrentProcessId(), pFile, pFile->h));
3046 return SQLITE_OK;
3047 #else
3048 #if SQLITE_MAX_MMAP_SIZE>0
3049 if( pFile->pMapRegion ){
3050 if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
3051 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
3052 "rc=SQLITE_OK\n", osGetCurrentProcessId(),
3053 pFile, pFile->pMapRegion));
3054 }else{
3055 pFile->lastErrno = osGetLastError();
3056 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
3057 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
3058 pFile, pFile->pMapRegion));
3059 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
3060 "winSync1", pFile->zPath);
3063 #endif
3064 rc = osFlushFileBuffers(pFile->h);
3065 SimulateIOError( rc=FALSE );
3066 if( rc ){
3067 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
3068 osGetCurrentProcessId(), pFile, pFile->h));
3069 return SQLITE_OK;
3070 }else{
3071 pFile->lastErrno = osGetLastError();
3072 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
3073 osGetCurrentProcessId(), pFile, pFile->h));
3074 return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
3075 "winSync2", pFile->zPath);
3077 #endif
3081 ** Determine the current size of a file in bytes
3083 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
3084 winFile *pFile = (winFile*)id;
3085 int rc = SQLITE_OK;
3087 assert( id!=0 );
3088 assert( pSize!=0 );
3089 SimulateIOError(return SQLITE_IOERR_FSTAT);
3090 OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
3092 #if SQLITE_OS_WINRT
3094 FILE_STANDARD_INFO info;
3095 if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
3096 &info, sizeof(info)) ){
3097 *pSize = info.EndOfFile.QuadPart;
3098 }else{
3099 pFile->lastErrno = osGetLastError();
3100 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
3101 "winFileSize", pFile->zPath);
3104 #else
3106 DWORD upperBits;
3107 DWORD lowerBits;
3108 DWORD lastErrno;
3110 lowerBits = osGetFileSize(pFile->h, &upperBits);
3111 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
3112 if( (lowerBits == INVALID_FILE_SIZE)
3113 && ((lastErrno = osGetLastError())!=NO_ERROR) ){
3114 pFile->lastErrno = lastErrno;
3115 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
3116 "winFileSize", pFile->zPath);
3119 #endif
3120 OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
3121 pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
3122 return rc;
3126 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
3128 #ifndef LOCKFILE_FAIL_IMMEDIATELY
3129 # define LOCKFILE_FAIL_IMMEDIATELY 1
3130 #endif
3132 #ifndef LOCKFILE_EXCLUSIVE_LOCK
3133 # define LOCKFILE_EXCLUSIVE_LOCK 2
3134 #endif
3137 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
3138 ** When the LockFile function was used, it was always expected to fail
3139 ** immediately if the lock could not be obtained. Also, it always expected to
3140 ** obtain an exclusive lock. These flags are used with the LockFileEx function
3141 ** and reflect those expectations; therefore, they should not be changed.
3143 #ifndef SQLITE_LOCKFILE_FLAGS
3144 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
3145 LOCKFILE_EXCLUSIVE_LOCK)
3146 #endif
3149 ** Currently, SQLite never calls the LockFileEx function without wanting the
3150 ** call to fail immediately if the lock cannot be obtained.
3152 #ifndef SQLITE_LOCKFILEEX_FLAGS
3153 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
3154 #endif
3157 ** Acquire a reader lock.
3158 ** Different API routines are called depending on whether or not this
3159 ** is Win9x or WinNT.
3161 static int winGetReadLock(winFile *pFile){
3162 int res;
3163 OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
3164 if( osIsNT() ){
3165 #if SQLITE_OS_WINCE
3167 ** NOTE: Windows CE is handled differently here due its lack of the Win32
3168 ** API LockFileEx.
3170 res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
3171 #else
3172 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
3173 SHARED_SIZE, 0);
3174 #endif
3176 #ifdef SQLITE_WIN32_HAS_ANSI
3177 else{
3178 int lk;
3179 sqlite3_randomness(sizeof(lk), &lk);
3180 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
3181 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
3182 SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
3184 #endif
3185 if( res == 0 ){
3186 pFile->lastErrno = osGetLastError();
3187 /* No need to log a failure to lock */
3189 OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
3190 return res;
3194 ** Undo a readlock
3196 static int winUnlockReadLock(winFile *pFile){
3197 int res;
3198 DWORD lastErrno;
3199 OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
3200 if( osIsNT() ){
3201 res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
3203 #ifdef SQLITE_WIN32_HAS_ANSI
3204 else{
3205 res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
3207 #endif
3208 if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
3209 pFile->lastErrno = lastErrno;
3210 winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
3211 "winUnlockReadLock", pFile->zPath);
3213 OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
3214 return res;
3218 ** Lock the file with the lock specified by parameter locktype - one
3219 ** of the following:
3221 ** (1) SHARED_LOCK
3222 ** (2) RESERVED_LOCK
3223 ** (3) PENDING_LOCK
3224 ** (4) EXCLUSIVE_LOCK
3226 ** Sometimes when requesting one lock state, additional lock states
3227 ** are inserted in between. The locking might fail on one of the later
3228 ** transitions leaving the lock state different from what it started but
3229 ** still short of its goal. The following chart shows the allowed
3230 ** transitions and the inserted intermediate states:
3232 ** UNLOCKED -> SHARED
3233 ** SHARED -> RESERVED
3234 ** SHARED -> (PENDING) -> EXCLUSIVE
3235 ** RESERVED -> (PENDING) -> EXCLUSIVE
3236 ** PENDING -> EXCLUSIVE
3238 ** This routine will only increase a lock. The winUnlock() routine
3239 ** erases all locks at once and returns us immediately to locking level 0.
3240 ** It is not possible to lower the locking level one step at a time. You
3241 ** must go straight to locking level 0.
3243 static int winLock(sqlite3_file *id, int locktype){
3244 int rc = SQLITE_OK; /* Return code from subroutines */
3245 int res = 1; /* Result of a Windows lock call */
3246 int newLocktype; /* Set pFile->locktype to this value before exiting */
3247 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
3248 winFile *pFile = (winFile*)id;
3249 DWORD lastErrno = NO_ERROR;
3251 assert( id!=0 );
3252 OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
3253 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
3255 /* If there is already a lock of this type or more restrictive on the
3256 ** OsFile, do nothing. Don't use the end_lock: exit path, as
3257 ** sqlite3OsEnterMutex() hasn't been called yet.
3259 if( pFile->locktype>=locktype ){
3260 OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
3261 return SQLITE_OK;
3264 /* Do not allow any kind of write-lock on a read-only database
3266 if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
3267 return SQLITE_IOERR_LOCK;
3270 /* Make sure the locking sequence is correct
3272 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
3273 assert( locktype!=PENDING_LOCK );
3274 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
3276 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
3277 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
3278 ** the PENDING_LOCK byte is temporary.
3280 newLocktype = pFile->locktype;
3281 if( pFile->locktype==NO_LOCK
3282 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
3284 int cnt = 3;
3285 while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
3286 PENDING_BYTE, 0, 1, 0))==0 ){
3287 /* Try 3 times to get the pending lock. This is needed to work
3288 ** around problems caused by indexing and/or anti-virus software on
3289 ** Windows systems.
3290 ** If you are using this code as a model for alternative VFSes, do not
3291 ** copy this retry logic. It is a hack intended for Windows only.
3293 lastErrno = osGetLastError();
3294 OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
3295 pFile->h, cnt, res));
3296 if( lastErrno==ERROR_INVALID_HANDLE ){
3297 pFile->lastErrno = lastErrno;
3298 rc = SQLITE_IOERR_LOCK;
3299 OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
3300 pFile->h, cnt, sqlite3ErrName(rc)));
3301 return rc;
3303 if( cnt ) sqlite3_win32_sleep(1);
3305 gotPendingLock = res;
3306 if( !res ){
3307 lastErrno = osGetLastError();
3311 /* Acquire a shared lock
3313 if( locktype==SHARED_LOCK && res ){
3314 assert( pFile->locktype==NO_LOCK );
3315 res = winGetReadLock(pFile);
3316 if( res ){
3317 newLocktype = SHARED_LOCK;
3318 }else{
3319 lastErrno = osGetLastError();
3323 /* Acquire a RESERVED lock
3325 if( locktype==RESERVED_LOCK && res ){
3326 assert( pFile->locktype==SHARED_LOCK );
3327 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
3328 if( res ){
3329 newLocktype = RESERVED_LOCK;
3330 }else{
3331 lastErrno = osGetLastError();
3335 /* Acquire a PENDING lock
3337 if( locktype==EXCLUSIVE_LOCK && res ){
3338 newLocktype = PENDING_LOCK;
3339 gotPendingLock = 0;
3342 /* Acquire an EXCLUSIVE lock
3344 if( locktype==EXCLUSIVE_LOCK && res ){
3345 assert( pFile->locktype>=SHARED_LOCK );
3346 (void)winUnlockReadLock(pFile);
3347 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
3348 SHARED_SIZE, 0);
3349 if( res ){
3350 newLocktype = EXCLUSIVE_LOCK;
3351 }else{
3352 lastErrno = osGetLastError();
3353 winGetReadLock(pFile);
3357 /* If we are holding a PENDING lock that ought to be released, then
3358 ** release it now.
3360 if( gotPendingLock && locktype==SHARED_LOCK ){
3361 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
3364 /* Update the state of the lock has held in the file descriptor then
3365 ** return the appropriate result code.
3367 if( res ){
3368 rc = SQLITE_OK;
3369 }else{
3370 pFile->lastErrno = lastErrno;
3371 rc = SQLITE_BUSY;
3372 OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
3373 pFile->h, locktype, newLocktype));
3375 pFile->locktype = (u8)newLocktype;
3376 OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
3377 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
3378 return rc;
3382 ** This routine checks if there is a RESERVED lock held on the specified
3383 ** file by this or any other process. If such a lock is held, return
3384 ** non-zero, otherwise zero.
3386 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
3387 int res;
3388 winFile *pFile = (winFile*)id;
3390 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
3391 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
3393 assert( id!=0 );
3394 if( pFile->locktype>=RESERVED_LOCK ){
3395 res = 1;
3396 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
3397 }else{
3398 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
3399 if( res ){
3400 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
3402 res = !res;
3403 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
3405 *pResOut = res;
3406 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
3407 pFile->h, pResOut, *pResOut));
3408 return SQLITE_OK;
3412 ** Lower the locking level on file descriptor id to locktype. locktype
3413 ** must be either NO_LOCK or SHARED_LOCK.
3415 ** If the locking level of the file descriptor is already at or below
3416 ** the requested locking level, this routine is a no-op.
3418 ** It is not possible for this routine to fail if the second argument
3419 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
3420 ** might return SQLITE_IOERR;
3422 static int winUnlock(sqlite3_file *id, int locktype){
3423 int type;
3424 winFile *pFile = (winFile*)id;
3425 int rc = SQLITE_OK;
3426 assert( pFile!=0 );
3427 assert( locktype<=SHARED_LOCK );
3428 OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
3429 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
3430 type = pFile->locktype;
3431 if( type>=EXCLUSIVE_LOCK ){
3432 winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
3433 if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
3434 /* This should never happen. We should always be able to
3435 ** reacquire the read lock */
3436 rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
3437 "winUnlock", pFile->zPath);
3440 if( type>=RESERVED_LOCK ){
3441 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
3443 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
3444 winUnlockReadLock(pFile);
3446 if( type>=PENDING_LOCK ){
3447 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
3449 pFile->locktype = (u8)locktype;
3450 OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
3451 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
3452 return rc;
3455 /******************************************************************************
3456 ****************************** No-op Locking **********************************
3458 ** Of the various locking implementations available, this is by far the
3459 ** simplest: locking is ignored. No attempt is made to lock the database
3460 ** file for reading or writing.
3462 ** This locking mode is appropriate for use on read-only databases
3463 ** (ex: databases that are burned into CD-ROM, for example.) It can
3464 ** also be used if the application employs some external mechanism to
3465 ** prevent simultaneous access of the same database by two or more
3466 ** database connections. But there is a serious risk of database
3467 ** corruption if this locking mode is used in situations where multiple
3468 ** database connections are accessing the same database file at the same
3469 ** time and one or more of those connections are writing.
3472 static int winNolockLock(sqlite3_file *id, int locktype){
3473 UNUSED_PARAMETER(id);
3474 UNUSED_PARAMETER(locktype);
3475 return SQLITE_OK;
3478 static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
3479 UNUSED_PARAMETER(id);
3480 UNUSED_PARAMETER(pResOut);
3481 return SQLITE_OK;
3484 static int winNolockUnlock(sqlite3_file *id, int locktype){
3485 UNUSED_PARAMETER(id);
3486 UNUSED_PARAMETER(locktype);
3487 return SQLITE_OK;
3490 /******************* End of the no-op lock implementation *********************
3491 ******************************************************************************/
3494 ** If *pArg is initially negative then this is a query. Set *pArg to
3495 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3497 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3499 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
3500 if( *pArg<0 ){
3501 *pArg = (pFile->ctrlFlags & mask)!=0;
3502 }else if( (*pArg)==0 ){
3503 pFile->ctrlFlags &= ~mask;
3504 }else{
3505 pFile->ctrlFlags |= mask;
3509 /* Forward references to VFS helper methods used for temporary files */
3510 static int winGetTempname(sqlite3_vfs *, char **);
3511 static int winIsDir(const void *);
3512 static BOOL winIsLongPathPrefix(const char *);
3513 static BOOL winIsDriveLetterAndColon(const char *);
3516 ** Control and query of the open file handle.
3518 static int winFileControl(sqlite3_file *id, int op, void *pArg){
3519 winFile *pFile = (winFile*)id;
3520 OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
3521 switch( op ){
3522 case SQLITE_FCNTL_LOCKSTATE: {
3523 *(int*)pArg = pFile->locktype;
3524 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3525 return SQLITE_OK;
3527 case SQLITE_FCNTL_LAST_ERRNO: {
3528 *(int*)pArg = (int)pFile->lastErrno;
3529 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3530 return SQLITE_OK;
3532 case SQLITE_FCNTL_CHUNK_SIZE: {
3533 pFile->szChunk = *(int *)pArg;
3534 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3535 return SQLITE_OK;
3537 case SQLITE_FCNTL_SIZE_HINT: {
3538 if( pFile->szChunk>0 ){
3539 sqlite3_int64 oldSz;
3540 int rc = winFileSize(id, &oldSz);
3541 if( rc==SQLITE_OK ){
3542 sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
3543 if( newSz>oldSz ){
3544 SimulateIOErrorBenign(1);
3545 rc = winTruncate(id, newSz);
3546 SimulateIOErrorBenign(0);
3549 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
3550 return rc;
3552 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3553 return SQLITE_OK;
3555 case SQLITE_FCNTL_PERSIST_WAL: {
3556 winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
3557 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3558 return SQLITE_OK;
3560 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3561 winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
3562 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3563 return SQLITE_OK;
3565 case SQLITE_FCNTL_VFSNAME: {
3566 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3567 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3568 return SQLITE_OK;
3570 case SQLITE_FCNTL_WIN32_AV_RETRY: {
3571 int *a = (int*)pArg;
3572 if( a[0]>0 ){
3573 winIoerrRetry = a[0];
3574 }else{
3575 a[0] = winIoerrRetry;
3577 if( a[1]>0 ){
3578 winIoerrRetryDelay = a[1];
3579 }else{
3580 a[1] = winIoerrRetryDelay;
3582 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3583 return SQLITE_OK;
3585 case SQLITE_FCNTL_WIN32_GET_HANDLE: {
3586 LPHANDLE phFile = (LPHANDLE)pArg;
3587 *phFile = pFile->h;
3588 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3589 return SQLITE_OK;
3591 #ifdef SQLITE_TEST
3592 case SQLITE_FCNTL_WIN32_SET_HANDLE: {
3593 LPHANDLE phFile = (LPHANDLE)pArg;
3594 HANDLE hOldFile = pFile->h;
3595 pFile->h = *phFile;
3596 *phFile = hOldFile;
3597 OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
3598 hOldFile, pFile->h));
3599 return SQLITE_OK;
3601 #endif
3602 case SQLITE_FCNTL_TEMPFILENAME: {
3603 char *zTFile = 0;
3604 int rc = winGetTempname(pFile->pVfs, &zTFile);
3605 if( rc==SQLITE_OK ){
3606 *(char**)pArg = zTFile;
3608 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
3609 return rc;
3611 #if SQLITE_MAX_MMAP_SIZE>0
3612 case SQLITE_FCNTL_MMAP_SIZE: {
3613 i64 newLimit = *(i64*)pArg;
3614 int rc = SQLITE_OK;
3615 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3616 newLimit = sqlite3GlobalConfig.mxMmap;
3619 /* The value of newLimit may be eventually cast to (SIZE_T) and passed
3620 ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
3621 ** least a 64-bit type. */
3622 if( newLimit>0 && sizeof(SIZE_T)<8 ){
3623 newLimit = (newLimit & 0x7FFFFFFF);
3626 *(i64*)pArg = pFile->mmapSizeMax;
3627 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
3628 pFile->mmapSizeMax = newLimit;
3629 if( pFile->mmapSize>0 ){
3630 winUnmapfile(pFile);
3631 rc = winMapfile(pFile, -1);
3634 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
3635 return rc;
3637 #endif
3639 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
3640 return SQLITE_NOTFOUND;
3644 ** Return the sector size in bytes of the underlying block device for
3645 ** the specified file. This is almost always 512 bytes, but may be
3646 ** larger for some devices.
3648 ** SQLite code assumes this function cannot fail. It also assumes that
3649 ** if two files are created in the same file-system directory (i.e.
3650 ** a database and its journal file) that the sector size will be the
3651 ** same for both.
3653 static int winSectorSize(sqlite3_file *id){
3654 (void)id;
3655 return SQLITE_DEFAULT_SECTOR_SIZE;
3659 ** Return a vector of device characteristics.
3661 static int winDeviceCharacteristics(sqlite3_file *id){
3662 winFile *p = (winFile*)id;
3663 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
3664 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
3668 ** Windows will only let you create file view mappings
3669 ** on allocation size granularity boundaries.
3670 ** During sqlite3_os_init() we do a GetSystemInfo()
3671 ** to get the granularity size.
3673 static SYSTEM_INFO winSysInfo;
3675 #ifndef SQLITE_OMIT_WAL
3678 ** Helper functions to obtain and relinquish the global mutex. The
3679 ** global mutex is used to protect the winLockInfo objects used by
3680 ** this file, all of which may be shared by multiple threads.
3682 ** Function winShmMutexHeld() is used to assert() that the global mutex
3683 ** is held when required. This function is only used as part of assert()
3684 ** statements. e.g.
3686 ** winShmEnterMutex()
3687 ** assert( winShmMutexHeld() );
3688 ** winShmLeaveMutex()
3690 static sqlite3_mutex *winBigLock = 0;
3691 static void winShmEnterMutex(void){
3692 sqlite3_mutex_enter(winBigLock);
3694 static void winShmLeaveMutex(void){
3695 sqlite3_mutex_leave(winBigLock);
3697 #ifndef NDEBUG
3698 static int winShmMutexHeld(void) {
3699 return sqlite3_mutex_held(winBigLock);
3701 #endif
3704 ** Object used to represent a single file opened and mmapped to provide
3705 ** shared memory. When multiple threads all reference the same
3706 ** log-summary, each thread has its own winFile object, but they all
3707 ** point to a single instance of this object. In other words, each
3708 ** log-summary is opened only once per process.
3710 ** winShmMutexHeld() must be true when creating or destroying
3711 ** this object or while reading or writing the following fields:
3713 ** nRef
3714 ** pNext
3716 ** The following fields are read-only after the object is created:
3718 ** fid
3719 ** zFilename
3721 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
3722 ** winShmMutexHeld() is true when reading or writing any other field
3723 ** in this structure.
3726 struct winShmNode {
3727 sqlite3_mutex *mutex; /* Mutex to access this object */
3728 char *zFilename; /* Name of the file */
3729 winFile hFile; /* File handle from winOpen */
3731 int szRegion; /* Size of shared-memory regions */
3732 int nRegion; /* Size of array apRegion */
3733 u8 isReadonly; /* True if read-only */
3734 u8 isUnlocked; /* True if no DMS lock held */
3736 struct ShmRegion {
3737 HANDLE hMap; /* File handle from CreateFileMapping */
3738 void *pMap;
3739 } *aRegion;
3740 DWORD lastErrno; /* The Windows errno from the last I/O error */
3742 int nRef; /* Number of winShm objects pointing to this */
3743 winShm *pFirst; /* All winShm objects pointing to this */
3744 winShmNode *pNext; /* Next in list of all winShmNode objects */
3745 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
3746 u8 nextShmId; /* Next available winShm.id value */
3747 #endif
3751 ** A global array of all winShmNode objects.
3753 ** The winShmMutexHeld() must be true while reading or writing this list.
3755 static winShmNode *winShmNodeList = 0;
3758 ** Structure used internally by this VFS to record the state of an
3759 ** open shared memory connection.
3761 ** The following fields are initialized when this object is created and
3762 ** are read-only thereafter:
3764 ** winShm.pShmNode
3765 ** winShm.id
3767 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
3768 ** while accessing any read/write fields.
3770 struct winShm {
3771 winShmNode *pShmNode; /* The underlying winShmNode object */
3772 winShm *pNext; /* Next winShm with the same winShmNode */
3773 u8 hasMutex; /* True if holding the winShmNode mutex */
3774 u16 sharedMask; /* Mask of shared locks held */
3775 u16 exclMask; /* Mask of exclusive locks held */
3776 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
3777 u8 id; /* Id of this connection with its winShmNode */
3778 #endif
3782 ** Constants used for locking
3784 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
3785 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
3788 ** Apply advisory locks for all n bytes beginning at ofst.
3790 #define WINSHM_UNLCK 1
3791 #define WINSHM_RDLCK 2
3792 #define WINSHM_WRLCK 3
3793 static int winShmSystemLock(
3794 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
3795 int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
3796 int ofst, /* Offset to first byte to be locked/unlocked */
3797 int nByte /* Number of bytes to lock or unlock */
3799 int rc = 0; /* Result code form Lock/UnlockFileEx() */
3801 /* Access to the winShmNode object is serialized by the caller */
3802 assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
3804 OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
3805 pFile->hFile.h, lockType, ofst, nByte));
3807 /* Release/Acquire the system-level lock */
3808 if( lockType==WINSHM_UNLCK ){
3809 rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
3810 }else{
3811 /* Initialize the locking parameters */
3812 DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
3813 if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
3814 rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
3817 if( rc!= 0 ){
3818 rc = SQLITE_OK;
3819 }else{
3820 pFile->lastErrno = osGetLastError();
3821 rc = SQLITE_BUSY;
3824 OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
3825 pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
3826 "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
3828 return rc;
3831 /* Forward references to VFS methods */
3832 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
3833 static int winDelete(sqlite3_vfs *,const char*,int);
3836 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
3838 ** This is not a VFS shared-memory method; it is a utility function called
3839 ** by VFS shared-memory methods.
3841 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
3842 winShmNode **pp;
3843 winShmNode *p;
3844 assert( winShmMutexHeld() );
3845 OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
3846 osGetCurrentProcessId(), deleteFlag));
3847 pp = &winShmNodeList;
3848 while( (p = *pp)!=0 ){
3849 if( p->nRef==0 ){
3850 int i;
3851 if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
3852 for(i=0; i<p->nRegion; i++){
3853 BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
3854 OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
3855 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
3856 UNUSED_VARIABLE_VALUE(bRc);
3857 bRc = osCloseHandle(p->aRegion[i].hMap);
3858 OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
3859 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
3860 UNUSED_VARIABLE_VALUE(bRc);
3862 if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
3863 SimulateIOErrorBenign(1);
3864 winClose((sqlite3_file *)&p->hFile);
3865 SimulateIOErrorBenign(0);
3867 if( deleteFlag ){
3868 SimulateIOErrorBenign(1);
3869 sqlite3BeginBenignMalloc();
3870 winDelete(pVfs, p->zFilename, 0);
3871 sqlite3EndBenignMalloc();
3872 SimulateIOErrorBenign(0);
3874 *pp = p->pNext;
3875 sqlite3_free(p->aRegion);
3876 sqlite3_free(p);
3877 }else{
3878 pp = &p->pNext;
3884 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
3885 ** take it now. Return SQLITE_OK if successful, or an SQLite error
3886 ** code otherwise.
3888 ** If the DMS cannot be locked because this is a readonly_shm=1
3889 ** connection and no other process already holds a lock, return
3890 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
3892 static int winLockSharedMemory(winShmNode *pShmNode){
3893 int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
3895 if( rc==SQLITE_OK ){
3896 if( pShmNode->isReadonly ){
3897 pShmNode->isUnlocked = 1;
3898 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
3899 return SQLITE_READONLY_CANTINIT;
3900 }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
3901 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
3902 return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
3903 "winLockSharedMemory", pShmNode->zFilename);
3907 if( rc==SQLITE_OK ){
3908 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
3911 return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
3915 ** Open the shared-memory area associated with database file pDbFd.
3917 ** When opening a new shared-memory file, if no other instances of that
3918 ** file are currently open, in this process or in other processes, then
3919 ** the file must be truncated to zero length or have its header cleared.
3921 static int winOpenSharedMemory(winFile *pDbFd){
3922 struct winShm *p; /* The connection to be opened */
3923 winShmNode *pShmNode = 0; /* The underlying mmapped file */
3924 int rc = SQLITE_OK; /* Result code */
3925 winShmNode *pNew; /* Newly allocated winShmNode */
3926 int nName; /* Size of zName in bytes */
3928 assert( pDbFd->pShm==0 ); /* Not previously opened */
3930 /* Allocate space for the new sqlite3_shm object. Also speculatively
3931 ** allocate space for a new winShmNode and filename.
3933 p = sqlite3MallocZero( sizeof(*p) );
3934 if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
3935 nName = sqlite3Strlen30(pDbFd->zPath);
3936 pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
3937 if( pNew==0 ){
3938 sqlite3_free(p);
3939 return SQLITE_IOERR_NOMEM_BKPT;
3941 pNew->zFilename = (char*)&pNew[1];
3942 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
3943 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
3945 /* Look to see if there is an existing winShmNode that can be used.
3946 ** If no matching winShmNode currently exists, create a new one.
3948 winShmEnterMutex();
3949 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
3950 /* TBD need to come up with better match here. Perhaps
3951 ** use FILE_ID_BOTH_DIR_INFO Structure.
3953 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
3955 if( pShmNode ){
3956 sqlite3_free(pNew);
3957 }else{
3958 int inFlags = SQLITE_OPEN_WAL;
3959 int outFlags = 0;
3961 pShmNode = pNew;
3962 pNew = 0;
3963 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
3964 pShmNode->pNext = winShmNodeList;
3965 winShmNodeList = pShmNode;
3967 if( sqlite3GlobalConfig.bCoreMutex ){
3968 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3969 if( pShmNode->mutex==0 ){
3970 rc = SQLITE_IOERR_NOMEM_BKPT;
3971 goto shm_open_err;
3975 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
3976 inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
3977 }else{
3978 inFlags |= SQLITE_OPEN_READONLY;
3980 rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
3981 (sqlite3_file*)&pShmNode->hFile,
3982 inFlags, &outFlags);
3983 if( rc!=SQLITE_OK ){
3984 rc = winLogError(rc, osGetLastError(), "winOpenShm",
3985 pShmNode->zFilename);
3986 goto shm_open_err;
3988 if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
3990 rc = winLockSharedMemory(pShmNode);
3991 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
3994 /* Make the new connection a child of the winShmNode */
3995 p->pShmNode = pShmNode;
3996 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
3997 p->id = pShmNode->nextShmId++;
3998 #endif
3999 pShmNode->nRef++;
4000 pDbFd->pShm = p;
4001 winShmLeaveMutex();
4003 /* The reference count on pShmNode has already been incremented under
4004 ** the cover of the winShmEnterMutex() mutex and the pointer from the
4005 ** new (struct winShm) object to the pShmNode has been set. All that is
4006 ** left to do is to link the new object into the linked list starting
4007 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4008 ** mutex.
4010 sqlite3_mutex_enter(pShmNode->mutex);
4011 p->pNext = pShmNode->pFirst;
4012 pShmNode->pFirst = p;
4013 sqlite3_mutex_leave(pShmNode->mutex);
4014 return rc;
4016 /* Jump here on any error */
4017 shm_open_err:
4018 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
4019 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
4020 sqlite3_free(p);
4021 sqlite3_free(pNew);
4022 winShmLeaveMutex();
4023 return rc;
4027 ** Close a connection to shared-memory. Delete the underlying
4028 ** storage if deleteFlag is true.
4030 static int winShmUnmap(
4031 sqlite3_file *fd, /* Database holding shared memory */
4032 int deleteFlag /* Delete after closing if true */
4034 winFile *pDbFd; /* Database holding shared-memory */
4035 winShm *p; /* The connection to be closed */
4036 winShmNode *pShmNode; /* The underlying shared-memory file */
4037 winShm **pp; /* For looping over sibling connections */
4039 pDbFd = (winFile*)fd;
4040 p = pDbFd->pShm;
4041 if( p==0 ) return SQLITE_OK;
4042 pShmNode = p->pShmNode;
4044 /* Remove connection p from the set of connections associated
4045 ** with pShmNode */
4046 sqlite3_mutex_enter(pShmNode->mutex);
4047 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4048 *pp = p->pNext;
4050 /* Free the connection p */
4051 sqlite3_free(p);
4052 pDbFd->pShm = 0;
4053 sqlite3_mutex_leave(pShmNode->mutex);
4055 /* If pShmNode->nRef has reached 0, then close the underlying
4056 ** shared-memory file, too */
4057 winShmEnterMutex();
4058 assert( pShmNode->nRef>0 );
4059 pShmNode->nRef--;
4060 if( pShmNode->nRef==0 ){
4061 winShmPurge(pDbFd->pVfs, deleteFlag);
4063 winShmLeaveMutex();
4065 return SQLITE_OK;
4069 ** Change the lock state for a shared-memory segment.
4071 static int winShmLock(
4072 sqlite3_file *fd, /* Database file holding the shared memory */
4073 int ofst, /* First lock to acquire or release */
4074 int n, /* Number of locks to acquire or release */
4075 int flags /* What to do with the lock */
4077 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
4078 winShm *p = pDbFd->pShm; /* The shared memory being locked */
4079 winShm *pX; /* For looping over all siblings */
4080 winShmNode *pShmNode;
4081 int rc = SQLITE_OK; /* Result code */
4082 u16 mask; /* Mask of locks to take or release */
4084 if( p==0 ) return SQLITE_IOERR_SHMLOCK;
4085 pShmNode = p->pShmNode;
4086 if( NEVER(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK;
4088 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
4089 assert( n>=1 );
4090 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4091 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4092 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4093 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4094 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
4096 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
4097 assert( n>1 || mask==(1<<ofst) );
4098 sqlite3_mutex_enter(pShmNode->mutex);
4099 if( flags & SQLITE_SHM_UNLOCK ){
4100 u16 allMask = 0; /* Mask of locks held by siblings */
4102 /* See if any siblings hold this same lock */
4103 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4104 if( pX==p ) continue;
4105 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4106 allMask |= pX->sharedMask;
4109 /* Unlock the system-level locks */
4110 if( (mask & allMask)==0 ){
4111 rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
4112 }else{
4113 rc = SQLITE_OK;
4116 /* Undo the local locks */
4117 if( rc==SQLITE_OK ){
4118 p->exclMask &= ~mask;
4119 p->sharedMask &= ~mask;
4121 }else if( flags & SQLITE_SHM_SHARED ){
4122 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4124 /* Find out which shared locks are already held by sibling connections.
4125 ** If any sibling already holds an exclusive lock, go ahead and return
4126 ** SQLITE_BUSY.
4128 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4129 if( (pX->exclMask & mask)!=0 ){
4130 rc = SQLITE_BUSY;
4131 break;
4133 allShared |= pX->sharedMask;
4136 /* Get shared locks at the system level, if necessary */
4137 if( rc==SQLITE_OK ){
4138 if( (allShared & mask)==0 ){
4139 rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
4140 }else{
4141 rc = SQLITE_OK;
4145 /* Get the local shared locks */
4146 if( rc==SQLITE_OK ){
4147 p->sharedMask |= mask;
4149 }else{
4150 /* Make sure no sibling connections hold locks that will block this
4151 ** lock. If any do, return SQLITE_BUSY right away.
4153 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4154 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4155 rc = SQLITE_BUSY;
4156 break;
4160 /* Get the exclusive locks at the system level. Then if successful
4161 ** also mark the local connection as being locked.
4163 if( rc==SQLITE_OK ){
4164 rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
4165 if( rc==SQLITE_OK ){
4166 assert( (p->sharedMask & mask)==0 );
4167 p->exclMask |= mask;
4171 sqlite3_mutex_leave(pShmNode->mutex);
4172 OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
4173 osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
4174 sqlite3ErrName(rc)));
4175 return rc;
4179 ** Implement a memory barrier or memory fence on shared memory.
4181 ** All loads and stores begun before the barrier must complete before
4182 ** any load or store begun after the barrier.
4184 static void winShmBarrier(
4185 sqlite3_file *fd /* Database holding the shared memory */
4187 UNUSED_PARAMETER(fd);
4188 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4189 winShmEnterMutex(); /* Also mutex, for redundancy */
4190 winShmLeaveMutex();
4194 ** This function is called to obtain a pointer to region iRegion of the
4195 ** shared-memory associated with the database file fd. Shared-memory regions
4196 ** are numbered starting from zero. Each shared-memory region is szRegion
4197 ** bytes in size.
4199 ** If an error occurs, an error code is returned and *pp is set to NULL.
4201 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
4202 ** region has not been allocated (by any client, including one running in a
4203 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4204 ** isWrite is non-zero and the requested shared-memory region has not yet
4205 ** been allocated, it is allocated by this function.
4207 ** If the shared-memory region has already been allocated or is allocated by
4208 ** this call as described above, then it is mapped into this processes
4209 ** address space (if it is not already), *pp is set to point to the mapped
4210 ** memory and SQLITE_OK returned.
4212 static int winShmMap(
4213 sqlite3_file *fd, /* Handle open on database file */
4214 int iRegion, /* Region to retrieve */
4215 int szRegion, /* Size of regions */
4216 int isWrite, /* True to extend file if necessary */
4217 void volatile **pp /* OUT: Mapped memory */
4219 winFile *pDbFd = (winFile*)fd;
4220 winShm *pShm = pDbFd->pShm;
4221 winShmNode *pShmNode;
4222 DWORD protect = PAGE_READWRITE;
4223 DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
4224 int rc = SQLITE_OK;
4226 if( !pShm ){
4227 rc = winOpenSharedMemory(pDbFd);
4228 if( rc!=SQLITE_OK ) return rc;
4229 pShm = pDbFd->pShm;
4230 assert( pShm!=0 );
4232 pShmNode = pShm->pShmNode;
4234 sqlite3_mutex_enter(pShmNode->mutex);
4235 if( pShmNode->isUnlocked ){
4236 rc = winLockSharedMemory(pShmNode);
4237 if( rc!=SQLITE_OK ) goto shmpage_out;
4238 pShmNode->isUnlocked = 0;
4240 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
4242 if( pShmNode->nRegion<=iRegion ){
4243 struct ShmRegion *apNew; /* New aRegion[] array */
4244 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4245 sqlite3_int64 sz; /* Current size of wal-index file */
4247 pShmNode->szRegion = szRegion;
4249 /* The requested region is not mapped into this processes address space.
4250 ** Check to see if it has been allocated (i.e. if the wal-index file is
4251 ** large enough to contain the requested region).
4253 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
4254 if( rc!=SQLITE_OK ){
4255 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
4256 "winShmMap1", pDbFd->zPath);
4257 goto shmpage_out;
4260 if( sz<nByte ){
4261 /* The requested memory region does not exist. If isWrite is set to
4262 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
4264 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
4265 ** the requested memory region.
4267 if( !isWrite ) goto shmpage_out;
4268 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
4269 if( rc!=SQLITE_OK ){
4270 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
4271 "winShmMap2", pDbFd->zPath);
4272 goto shmpage_out;
4276 /* Map the requested memory region into this processes address space. */
4277 apNew = (struct ShmRegion *)sqlite3_realloc64(
4278 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
4280 if( !apNew ){
4281 rc = SQLITE_IOERR_NOMEM_BKPT;
4282 goto shmpage_out;
4284 pShmNode->aRegion = apNew;
4286 if( pShmNode->isReadonly ){
4287 protect = PAGE_READONLY;
4288 flags = FILE_MAP_READ;
4291 while( pShmNode->nRegion<=iRegion ){
4292 HANDLE hMap = NULL; /* file-mapping handle */
4293 void *pMap = 0; /* Mapped memory region */
4295 #if SQLITE_OS_WINRT
4296 hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
4297 NULL, protect, nByte, NULL
4299 #elif defined(SQLITE_WIN32_HAS_WIDE)
4300 hMap = osCreateFileMappingW(pShmNode->hFile.h,
4301 NULL, protect, 0, nByte, NULL
4303 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
4304 hMap = osCreateFileMappingA(pShmNode->hFile.h,
4305 NULL, protect, 0, nByte, NULL
4307 #endif
4308 OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
4309 osGetCurrentProcessId(), pShmNode->nRegion, nByte,
4310 hMap ? "ok" : "failed"));
4311 if( hMap ){
4312 int iOffset = pShmNode->nRegion*szRegion;
4313 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
4314 #if SQLITE_OS_WINRT
4315 pMap = osMapViewOfFileFromApp(hMap, flags,
4316 iOffset - iOffsetShift, szRegion + iOffsetShift
4318 #else
4319 pMap = osMapViewOfFile(hMap, flags,
4320 0, iOffset - iOffsetShift, szRegion + iOffsetShift
4322 #endif
4323 OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
4324 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
4325 szRegion, pMap ? "ok" : "failed"));
4327 if( !pMap ){
4328 pShmNode->lastErrno = osGetLastError();
4329 rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
4330 "winShmMap3", pDbFd->zPath);
4331 if( hMap ) osCloseHandle(hMap);
4332 goto shmpage_out;
4335 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
4336 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
4337 pShmNode->nRegion++;
4341 shmpage_out:
4342 if( pShmNode->nRegion>iRegion ){
4343 int iOffset = iRegion*szRegion;
4344 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
4345 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
4346 *pp = (void *)&p[iOffsetShift];
4347 }else{
4348 *pp = 0;
4350 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
4351 sqlite3_mutex_leave(pShmNode->mutex);
4352 return rc;
4355 #else
4356 # define winShmMap 0
4357 # define winShmLock 0
4358 # define winShmBarrier 0
4359 # define winShmUnmap 0
4360 #endif /* #ifndef SQLITE_OMIT_WAL */
4363 ** Cleans up the mapped region of the specified file, if any.
4365 #if SQLITE_MAX_MMAP_SIZE>0
4366 static int winUnmapfile(winFile *pFile){
4367 assert( pFile!=0 );
4368 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
4369 "mmapSize=%lld, mmapSizeMax=%lld\n",
4370 osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
4371 pFile->mmapSize, pFile->mmapSizeMax));
4372 if( pFile->pMapRegion ){
4373 if( !osUnmapViewOfFile(pFile->pMapRegion) ){
4374 pFile->lastErrno = osGetLastError();
4375 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
4376 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
4377 pFile->pMapRegion));
4378 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
4379 "winUnmapfile1", pFile->zPath);
4381 pFile->pMapRegion = 0;
4382 pFile->mmapSize = 0;
4384 if( pFile->hMap!=NULL ){
4385 if( !osCloseHandle(pFile->hMap) ){
4386 pFile->lastErrno = osGetLastError();
4387 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
4388 osGetCurrentProcessId(), pFile, pFile->hMap));
4389 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
4390 "winUnmapfile2", pFile->zPath);
4392 pFile->hMap = NULL;
4394 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
4395 osGetCurrentProcessId(), pFile));
4396 return SQLITE_OK;
4400 ** Memory map or remap the file opened by file-descriptor pFd (if the file
4401 ** is already mapped, the existing mapping is replaced by the new). Or, if
4402 ** there already exists a mapping for this file, and there are still
4403 ** outstanding xFetch() references to it, this function is a no-op.
4405 ** If parameter nByte is non-negative, then it is the requested size of
4406 ** the mapping to create. Otherwise, if nByte is less than zero, then the
4407 ** requested size is the size of the file on disk. The actual size of the
4408 ** created mapping is either the requested size or the value configured
4409 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
4411 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
4412 ** recreated as a result of outstanding references) or an SQLite error
4413 ** code otherwise.
4415 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
4416 sqlite3_int64 nMap = nByte;
4417 int rc;
4419 assert( nMap>=0 || pFd->nFetchOut==0 );
4420 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
4421 osGetCurrentProcessId(), pFd, nByte));
4423 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4425 if( nMap<0 ){
4426 rc = winFileSize((sqlite3_file*)pFd, &nMap);
4427 if( rc ){
4428 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
4429 osGetCurrentProcessId(), pFd));
4430 return SQLITE_IOERR_FSTAT;
4433 if( nMap>pFd->mmapSizeMax ){
4434 nMap = pFd->mmapSizeMax;
4436 nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
4438 if( nMap==0 && pFd->mmapSize>0 ){
4439 winUnmapfile(pFd);
4441 if( nMap!=pFd->mmapSize ){
4442 void *pNew = 0;
4443 DWORD protect = PAGE_READONLY;
4444 DWORD flags = FILE_MAP_READ;
4446 winUnmapfile(pFd);
4447 #ifdef SQLITE_MMAP_READWRITE
4448 if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
4449 protect = PAGE_READWRITE;
4450 flags |= FILE_MAP_WRITE;
4452 #endif
4453 #if SQLITE_OS_WINRT
4454 pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
4455 #elif defined(SQLITE_WIN32_HAS_WIDE)
4456 pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
4457 (DWORD)((nMap>>32) & 0xffffffff),
4458 (DWORD)(nMap & 0xffffffff), NULL);
4459 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
4460 pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
4461 (DWORD)((nMap>>32) & 0xffffffff),
4462 (DWORD)(nMap & 0xffffffff), NULL);
4463 #endif
4464 if( pFd->hMap==NULL ){
4465 pFd->lastErrno = osGetLastError();
4466 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
4467 "winMapfile1", pFd->zPath);
4468 /* Log the error, but continue normal operation using xRead/xWrite */
4469 OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
4470 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
4471 return SQLITE_OK;
4473 assert( (nMap % winSysInfo.dwPageSize)==0 );
4474 assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
4475 #if SQLITE_OS_WINRT
4476 pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
4477 #else
4478 pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
4479 #endif
4480 if( pNew==NULL ){
4481 osCloseHandle(pFd->hMap);
4482 pFd->hMap = NULL;
4483 pFd->lastErrno = osGetLastError();
4484 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
4485 "winMapfile2", pFd->zPath);
4486 /* Log the error, but continue normal operation using xRead/xWrite */
4487 OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
4488 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
4489 return SQLITE_OK;
4491 pFd->pMapRegion = pNew;
4492 pFd->mmapSize = nMap;
4495 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
4496 osGetCurrentProcessId(), pFd));
4497 return SQLITE_OK;
4499 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
4502 ** If possible, return a pointer to a mapping of file fd starting at offset
4503 ** iOff. The mapping must be valid for at least nAmt bytes.
4505 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4506 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4507 ** Finally, if an error does occur, return an SQLite error code. The final
4508 ** value of *pp is undefined in this case.
4510 ** If this function does return a pointer, the caller must eventually
4511 ** release the reference by calling winUnfetch().
4513 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
4514 #if SQLITE_MAX_MMAP_SIZE>0
4515 winFile *pFd = (winFile*)fd; /* The underlying database file */
4516 #endif
4517 *pp = 0;
4519 OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
4520 osGetCurrentProcessId(), fd, iOff, nAmt, pp));
4522 #if SQLITE_MAX_MMAP_SIZE>0
4523 if( pFd->mmapSizeMax>0 ){
4524 /* Ensure that there is always at least a 256 byte buffer of addressable
4525 ** memory following the returned page. If the database is corrupt,
4526 ** SQLite may overread the page slightly (in practice only a few bytes,
4527 ** but 256 is safe, round, number). */
4528 const int nEofBuffer = 256;
4529 if( pFd->pMapRegion==0 ){
4530 int rc = winMapfile(pFd, -1);
4531 if( rc!=SQLITE_OK ){
4532 OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
4533 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
4534 return rc;
4537 if( pFd->mmapSize >= (iOff+nAmt+nEofBuffer) ){
4538 assert( pFd->pMapRegion!=0 );
4539 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4540 pFd->nFetchOut++;
4543 #endif
4545 OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
4546 osGetCurrentProcessId(), fd, pp, *pp));
4547 return SQLITE_OK;
4551 ** If the third argument is non-NULL, then this function releases a
4552 ** reference obtained by an earlier call to winFetch(). The second
4553 ** argument passed to this function must be the same as the corresponding
4554 ** argument that was passed to the winFetch() invocation.
4556 ** Or, if the third argument is NULL, then this function is being called
4557 ** to inform the VFS layer that, according to POSIX, any existing mapping
4558 ** may now be invalid and should be unmapped.
4560 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
4561 #if SQLITE_MAX_MMAP_SIZE>0
4562 winFile *pFd = (winFile*)fd; /* The underlying database file */
4564 /* If p==0 (unmap the entire file) then there must be no outstanding
4565 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4566 ** then there must be at least one outstanding. */
4567 assert( (p==0)==(pFd->nFetchOut==0) );
4569 /* If p!=0, it must match the iOff value. */
4570 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4572 OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
4573 osGetCurrentProcessId(), pFd, iOff, p));
4575 if( p ){
4576 pFd->nFetchOut--;
4577 }else{
4578 /* FIXME: If Windows truly always prevents truncating or deleting a
4579 ** file while a mapping is held, then the following winUnmapfile() call
4580 ** is unnecessary can be omitted - potentially improving
4581 ** performance. */
4582 winUnmapfile(pFd);
4585 assert( pFd->nFetchOut>=0 );
4586 #endif
4588 OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
4589 osGetCurrentProcessId(), fd));
4590 return SQLITE_OK;
4594 ** Here ends the implementation of all sqlite3_file methods.
4596 ********************** End sqlite3_file Methods *******************************
4597 ******************************************************************************/
4600 ** This vector defines all the methods that can operate on an
4601 ** sqlite3_file for win32.
4603 static const sqlite3_io_methods winIoMethod = {
4604 3, /* iVersion */
4605 winClose, /* xClose */
4606 winRead, /* xRead */
4607 winWrite, /* xWrite */
4608 winTruncate, /* xTruncate */
4609 winSync, /* xSync */
4610 winFileSize, /* xFileSize */
4611 winLock, /* xLock */
4612 winUnlock, /* xUnlock */
4613 winCheckReservedLock, /* xCheckReservedLock */
4614 winFileControl, /* xFileControl */
4615 winSectorSize, /* xSectorSize */
4616 winDeviceCharacteristics, /* xDeviceCharacteristics */
4617 winShmMap, /* xShmMap */
4618 winShmLock, /* xShmLock */
4619 winShmBarrier, /* xShmBarrier */
4620 winShmUnmap, /* xShmUnmap */
4621 winFetch, /* xFetch */
4622 winUnfetch /* xUnfetch */
4626 ** This vector defines all the methods that can operate on an
4627 ** sqlite3_file for win32 without performing any locking.
4629 static const sqlite3_io_methods winIoNolockMethod = {
4630 3, /* iVersion */
4631 winClose, /* xClose */
4632 winRead, /* xRead */
4633 winWrite, /* xWrite */
4634 winTruncate, /* xTruncate */
4635 winSync, /* xSync */
4636 winFileSize, /* xFileSize */
4637 winNolockLock, /* xLock */
4638 winNolockUnlock, /* xUnlock */
4639 winNolockCheckReservedLock, /* xCheckReservedLock */
4640 winFileControl, /* xFileControl */
4641 winSectorSize, /* xSectorSize */
4642 winDeviceCharacteristics, /* xDeviceCharacteristics */
4643 winShmMap, /* xShmMap */
4644 winShmLock, /* xShmLock */
4645 winShmBarrier, /* xShmBarrier */
4646 winShmUnmap, /* xShmUnmap */
4647 winFetch, /* xFetch */
4648 winUnfetch /* xUnfetch */
4651 static winVfsAppData winAppData = {
4652 &winIoMethod, /* pMethod */
4653 0, /* pAppData */
4654 0 /* bNoLock */
4657 static winVfsAppData winNolockAppData = {
4658 &winIoNolockMethod, /* pMethod */
4659 0, /* pAppData */
4660 1 /* bNoLock */
4663 /****************************************************************************
4664 **************************** sqlite3_vfs methods ****************************
4666 ** This division contains the implementation of methods on the
4667 ** sqlite3_vfs object.
4670 #if defined(__CYGWIN__)
4672 ** Convert a filename from whatever the underlying operating system
4673 ** supports for filenames into UTF-8. Space to hold the result is
4674 ** obtained from malloc and must be freed by the calling function.
4676 static char *winConvertToUtf8Filename(const void *zFilename){
4677 char *zConverted = 0;
4678 if( osIsNT() ){
4679 zConverted = winUnicodeToUtf8(zFilename);
4681 #ifdef SQLITE_WIN32_HAS_ANSI
4682 else{
4683 zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
4685 #endif
4686 /* caller will handle out of memory */
4687 return zConverted;
4689 #endif
4692 ** Convert a UTF-8 filename into whatever form the underlying
4693 ** operating system wants filenames in. Space to hold the result
4694 ** is obtained from malloc and must be freed by the calling
4695 ** function.
4697 static void *winConvertFromUtf8Filename(const char *zFilename){
4698 void *zConverted = 0;
4699 if( osIsNT() ){
4700 zConverted = winUtf8ToUnicode(zFilename);
4702 #ifdef SQLITE_WIN32_HAS_ANSI
4703 else{
4704 zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
4706 #endif
4707 /* caller will handle out of memory */
4708 return zConverted;
4712 ** This function returns non-zero if the specified UTF-8 string buffer
4713 ** ends with a directory separator character or one was successfully
4714 ** added to it.
4716 static int winMakeEndInDirSep(int nBuf, char *zBuf){
4717 if( zBuf ){
4718 int nLen = sqlite3Strlen30(zBuf);
4719 if( nLen>0 ){
4720 if( winIsDirSep(zBuf[nLen-1]) ){
4721 return 1;
4722 }else if( nLen+1<nBuf ){
4723 zBuf[nLen] = winGetDirSep();
4724 zBuf[nLen+1] = '\0';
4725 return 1;
4729 return 0;
4733 ** If sqlite3_temp_directory is defined, take the mutex and return true.
4735 ** If sqlite3_temp_directory is NULL (undefined), omit the mutex and
4736 ** return false.
4738 static int winTempDirDefined(void){
4739 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
4740 if( sqlite3_temp_directory!=0 ) return 1;
4741 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
4742 return 0;
4746 ** Create a temporary file name and store the resulting pointer into pzBuf.
4747 ** The pointer returned in pzBuf must be freed via sqlite3_free().
4749 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
4750 static char zChars[] =
4751 "abcdefghijklmnopqrstuvwxyz"
4752 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4753 "0123456789";
4754 size_t i, j;
4755 DWORD pid;
4756 int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
4757 int nMax, nBuf, nDir, nLen;
4758 char *zBuf;
4760 /* It's odd to simulate an io-error here, but really this is just
4761 ** using the io-error infrastructure to test that SQLite handles this
4762 ** function failing.
4764 SimulateIOError( return SQLITE_IOERR );
4766 /* Allocate a temporary buffer to store the fully qualified file
4767 ** name for the temporary file. If this fails, we cannot continue.
4769 nMax = pVfs->mxPathname; nBuf = nMax + 2;
4770 zBuf = sqlite3MallocZero( nBuf );
4771 if( !zBuf ){
4772 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4773 return SQLITE_IOERR_NOMEM_BKPT;
4776 /* Figure out the effective temporary directory. First, check if one
4777 ** has been explicitly set by the application; otherwise, use the one
4778 ** configured by the operating system.
4780 nDir = nMax - (nPre + 15);
4781 assert( nDir>0 );
4782 if( winTempDirDefined() ){
4783 int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
4784 if( nDirLen>0 ){
4785 if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
4786 nDirLen++;
4788 if( nDirLen>nDir ){
4789 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
4790 sqlite3_free(zBuf);
4791 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
4792 return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
4794 sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
4796 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR));
4799 #if defined(__CYGWIN__)
4800 else{
4801 static const char *azDirs[] = {
4802 0, /* getenv("SQLITE_TMPDIR") */
4803 0, /* getenv("TMPDIR") */
4804 0, /* getenv("TMP") */
4805 0, /* getenv("TEMP") */
4806 0, /* getenv("USERPROFILE") */
4807 "/var/tmp",
4808 "/usr/tmp",
4809 "/tmp",
4810 ".",
4811 0 /* List terminator */
4813 unsigned int i;
4814 const char *zDir = 0;
4816 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
4817 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
4818 if( !azDirs[2] ) azDirs[2] = getenv("TMP");
4819 if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
4820 if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
4821 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
4822 void *zConverted;
4823 if( zDir==0 ) continue;
4824 /* If the path starts with a drive letter followed by the colon
4825 ** character, assume it is already a native Win32 path; otherwise,
4826 ** it must be converted to a native Win32 path via the Cygwin API
4827 ** prior to using it.
4829 if( winIsDriveLetterAndColon(zDir) ){
4830 zConverted = winConvertFromUtf8Filename(zDir);
4831 if( !zConverted ){
4832 sqlite3_free(zBuf);
4833 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4834 return SQLITE_IOERR_NOMEM_BKPT;
4836 if( winIsDir(zConverted) ){
4837 sqlite3_snprintf(nMax, zBuf, "%s", zDir);
4838 sqlite3_free(zConverted);
4839 break;
4841 sqlite3_free(zConverted);
4842 }else{
4843 zConverted = sqlite3MallocZero( nMax+1 );
4844 if( !zConverted ){
4845 sqlite3_free(zBuf);
4846 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4847 return SQLITE_IOERR_NOMEM_BKPT;
4849 if( cygwin_conv_path(
4850 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
4851 zConverted, nMax+1)<0 ){
4852 sqlite3_free(zConverted);
4853 sqlite3_free(zBuf);
4854 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
4855 return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
4856 "winGetTempname2", zDir);
4858 if( winIsDir(zConverted) ){
4859 /* At this point, we know the candidate directory exists and should
4860 ** be used. However, we may need to convert the string containing
4861 ** its name into UTF-8 (i.e. if it is UTF-16 right now).
4863 char *zUtf8 = winConvertToUtf8Filename(zConverted);
4864 if( !zUtf8 ){
4865 sqlite3_free(zConverted);
4866 sqlite3_free(zBuf);
4867 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4868 return SQLITE_IOERR_NOMEM_BKPT;
4870 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
4871 sqlite3_free(zUtf8);
4872 sqlite3_free(zConverted);
4873 break;
4875 sqlite3_free(zConverted);
4879 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
4880 else if( osIsNT() ){
4881 char *zMulti;
4882 LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
4883 if( !zWidePath ){
4884 sqlite3_free(zBuf);
4885 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4886 return SQLITE_IOERR_NOMEM_BKPT;
4888 if( osGetTempPathW(nMax, zWidePath)==0 ){
4889 sqlite3_free(zWidePath);
4890 sqlite3_free(zBuf);
4891 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
4892 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
4893 "winGetTempname2", 0);
4895 zMulti = winUnicodeToUtf8(zWidePath);
4896 if( zMulti ){
4897 sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
4898 sqlite3_free(zMulti);
4899 sqlite3_free(zWidePath);
4900 }else{
4901 sqlite3_free(zWidePath);
4902 sqlite3_free(zBuf);
4903 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4904 return SQLITE_IOERR_NOMEM_BKPT;
4907 #ifdef SQLITE_WIN32_HAS_ANSI
4908 else{
4909 char *zUtf8;
4910 char *zMbcsPath = sqlite3MallocZero( nMax );
4911 if( !zMbcsPath ){
4912 sqlite3_free(zBuf);
4913 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4914 return SQLITE_IOERR_NOMEM_BKPT;
4916 if( osGetTempPathA(nMax, zMbcsPath)==0 ){
4917 sqlite3_free(zBuf);
4918 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
4919 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
4920 "winGetTempname3", 0);
4922 zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
4923 if( zUtf8 ){
4924 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
4925 sqlite3_free(zUtf8);
4926 }else{
4927 sqlite3_free(zBuf);
4928 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4929 return SQLITE_IOERR_NOMEM_BKPT;
4932 #endif /* SQLITE_WIN32_HAS_ANSI */
4933 #endif /* !SQLITE_OS_WINRT */
4936 ** Check to make sure the temporary directory ends with an appropriate
4937 ** separator. If it does not and there is not enough space left to add
4938 ** one, fail.
4940 if( !winMakeEndInDirSep(nDir+1, zBuf) ){
4941 sqlite3_free(zBuf);
4942 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
4943 return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
4947 ** Check that the output buffer is large enough for the temporary file
4948 ** name in the following format:
4950 ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
4952 ** If not, return SQLITE_ERROR. The number 17 is used here in order to
4953 ** account for the space used by the 15 character random suffix and the
4954 ** two trailing NUL characters. The final directory separator character
4955 ** has already added if it was not already present.
4957 nLen = sqlite3Strlen30(zBuf);
4958 if( (nLen + nPre + 17) > nBuf ){
4959 sqlite3_free(zBuf);
4960 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
4961 return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
4964 sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
4966 j = sqlite3Strlen30(zBuf);
4967 sqlite3_randomness(15, &zBuf[j]);
4968 pid = osGetCurrentProcessId();
4969 for(i=0; i<15; i++, j++){
4970 zBuf[j] += pid & 0xff;
4971 pid >>= 8;
4972 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4974 zBuf[j] = 0;
4975 zBuf[j+1] = 0;
4976 *pzBuf = zBuf;
4978 OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
4979 return SQLITE_OK;
4983 ** Return TRUE if the named file is really a directory. Return false if
4984 ** it is something other than a directory, or if there is any kind of memory
4985 ** allocation failure.
4987 static int winIsDir(const void *zConverted){
4988 DWORD attr;
4989 int rc = 0;
4990 DWORD lastErrno;
4992 if( osIsNT() ){
4993 int cnt = 0;
4994 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
4995 memset(&sAttrData, 0, sizeof(sAttrData));
4996 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
4997 GetFileExInfoStandard,
4998 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
4999 if( !rc ){
5000 return 0; /* Invalid name? */
5002 attr = sAttrData.dwFileAttributes;
5003 #if SQLITE_OS_WINCE==0
5004 }else{
5005 attr = osGetFileAttributesA((char*)zConverted);
5006 #endif
5008 return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
5011 /* forward reference */
5012 static int winAccess(
5013 sqlite3_vfs *pVfs, /* Not used on win32 */
5014 const char *zFilename, /* Name of file to check */
5015 int flags, /* Type of test to make on this file */
5016 int *pResOut /* OUT: Result */
5020 ** Open a file.
5022 static int winOpen(
5023 sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
5024 const char *zName, /* Name of the file (UTF-8) */
5025 sqlite3_file *id, /* Write the SQLite file handle here */
5026 int flags, /* Open mode flags */
5027 int *pOutFlags /* Status return flags */
5029 HANDLE h;
5030 DWORD lastErrno = 0;
5031 DWORD dwDesiredAccess;
5032 DWORD dwShareMode;
5033 DWORD dwCreationDisposition;
5034 DWORD dwFlagsAndAttributes = 0;
5035 #if SQLITE_OS_WINCE
5036 int isTemp = 0;
5037 #endif
5038 winVfsAppData *pAppData;
5039 winFile *pFile = (winFile*)id;
5040 void *zConverted; /* Filename in OS encoding */
5041 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
5042 int cnt = 0;
5044 /* If argument zPath is a NULL pointer, this function is required to open
5045 ** a temporary file. Use this buffer to store the file name in.
5047 char *zTmpname = 0; /* For temporary filename, if necessary. */
5049 int rc = SQLITE_OK; /* Function Return Code */
5050 #if !defined(NDEBUG) || SQLITE_OS_WINCE
5051 int eType = flags&0xFFFFFF00; /* Type of file to open */
5052 #endif
5054 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5055 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5056 int isCreate = (flags & SQLITE_OPEN_CREATE);
5057 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5058 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
5060 #ifndef NDEBUG
5061 int isOpenJournal = (isCreate && (
5062 eType==SQLITE_OPEN_SUPER_JOURNAL
5063 || eType==SQLITE_OPEN_MAIN_JOURNAL
5064 || eType==SQLITE_OPEN_WAL
5066 #endif
5068 OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
5069 zUtf8Name, id, flags, pOutFlags));
5071 /* Check the following statements are true:
5073 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5074 ** (b) if CREATE is set, then READWRITE must also be set, and
5075 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
5076 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
5078 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
5079 assert(isCreate==0 || isReadWrite);
5080 assert(isExclusive==0 || isCreate);
5081 assert(isDelete==0 || isCreate);
5083 /* The main DB, main journal, WAL file and super-journal are never
5084 ** automatically deleted. Nor are they ever temporary files. */
5085 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5086 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5087 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL );
5088 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
5090 /* Assert that the upper layer has set one of the "file-type" flags. */
5091 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5092 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5093 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_SUPER_JOURNAL
5094 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
5097 assert( pFile!=0 );
5098 memset(pFile, 0, sizeof(winFile));
5099 pFile->h = INVALID_HANDLE_VALUE;
5101 #if SQLITE_OS_WINRT
5102 if( !zUtf8Name && !sqlite3_temp_directory ){
5103 sqlite3_log(SQLITE_ERROR,
5104 "sqlite3_temp_directory variable should be set for WinRT");
5106 #endif
5108 /* If the second argument to this function is NULL, generate a
5109 ** temporary file name to use
5111 if( !zUtf8Name ){
5112 assert( isDelete && !isOpenJournal );
5113 rc = winGetTempname(pVfs, &zTmpname);
5114 if( rc!=SQLITE_OK ){
5115 OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
5116 return rc;
5118 zUtf8Name = zTmpname;
5121 /* Database filenames are double-zero terminated if they are not
5122 ** URIs with parameters. Hence, they can always be passed into
5123 ** sqlite3_uri_parameter().
5125 assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
5126 zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
5128 /* Convert the filename to the system encoding. */
5129 zConverted = winConvertFromUtf8Filename(zUtf8Name);
5130 if( zConverted==0 ){
5131 sqlite3_free(zTmpname);
5132 OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
5133 return SQLITE_IOERR_NOMEM_BKPT;
5136 if( winIsDir(zConverted) ){
5137 sqlite3_free(zConverted);
5138 sqlite3_free(zTmpname);
5139 OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
5140 return SQLITE_CANTOPEN_ISDIR;
5143 if( isReadWrite ){
5144 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
5145 }else{
5146 dwDesiredAccess = GENERIC_READ;
5149 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
5150 ** created. SQLite doesn't use it to indicate "exclusive access"
5151 ** as it is usually understood.
5153 if( isExclusive ){
5154 /* Creates a new file, only if it does not already exist. */
5155 /* If the file exists, it fails. */
5156 dwCreationDisposition = CREATE_NEW;
5157 }else if( isCreate ){
5158 /* Open existing file, or create if it doesn't exist */
5159 dwCreationDisposition = OPEN_ALWAYS;
5160 }else{
5161 /* Opens a file, only if it exists. */
5162 dwCreationDisposition = OPEN_EXISTING;
5165 if( 0==sqlite3_uri_boolean(zName, "exclusive", 0) ){
5166 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
5167 }else{
5168 dwShareMode = 0;
5171 if( isDelete ){
5172 #if SQLITE_OS_WINCE
5173 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
5174 isTemp = 1;
5175 #else
5176 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
5177 | FILE_ATTRIBUTE_HIDDEN
5178 | FILE_FLAG_DELETE_ON_CLOSE;
5179 #endif
5180 }else{
5181 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
5183 /* Reports from the internet are that performance is always
5184 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
5185 #if SQLITE_OS_WINCE
5186 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
5187 #endif
5189 if( osIsNT() ){
5190 #if SQLITE_OS_WINRT
5191 CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
5192 extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
5193 extendedParameters.dwFileAttributes =
5194 dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
5195 extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
5196 extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
5197 extendedParameters.lpSecurityAttributes = NULL;
5198 extendedParameters.hTemplateFile = NULL;
5200 h = osCreateFile2((LPCWSTR)zConverted,
5201 dwDesiredAccess,
5202 dwShareMode,
5203 dwCreationDisposition,
5204 &extendedParameters);
5205 if( h!=INVALID_HANDLE_VALUE ) break;
5206 if( isReadWrite ){
5207 int rc2, isRO = 0;
5208 sqlite3BeginBenignMalloc();
5209 rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO);
5210 sqlite3EndBenignMalloc();
5211 if( rc2==SQLITE_OK && isRO ) break;
5213 }while( winRetryIoerr(&cnt, &lastErrno) );
5214 #else
5216 h = osCreateFileW((LPCWSTR)zConverted,
5217 dwDesiredAccess,
5218 dwShareMode, NULL,
5219 dwCreationDisposition,
5220 dwFlagsAndAttributes,
5221 NULL);
5222 if( h!=INVALID_HANDLE_VALUE ) break;
5223 if( isReadWrite ){
5224 int rc2, isRO = 0;
5225 sqlite3BeginBenignMalloc();
5226 rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO);
5227 sqlite3EndBenignMalloc();
5228 if( rc2==SQLITE_OK && isRO ) break;
5230 }while( winRetryIoerr(&cnt, &lastErrno) );
5231 #endif
5233 #ifdef SQLITE_WIN32_HAS_ANSI
5234 else{
5236 h = osCreateFileA((LPCSTR)zConverted,
5237 dwDesiredAccess,
5238 dwShareMode, NULL,
5239 dwCreationDisposition,
5240 dwFlagsAndAttributes,
5241 NULL);
5242 if( h!=INVALID_HANDLE_VALUE ) break;
5243 if( isReadWrite ){
5244 int rc2, isRO = 0;
5245 sqlite3BeginBenignMalloc();
5246 rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO);
5247 sqlite3EndBenignMalloc();
5248 if( rc2==SQLITE_OK && isRO ) break;
5250 }while( winRetryIoerr(&cnt, &lastErrno) );
5252 #endif
5253 winLogIoerr(cnt, __LINE__);
5255 OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
5256 dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
5258 if( h==INVALID_HANDLE_VALUE ){
5259 sqlite3_free(zConverted);
5260 sqlite3_free(zTmpname);
5261 if( isReadWrite && !isExclusive ){
5262 return winOpen(pVfs, zName, id,
5263 ((flags|SQLITE_OPEN_READONLY) &
5264 ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
5265 pOutFlags);
5266 }else{
5267 pFile->lastErrno = lastErrno;
5268 winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
5269 return SQLITE_CANTOPEN_BKPT;
5273 if( pOutFlags ){
5274 if( isReadWrite ){
5275 *pOutFlags = SQLITE_OPEN_READWRITE;
5276 }else{
5277 *pOutFlags = SQLITE_OPEN_READONLY;
5281 OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
5282 "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
5283 *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
5285 pAppData = (winVfsAppData*)pVfs->pAppData;
5287 #if SQLITE_OS_WINCE
5289 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
5290 && ((pAppData==NULL) || !pAppData->bNoLock)
5291 && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
5293 osCloseHandle(h);
5294 sqlite3_free(zConverted);
5295 sqlite3_free(zTmpname);
5296 OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
5297 return rc;
5300 if( isTemp ){
5301 pFile->zDeleteOnClose = zConverted;
5302 }else
5303 #endif
5305 sqlite3_free(zConverted);
5308 sqlite3_free(zTmpname);
5309 id->pMethods = pAppData ? pAppData->pMethod : &winIoMethod;
5310 pFile->pVfs = pVfs;
5311 pFile->h = h;
5312 if( isReadonly ){
5313 pFile->ctrlFlags |= WINFILE_RDONLY;
5315 if( (flags & SQLITE_OPEN_MAIN_DB)
5316 && sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE)
5318 pFile->ctrlFlags |= WINFILE_PSOW;
5320 pFile->lastErrno = NO_ERROR;
5321 pFile->zPath = zName;
5322 #if SQLITE_MAX_MMAP_SIZE>0
5323 pFile->hMap = NULL;
5324 pFile->pMapRegion = 0;
5325 pFile->mmapSize = 0;
5326 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
5327 #endif
5329 OpenCounter(+1);
5330 return rc;
5334 ** Delete the named file.
5336 ** Note that Windows does not allow a file to be deleted if some other
5337 ** process has it open. Sometimes a virus scanner or indexing program
5338 ** will open a journal file shortly after it is created in order to do
5339 ** whatever it does. While this other process is holding the
5340 ** file open, we will be unable to delete it. To work around this
5341 ** problem, we delay 100 milliseconds and try to delete again. Up
5342 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
5343 ** up and returning an error.
5345 static int winDelete(
5346 sqlite3_vfs *pVfs, /* Not used on win32 */
5347 const char *zFilename, /* Name of file to delete */
5348 int syncDir /* Not used on win32 */
5350 int cnt = 0;
5351 int rc;
5352 DWORD attr;
5353 DWORD lastErrno = 0;
5354 void *zConverted;
5355 UNUSED_PARAMETER(pVfs);
5356 UNUSED_PARAMETER(syncDir);
5358 SimulateIOError(return SQLITE_IOERR_DELETE);
5359 OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
5361 zConverted = winConvertFromUtf8Filename(zFilename);
5362 if( zConverted==0 ){
5363 OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
5364 return SQLITE_IOERR_NOMEM_BKPT;
5366 if( osIsNT() ){
5367 do {
5368 #if SQLITE_OS_WINRT
5369 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
5370 memset(&sAttrData, 0, sizeof(sAttrData));
5371 if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
5372 &sAttrData) ){
5373 attr = sAttrData.dwFileAttributes;
5374 }else{
5375 lastErrno = osGetLastError();
5376 if( lastErrno==ERROR_FILE_NOT_FOUND
5377 || lastErrno==ERROR_PATH_NOT_FOUND ){
5378 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
5379 }else{
5380 rc = SQLITE_ERROR;
5382 break;
5384 #else
5385 attr = osGetFileAttributesW(zConverted);
5386 #endif
5387 if ( attr==INVALID_FILE_ATTRIBUTES ){
5388 lastErrno = osGetLastError();
5389 if( lastErrno==ERROR_FILE_NOT_FOUND
5390 || lastErrno==ERROR_PATH_NOT_FOUND ){
5391 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
5392 }else{
5393 rc = SQLITE_ERROR;
5395 break;
5397 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
5398 rc = SQLITE_ERROR; /* Files only. */
5399 break;
5401 if ( osDeleteFileW(zConverted) ){
5402 rc = SQLITE_OK; /* Deleted OK. */
5403 break;
5405 if ( !winRetryIoerr(&cnt, &lastErrno) ){
5406 rc = SQLITE_ERROR; /* No more retries. */
5407 break;
5409 } while(1);
5411 #ifdef SQLITE_WIN32_HAS_ANSI
5412 else{
5413 do {
5414 attr = osGetFileAttributesA(zConverted);
5415 if ( attr==INVALID_FILE_ATTRIBUTES ){
5416 lastErrno = osGetLastError();
5417 if( lastErrno==ERROR_FILE_NOT_FOUND
5418 || lastErrno==ERROR_PATH_NOT_FOUND ){
5419 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
5420 }else{
5421 rc = SQLITE_ERROR;
5423 break;
5425 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
5426 rc = SQLITE_ERROR; /* Files only. */
5427 break;
5429 if ( osDeleteFileA(zConverted) ){
5430 rc = SQLITE_OK; /* Deleted OK. */
5431 break;
5433 if ( !winRetryIoerr(&cnt, &lastErrno) ){
5434 rc = SQLITE_ERROR; /* No more retries. */
5435 break;
5437 } while(1);
5439 #endif
5440 if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
5441 rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
5442 }else{
5443 winLogIoerr(cnt, __LINE__);
5445 sqlite3_free(zConverted);
5446 OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
5447 return rc;
5451 ** Check the existence and status of a file.
5453 static int winAccess(
5454 sqlite3_vfs *pVfs, /* Not used on win32 */
5455 const char *zFilename, /* Name of file to check */
5456 int flags, /* Type of test to make on this file */
5457 int *pResOut /* OUT: Result */
5459 DWORD attr;
5460 int rc = 0;
5461 DWORD lastErrno = 0;
5462 void *zConverted;
5463 UNUSED_PARAMETER(pVfs);
5465 SimulateIOError( return SQLITE_IOERR_ACCESS; );
5466 OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
5467 zFilename, flags, pResOut));
5469 if( zFilename==0 ){
5470 *pResOut = 0;
5471 OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
5472 zFilename, pResOut, *pResOut));
5473 return SQLITE_OK;
5476 zConverted = winConvertFromUtf8Filename(zFilename);
5477 if( zConverted==0 ){
5478 OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
5479 return SQLITE_IOERR_NOMEM_BKPT;
5481 if( osIsNT() ){
5482 int cnt = 0;
5483 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
5484 memset(&sAttrData, 0, sizeof(sAttrData));
5485 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
5486 GetFileExInfoStandard,
5487 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
5488 if( rc ){
5489 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
5490 ** as if it does not exist.
5492 if( flags==SQLITE_ACCESS_EXISTS
5493 && sAttrData.nFileSizeHigh==0
5494 && sAttrData.nFileSizeLow==0 ){
5495 attr = INVALID_FILE_ATTRIBUTES;
5496 }else{
5497 attr = sAttrData.dwFileAttributes;
5499 }else{
5500 winLogIoerr(cnt, __LINE__);
5501 if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
5502 sqlite3_free(zConverted);
5503 return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
5504 zFilename);
5505 }else{
5506 attr = INVALID_FILE_ATTRIBUTES;
5510 #ifdef SQLITE_WIN32_HAS_ANSI
5511 else{
5512 attr = osGetFileAttributesA((char*)zConverted);
5514 #endif
5515 sqlite3_free(zConverted);
5516 switch( flags ){
5517 case SQLITE_ACCESS_READ:
5518 case SQLITE_ACCESS_EXISTS:
5519 rc = attr!=INVALID_FILE_ATTRIBUTES;
5520 break;
5521 case SQLITE_ACCESS_READWRITE:
5522 rc = attr!=INVALID_FILE_ATTRIBUTES &&
5523 (attr & FILE_ATTRIBUTE_READONLY)==0;
5524 break;
5525 default:
5526 assert(!"Invalid flags argument");
5528 *pResOut = rc;
5529 OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
5530 zFilename, pResOut, *pResOut));
5531 return SQLITE_OK;
5535 ** Returns non-zero if the specified path name starts with the "long path"
5536 ** prefix.
5538 static BOOL winIsLongPathPrefix(
5539 const char *zPathname
5541 return ( zPathname[0]=='\\' && zPathname[1]=='\\'
5542 && zPathname[2]=='?' && zPathname[3]=='\\' );
5546 ** Returns non-zero if the specified path name starts with a drive letter
5547 ** followed by a colon character.
5549 static BOOL winIsDriveLetterAndColon(
5550 const char *zPathname
5552 return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
5556 ** Returns non-zero if the specified path name should be used verbatim. If
5557 ** non-zero is returned from this function, the calling function must simply
5558 ** use the provided path name verbatim -OR- resolve it into a full path name
5559 ** using the GetFullPathName Win32 API function (if available).
5561 static BOOL winIsVerbatimPathname(
5562 const char *zPathname
5565 ** If the path name starts with a forward slash or a backslash, it is either
5566 ** a legal UNC name, a volume relative path, or an absolute path name in the
5567 ** "Unix" format on Windows. There is no easy way to differentiate between
5568 ** the final two cases; therefore, we return the safer return value of TRUE
5569 ** so that callers of this function will simply use it verbatim.
5571 if ( winIsDirSep(zPathname[0]) ){
5572 return TRUE;
5576 ** If the path name starts with a letter and a colon it is either a volume
5577 ** relative path or an absolute path. Callers of this function must not
5578 ** attempt to treat it as a relative path name (i.e. they should simply use
5579 ** it verbatim).
5581 if ( winIsDriveLetterAndColon(zPathname) ){
5582 return TRUE;
5586 ** If we get to this point, the path name should almost certainly be a purely
5587 ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
5589 return FALSE;
5593 ** Turn a relative pathname into a full pathname. Write the full
5594 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
5595 ** bytes in size.
5597 static int winFullPathnameNoMutex(
5598 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5599 const char *zRelative, /* Possibly relative input path */
5600 int nFull, /* Size of output buffer in bytes */
5601 char *zFull /* Output buffer */
5603 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
5604 DWORD nByte;
5605 void *zConverted;
5606 char *zOut;
5607 #endif
5609 /* If this path name begins with "/X:" or "\\?\", where "X" is any
5610 ** alphabetic character, discard the initial "/" from the pathname.
5612 if( zRelative[0]=='/' && (winIsDriveLetterAndColon(zRelative+1)
5613 || winIsLongPathPrefix(zRelative+1)) ){
5614 zRelative++;
5617 #if defined(__CYGWIN__)
5618 SimulateIOError( return SQLITE_ERROR );
5619 UNUSED_PARAMETER(nFull);
5620 assert( nFull>=pVfs->mxPathname );
5621 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
5623 ** NOTE: We are dealing with a relative path name and the data
5624 ** directory has been set. Therefore, use it as the basis
5625 ** for converting the relative path name to an absolute
5626 ** one by prepending the data directory and a slash.
5628 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
5629 if( !zOut ){
5630 return SQLITE_IOERR_NOMEM_BKPT;
5632 if( cygwin_conv_path(
5633 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
5634 CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
5635 sqlite3_free(zOut);
5636 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
5637 "winFullPathname1", zRelative);
5638 }else{
5639 char *zUtf8 = winConvertToUtf8Filename(zOut);
5640 if( !zUtf8 ){
5641 sqlite3_free(zOut);
5642 return SQLITE_IOERR_NOMEM_BKPT;
5644 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
5645 sqlite3_data_directory, winGetDirSep(), zUtf8);
5646 sqlite3_free(zUtf8);
5647 sqlite3_free(zOut);
5649 }else{
5650 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
5651 if( !zOut ){
5652 return SQLITE_IOERR_NOMEM_BKPT;
5654 if( cygwin_conv_path(
5655 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
5656 zRelative, zOut, pVfs->mxPathname+1)<0 ){
5657 sqlite3_free(zOut);
5658 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
5659 "winFullPathname2", zRelative);
5660 }else{
5661 char *zUtf8 = winConvertToUtf8Filename(zOut);
5662 if( !zUtf8 ){
5663 sqlite3_free(zOut);
5664 return SQLITE_IOERR_NOMEM_BKPT;
5666 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
5667 sqlite3_free(zUtf8);
5668 sqlite3_free(zOut);
5671 return SQLITE_OK;
5672 #endif
5674 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
5675 SimulateIOError( return SQLITE_ERROR );
5676 /* WinCE has no concept of a relative pathname, or so I am told. */
5677 /* WinRT has no way to convert a relative path to an absolute one. */
5678 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
5680 ** NOTE: We are dealing with a relative path name and the data
5681 ** directory has been set. Therefore, use it as the basis
5682 ** for converting the relative path name to an absolute
5683 ** one by prepending the data directory and a backslash.
5685 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
5686 sqlite3_data_directory, winGetDirSep(), zRelative);
5687 }else{
5688 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
5690 return SQLITE_OK;
5691 #endif
5693 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
5694 /* It's odd to simulate an io-error here, but really this is just
5695 ** using the io-error infrastructure to test that SQLite handles this
5696 ** function failing. This function could fail if, for example, the
5697 ** current working directory has been unlinked.
5699 SimulateIOError( return SQLITE_ERROR );
5700 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
5702 ** NOTE: We are dealing with a relative path name and the data
5703 ** directory has been set. Therefore, use it as the basis
5704 ** for converting the relative path name to an absolute
5705 ** one by prepending the data directory and a backslash.
5707 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
5708 sqlite3_data_directory, winGetDirSep(), zRelative);
5709 return SQLITE_OK;
5711 zConverted = winConvertFromUtf8Filename(zRelative);
5712 if( zConverted==0 ){
5713 return SQLITE_IOERR_NOMEM_BKPT;
5715 if( osIsNT() ){
5716 LPWSTR zTemp;
5717 nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
5718 if( nByte==0 ){
5719 sqlite3_free(zConverted);
5720 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
5721 "winFullPathname1", zRelative);
5723 nByte += 3;
5724 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
5725 if( zTemp==0 ){
5726 sqlite3_free(zConverted);
5727 return SQLITE_IOERR_NOMEM_BKPT;
5729 nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
5730 if( nByte==0 ){
5731 sqlite3_free(zConverted);
5732 sqlite3_free(zTemp);
5733 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
5734 "winFullPathname2", zRelative);
5736 sqlite3_free(zConverted);
5737 zOut = winUnicodeToUtf8(zTemp);
5738 sqlite3_free(zTemp);
5740 #ifdef SQLITE_WIN32_HAS_ANSI
5741 else{
5742 char *zTemp;
5743 nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
5744 if( nByte==0 ){
5745 sqlite3_free(zConverted);
5746 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
5747 "winFullPathname3", zRelative);
5749 nByte += 3;
5750 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
5751 if( zTemp==0 ){
5752 sqlite3_free(zConverted);
5753 return SQLITE_IOERR_NOMEM_BKPT;
5755 nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
5756 if( nByte==0 ){
5757 sqlite3_free(zConverted);
5758 sqlite3_free(zTemp);
5759 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
5760 "winFullPathname4", zRelative);
5762 sqlite3_free(zConverted);
5763 zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
5764 sqlite3_free(zTemp);
5766 #endif
5767 if( zOut ){
5768 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
5769 sqlite3_free(zOut);
5770 return SQLITE_OK;
5771 }else{
5772 return SQLITE_IOERR_NOMEM_BKPT;
5774 #endif
5776 static int winFullPathname(
5777 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5778 const char *zRelative, /* Possibly relative input path */
5779 int nFull, /* Size of output buffer in bytes */
5780 char *zFull /* Output buffer */
5782 int rc;
5783 MUTEX_LOGIC( sqlite3_mutex *pMutex; )
5784 MUTEX_LOGIC( pMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR); )
5785 sqlite3_mutex_enter(pMutex);
5786 rc = winFullPathnameNoMutex(pVfs, zRelative, nFull, zFull);
5787 sqlite3_mutex_leave(pMutex);
5788 return rc;
5791 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5793 ** Interfaces for opening a shared library, finding entry points
5794 ** within the shared library, and closing the shared library.
5796 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
5797 HANDLE h;
5798 #if defined(__CYGWIN__)
5799 int nFull = pVfs->mxPathname+1;
5800 char *zFull = sqlite3MallocZero( nFull );
5801 void *zConverted = 0;
5802 if( zFull==0 ){
5803 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
5804 return 0;
5806 if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
5807 sqlite3_free(zFull);
5808 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
5809 return 0;
5811 zConverted = winConvertFromUtf8Filename(zFull);
5812 sqlite3_free(zFull);
5813 #else
5814 void *zConverted = winConvertFromUtf8Filename(zFilename);
5815 UNUSED_PARAMETER(pVfs);
5816 #endif
5817 if( zConverted==0 ){
5818 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
5819 return 0;
5821 if( osIsNT() ){
5822 #if SQLITE_OS_WINRT
5823 h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
5824 #else
5825 h = osLoadLibraryW((LPCWSTR)zConverted);
5826 #endif
5828 #ifdef SQLITE_WIN32_HAS_ANSI
5829 else{
5830 h = osLoadLibraryA((char*)zConverted);
5832 #endif
5833 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
5834 sqlite3_free(zConverted);
5835 return (void*)h;
5837 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
5838 UNUSED_PARAMETER(pVfs);
5839 winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
5841 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
5842 FARPROC proc;
5843 UNUSED_PARAMETER(pVfs);
5844 proc = osGetProcAddressA((HANDLE)pH, zSym);
5845 OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
5846 (void*)pH, zSym, (void*)proc));
5847 return (void(*)(void))proc;
5849 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
5850 UNUSED_PARAMETER(pVfs);
5851 osFreeLibrary((HANDLE)pHandle);
5852 OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
5854 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5855 #define winDlOpen 0
5856 #define winDlError 0
5857 #define winDlSym 0
5858 #define winDlClose 0
5859 #endif
5861 /* State information for the randomness gatherer. */
5862 typedef struct EntropyGatherer EntropyGatherer;
5863 struct EntropyGatherer {
5864 unsigned char *a; /* Gather entropy into this buffer */
5865 int na; /* Size of a[] in bytes */
5866 int i; /* XOR next input into a[i] */
5867 int nXor; /* Number of XOR operations done */
5870 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
5871 /* Mix sz bytes of entropy into p. */
5872 static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
5873 int j, k;
5874 for(j=0, k=p->i; j<sz; j++){
5875 p->a[k++] ^= x[j];
5876 if( k>=p->na ) k = 0;
5878 p->i = k;
5879 p->nXor += sz;
5881 #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
5884 ** Write up to nBuf bytes of randomness into zBuf.
5886 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
5887 #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
5888 UNUSED_PARAMETER(pVfs);
5889 memset(zBuf, 0, nBuf);
5890 return nBuf;
5891 #else
5892 EntropyGatherer e;
5893 UNUSED_PARAMETER(pVfs);
5894 memset(zBuf, 0, nBuf);
5895 e.a = (unsigned char*)zBuf;
5896 e.na = nBuf;
5897 e.nXor = 0;
5898 e.i = 0;
5900 SYSTEMTIME x;
5901 osGetSystemTime(&x);
5902 xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
5905 DWORD pid = osGetCurrentProcessId();
5906 xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
5908 #if SQLITE_OS_WINRT
5910 ULONGLONG cnt = osGetTickCount64();
5911 xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
5913 #else
5915 DWORD cnt = osGetTickCount();
5916 xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
5918 #endif /* SQLITE_OS_WINRT */
5920 LARGE_INTEGER i;
5921 osQueryPerformanceCounter(&i);
5922 xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
5924 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
5926 UUID id;
5927 memset(&id, 0, sizeof(UUID));
5928 osUuidCreate(&id);
5929 xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
5930 memset(&id, 0, sizeof(UUID));
5931 osUuidCreateSequential(&id);
5932 xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
5934 #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
5935 return e.nXor>nBuf ? nBuf : e.nXor;
5936 #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
5941 ** Sleep for a little while. Return the amount of time slept.
5943 static int winSleep(sqlite3_vfs *pVfs, int microsec){
5944 sqlite3_win32_sleep((microsec+999)/1000);
5945 UNUSED_PARAMETER(pVfs);
5946 return ((microsec+999)/1000)*1000;
5950 ** The following variable, if set to a non-zero value, is interpreted as
5951 ** the number of seconds since 1970 and is used to set the result of
5952 ** sqlite3OsCurrentTime() during testing.
5954 #ifdef SQLITE_TEST
5955 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
5956 #endif
5959 ** Find the current time (in Universal Coordinated Time). Write into *piNow
5960 ** the current time and date as a Julian Day number times 86_400_000. In
5961 ** other words, write into *piNow the number of milliseconds since the Julian
5962 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5963 ** proleptic Gregorian calendar.
5965 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5966 ** cannot be found.
5968 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
5969 /* FILETIME structure is a 64-bit value representing the number of
5970 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
5972 FILETIME ft;
5973 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
5974 #ifdef SQLITE_TEST
5975 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5976 #endif
5977 /* 2^32 - to avoid use of LL and warnings in gcc */
5978 static const sqlite3_int64 max32BitValue =
5979 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
5980 (sqlite3_int64)294967296;
5982 #if SQLITE_OS_WINCE
5983 SYSTEMTIME time;
5984 osGetSystemTime(&time);
5985 /* if SystemTimeToFileTime() fails, it returns zero. */
5986 if (!osSystemTimeToFileTime(&time,&ft)){
5987 return SQLITE_ERROR;
5989 #else
5990 osGetSystemTimeAsFileTime( &ft );
5991 #endif
5993 *piNow = winFiletimeEpoch +
5994 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
5995 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
5997 #ifdef SQLITE_TEST
5998 if( sqlite3_current_time ){
5999 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6001 #endif
6002 UNUSED_PARAMETER(pVfs);
6003 return SQLITE_OK;
6007 ** Find the current time (in Universal Coordinated Time). Write the
6008 ** current time and date as a Julian Day number into *prNow and
6009 ** return 0. Return 1 if the time and date cannot be found.
6011 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
6012 int rc;
6013 sqlite3_int64 i;
6014 rc = winCurrentTimeInt64(pVfs, &i);
6015 if( !rc ){
6016 *prNow = i/86400000.0;
6018 return rc;
6022 ** The idea is that this function works like a combination of
6023 ** GetLastError() and FormatMessage() on Windows (or errno and
6024 ** strerror_r() on Unix). After an error is returned by an OS
6025 ** function, SQLite calls this function with zBuf pointing to
6026 ** a buffer of nBuf bytes. The OS layer should populate the
6027 ** buffer with a nul-terminated UTF-8 encoded error message
6028 ** describing the last IO error to have occurred within the calling
6029 ** thread.
6031 ** If the error message is too large for the supplied buffer,
6032 ** it should be truncated. The return value of xGetLastError
6033 ** is zero if the error message fits in the buffer, or non-zero
6034 ** otherwise (if the message was truncated). If non-zero is returned,
6035 ** then it is not necessary to include the nul-terminator character
6036 ** in the output buffer.
6038 ** Not supplying an error message will have no adverse effect
6039 ** on SQLite. It is fine to have an implementation that never
6040 ** returns an error message:
6042 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
6043 ** assert(zBuf[0]=='\0');
6044 ** return 0;
6045 ** }
6047 ** However if an error message is supplied, it will be incorporated
6048 ** by sqlite into the error message available to the user using
6049 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
6051 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
6052 DWORD e = osGetLastError();
6053 UNUSED_PARAMETER(pVfs);
6054 if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
6055 return e;
6059 ** Initialize and deinitialize the operating system interface.
6061 int sqlite3_os_init(void){
6062 static sqlite3_vfs winVfs = {
6063 3, /* iVersion */
6064 sizeof(winFile), /* szOsFile */
6065 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
6066 0, /* pNext */
6067 "win32", /* zName */
6068 &winAppData, /* pAppData */
6069 winOpen, /* xOpen */
6070 winDelete, /* xDelete */
6071 winAccess, /* xAccess */
6072 winFullPathname, /* xFullPathname */
6073 winDlOpen, /* xDlOpen */
6074 winDlError, /* xDlError */
6075 winDlSym, /* xDlSym */
6076 winDlClose, /* xDlClose */
6077 winRandomness, /* xRandomness */
6078 winSleep, /* xSleep */
6079 winCurrentTime, /* xCurrentTime */
6080 winGetLastError, /* xGetLastError */
6081 winCurrentTimeInt64, /* xCurrentTimeInt64 */
6082 winSetSystemCall, /* xSetSystemCall */
6083 winGetSystemCall, /* xGetSystemCall */
6084 winNextSystemCall, /* xNextSystemCall */
6086 #if defined(SQLITE_WIN32_HAS_WIDE)
6087 static sqlite3_vfs winLongPathVfs = {
6088 3, /* iVersion */
6089 sizeof(winFile), /* szOsFile */
6090 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
6091 0, /* pNext */
6092 "win32-longpath", /* zName */
6093 &winAppData, /* pAppData */
6094 winOpen, /* xOpen */
6095 winDelete, /* xDelete */
6096 winAccess, /* xAccess */
6097 winFullPathname, /* xFullPathname */
6098 winDlOpen, /* xDlOpen */
6099 winDlError, /* xDlError */
6100 winDlSym, /* xDlSym */
6101 winDlClose, /* xDlClose */
6102 winRandomness, /* xRandomness */
6103 winSleep, /* xSleep */
6104 winCurrentTime, /* xCurrentTime */
6105 winGetLastError, /* xGetLastError */
6106 winCurrentTimeInt64, /* xCurrentTimeInt64 */
6107 winSetSystemCall, /* xSetSystemCall */
6108 winGetSystemCall, /* xGetSystemCall */
6109 winNextSystemCall, /* xNextSystemCall */
6111 #endif
6112 static sqlite3_vfs winNolockVfs = {
6113 3, /* iVersion */
6114 sizeof(winFile), /* szOsFile */
6115 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
6116 0, /* pNext */
6117 "win32-none", /* zName */
6118 &winNolockAppData, /* pAppData */
6119 winOpen, /* xOpen */
6120 winDelete, /* xDelete */
6121 winAccess, /* xAccess */
6122 winFullPathname, /* xFullPathname */
6123 winDlOpen, /* xDlOpen */
6124 winDlError, /* xDlError */
6125 winDlSym, /* xDlSym */
6126 winDlClose, /* xDlClose */
6127 winRandomness, /* xRandomness */
6128 winSleep, /* xSleep */
6129 winCurrentTime, /* xCurrentTime */
6130 winGetLastError, /* xGetLastError */
6131 winCurrentTimeInt64, /* xCurrentTimeInt64 */
6132 winSetSystemCall, /* xSetSystemCall */
6133 winGetSystemCall, /* xGetSystemCall */
6134 winNextSystemCall, /* xNextSystemCall */
6136 #if defined(SQLITE_WIN32_HAS_WIDE)
6137 static sqlite3_vfs winLongPathNolockVfs = {
6138 3, /* iVersion */
6139 sizeof(winFile), /* szOsFile */
6140 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
6141 0, /* pNext */
6142 "win32-longpath-none", /* zName */
6143 &winNolockAppData, /* pAppData */
6144 winOpen, /* xOpen */
6145 winDelete, /* xDelete */
6146 winAccess, /* xAccess */
6147 winFullPathname, /* xFullPathname */
6148 winDlOpen, /* xDlOpen */
6149 winDlError, /* xDlError */
6150 winDlSym, /* xDlSym */
6151 winDlClose, /* xDlClose */
6152 winRandomness, /* xRandomness */
6153 winSleep, /* xSleep */
6154 winCurrentTime, /* xCurrentTime */
6155 winGetLastError, /* xGetLastError */
6156 winCurrentTimeInt64, /* xCurrentTimeInt64 */
6157 winSetSystemCall, /* xSetSystemCall */
6158 winGetSystemCall, /* xGetSystemCall */
6159 winNextSystemCall, /* xNextSystemCall */
6161 #endif
6163 /* Double-check that the aSyscall[] array has been constructed
6164 ** correctly. See ticket [bb3a86e890c8e96ab] */
6165 assert( ArraySize(aSyscall)==80 );
6167 /* get memory map allocation granularity */
6168 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
6169 #if SQLITE_OS_WINRT
6170 osGetNativeSystemInfo(&winSysInfo);
6171 #else
6172 osGetSystemInfo(&winSysInfo);
6173 #endif
6174 assert( winSysInfo.dwAllocationGranularity>0 );
6175 assert( winSysInfo.dwPageSize>0 );
6177 sqlite3_vfs_register(&winVfs, 1);
6179 #if defined(SQLITE_WIN32_HAS_WIDE)
6180 sqlite3_vfs_register(&winLongPathVfs, 0);
6181 #endif
6183 sqlite3_vfs_register(&winNolockVfs, 0);
6185 #if defined(SQLITE_WIN32_HAS_WIDE)
6186 sqlite3_vfs_register(&winLongPathNolockVfs, 0);
6187 #endif
6189 #ifndef SQLITE_OMIT_WAL
6190 winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
6191 #endif
6193 return SQLITE_OK;
6196 int sqlite3_os_end(void){
6197 #if SQLITE_OS_WINRT
6198 if( sleepObj!=NULL ){
6199 osCloseHandle(sleepObj);
6200 sleepObj = NULL;
6202 #endif
6204 #ifndef SQLITE_OMIT_WAL
6205 winBigLock = 0;
6206 #endif
6208 return SQLITE_OK;
6211 #endif /* SQLITE_OS_WIN */