Snapshot of upstream SQLite 3.25.0
[sqlcipher.git] / src / os_win.c
blob2a4b613ff869b3d37212db4cd2640dbde51e2858
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; /* Usable size of mapped region */
288 sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
289 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
290 #endif
294 ** The winVfsAppData structure is used for the pAppData member for all of the
295 ** Win32 VFS variants.
297 typedef struct winVfsAppData winVfsAppData;
298 struct winVfsAppData {
299 const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
300 void *pAppData; /* The extra pAppData, if any. */
301 BOOL bNoLock; /* Non-zero if locking is disabled. */
305 ** Allowed values for winFile.ctrlFlags
307 #define WINFILE_RDONLY 0x02 /* Connection is read only */
308 #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
309 #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
312 * The size of the buffer used by sqlite3_win32_write_debug().
314 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
315 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
316 #endif
319 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
320 * various Win32 API heap functions instead of our own.
322 #ifdef SQLITE_WIN32_MALLOC
325 * If this is non-zero, an isolated heap will be created by the native Win32
326 * allocator subsystem; otherwise, the default process heap will be used. This
327 * setting has no effect when compiling for WinRT. By default, this is enabled
328 * and an isolated heap will be created to store all allocated data.
330 ******************************************************************************
331 * WARNING: It is important to note that when this setting is non-zero and the
332 * winMemShutdown function is called (e.g. by the sqlite3_shutdown
333 * function), all data that was allocated using the isolated heap will
334 * be freed immediately and any attempt to access any of that freed
335 * data will almost certainly result in an immediate access violation.
336 ******************************************************************************
338 #ifndef SQLITE_WIN32_HEAP_CREATE
339 # define SQLITE_WIN32_HEAP_CREATE (TRUE)
340 #endif
343 * This is the maximum possible initial size of the Win32-specific heap, in
344 * bytes.
346 #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
347 # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
348 #endif
351 * This is the extra space for the initial size of the Win32-specific heap,
352 * in bytes. This value may be zero.
354 #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
355 # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
356 #endif
359 * Calculate the maximum legal cache size, in pages, based on the maximum
360 * possible initial heap size and the default page size, setting aside the
361 * needed extra space.
363 #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
364 # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
365 (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
366 (SQLITE_DEFAULT_PAGE_SIZE))
367 #endif
370 * This is cache size used in the calculation of the initial size of the
371 * Win32-specific heap. It cannot be negative.
373 #ifndef SQLITE_WIN32_CACHE_SIZE
374 # if SQLITE_DEFAULT_CACHE_SIZE>=0
375 # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
376 # else
377 # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
378 # endif
379 #endif
382 * Make sure that the calculated cache size, in pages, cannot cause the
383 * initial size of the Win32-specific heap to exceed the maximum amount
384 * of memory that can be specified in the call to HeapCreate.
386 #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
387 # undef SQLITE_WIN32_CACHE_SIZE
388 # define SQLITE_WIN32_CACHE_SIZE (2000)
389 #endif
392 * The initial size of the Win32-specific heap. This value may be zero.
394 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
395 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
396 (SQLITE_DEFAULT_PAGE_SIZE) + \
397 (SQLITE_WIN32_HEAP_INIT_EXTRA))
398 #endif
401 * The maximum size of the Win32-specific heap. This value may be zero.
403 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
404 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
405 #endif
408 * The extra flags to use in calls to the Win32 heap APIs. This value may be
409 * zero for the default behavior.
411 #ifndef SQLITE_WIN32_HEAP_FLAGS
412 # define SQLITE_WIN32_HEAP_FLAGS (0)
413 #endif
417 ** The winMemData structure stores information required by the Win32-specific
418 ** sqlite3_mem_methods implementation.
420 typedef struct winMemData winMemData;
421 struct winMemData {
422 #ifndef NDEBUG
423 u32 magic1; /* Magic number to detect structure corruption. */
424 #endif
425 HANDLE hHeap; /* The handle to our heap. */
426 BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
427 #ifndef NDEBUG
428 u32 magic2; /* Magic number to detect structure corruption. */
429 #endif
432 #ifndef NDEBUG
433 #define WINMEM_MAGIC1 0x42b2830b
434 #define WINMEM_MAGIC2 0xbd4d7cf4
435 #endif
437 static struct winMemData win_mem_data = {
438 #ifndef NDEBUG
439 WINMEM_MAGIC1,
440 #endif
441 NULL, FALSE
442 #ifndef NDEBUG
443 ,WINMEM_MAGIC2
444 #endif
447 #ifndef NDEBUG
448 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
449 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
450 #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
451 #else
452 #define winMemAssertMagic()
453 #endif
455 #define winMemGetDataPtr() &win_mem_data
456 #define winMemGetHeap() win_mem_data.hHeap
457 #define winMemGetOwned() win_mem_data.bOwned
459 static void *winMemMalloc(int nBytes);
460 static void winMemFree(void *pPrior);
461 static void *winMemRealloc(void *pPrior, int nBytes);
462 static int winMemSize(void *p);
463 static int winMemRoundup(int n);
464 static int winMemInit(void *pAppData);
465 static void winMemShutdown(void *pAppData);
467 const sqlite3_mem_methods *sqlite3MemGetWin32(void);
468 #endif /* SQLITE_WIN32_MALLOC */
471 ** The following variable is (normally) set once and never changes
472 ** thereafter. It records whether the operating system is Win9x
473 ** or WinNT.
475 ** 0: Operating system unknown.
476 ** 1: Operating system is Win9x.
477 ** 2: Operating system is WinNT.
479 ** In order to facilitate testing on a WinNT system, the test fixture
480 ** can manually set this value to 1 to emulate Win98 behavior.
482 #ifdef SQLITE_TEST
483 LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
484 #else
485 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
486 #endif
488 #ifndef SYSCALL
489 # define SYSCALL sqlite3_syscall_ptr
490 #endif
493 ** This function is not available on Windows CE or WinRT.
496 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
497 # define osAreFileApisANSI() 1
498 #endif
501 ** Many system calls are accessed through pointer-to-functions so that
502 ** they may be overridden at runtime to facilitate fault injection during
503 ** testing and sandboxing. The following array holds the names and pointers
504 ** to all overrideable system calls.
506 static struct win_syscall {
507 const char *zName; /* Name of the system call */
508 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
509 sqlite3_syscall_ptr pDefault; /* Default value */
510 } aSyscall[] = {
511 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
512 { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
513 #else
514 { "AreFileApisANSI", (SYSCALL)0, 0 },
515 #endif
517 #ifndef osAreFileApisANSI
518 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
519 #endif
521 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
522 { "CharLowerW", (SYSCALL)CharLowerW, 0 },
523 #else
524 { "CharLowerW", (SYSCALL)0, 0 },
525 #endif
527 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
529 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
530 { "CharUpperW", (SYSCALL)CharUpperW, 0 },
531 #else
532 { "CharUpperW", (SYSCALL)0, 0 },
533 #endif
535 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
537 { "CloseHandle", (SYSCALL)CloseHandle, 0 },
539 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
541 #if defined(SQLITE_WIN32_HAS_ANSI)
542 { "CreateFileA", (SYSCALL)CreateFileA, 0 },
543 #else
544 { "CreateFileA", (SYSCALL)0, 0 },
545 #endif
547 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
548 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
550 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
551 { "CreateFileW", (SYSCALL)CreateFileW, 0 },
552 #else
553 { "CreateFileW", (SYSCALL)0, 0 },
554 #endif
556 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
557 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
559 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
560 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
561 SQLITE_WIN32_CREATEFILEMAPPINGA
562 { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
563 #else
564 { "CreateFileMappingA", (SYSCALL)0, 0 },
565 #endif
567 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
568 DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
570 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
571 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
572 { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
573 #else
574 { "CreateFileMappingW", (SYSCALL)0, 0 },
575 #endif
577 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
578 DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
580 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
581 { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
582 #else
583 { "CreateMutexW", (SYSCALL)0, 0 },
584 #endif
586 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
587 LPCWSTR))aSyscall[8].pCurrent)
589 #if defined(SQLITE_WIN32_HAS_ANSI)
590 { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
591 #else
592 { "DeleteFileA", (SYSCALL)0, 0 },
593 #endif
595 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
597 #if defined(SQLITE_WIN32_HAS_WIDE)
598 { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
599 #else
600 { "DeleteFileW", (SYSCALL)0, 0 },
601 #endif
603 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
605 #if SQLITE_OS_WINCE
606 { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
607 #else
608 { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
609 #endif
611 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
612 LPFILETIME))aSyscall[11].pCurrent)
614 #if SQLITE_OS_WINCE
615 { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
616 #else
617 { "FileTimeToSystemTime", (SYSCALL)0, 0 },
618 #endif
620 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
621 LPSYSTEMTIME))aSyscall[12].pCurrent)
623 { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
625 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
627 #if defined(SQLITE_WIN32_HAS_ANSI)
628 { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
629 #else
630 { "FormatMessageA", (SYSCALL)0, 0 },
631 #endif
633 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
634 DWORD,va_list*))aSyscall[14].pCurrent)
636 #if defined(SQLITE_WIN32_HAS_WIDE)
637 { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
638 #else
639 { "FormatMessageW", (SYSCALL)0, 0 },
640 #endif
642 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
643 DWORD,va_list*))aSyscall[15].pCurrent)
645 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
646 { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
647 #else
648 { "FreeLibrary", (SYSCALL)0, 0 },
649 #endif
651 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
653 { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
655 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
657 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
658 { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
659 #else
660 { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
661 #endif
663 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
664 LPDWORD))aSyscall[18].pCurrent)
666 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
667 { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
668 #else
669 { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
670 #endif
672 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
673 LPDWORD))aSyscall[19].pCurrent)
675 #if defined(SQLITE_WIN32_HAS_ANSI)
676 { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
677 #else
678 { "GetFileAttributesA", (SYSCALL)0, 0 },
679 #endif
681 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
683 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
684 { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
685 #else
686 { "GetFileAttributesW", (SYSCALL)0, 0 },
687 #endif
689 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
691 #if defined(SQLITE_WIN32_HAS_WIDE)
692 { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
693 #else
694 { "GetFileAttributesExW", (SYSCALL)0, 0 },
695 #endif
697 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
698 LPVOID))aSyscall[22].pCurrent)
700 #if !SQLITE_OS_WINRT
701 { "GetFileSize", (SYSCALL)GetFileSize, 0 },
702 #else
703 { "GetFileSize", (SYSCALL)0, 0 },
704 #endif
706 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
708 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
709 { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
710 #else
711 { "GetFullPathNameA", (SYSCALL)0, 0 },
712 #endif
714 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
715 LPSTR*))aSyscall[24].pCurrent)
717 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
718 { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
719 #else
720 { "GetFullPathNameW", (SYSCALL)0, 0 },
721 #endif
723 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
724 LPWSTR*))aSyscall[25].pCurrent)
726 { "GetLastError", (SYSCALL)GetLastError, 0 },
728 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
730 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
731 #if SQLITE_OS_WINCE
732 /* The GetProcAddressA() routine is only available on Windows CE. */
733 { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
734 #else
735 /* All other Windows platforms expect GetProcAddress() to take
736 ** an ANSI string regardless of the _UNICODE setting */
737 { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
738 #endif
739 #else
740 { "GetProcAddressA", (SYSCALL)0, 0 },
741 #endif
743 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
744 LPCSTR))aSyscall[27].pCurrent)
746 #if !SQLITE_OS_WINRT
747 { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
748 #else
749 { "GetSystemInfo", (SYSCALL)0, 0 },
750 #endif
752 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
754 { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
756 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
758 #if !SQLITE_OS_WINCE
759 { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
760 #else
761 { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
762 #endif
764 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
765 LPFILETIME))aSyscall[30].pCurrent)
767 #if defined(SQLITE_WIN32_HAS_ANSI)
768 { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
769 #else
770 { "GetTempPathA", (SYSCALL)0, 0 },
771 #endif
773 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
775 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
776 { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
777 #else
778 { "GetTempPathW", (SYSCALL)0, 0 },
779 #endif
781 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
783 #if !SQLITE_OS_WINRT
784 { "GetTickCount", (SYSCALL)GetTickCount, 0 },
785 #else
786 { "GetTickCount", (SYSCALL)0, 0 },
787 #endif
789 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
791 #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
792 { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
793 #else
794 { "GetVersionExA", (SYSCALL)0, 0 },
795 #endif
797 #define osGetVersionExA ((BOOL(WINAPI*)( \
798 LPOSVERSIONINFOA))aSyscall[34].pCurrent)
800 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
801 SQLITE_WIN32_GETVERSIONEX
802 { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
803 #else
804 { "GetVersionExW", (SYSCALL)0, 0 },
805 #endif
807 #define osGetVersionExW ((BOOL(WINAPI*)( \
808 LPOSVERSIONINFOW))aSyscall[35].pCurrent)
810 { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
812 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
813 SIZE_T))aSyscall[36].pCurrent)
815 #if !SQLITE_OS_WINRT
816 { "HeapCreate", (SYSCALL)HeapCreate, 0 },
817 #else
818 { "HeapCreate", (SYSCALL)0, 0 },
819 #endif
821 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
822 SIZE_T))aSyscall[37].pCurrent)
824 #if !SQLITE_OS_WINRT
825 { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
826 #else
827 { "HeapDestroy", (SYSCALL)0, 0 },
828 #endif
830 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
832 { "HeapFree", (SYSCALL)HeapFree, 0 },
834 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
836 { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
838 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
839 SIZE_T))aSyscall[40].pCurrent)
841 { "HeapSize", (SYSCALL)HeapSize, 0 },
843 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
844 LPCVOID))aSyscall[41].pCurrent)
846 #if !SQLITE_OS_WINRT
847 { "HeapValidate", (SYSCALL)HeapValidate, 0 },
848 #else
849 { "HeapValidate", (SYSCALL)0, 0 },
850 #endif
852 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
853 LPCVOID))aSyscall[42].pCurrent)
855 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
856 { "HeapCompact", (SYSCALL)HeapCompact, 0 },
857 #else
858 { "HeapCompact", (SYSCALL)0, 0 },
859 #endif
861 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
863 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
864 { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
865 #else
866 { "LoadLibraryA", (SYSCALL)0, 0 },
867 #endif
869 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
871 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
872 !defined(SQLITE_OMIT_LOAD_EXTENSION)
873 { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
874 #else
875 { "LoadLibraryW", (SYSCALL)0, 0 },
876 #endif
878 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
880 #if !SQLITE_OS_WINRT
881 { "LocalFree", (SYSCALL)LocalFree, 0 },
882 #else
883 { "LocalFree", (SYSCALL)0, 0 },
884 #endif
886 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
888 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
889 { "LockFile", (SYSCALL)LockFile, 0 },
890 #else
891 { "LockFile", (SYSCALL)0, 0 },
892 #endif
894 #ifndef osLockFile
895 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
896 DWORD))aSyscall[47].pCurrent)
897 #endif
899 #if !SQLITE_OS_WINCE
900 { "LockFileEx", (SYSCALL)LockFileEx, 0 },
901 #else
902 { "LockFileEx", (SYSCALL)0, 0 },
903 #endif
905 #ifndef osLockFileEx
906 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
907 LPOVERLAPPED))aSyscall[48].pCurrent)
908 #endif
910 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
911 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
912 { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
913 #else
914 { "MapViewOfFile", (SYSCALL)0, 0 },
915 #endif
917 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
918 SIZE_T))aSyscall[49].pCurrent)
920 { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
922 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
923 int))aSyscall[50].pCurrent)
925 { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
927 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
928 LARGE_INTEGER*))aSyscall[51].pCurrent)
930 { "ReadFile", (SYSCALL)ReadFile, 0 },
932 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
933 LPOVERLAPPED))aSyscall[52].pCurrent)
935 { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
937 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
939 #if !SQLITE_OS_WINRT
940 { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
941 #else
942 { "SetFilePointer", (SYSCALL)0, 0 },
943 #endif
945 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
946 DWORD))aSyscall[54].pCurrent)
948 #if !SQLITE_OS_WINRT
949 { "Sleep", (SYSCALL)Sleep, 0 },
950 #else
951 { "Sleep", (SYSCALL)0, 0 },
952 #endif
954 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
956 { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
958 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
959 LPFILETIME))aSyscall[56].pCurrent)
961 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
962 { "UnlockFile", (SYSCALL)UnlockFile, 0 },
963 #else
964 { "UnlockFile", (SYSCALL)0, 0 },
965 #endif
967 #ifndef osUnlockFile
968 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
969 DWORD))aSyscall[57].pCurrent)
970 #endif
972 #if !SQLITE_OS_WINCE
973 { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
974 #else
975 { "UnlockFileEx", (SYSCALL)0, 0 },
976 #endif
978 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
979 LPOVERLAPPED))aSyscall[58].pCurrent)
981 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
982 { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
983 #else
984 { "UnmapViewOfFile", (SYSCALL)0, 0 },
985 #endif
987 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
989 { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
991 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
992 LPCSTR,LPBOOL))aSyscall[60].pCurrent)
994 { "WriteFile", (SYSCALL)WriteFile, 0 },
996 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
997 LPOVERLAPPED))aSyscall[61].pCurrent)
999 #if SQLITE_OS_WINRT
1000 { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
1001 #else
1002 { "CreateEventExW", (SYSCALL)0, 0 },
1003 #endif
1005 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
1006 DWORD,DWORD))aSyscall[62].pCurrent)
1008 #if !SQLITE_OS_WINRT
1009 { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
1010 #else
1011 { "WaitForSingleObject", (SYSCALL)0, 0 },
1012 #endif
1014 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
1015 DWORD))aSyscall[63].pCurrent)
1017 #if !SQLITE_OS_WINCE
1018 { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
1019 #else
1020 { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
1021 #endif
1023 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
1024 BOOL))aSyscall[64].pCurrent)
1026 #if SQLITE_OS_WINRT
1027 { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
1028 #else
1029 { "SetFilePointerEx", (SYSCALL)0, 0 },
1030 #endif
1032 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
1033 PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
1035 #if SQLITE_OS_WINRT
1036 { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
1037 #else
1038 { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
1039 #endif
1041 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
1042 FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
1044 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
1045 { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
1046 #else
1047 { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
1048 #endif
1050 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
1051 SIZE_T))aSyscall[67].pCurrent)
1053 #if SQLITE_OS_WINRT
1054 { "CreateFile2", (SYSCALL)CreateFile2, 0 },
1055 #else
1056 { "CreateFile2", (SYSCALL)0, 0 },
1057 #endif
1059 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
1060 LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
1062 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
1063 { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
1064 #else
1065 { "LoadPackagedLibrary", (SYSCALL)0, 0 },
1066 #endif
1068 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
1069 DWORD))aSyscall[69].pCurrent)
1071 #if SQLITE_OS_WINRT
1072 { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
1073 #else
1074 { "GetTickCount64", (SYSCALL)0, 0 },
1075 #endif
1077 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
1079 #if SQLITE_OS_WINRT
1080 { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
1081 #else
1082 { "GetNativeSystemInfo", (SYSCALL)0, 0 },
1083 #endif
1085 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
1086 LPSYSTEM_INFO))aSyscall[71].pCurrent)
1088 #if defined(SQLITE_WIN32_HAS_ANSI)
1089 { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
1090 #else
1091 { "OutputDebugStringA", (SYSCALL)0, 0 },
1092 #endif
1094 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
1096 #if defined(SQLITE_WIN32_HAS_WIDE)
1097 { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
1098 #else
1099 { "OutputDebugStringW", (SYSCALL)0, 0 },
1100 #endif
1102 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
1104 { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
1106 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
1108 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
1109 { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
1110 #else
1111 { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
1112 #endif
1114 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
1115 LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
1118 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
1119 ** is really just a macro that uses a compiler intrinsic (e.g. x64).
1120 ** So do not try to make this is into a redefinable interface.
1122 #if defined(InterlockedCompareExchange)
1123 { "InterlockedCompareExchange", (SYSCALL)0, 0 },
1125 #define osInterlockedCompareExchange InterlockedCompareExchange
1126 #else
1127 { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
1129 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
1130 SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
1131 #endif /* defined(InterlockedCompareExchange) */
1133 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
1134 { "UuidCreate", (SYSCALL)UuidCreate, 0 },
1135 #else
1136 { "UuidCreate", (SYSCALL)0, 0 },
1137 #endif
1139 #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
1141 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
1142 { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
1143 #else
1144 { "UuidCreateSequential", (SYSCALL)0, 0 },
1145 #endif
1147 #define osUuidCreateSequential \
1148 ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
1150 #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
1151 { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
1152 #else
1153 { "FlushViewOfFile", (SYSCALL)0, 0 },
1154 #endif
1156 #define osFlushViewOfFile \
1157 ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
1159 }; /* End of the overrideable system calls */
1162 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
1163 ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
1164 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
1165 ** system call named zName.
1167 static int winSetSystemCall(
1168 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
1169 const char *zName, /* Name of system call to override */
1170 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
1172 unsigned int i;
1173 int rc = SQLITE_NOTFOUND;
1175 UNUSED_PARAMETER(pNotUsed);
1176 if( zName==0 ){
1177 /* If no zName is given, restore all system calls to their default
1178 ** settings and return NULL
1180 rc = SQLITE_OK;
1181 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
1182 if( aSyscall[i].pDefault ){
1183 aSyscall[i].pCurrent = aSyscall[i].pDefault;
1186 }else{
1187 /* If zName is specified, operate on only the one system call
1188 ** specified.
1190 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
1191 if( strcmp(zName, aSyscall[i].zName)==0 ){
1192 if( aSyscall[i].pDefault==0 ){
1193 aSyscall[i].pDefault = aSyscall[i].pCurrent;
1195 rc = SQLITE_OK;
1196 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
1197 aSyscall[i].pCurrent = pNewFunc;
1198 break;
1202 return rc;
1206 ** Return the value of a system call. Return NULL if zName is not a
1207 ** recognized system call name. NULL is also returned if the system call
1208 ** is currently undefined.
1210 static sqlite3_syscall_ptr winGetSystemCall(
1211 sqlite3_vfs *pNotUsed,
1212 const char *zName
1214 unsigned int i;
1216 UNUSED_PARAMETER(pNotUsed);
1217 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
1218 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
1220 return 0;
1224 ** Return the name of the first system call after zName. If zName==NULL
1225 ** then return the name of the first system call. Return NULL if zName
1226 ** is the last system call or if zName is not the name of a valid
1227 ** system call.
1229 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
1230 int i = -1;
1232 UNUSED_PARAMETER(p);
1233 if( zName ){
1234 for(i=0; i<ArraySize(aSyscall)-1; i++){
1235 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
1238 for(i++; i<ArraySize(aSyscall); i++){
1239 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
1241 return 0;
1244 #ifdef SQLITE_WIN32_MALLOC
1246 ** If a Win32 native heap has been configured, this function will attempt to
1247 ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
1248 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
1249 ** "pnLargest" argument, if non-zero, will be used to return the size of the
1250 ** largest committed free block in the heap, in bytes.
1252 int sqlite3_win32_compact_heap(LPUINT pnLargest){
1253 int rc = SQLITE_OK;
1254 UINT nLargest = 0;
1255 HANDLE hHeap;
1257 winMemAssertMagic();
1258 hHeap = winMemGetHeap();
1259 assert( hHeap!=0 );
1260 assert( hHeap!=INVALID_HANDLE_VALUE );
1261 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1262 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1263 #endif
1264 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
1265 if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
1266 DWORD lastErrno = osGetLastError();
1267 if( lastErrno==NO_ERROR ){
1268 sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
1269 (void*)hHeap);
1270 rc = SQLITE_NOMEM_BKPT;
1271 }else{
1272 sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
1273 osGetLastError(), (void*)hHeap);
1274 rc = SQLITE_ERROR;
1277 #else
1278 sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
1279 (void*)hHeap);
1280 rc = SQLITE_NOTFOUND;
1281 #endif
1282 if( pnLargest ) *pnLargest = nLargest;
1283 return rc;
1287 ** If a Win32 native heap has been configured, this function will attempt to
1288 ** destroy and recreate it. If the Win32 native heap is not isolated and/or
1289 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
1290 ** be returned and no changes will be made to the Win32 native heap.
1292 int sqlite3_win32_reset_heap(){
1293 int rc;
1294 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
1295 MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
1296 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
1297 MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
1298 sqlite3_mutex_enter(pMaster);
1299 sqlite3_mutex_enter(pMem);
1300 winMemAssertMagic();
1301 if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
1303 ** At this point, there should be no outstanding memory allocations on
1304 ** the heap. Also, since both the master and memsys locks are currently
1305 ** being held by us, no other function (i.e. from another thread) should
1306 ** be able to even access the heap. Attempt to destroy and recreate our
1307 ** isolated Win32 native heap now.
1309 assert( winMemGetHeap()!=NULL );
1310 assert( winMemGetOwned() );
1311 assert( sqlite3_memory_used()==0 );
1312 winMemShutdown(winMemGetDataPtr());
1313 assert( winMemGetHeap()==NULL );
1314 assert( !winMemGetOwned() );
1315 assert( sqlite3_memory_used()==0 );
1316 rc = winMemInit(winMemGetDataPtr());
1317 assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
1318 assert( rc!=SQLITE_OK || winMemGetOwned() );
1319 assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
1320 }else{
1322 ** The Win32 native heap cannot be modified because it may be in use.
1324 rc = SQLITE_BUSY;
1326 sqlite3_mutex_leave(pMem);
1327 sqlite3_mutex_leave(pMaster);
1328 return rc;
1330 #endif /* SQLITE_WIN32_MALLOC */
1333 ** This function outputs the specified (ANSI) string to the Win32 debugger
1334 ** (if available).
1337 void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
1338 char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
1339 int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
1340 if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
1341 assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
1342 #ifdef SQLITE_ENABLE_API_ARMOR
1343 if( !zBuf ){
1344 (void)SQLITE_MISUSE_BKPT;
1345 return;
1347 #endif
1348 #if defined(SQLITE_WIN32_HAS_ANSI)
1349 if( nMin>0 ){
1350 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
1351 memcpy(zDbgBuf, zBuf, nMin);
1352 osOutputDebugStringA(zDbgBuf);
1353 }else{
1354 osOutputDebugStringA(zBuf);
1356 #elif defined(SQLITE_WIN32_HAS_WIDE)
1357 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
1358 if ( osMultiByteToWideChar(
1359 osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
1360 nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
1361 return;
1363 osOutputDebugStringW((LPCWSTR)zDbgBuf);
1364 #else
1365 if( nMin>0 ){
1366 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
1367 memcpy(zDbgBuf, zBuf, nMin);
1368 fprintf(stderr, "%s", zDbgBuf);
1369 }else{
1370 fprintf(stderr, "%s", zBuf);
1372 #endif
1376 ** The following routine suspends the current thread for at least ms
1377 ** milliseconds. This is equivalent to the Win32 Sleep() interface.
1379 #if SQLITE_OS_WINRT
1380 static HANDLE sleepObj = NULL;
1381 #endif
1383 void sqlite3_win32_sleep(DWORD milliseconds){
1384 #if SQLITE_OS_WINRT
1385 if ( sleepObj==NULL ){
1386 sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
1387 SYNCHRONIZE);
1389 assert( sleepObj!=NULL );
1390 osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
1391 #else
1392 osSleep(milliseconds);
1393 #endif
1396 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
1397 SQLITE_THREADSAFE>0
1398 DWORD sqlite3Win32Wait(HANDLE hObject){
1399 DWORD rc;
1400 while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
1401 TRUE))==WAIT_IO_COMPLETION ){}
1402 return rc;
1404 #endif
1407 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
1408 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
1410 ** Here is an interesting observation: Win95, Win98, and WinME lack
1411 ** the LockFileEx() API. But we can still statically link against that
1412 ** API as long as we don't call it when running Win95/98/ME. A call to
1413 ** this routine is used to determine if the host is Win95/98/ME or
1414 ** WinNT/2K/XP so that we will know whether or not we can safely call
1415 ** the LockFileEx() API.
1418 #if !SQLITE_WIN32_GETVERSIONEX
1419 # define osIsNT() (1)
1420 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
1421 # define osIsNT() (1)
1422 #elif !defined(SQLITE_WIN32_HAS_WIDE)
1423 # define osIsNT() (0)
1424 #else
1425 # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
1426 #endif
1429 ** This function determines if the machine is running a version of Windows
1430 ** based on the NT kernel.
1432 int sqlite3_win32_is_nt(void){
1433 #if SQLITE_OS_WINRT
1435 ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
1436 ** kernel.
1438 return 1;
1439 #elif SQLITE_WIN32_GETVERSIONEX
1440 if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
1441 #if defined(SQLITE_WIN32_HAS_ANSI)
1442 OSVERSIONINFOA sInfo;
1443 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
1444 osGetVersionExA(&sInfo);
1445 osInterlockedCompareExchange(&sqlite3_os_type,
1446 (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
1447 #elif defined(SQLITE_WIN32_HAS_WIDE)
1448 OSVERSIONINFOW sInfo;
1449 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
1450 osGetVersionExW(&sInfo);
1451 osInterlockedCompareExchange(&sqlite3_os_type,
1452 (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
1453 #endif
1455 return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
1456 #elif SQLITE_TEST
1457 return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
1458 #else
1460 ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
1461 ** deprecated are always assumed to be based on the NT kernel.
1463 return 1;
1464 #endif
1467 #ifdef SQLITE_WIN32_MALLOC
1469 ** Allocate nBytes of memory.
1471 static void *winMemMalloc(int nBytes){
1472 HANDLE hHeap;
1473 void *p;
1475 winMemAssertMagic();
1476 hHeap = winMemGetHeap();
1477 assert( hHeap!=0 );
1478 assert( hHeap!=INVALID_HANDLE_VALUE );
1479 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1480 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1481 #endif
1482 assert( nBytes>=0 );
1483 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
1484 if( !p ){
1485 sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
1486 nBytes, osGetLastError(), (void*)hHeap);
1488 return p;
1492 ** Free memory.
1494 static void winMemFree(void *pPrior){
1495 HANDLE hHeap;
1497 winMemAssertMagic();
1498 hHeap = winMemGetHeap();
1499 assert( hHeap!=0 );
1500 assert( hHeap!=INVALID_HANDLE_VALUE );
1501 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1502 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
1503 #endif
1504 if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
1505 if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
1506 sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
1507 pPrior, osGetLastError(), (void*)hHeap);
1512 ** Change the size of an existing memory allocation
1514 static void *winMemRealloc(void *pPrior, int nBytes){
1515 HANDLE hHeap;
1516 void *p;
1518 winMemAssertMagic();
1519 hHeap = winMemGetHeap();
1520 assert( hHeap!=0 );
1521 assert( hHeap!=INVALID_HANDLE_VALUE );
1522 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1523 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
1524 #endif
1525 assert( nBytes>=0 );
1526 if( !pPrior ){
1527 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
1528 }else{
1529 p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
1531 if( !p ){
1532 sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
1533 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
1534 (void*)hHeap);
1536 return p;
1540 ** Return the size of an outstanding allocation, in bytes.
1542 static int winMemSize(void *p){
1543 HANDLE hHeap;
1544 SIZE_T n;
1546 winMemAssertMagic();
1547 hHeap = winMemGetHeap();
1548 assert( hHeap!=0 );
1549 assert( hHeap!=INVALID_HANDLE_VALUE );
1550 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1551 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
1552 #endif
1553 if( !p ) return 0;
1554 n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
1555 if( n==(SIZE_T)-1 ){
1556 sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
1557 p, osGetLastError(), (void*)hHeap);
1558 return 0;
1560 return (int)n;
1564 ** Round up a request size to the next valid allocation size.
1566 static int winMemRoundup(int n){
1567 return n;
1571 ** Initialize this module.
1573 static int winMemInit(void *pAppData){
1574 winMemData *pWinMemData = (winMemData *)pAppData;
1576 if( !pWinMemData ) return SQLITE_ERROR;
1577 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
1578 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
1580 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
1581 if( !pWinMemData->hHeap ){
1582 DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
1583 DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
1584 if( dwMaximumSize==0 ){
1585 dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
1586 }else if( dwInitialSize>dwMaximumSize ){
1587 dwInitialSize = dwMaximumSize;
1589 pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
1590 dwInitialSize, dwMaximumSize);
1591 if( !pWinMemData->hHeap ){
1592 sqlite3_log(SQLITE_NOMEM,
1593 "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
1594 osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
1595 dwMaximumSize);
1596 return SQLITE_NOMEM_BKPT;
1598 pWinMemData->bOwned = TRUE;
1599 assert( pWinMemData->bOwned );
1601 #else
1602 pWinMemData->hHeap = osGetProcessHeap();
1603 if( !pWinMemData->hHeap ){
1604 sqlite3_log(SQLITE_NOMEM,
1605 "failed to GetProcessHeap (%lu)", osGetLastError());
1606 return SQLITE_NOMEM_BKPT;
1608 pWinMemData->bOwned = FALSE;
1609 assert( !pWinMemData->bOwned );
1610 #endif
1611 assert( pWinMemData->hHeap!=0 );
1612 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
1613 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1614 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1615 #endif
1616 return SQLITE_OK;
1620 ** Deinitialize this module.
1622 static void winMemShutdown(void *pAppData){
1623 winMemData *pWinMemData = (winMemData *)pAppData;
1625 if( !pWinMemData ) return;
1626 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
1627 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
1629 if( pWinMemData->hHeap ){
1630 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
1631 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1632 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1633 #endif
1634 if( pWinMemData->bOwned ){
1635 if( !osHeapDestroy(pWinMemData->hHeap) ){
1636 sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
1637 osGetLastError(), (void*)pWinMemData->hHeap);
1639 pWinMemData->bOwned = FALSE;
1641 pWinMemData->hHeap = NULL;
1646 ** Populate the low-level memory allocation function pointers in
1647 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
1648 ** arguments specify the block of memory to manage.
1650 ** This routine is only called by sqlite3_config(), and therefore
1651 ** is not required to be threadsafe (it is not).
1653 const sqlite3_mem_methods *sqlite3MemGetWin32(void){
1654 static const sqlite3_mem_methods winMemMethods = {
1655 winMemMalloc,
1656 winMemFree,
1657 winMemRealloc,
1658 winMemSize,
1659 winMemRoundup,
1660 winMemInit,
1661 winMemShutdown,
1662 &win_mem_data
1664 return &winMemMethods;
1667 void sqlite3MemSetDefault(void){
1668 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
1670 #endif /* SQLITE_WIN32_MALLOC */
1673 ** Convert a UTF-8 string to Microsoft Unicode.
1675 ** Space to hold the returned string is obtained from sqlite3_malloc().
1677 static LPWSTR winUtf8ToUnicode(const char *zText){
1678 int nChar;
1679 LPWSTR zWideText;
1681 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
1682 if( nChar==0 ){
1683 return 0;
1685 zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
1686 if( zWideText==0 ){
1687 return 0;
1689 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
1690 nChar);
1691 if( nChar==0 ){
1692 sqlite3_free(zWideText);
1693 zWideText = 0;
1695 return zWideText;
1699 ** Convert a Microsoft Unicode string to UTF-8.
1701 ** Space to hold the returned string is obtained from sqlite3_malloc().
1703 static char *winUnicodeToUtf8(LPCWSTR zWideText){
1704 int nByte;
1705 char *zText;
1707 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
1708 if( nByte == 0 ){
1709 return 0;
1711 zText = sqlite3MallocZero( nByte );
1712 if( zText==0 ){
1713 return 0;
1715 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
1716 0, 0);
1717 if( nByte == 0 ){
1718 sqlite3_free(zText);
1719 zText = 0;
1721 return zText;
1725 ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
1726 ** code page.
1728 ** Space to hold the returned string is obtained from sqlite3_malloc().
1730 static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
1731 int nByte;
1732 LPWSTR zMbcsText;
1733 int codepage = useAnsi ? CP_ACP : CP_OEMCP;
1735 nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
1736 0)*sizeof(WCHAR);
1737 if( nByte==0 ){
1738 return 0;
1740 zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
1741 if( zMbcsText==0 ){
1742 return 0;
1744 nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
1745 nByte);
1746 if( nByte==0 ){
1747 sqlite3_free(zMbcsText);
1748 zMbcsText = 0;
1750 return zMbcsText;
1754 ** Convert a Microsoft Unicode string to a multi-byte character string,
1755 ** using the ANSI or OEM code page.
1757 ** Space to hold the returned string is obtained from sqlite3_malloc().
1759 static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
1760 int nByte;
1761 char *zText;
1762 int codepage = useAnsi ? CP_ACP : CP_OEMCP;
1764 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
1765 if( nByte == 0 ){
1766 return 0;
1768 zText = sqlite3MallocZero( nByte );
1769 if( zText==0 ){
1770 return 0;
1772 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
1773 nByte, 0, 0);
1774 if( nByte == 0 ){
1775 sqlite3_free(zText);
1776 zText = 0;
1778 return zText;
1782 ** Convert a multi-byte character string to UTF-8.
1784 ** Space to hold the returned string is obtained from sqlite3_malloc().
1786 static char *winMbcsToUtf8(const char *zText, int useAnsi){
1787 char *zTextUtf8;
1788 LPWSTR zTmpWide;
1790 zTmpWide = winMbcsToUnicode(zText, useAnsi);
1791 if( zTmpWide==0 ){
1792 return 0;
1794 zTextUtf8 = winUnicodeToUtf8(zTmpWide);
1795 sqlite3_free(zTmpWide);
1796 return zTextUtf8;
1800 ** Convert a UTF-8 string to a multi-byte character string.
1802 ** Space to hold the returned string is obtained from sqlite3_malloc().
1804 static char *winUtf8ToMbcs(const char *zText, int useAnsi){
1805 char *zTextMbcs;
1806 LPWSTR zTmpWide;
1808 zTmpWide = winUtf8ToUnicode(zText);
1809 if( zTmpWide==0 ){
1810 return 0;
1812 zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
1813 sqlite3_free(zTmpWide);
1814 return zTextMbcs;
1818 ** This is a public wrapper for the winUtf8ToUnicode() function.
1820 LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
1821 #ifdef SQLITE_ENABLE_API_ARMOR
1822 if( !zText ){
1823 (void)SQLITE_MISUSE_BKPT;
1824 return 0;
1826 #endif
1827 #ifndef SQLITE_OMIT_AUTOINIT
1828 if( sqlite3_initialize() ) return 0;
1829 #endif
1830 return winUtf8ToUnicode(zText);
1834 ** This is a public wrapper for the winUnicodeToUtf8() function.
1836 char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
1837 #ifdef SQLITE_ENABLE_API_ARMOR
1838 if( !zWideText ){
1839 (void)SQLITE_MISUSE_BKPT;
1840 return 0;
1842 #endif
1843 #ifndef SQLITE_OMIT_AUTOINIT
1844 if( sqlite3_initialize() ) return 0;
1845 #endif
1846 return winUnicodeToUtf8(zWideText);
1850 ** This is a public wrapper for the winMbcsToUtf8() function.
1852 char *sqlite3_win32_mbcs_to_utf8(const char *zText){
1853 #ifdef SQLITE_ENABLE_API_ARMOR
1854 if( !zText ){
1855 (void)SQLITE_MISUSE_BKPT;
1856 return 0;
1858 #endif
1859 #ifndef SQLITE_OMIT_AUTOINIT
1860 if( sqlite3_initialize() ) return 0;
1861 #endif
1862 return winMbcsToUtf8(zText, osAreFileApisANSI());
1866 ** This is a public wrapper for the winMbcsToUtf8() function.
1868 char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
1869 #ifdef SQLITE_ENABLE_API_ARMOR
1870 if( !zText ){
1871 (void)SQLITE_MISUSE_BKPT;
1872 return 0;
1874 #endif
1875 #ifndef SQLITE_OMIT_AUTOINIT
1876 if( sqlite3_initialize() ) return 0;
1877 #endif
1878 return winMbcsToUtf8(zText, useAnsi);
1882 ** This is a public wrapper for the winUtf8ToMbcs() function.
1884 char *sqlite3_win32_utf8_to_mbcs(const char *zText){
1885 #ifdef SQLITE_ENABLE_API_ARMOR
1886 if( !zText ){
1887 (void)SQLITE_MISUSE_BKPT;
1888 return 0;
1890 #endif
1891 #ifndef SQLITE_OMIT_AUTOINIT
1892 if( sqlite3_initialize() ) return 0;
1893 #endif
1894 return winUtf8ToMbcs(zText, osAreFileApisANSI());
1898 ** This is a public wrapper for the winUtf8ToMbcs() function.
1900 char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
1901 #ifdef SQLITE_ENABLE_API_ARMOR
1902 if( !zText ){
1903 (void)SQLITE_MISUSE_BKPT;
1904 return 0;
1906 #endif
1907 #ifndef SQLITE_OMIT_AUTOINIT
1908 if( sqlite3_initialize() ) return 0;
1909 #endif
1910 return winUtf8ToMbcs(zText, useAnsi);
1914 ** This function is the same as sqlite3_win32_set_directory (below); however,
1915 ** it accepts a UTF-8 string.
1917 int sqlite3_win32_set_directory8(
1918 unsigned long type, /* Identifier for directory being set or reset */
1919 const char *zValue /* New value for directory being set or reset */
1921 char **ppDirectory = 0;
1922 #ifndef SQLITE_OMIT_AUTOINIT
1923 int rc = sqlite3_initialize();
1924 if( rc ) return rc;
1925 #endif
1926 if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
1927 ppDirectory = &sqlite3_data_directory;
1928 }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
1929 ppDirectory = &sqlite3_temp_directory;
1931 assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
1932 || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
1934 assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
1935 if( ppDirectory ){
1936 char *zCopy = 0;
1937 if( zValue && zValue[0] ){
1938 zCopy = sqlite3_mprintf("%s", zValue);
1939 if ( zCopy==0 ){
1940 return SQLITE_NOMEM_BKPT;
1943 sqlite3_free(*ppDirectory);
1944 *ppDirectory = zCopy;
1945 return SQLITE_OK;
1947 return SQLITE_ERROR;
1951 ** This function is the same as sqlite3_win32_set_directory (below); however,
1952 ** it accepts a UTF-16 string.
1954 int sqlite3_win32_set_directory16(
1955 unsigned long type, /* Identifier for directory being set or reset */
1956 const void *zValue /* New value for directory being set or reset */
1958 int rc;
1959 char *zUtf8 = 0;
1960 if( zValue ){
1961 zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);
1962 if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;
1964 rc = sqlite3_win32_set_directory8(type, zUtf8);
1965 if( zUtf8 ) sqlite3_free(zUtf8);
1966 return rc;
1970 ** This function sets the data directory or the temporary directory based on
1971 ** the provided arguments. The type argument must be 1 in order to set the
1972 ** data directory or 2 in order to set the temporary directory. The zValue
1973 ** argument is the name of the directory to use. The return value will be
1974 ** SQLITE_OK if successful.
1976 int sqlite3_win32_set_directory(
1977 unsigned long type, /* Identifier for directory being set or reset */
1978 void *zValue /* New value for directory being set or reset */
1980 return sqlite3_win32_set_directory16(type, zValue);
1984 ** The return value of winGetLastErrorMsg
1985 ** is zero if the error message fits in the buffer, or non-zero
1986 ** otherwise (if the message was truncated).
1988 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
1989 /* FormatMessage returns 0 on failure. Otherwise it
1990 ** returns the number of TCHARs written to the output
1991 ** buffer, excluding the terminating null char.
1993 DWORD dwLen = 0;
1994 char *zOut = 0;
1996 if( osIsNT() ){
1997 #if SQLITE_OS_WINRT
1998 WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
1999 dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
2000 FORMAT_MESSAGE_IGNORE_INSERTS,
2001 NULL,
2002 lastErrno,
2004 zTempWide,
2005 SQLITE_WIN32_MAX_ERRMSG_CHARS,
2007 #else
2008 LPWSTR zTempWide = NULL;
2009 dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2010 FORMAT_MESSAGE_FROM_SYSTEM |
2011 FORMAT_MESSAGE_IGNORE_INSERTS,
2012 NULL,
2013 lastErrno,
2015 (LPWSTR) &zTempWide,
2018 #endif
2019 if( dwLen > 0 ){
2020 /* allocate a buffer and convert to UTF8 */
2021 sqlite3BeginBenignMalloc();
2022 zOut = winUnicodeToUtf8(zTempWide);
2023 sqlite3EndBenignMalloc();
2024 #if !SQLITE_OS_WINRT
2025 /* free the system buffer allocated by FormatMessage */
2026 osLocalFree(zTempWide);
2027 #endif
2030 #ifdef SQLITE_WIN32_HAS_ANSI
2031 else{
2032 char *zTemp = NULL;
2033 dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2034 FORMAT_MESSAGE_FROM_SYSTEM |
2035 FORMAT_MESSAGE_IGNORE_INSERTS,
2036 NULL,
2037 lastErrno,
2039 (LPSTR) &zTemp,
2042 if( dwLen > 0 ){
2043 /* allocate a buffer and convert to UTF8 */
2044 sqlite3BeginBenignMalloc();
2045 zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
2046 sqlite3EndBenignMalloc();
2047 /* free the system buffer allocated by FormatMessage */
2048 osLocalFree(zTemp);
2051 #endif
2052 if( 0 == dwLen ){
2053 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
2054 }else{
2055 /* copy a maximum of nBuf chars to output buffer */
2056 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
2057 /* free the UTF8 buffer */
2058 sqlite3_free(zOut);
2060 return 0;
2065 ** This function - winLogErrorAtLine() - is only ever called via the macro
2066 ** winLogError().
2068 ** This routine is invoked after an error occurs in an OS function.
2069 ** It logs a message using sqlite3_log() containing the current value of
2070 ** error code and, if possible, the human-readable equivalent from
2071 ** FormatMessage.
2073 ** The first argument passed to the macro should be the error code that
2074 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
2075 ** The two subsequent arguments should be the name of the OS function that
2076 ** failed and the associated file-system path, if any.
2078 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
2079 static int winLogErrorAtLine(
2080 int errcode, /* SQLite error code */
2081 DWORD lastErrno, /* Win32 last error */
2082 const char *zFunc, /* Name of OS function that failed */
2083 const char *zPath, /* File path associated with error */
2084 int iLine /* Source line number where error occurred */
2086 char zMsg[500]; /* Human readable error text */
2087 int i; /* Loop counter */
2089 zMsg[0] = 0;
2090 winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
2091 assert( errcode!=SQLITE_OK );
2092 if( zPath==0 ) zPath = "";
2093 for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
2094 zMsg[i] = 0;
2095 sqlite3_log(errcode,
2096 "os_win.c:%d: (%lu) %s(%s) - %s",
2097 iLine, lastErrno, zFunc, zPath, zMsg
2100 return errcode;
2104 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
2105 ** will be retried following a locking error - probably caused by
2106 ** antivirus software. Also the initial delay before the first retry.
2107 ** The delay increases linearly with each retry.
2109 #ifndef SQLITE_WIN32_IOERR_RETRY
2110 # define SQLITE_WIN32_IOERR_RETRY 10
2111 #endif
2112 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
2113 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
2114 #endif
2115 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
2116 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
2119 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
2120 ** error code obtained via GetLastError() is eligible to be retried. It
2121 ** must accept the error code DWORD as its only argument and should return
2122 ** non-zero if the error code is transient in nature and the operation
2123 ** responsible for generating the original error might succeed upon being
2124 ** retried. The argument to this macro should be a variable.
2126 ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
2127 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
2128 ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
2129 ** may be used to include additional error codes in the set that should
2130 ** result in the failing I/O operation being retried by the caller. If
2131 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
2132 ** identical to those of the "winIoerrCanRetry1" macro.
2134 #if !defined(winIoerrCanRetry1)
2135 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
2136 ((a)==ERROR_SHARING_VIOLATION) || \
2137 ((a)==ERROR_LOCK_VIOLATION) || \
2138 ((a)==ERROR_DEV_NOT_EXIST) || \
2139 ((a)==ERROR_NETNAME_DELETED) || \
2140 ((a)==ERROR_SEM_TIMEOUT) || \
2141 ((a)==ERROR_NETWORK_UNREACHABLE))
2142 #endif
2145 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
2146 ** to see if it should be retried. Return TRUE to retry. Return FALSE
2147 ** to give up with an error.
2149 static int winRetryIoerr(int *pnRetry, DWORD *pError){
2150 DWORD e = osGetLastError();
2151 if( *pnRetry>=winIoerrRetry ){
2152 if( pError ){
2153 *pError = e;
2155 return 0;
2157 if( winIoerrCanRetry1(e) ){
2158 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
2159 ++*pnRetry;
2160 return 1;
2162 #if defined(winIoerrCanRetry2)
2163 else if( winIoerrCanRetry2(e) ){
2164 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
2165 ++*pnRetry;
2166 return 1;
2168 #endif
2169 if( pError ){
2170 *pError = e;
2172 return 0;
2176 ** Log a I/O error retry episode.
2178 static void winLogIoerr(int nRetry, int lineno){
2179 if( nRetry ){
2180 sqlite3_log(SQLITE_NOTICE,
2181 "delayed %dms for lock/sharing conflict at line %d",
2182 winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
2188 ** This #if does not rely on the SQLITE_OS_WINCE define because the
2189 ** corresponding section in "date.c" cannot use it.
2191 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
2192 (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
2194 ** The MSVC CRT on Windows CE may not have a localtime() function.
2195 ** So define a substitute.
2197 # include <time.h>
2198 struct tm *__cdecl localtime(const time_t *t)
2200 static struct tm y;
2201 FILETIME uTm, lTm;
2202 SYSTEMTIME pTm;
2203 sqlite3_int64 t64;
2204 t64 = *t;
2205 t64 = (t64 + 11644473600)*10000000;
2206 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
2207 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
2208 osFileTimeToLocalFileTime(&uTm,&lTm);
2209 osFileTimeToSystemTime(&lTm,&pTm);
2210 y.tm_year = pTm.wYear - 1900;
2211 y.tm_mon = pTm.wMonth - 1;
2212 y.tm_wday = pTm.wDayOfWeek;
2213 y.tm_mday = pTm.wDay;
2214 y.tm_hour = pTm.wHour;
2215 y.tm_min = pTm.wMinute;
2216 y.tm_sec = pTm.wSecond;
2217 return &y;
2219 #endif
2221 #if SQLITE_OS_WINCE
2222 /*************************************************************************
2223 ** This section contains code for WinCE only.
2225 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
2228 ** Acquire a lock on the handle h
2230 static void winceMutexAcquire(HANDLE h){
2231 DWORD dwErr;
2232 do {
2233 dwErr = osWaitForSingleObject(h, INFINITE);
2234 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
2237 ** Release a lock acquired by winceMutexAcquire()
2239 #define winceMutexRelease(h) ReleaseMutex(h)
2242 ** Create the mutex and shared memory used for locking in the file
2243 ** descriptor pFile
2245 static int winceCreateLock(const char *zFilename, winFile *pFile){
2246 LPWSTR zTok;
2247 LPWSTR zName;
2248 DWORD lastErrno;
2249 BOOL bLogged = FALSE;
2250 BOOL bInit = TRUE;
2252 zName = winUtf8ToUnicode(zFilename);
2253 if( zName==0 ){
2254 /* out of memory */
2255 return SQLITE_IOERR_NOMEM_BKPT;
2258 /* Initialize the local lockdata */
2259 memset(&pFile->local, 0, sizeof(pFile->local));
2261 /* Replace the backslashes from the filename and lowercase it
2262 ** to derive a mutex name. */
2263 zTok = osCharLowerW(zName);
2264 for (;*zTok;zTok++){
2265 if (*zTok == '\\') *zTok = '_';
2268 /* Create/open the named mutex */
2269 pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
2270 if (!pFile->hMutex){
2271 pFile->lastErrno = osGetLastError();
2272 sqlite3_free(zName);
2273 return winLogError(SQLITE_IOERR, pFile->lastErrno,
2274 "winceCreateLock1", zFilename);
2277 /* Acquire the mutex before continuing */
2278 winceMutexAcquire(pFile->hMutex);
2280 /* Since the names of named mutexes, semaphores, file mappings etc are
2281 ** case-sensitive, take advantage of that by uppercasing the mutex name
2282 ** and using that as the shared filemapping name.
2284 osCharUpperW(zName);
2285 pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
2286 PAGE_READWRITE, 0, sizeof(winceLock),
2287 zName);
2289 /* Set a flag that indicates we're the first to create the memory so it
2290 ** must be zero-initialized */
2291 lastErrno = osGetLastError();
2292 if (lastErrno == ERROR_ALREADY_EXISTS){
2293 bInit = FALSE;
2296 sqlite3_free(zName);
2298 /* If we succeeded in making the shared memory handle, map it. */
2299 if( pFile->hShared ){
2300 pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
2301 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
2302 /* If mapping failed, close the shared memory handle and erase it */
2303 if( !pFile->shared ){
2304 pFile->lastErrno = osGetLastError();
2305 winLogError(SQLITE_IOERR, pFile->lastErrno,
2306 "winceCreateLock2", zFilename);
2307 bLogged = TRUE;
2308 osCloseHandle(pFile->hShared);
2309 pFile->hShared = NULL;
2313 /* If shared memory could not be created, then close the mutex and fail */
2314 if( pFile->hShared==NULL ){
2315 if( !bLogged ){
2316 pFile->lastErrno = lastErrno;
2317 winLogError(SQLITE_IOERR, pFile->lastErrno,
2318 "winceCreateLock3", zFilename);
2319 bLogged = TRUE;
2321 winceMutexRelease(pFile->hMutex);
2322 osCloseHandle(pFile->hMutex);
2323 pFile->hMutex = NULL;
2324 return SQLITE_IOERR;
2327 /* Initialize the shared memory if we're supposed to */
2328 if( bInit ){
2329 memset(pFile->shared, 0, sizeof(winceLock));
2332 winceMutexRelease(pFile->hMutex);
2333 return SQLITE_OK;
2337 ** Destroy the part of winFile that deals with wince locks
2339 static void winceDestroyLock(winFile *pFile){
2340 if (pFile->hMutex){
2341 /* Acquire the mutex */
2342 winceMutexAcquire(pFile->hMutex);
2344 /* The following blocks should probably assert in debug mode, but they
2345 are to cleanup in case any locks remained open */
2346 if (pFile->local.nReaders){
2347 pFile->shared->nReaders --;
2349 if (pFile->local.bReserved){
2350 pFile->shared->bReserved = FALSE;
2352 if (pFile->local.bPending){
2353 pFile->shared->bPending = FALSE;
2355 if (pFile->local.bExclusive){
2356 pFile->shared->bExclusive = FALSE;
2359 /* De-reference and close our copy of the shared memory handle */
2360 osUnmapViewOfFile(pFile->shared);
2361 osCloseHandle(pFile->hShared);
2363 /* Done with the mutex */
2364 winceMutexRelease(pFile->hMutex);
2365 osCloseHandle(pFile->hMutex);
2366 pFile->hMutex = NULL;
2371 ** An implementation of the LockFile() API of Windows for CE
2373 static BOOL winceLockFile(
2374 LPHANDLE phFile,
2375 DWORD dwFileOffsetLow,
2376 DWORD dwFileOffsetHigh,
2377 DWORD nNumberOfBytesToLockLow,
2378 DWORD nNumberOfBytesToLockHigh
2380 winFile *pFile = HANDLE_TO_WINFILE(phFile);
2381 BOOL bReturn = FALSE;
2383 UNUSED_PARAMETER(dwFileOffsetHigh);
2384 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
2386 if (!pFile->hMutex) return TRUE;
2387 winceMutexAcquire(pFile->hMutex);
2389 /* Wanting an exclusive lock? */
2390 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
2391 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
2392 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
2393 pFile->shared->bExclusive = TRUE;
2394 pFile->local.bExclusive = TRUE;
2395 bReturn = TRUE;
2399 /* Want a read-only lock? */
2400 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
2401 nNumberOfBytesToLockLow == 1){
2402 if (pFile->shared->bExclusive == 0){
2403 pFile->local.nReaders ++;
2404 if (pFile->local.nReaders == 1){
2405 pFile->shared->nReaders ++;
2407 bReturn = TRUE;
2411 /* Want a pending lock? */
2412 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
2413 && nNumberOfBytesToLockLow == 1){
2414 /* If no pending lock has been acquired, then acquire it */
2415 if (pFile->shared->bPending == 0) {
2416 pFile->shared->bPending = TRUE;
2417 pFile->local.bPending = TRUE;
2418 bReturn = TRUE;
2422 /* Want a reserved lock? */
2423 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
2424 && nNumberOfBytesToLockLow == 1){
2425 if (pFile->shared->bReserved == 0) {
2426 pFile->shared->bReserved = TRUE;
2427 pFile->local.bReserved = TRUE;
2428 bReturn = TRUE;
2432 winceMutexRelease(pFile->hMutex);
2433 return bReturn;
2437 ** An implementation of the UnlockFile API of Windows for CE
2439 static BOOL winceUnlockFile(
2440 LPHANDLE phFile,
2441 DWORD dwFileOffsetLow,
2442 DWORD dwFileOffsetHigh,
2443 DWORD nNumberOfBytesToUnlockLow,
2444 DWORD nNumberOfBytesToUnlockHigh
2446 winFile *pFile = HANDLE_TO_WINFILE(phFile);
2447 BOOL bReturn = FALSE;
2449 UNUSED_PARAMETER(dwFileOffsetHigh);
2450 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
2452 if (!pFile->hMutex) return TRUE;
2453 winceMutexAcquire(pFile->hMutex);
2455 /* Releasing a reader lock or an exclusive lock */
2456 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
2457 /* Did we have an exclusive lock? */
2458 if (pFile->local.bExclusive){
2459 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
2460 pFile->local.bExclusive = FALSE;
2461 pFile->shared->bExclusive = FALSE;
2462 bReturn = TRUE;
2465 /* Did we just have a reader lock? */
2466 else if (pFile->local.nReaders){
2467 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
2468 || nNumberOfBytesToUnlockLow == 1);
2469 pFile->local.nReaders --;
2470 if (pFile->local.nReaders == 0)
2472 pFile->shared->nReaders --;
2474 bReturn = TRUE;
2478 /* Releasing a pending lock */
2479 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
2480 && nNumberOfBytesToUnlockLow == 1){
2481 if (pFile->local.bPending){
2482 pFile->local.bPending = FALSE;
2483 pFile->shared->bPending = FALSE;
2484 bReturn = TRUE;
2487 /* Releasing a reserved lock */
2488 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
2489 && nNumberOfBytesToUnlockLow == 1){
2490 if (pFile->local.bReserved) {
2491 pFile->local.bReserved = FALSE;
2492 pFile->shared->bReserved = FALSE;
2493 bReturn = TRUE;
2497 winceMutexRelease(pFile->hMutex);
2498 return bReturn;
2501 ** End of the special code for wince
2502 *****************************************************************************/
2503 #endif /* SQLITE_OS_WINCE */
2506 ** Lock a file region.
2508 static BOOL winLockFile(
2509 LPHANDLE phFile,
2510 DWORD flags,
2511 DWORD offsetLow,
2512 DWORD offsetHigh,
2513 DWORD numBytesLow,
2514 DWORD numBytesHigh
2516 #if SQLITE_OS_WINCE
2518 ** NOTE: Windows CE is handled differently here due its lack of the Win32
2519 ** API LockFile.
2521 return winceLockFile(phFile, offsetLow, offsetHigh,
2522 numBytesLow, numBytesHigh);
2523 #else
2524 if( osIsNT() ){
2525 OVERLAPPED ovlp;
2526 memset(&ovlp, 0, sizeof(OVERLAPPED));
2527 ovlp.Offset = offsetLow;
2528 ovlp.OffsetHigh = offsetHigh;
2529 return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
2530 }else{
2531 return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
2532 numBytesHigh);
2534 #endif
2538 ** Unlock a file region.
2540 static BOOL winUnlockFile(
2541 LPHANDLE phFile,
2542 DWORD offsetLow,
2543 DWORD offsetHigh,
2544 DWORD numBytesLow,
2545 DWORD numBytesHigh
2547 #if SQLITE_OS_WINCE
2549 ** NOTE: Windows CE is handled differently here due its lack of the Win32
2550 ** API UnlockFile.
2552 return winceUnlockFile(phFile, offsetLow, offsetHigh,
2553 numBytesLow, numBytesHigh);
2554 #else
2555 if( osIsNT() ){
2556 OVERLAPPED ovlp;
2557 memset(&ovlp, 0, sizeof(OVERLAPPED));
2558 ovlp.Offset = offsetLow;
2559 ovlp.OffsetHigh = offsetHigh;
2560 return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
2561 }else{
2562 return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
2563 numBytesHigh);
2565 #endif
2568 /*****************************************************************************
2569 ** The next group of routines implement the I/O methods specified
2570 ** by the sqlite3_io_methods object.
2571 ******************************************************************************/
2574 ** Some Microsoft compilers lack this definition.
2576 #ifndef INVALID_SET_FILE_POINTER
2577 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
2578 #endif
2581 ** Move the current position of the file handle passed as the first
2582 ** argument to offset iOffset within the file. If successful, return 0.
2583 ** Otherwise, set pFile->lastErrno and return non-zero.
2585 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
2586 #if !SQLITE_OS_WINRT
2587 LONG upperBits; /* Most sig. 32 bits of new offset */
2588 LONG lowerBits; /* Least sig. 32 bits of new offset */
2589 DWORD dwRet; /* Value returned by SetFilePointer() */
2590 DWORD lastErrno; /* Value returned by GetLastError() */
2592 OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
2594 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
2595 lowerBits = (LONG)(iOffset & 0xffffffff);
2597 /* API oddity: If successful, SetFilePointer() returns a dword
2598 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
2599 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
2600 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
2601 ** whether an error has actually occurred, it is also necessary to call
2602 ** GetLastError().
2604 dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
2606 if( (dwRet==INVALID_SET_FILE_POINTER
2607 && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
2608 pFile->lastErrno = lastErrno;
2609 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
2610 "winSeekFile", pFile->zPath);
2611 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
2612 return 1;
2615 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
2616 return 0;
2617 #else
2619 ** Same as above, except that this implementation works for WinRT.
2622 LARGE_INTEGER x; /* The new offset */
2623 BOOL bRet; /* Value returned by SetFilePointerEx() */
2625 x.QuadPart = iOffset;
2626 bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
2628 if(!bRet){
2629 pFile->lastErrno = osGetLastError();
2630 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
2631 "winSeekFile", pFile->zPath);
2632 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
2633 return 1;
2636 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
2637 return 0;
2638 #endif
2641 #if SQLITE_MAX_MMAP_SIZE>0
2642 /* Forward references to VFS helper methods used for memory mapped files */
2643 static int winMapfile(winFile*, sqlite3_int64);
2644 static int winUnmapfile(winFile*);
2645 #endif
2648 ** Close a file.
2650 ** It is reported that an attempt to close a handle might sometimes
2651 ** fail. This is a very unreasonable result, but Windows is notorious
2652 ** for being unreasonable so I do not doubt that it might happen. If
2653 ** the close fails, we pause for 100 milliseconds and try again. As
2654 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
2655 ** giving up and returning an error.
2657 #define MX_CLOSE_ATTEMPT 3
2658 static int winClose(sqlite3_file *id){
2659 int rc, cnt = 0;
2660 winFile *pFile = (winFile*)id;
2662 assert( id!=0 );
2663 #ifndef SQLITE_OMIT_WAL
2664 assert( pFile->pShm==0 );
2665 #endif
2666 assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
2667 OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
2668 osGetCurrentProcessId(), pFile, pFile->h));
2670 #if SQLITE_MAX_MMAP_SIZE>0
2671 winUnmapfile(pFile);
2672 #endif
2675 rc = osCloseHandle(pFile->h);
2676 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
2677 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
2678 #if SQLITE_OS_WINCE
2679 #define WINCE_DELETION_ATTEMPTS 3
2681 winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
2682 if( pAppData==NULL || !pAppData->bNoLock ){
2683 winceDestroyLock(pFile);
2686 if( pFile->zDeleteOnClose ){
2687 int cnt = 0;
2688 while(
2689 osDeleteFileW(pFile->zDeleteOnClose)==0
2690 && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
2691 && cnt++ < WINCE_DELETION_ATTEMPTS
2693 sqlite3_win32_sleep(100); /* Wait a little before trying again */
2695 sqlite3_free(pFile->zDeleteOnClose);
2697 #endif
2698 if( rc ){
2699 pFile->h = NULL;
2701 OpenCounter(-1);
2702 OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
2703 osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
2704 return rc ? SQLITE_OK
2705 : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
2706 "winClose", pFile->zPath);
2710 ** Read data from a file into a buffer. Return SQLITE_OK if all
2711 ** bytes were read successfully and SQLITE_IOERR if anything goes
2712 ** wrong.
2714 static int winRead(
2715 sqlite3_file *id, /* File to read from */
2716 void *pBuf, /* Write content into this buffer */
2717 int amt, /* Number of bytes to read */
2718 sqlite3_int64 offset /* Begin reading at this offset */
2720 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2721 OVERLAPPED overlapped; /* The offset for ReadFile. */
2722 #endif
2723 winFile *pFile = (winFile*)id; /* file handle */
2724 DWORD nRead; /* Number of bytes actually read from file */
2725 int nRetry = 0; /* Number of retrys */
2727 assert( id!=0 );
2728 assert( amt>0 );
2729 assert( offset>=0 );
2730 SimulateIOError(return SQLITE_IOERR_READ);
2731 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
2732 "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
2733 pFile->h, pBuf, amt, offset, pFile->locktype));
2735 #if SQLITE_MAX_MMAP_SIZE>0
2736 /* Deal with as much of this read request as possible by transfering
2737 ** data from the memory mapping using memcpy(). */
2738 if( offset<pFile->mmapSize ){
2739 if( offset+amt <= pFile->mmapSize ){
2740 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
2741 OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2742 osGetCurrentProcessId(), pFile, pFile->h));
2743 return SQLITE_OK;
2744 }else{
2745 int nCopy = (int)(pFile->mmapSize - offset);
2746 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
2747 pBuf = &((u8 *)pBuf)[nCopy];
2748 amt -= nCopy;
2749 offset += nCopy;
2752 #endif
2754 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
2755 if( winSeekFile(pFile, offset) ){
2756 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
2757 osGetCurrentProcessId(), pFile, pFile->h));
2758 return SQLITE_FULL;
2760 while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
2761 #else
2762 memset(&overlapped, 0, sizeof(OVERLAPPED));
2763 overlapped.Offset = (LONG)(offset & 0xffffffff);
2764 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
2765 while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
2766 osGetLastError()!=ERROR_HANDLE_EOF ){
2767 #endif
2768 DWORD lastErrno;
2769 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
2770 pFile->lastErrno = lastErrno;
2771 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
2772 osGetCurrentProcessId(), pFile, pFile->h));
2773 return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
2774 "winRead", pFile->zPath);
2776 winLogIoerr(nRetry, __LINE__);
2777 if( nRead<(DWORD)amt ){
2778 /* Unread parts of the buffer must be zero-filled */
2779 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
2780 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
2781 osGetCurrentProcessId(), pFile, pFile->h));
2782 return SQLITE_IOERR_SHORT_READ;
2785 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2786 osGetCurrentProcessId(), pFile, pFile->h));
2787 return SQLITE_OK;
2791 ** Write data from a buffer into a file. Return SQLITE_OK on success
2792 ** or some other error code on failure.
2794 static int winWrite(
2795 sqlite3_file *id, /* File to write into */
2796 const void *pBuf, /* The bytes to be written */
2797 int amt, /* Number of bytes to write */
2798 sqlite3_int64 offset /* Offset into the file to begin writing at */
2800 int rc = 0; /* True if error has occurred, else false */
2801 winFile *pFile = (winFile*)id; /* File handle */
2802 int nRetry = 0; /* Number of retries */
2804 assert( amt>0 );
2805 assert( pFile );
2806 SimulateIOError(return SQLITE_IOERR_WRITE);
2807 SimulateDiskfullError(return SQLITE_FULL);
2809 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
2810 "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
2811 pFile->h, pBuf, amt, offset, pFile->locktype));
2813 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
2814 /* Deal with as much of this write request as possible by transfering
2815 ** data from the memory mapping using memcpy(). */
2816 if( offset<pFile->mmapSize ){
2817 if( offset+amt <= pFile->mmapSize ){
2818 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
2819 OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2820 osGetCurrentProcessId(), pFile, pFile->h));
2821 return SQLITE_OK;
2822 }else{
2823 int nCopy = (int)(pFile->mmapSize - offset);
2824 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
2825 pBuf = &((u8 *)pBuf)[nCopy];
2826 amt -= nCopy;
2827 offset += nCopy;
2830 #endif
2832 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
2833 rc = winSeekFile(pFile, offset);
2834 if( rc==0 ){
2835 #else
2837 #endif
2838 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2839 OVERLAPPED overlapped; /* The offset for WriteFile. */
2840 #endif
2841 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
2842 int nRem = amt; /* Number of bytes yet to be written */
2843 DWORD nWrite; /* Bytes written by each WriteFile() call */
2844 DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
2846 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2847 memset(&overlapped, 0, sizeof(OVERLAPPED));
2848 overlapped.Offset = (LONG)(offset & 0xffffffff);
2849 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
2850 #endif
2852 while( nRem>0 ){
2853 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
2854 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
2855 #else
2856 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
2857 #endif
2858 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
2859 break;
2861 assert( nWrite==0 || nWrite<=(DWORD)nRem );
2862 if( nWrite==0 || nWrite>(DWORD)nRem ){
2863 lastErrno = osGetLastError();
2864 break;
2866 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2867 offset += nWrite;
2868 overlapped.Offset = (LONG)(offset & 0xffffffff);
2869 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
2870 #endif
2871 aRem += nWrite;
2872 nRem -= nWrite;
2874 if( nRem>0 ){
2875 pFile->lastErrno = lastErrno;
2876 rc = 1;
2880 if( rc ){
2881 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
2882 || ( pFile->lastErrno==ERROR_DISK_FULL )){
2883 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
2884 osGetCurrentProcessId(), pFile, pFile->h));
2885 return winLogError(SQLITE_FULL, pFile->lastErrno,
2886 "winWrite1", pFile->zPath);
2888 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
2889 osGetCurrentProcessId(), pFile, pFile->h));
2890 return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
2891 "winWrite2", pFile->zPath);
2892 }else{
2893 winLogIoerr(nRetry, __LINE__);
2895 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2896 osGetCurrentProcessId(), pFile, pFile->h));
2897 return SQLITE_OK;
2901 ** Truncate an open file to a specified size
2903 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
2904 winFile *pFile = (winFile*)id; /* File handle object */
2905 int rc = SQLITE_OK; /* Return code for this function */
2906 DWORD lastErrno;
2907 #if SQLITE_MAX_MMAP_SIZE>0
2908 sqlite3_int64 oldMmapSize;
2909 #endif
2911 assert( pFile );
2912 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
2913 OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
2914 osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
2916 /* If the user has configured a chunk-size for this file, truncate the
2917 ** file so that it consists of an integer number of chunks (i.e. the
2918 ** actual file size after the operation may be larger than the requested
2919 ** size).
2921 if( pFile->szChunk>0 ){
2922 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
2925 #if SQLITE_MAX_MMAP_SIZE>0
2926 if( pFile->pMapRegion ){
2927 oldMmapSize = pFile->mmapSize;
2928 }else{
2929 oldMmapSize = 0;
2931 winUnmapfile(pFile);
2932 #endif
2934 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
2935 if( winSeekFile(pFile, nByte) ){
2936 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
2937 "winTruncate1", pFile->zPath);
2938 }else if( 0==osSetEndOfFile(pFile->h) &&
2939 ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
2940 pFile->lastErrno = lastErrno;
2941 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
2942 "winTruncate2", pFile->zPath);
2945 #if SQLITE_MAX_MMAP_SIZE>0
2946 if( rc==SQLITE_OK && oldMmapSize>0 ){
2947 if( oldMmapSize>nByte ){
2948 winMapfile(pFile, -1);
2949 }else{
2950 winMapfile(pFile, oldMmapSize);
2953 #endif
2955 OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
2956 osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
2957 return rc;
2960 #ifdef SQLITE_TEST
2962 ** Count the number of fullsyncs and normal syncs. This is used to test
2963 ** that syncs and fullsyncs are occuring at the right times.
2965 int sqlite3_sync_count = 0;
2966 int sqlite3_fullsync_count = 0;
2967 #endif
2970 ** Make sure all writes to a particular file are committed to disk.
2972 static int winSync(sqlite3_file *id, int flags){
2973 #ifndef SQLITE_NO_SYNC
2975 ** Used only when SQLITE_NO_SYNC is not defined.
2977 BOOL rc;
2978 #endif
2979 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
2980 defined(SQLITE_HAVE_OS_TRACE)
2982 ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
2983 ** OSTRACE() macros.
2985 winFile *pFile = (winFile*)id;
2986 #else
2987 UNUSED_PARAMETER(id);
2988 #endif
2990 assert( pFile );
2991 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2992 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2993 || (flags&0x0F)==SQLITE_SYNC_FULL
2996 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2997 ** line is to test that doing so does not cause any problems.
2999 SimulateDiskfullError( return SQLITE_FULL );
3001 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
3002 osGetCurrentProcessId(), pFile, pFile->h, flags,
3003 pFile->locktype));
3005 #ifndef SQLITE_TEST
3006 UNUSED_PARAMETER(flags);
3007 #else
3008 if( (flags&0x0F)==SQLITE_SYNC_FULL ){
3009 sqlite3_fullsync_count++;
3011 sqlite3_sync_count++;
3012 #endif
3014 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3015 ** no-op
3017 #ifdef SQLITE_NO_SYNC
3018 OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
3019 osGetCurrentProcessId(), pFile, pFile->h));
3020 return SQLITE_OK;
3021 #else
3022 #if SQLITE_MAX_MMAP_SIZE>0
3023 if( pFile->pMapRegion ){
3024 if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
3025 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
3026 "rc=SQLITE_OK\n", osGetCurrentProcessId(),
3027 pFile, pFile->pMapRegion));
3028 }else{
3029 pFile->lastErrno = osGetLastError();
3030 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
3031 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
3032 pFile, pFile->pMapRegion));
3033 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
3034 "winSync1", pFile->zPath);
3037 #endif
3038 rc = osFlushFileBuffers(pFile->h);
3039 SimulateIOError( rc=FALSE );
3040 if( rc ){
3041 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
3042 osGetCurrentProcessId(), pFile, pFile->h));
3043 return SQLITE_OK;
3044 }else{
3045 pFile->lastErrno = osGetLastError();
3046 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
3047 osGetCurrentProcessId(), pFile, pFile->h));
3048 return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
3049 "winSync2", pFile->zPath);
3051 #endif
3055 ** Determine the current size of a file in bytes
3057 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
3058 winFile *pFile = (winFile*)id;
3059 int rc = SQLITE_OK;
3061 assert( id!=0 );
3062 assert( pSize!=0 );
3063 SimulateIOError(return SQLITE_IOERR_FSTAT);
3064 OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
3066 #if SQLITE_OS_WINRT
3068 FILE_STANDARD_INFO info;
3069 if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
3070 &info, sizeof(info)) ){
3071 *pSize = info.EndOfFile.QuadPart;
3072 }else{
3073 pFile->lastErrno = osGetLastError();
3074 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
3075 "winFileSize", pFile->zPath);
3078 #else
3080 DWORD upperBits;
3081 DWORD lowerBits;
3082 DWORD lastErrno;
3084 lowerBits = osGetFileSize(pFile->h, &upperBits);
3085 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
3086 if( (lowerBits == INVALID_FILE_SIZE)
3087 && ((lastErrno = osGetLastError())!=NO_ERROR) ){
3088 pFile->lastErrno = lastErrno;
3089 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
3090 "winFileSize", pFile->zPath);
3093 #endif
3094 OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
3095 pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
3096 return rc;
3100 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
3102 #ifndef LOCKFILE_FAIL_IMMEDIATELY
3103 # define LOCKFILE_FAIL_IMMEDIATELY 1
3104 #endif
3106 #ifndef LOCKFILE_EXCLUSIVE_LOCK
3107 # define LOCKFILE_EXCLUSIVE_LOCK 2
3108 #endif
3111 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
3112 ** When the LockFile function was used, it was always expected to fail
3113 ** immediately if the lock could not be obtained. Also, it always expected to
3114 ** obtain an exclusive lock. These flags are used with the LockFileEx function
3115 ** and reflect those expectations; therefore, they should not be changed.
3117 #ifndef SQLITE_LOCKFILE_FLAGS
3118 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
3119 LOCKFILE_EXCLUSIVE_LOCK)
3120 #endif
3123 ** Currently, SQLite never calls the LockFileEx function without wanting the
3124 ** call to fail immediately if the lock cannot be obtained.
3126 #ifndef SQLITE_LOCKFILEEX_FLAGS
3127 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
3128 #endif
3131 ** Acquire a reader lock.
3132 ** Different API routines are called depending on whether or not this
3133 ** is Win9x or WinNT.
3135 static int winGetReadLock(winFile *pFile){
3136 int res;
3137 OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
3138 if( osIsNT() ){
3139 #if SQLITE_OS_WINCE
3141 ** NOTE: Windows CE is handled differently here due its lack of the Win32
3142 ** API LockFileEx.
3144 res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
3145 #else
3146 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
3147 SHARED_SIZE, 0);
3148 #endif
3150 #ifdef SQLITE_WIN32_HAS_ANSI
3151 else{
3152 int lk;
3153 sqlite3_randomness(sizeof(lk), &lk);
3154 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
3155 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
3156 SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
3158 #endif
3159 if( res == 0 ){
3160 pFile->lastErrno = osGetLastError();
3161 /* No need to log a failure to lock */
3163 OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
3164 return res;
3168 ** Undo a readlock
3170 static int winUnlockReadLock(winFile *pFile){
3171 int res;
3172 DWORD lastErrno;
3173 OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
3174 if( osIsNT() ){
3175 res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
3177 #ifdef SQLITE_WIN32_HAS_ANSI
3178 else{
3179 res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
3181 #endif
3182 if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
3183 pFile->lastErrno = lastErrno;
3184 winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
3185 "winUnlockReadLock", pFile->zPath);
3187 OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
3188 return res;
3192 ** Lock the file with the lock specified by parameter locktype - one
3193 ** of the following:
3195 ** (1) SHARED_LOCK
3196 ** (2) RESERVED_LOCK
3197 ** (3) PENDING_LOCK
3198 ** (4) EXCLUSIVE_LOCK
3200 ** Sometimes when requesting one lock state, additional lock states
3201 ** are inserted in between. The locking might fail on one of the later
3202 ** transitions leaving the lock state different from what it started but
3203 ** still short of its goal. The following chart shows the allowed
3204 ** transitions and the inserted intermediate states:
3206 ** UNLOCKED -> SHARED
3207 ** SHARED -> RESERVED
3208 ** SHARED -> (PENDING) -> EXCLUSIVE
3209 ** RESERVED -> (PENDING) -> EXCLUSIVE
3210 ** PENDING -> EXCLUSIVE
3212 ** This routine will only increase a lock. The winUnlock() routine
3213 ** erases all locks at once and returns us immediately to locking level 0.
3214 ** It is not possible to lower the locking level one step at a time. You
3215 ** must go straight to locking level 0.
3217 static int winLock(sqlite3_file *id, int locktype){
3218 int rc = SQLITE_OK; /* Return code from subroutines */
3219 int res = 1; /* Result of a Windows lock call */
3220 int newLocktype; /* Set pFile->locktype to this value before exiting */
3221 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
3222 winFile *pFile = (winFile*)id;
3223 DWORD lastErrno = NO_ERROR;
3225 assert( id!=0 );
3226 OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
3227 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
3229 /* If there is already a lock of this type or more restrictive on the
3230 ** OsFile, do nothing. Don't use the end_lock: exit path, as
3231 ** sqlite3OsEnterMutex() hasn't been called yet.
3233 if( pFile->locktype>=locktype ){
3234 OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
3235 return SQLITE_OK;
3238 /* Do not allow any kind of write-lock on a read-only database
3240 if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
3241 return SQLITE_IOERR_LOCK;
3244 /* Make sure the locking sequence is correct
3246 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
3247 assert( locktype!=PENDING_LOCK );
3248 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
3250 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
3251 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
3252 ** the PENDING_LOCK byte is temporary.
3254 newLocktype = pFile->locktype;
3255 if( pFile->locktype==NO_LOCK
3256 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
3258 int cnt = 3;
3259 while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
3260 PENDING_BYTE, 0, 1, 0))==0 ){
3261 /* Try 3 times to get the pending lock. This is needed to work
3262 ** around problems caused by indexing and/or anti-virus software on
3263 ** Windows systems.
3264 ** If you are using this code as a model for alternative VFSes, do not
3265 ** copy this retry logic. It is a hack intended for Windows only.
3267 lastErrno = osGetLastError();
3268 OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
3269 pFile->h, cnt, res));
3270 if( lastErrno==ERROR_INVALID_HANDLE ){
3271 pFile->lastErrno = lastErrno;
3272 rc = SQLITE_IOERR_LOCK;
3273 OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
3274 pFile->h, cnt, sqlite3ErrName(rc)));
3275 return rc;
3277 if( cnt ) sqlite3_win32_sleep(1);
3279 gotPendingLock = res;
3280 if( !res ){
3281 lastErrno = osGetLastError();
3285 /* Acquire a shared lock
3287 if( locktype==SHARED_LOCK && res ){
3288 assert( pFile->locktype==NO_LOCK );
3289 res = winGetReadLock(pFile);
3290 if( res ){
3291 newLocktype = SHARED_LOCK;
3292 }else{
3293 lastErrno = osGetLastError();
3297 /* Acquire a RESERVED lock
3299 if( locktype==RESERVED_LOCK && res ){
3300 assert( pFile->locktype==SHARED_LOCK );
3301 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
3302 if( res ){
3303 newLocktype = RESERVED_LOCK;
3304 }else{
3305 lastErrno = osGetLastError();
3309 /* Acquire a PENDING lock
3311 if( locktype==EXCLUSIVE_LOCK && res ){
3312 newLocktype = PENDING_LOCK;
3313 gotPendingLock = 0;
3316 /* Acquire an EXCLUSIVE lock
3318 if( locktype==EXCLUSIVE_LOCK && res ){
3319 assert( pFile->locktype>=SHARED_LOCK );
3320 res = winUnlockReadLock(pFile);
3321 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
3322 SHARED_SIZE, 0);
3323 if( res ){
3324 newLocktype = EXCLUSIVE_LOCK;
3325 }else{
3326 lastErrno = osGetLastError();
3327 winGetReadLock(pFile);
3331 /* If we are holding a PENDING lock that ought to be released, then
3332 ** release it now.
3334 if( gotPendingLock && locktype==SHARED_LOCK ){
3335 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
3338 /* Update the state of the lock has held in the file descriptor then
3339 ** return the appropriate result code.
3341 if( res ){
3342 rc = SQLITE_OK;
3343 }else{
3344 pFile->lastErrno = lastErrno;
3345 rc = SQLITE_BUSY;
3346 OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
3347 pFile->h, locktype, newLocktype));
3349 pFile->locktype = (u8)newLocktype;
3350 OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
3351 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
3352 return rc;
3356 ** This routine checks if there is a RESERVED lock held on the specified
3357 ** file by this or any other process. If such a lock is held, return
3358 ** non-zero, otherwise zero.
3360 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
3361 int res;
3362 winFile *pFile = (winFile*)id;
3364 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
3365 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
3367 assert( id!=0 );
3368 if( pFile->locktype>=RESERVED_LOCK ){
3369 res = 1;
3370 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
3371 }else{
3372 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
3373 if( res ){
3374 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
3376 res = !res;
3377 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
3379 *pResOut = res;
3380 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
3381 pFile->h, pResOut, *pResOut));
3382 return SQLITE_OK;
3386 ** Lower the locking level on file descriptor id to locktype. locktype
3387 ** must be either NO_LOCK or SHARED_LOCK.
3389 ** If the locking level of the file descriptor is already at or below
3390 ** the requested locking level, this routine is a no-op.
3392 ** It is not possible for this routine to fail if the second argument
3393 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
3394 ** might return SQLITE_IOERR;
3396 static int winUnlock(sqlite3_file *id, int locktype){
3397 int type;
3398 winFile *pFile = (winFile*)id;
3399 int rc = SQLITE_OK;
3400 assert( pFile!=0 );
3401 assert( locktype<=SHARED_LOCK );
3402 OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
3403 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
3404 type = pFile->locktype;
3405 if( type>=EXCLUSIVE_LOCK ){
3406 winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
3407 if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
3408 /* This should never happen. We should always be able to
3409 ** reacquire the read lock */
3410 rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
3411 "winUnlock", pFile->zPath);
3414 if( type>=RESERVED_LOCK ){
3415 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
3417 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
3418 winUnlockReadLock(pFile);
3420 if( type>=PENDING_LOCK ){
3421 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
3423 pFile->locktype = (u8)locktype;
3424 OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
3425 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
3426 return rc;
3429 /******************************************************************************
3430 ****************************** No-op Locking **********************************
3432 ** Of the various locking implementations available, this is by far the
3433 ** simplest: locking is ignored. No attempt is made to lock the database
3434 ** file for reading or writing.
3436 ** This locking mode is appropriate for use on read-only databases
3437 ** (ex: databases that are burned into CD-ROM, for example.) It can
3438 ** also be used if the application employs some external mechanism to
3439 ** prevent simultaneous access of the same database by two or more
3440 ** database connections. But there is a serious risk of database
3441 ** corruption if this locking mode is used in situations where multiple
3442 ** database connections are accessing the same database file at the same
3443 ** time and one or more of those connections are writing.
3446 static int winNolockLock(sqlite3_file *id, int locktype){
3447 UNUSED_PARAMETER(id);
3448 UNUSED_PARAMETER(locktype);
3449 return SQLITE_OK;
3452 static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
3453 UNUSED_PARAMETER(id);
3454 UNUSED_PARAMETER(pResOut);
3455 return SQLITE_OK;
3458 static int winNolockUnlock(sqlite3_file *id, int locktype){
3459 UNUSED_PARAMETER(id);
3460 UNUSED_PARAMETER(locktype);
3461 return SQLITE_OK;
3464 /******************* End of the no-op lock implementation *********************
3465 ******************************************************************************/
3468 ** If *pArg is initially negative then this is a query. Set *pArg to
3469 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3471 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3473 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
3474 if( *pArg<0 ){
3475 *pArg = (pFile->ctrlFlags & mask)!=0;
3476 }else if( (*pArg)==0 ){
3477 pFile->ctrlFlags &= ~mask;
3478 }else{
3479 pFile->ctrlFlags |= mask;
3483 /* Forward references to VFS helper methods used for temporary files */
3484 static int winGetTempname(sqlite3_vfs *, char **);
3485 static int winIsDir(const void *);
3486 static BOOL winIsDriveLetterAndColon(const char *);
3489 ** Control and query of the open file handle.
3491 static int winFileControl(sqlite3_file *id, int op, void *pArg){
3492 winFile *pFile = (winFile*)id;
3493 OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
3494 switch( op ){
3495 case SQLITE_FCNTL_LOCKSTATE: {
3496 *(int*)pArg = pFile->locktype;
3497 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3498 return SQLITE_OK;
3500 case SQLITE_FCNTL_LAST_ERRNO: {
3501 *(int*)pArg = (int)pFile->lastErrno;
3502 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3503 return SQLITE_OK;
3505 case SQLITE_FCNTL_CHUNK_SIZE: {
3506 pFile->szChunk = *(int *)pArg;
3507 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3508 return SQLITE_OK;
3510 case SQLITE_FCNTL_SIZE_HINT: {
3511 if( pFile->szChunk>0 ){
3512 sqlite3_int64 oldSz;
3513 int rc = winFileSize(id, &oldSz);
3514 if( rc==SQLITE_OK ){
3515 sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
3516 if( newSz>oldSz ){
3517 SimulateIOErrorBenign(1);
3518 rc = winTruncate(id, newSz);
3519 SimulateIOErrorBenign(0);
3522 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
3523 return rc;
3525 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3526 return SQLITE_OK;
3528 case SQLITE_FCNTL_PERSIST_WAL: {
3529 winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
3530 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3531 return SQLITE_OK;
3533 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3534 winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
3535 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3536 return SQLITE_OK;
3538 case SQLITE_FCNTL_VFSNAME: {
3539 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3540 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3541 return SQLITE_OK;
3543 case SQLITE_FCNTL_WIN32_AV_RETRY: {
3544 int *a = (int*)pArg;
3545 if( a[0]>0 ){
3546 winIoerrRetry = a[0];
3547 }else{
3548 a[0] = winIoerrRetry;
3550 if( a[1]>0 ){
3551 winIoerrRetryDelay = a[1];
3552 }else{
3553 a[1] = winIoerrRetryDelay;
3555 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3556 return SQLITE_OK;
3558 case SQLITE_FCNTL_WIN32_GET_HANDLE: {
3559 LPHANDLE phFile = (LPHANDLE)pArg;
3560 *phFile = pFile->h;
3561 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3562 return SQLITE_OK;
3564 #ifdef SQLITE_TEST
3565 case SQLITE_FCNTL_WIN32_SET_HANDLE: {
3566 LPHANDLE phFile = (LPHANDLE)pArg;
3567 HANDLE hOldFile = pFile->h;
3568 pFile->h = *phFile;
3569 *phFile = hOldFile;
3570 OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
3571 hOldFile, pFile->h));
3572 return SQLITE_OK;
3574 #endif
3575 case SQLITE_FCNTL_TEMPFILENAME: {
3576 char *zTFile = 0;
3577 int rc = winGetTempname(pFile->pVfs, &zTFile);
3578 if( rc==SQLITE_OK ){
3579 *(char**)pArg = zTFile;
3581 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
3582 return rc;
3584 #if SQLITE_MAX_MMAP_SIZE>0
3585 case SQLITE_FCNTL_MMAP_SIZE: {
3586 i64 newLimit = *(i64*)pArg;
3587 int rc = SQLITE_OK;
3588 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3589 newLimit = sqlite3GlobalConfig.mxMmap;
3592 /* The value of newLimit may be eventually cast to (SIZE_T) and passed
3593 ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
3594 ** least a 64-bit type. */
3595 if( newLimit>0 && sizeof(SIZE_T)<8 ){
3596 newLimit = (newLimit & 0x7FFFFFFF);
3599 *(i64*)pArg = pFile->mmapSizeMax;
3600 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
3601 pFile->mmapSizeMax = newLimit;
3602 if( pFile->mmapSize>0 ){
3603 winUnmapfile(pFile);
3604 rc = winMapfile(pFile, -1);
3607 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
3608 return rc;
3610 #endif
3612 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
3613 return SQLITE_NOTFOUND;
3617 ** Return the sector size in bytes of the underlying block device for
3618 ** the specified file. This is almost always 512 bytes, but may be
3619 ** larger for some devices.
3621 ** SQLite code assumes this function cannot fail. It also assumes that
3622 ** if two files are created in the same file-system directory (i.e.
3623 ** a database and its journal file) that the sector size will be the
3624 ** same for both.
3626 static int winSectorSize(sqlite3_file *id){
3627 (void)id;
3628 return SQLITE_DEFAULT_SECTOR_SIZE;
3632 ** Return a vector of device characteristics.
3634 static int winDeviceCharacteristics(sqlite3_file *id){
3635 winFile *p = (winFile*)id;
3636 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
3637 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
3641 ** Windows will only let you create file view mappings
3642 ** on allocation size granularity boundaries.
3643 ** During sqlite3_os_init() we do a GetSystemInfo()
3644 ** to get the granularity size.
3646 static SYSTEM_INFO winSysInfo;
3648 #ifndef SQLITE_OMIT_WAL
3651 ** Helper functions to obtain and relinquish the global mutex. The
3652 ** global mutex is used to protect the winLockInfo objects used by
3653 ** this file, all of which may be shared by multiple threads.
3655 ** Function winShmMutexHeld() is used to assert() that the global mutex
3656 ** is held when required. This function is only used as part of assert()
3657 ** statements. e.g.
3659 ** winShmEnterMutex()
3660 ** assert( winShmMutexHeld() );
3661 ** winShmLeaveMutex()
3663 static sqlite3_mutex *winBigLock = 0;
3664 static void winShmEnterMutex(void){
3665 sqlite3_mutex_enter(winBigLock);
3667 static void winShmLeaveMutex(void){
3668 sqlite3_mutex_leave(winBigLock);
3670 #ifndef NDEBUG
3671 static int winShmMutexHeld(void) {
3672 return sqlite3_mutex_held(winBigLock);
3674 #endif
3677 ** Object used to represent a single file opened and mmapped to provide
3678 ** shared memory. When multiple threads all reference the same
3679 ** log-summary, each thread has its own winFile object, but they all
3680 ** point to a single instance of this object. In other words, each
3681 ** log-summary is opened only once per process.
3683 ** winShmMutexHeld() must be true when creating or destroying
3684 ** this object or while reading or writing the following fields:
3686 ** nRef
3687 ** pNext
3689 ** The following fields are read-only after the object is created:
3691 ** fid
3692 ** zFilename
3694 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
3695 ** winShmMutexHeld() is true when reading or writing any other field
3696 ** in this structure.
3699 struct winShmNode {
3700 sqlite3_mutex *mutex; /* Mutex to access this object */
3701 char *zFilename; /* Name of the file */
3702 winFile hFile; /* File handle from winOpen */
3704 int szRegion; /* Size of shared-memory regions */
3705 int nRegion; /* Size of array apRegion */
3706 u8 isReadonly; /* True if read-only */
3707 u8 isUnlocked; /* True if no DMS lock held */
3709 struct ShmRegion {
3710 HANDLE hMap; /* File handle from CreateFileMapping */
3711 void *pMap;
3712 } *aRegion;
3713 DWORD lastErrno; /* The Windows errno from the last I/O error */
3715 int nRef; /* Number of winShm objects pointing to this */
3716 winShm *pFirst; /* All winShm objects pointing to this */
3717 winShmNode *pNext; /* Next in list of all winShmNode objects */
3718 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
3719 u8 nextShmId; /* Next available winShm.id value */
3720 #endif
3724 ** A global array of all winShmNode objects.
3726 ** The winShmMutexHeld() must be true while reading or writing this list.
3728 static winShmNode *winShmNodeList = 0;
3731 ** Structure used internally by this VFS to record the state of an
3732 ** open shared memory connection.
3734 ** The following fields are initialized when this object is created and
3735 ** are read-only thereafter:
3737 ** winShm.pShmNode
3738 ** winShm.id
3740 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
3741 ** while accessing any read/write fields.
3743 struct winShm {
3744 winShmNode *pShmNode; /* The underlying winShmNode object */
3745 winShm *pNext; /* Next winShm with the same winShmNode */
3746 u8 hasMutex; /* True if holding the winShmNode mutex */
3747 u16 sharedMask; /* Mask of shared locks held */
3748 u16 exclMask; /* Mask of exclusive locks held */
3749 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
3750 u8 id; /* Id of this connection with its winShmNode */
3751 #endif
3755 ** Constants used for locking
3757 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
3758 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
3761 ** Apply advisory locks for all n bytes beginning at ofst.
3763 #define WINSHM_UNLCK 1
3764 #define WINSHM_RDLCK 2
3765 #define WINSHM_WRLCK 3
3766 static int winShmSystemLock(
3767 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
3768 int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
3769 int ofst, /* Offset to first byte to be locked/unlocked */
3770 int nByte /* Number of bytes to lock or unlock */
3772 int rc = 0; /* Result code form Lock/UnlockFileEx() */
3774 /* Access to the winShmNode object is serialized by the caller */
3775 assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
3777 OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
3778 pFile->hFile.h, lockType, ofst, nByte));
3780 /* Release/Acquire the system-level lock */
3781 if( lockType==WINSHM_UNLCK ){
3782 rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
3783 }else{
3784 /* Initialize the locking parameters */
3785 DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
3786 if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
3787 rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
3790 if( rc!= 0 ){
3791 rc = SQLITE_OK;
3792 }else{
3793 pFile->lastErrno = osGetLastError();
3794 rc = SQLITE_BUSY;
3797 OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
3798 pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
3799 "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
3801 return rc;
3804 /* Forward references to VFS methods */
3805 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
3806 static int winDelete(sqlite3_vfs *,const char*,int);
3809 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
3811 ** This is not a VFS shared-memory method; it is a utility function called
3812 ** by VFS shared-memory methods.
3814 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
3815 winShmNode **pp;
3816 winShmNode *p;
3817 assert( winShmMutexHeld() );
3818 OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
3819 osGetCurrentProcessId(), deleteFlag));
3820 pp = &winShmNodeList;
3821 while( (p = *pp)!=0 ){
3822 if( p->nRef==0 ){
3823 int i;
3824 if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
3825 for(i=0; i<p->nRegion; i++){
3826 BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
3827 OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
3828 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
3829 UNUSED_VARIABLE_VALUE(bRc);
3830 bRc = osCloseHandle(p->aRegion[i].hMap);
3831 OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
3832 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
3833 UNUSED_VARIABLE_VALUE(bRc);
3835 if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
3836 SimulateIOErrorBenign(1);
3837 winClose((sqlite3_file *)&p->hFile);
3838 SimulateIOErrorBenign(0);
3840 if( deleteFlag ){
3841 SimulateIOErrorBenign(1);
3842 sqlite3BeginBenignMalloc();
3843 winDelete(pVfs, p->zFilename, 0);
3844 sqlite3EndBenignMalloc();
3845 SimulateIOErrorBenign(0);
3847 *pp = p->pNext;
3848 sqlite3_free(p->aRegion);
3849 sqlite3_free(p);
3850 }else{
3851 pp = &p->pNext;
3857 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
3858 ** take it now. Return SQLITE_OK if successful, or an SQLite error
3859 ** code otherwise.
3861 ** If the DMS cannot be locked because this is a readonly_shm=1
3862 ** connection and no other process already holds a lock, return
3863 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
3865 static int winLockSharedMemory(winShmNode *pShmNode){
3866 int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
3868 if( rc==SQLITE_OK ){
3869 if( pShmNode->isReadonly ){
3870 pShmNode->isUnlocked = 1;
3871 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
3872 return SQLITE_READONLY_CANTINIT;
3873 }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
3874 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
3875 return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
3876 "winLockSharedMemory", pShmNode->zFilename);
3880 if( rc==SQLITE_OK ){
3881 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
3884 return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
3888 ** Open the shared-memory area associated with database file pDbFd.
3890 ** When opening a new shared-memory file, if no other instances of that
3891 ** file are currently open, in this process or in other processes, then
3892 ** the file must be truncated to zero length or have its header cleared.
3894 static int winOpenSharedMemory(winFile *pDbFd){
3895 struct winShm *p; /* The connection to be opened */
3896 winShmNode *pShmNode = 0; /* The underlying mmapped file */
3897 int rc = SQLITE_OK; /* Result code */
3898 winShmNode *pNew; /* Newly allocated winShmNode */
3899 int nName; /* Size of zName in bytes */
3901 assert( pDbFd->pShm==0 ); /* Not previously opened */
3903 /* Allocate space for the new sqlite3_shm object. Also speculatively
3904 ** allocate space for a new winShmNode and filename.
3906 p = sqlite3MallocZero( sizeof(*p) );
3907 if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
3908 nName = sqlite3Strlen30(pDbFd->zPath);
3909 pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
3910 if( pNew==0 ){
3911 sqlite3_free(p);
3912 return SQLITE_IOERR_NOMEM_BKPT;
3914 pNew->zFilename = (char*)&pNew[1];
3915 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
3916 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
3918 /* Look to see if there is an existing winShmNode that can be used.
3919 ** If no matching winShmNode currently exists, create a new one.
3921 winShmEnterMutex();
3922 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
3923 /* TBD need to come up with better match here. Perhaps
3924 ** use FILE_ID_BOTH_DIR_INFO Structure.
3926 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
3928 if( pShmNode ){
3929 sqlite3_free(pNew);
3930 }else{
3931 int inFlags = SQLITE_OPEN_WAL;
3932 int outFlags = 0;
3934 pShmNode = pNew;
3935 pNew = 0;
3936 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
3937 pShmNode->pNext = winShmNodeList;
3938 winShmNodeList = pShmNode;
3940 if( sqlite3GlobalConfig.bCoreMutex ){
3941 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3942 if( pShmNode->mutex==0 ){
3943 rc = SQLITE_IOERR_NOMEM_BKPT;
3944 goto shm_open_err;
3948 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
3949 inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
3950 }else{
3951 inFlags |= SQLITE_OPEN_READONLY;
3953 rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
3954 (sqlite3_file*)&pShmNode->hFile,
3955 inFlags, &outFlags);
3956 if( rc!=SQLITE_OK ){
3957 rc = winLogError(rc, osGetLastError(), "winOpenShm",
3958 pShmNode->zFilename);
3959 goto shm_open_err;
3961 if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
3963 rc = winLockSharedMemory(pShmNode);
3964 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
3967 /* Make the new connection a child of the winShmNode */
3968 p->pShmNode = pShmNode;
3969 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
3970 p->id = pShmNode->nextShmId++;
3971 #endif
3972 pShmNode->nRef++;
3973 pDbFd->pShm = p;
3974 winShmLeaveMutex();
3976 /* The reference count on pShmNode has already been incremented under
3977 ** the cover of the winShmEnterMutex() mutex and the pointer from the
3978 ** new (struct winShm) object to the pShmNode has been set. All that is
3979 ** left to do is to link the new object into the linked list starting
3980 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3981 ** mutex.
3983 sqlite3_mutex_enter(pShmNode->mutex);
3984 p->pNext = pShmNode->pFirst;
3985 pShmNode->pFirst = p;
3986 sqlite3_mutex_leave(pShmNode->mutex);
3987 return rc;
3989 /* Jump here on any error */
3990 shm_open_err:
3991 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
3992 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
3993 sqlite3_free(p);
3994 sqlite3_free(pNew);
3995 winShmLeaveMutex();
3996 return rc;
4000 ** Close a connection to shared-memory. Delete the underlying
4001 ** storage if deleteFlag is true.
4003 static int winShmUnmap(
4004 sqlite3_file *fd, /* Database holding shared memory */
4005 int deleteFlag /* Delete after closing if true */
4007 winFile *pDbFd; /* Database holding shared-memory */
4008 winShm *p; /* The connection to be closed */
4009 winShmNode *pShmNode; /* The underlying shared-memory file */
4010 winShm **pp; /* For looping over sibling connections */
4012 pDbFd = (winFile*)fd;
4013 p = pDbFd->pShm;
4014 if( p==0 ) return SQLITE_OK;
4015 pShmNode = p->pShmNode;
4017 /* Remove connection p from the set of connections associated
4018 ** with pShmNode */
4019 sqlite3_mutex_enter(pShmNode->mutex);
4020 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4021 *pp = p->pNext;
4023 /* Free the connection p */
4024 sqlite3_free(p);
4025 pDbFd->pShm = 0;
4026 sqlite3_mutex_leave(pShmNode->mutex);
4028 /* If pShmNode->nRef has reached 0, then close the underlying
4029 ** shared-memory file, too */
4030 winShmEnterMutex();
4031 assert( pShmNode->nRef>0 );
4032 pShmNode->nRef--;
4033 if( pShmNode->nRef==0 ){
4034 winShmPurge(pDbFd->pVfs, deleteFlag);
4036 winShmLeaveMutex();
4038 return SQLITE_OK;
4042 ** Change the lock state for a shared-memory segment.
4044 static int winShmLock(
4045 sqlite3_file *fd, /* Database file holding the shared memory */
4046 int ofst, /* First lock to acquire or release */
4047 int n, /* Number of locks to acquire or release */
4048 int flags /* What to do with the lock */
4050 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
4051 winShm *p = pDbFd->pShm; /* The shared memory being locked */
4052 winShm *pX; /* For looping over all siblings */
4053 winShmNode *pShmNode = p->pShmNode;
4054 int rc = SQLITE_OK; /* Result code */
4055 u16 mask; /* Mask of locks to take or release */
4057 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
4058 assert( n>=1 );
4059 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4060 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4061 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4062 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4063 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
4065 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
4066 assert( n>1 || mask==(1<<ofst) );
4067 sqlite3_mutex_enter(pShmNode->mutex);
4068 if( flags & SQLITE_SHM_UNLOCK ){
4069 u16 allMask = 0; /* Mask of locks held by siblings */
4071 /* See if any siblings hold this same lock */
4072 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4073 if( pX==p ) continue;
4074 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4075 allMask |= pX->sharedMask;
4078 /* Unlock the system-level locks */
4079 if( (mask & allMask)==0 ){
4080 rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
4081 }else{
4082 rc = SQLITE_OK;
4085 /* Undo the local locks */
4086 if( rc==SQLITE_OK ){
4087 p->exclMask &= ~mask;
4088 p->sharedMask &= ~mask;
4090 }else if( flags & SQLITE_SHM_SHARED ){
4091 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4093 /* Find out which shared locks are already held by sibling connections.
4094 ** If any sibling already holds an exclusive lock, go ahead and return
4095 ** SQLITE_BUSY.
4097 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4098 if( (pX->exclMask & mask)!=0 ){
4099 rc = SQLITE_BUSY;
4100 break;
4102 allShared |= pX->sharedMask;
4105 /* Get shared locks at the system level, if necessary */
4106 if( rc==SQLITE_OK ){
4107 if( (allShared & mask)==0 ){
4108 rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
4109 }else{
4110 rc = SQLITE_OK;
4114 /* Get the local shared locks */
4115 if( rc==SQLITE_OK ){
4116 p->sharedMask |= mask;
4118 }else{
4119 /* Make sure no sibling connections hold locks that will block this
4120 ** lock. If any do, return SQLITE_BUSY right away.
4122 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4123 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4124 rc = SQLITE_BUSY;
4125 break;
4129 /* Get the exclusive locks at the system level. Then if successful
4130 ** also mark the local connection as being locked.
4132 if( rc==SQLITE_OK ){
4133 rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
4134 if( rc==SQLITE_OK ){
4135 assert( (p->sharedMask & mask)==0 );
4136 p->exclMask |= mask;
4140 sqlite3_mutex_leave(pShmNode->mutex);
4141 OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
4142 osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
4143 sqlite3ErrName(rc)));
4144 return rc;
4148 ** Implement a memory barrier or memory fence on shared memory.
4150 ** All loads and stores begun before the barrier must complete before
4151 ** any load or store begun after the barrier.
4153 static void winShmBarrier(
4154 sqlite3_file *fd /* Database holding the shared memory */
4156 UNUSED_PARAMETER(fd);
4157 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4158 winShmEnterMutex(); /* Also mutex, for redundancy */
4159 winShmLeaveMutex();
4163 ** This function is called to obtain a pointer to region iRegion of the
4164 ** shared-memory associated with the database file fd. Shared-memory regions
4165 ** are numbered starting from zero. Each shared-memory region is szRegion
4166 ** bytes in size.
4168 ** If an error occurs, an error code is returned and *pp is set to NULL.
4170 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
4171 ** region has not been allocated (by any client, including one running in a
4172 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4173 ** isWrite is non-zero and the requested shared-memory region has not yet
4174 ** been allocated, it is allocated by this function.
4176 ** If the shared-memory region has already been allocated or is allocated by
4177 ** this call as described above, then it is mapped into this processes
4178 ** address space (if it is not already), *pp is set to point to the mapped
4179 ** memory and SQLITE_OK returned.
4181 static int winShmMap(
4182 sqlite3_file *fd, /* Handle open on database file */
4183 int iRegion, /* Region to retrieve */
4184 int szRegion, /* Size of regions */
4185 int isWrite, /* True to extend file if necessary */
4186 void volatile **pp /* OUT: Mapped memory */
4188 winFile *pDbFd = (winFile*)fd;
4189 winShm *pShm = pDbFd->pShm;
4190 winShmNode *pShmNode;
4191 DWORD protect = PAGE_READWRITE;
4192 DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
4193 int rc = SQLITE_OK;
4195 if( !pShm ){
4196 rc = winOpenSharedMemory(pDbFd);
4197 if( rc!=SQLITE_OK ) return rc;
4198 pShm = pDbFd->pShm;
4200 pShmNode = pShm->pShmNode;
4202 sqlite3_mutex_enter(pShmNode->mutex);
4203 if( pShmNode->isUnlocked ){
4204 rc = winLockSharedMemory(pShmNode);
4205 if( rc!=SQLITE_OK ) goto shmpage_out;
4206 pShmNode->isUnlocked = 0;
4208 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
4210 if( pShmNode->nRegion<=iRegion ){
4211 struct ShmRegion *apNew; /* New aRegion[] array */
4212 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4213 sqlite3_int64 sz; /* Current size of wal-index file */
4215 pShmNode->szRegion = szRegion;
4217 /* The requested region is not mapped into this processes address space.
4218 ** Check to see if it has been allocated (i.e. if the wal-index file is
4219 ** large enough to contain the requested region).
4221 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
4222 if( rc!=SQLITE_OK ){
4223 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
4224 "winShmMap1", pDbFd->zPath);
4225 goto shmpage_out;
4228 if( sz<nByte ){
4229 /* The requested memory region does not exist. If isWrite is set to
4230 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
4232 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
4233 ** the requested memory region.
4235 if( !isWrite ) goto shmpage_out;
4236 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
4237 if( rc!=SQLITE_OK ){
4238 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
4239 "winShmMap2", pDbFd->zPath);
4240 goto shmpage_out;
4244 /* Map the requested memory region into this processes address space. */
4245 apNew = (struct ShmRegion *)sqlite3_realloc64(
4246 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
4248 if( !apNew ){
4249 rc = SQLITE_IOERR_NOMEM_BKPT;
4250 goto shmpage_out;
4252 pShmNode->aRegion = apNew;
4254 if( pShmNode->isReadonly ){
4255 protect = PAGE_READONLY;
4256 flags = FILE_MAP_READ;
4259 while( pShmNode->nRegion<=iRegion ){
4260 HANDLE hMap = NULL; /* file-mapping handle */
4261 void *pMap = 0; /* Mapped memory region */
4263 #if SQLITE_OS_WINRT
4264 hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
4265 NULL, protect, nByte, NULL
4267 #elif defined(SQLITE_WIN32_HAS_WIDE)
4268 hMap = osCreateFileMappingW(pShmNode->hFile.h,
4269 NULL, protect, 0, nByte, NULL
4271 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
4272 hMap = osCreateFileMappingA(pShmNode->hFile.h,
4273 NULL, protect, 0, nByte, NULL
4275 #endif
4276 OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
4277 osGetCurrentProcessId(), pShmNode->nRegion, nByte,
4278 hMap ? "ok" : "failed"));
4279 if( hMap ){
4280 int iOffset = pShmNode->nRegion*szRegion;
4281 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
4282 #if SQLITE_OS_WINRT
4283 pMap = osMapViewOfFileFromApp(hMap, flags,
4284 iOffset - iOffsetShift, szRegion + iOffsetShift
4286 #else
4287 pMap = osMapViewOfFile(hMap, flags,
4288 0, iOffset - iOffsetShift, szRegion + iOffsetShift
4290 #endif
4291 OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
4292 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
4293 szRegion, pMap ? "ok" : "failed"));
4295 if( !pMap ){
4296 pShmNode->lastErrno = osGetLastError();
4297 rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
4298 "winShmMap3", pDbFd->zPath);
4299 if( hMap ) osCloseHandle(hMap);
4300 goto shmpage_out;
4303 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
4304 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
4305 pShmNode->nRegion++;
4309 shmpage_out:
4310 if( pShmNode->nRegion>iRegion ){
4311 int iOffset = iRegion*szRegion;
4312 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
4313 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
4314 *pp = (void *)&p[iOffsetShift];
4315 }else{
4316 *pp = 0;
4318 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
4319 sqlite3_mutex_leave(pShmNode->mutex);
4320 return rc;
4323 #else
4324 # define winShmMap 0
4325 # define winShmLock 0
4326 # define winShmBarrier 0
4327 # define winShmUnmap 0
4328 #endif /* #ifndef SQLITE_OMIT_WAL */
4331 ** Cleans up the mapped region of the specified file, if any.
4333 #if SQLITE_MAX_MMAP_SIZE>0
4334 static int winUnmapfile(winFile *pFile){
4335 assert( pFile!=0 );
4336 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
4337 "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
4338 osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
4339 pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
4340 if( pFile->pMapRegion ){
4341 if( !osUnmapViewOfFile(pFile->pMapRegion) ){
4342 pFile->lastErrno = osGetLastError();
4343 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
4344 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
4345 pFile->pMapRegion));
4346 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
4347 "winUnmapfile1", pFile->zPath);
4349 pFile->pMapRegion = 0;
4350 pFile->mmapSize = 0;
4351 pFile->mmapSizeActual = 0;
4353 if( pFile->hMap!=NULL ){
4354 if( !osCloseHandle(pFile->hMap) ){
4355 pFile->lastErrno = osGetLastError();
4356 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
4357 osGetCurrentProcessId(), pFile, pFile->hMap));
4358 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
4359 "winUnmapfile2", pFile->zPath);
4361 pFile->hMap = NULL;
4363 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
4364 osGetCurrentProcessId(), pFile));
4365 return SQLITE_OK;
4369 ** Memory map or remap the file opened by file-descriptor pFd (if the file
4370 ** is already mapped, the existing mapping is replaced by the new). Or, if
4371 ** there already exists a mapping for this file, and there are still
4372 ** outstanding xFetch() references to it, this function is a no-op.
4374 ** If parameter nByte is non-negative, then it is the requested size of
4375 ** the mapping to create. Otherwise, if nByte is less than zero, then the
4376 ** requested size is the size of the file on disk. The actual size of the
4377 ** created mapping is either the requested size or the value configured
4378 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
4380 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
4381 ** recreated as a result of outstanding references) or an SQLite error
4382 ** code otherwise.
4384 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
4385 sqlite3_int64 nMap = nByte;
4386 int rc;
4388 assert( nMap>=0 || pFd->nFetchOut==0 );
4389 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
4390 osGetCurrentProcessId(), pFd, nByte));
4392 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4394 if( nMap<0 ){
4395 rc = winFileSize((sqlite3_file*)pFd, &nMap);
4396 if( rc ){
4397 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
4398 osGetCurrentProcessId(), pFd));
4399 return SQLITE_IOERR_FSTAT;
4402 if( nMap>pFd->mmapSizeMax ){
4403 nMap = pFd->mmapSizeMax;
4405 nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
4407 if( nMap==0 && pFd->mmapSize>0 ){
4408 winUnmapfile(pFd);
4410 if( nMap!=pFd->mmapSize ){
4411 void *pNew = 0;
4412 DWORD protect = PAGE_READONLY;
4413 DWORD flags = FILE_MAP_READ;
4415 winUnmapfile(pFd);
4416 #ifdef SQLITE_MMAP_READWRITE
4417 if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
4418 protect = PAGE_READWRITE;
4419 flags |= FILE_MAP_WRITE;
4421 #endif
4422 #if SQLITE_OS_WINRT
4423 pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
4424 #elif defined(SQLITE_WIN32_HAS_WIDE)
4425 pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
4426 (DWORD)((nMap>>32) & 0xffffffff),
4427 (DWORD)(nMap & 0xffffffff), NULL);
4428 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
4429 pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
4430 (DWORD)((nMap>>32) & 0xffffffff),
4431 (DWORD)(nMap & 0xffffffff), NULL);
4432 #endif
4433 if( pFd->hMap==NULL ){
4434 pFd->lastErrno = osGetLastError();
4435 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
4436 "winMapfile1", pFd->zPath);
4437 /* Log the error, but continue normal operation using xRead/xWrite */
4438 OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
4439 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
4440 return SQLITE_OK;
4442 assert( (nMap % winSysInfo.dwPageSize)==0 );
4443 assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
4444 #if SQLITE_OS_WINRT
4445 pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
4446 #else
4447 pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
4448 #endif
4449 if( pNew==NULL ){
4450 osCloseHandle(pFd->hMap);
4451 pFd->hMap = NULL;
4452 pFd->lastErrno = osGetLastError();
4453 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
4454 "winMapfile2", pFd->zPath);
4455 /* Log the error, but continue normal operation using xRead/xWrite */
4456 OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
4457 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
4458 return SQLITE_OK;
4460 pFd->pMapRegion = pNew;
4461 pFd->mmapSize = nMap;
4462 pFd->mmapSizeActual = nMap;
4465 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
4466 osGetCurrentProcessId(), pFd));
4467 return SQLITE_OK;
4469 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
4472 ** If possible, return a pointer to a mapping of file fd starting at offset
4473 ** iOff. The mapping must be valid for at least nAmt bytes.
4475 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4476 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4477 ** Finally, if an error does occur, return an SQLite error code. The final
4478 ** value of *pp is undefined in this case.
4480 ** If this function does return a pointer, the caller must eventually
4481 ** release the reference by calling winUnfetch().
4483 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
4484 #if SQLITE_MAX_MMAP_SIZE>0
4485 winFile *pFd = (winFile*)fd; /* The underlying database file */
4486 #endif
4487 *pp = 0;
4489 OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
4490 osGetCurrentProcessId(), fd, iOff, nAmt, pp));
4492 #if SQLITE_MAX_MMAP_SIZE>0
4493 if( pFd->mmapSizeMax>0 ){
4494 if( pFd->pMapRegion==0 ){
4495 int rc = winMapfile(pFd, -1);
4496 if( rc!=SQLITE_OK ){
4497 OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
4498 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
4499 return rc;
4502 if( pFd->mmapSize >= iOff+nAmt ){
4503 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4504 pFd->nFetchOut++;
4507 #endif
4509 OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
4510 osGetCurrentProcessId(), fd, pp, *pp));
4511 return SQLITE_OK;
4515 ** If the third argument is non-NULL, then this function releases a
4516 ** reference obtained by an earlier call to winFetch(). The second
4517 ** argument passed to this function must be the same as the corresponding
4518 ** argument that was passed to the winFetch() invocation.
4520 ** Or, if the third argument is NULL, then this function is being called
4521 ** to inform the VFS layer that, according to POSIX, any existing mapping
4522 ** may now be invalid and should be unmapped.
4524 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
4525 #if SQLITE_MAX_MMAP_SIZE>0
4526 winFile *pFd = (winFile*)fd; /* The underlying database file */
4528 /* If p==0 (unmap the entire file) then there must be no outstanding
4529 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4530 ** then there must be at least one outstanding. */
4531 assert( (p==0)==(pFd->nFetchOut==0) );
4533 /* If p!=0, it must match the iOff value. */
4534 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4536 OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
4537 osGetCurrentProcessId(), pFd, iOff, p));
4539 if( p ){
4540 pFd->nFetchOut--;
4541 }else{
4542 /* FIXME: If Windows truly always prevents truncating or deleting a
4543 ** file while a mapping is held, then the following winUnmapfile() call
4544 ** is unnecessary can be omitted - potentially improving
4545 ** performance. */
4546 winUnmapfile(pFd);
4549 assert( pFd->nFetchOut>=0 );
4550 #endif
4552 OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
4553 osGetCurrentProcessId(), fd));
4554 return SQLITE_OK;
4558 ** Here ends the implementation of all sqlite3_file methods.
4560 ********************** End sqlite3_file Methods *******************************
4561 ******************************************************************************/
4564 ** This vector defines all the methods that can operate on an
4565 ** sqlite3_file for win32.
4567 static const sqlite3_io_methods winIoMethod = {
4568 3, /* iVersion */
4569 winClose, /* xClose */
4570 winRead, /* xRead */
4571 winWrite, /* xWrite */
4572 winTruncate, /* xTruncate */
4573 winSync, /* xSync */
4574 winFileSize, /* xFileSize */
4575 winLock, /* xLock */
4576 winUnlock, /* xUnlock */
4577 winCheckReservedLock, /* xCheckReservedLock */
4578 winFileControl, /* xFileControl */
4579 winSectorSize, /* xSectorSize */
4580 winDeviceCharacteristics, /* xDeviceCharacteristics */
4581 winShmMap, /* xShmMap */
4582 winShmLock, /* xShmLock */
4583 winShmBarrier, /* xShmBarrier */
4584 winShmUnmap, /* xShmUnmap */
4585 winFetch, /* xFetch */
4586 winUnfetch /* xUnfetch */
4590 ** This vector defines all the methods that can operate on an
4591 ** sqlite3_file for win32 without performing any locking.
4593 static const sqlite3_io_methods winIoNolockMethod = {
4594 3, /* iVersion */
4595 winClose, /* xClose */
4596 winRead, /* xRead */
4597 winWrite, /* xWrite */
4598 winTruncate, /* xTruncate */
4599 winSync, /* xSync */
4600 winFileSize, /* xFileSize */
4601 winNolockLock, /* xLock */
4602 winNolockUnlock, /* xUnlock */
4603 winNolockCheckReservedLock, /* xCheckReservedLock */
4604 winFileControl, /* xFileControl */
4605 winSectorSize, /* xSectorSize */
4606 winDeviceCharacteristics, /* xDeviceCharacteristics */
4607 winShmMap, /* xShmMap */
4608 winShmLock, /* xShmLock */
4609 winShmBarrier, /* xShmBarrier */
4610 winShmUnmap, /* xShmUnmap */
4611 winFetch, /* xFetch */
4612 winUnfetch /* xUnfetch */
4615 static winVfsAppData winAppData = {
4616 &winIoMethod, /* pMethod */
4617 0, /* pAppData */
4618 0 /* bNoLock */
4621 static winVfsAppData winNolockAppData = {
4622 &winIoNolockMethod, /* pMethod */
4623 0, /* pAppData */
4624 1 /* bNoLock */
4627 /****************************************************************************
4628 **************************** sqlite3_vfs methods ****************************
4630 ** This division contains the implementation of methods on the
4631 ** sqlite3_vfs object.
4634 #if defined(__CYGWIN__)
4636 ** Convert a filename from whatever the underlying operating system
4637 ** supports for filenames into UTF-8. Space to hold the result is
4638 ** obtained from malloc and must be freed by the calling function.
4640 static char *winConvertToUtf8Filename(const void *zFilename){
4641 char *zConverted = 0;
4642 if( osIsNT() ){
4643 zConverted = winUnicodeToUtf8(zFilename);
4645 #ifdef SQLITE_WIN32_HAS_ANSI
4646 else{
4647 zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
4649 #endif
4650 /* caller will handle out of memory */
4651 return zConverted;
4653 #endif
4656 ** Convert a UTF-8 filename into whatever form the underlying
4657 ** operating system wants filenames in. Space to hold the result
4658 ** is obtained from malloc and must be freed by the calling
4659 ** function.
4661 static void *winConvertFromUtf8Filename(const char *zFilename){
4662 void *zConverted = 0;
4663 if( osIsNT() ){
4664 zConverted = winUtf8ToUnicode(zFilename);
4666 #ifdef SQLITE_WIN32_HAS_ANSI
4667 else{
4668 zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
4670 #endif
4671 /* caller will handle out of memory */
4672 return zConverted;
4676 ** This function returns non-zero if the specified UTF-8 string buffer
4677 ** ends with a directory separator character or one was successfully
4678 ** added to it.
4680 static int winMakeEndInDirSep(int nBuf, char *zBuf){
4681 if( zBuf ){
4682 int nLen = sqlite3Strlen30(zBuf);
4683 if( nLen>0 ){
4684 if( winIsDirSep(zBuf[nLen-1]) ){
4685 return 1;
4686 }else if( nLen+1<nBuf ){
4687 zBuf[nLen] = winGetDirSep();
4688 zBuf[nLen+1] = '\0';
4689 return 1;
4693 return 0;
4697 ** Create a temporary file name and store the resulting pointer into pzBuf.
4698 ** The pointer returned in pzBuf must be freed via sqlite3_free().
4700 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
4701 static char zChars[] =
4702 "abcdefghijklmnopqrstuvwxyz"
4703 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4704 "0123456789";
4705 size_t i, j;
4706 int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
4707 int nMax, nBuf, nDir, nLen;
4708 char *zBuf;
4710 /* It's odd to simulate an io-error here, but really this is just
4711 ** using the io-error infrastructure to test that SQLite handles this
4712 ** function failing.
4714 SimulateIOError( return SQLITE_IOERR );
4716 /* Allocate a temporary buffer to store the fully qualified file
4717 ** name for the temporary file. If this fails, we cannot continue.
4719 nMax = pVfs->mxPathname; nBuf = nMax + 2;
4720 zBuf = sqlite3MallocZero( nBuf );
4721 if( !zBuf ){
4722 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4723 return SQLITE_IOERR_NOMEM_BKPT;
4726 /* Figure out the effective temporary directory. First, check if one
4727 ** has been explicitly set by the application; otherwise, use the one
4728 ** configured by the operating system.
4730 nDir = nMax - (nPre + 15);
4731 assert( nDir>0 );
4732 if( sqlite3_temp_directory ){
4733 int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
4734 if( nDirLen>0 ){
4735 if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
4736 nDirLen++;
4738 if( nDirLen>nDir ){
4739 sqlite3_free(zBuf);
4740 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
4741 return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
4743 sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
4746 #if defined(__CYGWIN__)
4747 else{
4748 static const char *azDirs[] = {
4749 0, /* getenv("SQLITE_TMPDIR") */
4750 0, /* getenv("TMPDIR") */
4751 0, /* getenv("TMP") */
4752 0, /* getenv("TEMP") */
4753 0, /* getenv("USERPROFILE") */
4754 "/var/tmp",
4755 "/usr/tmp",
4756 "/tmp",
4757 ".",
4758 0 /* List terminator */
4760 unsigned int i;
4761 const char *zDir = 0;
4763 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
4764 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
4765 if( !azDirs[2] ) azDirs[2] = getenv("TMP");
4766 if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
4767 if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
4768 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
4769 void *zConverted;
4770 if( zDir==0 ) continue;
4771 /* If the path starts with a drive letter followed by the colon
4772 ** character, assume it is already a native Win32 path; otherwise,
4773 ** it must be converted to a native Win32 path via the Cygwin API
4774 ** prior to using it.
4776 if( winIsDriveLetterAndColon(zDir) ){
4777 zConverted = winConvertFromUtf8Filename(zDir);
4778 if( !zConverted ){
4779 sqlite3_free(zBuf);
4780 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4781 return SQLITE_IOERR_NOMEM_BKPT;
4783 if( winIsDir(zConverted) ){
4784 sqlite3_snprintf(nMax, zBuf, "%s", zDir);
4785 sqlite3_free(zConverted);
4786 break;
4788 sqlite3_free(zConverted);
4789 }else{
4790 zConverted = sqlite3MallocZero( nMax+1 );
4791 if( !zConverted ){
4792 sqlite3_free(zBuf);
4793 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4794 return SQLITE_IOERR_NOMEM_BKPT;
4796 if( cygwin_conv_path(
4797 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
4798 zConverted, nMax+1)<0 ){
4799 sqlite3_free(zConverted);
4800 sqlite3_free(zBuf);
4801 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
4802 return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
4803 "winGetTempname2", zDir);
4805 if( winIsDir(zConverted) ){
4806 /* At this point, we know the candidate directory exists and should
4807 ** be used. However, we may need to convert the string containing
4808 ** its name into UTF-8 (i.e. if it is UTF-16 right now).
4810 char *zUtf8 = winConvertToUtf8Filename(zConverted);
4811 if( !zUtf8 ){
4812 sqlite3_free(zConverted);
4813 sqlite3_free(zBuf);
4814 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4815 return SQLITE_IOERR_NOMEM_BKPT;
4817 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
4818 sqlite3_free(zUtf8);
4819 sqlite3_free(zConverted);
4820 break;
4822 sqlite3_free(zConverted);
4826 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
4827 else if( osIsNT() ){
4828 char *zMulti;
4829 LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
4830 if( !zWidePath ){
4831 sqlite3_free(zBuf);
4832 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4833 return SQLITE_IOERR_NOMEM_BKPT;
4835 if( osGetTempPathW(nMax, zWidePath)==0 ){
4836 sqlite3_free(zWidePath);
4837 sqlite3_free(zBuf);
4838 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
4839 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
4840 "winGetTempname2", 0);
4842 zMulti = winUnicodeToUtf8(zWidePath);
4843 if( zMulti ){
4844 sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
4845 sqlite3_free(zMulti);
4846 sqlite3_free(zWidePath);
4847 }else{
4848 sqlite3_free(zWidePath);
4849 sqlite3_free(zBuf);
4850 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4851 return SQLITE_IOERR_NOMEM_BKPT;
4854 #ifdef SQLITE_WIN32_HAS_ANSI
4855 else{
4856 char *zUtf8;
4857 char *zMbcsPath = sqlite3MallocZero( nMax );
4858 if( !zMbcsPath ){
4859 sqlite3_free(zBuf);
4860 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4861 return SQLITE_IOERR_NOMEM_BKPT;
4863 if( osGetTempPathA(nMax, zMbcsPath)==0 ){
4864 sqlite3_free(zBuf);
4865 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
4866 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
4867 "winGetTempname3", 0);
4869 zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
4870 if( zUtf8 ){
4871 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
4872 sqlite3_free(zUtf8);
4873 }else{
4874 sqlite3_free(zBuf);
4875 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4876 return SQLITE_IOERR_NOMEM_BKPT;
4879 #endif /* SQLITE_WIN32_HAS_ANSI */
4880 #endif /* !SQLITE_OS_WINRT */
4883 ** Check to make sure the temporary directory ends with an appropriate
4884 ** separator. If it does not and there is not enough space left to add
4885 ** one, fail.
4887 if( !winMakeEndInDirSep(nDir+1, zBuf) ){
4888 sqlite3_free(zBuf);
4889 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
4890 return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
4894 ** Check that the output buffer is large enough for the temporary file
4895 ** name in the following format:
4897 ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
4899 ** If not, return SQLITE_ERROR. The number 17 is used here in order to
4900 ** account for the space used by the 15 character random suffix and the
4901 ** two trailing NUL characters. The final directory separator character
4902 ** has already added if it was not already present.
4904 nLen = sqlite3Strlen30(zBuf);
4905 if( (nLen + nPre + 17) > nBuf ){
4906 sqlite3_free(zBuf);
4907 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
4908 return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
4911 sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
4913 j = sqlite3Strlen30(zBuf);
4914 sqlite3_randomness(15, &zBuf[j]);
4915 for(i=0; i<15; i++, j++){
4916 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4918 zBuf[j] = 0;
4919 zBuf[j+1] = 0;
4920 *pzBuf = zBuf;
4922 OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
4923 return SQLITE_OK;
4927 ** Return TRUE if the named file is really a directory. Return false if
4928 ** it is something other than a directory, or if there is any kind of memory
4929 ** allocation failure.
4931 static int winIsDir(const void *zConverted){
4932 DWORD attr;
4933 int rc = 0;
4934 DWORD lastErrno;
4936 if( osIsNT() ){
4937 int cnt = 0;
4938 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
4939 memset(&sAttrData, 0, sizeof(sAttrData));
4940 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
4941 GetFileExInfoStandard,
4942 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
4943 if( !rc ){
4944 return 0; /* Invalid name? */
4946 attr = sAttrData.dwFileAttributes;
4947 #if SQLITE_OS_WINCE==0
4948 }else{
4949 attr = osGetFileAttributesA((char*)zConverted);
4950 #endif
4952 return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
4955 /* forward reference */
4956 static int winAccess(
4957 sqlite3_vfs *pVfs, /* Not used on win32 */
4958 const char *zFilename, /* Name of file to check */
4959 int flags, /* Type of test to make on this file */
4960 int *pResOut /* OUT: Result */
4964 ** Open a file.
4966 static int winOpen(
4967 sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
4968 const char *zName, /* Name of the file (UTF-8) */
4969 sqlite3_file *id, /* Write the SQLite file handle here */
4970 int flags, /* Open mode flags */
4971 int *pOutFlags /* Status return flags */
4973 HANDLE h;
4974 DWORD lastErrno = 0;
4975 DWORD dwDesiredAccess;
4976 DWORD dwShareMode;
4977 DWORD dwCreationDisposition;
4978 DWORD dwFlagsAndAttributes = 0;
4979 #if SQLITE_OS_WINCE
4980 int isTemp = 0;
4981 #endif
4982 winVfsAppData *pAppData;
4983 winFile *pFile = (winFile*)id;
4984 void *zConverted; /* Filename in OS encoding */
4985 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
4986 int cnt = 0;
4988 /* If argument zPath is a NULL pointer, this function is required to open
4989 ** a temporary file. Use this buffer to store the file name in.
4991 char *zTmpname = 0; /* For temporary filename, if necessary. */
4993 int rc = SQLITE_OK; /* Function Return Code */
4994 #if !defined(NDEBUG) || SQLITE_OS_WINCE
4995 int eType = flags&0xFFFFFF00; /* Type of file to open */
4996 #endif
4998 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4999 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5000 int isCreate = (flags & SQLITE_OPEN_CREATE);
5001 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5002 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
5004 #ifndef NDEBUG
5005 int isOpenJournal = (isCreate && (
5006 eType==SQLITE_OPEN_MASTER_JOURNAL
5007 || eType==SQLITE_OPEN_MAIN_JOURNAL
5008 || eType==SQLITE_OPEN_WAL
5010 #endif
5012 OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
5013 zUtf8Name, id, flags, pOutFlags));
5015 /* Check the following statements are true:
5017 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5018 ** (b) if CREATE is set, then READWRITE must also be set, and
5019 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
5020 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
5022 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
5023 assert(isCreate==0 || isReadWrite);
5024 assert(isExclusive==0 || isCreate);
5025 assert(isDelete==0 || isCreate);
5027 /* The main DB, main journal, WAL file and master journal are never
5028 ** automatically deleted. Nor are they ever temporary files. */
5029 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5030 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5031 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
5032 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
5034 /* Assert that the upper layer has set one of the "file-type" flags. */
5035 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5036 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5037 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
5038 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
5041 assert( pFile!=0 );
5042 memset(pFile, 0, sizeof(winFile));
5043 pFile->h = INVALID_HANDLE_VALUE;
5045 #if SQLITE_OS_WINRT
5046 if( !zUtf8Name && !sqlite3_temp_directory ){
5047 sqlite3_log(SQLITE_ERROR,
5048 "sqlite3_temp_directory variable should be set for WinRT");
5050 #endif
5052 /* If the second argument to this function is NULL, generate a
5053 ** temporary file name to use
5055 if( !zUtf8Name ){
5056 assert( isDelete && !isOpenJournal );
5057 rc = winGetTempname(pVfs, &zTmpname);
5058 if( rc!=SQLITE_OK ){
5059 OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
5060 return rc;
5062 zUtf8Name = zTmpname;
5065 /* Database filenames are double-zero terminated if they are not
5066 ** URIs with parameters. Hence, they can always be passed into
5067 ** sqlite3_uri_parameter().
5069 assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
5070 zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
5072 /* Convert the filename to the system encoding. */
5073 zConverted = winConvertFromUtf8Filename(zUtf8Name);
5074 if( zConverted==0 ){
5075 sqlite3_free(zTmpname);
5076 OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
5077 return SQLITE_IOERR_NOMEM_BKPT;
5080 if( winIsDir(zConverted) ){
5081 sqlite3_free(zConverted);
5082 sqlite3_free(zTmpname);
5083 OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
5084 return SQLITE_CANTOPEN_ISDIR;
5087 if( isReadWrite ){
5088 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
5089 }else{
5090 dwDesiredAccess = GENERIC_READ;
5093 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
5094 ** created. SQLite doesn't use it to indicate "exclusive access"
5095 ** as it is usually understood.
5097 if( isExclusive ){
5098 /* Creates a new file, only if it does not already exist. */
5099 /* If the file exists, it fails. */
5100 dwCreationDisposition = CREATE_NEW;
5101 }else if( isCreate ){
5102 /* Open existing file, or create if it doesn't exist */
5103 dwCreationDisposition = OPEN_ALWAYS;
5104 }else{
5105 /* Opens a file, only if it exists. */
5106 dwCreationDisposition = OPEN_EXISTING;
5109 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
5111 if( isDelete ){
5112 #if SQLITE_OS_WINCE
5113 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
5114 isTemp = 1;
5115 #else
5116 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
5117 | FILE_ATTRIBUTE_HIDDEN
5118 | FILE_FLAG_DELETE_ON_CLOSE;
5119 #endif
5120 }else{
5121 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
5123 /* Reports from the internet are that performance is always
5124 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
5125 #if SQLITE_OS_WINCE
5126 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
5127 #endif
5129 if( osIsNT() ){
5130 #if SQLITE_OS_WINRT
5131 CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
5132 extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
5133 extendedParameters.dwFileAttributes =
5134 dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
5135 extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
5136 extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
5137 extendedParameters.lpSecurityAttributes = NULL;
5138 extendedParameters.hTemplateFile = NULL;
5140 h = osCreateFile2((LPCWSTR)zConverted,
5141 dwDesiredAccess,
5142 dwShareMode,
5143 dwCreationDisposition,
5144 &extendedParameters);
5145 if( h!=INVALID_HANDLE_VALUE ) break;
5146 if( isReadWrite ){
5147 int rc2, isRO = 0;
5148 sqlite3BeginBenignMalloc();
5149 rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
5150 sqlite3EndBenignMalloc();
5151 if( rc2==SQLITE_OK && isRO ) break;
5153 }while( winRetryIoerr(&cnt, &lastErrno) );
5154 #else
5156 h = osCreateFileW((LPCWSTR)zConverted,
5157 dwDesiredAccess,
5158 dwShareMode, NULL,
5159 dwCreationDisposition,
5160 dwFlagsAndAttributes,
5161 NULL);
5162 if( h!=INVALID_HANDLE_VALUE ) break;
5163 if( isReadWrite ){
5164 int rc2, isRO = 0;
5165 sqlite3BeginBenignMalloc();
5166 rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
5167 sqlite3EndBenignMalloc();
5168 if( rc2==SQLITE_OK && isRO ) break;
5170 }while( winRetryIoerr(&cnt, &lastErrno) );
5171 #endif
5173 #ifdef SQLITE_WIN32_HAS_ANSI
5174 else{
5176 h = osCreateFileA((LPCSTR)zConverted,
5177 dwDesiredAccess,
5178 dwShareMode, NULL,
5179 dwCreationDisposition,
5180 dwFlagsAndAttributes,
5181 NULL);
5182 if( h!=INVALID_HANDLE_VALUE ) break;
5183 if( isReadWrite ){
5184 int rc2, isRO = 0;
5185 sqlite3BeginBenignMalloc();
5186 rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
5187 sqlite3EndBenignMalloc();
5188 if( rc2==SQLITE_OK && isRO ) break;
5190 }while( winRetryIoerr(&cnt, &lastErrno) );
5192 #endif
5193 winLogIoerr(cnt, __LINE__);
5195 OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
5196 dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
5198 if( h==INVALID_HANDLE_VALUE ){
5199 sqlite3_free(zConverted);
5200 sqlite3_free(zTmpname);
5201 if( isReadWrite && !isExclusive ){
5202 return winOpen(pVfs, zName, id,
5203 ((flags|SQLITE_OPEN_READONLY) &
5204 ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
5205 pOutFlags);
5206 }else{
5207 pFile->lastErrno = lastErrno;
5208 winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
5209 return SQLITE_CANTOPEN_BKPT;
5213 if( pOutFlags ){
5214 if( isReadWrite ){
5215 *pOutFlags = SQLITE_OPEN_READWRITE;
5216 }else{
5217 *pOutFlags = SQLITE_OPEN_READONLY;
5221 OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
5222 "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
5223 *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
5225 pAppData = (winVfsAppData*)pVfs->pAppData;
5227 #if SQLITE_OS_WINCE
5229 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
5230 && ((pAppData==NULL) || !pAppData->bNoLock)
5231 && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
5233 osCloseHandle(h);
5234 sqlite3_free(zConverted);
5235 sqlite3_free(zTmpname);
5236 OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
5237 return rc;
5240 if( isTemp ){
5241 pFile->zDeleteOnClose = zConverted;
5242 }else
5243 #endif
5245 sqlite3_free(zConverted);
5248 sqlite3_free(zTmpname);
5249 pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
5250 pFile->pVfs = pVfs;
5251 pFile->h = h;
5252 if( isReadonly ){
5253 pFile->ctrlFlags |= WINFILE_RDONLY;
5255 if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
5256 pFile->ctrlFlags |= WINFILE_PSOW;
5258 pFile->lastErrno = NO_ERROR;
5259 pFile->zPath = zName;
5260 #if SQLITE_MAX_MMAP_SIZE>0
5261 pFile->hMap = NULL;
5262 pFile->pMapRegion = 0;
5263 pFile->mmapSize = 0;
5264 pFile->mmapSizeActual = 0;
5265 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
5266 #endif
5268 OpenCounter(+1);
5269 return rc;
5273 ** Delete the named file.
5275 ** Note that Windows does not allow a file to be deleted if some other
5276 ** process has it open. Sometimes a virus scanner or indexing program
5277 ** will open a journal file shortly after it is created in order to do
5278 ** whatever it does. While this other process is holding the
5279 ** file open, we will be unable to delete it. To work around this
5280 ** problem, we delay 100 milliseconds and try to delete again. Up
5281 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
5282 ** up and returning an error.
5284 static int winDelete(
5285 sqlite3_vfs *pVfs, /* Not used on win32 */
5286 const char *zFilename, /* Name of file to delete */
5287 int syncDir /* Not used on win32 */
5289 int cnt = 0;
5290 int rc;
5291 DWORD attr;
5292 DWORD lastErrno = 0;
5293 void *zConverted;
5294 UNUSED_PARAMETER(pVfs);
5295 UNUSED_PARAMETER(syncDir);
5297 SimulateIOError(return SQLITE_IOERR_DELETE);
5298 OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
5300 zConverted = winConvertFromUtf8Filename(zFilename);
5301 if( zConverted==0 ){
5302 OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
5303 return SQLITE_IOERR_NOMEM_BKPT;
5305 if( osIsNT() ){
5306 do {
5307 #if SQLITE_OS_WINRT
5308 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
5309 memset(&sAttrData, 0, sizeof(sAttrData));
5310 if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
5311 &sAttrData) ){
5312 attr = sAttrData.dwFileAttributes;
5313 }else{
5314 lastErrno = osGetLastError();
5315 if( lastErrno==ERROR_FILE_NOT_FOUND
5316 || lastErrno==ERROR_PATH_NOT_FOUND ){
5317 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
5318 }else{
5319 rc = SQLITE_ERROR;
5321 break;
5323 #else
5324 attr = osGetFileAttributesW(zConverted);
5325 #endif
5326 if ( attr==INVALID_FILE_ATTRIBUTES ){
5327 lastErrno = osGetLastError();
5328 if( lastErrno==ERROR_FILE_NOT_FOUND
5329 || lastErrno==ERROR_PATH_NOT_FOUND ){
5330 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
5331 }else{
5332 rc = SQLITE_ERROR;
5334 break;
5336 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
5337 rc = SQLITE_ERROR; /* Files only. */
5338 break;
5340 if ( osDeleteFileW(zConverted) ){
5341 rc = SQLITE_OK; /* Deleted OK. */
5342 break;
5344 if ( !winRetryIoerr(&cnt, &lastErrno) ){
5345 rc = SQLITE_ERROR; /* No more retries. */
5346 break;
5348 } while(1);
5350 #ifdef SQLITE_WIN32_HAS_ANSI
5351 else{
5352 do {
5353 attr = osGetFileAttributesA(zConverted);
5354 if ( attr==INVALID_FILE_ATTRIBUTES ){
5355 lastErrno = osGetLastError();
5356 if( lastErrno==ERROR_FILE_NOT_FOUND
5357 || lastErrno==ERROR_PATH_NOT_FOUND ){
5358 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
5359 }else{
5360 rc = SQLITE_ERROR;
5362 break;
5364 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
5365 rc = SQLITE_ERROR; /* Files only. */
5366 break;
5368 if ( osDeleteFileA(zConverted) ){
5369 rc = SQLITE_OK; /* Deleted OK. */
5370 break;
5372 if ( !winRetryIoerr(&cnt, &lastErrno) ){
5373 rc = SQLITE_ERROR; /* No more retries. */
5374 break;
5376 } while(1);
5378 #endif
5379 if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
5380 rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
5381 }else{
5382 winLogIoerr(cnt, __LINE__);
5384 sqlite3_free(zConverted);
5385 OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
5386 return rc;
5390 ** Check the existence and status of a file.
5392 static int winAccess(
5393 sqlite3_vfs *pVfs, /* Not used on win32 */
5394 const char *zFilename, /* Name of file to check */
5395 int flags, /* Type of test to make on this file */
5396 int *pResOut /* OUT: Result */
5398 DWORD attr;
5399 int rc = 0;
5400 DWORD lastErrno = 0;
5401 void *zConverted;
5402 UNUSED_PARAMETER(pVfs);
5404 SimulateIOError( return SQLITE_IOERR_ACCESS; );
5405 OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
5406 zFilename, flags, pResOut));
5408 zConverted = winConvertFromUtf8Filename(zFilename);
5409 if( zConverted==0 ){
5410 OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
5411 return SQLITE_IOERR_NOMEM_BKPT;
5413 if( osIsNT() ){
5414 int cnt = 0;
5415 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
5416 memset(&sAttrData, 0, sizeof(sAttrData));
5417 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
5418 GetFileExInfoStandard,
5419 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
5420 if( rc ){
5421 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
5422 ** as if it does not exist.
5424 if( flags==SQLITE_ACCESS_EXISTS
5425 && sAttrData.nFileSizeHigh==0
5426 && sAttrData.nFileSizeLow==0 ){
5427 attr = INVALID_FILE_ATTRIBUTES;
5428 }else{
5429 attr = sAttrData.dwFileAttributes;
5431 }else{
5432 winLogIoerr(cnt, __LINE__);
5433 if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
5434 sqlite3_free(zConverted);
5435 return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
5436 zFilename);
5437 }else{
5438 attr = INVALID_FILE_ATTRIBUTES;
5442 #ifdef SQLITE_WIN32_HAS_ANSI
5443 else{
5444 attr = osGetFileAttributesA((char*)zConverted);
5446 #endif
5447 sqlite3_free(zConverted);
5448 switch( flags ){
5449 case SQLITE_ACCESS_READ:
5450 case SQLITE_ACCESS_EXISTS:
5451 rc = attr!=INVALID_FILE_ATTRIBUTES;
5452 break;
5453 case SQLITE_ACCESS_READWRITE:
5454 rc = attr!=INVALID_FILE_ATTRIBUTES &&
5455 (attr & FILE_ATTRIBUTE_READONLY)==0;
5456 break;
5457 default:
5458 assert(!"Invalid flags argument");
5460 *pResOut = rc;
5461 OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
5462 zFilename, pResOut, *pResOut));
5463 return SQLITE_OK;
5467 ** Returns non-zero if the specified path name starts with a drive letter
5468 ** followed by a colon character.
5470 static BOOL winIsDriveLetterAndColon(
5471 const char *zPathname
5473 return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
5477 ** Returns non-zero if the specified path name should be used verbatim. If
5478 ** non-zero is returned from this function, the calling function must simply
5479 ** use the provided path name verbatim -OR- resolve it into a full path name
5480 ** using the GetFullPathName Win32 API function (if available).
5482 static BOOL winIsVerbatimPathname(
5483 const char *zPathname
5486 ** If the path name starts with a forward slash or a backslash, it is either
5487 ** a legal UNC name, a volume relative path, or an absolute path name in the
5488 ** "Unix" format on Windows. There is no easy way to differentiate between
5489 ** the final two cases; therefore, we return the safer return value of TRUE
5490 ** so that callers of this function will simply use it verbatim.
5492 if ( winIsDirSep(zPathname[0]) ){
5493 return TRUE;
5497 ** If the path name starts with a letter and a colon it is either a volume
5498 ** relative path or an absolute path. Callers of this function must not
5499 ** attempt to treat it as a relative path name (i.e. they should simply use
5500 ** it verbatim).
5502 if ( winIsDriveLetterAndColon(zPathname) ){
5503 return TRUE;
5507 ** If we get to this point, the path name should almost certainly be a purely
5508 ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
5510 return FALSE;
5514 ** Turn a relative pathname into a full pathname. Write the full
5515 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
5516 ** bytes in size.
5518 static int winFullPathname(
5519 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5520 const char *zRelative, /* Possibly relative input path */
5521 int nFull, /* Size of output buffer in bytes */
5522 char *zFull /* Output buffer */
5524 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
5525 DWORD nByte;
5526 void *zConverted;
5527 char *zOut;
5528 #endif
5530 /* If this path name begins with "/X:", where "X" is any alphabetic
5531 ** character, discard the initial "/" from the pathname.
5533 if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
5534 zRelative++;
5537 #if defined(__CYGWIN__)
5538 SimulateIOError( return SQLITE_ERROR );
5539 UNUSED_PARAMETER(nFull);
5540 assert( nFull>=pVfs->mxPathname );
5541 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
5543 ** NOTE: We are dealing with a relative path name and the data
5544 ** directory has been set. Therefore, use it as the basis
5545 ** for converting the relative path name to an absolute
5546 ** one by prepending the data directory and a slash.
5548 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
5549 if( !zOut ){
5550 return SQLITE_IOERR_NOMEM_BKPT;
5552 if( cygwin_conv_path(
5553 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
5554 CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
5555 sqlite3_free(zOut);
5556 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
5557 "winFullPathname1", zRelative);
5558 }else{
5559 char *zUtf8 = winConvertToUtf8Filename(zOut);
5560 if( !zUtf8 ){
5561 sqlite3_free(zOut);
5562 return SQLITE_IOERR_NOMEM_BKPT;
5564 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
5565 sqlite3_data_directory, winGetDirSep(), zUtf8);
5566 sqlite3_free(zUtf8);
5567 sqlite3_free(zOut);
5569 }else{
5570 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
5571 if( !zOut ){
5572 return SQLITE_IOERR_NOMEM_BKPT;
5574 if( cygwin_conv_path(
5575 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
5576 zRelative, zOut, pVfs->mxPathname+1)<0 ){
5577 sqlite3_free(zOut);
5578 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
5579 "winFullPathname2", zRelative);
5580 }else{
5581 char *zUtf8 = winConvertToUtf8Filename(zOut);
5582 if( !zUtf8 ){
5583 sqlite3_free(zOut);
5584 return SQLITE_IOERR_NOMEM_BKPT;
5586 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
5587 sqlite3_free(zUtf8);
5588 sqlite3_free(zOut);
5591 return SQLITE_OK;
5592 #endif
5594 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
5595 SimulateIOError( return SQLITE_ERROR );
5596 /* WinCE has no concept of a relative pathname, or so I am told. */
5597 /* WinRT has no way to convert a relative path to an absolute one. */
5598 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
5600 ** NOTE: We are dealing with a relative path name and the data
5601 ** directory has been set. Therefore, use it as the basis
5602 ** for converting the relative path name to an absolute
5603 ** one by prepending the data directory and a backslash.
5605 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
5606 sqlite3_data_directory, winGetDirSep(), zRelative);
5607 }else{
5608 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
5610 return SQLITE_OK;
5611 #endif
5613 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
5614 /* It's odd to simulate an io-error here, but really this is just
5615 ** using the io-error infrastructure to test that SQLite handles this
5616 ** function failing. This function could fail if, for example, the
5617 ** current working directory has been unlinked.
5619 SimulateIOError( return SQLITE_ERROR );
5620 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
5622 ** NOTE: We are dealing with a relative path name and the data
5623 ** directory has been set. Therefore, use it as the basis
5624 ** for converting the relative path name to an absolute
5625 ** one by prepending the data directory and a backslash.
5627 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
5628 sqlite3_data_directory, winGetDirSep(), zRelative);
5629 return SQLITE_OK;
5631 zConverted = winConvertFromUtf8Filename(zRelative);
5632 if( zConverted==0 ){
5633 return SQLITE_IOERR_NOMEM_BKPT;
5635 if( osIsNT() ){
5636 LPWSTR zTemp;
5637 nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
5638 if( nByte==0 ){
5639 sqlite3_free(zConverted);
5640 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
5641 "winFullPathname1", zRelative);
5643 nByte += 3;
5644 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
5645 if( zTemp==0 ){
5646 sqlite3_free(zConverted);
5647 return SQLITE_IOERR_NOMEM_BKPT;
5649 nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
5650 if( nByte==0 ){
5651 sqlite3_free(zConverted);
5652 sqlite3_free(zTemp);
5653 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
5654 "winFullPathname2", zRelative);
5656 sqlite3_free(zConverted);
5657 zOut = winUnicodeToUtf8(zTemp);
5658 sqlite3_free(zTemp);
5660 #ifdef SQLITE_WIN32_HAS_ANSI
5661 else{
5662 char *zTemp;
5663 nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
5664 if( nByte==0 ){
5665 sqlite3_free(zConverted);
5666 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
5667 "winFullPathname3", zRelative);
5669 nByte += 3;
5670 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
5671 if( zTemp==0 ){
5672 sqlite3_free(zConverted);
5673 return SQLITE_IOERR_NOMEM_BKPT;
5675 nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
5676 if( nByte==0 ){
5677 sqlite3_free(zConverted);
5678 sqlite3_free(zTemp);
5679 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
5680 "winFullPathname4", zRelative);
5682 sqlite3_free(zConverted);
5683 zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
5684 sqlite3_free(zTemp);
5686 #endif
5687 if( zOut ){
5688 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
5689 sqlite3_free(zOut);
5690 return SQLITE_OK;
5691 }else{
5692 return SQLITE_IOERR_NOMEM_BKPT;
5694 #endif
5697 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5699 ** Interfaces for opening a shared library, finding entry points
5700 ** within the shared library, and closing the shared library.
5702 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
5703 HANDLE h;
5704 #if defined(__CYGWIN__)
5705 int nFull = pVfs->mxPathname+1;
5706 char *zFull = sqlite3MallocZero( nFull );
5707 void *zConverted = 0;
5708 if( zFull==0 ){
5709 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
5710 return 0;
5712 if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
5713 sqlite3_free(zFull);
5714 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
5715 return 0;
5717 zConverted = winConvertFromUtf8Filename(zFull);
5718 sqlite3_free(zFull);
5719 #else
5720 void *zConverted = winConvertFromUtf8Filename(zFilename);
5721 UNUSED_PARAMETER(pVfs);
5722 #endif
5723 if( zConverted==0 ){
5724 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
5725 return 0;
5727 if( osIsNT() ){
5728 #if SQLITE_OS_WINRT
5729 h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
5730 #else
5731 h = osLoadLibraryW((LPCWSTR)zConverted);
5732 #endif
5734 #ifdef SQLITE_WIN32_HAS_ANSI
5735 else{
5736 h = osLoadLibraryA((char*)zConverted);
5738 #endif
5739 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
5740 sqlite3_free(zConverted);
5741 return (void*)h;
5743 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
5744 UNUSED_PARAMETER(pVfs);
5745 winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
5747 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
5748 FARPROC proc;
5749 UNUSED_PARAMETER(pVfs);
5750 proc = osGetProcAddressA((HANDLE)pH, zSym);
5751 OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
5752 (void*)pH, zSym, (void*)proc));
5753 return (void(*)(void))proc;
5755 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
5756 UNUSED_PARAMETER(pVfs);
5757 osFreeLibrary((HANDLE)pHandle);
5758 OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
5760 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5761 #define winDlOpen 0
5762 #define winDlError 0
5763 #define winDlSym 0
5764 #define winDlClose 0
5765 #endif
5767 /* State information for the randomness gatherer. */
5768 typedef struct EntropyGatherer EntropyGatherer;
5769 struct EntropyGatherer {
5770 unsigned char *a; /* Gather entropy into this buffer */
5771 int na; /* Size of a[] in bytes */
5772 int i; /* XOR next input into a[i] */
5773 int nXor; /* Number of XOR operations done */
5776 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
5777 /* Mix sz bytes of entropy into p. */
5778 static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
5779 int j, k;
5780 for(j=0, k=p->i; j<sz; j++){
5781 p->a[k++] ^= x[j];
5782 if( k>=p->na ) k = 0;
5784 p->i = k;
5785 p->nXor += sz;
5787 #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
5790 ** Write up to nBuf bytes of randomness into zBuf.
5792 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
5793 #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
5794 UNUSED_PARAMETER(pVfs);
5795 memset(zBuf, 0, nBuf);
5796 return nBuf;
5797 #else
5798 EntropyGatherer e;
5799 UNUSED_PARAMETER(pVfs);
5800 memset(zBuf, 0, nBuf);
5801 e.a = (unsigned char*)zBuf;
5802 e.na = nBuf;
5803 e.nXor = 0;
5804 e.i = 0;
5806 SYSTEMTIME x;
5807 osGetSystemTime(&x);
5808 xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
5811 DWORD pid = osGetCurrentProcessId();
5812 xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
5814 #if SQLITE_OS_WINRT
5816 ULONGLONG cnt = osGetTickCount64();
5817 xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
5819 #else
5821 DWORD cnt = osGetTickCount();
5822 xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
5824 #endif /* SQLITE_OS_WINRT */
5826 LARGE_INTEGER i;
5827 osQueryPerformanceCounter(&i);
5828 xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
5830 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
5832 UUID id;
5833 memset(&id, 0, sizeof(UUID));
5834 osUuidCreate(&id);
5835 xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
5836 memset(&id, 0, sizeof(UUID));
5837 osUuidCreateSequential(&id);
5838 xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
5840 #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
5841 return e.nXor>nBuf ? nBuf : e.nXor;
5842 #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
5847 ** Sleep for a little while. Return the amount of time slept.
5849 static int winSleep(sqlite3_vfs *pVfs, int microsec){
5850 sqlite3_win32_sleep((microsec+999)/1000);
5851 UNUSED_PARAMETER(pVfs);
5852 return ((microsec+999)/1000)*1000;
5856 ** The following variable, if set to a non-zero value, is interpreted as
5857 ** the number of seconds since 1970 and is used to set the result of
5858 ** sqlite3OsCurrentTime() during testing.
5860 #ifdef SQLITE_TEST
5861 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
5862 #endif
5865 ** Find the current time (in Universal Coordinated Time). Write into *piNow
5866 ** the current time and date as a Julian Day number times 86_400_000. In
5867 ** other words, write into *piNow the number of milliseconds since the Julian
5868 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5869 ** proleptic Gregorian calendar.
5871 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5872 ** cannot be found.
5874 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
5875 /* FILETIME structure is a 64-bit value representing the number of
5876 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
5878 FILETIME ft;
5879 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
5880 #ifdef SQLITE_TEST
5881 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5882 #endif
5883 /* 2^32 - to avoid use of LL and warnings in gcc */
5884 static const sqlite3_int64 max32BitValue =
5885 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
5886 (sqlite3_int64)294967296;
5888 #if SQLITE_OS_WINCE
5889 SYSTEMTIME time;
5890 osGetSystemTime(&time);
5891 /* if SystemTimeToFileTime() fails, it returns zero. */
5892 if (!osSystemTimeToFileTime(&time,&ft)){
5893 return SQLITE_ERROR;
5895 #else
5896 osGetSystemTimeAsFileTime( &ft );
5897 #endif
5899 *piNow = winFiletimeEpoch +
5900 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
5901 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
5903 #ifdef SQLITE_TEST
5904 if( sqlite3_current_time ){
5905 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5907 #endif
5908 UNUSED_PARAMETER(pVfs);
5909 return SQLITE_OK;
5913 ** Find the current time (in Universal Coordinated Time). Write the
5914 ** current time and date as a Julian Day number into *prNow and
5915 ** return 0. Return 1 if the time and date cannot be found.
5917 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
5918 int rc;
5919 sqlite3_int64 i;
5920 rc = winCurrentTimeInt64(pVfs, &i);
5921 if( !rc ){
5922 *prNow = i/86400000.0;
5924 return rc;
5928 ** The idea is that this function works like a combination of
5929 ** GetLastError() and FormatMessage() on Windows (or errno and
5930 ** strerror_r() on Unix). After an error is returned by an OS
5931 ** function, SQLite calls this function with zBuf pointing to
5932 ** a buffer of nBuf bytes. The OS layer should populate the
5933 ** buffer with a nul-terminated UTF-8 encoded error message
5934 ** describing the last IO error to have occurred within the calling
5935 ** thread.
5937 ** If the error message is too large for the supplied buffer,
5938 ** it should be truncated. The return value of xGetLastError
5939 ** is zero if the error message fits in the buffer, or non-zero
5940 ** otherwise (if the message was truncated). If non-zero is returned,
5941 ** then it is not necessary to include the nul-terminator character
5942 ** in the output buffer.
5944 ** Not supplying an error message will have no adverse effect
5945 ** on SQLite. It is fine to have an implementation that never
5946 ** returns an error message:
5948 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
5949 ** assert(zBuf[0]=='\0');
5950 ** return 0;
5951 ** }
5953 ** However if an error message is supplied, it will be incorporated
5954 ** by sqlite into the error message available to the user using
5955 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
5957 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
5958 DWORD e = osGetLastError();
5959 UNUSED_PARAMETER(pVfs);
5960 if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
5961 return e;
5965 ** Initialize and deinitialize the operating system interface.
5967 int sqlite3_os_init(void){
5968 static sqlite3_vfs winVfs = {
5969 3, /* iVersion */
5970 sizeof(winFile), /* szOsFile */
5971 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
5972 0, /* pNext */
5973 "win32", /* zName */
5974 &winAppData, /* pAppData */
5975 winOpen, /* xOpen */
5976 winDelete, /* xDelete */
5977 winAccess, /* xAccess */
5978 winFullPathname, /* xFullPathname */
5979 winDlOpen, /* xDlOpen */
5980 winDlError, /* xDlError */
5981 winDlSym, /* xDlSym */
5982 winDlClose, /* xDlClose */
5983 winRandomness, /* xRandomness */
5984 winSleep, /* xSleep */
5985 winCurrentTime, /* xCurrentTime */
5986 winGetLastError, /* xGetLastError */
5987 winCurrentTimeInt64, /* xCurrentTimeInt64 */
5988 winSetSystemCall, /* xSetSystemCall */
5989 winGetSystemCall, /* xGetSystemCall */
5990 winNextSystemCall, /* xNextSystemCall */
5992 #if defined(SQLITE_WIN32_HAS_WIDE)
5993 static sqlite3_vfs winLongPathVfs = {
5994 3, /* iVersion */
5995 sizeof(winFile), /* szOsFile */
5996 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
5997 0, /* pNext */
5998 "win32-longpath", /* zName */
5999 &winAppData, /* pAppData */
6000 winOpen, /* xOpen */
6001 winDelete, /* xDelete */
6002 winAccess, /* xAccess */
6003 winFullPathname, /* xFullPathname */
6004 winDlOpen, /* xDlOpen */
6005 winDlError, /* xDlError */
6006 winDlSym, /* xDlSym */
6007 winDlClose, /* xDlClose */
6008 winRandomness, /* xRandomness */
6009 winSleep, /* xSleep */
6010 winCurrentTime, /* xCurrentTime */
6011 winGetLastError, /* xGetLastError */
6012 winCurrentTimeInt64, /* xCurrentTimeInt64 */
6013 winSetSystemCall, /* xSetSystemCall */
6014 winGetSystemCall, /* xGetSystemCall */
6015 winNextSystemCall, /* xNextSystemCall */
6017 #endif
6018 static sqlite3_vfs winNolockVfs = {
6019 3, /* iVersion */
6020 sizeof(winFile), /* szOsFile */
6021 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
6022 0, /* pNext */
6023 "win32-none", /* zName */
6024 &winNolockAppData, /* pAppData */
6025 winOpen, /* xOpen */
6026 winDelete, /* xDelete */
6027 winAccess, /* xAccess */
6028 winFullPathname, /* xFullPathname */
6029 winDlOpen, /* xDlOpen */
6030 winDlError, /* xDlError */
6031 winDlSym, /* xDlSym */
6032 winDlClose, /* xDlClose */
6033 winRandomness, /* xRandomness */
6034 winSleep, /* xSleep */
6035 winCurrentTime, /* xCurrentTime */
6036 winGetLastError, /* xGetLastError */
6037 winCurrentTimeInt64, /* xCurrentTimeInt64 */
6038 winSetSystemCall, /* xSetSystemCall */
6039 winGetSystemCall, /* xGetSystemCall */
6040 winNextSystemCall, /* xNextSystemCall */
6042 #if defined(SQLITE_WIN32_HAS_WIDE)
6043 static sqlite3_vfs winLongPathNolockVfs = {
6044 3, /* iVersion */
6045 sizeof(winFile), /* szOsFile */
6046 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
6047 0, /* pNext */
6048 "win32-longpath-none", /* zName */
6049 &winNolockAppData, /* pAppData */
6050 winOpen, /* xOpen */
6051 winDelete, /* xDelete */
6052 winAccess, /* xAccess */
6053 winFullPathname, /* xFullPathname */
6054 winDlOpen, /* xDlOpen */
6055 winDlError, /* xDlError */
6056 winDlSym, /* xDlSym */
6057 winDlClose, /* xDlClose */
6058 winRandomness, /* xRandomness */
6059 winSleep, /* xSleep */
6060 winCurrentTime, /* xCurrentTime */
6061 winGetLastError, /* xGetLastError */
6062 winCurrentTimeInt64, /* xCurrentTimeInt64 */
6063 winSetSystemCall, /* xSetSystemCall */
6064 winGetSystemCall, /* xGetSystemCall */
6065 winNextSystemCall, /* xNextSystemCall */
6067 #endif
6069 /* Double-check that the aSyscall[] array has been constructed
6070 ** correctly. See ticket [bb3a86e890c8e96ab] */
6071 assert( ArraySize(aSyscall)==80 );
6073 /* get memory map allocation granularity */
6074 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
6075 #if SQLITE_OS_WINRT
6076 osGetNativeSystemInfo(&winSysInfo);
6077 #else
6078 osGetSystemInfo(&winSysInfo);
6079 #endif
6080 assert( winSysInfo.dwAllocationGranularity>0 );
6081 assert( winSysInfo.dwPageSize>0 );
6083 sqlite3_vfs_register(&winVfs, 1);
6085 #if defined(SQLITE_WIN32_HAS_WIDE)
6086 sqlite3_vfs_register(&winLongPathVfs, 0);
6087 #endif
6089 sqlite3_vfs_register(&winNolockVfs, 0);
6091 #if defined(SQLITE_WIN32_HAS_WIDE)
6092 sqlite3_vfs_register(&winLongPathNolockVfs, 0);
6093 #endif
6095 #ifndef SQLITE_OMIT_WAL
6096 winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
6097 #endif
6099 return SQLITE_OK;
6102 int sqlite3_os_end(void){
6103 #if SQLITE_OS_WINRT
6104 if( sleepObj!=NULL ){
6105 osCloseHandle(sleepObj);
6106 sleepObj = NULL;
6108 #endif
6110 #ifndef SQLITE_OMIT_WAL
6111 winBigLock = 0;
6112 #endif
6114 return SQLITE_OK;
6117 #endif /* SQLITE_OS_WIN */