Further corrections to read-only SHM file handling on Win32.
[sqlite.git] / src / os_win.c
blob6b0bb3dbd0dbbb3c50df166a2684aa2bade59e57
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 * The value used with sqlite3_win32_set_directory() to specify that
320 * the data directory should be changed.
322 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
323 # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
324 #endif
327 * The value used with sqlite3_win32_set_directory() to specify that
328 * the temporary directory should be changed.
330 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
331 # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
332 #endif
335 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
336 * various Win32 API heap functions instead of our own.
338 #ifdef SQLITE_WIN32_MALLOC
341 * If this is non-zero, an isolated heap will be created by the native Win32
342 * allocator subsystem; otherwise, the default process heap will be used. This
343 * setting has no effect when compiling for WinRT. By default, this is enabled
344 * and an isolated heap will be created to store all allocated data.
346 ******************************************************************************
347 * WARNING: It is important to note that when this setting is non-zero and the
348 * winMemShutdown function is called (e.g. by the sqlite3_shutdown
349 * function), all data that was allocated using the isolated heap will
350 * be freed immediately and any attempt to access any of that freed
351 * data will almost certainly result in an immediate access violation.
352 ******************************************************************************
354 #ifndef SQLITE_WIN32_HEAP_CREATE
355 # define SQLITE_WIN32_HEAP_CREATE (TRUE)
356 #endif
359 * This is the maximum possible initial size of the Win32-specific heap, in
360 * bytes.
362 #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
363 # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
364 #endif
367 * This is the extra space for the initial size of the Win32-specific heap,
368 * in bytes. This value may be zero.
370 #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
371 # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
372 #endif
375 * Calculate the maximum legal cache size, in pages, based on the maximum
376 * possible initial heap size and the default page size, setting aside the
377 * needed extra space.
379 #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
380 # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
381 (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
382 (SQLITE_DEFAULT_PAGE_SIZE))
383 #endif
386 * This is cache size used in the calculation of the initial size of the
387 * Win32-specific heap. It cannot be negative.
389 #ifndef SQLITE_WIN32_CACHE_SIZE
390 # if SQLITE_DEFAULT_CACHE_SIZE>=0
391 # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
392 # else
393 # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
394 # endif
395 #endif
398 * Make sure that the calculated cache size, in pages, cannot cause the
399 * initial size of the Win32-specific heap to exceed the maximum amount
400 * of memory that can be specified in the call to HeapCreate.
402 #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
403 # undef SQLITE_WIN32_CACHE_SIZE
404 # define SQLITE_WIN32_CACHE_SIZE (2000)
405 #endif
408 * The initial size of the Win32-specific heap. This value may be zero.
410 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
411 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
412 (SQLITE_DEFAULT_PAGE_SIZE) + \
413 (SQLITE_WIN32_HEAP_INIT_EXTRA))
414 #endif
417 * The maximum size of the Win32-specific heap. This value may be zero.
419 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
420 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
421 #endif
424 * The extra flags to use in calls to the Win32 heap APIs. This value may be
425 * zero for the default behavior.
427 #ifndef SQLITE_WIN32_HEAP_FLAGS
428 # define SQLITE_WIN32_HEAP_FLAGS (0)
429 #endif
433 ** The winMemData structure stores information required by the Win32-specific
434 ** sqlite3_mem_methods implementation.
436 typedef struct winMemData winMemData;
437 struct winMemData {
438 #ifndef NDEBUG
439 u32 magic1; /* Magic number to detect structure corruption. */
440 #endif
441 HANDLE hHeap; /* The handle to our heap. */
442 BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
443 #ifndef NDEBUG
444 u32 magic2; /* Magic number to detect structure corruption. */
445 #endif
448 #ifndef NDEBUG
449 #define WINMEM_MAGIC1 0x42b2830b
450 #define WINMEM_MAGIC2 0xbd4d7cf4
451 #endif
453 static struct winMemData win_mem_data = {
454 #ifndef NDEBUG
455 WINMEM_MAGIC1,
456 #endif
457 NULL, FALSE
458 #ifndef NDEBUG
459 ,WINMEM_MAGIC2
460 #endif
463 #ifndef NDEBUG
464 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
465 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
466 #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
467 #else
468 #define winMemAssertMagic()
469 #endif
471 #define winMemGetDataPtr() &win_mem_data
472 #define winMemGetHeap() win_mem_data.hHeap
473 #define winMemGetOwned() win_mem_data.bOwned
475 static void *winMemMalloc(int nBytes);
476 static void winMemFree(void *pPrior);
477 static void *winMemRealloc(void *pPrior, int nBytes);
478 static int winMemSize(void *p);
479 static int winMemRoundup(int n);
480 static int winMemInit(void *pAppData);
481 static void winMemShutdown(void *pAppData);
483 const sqlite3_mem_methods *sqlite3MemGetWin32(void);
484 #endif /* SQLITE_WIN32_MALLOC */
487 ** The following variable is (normally) set once and never changes
488 ** thereafter. It records whether the operating system is Win9x
489 ** or WinNT.
491 ** 0: Operating system unknown.
492 ** 1: Operating system is Win9x.
493 ** 2: Operating system is WinNT.
495 ** In order to facilitate testing on a WinNT system, the test fixture
496 ** can manually set this value to 1 to emulate Win98 behavior.
498 #ifdef SQLITE_TEST
499 LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
500 #else
501 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
502 #endif
504 #ifndef SYSCALL
505 # define SYSCALL sqlite3_syscall_ptr
506 #endif
509 ** This function is not available on Windows CE or WinRT.
512 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
513 # define osAreFileApisANSI() 1
514 #endif
517 ** Many system calls are accessed through pointer-to-functions so that
518 ** they may be overridden at runtime to facilitate fault injection during
519 ** testing and sandboxing. The following array holds the names and pointers
520 ** to all overrideable system calls.
522 static struct win_syscall {
523 const char *zName; /* Name of the system call */
524 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
525 sqlite3_syscall_ptr pDefault; /* Default value */
526 } aSyscall[] = {
527 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
528 { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
529 #else
530 { "AreFileApisANSI", (SYSCALL)0, 0 },
531 #endif
533 #ifndef osAreFileApisANSI
534 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
535 #endif
537 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
538 { "CharLowerW", (SYSCALL)CharLowerW, 0 },
539 #else
540 { "CharLowerW", (SYSCALL)0, 0 },
541 #endif
543 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
545 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
546 { "CharUpperW", (SYSCALL)CharUpperW, 0 },
547 #else
548 { "CharUpperW", (SYSCALL)0, 0 },
549 #endif
551 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
553 { "CloseHandle", (SYSCALL)CloseHandle, 0 },
555 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
557 #if defined(SQLITE_WIN32_HAS_ANSI)
558 { "CreateFileA", (SYSCALL)CreateFileA, 0 },
559 #else
560 { "CreateFileA", (SYSCALL)0, 0 },
561 #endif
563 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
564 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
566 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
567 { "CreateFileW", (SYSCALL)CreateFileW, 0 },
568 #else
569 { "CreateFileW", (SYSCALL)0, 0 },
570 #endif
572 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
573 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
575 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
576 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
577 SQLITE_WIN32_CREATEFILEMAPPINGA
578 { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
579 #else
580 { "CreateFileMappingA", (SYSCALL)0, 0 },
581 #endif
583 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
584 DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
586 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
587 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
588 { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
589 #else
590 { "CreateFileMappingW", (SYSCALL)0, 0 },
591 #endif
593 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
594 DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
596 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
597 { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
598 #else
599 { "CreateMutexW", (SYSCALL)0, 0 },
600 #endif
602 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
603 LPCWSTR))aSyscall[8].pCurrent)
605 #if defined(SQLITE_WIN32_HAS_ANSI)
606 { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
607 #else
608 { "DeleteFileA", (SYSCALL)0, 0 },
609 #endif
611 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
613 #if defined(SQLITE_WIN32_HAS_WIDE)
614 { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
615 #else
616 { "DeleteFileW", (SYSCALL)0, 0 },
617 #endif
619 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
621 #if SQLITE_OS_WINCE
622 { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
623 #else
624 { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
625 #endif
627 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
628 LPFILETIME))aSyscall[11].pCurrent)
630 #if SQLITE_OS_WINCE
631 { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
632 #else
633 { "FileTimeToSystemTime", (SYSCALL)0, 0 },
634 #endif
636 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
637 LPSYSTEMTIME))aSyscall[12].pCurrent)
639 { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
641 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
643 #if defined(SQLITE_WIN32_HAS_ANSI)
644 { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
645 #else
646 { "FormatMessageA", (SYSCALL)0, 0 },
647 #endif
649 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
650 DWORD,va_list*))aSyscall[14].pCurrent)
652 #if defined(SQLITE_WIN32_HAS_WIDE)
653 { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
654 #else
655 { "FormatMessageW", (SYSCALL)0, 0 },
656 #endif
658 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
659 DWORD,va_list*))aSyscall[15].pCurrent)
661 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
662 { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
663 #else
664 { "FreeLibrary", (SYSCALL)0, 0 },
665 #endif
667 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
669 { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
671 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
673 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
674 { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
675 #else
676 { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
677 #endif
679 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
680 LPDWORD))aSyscall[18].pCurrent)
682 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
683 { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
684 #else
685 { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
686 #endif
688 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
689 LPDWORD))aSyscall[19].pCurrent)
691 #if defined(SQLITE_WIN32_HAS_ANSI)
692 { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
693 #else
694 { "GetFileAttributesA", (SYSCALL)0, 0 },
695 #endif
697 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
699 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
700 { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
701 #else
702 { "GetFileAttributesW", (SYSCALL)0, 0 },
703 #endif
705 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
707 #if defined(SQLITE_WIN32_HAS_WIDE)
708 { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
709 #else
710 { "GetFileAttributesExW", (SYSCALL)0, 0 },
711 #endif
713 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
714 LPVOID))aSyscall[22].pCurrent)
716 #if !SQLITE_OS_WINRT
717 { "GetFileSize", (SYSCALL)GetFileSize, 0 },
718 #else
719 { "GetFileSize", (SYSCALL)0, 0 },
720 #endif
722 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
724 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
725 { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
726 #else
727 { "GetFullPathNameA", (SYSCALL)0, 0 },
728 #endif
730 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
731 LPSTR*))aSyscall[24].pCurrent)
733 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
734 { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
735 #else
736 { "GetFullPathNameW", (SYSCALL)0, 0 },
737 #endif
739 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
740 LPWSTR*))aSyscall[25].pCurrent)
742 { "GetLastError", (SYSCALL)GetLastError, 0 },
744 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
746 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
747 #if SQLITE_OS_WINCE
748 /* The GetProcAddressA() routine is only available on Windows CE. */
749 { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
750 #else
751 /* All other Windows platforms expect GetProcAddress() to take
752 ** an ANSI string regardless of the _UNICODE setting */
753 { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
754 #endif
755 #else
756 { "GetProcAddressA", (SYSCALL)0, 0 },
757 #endif
759 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
760 LPCSTR))aSyscall[27].pCurrent)
762 #if !SQLITE_OS_WINRT
763 { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
764 #else
765 { "GetSystemInfo", (SYSCALL)0, 0 },
766 #endif
768 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
770 { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
772 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
774 #if !SQLITE_OS_WINCE
775 { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
776 #else
777 { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
778 #endif
780 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
781 LPFILETIME))aSyscall[30].pCurrent)
783 #if defined(SQLITE_WIN32_HAS_ANSI)
784 { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
785 #else
786 { "GetTempPathA", (SYSCALL)0, 0 },
787 #endif
789 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
791 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
792 { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
793 #else
794 { "GetTempPathW", (SYSCALL)0, 0 },
795 #endif
797 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
799 #if !SQLITE_OS_WINRT
800 { "GetTickCount", (SYSCALL)GetTickCount, 0 },
801 #else
802 { "GetTickCount", (SYSCALL)0, 0 },
803 #endif
805 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
807 #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
808 { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
809 #else
810 { "GetVersionExA", (SYSCALL)0, 0 },
811 #endif
813 #define osGetVersionExA ((BOOL(WINAPI*)( \
814 LPOSVERSIONINFOA))aSyscall[34].pCurrent)
816 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
817 SQLITE_WIN32_GETVERSIONEX
818 { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
819 #else
820 { "GetVersionExW", (SYSCALL)0, 0 },
821 #endif
823 #define osGetVersionExW ((BOOL(WINAPI*)( \
824 LPOSVERSIONINFOW))aSyscall[35].pCurrent)
826 { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
828 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
829 SIZE_T))aSyscall[36].pCurrent)
831 #if !SQLITE_OS_WINRT
832 { "HeapCreate", (SYSCALL)HeapCreate, 0 },
833 #else
834 { "HeapCreate", (SYSCALL)0, 0 },
835 #endif
837 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
838 SIZE_T))aSyscall[37].pCurrent)
840 #if !SQLITE_OS_WINRT
841 { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
842 #else
843 { "HeapDestroy", (SYSCALL)0, 0 },
844 #endif
846 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
848 { "HeapFree", (SYSCALL)HeapFree, 0 },
850 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
852 { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
854 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
855 SIZE_T))aSyscall[40].pCurrent)
857 { "HeapSize", (SYSCALL)HeapSize, 0 },
859 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
860 LPCVOID))aSyscall[41].pCurrent)
862 #if !SQLITE_OS_WINRT
863 { "HeapValidate", (SYSCALL)HeapValidate, 0 },
864 #else
865 { "HeapValidate", (SYSCALL)0, 0 },
866 #endif
868 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
869 LPCVOID))aSyscall[42].pCurrent)
871 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
872 { "HeapCompact", (SYSCALL)HeapCompact, 0 },
873 #else
874 { "HeapCompact", (SYSCALL)0, 0 },
875 #endif
877 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
879 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
880 { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
881 #else
882 { "LoadLibraryA", (SYSCALL)0, 0 },
883 #endif
885 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
887 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
888 !defined(SQLITE_OMIT_LOAD_EXTENSION)
889 { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
890 #else
891 { "LoadLibraryW", (SYSCALL)0, 0 },
892 #endif
894 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
896 #if !SQLITE_OS_WINRT
897 { "LocalFree", (SYSCALL)LocalFree, 0 },
898 #else
899 { "LocalFree", (SYSCALL)0, 0 },
900 #endif
902 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
904 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
905 { "LockFile", (SYSCALL)LockFile, 0 },
906 #else
907 { "LockFile", (SYSCALL)0, 0 },
908 #endif
910 #ifndef osLockFile
911 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
912 DWORD))aSyscall[47].pCurrent)
913 #endif
915 #if !SQLITE_OS_WINCE
916 { "LockFileEx", (SYSCALL)LockFileEx, 0 },
917 #else
918 { "LockFileEx", (SYSCALL)0, 0 },
919 #endif
921 #ifndef osLockFileEx
922 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
923 LPOVERLAPPED))aSyscall[48].pCurrent)
924 #endif
926 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
927 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
928 { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
929 #else
930 { "MapViewOfFile", (SYSCALL)0, 0 },
931 #endif
933 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
934 SIZE_T))aSyscall[49].pCurrent)
936 { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
938 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
939 int))aSyscall[50].pCurrent)
941 { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
943 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
944 LARGE_INTEGER*))aSyscall[51].pCurrent)
946 { "ReadFile", (SYSCALL)ReadFile, 0 },
948 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
949 LPOVERLAPPED))aSyscall[52].pCurrent)
951 { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
953 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
955 #if !SQLITE_OS_WINRT
956 { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
957 #else
958 { "SetFilePointer", (SYSCALL)0, 0 },
959 #endif
961 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
962 DWORD))aSyscall[54].pCurrent)
964 #if !SQLITE_OS_WINRT
965 { "Sleep", (SYSCALL)Sleep, 0 },
966 #else
967 { "Sleep", (SYSCALL)0, 0 },
968 #endif
970 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
972 { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
974 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
975 LPFILETIME))aSyscall[56].pCurrent)
977 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
978 { "UnlockFile", (SYSCALL)UnlockFile, 0 },
979 #else
980 { "UnlockFile", (SYSCALL)0, 0 },
981 #endif
983 #ifndef osUnlockFile
984 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
985 DWORD))aSyscall[57].pCurrent)
986 #endif
988 #if !SQLITE_OS_WINCE
989 { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
990 #else
991 { "UnlockFileEx", (SYSCALL)0, 0 },
992 #endif
994 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
995 LPOVERLAPPED))aSyscall[58].pCurrent)
997 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
998 { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
999 #else
1000 { "UnmapViewOfFile", (SYSCALL)0, 0 },
1001 #endif
1003 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
1005 { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
1007 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
1008 LPCSTR,LPBOOL))aSyscall[60].pCurrent)
1010 { "WriteFile", (SYSCALL)WriteFile, 0 },
1012 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
1013 LPOVERLAPPED))aSyscall[61].pCurrent)
1015 #if SQLITE_OS_WINRT
1016 { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
1017 #else
1018 { "CreateEventExW", (SYSCALL)0, 0 },
1019 #endif
1021 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
1022 DWORD,DWORD))aSyscall[62].pCurrent)
1024 #if !SQLITE_OS_WINRT
1025 { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
1026 #else
1027 { "WaitForSingleObject", (SYSCALL)0, 0 },
1028 #endif
1030 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
1031 DWORD))aSyscall[63].pCurrent)
1033 #if !SQLITE_OS_WINCE
1034 { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
1035 #else
1036 { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
1037 #endif
1039 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
1040 BOOL))aSyscall[64].pCurrent)
1042 #if SQLITE_OS_WINRT
1043 { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
1044 #else
1045 { "SetFilePointerEx", (SYSCALL)0, 0 },
1046 #endif
1048 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
1049 PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
1051 #if SQLITE_OS_WINRT
1052 { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
1053 #else
1054 { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
1055 #endif
1057 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
1058 FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
1060 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
1061 { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
1062 #else
1063 { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
1064 #endif
1066 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
1067 SIZE_T))aSyscall[67].pCurrent)
1069 #if SQLITE_OS_WINRT
1070 { "CreateFile2", (SYSCALL)CreateFile2, 0 },
1071 #else
1072 { "CreateFile2", (SYSCALL)0, 0 },
1073 #endif
1075 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
1076 LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
1078 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
1079 { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
1080 #else
1081 { "LoadPackagedLibrary", (SYSCALL)0, 0 },
1082 #endif
1084 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
1085 DWORD))aSyscall[69].pCurrent)
1087 #if SQLITE_OS_WINRT
1088 { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
1089 #else
1090 { "GetTickCount64", (SYSCALL)0, 0 },
1091 #endif
1093 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
1095 #if SQLITE_OS_WINRT
1096 { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
1097 #else
1098 { "GetNativeSystemInfo", (SYSCALL)0, 0 },
1099 #endif
1101 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
1102 LPSYSTEM_INFO))aSyscall[71].pCurrent)
1104 #if defined(SQLITE_WIN32_HAS_ANSI)
1105 { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
1106 #else
1107 { "OutputDebugStringA", (SYSCALL)0, 0 },
1108 #endif
1110 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
1112 #if defined(SQLITE_WIN32_HAS_WIDE)
1113 { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
1114 #else
1115 { "OutputDebugStringW", (SYSCALL)0, 0 },
1116 #endif
1118 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
1120 { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
1122 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
1124 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
1125 { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
1126 #else
1127 { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
1128 #endif
1130 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
1131 LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
1134 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
1135 ** is really just a macro that uses a compiler intrinsic (e.g. x64).
1136 ** So do not try to make this is into a redefinable interface.
1138 #if defined(InterlockedCompareExchange)
1139 { "InterlockedCompareExchange", (SYSCALL)0, 0 },
1141 #define osInterlockedCompareExchange InterlockedCompareExchange
1142 #else
1143 { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
1145 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
1146 SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
1147 #endif /* defined(InterlockedCompareExchange) */
1149 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
1150 { "UuidCreate", (SYSCALL)UuidCreate, 0 },
1151 #else
1152 { "UuidCreate", (SYSCALL)0, 0 },
1153 #endif
1155 #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
1157 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
1158 { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
1159 #else
1160 { "UuidCreateSequential", (SYSCALL)0, 0 },
1161 #endif
1163 #define osUuidCreateSequential \
1164 ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
1166 #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
1167 { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
1168 #else
1169 { "FlushViewOfFile", (SYSCALL)0, 0 },
1170 #endif
1172 #define osFlushViewOfFile \
1173 ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
1175 }; /* End of the overrideable system calls */
1178 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
1179 ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
1180 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
1181 ** system call named zName.
1183 static int winSetSystemCall(
1184 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
1185 const char *zName, /* Name of system call to override */
1186 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
1188 unsigned int i;
1189 int rc = SQLITE_NOTFOUND;
1191 UNUSED_PARAMETER(pNotUsed);
1192 if( zName==0 ){
1193 /* If no zName is given, restore all system calls to their default
1194 ** settings and return NULL
1196 rc = SQLITE_OK;
1197 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
1198 if( aSyscall[i].pDefault ){
1199 aSyscall[i].pCurrent = aSyscall[i].pDefault;
1202 }else{
1203 /* If zName is specified, operate on only the one system call
1204 ** specified.
1206 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
1207 if( strcmp(zName, aSyscall[i].zName)==0 ){
1208 if( aSyscall[i].pDefault==0 ){
1209 aSyscall[i].pDefault = aSyscall[i].pCurrent;
1211 rc = SQLITE_OK;
1212 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
1213 aSyscall[i].pCurrent = pNewFunc;
1214 break;
1218 return rc;
1222 ** Return the value of a system call. Return NULL if zName is not a
1223 ** recognized system call name. NULL is also returned if the system call
1224 ** is currently undefined.
1226 static sqlite3_syscall_ptr winGetSystemCall(
1227 sqlite3_vfs *pNotUsed,
1228 const char *zName
1230 unsigned int i;
1232 UNUSED_PARAMETER(pNotUsed);
1233 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
1234 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
1236 return 0;
1240 ** Return the name of the first system call after zName. If zName==NULL
1241 ** then return the name of the first system call. Return NULL if zName
1242 ** is the last system call or if zName is not the name of a valid
1243 ** system call.
1245 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
1246 int i = -1;
1248 UNUSED_PARAMETER(p);
1249 if( zName ){
1250 for(i=0; i<ArraySize(aSyscall)-1; i++){
1251 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
1254 for(i++; i<ArraySize(aSyscall); i++){
1255 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
1257 return 0;
1260 #ifdef SQLITE_WIN32_MALLOC
1262 ** If a Win32 native heap has been configured, this function will attempt to
1263 ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
1264 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
1265 ** "pnLargest" argument, if non-zero, will be used to return the size of the
1266 ** largest committed free block in the heap, in bytes.
1268 int sqlite3_win32_compact_heap(LPUINT pnLargest){
1269 int rc = SQLITE_OK;
1270 UINT nLargest = 0;
1271 HANDLE hHeap;
1273 winMemAssertMagic();
1274 hHeap = winMemGetHeap();
1275 assert( hHeap!=0 );
1276 assert( hHeap!=INVALID_HANDLE_VALUE );
1277 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1278 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1279 #endif
1280 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
1281 if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
1282 DWORD lastErrno = osGetLastError();
1283 if( lastErrno==NO_ERROR ){
1284 sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
1285 (void*)hHeap);
1286 rc = SQLITE_NOMEM_BKPT;
1287 }else{
1288 sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
1289 osGetLastError(), (void*)hHeap);
1290 rc = SQLITE_ERROR;
1293 #else
1294 sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
1295 (void*)hHeap);
1296 rc = SQLITE_NOTFOUND;
1297 #endif
1298 if( pnLargest ) *pnLargest = nLargest;
1299 return rc;
1303 ** If a Win32 native heap has been configured, this function will attempt to
1304 ** destroy and recreate it. If the Win32 native heap is not isolated and/or
1305 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
1306 ** be returned and no changes will be made to the Win32 native heap.
1308 int sqlite3_win32_reset_heap(){
1309 int rc;
1310 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
1311 MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
1312 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
1313 MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
1314 sqlite3_mutex_enter(pMaster);
1315 sqlite3_mutex_enter(pMem);
1316 winMemAssertMagic();
1317 if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
1319 ** At this point, there should be no outstanding memory allocations on
1320 ** the heap. Also, since both the master and memsys locks are currently
1321 ** being held by us, no other function (i.e. from another thread) should
1322 ** be able to even access the heap. Attempt to destroy and recreate our
1323 ** isolated Win32 native heap now.
1325 assert( winMemGetHeap()!=NULL );
1326 assert( winMemGetOwned() );
1327 assert( sqlite3_memory_used()==0 );
1328 winMemShutdown(winMemGetDataPtr());
1329 assert( winMemGetHeap()==NULL );
1330 assert( !winMemGetOwned() );
1331 assert( sqlite3_memory_used()==0 );
1332 rc = winMemInit(winMemGetDataPtr());
1333 assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
1334 assert( rc!=SQLITE_OK || winMemGetOwned() );
1335 assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
1336 }else{
1338 ** The Win32 native heap cannot be modified because it may be in use.
1340 rc = SQLITE_BUSY;
1342 sqlite3_mutex_leave(pMem);
1343 sqlite3_mutex_leave(pMaster);
1344 return rc;
1346 #endif /* SQLITE_WIN32_MALLOC */
1349 ** This function outputs the specified (ANSI) string to the Win32 debugger
1350 ** (if available).
1353 void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
1354 char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
1355 int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
1356 if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
1357 assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
1358 #ifdef SQLITE_ENABLE_API_ARMOR
1359 if( !zBuf ){
1360 (void)SQLITE_MISUSE_BKPT;
1361 return;
1363 #endif
1364 #if defined(SQLITE_WIN32_HAS_ANSI)
1365 if( nMin>0 ){
1366 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
1367 memcpy(zDbgBuf, zBuf, nMin);
1368 osOutputDebugStringA(zDbgBuf);
1369 }else{
1370 osOutputDebugStringA(zBuf);
1372 #elif defined(SQLITE_WIN32_HAS_WIDE)
1373 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
1374 if ( osMultiByteToWideChar(
1375 osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
1376 nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
1377 return;
1379 osOutputDebugStringW((LPCWSTR)zDbgBuf);
1380 #else
1381 if( nMin>0 ){
1382 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
1383 memcpy(zDbgBuf, zBuf, nMin);
1384 fprintf(stderr, "%s", zDbgBuf);
1385 }else{
1386 fprintf(stderr, "%s", zBuf);
1388 #endif
1392 ** The following routine suspends the current thread for at least ms
1393 ** milliseconds. This is equivalent to the Win32 Sleep() interface.
1395 #if SQLITE_OS_WINRT
1396 static HANDLE sleepObj = NULL;
1397 #endif
1399 void sqlite3_win32_sleep(DWORD milliseconds){
1400 #if SQLITE_OS_WINRT
1401 if ( sleepObj==NULL ){
1402 sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
1403 SYNCHRONIZE);
1405 assert( sleepObj!=NULL );
1406 osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
1407 #else
1408 osSleep(milliseconds);
1409 #endif
1412 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
1413 SQLITE_THREADSAFE>0
1414 DWORD sqlite3Win32Wait(HANDLE hObject){
1415 DWORD rc;
1416 while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
1417 TRUE))==WAIT_IO_COMPLETION ){}
1418 return rc;
1420 #endif
1423 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
1424 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
1426 ** Here is an interesting observation: Win95, Win98, and WinME lack
1427 ** the LockFileEx() API. But we can still statically link against that
1428 ** API as long as we don't call it when running Win95/98/ME. A call to
1429 ** this routine is used to determine if the host is Win95/98/ME or
1430 ** WinNT/2K/XP so that we will know whether or not we can safely call
1431 ** the LockFileEx() API.
1434 #if !SQLITE_WIN32_GETVERSIONEX
1435 # define osIsNT() (1)
1436 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
1437 # define osIsNT() (1)
1438 #elif !defined(SQLITE_WIN32_HAS_WIDE)
1439 # define osIsNT() (0)
1440 #else
1441 # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
1442 #endif
1445 ** This function determines if the machine is running a version of Windows
1446 ** based on the NT kernel.
1448 int sqlite3_win32_is_nt(void){
1449 #if SQLITE_OS_WINRT
1451 ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
1452 ** kernel.
1454 return 1;
1455 #elif SQLITE_WIN32_GETVERSIONEX
1456 if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
1457 #if defined(SQLITE_WIN32_HAS_ANSI)
1458 OSVERSIONINFOA sInfo;
1459 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
1460 osGetVersionExA(&sInfo);
1461 osInterlockedCompareExchange(&sqlite3_os_type,
1462 (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
1463 #elif defined(SQLITE_WIN32_HAS_WIDE)
1464 OSVERSIONINFOW sInfo;
1465 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
1466 osGetVersionExW(&sInfo);
1467 osInterlockedCompareExchange(&sqlite3_os_type,
1468 (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
1469 #endif
1471 return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
1472 #elif SQLITE_TEST
1473 return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
1474 #else
1476 ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
1477 ** deprecated are always assumed to be based on the NT kernel.
1479 return 1;
1480 #endif
1483 #ifdef SQLITE_WIN32_MALLOC
1485 ** Allocate nBytes of memory.
1487 static void *winMemMalloc(int nBytes){
1488 HANDLE hHeap;
1489 void *p;
1491 winMemAssertMagic();
1492 hHeap = winMemGetHeap();
1493 assert( hHeap!=0 );
1494 assert( hHeap!=INVALID_HANDLE_VALUE );
1495 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1496 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1497 #endif
1498 assert( nBytes>=0 );
1499 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
1500 if( !p ){
1501 sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
1502 nBytes, osGetLastError(), (void*)hHeap);
1504 return p;
1508 ** Free memory.
1510 static void winMemFree(void *pPrior){
1511 HANDLE hHeap;
1513 winMemAssertMagic();
1514 hHeap = winMemGetHeap();
1515 assert( hHeap!=0 );
1516 assert( hHeap!=INVALID_HANDLE_VALUE );
1517 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1518 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
1519 #endif
1520 if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
1521 if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
1522 sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
1523 pPrior, osGetLastError(), (void*)hHeap);
1528 ** Change the size of an existing memory allocation
1530 static void *winMemRealloc(void *pPrior, int nBytes){
1531 HANDLE hHeap;
1532 void *p;
1534 winMemAssertMagic();
1535 hHeap = winMemGetHeap();
1536 assert( hHeap!=0 );
1537 assert( hHeap!=INVALID_HANDLE_VALUE );
1538 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1539 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
1540 #endif
1541 assert( nBytes>=0 );
1542 if( !pPrior ){
1543 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
1544 }else{
1545 p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
1547 if( !p ){
1548 sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
1549 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
1550 (void*)hHeap);
1552 return p;
1556 ** Return the size of an outstanding allocation, in bytes.
1558 static int winMemSize(void *p){
1559 HANDLE hHeap;
1560 SIZE_T n;
1562 winMemAssertMagic();
1563 hHeap = winMemGetHeap();
1564 assert( hHeap!=0 );
1565 assert( hHeap!=INVALID_HANDLE_VALUE );
1566 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1567 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
1568 #endif
1569 if( !p ) return 0;
1570 n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
1571 if( n==(SIZE_T)-1 ){
1572 sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
1573 p, osGetLastError(), (void*)hHeap);
1574 return 0;
1576 return (int)n;
1580 ** Round up a request size to the next valid allocation size.
1582 static int winMemRoundup(int n){
1583 return n;
1587 ** Initialize this module.
1589 static int winMemInit(void *pAppData){
1590 winMemData *pWinMemData = (winMemData *)pAppData;
1592 if( !pWinMemData ) return SQLITE_ERROR;
1593 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
1594 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
1596 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
1597 if( !pWinMemData->hHeap ){
1598 DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
1599 DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
1600 if( dwMaximumSize==0 ){
1601 dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
1602 }else if( dwInitialSize>dwMaximumSize ){
1603 dwInitialSize = dwMaximumSize;
1605 pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
1606 dwInitialSize, dwMaximumSize);
1607 if( !pWinMemData->hHeap ){
1608 sqlite3_log(SQLITE_NOMEM,
1609 "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
1610 osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
1611 dwMaximumSize);
1612 return SQLITE_NOMEM_BKPT;
1614 pWinMemData->bOwned = TRUE;
1615 assert( pWinMemData->bOwned );
1617 #else
1618 pWinMemData->hHeap = osGetProcessHeap();
1619 if( !pWinMemData->hHeap ){
1620 sqlite3_log(SQLITE_NOMEM,
1621 "failed to GetProcessHeap (%lu)", osGetLastError());
1622 return SQLITE_NOMEM_BKPT;
1624 pWinMemData->bOwned = FALSE;
1625 assert( !pWinMemData->bOwned );
1626 #endif
1627 assert( pWinMemData->hHeap!=0 );
1628 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
1629 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1630 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1631 #endif
1632 return SQLITE_OK;
1636 ** Deinitialize this module.
1638 static void winMemShutdown(void *pAppData){
1639 winMemData *pWinMemData = (winMemData *)pAppData;
1641 if( !pWinMemData ) return;
1642 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
1643 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
1645 if( pWinMemData->hHeap ){
1646 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
1647 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1648 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1649 #endif
1650 if( pWinMemData->bOwned ){
1651 if( !osHeapDestroy(pWinMemData->hHeap) ){
1652 sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
1653 osGetLastError(), (void*)pWinMemData->hHeap);
1655 pWinMemData->bOwned = FALSE;
1657 pWinMemData->hHeap = NULL;
1662 ** Populate the low-level memory allocation function pointers in
1663 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
1664 ** arguments specify the block of memory to manage.
1666 ** This routine is only called by sqlite3_config(), and therefore
1667 ** is not required to be threadsafe (it is not).
1669 const sqlite3_mem_methods *sqlite3MemGetWin32(void){
1670 static const sqlite3_mem_methods winMemMethods = {
1671 winMemMalloc,
1672 winMemFree,
1673 winMemRealloc,
1674 winMemSize,
1675 winMemRoundup,
1676 winMemInit,
1677 winMemShutdown,
1678 &win_mem_data
1680 return &winMemMethods;
1683 void sqlite3MemSetDefault(void){
1684 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
1686 #endif /* SQLITE_WIN32_MALLOC */
1689 ** Convert a UTF-8 string to Microsoft Unicode.
1691 ** Space to hold the returned string is obtained from sqlite3_malloc().
1693 static LPWSTR winUtf8ToUnicode(const char *zText){
1694 int nChar;
1695 LPWSTR zWideText;
1697 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
1698 if( nChar==0 ){
1699 return 0;
1701 zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
1702 if( zWideText==0 ){
1703 return 0;
1705 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
1706 nChar);
1707 if( nChar==0 ){
1708 sqlite3_free(zWideText);
1709 zWideText = 0;
1711 return zWideText;
1715 ** Convert a Microsoft Unicode string to UTF-8.
1717 ** Space to hold the returned string is obtained from sqlite3_malloc().
1719 static char *winUnicodeToUtf8(LPCWSTR zWideText){
1720 int nByte;
1721 char *zText;
1723 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
1724 if( nByte == 0 ){
1725 return 0;
1727 zText = sqlite3MallocZero( nByte );
1728 if( zText==0 ){
1729 return 0;
1731 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
1732 0, 0);
1733 if( nByte == 0 ){
1734 sqlite3_free(zText);
1735 zText = 0;
1737 return zText;
1741 ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
1742 ** code page.
1744 ** Space to hold the returned string is obtained from sqlite3_malloc().
1746 static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
1747 int nByte;
1748 LPWSTR zMbcsText;
1749 int codepage = useAnsi ? CP_ACP : CP_OEMCP;
1751 nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
1752 0)*sizeof(WCHAR);
1753 if( nByte==0 ){
1754 return 0;
1756 zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
1757 if( zMbcsText==0 ){
1758 return 0;
1760 nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
1761 nByte);
1762 if( nByte==0 ){
1763 sqlite3_free(zMbcsText);
1764 zMbcsText = 0;
1766 return zMbcsText;
1770 ** Convert a Microsoft Unicode string to a multi-byte character string,
1771 ** using the ANSI or OEM code page.
1773 ** Space to hold the returned string is obtained from sqlite3_malloc().
1775 static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
1776 int nByte;
1777 char *zText;
1778 int codepage = useAnsi ? CP_ACP : CP_OEMCP;
1780 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
1781 if( nByte == 0 ){
1782 return 0;
1784 zText = sqlite3MallocZero( nByte );
1785 if( zText==0 ){
1786 return 0;
1788 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
1789 nByte, 0, 0);
1790 if( nByte == 0 ){
1791 sqlite3_free(zText);
1792 zText = 0;
1794 return zText;
1798 ** Convert a multi-byte character string to UTF-8.
1800 ** Space to hold the returned string is obtained from sqlite3_malloc().
1802 static char *winMbcsToUtf8(const char *zText, int useAnsi){
1803 char *zTextUtf8;
1804 LPWSTR zTmpWide;
1806 zTmpWide = winMbcsToUnicode(zText, useAnsi);
1807 if( zTmpWide==0 ){
1808 return 0;
1810 zTextUtf8 = winUnicodeToUtf8(zTmpWide);
1811 sqlite3_free(zTmpWide);
1812 return zTextUtf8;
1816 ** Convert a UTF-8 string to a multi-byte character string.
1818 ** Space to hold the returned string is obtained from sqlite3_malloc().
1820 static char *winUtf8ToMbcs(const char *zText, int useAnsi){
1821 char *zTextMbcs;
1822 LPWSTR zTmpWide;
1824 zTmpWide = winUtf8ToUnicode(zText);
1825 if( zTmpWide==0 ){
1826 return 0;
1828 zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
1829 sqlite3_free(zTmpWide);
1830 return zTextMbcs;
1834 ** This is a public wrapper for the winUtf8ToUnicode() function.
1836 LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
1837 #ifdef SQLITE_ENABLE_API_ARMOR
1838 if( !zText ){
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 winUtf8ToUnicode(zText);
1850 ** This is a public wrapper for the winUnicodeToUtf8() function.
1852 char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
1853 #ifdef SQLITE_ENABLE_API_ARMOR
1854 if( !zWideText ){
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 winUnicodeToUtf8(zWideText);
1866 ** This is a public wrapper for the winMbcsToUtf8() function.
1868 char *sqlite3_win32_mbcs_to_utf8(const char *zText){
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, osAreFileApisANSI());
1882 ** This is a public wrapper for the winMbcsToUtf8() function.
1884 char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
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 winMbcsToUtf8(zText, useAnsi);
1898 ** This is a public wrapper for the winUtf8ToMbcs() function.
1900 char *sqlite3_win32_utf8_to_mbcs(const char *zText){
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, osAreFileApisANSI());
1914 ** This is a public wrapper for the winUtf8ToMbcs() function.
1916 char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
1917 #ifdef SQLITE_ENABLE_API_ARMOR
1918 if( !zText ){
1919 (void)SQLITE_MISUSE_BKPT;
1920 return 0;
1922 #endif
1923 #ifndef SQLITE_OMIT_AUTOINIT
1924 if( sqlite3_initialize() ) return 0;
1925 #endif
1926 return winUtf8ToMbcs(zText, useAnsi);
1930 ** This function sets the data directory or the temporary directory based on
1931 ** the provided arguments. The type argument must be 1 in order to set the
1932 ** data directory or 2 in order to set the temporary directory. The zValue
1933 ** argument is the name of the directory to use. The return value will be
1934 ** SQLITE_OK if successful.
1936 int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
1937 char **ppDirectory = 0;
1938 #ifndef SQLITE_OMIT_AUTOINIT
1939 int rc = sqlite3_initialize();
1940 if( rc ) return rc;
1941 #endif
1942 if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
1943 ppDirectory = &sqlite3_data_directory;
1944 }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
1945 ppDirectory = &sqlite3_temp_directory;
1947 assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
1948 || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
1950 assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
1951 if( ppDirectory ){
1952 char *zValueUtf8 = 0;
1953 if( zValue && zValue[0] ){
1954 zValueUtf8 = winUnicodeToUtf8(zValue);
1955 if ( zValueUtf8==0 ){
1956 return SQLITE_NOMEM_BKPT;
1959 sqlite3_free(*ppDirectory);
1960 *ppDirectory = zValueUtf8;
1961 return SQLITE_OK;
1963 return SQLITE_ERROR;
1967 ** The return value of winGetLastErrorMsg
1968 ** is zero if the error message fits in the buffer, or non-zero
1969 ** otherwise (if the message was truncated).
1971 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
1972 /* FormatMessage returns 0 on failure. Otherwise it
1973 ** returns the number of TCHARs written to the output
1974 ** buffer, excluding the terminating null char.
1976 DWORD dwLen = 0;
1977 char *zOut = 0;
1979 if( osIsNT() ){
1980 #if SQLITE_OS_WINRT
1981 WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
1982 dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
1983 FORMAT_MESSAGE_IGNORE_INSERTS,
1984 NULL,
1985 lastErrno,
1987 zTempWide,
1988 SQLITE_WIN32_MAX_ERRMSG_CHARS,
1990 #else
1991 LPWSTR zTempWide = NULL;
1992 dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1993 FORMAT_MESSAGE_FROM_SYSTEM |
1994 FORMAT_MESSAGE_IGNORE_INSERTS,
1995 NULL,
1996 lastErrno,
1998 (LPWSTR) &zTempWide,
2001 #endif
2002 if( dwLen > 0 ){
2003 /* allocate a buffer and convert to UTF8 */
2004 sqlite3BeginBenignMalloc();
2005 zOut = winUnicodeToUtf8(zTempWide);
2006 sqlite3EndBenignMalloc();
2007 #if !SQLITE_OS_WINRT
2008 /* free the system buffer allocated by FormatMessage */
2009 osLocalFree(zTempWide);
2010 #endif
2013 #ifdef SQLITE_WIN32_HAS_ANSI
2014 else{
2015 char *zTemp = NULL;
2016 dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2017 FORMAT_MESSAGE_FROM_SYSTEM |
2018 FORMAT_MESSAGE_IGNORE_INSERTS,
2019 NULL,
2020 lastErrno,
2022 (LPSTR) &zTemp,
2025 if( dwLen > 0 ){
2026 /* allocate a buffer and convert to UTF8 */
2027 sqlite3BeginBenignMalloc();
2028 zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
2029 sqlite3EndBenignMalloc();
2030 /* free the system buffer allocated by FormatMessage */
2031 osLocalFree(zTemp);
2034 #endif
2035 if( 0 == dwLen ){
2036 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
2037 }else{
2038 /* copy a maximum of nBuf chars to output buffer */
2039 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
2040 /* free the UTF8 buffer */
2041 sqlite3_free(zOut);
2043 return 0;
2048 ** This function - winLogErrorAtLine() - is only ever called via the macro
2049 ** winLogError().
2051 ** This routine is invoked after an error occurs in an OS function.
2052 ** It logs a message using sqlite3_log() containing the current value of
2053 ** error code and, if possible, the human-readable equivalent from
2054 ** FormatMessage.
2056 ** The first argument passed to the macro should be the error code that
2057 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
2058 ** The two subsequent arguments should be the name of the OS function that
2059 ** failed and the associated file-system path, if any.
2061 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
2062 static int winLogErrorAtLine(
2063 int errcode, /* SQLite error code */
2064 DWORD lastErrno, /* Win32 last error */
2065 const char *zFunc, /* Name of OS function that failed */
2066 const char *zPath, /* File path associated with error */
2067 int iLine /* Source line number where error occurred */
2069 char zMsg[500]; /* Human readable error text */
2070 int i; /* Loop counter */
2072 zMsg[0] = 0;
2073 winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
2074 assert( errcode!=SQLITE_OK );
2075 if( zPath==0 ) zPath = "";
2076 for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
2077 zMsg[i] = 0;
2078 sqlite3_log(errcode,
2079 "os_win.c:%d: (%lu) %s(%s) - %s",
2080 iLine, lastErrno, zFunc, zPath, zMsg
2083 return errcode;
2087 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
2088 ** will be retried following a locking error - probably caused by
2089 ** antivirus software. Also the initial delay before the first retry.
2090 ** The delay increases linearly with each retry.
2092 #ifndef SQLITE_WIN32_IOERR_RETRY
2093 # define SQLITE_WIN32_IOERR_RETRY 10
2094 #endif
2095 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
2096 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
2097 #endif
2098 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
2099 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
2102 ** The "winIsLockingError" macro is used to determine if a particular I/O
2103 ** error code is due to file locking. It must accept the error code DWORD
2104 ** as its only argument and should return non-zero if the error code is due
2105 ** to file locking.
2107 #if !defined(winIsLockingError)
2108 #define winIsLockingError(a) (((a)==NO_ERROR) || \
2109 ((a)==ERROR_LOCK_VIOLATION) || \
2110 ((a)==ERROR_HANDLE_EOF) || \
2111 ((a)==ERROR_IO_PENDING))
2112 #endif
2115 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
2116 ** error code obtained via GetLastError() is eligible to be retried. It
2117 ** must accept the error code DWORD as its only argument and should return
2118 ** non-zero if the error code is transient in nature and the operation
2119 ** responsible for generating the original error might succeed upon being
2120 ** retried. The argument to this macro should be a variable.
2122 ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
2123 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
2124 ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
2125 ** may be used to include additional error codes in the set that should
2126 ** result in the failing I/O operation being retried by the caller. If
2127 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
2128 ** identical to those of the "winIoerrCanRetry1" macro.
2130 #if !defined(winIoerrCanRetry1)
2131 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
2132 ((a)==ERROR_SHARING_VIOLATION) || \
2133 ((a)==ERROR_LOCK_VIOLATION) || \
2134 ((a)==ERROR_DEV_NOT_EXIST) || \
2135 ((a)==ERROR_NETNAME_DELETED) || \
2136 ((a)==ERROR_SEM_TIMEOUT) || \
2137 ((a)==ERROR_NETWORK_UNREACHABLE))
2138 #endif
2141 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
2142 ** to see if it should be retried. Return TRUE to retry. Return FALSE
2143 ** to give up with an error.
2145 static int winRetryIoerr(int *pnRetry, DWORD *pError){
2146 DWORD e = osGetLastError();
2147 if( *pnRetry>=winIoerrRetry ){
2148 if( pError ){
2149 *pError = e;
2151 return 0;
2153 if( winIoerrCanRetry1(e) ){
2154 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
2155 ++*pnRetry;
2156 return 1;
2158 #if defined(winIoerrCanRetry2)
2159 else if( winIoerrCanRetry2(e) ){
2160 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
2161 ++*pnRetry;
2162 return 1;
2164 #endif
2165 if( pError ){
2166 *pError = e;
2168 return 0;
2172 ** Log a I/O error retry episode.
2174 static void winLogIoerr(int nRetry, int lineno){
2175 if( nRetry ){
2176 sqlite3_log(SQLITE_NOTICE,
2177 "delayed %dms for lock/sharing conflict at line %d",
2178 winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
2184 ** This #if does not rely on the SQLITE_OS_WINCE define because the
2185 ** corresponding section in "date.c" cannot use it.
2187 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
2188 (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
2190 ** The MSVC CRT on Windows CE may not have a localtime() function.
2191 ** So define a substitute.
2193 # include <time.h>
2194 struct tm *__cdecl localtime(const time_t *t)
2196 static struct tm y;
2197 FILETIME uTm, lTm;
2198 SYSTEMTIME pTm;
2199 sqlite3_int64 t64;
2200 t64 = *t;
2201 t64 = (t64 + 11644473600)*10000000;
2202 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
2203 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
2204 osFileTimeToLocalFileTime(&uTm,&lTm);
2205 osFileTimeToSystemTime(&lTm,&pTm);
2206 y.tm_year = pTm.wYear - 1900;
2207 y.tm_mon = pTm.wMonth - 1;
2208 y.tm_wday = pTm.wDayOfWeek;
2209 y.tm_mday = pTm.wDay;
2210 y.tm_hour = pTm.wHour;
2211 y.tm_min = pTm.wMinute;
2212 y.tm_sec = pTm.wSecond;
2213 return &y;
2215 #endif
2217 #if SQLITE_OS_WINCE
2218 /*************************************************************************
2219 ** This section contains code for WinCE only.
2221 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
2224 ** Acquire a lock on the handle h
2226 static void winceMutexAcquire(HANDLE h){
2227 DWORD dwErr;
2228 do {
2229 dwErr = osWaitForSingleObject(h, INFINITE);
2230 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
2233 ** Release a lock acquired by winceMutexAcquire()
2235 #define winceMutexRelease(h) ReleaseMutex(h)
2238 ** Create the mutex and shared memory used for locking in the file
2239 ** descriptor pFile
2241 static int winceCreateLock(const char *zFilename, winFile *pFile){
2242 LPWSTR zTok;
2243 LPWSTR zName;
2244 DWORD lastErrno;
2245 BOOL bLogged = FALSE;
2246 BOOL bInit = TRUE;
2248 zName = winUtf8ToUnicode(zFilename);
2249 if( zName==0 ){
2250 /* out of memory */
2251 return SQLITE_IOERR_NOMEM_BKPT;
2254 /* Initialize the local lockdata */
2255 memset(&pFile->local, 0, sizeof(pFile->local));
2257 /* Replace the backslashes from the filename and lowercase it
2258 ** to derive a mutex name. */
2259 zTok = osCharLowerW(zName);
2260 for (;*zTok;zTok++){
2261 if (*zTok == '\\') *zTok = '_';
2264 /* Create/open the named mutex */
2265 pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
2266 if (!pFile->hMutex){
2267 pFile->lastErrno = osGetLastError();
2268 sqlite3_free(zName);
2269 return winLogError(SQLITE_IOERR, pFile->lastErrno,
2270 "winceCreateLock1", zFilename);
2273 /* Acquire the mutex before continuing */
2274 winceMutexAcquire(pFile->hMutex);
2276 /* Since the names of named mutexes, semaphores, file mappings etc are
2277 ** case-sensitive, take advantage of that by uppercasing the mutex name
2278 ** and using that as the shared filemapping name.
2280 osCharUpperW(zName);
2281 pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
2282 PAGE_READWRITE, 0, sizeof(winceLock),
2283 zName);
2285 /* Set a flag that indicates we're the first to create the memory so it
2286 ** must be zero-initialized */
2287 lastErrno = osGetLastError();
2288 if (lastErrno == ERROR_ALREADY_EXISTS){
2289 bInit = FALSE;
2292 sqlite3_free(zName);
2294 /* If we succeeded in making the shared memory handle, map it. */
2295 if( pFile->hShared ){
2296 pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
2297 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
2298 /* If mapping failed, close the shared memory handle and erase it */
2299 if( !pFile->shared ){
2300 pFile->lastErrno = osGetLastError();
2301 winLogError(SQLITE_IOERR, pFile->lastErrno,
2302 "winceCreateLock2", zFilename);
2303 bLogged = TRUE;
2304 osCloseHandle(pFile->hShared);
2305 pFile->hShared = NULL;
2309 /* If shared memory could not be created, then close the mutex and fail */
2310 if( pFile->hShared==NULL ){
2311 if( !bLogged ){
2312 pFile->lastErrno = lastErrno;
2313 winLogError(SQLITE_IOERR, pFile->lastErrno,
2314 "winceCreateLock3", zFilename);
2315 bLogged = TRUE;
2317 winceMutexRelease(pFile->hMutex);
2318 osCloseHandle(pFile->hMutex);
2319 pFile->hMutex = NULL;
2320 return SQLITE_IOERR;
2323 /* Initialize the shared memory if we're supposed to */
2324 if( bInit ){
2325 memset(pFile->shared, 0, sizeof(winceLock));
2328 winceMutexRelease(pFile->hMutex);
2329 return SQLITE_OK;
2333 ** Destroy the part of winFile that deals with wince locks
2335 static void winceDestroyLock(winFile *pFile){
2336 if (pFile->hMutex){
2337 /* Acquire the mutex */
2338 winceMutexAcquire(pFile->hMutex);
2340 /* The following blocks should probably assert in debug mode, but they
2341 are to cleanup in case any locks remained open */
2342 if (pFile->local.nReaders){
2343 pFile->shared->nReaders --;
2345 if (pFile->local.bReserved){
2346 pFile->shared->bReserved = FALSE;
2348 if (pFile->local.bPending){
2349 pFile->shared->bPending = FALSE;
2351 if (pFile->local.bExclusive){
2352 pFile->shared->bExclusive = FALSE;
2355 /* De-reference and close our copy of the shared memory handle */
2356 osUnmapViewOfFile(pFile->shared);
2357 osCloseHandle(pFile->hShared);
2359 /* Done with the mutex */
2360 winceMutexRelease(pFile->hMutex);
2361 osCloseHandle(pFile->hMutex);
2362 pFile->hMutex = NULL;
2367 ** An implementation of the LockFile() API of Windows for CE
2369 static BOOL winceLockFile(
2370 LPHANDLE phFile,
2371 DWORD dwFileOffsetLow,
2372 DWORD dwFileOffsetHigh,
2373 DWORD nNumberOfBytesToLockLow,
2374 DWORD nNumberOfBytesToLockHigh
2376 winFile *pFile = HANDLE_TO_WINFILE(phFile);
2377 BOOL bReturn = FALSE;
2379 UNUSED_PARAMETER(dwFileOffsetHigh);
2380 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
2382 if (!pFile->hMutex) return TRUE;
2383 winceMutexAcquire(pFile->hMutex);
2385 /* Wanting an exclusive lock? */
2386 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
2387 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
2388 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
2389 pFile->shared->bExclusive = TRUE;
2390 pFile->local.bExclusive = TRUE;
2391 bReturn = TRUE;
2395 /* Want a read-only lock? */
2396 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
2397 nNumberOfBytesToLockLow == 1){
2398 if (pFile->shared->bExclusive == 0){
2399 pFile->local.nReaders ++;
2400 if (pFile->local.nReaders == 1){
2401 pFile->shared->nReaders ++;
2403 bReturn = TRUE;
2407 /* Want a pending lock? */
2408 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
2409 && nNumberOfBytesToLockLow == 1){
2410 /* If no pending lock has been acquired, then acquire it */
2411 if (pFile->shared->bPending == 0) {
2412 pFile->shared->bPending = TRUE;
2413 pFile->local.bPending = TRUE;
2414 bReturn = TRUE;
2418 /* Want a reserved lock? */
2419 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
2420 && nNumberOfBytesToLockLow == 1){
2421 if (pFile->shared->bReserved == 0) {
2422 pFile->shared->bReserved = TRUE;
2423 pFile->local.bReserved = TRUE;
2424 bReturn = TRUE;
2428 winceMutexRelease(pFile->hMutex);
2429 return bReturn;
2433 ** An implementation of the UnlockFile API of Windows for CE
2435 static BOOL winceUnlockFile(
2436 LPHANDLE phFile,
2437 DWORD dwFileOffsetLow,
2438 DWORD dwFileOffsetHigh,
2439 DWORD nNumberOfBytesToUnlockLow,
2440 DWORD nNumberOfBytesToUnlockHigh
2442 winFile *pFile = HANDLE_TO_WINFILE(phFile);
2443 BOOL bReturn = FALSE;
2445 UNUSED_PARAMETER(dwFileOffsetHigh);
2446 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
2448 if (!pFile->hMutex) return TRUE;
2449 winceMutexAcquire(pFile->hMutex);
2451 /* Releasing a reader lock or an exclusive lock */
2452 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
2453 /* Did we have an exclusive lock? */
2454 if (pFile->local.bExclusive){
2455 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
2456 pFile->local.bExclusive = FALSE;
2457 pFile->shared->bExclusive = FALSE;
2458 bReturn = TRUE;
2461 /* Did we just have a reader lock? */
2462 else if (pFile->local.nReaders){
2463 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
2464 || nNumberOfBytesToUnlockLow == 1);
2465 pFile->local.nReaders --;
2466 if (pFile->local.nReaders == 0)
2468 pFile->shared->nReaders --;
2470 bReturn = TRUE;
2474 /* Releasing a pending lock */
2475 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
2476 && nNumberOfBytesToUnlockLow == 1){
2477 if (pFile->local.bPending){
2478 pFile->local.bPending = FALSE;
2479 pFile->shared->bPending = FALSE;
2480 bReturn = TRUE;
2483 /* Releasing a reserved lock */
2484 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
2485 && nNumberOfBytesToUnlockLow == 1){
2486 if (pFile->local.bReserved) {
2487 pFile->local.bReserved = FALSE;
2488 pFile->shared->bReserved = FALSE;
2489 bReturn = TRUE;
2493 winceMutexRelease(pFile->hMutex);
2494 return bReturn;
2497 ** End of the special code for wince
2498 *****************************************************************************/
2499 #endif /* SQLITE_OS_WINCE */
2502 ** Lock a file region.
2504 static BOOL winLockFile(
2505 LPHANDLE phFile,
2506 DWORD flags,
2507 DWORD offsetLow,
2508 DWORD offsetHigh,
2509 DWORD numBytesLow,
2510 DWORD numBytesHigh
2512 #if SQLITE_OS_WINCE
2514 ** NOTE: Windows CE is handled differently here due its lack of the Win32
2515 ** API LockFile.
2517 return winceLockFile(phFile, offsetLow, offsetHigh,
2518 numBytesLow, numBytesHigh);
2519 #else
2520 if( osIsNT() ){
2521 OVERLAPPED ovlp;
2522 memset(&ovlp, 0, sizeof(OVERLAPPED));
2523 ovlp.Offset = offsetLow;
2524 ovlp.OffsetHigh = offsetHigh;
2525 return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
2526 }else{
2527 return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
2528 numBytesHigh);
2530 #endif
2534 ** Unlock a file region.
2536 static BOOL winUnlockFile(
2537 LPHANDLE phFile,
2538 DWORD offsetLow,
2539 DWORD offsetHigh,
2540 DWORD numBytesLow,
2541 DWORD numBytesHigh
2543 #if SQLITE_OS_WINCE
2545 ** NOTE: Windows CE is handled differently here due its lack of the Win32
2546 ** API UnlockFile.
2548 return winceUnlockFile(phFile, offsetLow, offsetHigh,
2549 numBytesLow, numBytesHigh);
2550 #else
2551 if( osIsNT() ){
2552 OVERLAPPED ovlp;
2553 memset(&ovlp, 0, sizeof(OVERLAPPED));
2554 ovlp.Offset = offsetLow;
2555 ovlp.OffsetHigh = offsetHigh;
2556 return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
2557 }else{
2558 return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
2559 numBytesHigh);
2561 #endif
2564 /*****************************************************************************
2565 ** The next group of routines implement the I/O methods specified
2566 ** by the sqlite3_io_methods object.
2567 ******************************************************************************/
2570 ** Some Microsoft compilers lack this definition.
2572 #ifndef INVALID_SET_FILE_POINTER
2573 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
2574 #endif
2577 ** Move the current position of the file handle passed as the first
2578 ** argument to offset iOffset within the file. If successful, return 0.
2579 ** Otherwise, set pFile->lastErrno and return non-zero.
2581 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
2582 #if !SQLITE_OS_WINRT
2583 LONG upperBits; /* Most sig. 32 bits of new offset */
2584 LONG lowerBits; /* Least sig. 32 bits of new offset */
2585 DWORD dwRet; /* Value returned by SetFilePointer() */
2586 DWORD lastErrno; /* Value returned by GetLastError() */
2588 OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
2590 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
2591 lowerBits = (LONG)(iOffset & 0xffffffff);
2593 /* API oddity: If successful, SetFilePointer() returns a dword
2594 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
2595 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
2596 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
2597 ** whether an error has actually occurred, it is also necessary to call
2598 ** GetLastError().
2600 dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
2602 if( (dwRet==INVALID_SET_FILE_POINTER
2603 && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
2604 pFile->lastErrno = lastErrno;
2605 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
2606 "winSeekFile", pFile->zPath);
2607 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
2608 return 1;
2611 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
2612 return 0;
2613 #else
2615 ** Same as above, except that this implementation works for WinRT.
2618 LARGE_INTEGER x; /* The new offset */
2619 BOOL bRet; /* Value returned by SetFilePointerEx() */
2621 x.QuadPart = iOffset;
2622 bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
2624 if(!bRet){
2625 pFile->lastErrno = osGetLastError();
2626 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
2627 "winSeekFile", pFile->zPath);
2628 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
2629 return 1;
2632 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
2633 return 0;
2634 #endif
2637 #if SQLITE_MAX_MMAP_SIZE>0
2638 /* Forward references to VFS helper methods used for memory mapped files */
2639 static int winMapfile(winFile*, sqlite3_int64);
2640 static int winUnmapfile(winFile*);
2641 #endif
2644 ** Close a file.
2646 ** It is reported that an attempt to close a handle might sometimes
2647 ** fail. This is a very unreasonable result, but Windows is notorious
2648 ** for being unreasonable so I do not doubt that it might happen. If
2649 ** the close fails, we pause for 100 milliseconds and try again. As
2650 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
2651 ** giving up and returning an error.
2653 #define MX_CLOSE_ATTEMPT 3
2654 static int winClose(sqlite3_file *id){
2655 int rc, cnt = 0;
2656 winFile *pFile = (winFile*)id;
2658 assert( id!=0 );
2659 #ifndef SQLITE_OMIT_WAL
2660 assert( pFile->pShm==0 );
2661 #endif
2662 assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
2663 OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
2664 osGetCurrentProcessId(), pFile, pFile->h));
2666 #if SQLITE_MAX_MMAP_SIZE>0
2667 winUnmapfile(pFile);
2668 #endif
2671 rc = osCloseHandle(pFile->h);
2672 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
2673 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
2674 #if SQLITE_OS_WINCE
2675 #define WINCE_DELETION_ATTEMPTS 3
2677 winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
2678 if( pAppData==NULL || !pAppData->bNoLock ){
2679 winceDestroyLock(pFile);
2682 if( pFile->zDeleteOnClose ){
2683 int cnt = 0;
2684 while(
2685 osDeleteFileW(pFile->zDeleteOnClose)==0
2686 && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
2687 && cnt++ < WINCE_DELETION_ATTEMPTS
2689 sqlite3_win32_sleep(100); /* Wait a little before trying again */
2691 sqlite3_free(pFile->zDeleteOnClose);
2693 #endif
2694 if( rc ){
2695 pFile->h = NULL;
2697 OpenCounter(-1);
2698 OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
2699 osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
2700 return rc ? SQLITE_OK
2701 : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
2702 "winClose", pFile->zPath);
2706 ** Read data from a file into a buffer. Return SQLITE_OK if all
2707 ** bytes were read successfully and SQLITE_IOERR if anything goes
2708 ** wrong.
2710 static int winRead(
2711 sqlite3_file *id, /* File to read from */
2712 void *pBuf, /* Write content into this buffer */
2713 int amt, /* Number of bytes to read */
2714 sqlite3_int64 offset /* Begin reading at this offset */
2716 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2717 OVERLAPPED overlapped; /* The offset for ReadFile. */
2718 #endif
2719 winFile *pFile = (winFile*)id; /* file handle */
2720 DWORD nRead; /* Number of bytes actually read from file */
2721 int nRetry = 0; /* Number of retrys */
2723 assert( id!=0 );
2724 assert( amt>0 );
2725 assert( offset>=0 );
2726 SimulateIOError(return SQLITE_IOERR_READ);
2727 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
2728 "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
2729 pFile->h, pBuf, amt, offset, pFile->locktype));
2731 #if SQLITE_MAX_MMAP_SIZE>0
2732 /* Deal with as much of this read request as possible by transfering
2733 ** data from the memory mapping using memcpy(). */
2734 if( offset<pFile->mmapSize ){
2735 if( offset+amt <= pFile->mmapSize ){
2736 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
2737 OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2738 osGetCurrentProcessId(), pFile, pFile->h));
2739 return SQLITE_OK;
2740 }else{
2741 int nCopy = (int)(pFile->mmapSize - offset);
2742 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
2743 pBuf = &((u8 *)pBuf)[nCopy];
2744 amt -= nCopy;
2745 offset += nCopy;
2748 #endif
2750 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
2751 if( winSeekFile(pFile, offset) ){
2752 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
2753 osGetCurrentProcessId(), pFile, pFile->h));
2754 return SQLITE_FULL;
2756 while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
2757 #else
2758 memset(&overlapped, 0, sizeof(OVERLAPPED));
2759 overlapped.Offset = (LONG)(offset & 0xffffffff);
2760 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
2761 while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
2762 osGetLastError()!=ERROR_HANDLE_EOF ){
2763 #endif
2764 DWORD lastErrno;
2765 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
2766 pFile->lastErrno = lastErrno;
2767 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
2768 osGetCurrentProcessId(), pFile, pFile->h));
2769 return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
2770 "winRead", pFile->zPath);
2772 winLogIoerr(nRetry, __LINE__);
2773 if( nRead<(DWORD)amt ){
2774 /* Unread parts of the buffer must be zero-filled */
2775 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
2776 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
2777 osGetCurrentProcessId(), pFile, pFile->h));
2778 return SQLITE_IOERR_SHORT_READ;
2781 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2782 osGetCurrentProcessId(), pFile, pFile->h));
2783 return SQLITE_OK;
2787 ** Write data from a buffer into a file. Return SQLITE_OK on success
2788 ** or some other error code on failure.
2790 static int winWrite(
2791 sqlite3_file *id, /* File to write into */
2792 const void *pBuf, /* The bytes to be written */
2793 int amt, /* Number of bytes to write */
2794 sqlite3_int64 offset /* Offset into the file to begin writing at */
2796 int rc = 0; /* True if error has occurred, else false */
2797 winFile *pFile = (winFile*)id; /* File handle */
2798 int nRetry = 0; /* Number of retries */
2800 assert( amt>0 );
2801 assert( pFile );
2802 SimulateIOError(return SQLITE_IOERR_WRITE);
2803 SimulateDiskfullError(return SQLITE_FULL);
2805 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
2806 "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
2807 pFile->h, pBuf, amt, offset, pFile->locktype));
2809 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
2810 /* Deal with as much of this write request as possible by transfering
2811 ** data from the memory mapping using memcpy(). */
2812 if( offset<pFile->mmapSize ){
2813 if( offset+amt <= pFile->mmapSize ){
2814 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
2815 OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2816 osGetCurrentProcessId(), pFile, pFile->h));
2817 return SQLITE_OK;
2818 }else{
2819 int nCopy = (int)(pFile->mmapSize - offset);
2820 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
2821 pBuf = &((u8 *)pBuf)[nCopy];
2822 amt -= nCopy;
2823 offset += nCopy;
2826 #endif
2828 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
2829 rc = winSeekFile(pFile, offset);
2830 if( rc==0 ){
2831 #else
2833 #endif
2834 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2835 OVERLAPPED overlapped; /* The offset for WriteFile. */
2836 #endif
2837 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
2838 int nRem = amt; /* Number of bytes yet to be written */
2839 DWORD nWrite; /* Bytes written by each WriteFile() call */
2840 DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
2842 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2843 memset(&overlapped, 0, sizeof(OVERLAPPED));
2844 overlapped.Offset = (LONG)(offset & 0xffffffff);
2845 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
2846 #endif
2848 while( nRem>0 ){
2849 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
2850 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
2851 #else
2852 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
2853 #endif
2854 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
2855 break;
2857 assert( nWrite==0 || nWrite<=(DWORD)nRem );
2858 if( nWrite==0 || nWrite>(DWORD)nRem ){
2859 lastErrno = osGetLastError();
2860 break;
2862 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2863 offset += nWrite;
2864 overlapped.Offset = (LONG)(offset & 0xffffffff);
2865 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
2866 #endif
2867 aRem += nWrite;
2868 nRem -= nWrite;
2870 if( nRem>0 ){
2871 pFile->lastErrno = lastErrno;
2872 rc = 1;
2876 if( rc ){
2877 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
2878 || ( pFile->lastErrno==ERROR_DISK_FULL )){
2879 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
2880 osGetCurrentProcessId(), pFile, pFile->h));
2881 return winLogError(SQLITE_FULL, pFile->lastErrno,
2882 "winWrite1", pFile->zPath);
2884 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
2885 osGetCurrentProcessId(), pFile, pFile->h));
2886 return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
2887 "winWrite2", pFile->zPath);
2888 }else{
2889 winLogIoerr(nRetry, __LINE__);
2891 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2892 osGetCurrentProcessId(), pFile, pFile->h));
2893 return SQLITE_OK;
2897 ** Truncate an open file to a specified size
2899 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
2900 winFile *pFile = (winFile*)id; /* File handle object */
2901 int rc = SQLITE_OK; /* Return code for this function */
2902 DWORD lastErrno;
2904 assert( pFile );
2905 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
2906 OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
2907 osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
2909 /* If the user has configured a chunk-size for this file, truncate the
2910 ** file so that it consists of an integer number of chunks (i.e. the
2911 ** actual file size after the operation may be larger than the requested
2912 ** size).
2914 if( pFile->szChunk>0 ){
2915 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
2918 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
2919 if( winSeekFile(pFile, nByte) ){
2920 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
2921 "winTruncate1", pFile->zPath);
2922 }else if( 0==osSetEndOfFile(pFile->h) &&
2923 ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
2924 pFile->lastErrno = lastErrno;
2925 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
2926 "winTruncate2", pFile->zPath);
2929 #if SQLITE_MAX_MMAP_SIZE>0
2930 /* If the file was truncated to a size smaller than the currently
2931 ** mapped region, reduce the effective mapping size as well. SQLite will
2932 ** use read() and write() to access data beyond this point from now on.
2934 if( pFile->pMapRegion && nByte<pFile->mmapSize ){
2935 pFile->mmapSize = nByte;
2937 #endif
2939 OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
2940 osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
2941 return rc;
2944 #ifdef SQLITE_TEST
2946 ** Count the number of fullsyncs and normal syncs. This is used to test
2947 ** that syncs and fullsyncs are occuring at the right times.
2949 int sqlite3_sync_count = 0;
2950 int sqlite3_fullsync_count = 0;
2951 #endif
2954 ** Make sure all writes to a particular file are committed to disk.
2956 static int winSync(sqlite3_file *id, int flags){
2957 #ifndef SQLITE_NO_SYNC
2959 ** Used only when SQLITE_NO_SYNC is not defined.
2961 BOOL rc;
2962 #endif
2963 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
2964 defined(SQLITE_HAVE_OS_TRACE)
2966 ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
2967 ** OSTRACE() macros.
2969 winFile *pFile = (winFile*)id;
2970 #else
2971 UNUSED_PARAMETER(id);
2972 #endif
2974 assert( pFile );
2975 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2976 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2977 || (flags&0x0F)==SQLITE_SYNC_FULL
2980 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2981 ** line is to test that doing so does not cause any problems.
2983 SimulateDiskfullError( return SQLITE_FULL );
2985 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
2986 osGetCurrentProcessId(), pFile, pFile->h, flags,
2987 pFile->locktype));
2989 #ifndef SQLITE_TEST
2990 UNUSED_PARAMETER(flags);
2991 #else
2992 if( (flags&0x0F)==SQLITE_SYNC_FULL ){
2993 sqlite3_fullsync_count++;
2995 sqlite3_sync_count++;
2996 #endif
2998 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2999 ** no-op
3001 #ifdef SQLITE_NO_SYNC
3002 OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
3003 osGetCurrentProcessId(), pFile, pFile->h));
3004 return SQLITE_OK;
3005 #else
3006 #if SQLITE_MAX_MMAP_SIZE>0
3007 if( pFile->pMapRegion ){
3008 if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
3009 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
3010 "rc=SQLITE_OK\n", osGetCurrentProcessId(),
3011 pFile, pFile->pMapRegion));
3012 }else{
3013 pFile->lastErrno = osGetLastError();
3014 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
3015 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
3016 pFile, pFile->pMapRegion));
3017 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
3018 "winSync1", pFile->zPath);
3021 #endif
3022 rc = osFlushFileBuffers(pFile->h);
3023 SimulateIOError( rc=FALSE );
3024 if( rc ){
3025 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
3026 osGetCurrentProcessId(), pFile, pFile->h));
3027 return SQLITE_OK;
3028 }else{
3029 pFile->lastErrno = osGetLastError();
3030 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
3031 osGetCurrentProcessId(), pFile, pFile->h));
3032 return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
3033 "winSync2", pFile->zPath);
3035 #endif
3039 ** Determine the current size of a file in bytes
3041 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
3042 winFile *pFile = (winFile*)id;
3043 int rc = SQLITE_OK;
3045 assert( id!=0 );
3046 assert( pSize!=0 );
3047 SimulateIOError(return SQLITE_IOERR_FSTAT);
3048 OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
3050 #if SQLITE_OS_WINRT
3052 FILE_STANDARD_INFO info;
3053 if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
3054 &info, sizeof(info)) ){
3055 *pSize = info.EndOfFile.QuadPart;
3056 }else{
3057 pFile->lastErrno = osGetLastError();
3058 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
3059 "winFileSize", pFile->zPath);
3062 #else
3064 DWORD upperBits;
3065 DWORD lowerBits;
3066 DWORD lastErrno;
3068 lowerBits = osGetFileSize(pFile->h, &upperBits);
3069 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
3070 if( (lowerBits == INVALID_FILE_SIZE)
3071 && ((lastErrno = osGetLastError())!=NO_ERROR) ){
3072 pFile->lastErrno = lastErrno;
3073 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
3074 "winFileSize", pFile->zPath);
3077 #endif
3078 OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
3079 pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
3080 return rc;
3084 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
3086 #ifndef LOCKFILE_FAIL_IMMEDIATELY
3087 # define LOCKFILE_FAIL_IMMEDIATELY 1
3088 #endif
3090 #ifndef LOCKFILE_EXCLUSIVE_LOCK
3091 # define LOCKFILE_EXCLUSIVE_LOCK 2
3092 #endif
3095 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
3096 ** When the LockFile function was used, it was always expected to fail
3097 ** immediately if the lock could not be obtained. Also, it always expected to
3098 ** obtain an exclusive lock. These flags are used with the LockFileEx function
3099 ** and reflect those expectations; therefore, they should not be changed.
3101 #ifndef SQLITE_LOCKFILE_FLAGS
3102 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
3103 LOCKFILE_EXCLUSIVE_LOCK)
3104 #endif
3107 ** Currently, SQLite never calls the LockFileEx function without wanting the
3108 ** call to fail immediately if the lock cannot be obtained.
3110 #ifndef SQLITE_LOCKFILEEX_FLAGS
3111 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
3112 #endif
3115 ** Acquire a reader lock.
3116 ** Different API routines are called depending on whether or not this
3117 ** is Win9x or WinNT.
3119 static int winGetReadLock(winFile *pFile){
3120 int res;
3121 OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
3122 if( osIsNT() ){
3123 #if SQLITE_OS_WINCE
3125 ** NOTE: Windows CE is handled differently here due its lack of the Win32
3126 ** API LockFileEx.
3128 res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
3129 #else
3130 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
3131 SHARED_SIZE, 0);
3132 #endif
3134 #ifdef SQLITE_WIN32_HAS_ANSI
3135 else{
3136 int lk;
3137 sqlite3_randomness(sizeof(lk), &lk);
3138 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
3139 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
3140 SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
3142 #endif
3143 if( res == 0 ){
3144 pFile->lastErrno = osGetLastError();
3145 /* No need to log a failure to lock */
3147 OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
3148 return res;
3152 ** Undo a readlock
3154 static int winUnlockReadLock(winFile *pFile){
3155 int res;
3156 DWORD lastErrno;
3157 OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
3158 if( osIsNT() ){
3159 res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
3161 #ifdef SQLITE_WIN32_HAS_ANSI
3162 else{
3163 res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
3165 #endif
3166 if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
3167 pFile->lastErrno = lastErrno;
3168 winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
3169 "winUnlockReadLock", pFile->zPath);
3171 OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
3172 return res;
3176 ** Lock the file with the lock specified by parameter locktype - one
3177 ** of the following:
3179 ** (1) SHARED_LOCK
3180 ** (2) RESERVED_LOCK
3181 ** (3) PENDING_LOCK
3182 ** (4) EXCLUSIVE_LOCK
3184 ** Sometimes when requesting one lock state, additional lock states
3185 ** are inserted in between. The locking might fail on one of the later
3186 ** transitions leaving the lock state different from what it started but
3187 ** still short of its goal. The following chart shows the allowed
3188 ** transitions and the inserted intermediate states:
3190 ** UNLOCKED -> SHARED
3191 ** SHARED -> RESERVED
3192 ** SHARED -> (PENDING) -> EXCLUSIVE
3193 ** RESERVED -> (PENDING) -> EXCLUSIVE
3194 ** PENDING -> EXCLUSIVE
3196 ** This routine will only increase a lock. The winUnlock() routine
3197 ** erases all locks at once and returns us immediately to locking level 0.
3198 ** It is not possible to lower the locking level one step at a time. You
3199 ** must go straight to locking level 0.
3201 static int winLock(sqlite3_file *id, int locktype){
3202 int rc = SQLITE_OK; /* Return code from subroutines */
3203 int res = 1; /* Result of a Windows lock call */
3204 int newLocktype; /* Set pFile->locktype to this value before exiting */
3205 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
3206 winFile *pFile = (winFile*)id;
3207 DWORD lastErrno = NO_ERROR;
3209 assert( id!=0 );
3210 OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
3211 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
3213 /* If there is already a lock of this type or more restrictive on the
3214 ** OsFile, do nothing. Don't use the end_lock: exit path, as
3215 ** sqlite3OsEnterMutex() hasn't been called yet.
3217 if( pFile->locktype>=locktype ){
3218 OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
3219 return SQLITE_OK;
3222 /* Do not allow any kind of write-lock on a read-only database
3224 if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
3225 return SQLITE_IOERR_LOCK;
3228 /* Make sure the locking sequence is correct
3230 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
3231 assert( locktype!=PENDING_LOCK );
3232 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
3234 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
3235 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
3236 ** the PENDING_LOCK byte is temporary.
3238 newLocktype = pFile->locktype;
3239 if( pFile->locktype==NO_LOCK
3240 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
3242 int cnt = 3;
3243 while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
3244 PENDING_BYTE, 0, 1, 0))==0 ){
3245 /* Try 3 times to get the pending lock. This is needed to work
3246 ** around problems caused by indexing and/or anti-virus software on
3247 ** Windows systems.
3248 ** If you are using this code as a model for alternative VFSes, do not
3249 ** copy this retry logic. It is a hack intended for Windows only.
3251 lastErrno = osGetLastError();
3252 OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
3253 pFile->h, cnt, res));
3254 if( lastErrno==ERROR_INVALID_HANDLE ){
3255 pFile->lastErrno = lastErrno;
3256 rc = SQLITE_IOERR_LOCK;
3257 OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
3258 pFile->h, cnt, sqlite3ErrName(rc)));
3259 return rc;
3261 if( cnt ) sqlite3_win32_sleep(1);
3263 gotPendingLock = res;
3264 if( !res ){
3265 lastErrno = osGetLastError();
3269 /* Acquire a shared lock
3271 if( locktype==SHARED_LOCK && res ){
3272 assert( pFile->locktype==NO_LOCK );
3273 res = winGetReadLock(pFile);
3274 if( res ){
3275 newLocktype = SHARED_LOCK;
3276 }else{
3277 lastErrno = osGetLastError();
3281 /* Acquire a RESERVED lock
3283 if( locktype==RESERVED_LOCK && res ){
3284 assert( pFile->locktype==SHARED_LOCK );
3285 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
3286 if( res ){
3287 newLocktype = RESERVED_LOCK;
3288 }else{
3289 lastErrno = osGetLastError();
3293 /* Acquire a PENDING lock
3295 if( locktype==EXCLUSIVE_LOCK && res ){
3296 newLocktype = PENDING_LOCK;
3297 gotPendingLock = 0;
3300 /* Acquire an EXCLUSIVE lock
3302 if( locktype==EXCLUSIVE_LOCK && res ){
3303 assert( pFile->locktype>=SHARED_LOCK );
3304 res = winUnlockReadLock(pFile);
3305 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
3306 SHARED_SIZE, 0);
3307 if( res ){
3308 newLocktype = EXCLUSIVE_LOCK;
3309 }else{
3310 lastErrno = osGetLastError();
3311 winGetReadLock(pFile);
3315 /* If we are holding a PENDING lock that ought to be released, then
3316 ** release it now.
3318 if( gotPendingLock && locktype==SHARED_LOCK ){
3319 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
3322 /* Update the state of the lock has held in the file descriptor then
3323 ** return the appropriate result code.
3325 if( res ){
3326 rc = SQLITE_OK;
3327 }else{
3328 pFile->lastErrno = lastErrno;
3329 rc = SQLITE_BUSY;
3330 OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
3331 pFile->h, locktype, newLocktype));
3333 pFile->locktype = (u8)newLocktype;
3334 OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
3335 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
3336 return rc;
3340 ** This routine checks if there is a RESERVED lock held on the specified
3341 ** file by this or any other process. If such a lock is held, return
3342 ** non-zero, otherwise zero.
3344 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
3345 int res;
3346 winFile *pFile = (winFile*)id;
3348 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
3349 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
3351 assert( id!=0 );
3352 if( pFile->locktype>=RESERVED_LOCK ){
3353 res = 1;
3354 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
3355 }else{
3356 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
3357 if( res ){
3358 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
3360 res = !res;
3361 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
3363 *pResOut = res;
3364 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
3365 pFile->h, pResOut, *pResOut));
3366 return SQLITE_OK;
3370 ** Lower the locking level on file descriptor id to locktype. locktype
3371 ** must be either NO_LOCK or SHARED_LOCK.
3373 ** If the locking level of the file descriptor is already at or below
3374 ** the requested locking level, this routine is a no-op.
3376 ** It is not possible for this routine to fail if the second argument
3377 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
3378 ** might return SQLITE_IOERR;
3380 static int winUnlock(sqlite3_file *id, int locktype){
3381 int type;
3382 winFile *pFile = (winFile*)id;
3383 int rc = SQLITE_OK;
3384 assert( pFile!=0 );
3385 assert( locktype<=SHARED_LOCK );
3386 OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
3387 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
3388 type = pFile->locktype;
3389 if( type>=EXCLUSIVE_LOCK ){
3390 winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
3391 if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
3392 /* This should never happen. We should always be able to
3393 ** reacquire the read lock */
3394 rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
3395 "winUnlock", pFile->zPath);
3398 if( type>=RESERVED_LOCK ){
3399 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
3401 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
3402 winUnlockReadLock(pFile);
3404 if( type>=PENDING_LOCK ){
3405 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
3407 pFile->locktype = (u8)locktype;
3408 OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
3409 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
3410 return rc;
3413 /******************************************************************************
3414 ****************************** No-op Locking **********************************
3416 ** Of the various locking implementations available, this is by far the
3417 ** simplest: locking is ignored. No attempt is made to lock the database
3418 ** file for reading or writing.
3420 ** This locking mode is appropriate for use on read-only databases
3421 ** (ex: databases that are burned into CD-ROM, for example.) It can
3422 ** also be used if the application employs some external mechanism to
3423 ** prevent simultaneous access of the same database by two or more
3424 ** database connections. But there is a serious risk of database
3425 ** corruption if this locking mode is used in situations where multiple
3426 ** database connections are accessing the same database file at the same
3427 ** time and one or more of those connections are writing.
3430 static int winNolockLock(sqlite3_file *id, int locktype){
3431 UNUSED_PARAMETER(id);
3432 UNUSED_PARAMETER(locktype);
3433 return SQLITE_OK;
3436 static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
3437 UNUSED_PARAMETER(id);
3438 UNUSED_PARAMETER(pResOut);
3439 return SQLITE_OK;
3442 static int winNolockUnlock(sqlite3_file *id, int locktype){
3443 UNUSED_PARAMETER(id);
3444 UNUSED_PARAMETER(locktype);
3445 return SQLITE_OK;
3448 /******************* End of the no-op lock implementation *********************
3449 ******************************************************************************/
3452 ** If *pArg is initially negative then this is a query. Set *pArg to
3453 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3455 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3457 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
3458 if( *pArg<0 ){
3459 *pArg = (pFile->ctrlFlags & mask)!=0;
3460 }else if( (*pArg)==0 ){
3461 pFile->ctrlFlags &= ~mask;
3462 }else{
3463 pFile->ctrlFlags |= mask;
3467 /* Forward references to VFS helper methods used for temporary files */
3468 static int winGetTempname(sqlite3_vfs *, char **);
3469 static int winIsDir(const void *);
3470 static BOOL winIsDriveLetterAndColon(const char *);
3473 ** Control and query of the open file handle.
3475 static int winFileControl(sqlite3_file *id, int op, void *pArg){
3476 winFile *pFile = (winFile*)id;
3477 OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
3478 switch( op ){
3479 case SQLITE_FCNTL_LOCKSTATE: {
3480 *(int*)pArg = pFile->locktype;
3481 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3482 return SQLITE_OK;
3484 case SQLITE_FCNTL_LAST_ERRNO: {
3485 *(int*)pArg = (int)pFile->lastErrno;
3486 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3487 return SQLITE_OK;
3489 case SQLITE_FCNTL_CHUNK_SIZE: {
3490 pFile->szChunk = *(int *)pArg;
3491 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3492 return SQLITE_OK;
3494 case SQLITE_FCNTL_SIZE_HINT: {
3495 if( pFile->szChunk>0 ){
3496 sqlite3_int64 oldSz;
3497 int rc = winFileSize(id, &oldSz);
3498 if( rc==SQLITE_OK ){
3499 sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
3500 if( newSz>oldSz ){
3501 SimulateIOErrorBenign(1);
3502 rc = winTruncate(id, newSz);
3503 SimulateIOErrorBenign(0);
3506 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
3507 return rc;
3509 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3510 return SQLITE_OK;
3512 case SQLITE_FCNTL_PERSIST_WAL: {
3513 winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
3514 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3515 return SQLITE_OK;
3517 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3518 winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
3519 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3520 return SQLITE_OK;
3522 case SQLITE_FCNTL_VFSNAME: {
3523 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3524 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3525 return SQLITE_OK;
3527 case SQLITE_FCNTL_WIN32_AV_RETRY: {
3528 int *a = (int*)pArg;
3529 if( a[0]>0 ){
3530 winIoerrRetry = a[0];
3531 }else{
3532 a[0] = winIoerrRetry;
3534 if( a[1]>0 ){
3535 winIoerrRetryDelay = a[1];
3536 }else{
3537 a[1] = winIoerrRetryDelay;
3539 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3540 return SQLITE_OK;
3542 case SQLITE_FCNTL_WIN32_GET_HANDLE: {
3543 LPHANDLE phFile = (LPHANDLE)pArg;
3544 *phFile = pFile->h;
3545 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
3546 return SQLITE_OK;
3548 #ifdef SQLITE_TEST
3549 case SQLITE_FCNTL_WIN32_SET_HANDLE: {
3550 LPHANDLE phFile = (LPHANDLE)pArg;
3551 HANDLE hOldFile = pFile->h;
3552 pFile->h = *phFile;
3553 *phFile = hOldFile;
3554 OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
3555 hOldFile, pFile->h));
3556 return SQLITE_OK;
3558 #endif
3559 case SQLITE_FCNTL_TEMPFILENAME: {
3560 char *zTFile = 0;
3561 int rc = winGetTempname(pFile->pVfs, &zTFile);
3562 if( rc==SQLITE_OK ){
3563 *(char**)pArg = zTFile;
3565 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
3566 return rc;
3568 #if SQLITE_MAX_MMAP_SIZE>0
3569 case SQLITE_FCNTL_MMAP_SIZE: {
3570 i64 newLimit = *(i64*)pArg;
3571 int rc = SQLITE_OK;
3572 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3573 newLimit = sqlite3GlobalConfig.mxMmap;
3576 /* The value of newLimit may be eventually cast to (SIZE_T) and passed
3577 ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
3578 ** least a 64-bit type. */
3579 if( newLimit>0 && sizeof(SIZE_T)<8 ){
3580 newLimit = (newLimit & 0x7FFFFFFF);
3583 *(i64*)pArg = pFile->mmapSizeMax;
3584 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
3585 pFile->mmapSizeMax = newLimit;
3586 if( pFile->mmapSize>0 ){
3587 winUnmapfile(pFile);
3588 rc = winMapfile(pFile, -1);
3591 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
3592 return rc;
3594 #endif
3596 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
3597 return SQLITE_NOTFOUND;
3601 ** Return the sector size in bytes of the underlying block device for
3602 ** the specified file. This is almost always 512 bytes, but may be
3603 ** larger for some devices.
3605 ** SQLite code assumes this function cannot fail. It also assumes that
3606 ** if two files are created in the same file-system directory (i.e.
3607 ** a database and its journal file) that the sector size will be the
3608 ** same for both.
3610 static int winSectorSize(sqlite3_file *id){
3611 (void)id;
3612 return SQLITE_DEFAULT_SECTOR_SIZE;
3616 ** Return a vector of device characteristics.
3618 static int winDeviceCharacteristics(sqlite3_file *id){
3619 winFile *p = (winFile*)id;
3620 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
3621 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
3625 ** Windows will only let you create file view mappings
3626 ** on allocation size granularity boundaries.
3627 ** During sqlite3_os_init() we do a GetSystemInfo()
3628 ** to get the granularity size.
3630 static SYSTEM_INFO winSysInfo;
3632 #ifndef SQLITE_OMIT_WAL
3635 ** Helper functions to obtain and relinquish the global mutex. The
3636 ** global mutex is used to protect the winLockInfo objects used by
3637 ** this file, all of which may be shared by multiple threads.
3639 ** Function winShmMutexHeld() is used to assert() that the global mutex
3640 ** is held when required. This function is only used as part of assert()
3641 ** statements. e.g.
3643 ** winShmEnterMutex()
3644 ** assert( winShmMutexHeld() );
3645 ** winShmLeaveMutex()
3647 static void winShmEnterMutex(void){
3648 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
3650 static void winShmLeaveMutex(void){
3651 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
3653 #ifndef NDEBUG
3654 static int winShmMutexHeld(void) {
3655 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
3657 #endif
3660 ** Object used to represent a single file opened and mmapped to provide
3661 ** shared memory. When multiple threads all reference the same
3662 ** log-summary, each thread has its own winFile object, but they all
3663 ** point to a single instance of this object. In other words, each
3664 ** log-summary is opened only once per process.
3666 ** winShmMutexHeld() must be true when creating or destroying
3667 ** this object or while reading or writing the following fields:
3669 ** nRef
3670 ** pNext
3672 ** The following fields are read-only after the object is created:
3674 ** fid
3675 ** zFilename
3677 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
3678 ** winShmMutexHeld() is true when reading or writing any other field
3679 ** in this structure.
3682 struct winShmNode {
3683 sqlite3_mutex *mutex; /* Mutex to access this object */
3684 char *zFilename; /* Name of the file */
3685 winFile hFile; /* File handle from winOpen */
3687 int szRegion; /* Size of shared-memory regions */
3688 int nRegion; /* Size of array apRegion */
3689 u8 isReadonly; /* True if read-only */
3690 u8 isUnlocked; /* True if no DMS lock held */
3692 struct ShmRegion {
3693 HANDLE hMap; /* File handle from CreateFileMapping */
3694 void *pMap;
3695 } *aRegion;
3696 DWORD lastErrno; /* The Windows errno from the last I/O error */
3698 int nRef; /* Number of winShm objects pointing to this */
3699 winShm *pFirst; /* All winShm objects pointing to this */
3700 winShmNode *pNext; /* Next in list of all winShmNode objects */
3701 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
3702 u8 nextShmId; /* Next available winShm.id value */
3703 #endif
3707 ** A global array of all winShmNode objects.
3709 ** The winShmMutexHeld() must be true while reading or writing this list.
3711 static winShmNode *winShmNodeList = 0;
3714 ** Structure used internally by this VFS to record the state of an
3715 ** open shared memory connection.
3717 ** The following fields are initialized when this object is created and
3718 ** are read-only thereafter:
3720 ** winShm.pShmNode
3721 ** winShm.id
3723 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
3724 ** while accessing any read/write fields.
3726 struct winShm {
3727 winShmNode *pShmNode; /* The underlying winShmNode object */
3728 winShm *pNext; /* Next winShm with the same winShmNode */
3729 u8 hasMutex; /* True if holding the winShmNode mutex */
3730 u16 sharedMask; /* Mask of shared locks held */
3731 u16 exclMask; /* Mask of exclusive locks held */
3732 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
3733 u8 id; /* Id of this connection with its winShmNode */
3734 #endif
3738 ** Constants used for locking
3740 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
3741 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
3744 ** Apply advisory locks for all n bytes beginning at ofst.
3746 #define WINSHM_UNLCK 1
3747 #define WINSHM_RDLCK 2
3748 #define WINSHM_WRLCK 3
3749 static int winShmSystemLock(
3750 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
3751 int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
3752 int ofst, /* Offset to first byte to be locked/unlocked */
3753 int nByte /* Number of bytes to lock or unlock */
3755 int rc = 0; /* Result code form Lock/UnlockFileEx() */
3757 /* Access to the winShmNode object is serialized by the caller */
3758 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
3760 OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
3761 pFile->hFile.h, lockType, ofst, nByte));
3763 /* Release/Acquire the system-level lock */
3764 if( lockType==WINSHM_UNLCK ){
3765 rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
3766 }else{
3767 /* Initialize the locking parameters */
3768 DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
3769 if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
3770 rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
3773 if( rc!= 0 ){
3774 rc = SQLITE_OK;
3775 }else{
3776 pFile->lastErrno = osGetLastError();
3777 rc = SQLITE_BUSY;
3780 OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
3781 pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
3782 "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
3784 return rc;
3787 /* Forward references to VFS methods */
3788 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
3789 static int winDelete(sqlite3_vfs *,const char*,int);
3792 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
3794 ** This is not a VFS shared-memory method; it is a utility function called
3795 ** by VFS shared-memory methods.
3797 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
3798 winShmNode **pp;
3799 winShmNode *p;
3800 assert( winShmMutexHeld() );
3801 OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
3802 osGetCurrentProcessId(), deleteFlag));
3803 pp = &winShmNodeList;
3804 while( (p = *pp)!=0 ){
3805 if( p->nRef==0 ){
3806 int i;
3807 if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
3808 for(i=0; i<p->nRegion; i++){
3809 BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
3810 OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
3811 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
3812 UNUSED_VARIABLE_VALUE(bRc);
3813 bRc = osCloseHandle(p->aRegion[i].hMap);
3814 OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
3815 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
3816 UNUSED_VARIABLE_VALUE(bRc);
3818 if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
3819 SimulateIOErrorBenign(1);
3820 winClose((sqlite3_file *)&p->hFile);
3821 SimulateIOErrorBenign(0);
3823 if( deleteFlag ){
3824 SimulateIOErrorBenign(1);
3825 sqlite3BeginBenignMalloc();
3826 winDelete(pVfs, p->zFilename, 0);
3827 sqlite3EndBenignMalloc();
3828 SimulateIOErrorBenign(0);
3830 *pp = p->pNext;
3831 sqlite3_free(p->aRegion);
3832 sqlite3_free(p);
3833 }else{
3834 pp = &p->pNext;
3840 ** Query the status of the DMS lock for the specified file. Returns
3841 ** SQLITE_OK upon success. Upon success, the integer pointed to by
3842 ** the pLockType argument will be set to the lock type held by the
3843 ** other process, as follows:
3845 ** WINSHM_UNLCK -- No locks are held on the DMS.
3846 ** WINSHM_RDLCK -- A SHARED lock is held on the DMS.
3847 ** WINSHM_WRLCK -- An EXCLUSIVE lock is held on the DMS.
3849 static int winGetShmDmsLockType(
3850 winFile *pFile, /* File handle object */
3851 int bReadOnly, /* Non-zero if the SHM was opened read-only */
3852 int *pLockType /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
3854 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
3855 OVERLAPPED overlapped; /* The offset for ReadFile/WriteFile. */
3856 #endif
3857 LPVOID pOverlapped = 0;
3858 sqlite3_int64 offset = WIN_SHM_DMS;
3859 BYTE notUsed1 = 0;
3860 DWORD notUsed2 = 0;
3862 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
3863 if( winSeekFile(pFile, offset) ){
3864 return SQLITE_IOERR_SEEK;
3866 #else
3867 memset(&overlapped, 0, sizeof(OVERLAPPED));
3868 overlapped.Offset = (LONG)(offset & 0xffffffff);
3869 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
3870 pOverlapped = &overlapped;
3871 #endif
3872 if( bReadOnly ||
3873 !osWriteFile(pFile->h, &notUsed1, 1, &notUsed2, pOverlapped) ){
3874 DWORD lastErrno = bReadOnly ? NO_ERROR : osGetLastError();
3875 if( !osReadFile(pFile->h, &notUsed1, 1, &notUsed2, pOverlapped) ){
3876 lastErrno = osGetLastError();
3877 if( winIsLockingError(lastErrno) ){
3878 if( pLockType ) *pLockType = WINSHM_WRLCK;
3879 }else{
3880 return SQLITE_IOERR_READ;
3882 }else{
3883 if( winIsLockingError(lastErrno) ){
3884 if( pLockType ) *pLockType = WINSHM_RDLCK;
3885 }else{
3886 return SQLITE_IOERR_WRITE;
3889 }else{
3890 if( pLockType ) *pLockType = WINSHM_UNLCK;
3892 return SQLITE_OK;
3896 ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
3897 ** take it now. Return SQLITE_OK if successful, or an SQLite error
3898 ** code otherwise.
3900 ** If the DMS cannot be locked because this is a readonly_shm=1
3901 ** connection and no other process already holds a lock, return
3902 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
3904 static int winLockSharedMemory(winShmNode *pShmNode){
3905 int lockType;
3906 int rc = SQLITE_OK;
3908 /* Use ReadFile/WriteFile to determine the locks other processes are
3909 ** holding on the DMS byte. If it indicates that another process is
3910 ** holding a SHARED lock, then this process may also take a SHARED
3911 ** lock and proceed with opening the *-shm file.
3913 ** Or, if no other process is holding any lock, then this process
3914 ** is the first to open it. In this case take an EXCLUSIVE lock on the
3915 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
3916 ** downgrade to a SHARED lock on the DMS byte.
3918 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
3919 ** return SQLITE_BUSY to the caller (it will try again). An earlier
3920 ** version of this code attempted the SHARED lock at this point. But
3921 ** this introduced a subtle race condition: if the process holding
3922 ** EXCLUSIVE failed just before truncating the *-shm file, then this
3923 ** process might open and use the *-shm file without truncating it.
3924 ** And if the *-shm file has been corrupted by a power failure or
3925 ** system crash, the database itself may also become corrupt. */
3926 if( winGetShmDmsLockType(&pShmNode->hFile, pShmNode->isReadonly,
3927 &lockType)!=SQLITE_OK ){
3928 rc = SQLITE_IOERR_LOCK;
3929 }else if( lockType==WINSHM_UNLCK ){
3930 if( pShmNode->isReadonly ){
3931 pShmNode->isUnlocked = 1;
3932 rc = SQLITE_READONLY_CANTINIT;
3933 }else{
3934 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
3935 rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
3936 if( rc==SQLITE_OK && winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
3937 rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
3938 "winLockSharedMemory", pShmNode->zFilename);
3941 }else if( lockType==WINSHM_WRLCK ){
3942 rc = SQLITE_BUSY;
3945 if( rc==SQLITE_OK ){
3946 assert( lockType==WINSHM_UNLCK || lockType==WINSHM_RDLCK );
3947 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
3948 rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
3951 return rc;
3955 ** Open the shared-memory area associated with database file pDbFd.
3957 ** When opening a new shared-memory file, if no other instances of that
3958 ** file are currently open, in this process or in other processes, then
3959 ** the file must be truncated to zero length or have its header cleared.
3961 static int winOpenSharedMemory(winFile *pDbFd){
3962 struct winShm *p; /* The connection to be opened */
3963 winShmNode *pShmNode = 0; /* The underlying mmapped file */
3964 int rc = SQLITE_OK; /* Result code */
3965 int rc2 = SQLITE_ERROR; /* winOpen result code */
3966 winShmNode *pNew; /* Newly allocated winShmNode */
3967 int nName; /* Size of zName in bytes */
3969 assert( pDbFd->pShm==0 ); /* Not previously opened */
3971 /* Allocate space for the new sqlite3_shm object. Also speculatively
3972 ** allocate space for a new winShmNode and filename.
3974 p = sqlite3MallocZero( sizeof(*p) );
3975 if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
3976 nName = sqlite3Strlen30(pDbFd->zPath);
3977 pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
3978 if( pNew==0 ){
3979 sqlite3_free(p);
3980 return SQLITE_IOERR_NOMEM_BKPT;
3982 pNew->zFilename = (char*)&pNew[1];
3983 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
3984 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
3986 /* Look to see if there is an existing winShmNode that can be used.
3987 ** If no matching winShmNode currently exists, create a new one.
3989 winShmEnterMutex();
3990 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
3991 /* TBD need to come up with better match here. Perhaps
3992 ** use FILE_ID_BOTH_DIR_INFO Structure.
3994 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
3996 if( pShmNode ){
3997 sqlite3_free(pNew);
3998 }else{
3999 pShmNode = pNew;
4000 pNew = 0;
4001 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
4002 pShmNode->pNext = winShmNodeList;
4003 winShmNodeList = pShmNode;
4005 if( sqlite3GlobalConfig.bCoreMutex ){
4006 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4007 if( pShmNode->mutex==0 ){
4008 rc = SQLITE_IOERR_NOMEM_BKPT;
4009 goto shm_open_err;
4013 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
4014 rc2 = winOpen(pDbFd->pVfs,
4015 pShmNode->zFilename,
4016 (sqlite3_file*)&pShmNode->hFile,
4017 SQLITE_OPEN_WAL|SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE,
4020 if( rc2!=SQLITE_OK ){
4021 rc2 = winOpen(pDbFd->pVfs,
4022 pShmNode->zFilename,
4023 (sqlite3_file*)&pShmNode->hFile,
4024 SQLITE_OPEN_WAL|SQLITE_OPEN_READONLY,
4026 if( rc2!=SQLITE_OK ){
4027 rc = winLogError(SQLITE_CANTOPEN_BKPT, osGetLastError(),
4028 "winOpenShm", pShmNode->zFilename);
4029 goto shm_open_err;
4031 pShmNode->isReadonly = 1;
4034 rc = winLockSharedMemory(pShmNode);
4035 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
4038 /* Make the new connection a child of the winShmNode */
4039 p->pShmNode = pShmNode;
4040 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
4041 p->id = pShmNode->nextShmId++;
4042 #endif
4043 pShmNode->nRef++;
4044 pDbFd->pShm = p;
4045 winShmLeaveMutex();
4047 /* The reference count on pShmNode has already been incremented under
4048 ** the cover of the winShmEnterMutex() mutex and the pointer from the
4049 ** new (struct winShm) object to the pShmNode has been set. All that is
4050 ** left to do is to link the new object into the linked list starting
4051 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4052 ** mutex.
4054 sqlite3_mutex_enter(pShmNode->mutex);
4055 p->pNext = pShmNode->pFirst;
4056 pShmNode->pFirst = p;
4057 sqlite3_mutex_leave(pShmNode->mutex);
4058 return rc;
4060 /* Jump here on any error */
4061 shm_open_err:
4062 winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
4063 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
4064 sqlite3_free(p);
4065 sqlite3_free(pNew);
4066 winShmLeaveMutex();
4067 return rc;
4071 ** Close a connection to shared-memory. Delete the underlying
4072 ** storage if deleteFlag is true.
4074 static int winShmUnmap(
4075 sqlite3_file *fd, /* Database holding shared memory */
4076 int deleteFlag /* Delete after closing if true */
4078 winFile *pDbFd; /* Database holding shared-memory */
4079 winShm *p; /* The connection to be closed */
4080 winShmNode *pShmNode; /* The underlying shared-memory file */
4081 winShm **pp; /* For looping over sibling connections */
4083 pDbFd = (winFile*)fd;
4084 p = pDbFd->pShm;
4085 if( p==0 ) return SQLITE_OK;
4086 pShmNode = p->pShmNode;
4088 /* Remove connection p from the set of connections associated
4089 ** with pShmNode */
4090 sqlite3_mutex_enter(pShmNode->mutex);
4091 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4092 *pp = p->pNext;
4094 /* Free the connection p */
4095 sqlite3_free(p);
4096 pDbFd->pShm = 0;
4097 sqlite3_mutex_leave(pShmNode->mutex);
4099 /* If pShmNode->nRef has reached 0, then close the underlying
4100 ** shared-memory file, too */
4101 winShmEnterMutex();
4102 assert( pShmNode->nRef>0 );
4103 pShmNode->nRef--;
4104 if( pShmNode->nRef==0 ){
4105 winShmPurge(pDbFd->pVfs, deleteFlag);
4107 winShmLeaveMutex();
4109 return SQLITE_OK;
4113 ** Change the lock state for a shared-memory segment.
4115 static int winShmLock(
4116 sqlite3_file *fd, /* Database file holding the shared memory */
4117 int ofst, /* First lock to acquire or release */
4118 int n, /* Number of locks to acquire or release */
4119 int flags /* What to do with the lock */
4121 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
4122 winShm *p = pDbFd->pShm; /* The shared memory being locked */
4123 winShm *pX; /* For looping over all siblings */
4124 winShmNode *pShmNode = p->pShmNode;
4125 int rc = SQLITE_OK; /* Result code */
4126 u16 mask; /* Mask of locks to take or release */
4128 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
4129 assert( n>=1 );
4130 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4131 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4132 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4133 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4134 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
4136 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
4137 assert( n>1 || mask==(1<<ofst) );
4138 sqlite3_mutex_enter(pShmNode->mutex);
4139 if( flags & SQLITE_SHM_UNLOCK ){
4140 u16 allMask = 0; /* Mask of locks held by siblings */
4142 /* See if any siblings hold this same lock */
4143 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4144 if( pX==p ) continue;
4145 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4146 allMask |= pX->sharedMask;
4149 /* Unlock the system-level locks */
4150 if( (mask & allMask)==0 ){
4151 rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
4152 }else{
4153 rc = SQLITE_OK;
4156 /* Undo the local locks */
4157 if( rc==SQLITE_OK ){
4158 p->exclMask &= ~mask;
4159 p->sharedMask &= ~mask;
4161 }else if( flags & SQLITE_SHM_SHARED ){
4162 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4164 /* Find out which shared locks are already held by sibling connections.
4165 ** If any sibling already holds an exclusive lock, go ahead and return
4166 ** SQLITE_BUSY.
4168 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4169 if( (pX->exclMask & mask)!=0 ){
4170 rc = SQLITE_BUSY;
4171 break;
4173 allShared |= pX->sharedMask;
4176 /* Get shared locks at the system level, if necessary */
4177 if( rc==SQLITE_OK ){
4178 if( (allShared & mask)==0 ){
4179 rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
4180 }else{
4181 rc = SQLITE_OK;
4185 /* Get the local shared locks */
4186 if( rc==SQLITE_OK ){
4187 p->sharedMask |= mask;
4189 }else{
4190 /* Make sure no sibling connections hold locks that will block this
4191 ** lock. If any do, return SQLITE_BUSY right away.
4193 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4194 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4195 rc = SQLITE_BUSY;
4196 break;
4200 /* Get the exclusive locks at the system level. Then if successful
4201 ** also mark the local connection as being locked.
4203 if( rc==SQLITE_OK ){
4204 rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
4205 if( rc==SQLITE_OK ){
4206 assert( (p->sharedMask & mask)==0 );
4207 p->exclMask |= mask;
4211 sqlite3_mutex_leave(pShmNode->mutex);
4212 OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
4213 osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
4214 sqlite3ErrName(rc)));
4215 return rc;
4219 ** Implement a memory barrier or memory fence on shared memory.
4221 ** All loads and stores begun before the barrier must complete before
4222 ** any load or store begun after the barrier.
4224 static void winShmBarrier(
4225 sqlite3_file *fd /* Database holding the shared memory */
4227 UNUSED_PARAMETER(fd);
4228 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4229 winShmEnterMutex(); /* Also mutex, for redundancy */
4230 winShmLeaveMutex();
4234 ** This function is called to obtain a pointer to region iRegion of the
4235 ** shared-memory associated with the database file fd. Shared-memory regions
4236 ** are numbered starting from zero. Each shared-memory region is szRegion
4237 ** bytes in size.
4239 ** If an error occurs, an error code is returned and *pp is set to NULL.
4241 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
4242 ** region has not been allocated (by any client, including one running in a
4243 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4244 ** isWrite is non-zero and the requested shared-memory region has not yet
4245 ** been allocated, it is allocated by this function.
4247 ** If the shared-memory region has already been allocated or is allocated by
4248 ** this call as described above, then it is mapped into this processes
4249 ** address space (if it is not already), *pp is set to point to the mapped
4250 ** memory and SQLITE_OK returned.
4252 static int winShmMap(
4253 sqlite3_file *fd, /* Handle open on database file */
4254 int iRegion, /* Region to retrieve */
4255 int szRegion, /* Size of regions */
4256 int isWrite, /* True to extend file if necessary */
4257 void volatile **pp /* OUT: Mapped memory */
4259 winFile *pDbFd = (winFile*)fd;
4260 winShm *pShm = pDbFd->pShm;
4261 winShmNode *pShmNode;
4262 DWORD protect = PAGE_READWRITE;
4263 DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
4264 int rc = SQLITE_OK;
4266 if( !pShm ){
4267 rc = winOpenSharedMemory(pDbFd);
4268 if( rc!=SQLITE_OK ) return rc;
4269 pShm = pDbFd->pShm;
4271 pShmNode = pShm->pShmNode;
4273 sqlite3_mutex_enter(pShmNode->mutex);
4274 if( pShmNode->isUnlocked ){
4275 rc = winLockSharedMemory(pShmNode);
4276 if( rc!=SQLITE_OK ) goto shmpage_out;
4277 pShmNode->isUnlocked = 0;
4279 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
4281 if( pShmNode->nRegion<=iRegion ){
4282 struct ShmRegion *apNew; /* New aRegion[] array */
4283 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4284 sqlite3_int64 sz; /* Current size of wal-index file */
4286 pShmNode->szRegion = szRegion;
4288 /* The requested region is not mapped into this processes address space.
4289 ** Check to see if it has been allocated (i.e. if the wal-index file is
4290 ** large enough to contain the requested region).
4292 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
4293 if( rc!=SQLITE_OK ){
4294 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
4295 "winShmMap1", pDbFd->zPath);
4296 goto shmpage_out;
4299 if( sz<nByte ){
4300 /* The requested memory region does not exist. If isWrite is set to
4301 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
4303 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
4304 ** the requested memory region.
4306 if( !isWrite ) goto shmpage_out;
4307 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
4308 if( rc!=SQLITE_OK ){
4309 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
4310 "winShmMap2", pDbFd->zPath);
4311 goto shmpage_out;
4315 /* Map the requested memory region into this processes address space. */
4316 apNew = (struct ShmRegion *)sqlite3_realloc64(
4317 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
4319 if( !apNew ){
4320 rc = SQLITE_IOERR_NOMEM_BKPT;
4321 goto shmpage_out;
4323 pShmNode->aRegion = apNew;
4325 if( pShmNode->isReadonly ){
4326 protect = PAGE_READONLY;
4327 flags = FILE_MAP_READ;
4330 while( pShmNode->nRegion<=iRegion ){
4331 HANDLE hMap = NULL; /* file-mapping handle */
4332 void *pMap = 0; /* Mapped memory region */
4334 #if SQLITE_OS_WINRT
4335 hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
4336 NULL, protect, nByte, NULL
4338 #elif defined(SQLITE_WIN32_HAS_WIDE)
4339 hMap = osCreateFileMappingW(pShmNode->hFile.h,
4340 NULL, protect, 0, nByte, NULL
4342 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
4343 hMap = osCreateFileMappingA(pShmNode->hFile.h,
4344 NULL, protect, 0, nByte, NULL
4346 #endif
4347 OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
4348 osGetCurrentProcessId(), pShmNode->nRegion, nByte,
4349 hMap ? "ok" : "failed"));
4350 if( hMap ){
4351 int iOffset = pShmNode->nRegion*szRegion;
4352 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
4353 #if SQLITE_OS_WINRT
4354 pMap = osMapViewOfFileFromApp(hMap, flags,
4355 iOffset - iOffsetShift, szRegion + iOffsetShift
4357 #else
4358 pMap = osMapViewOfFile(hMap, flags,
4359 0, iOffset - iOffsetShift, szRegion + iOffsetShift
4361 #endif
4362 OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
4363 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
4364 szRegion, pMap ? "ok" : "failed"));
4366 if( !pMap ){
4367 pShmNode->lastErrno = osGetLastError();
4368 rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
4369 "winShmMap3", pDbFd->zPath);
4370 if( hMap ) osCloseHandle(hMap);
4371 goto shmpage_out;
4374 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
4375 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
4376 pShmNode->nRegion++;
4380 shmpage_out:
4381 if( pShmNode->nRegion>iRegion ){
4382 int iOffset = iRegion*szRegion;
4383 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
4384 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
4385 *pp = (void *)&p[iOffsetShift];
4386 }else{
4387 *pp = 0;
4389 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
4390 sqlite3_mutex_leave(pShmNode->mutex);
4391 return rc;
4394 #else
4395 # define winShmMap 0
4396 # define winShmLock 0
4397 # define winShmBarrier 0
4398 # define winShmUnmap 0
4399 #endif /* #ifndef SQLITE_OMIT_WAL */
4402 ** Cleans up the mapped region of the specified file, if any.
4404 #if SQLITE_MAX_MMAP_SIZE>0
4405 static int winUnmapfile(winFile *pFile){
4406 assert( pFile!=0 );
4407 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
4408 "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
4409 osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
4410 pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
4411 if( pFile->pMapRegion ){
4412 if( !osUnmapViewOfFile(pFile->pMapRegion) ){
4413 pFile->lastErrno = osGetLastError();
4414 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
4415 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
4416 pFile->pMapRegion));
4417 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
4418 "winUnmapfile1", pFile->zPath);
4420 pFile->pMapRegion = 0;
4421 pFile->mmapSize = 0;
4422 pFile->mmapSizeActual = 0;
4424 if( pFile->hMap!=NULL ){
4425 if( !osCloseHandle(pFile->hMap) ){
4426 pFile->lastErrno = osGetLastError();
4427 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
4428 osGetCurrentProcessId(), pFile, pFile->hMap));
4429 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
4430 "winUnmapfile2", pFile->zPath);
4432 pFile->hMap = NULL;
4434 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
4435 osGetCurrentProcessId(), pFile));
4436 return SQLITE_OK;
4440 ** Memory map or remap the file opened by file-descriptor pFd (if the file
4441 ** is already mapped, the existing mapping is replaced by the new). Or, if
4442 ** there already exists a mapping for this file, and there are still
4443 ** outstanding xFetch() references to it, this function is a no-op.
4445 ** If parameter nByte is non-negative, then it is the requested size of
4446 ** the mapping to create. Otherwise, if nByte is less than zero, then the
4447 ** requested size is the size of the file on disk. The actual size of the
4448 ** created mapping is either the requested size or the value configured
4449 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
4451 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
4452 ** recreated as a result of outstanding references) or an SQLite error
4453 ** code otherwise.
4455 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
4456 sqlite3_int64 nMap = nByte;
4457 int rc;
4459 assert( nMap>=0 || pFd->nFetchOut==0 );
4460 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
4461 osGetCurrentProcessId(), pFd, nByte));
4463 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4465 if( nMap<0 ){
4466 rc = winFileSize((sqlite3_file*)pFd, &nMap);
4467 if( rc ){
4468 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
4469 osGetCurrentProcessId(), pFd));
4470 return SQLITE_IOERR_FSTAT;
4473 if( nMap>pFd->mmapSizeMax ){
4474 nMap = pFd->mmapSizeMax;
4476 nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
4478 if( nMap==0 && pFd->mmapSize>0 ){
4479 winUnmapfile(pFd);
4481 if( nMap!=pFd->mmapSize ){
4482 void *pNew = 0;
4483 DWORD protect = PAGE_READONLY;
4484 DWORD flags = FILE_MAP_READ;
4486 winUnmapfile(pFd);
4487 #ifdef SQLITE_MMAP_READWRITE
4488 if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
4489 protect = PAGE_READWRITE;
4490 flags |= FILE_MAP_WRITE;
4492 #endif
4493 #if SQLITE_OS_WINRT
4494 pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
4495 #elif defined(SQLITE_WIN32_HAS_WIDE)
4496 pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
4497 (DWORD)((nMap>>32) & 0xffffffff),
4498 (DWORD)(nMap & 0xffffffff), NULL);
4499 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
4500 pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
4501 (DWORD)((nMap>>32) & 0xffffffff),
4502 (DWORD)(nMap & 0xffffffff), NULL);
4503 #endif
4504 if( pFd->hMap==NULL ){
4505 pFd->lastErrno = osGetLastError();
4506 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
4507 "winMapfile1", pFd->zPath);
4508 /* Log the error, but continue normal operation using xRead/xWrite */
4509 OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
4510 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
4511 return SQLITE_OK;
4513 assert( (nMap % winSysInfo.dwPageSize)==0 );
4514 assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
4515 #if SQLITE_OS_WINRT
4516 pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
4517 #else
4518 pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
4519 #endif
4520 if( pNew==NULL ){
4521 osCloseHandle(pFd->hMap);
4522 pFd->hMap = NULL;
4523 pFd->lastErrno = osGetLastError();
4524 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
4525 "winMapfile2", pFd->zPath);
4526 /* Log the error, but continue normal operation using xRead/xWrite */
4527 OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
4528 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
4529 return SQLITE_OK;
4531 pFd->pMapRegion = pNew;
4532 pFd->mmapSize = nMap;
4533 pFd->mmapSizeActual = nMap;
4536 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
4537 osGetCurrentProcessId(), pFd));
4538 return SQLITE_OK;
4540 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
4543 ** If possible, return a pointer to a mapping of file fd starting at offset
4544 ** iOff. The mapping must be valid for at least nAmt bytes.
4546 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4547 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4548 ** Finally, if an error does occur, return an SQLite error code. The final
4549 ** value of *pp is undefined in this case.
4551 ** If this function does return a pointer, the caller must eventually
4552 ** release the reference by calling winUnfetch().
4554 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
4555 #if SQLITE_MAX_MMAP_SIZE>0
4556 winFile *pFd = (winFile*)fd; /* The underlying database file */
4557 #endif
4558 *pp = 0;
4560 OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
4561 osGetCurrentProcessId(), fd, iOff, nAmt, pp));
4563 #if SQLITE_MAX_MMAP_SIZE>0
4564 if( pFd->mmapSizeMax>0 ){
4565 if( pFd->pMapRegion==0 ){
4566 int rc = winMapfile(pFd, -1);
4567 if( rc!=SQLITE_OK ){
4568 OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
4569 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
4570 return rc;
4573 if( pFd->mmapSize >= iOff+nAmt ){
4574 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4575 pFd->nFetchOut++;
4578 #endif
4580 OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
4581 osGetCurrentProcessId(), fd, pp, *pp));
4582 return SQLITE_OK;
4586 ** If the third argument is non-NULL, then this function releases a
4587 ** reference obtained by an earlier call to winFetch(). The second
4588 ** argument passed to this function must be the same as the corresponding
4589 ** argument that was passed to the winFetch() invocation.
4591 ** Or, if the third argument is NULL, then this function is being called
4592 ** to inform the VFS layer that, according to POSIX, any existing mapping
4593 ** may now be invalid and should be unmapped.
4595 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
4596 #if SQLITE_MAX_MMAP_SIZE>0
4597 winFile *pFd = (winFile*)fd; /* The underlying database file */
4599 /* If p==0 (unmap the entire file) then there must be no outstanding
4600 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4601 ** then there must be at least one outstanding. */
4602 assert( (p==0)==(pFd->nFetchOut==0) );
4604 /* If p!=0, it must match the iOff value. */
4605 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4607 OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
4608 osGetCurrentProcessId(), pFd, iOff, p));
4610 if( p ){
4611 pFd->nFetchOut--;
4612 }else{
4613 /* FIXME: If Windows truly always prevents truncating or deleting a
4614 ** file while a mapping is held, then the following winUnmapfile() call
4615 ** is unnecessary can be omitted - potentially improving
4616 ** performance. */
4617 winUnmapfile(pFd);
4620 assert( pFd->nFetchOut>=0 );
4621 #endif
4623 OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
4624 osGetCurrentProcessId(), fd));
4625 return SQLITE_OK;
4629 ** Here ends the implementation of all sqlite3_file methods.
4631 ********************** End sqlite3_file Methods *******************************
4632 ******************************************************************************/
4635 ** This vector defines all the methods that can operate on an
4636 ** sqlite3_file for win32.
4638 static const sqlite3_io_methods winIoMethod = {
4639 3, /* iVersion */
4640 winClose, /* xClose */
4641 winRead, /* xRead */
4642 winWrite, /* xWrite */
4643 winTruncate, /* xTruncate */
4644 winSync, /* xSync */
4645 winFileSize, /* xFileSize */
4646 winLock, /* xLock */
4647 winUnlock, /* xUnlock */
4648 winCheckReservedLock, /* xCheckReservedLock */
4649 winFileControl, /* xFileControl */
4650 winSectorSize, /* xSectorSize */
4651 winDeviceCharacteristics, /* xDeviceCharacteristics */
4652 winShmMap, /* xShmMap */
4653 winShmLock, /* xShmLock */
4654 winShmBarrier, /* xShmBarrier */
4655 winShmUnmap, /* xShmUnmap */
4656 winFetch, /* xFetch */
4657 winUnfetch /* xUnfetch */
4661 ** This vector defines all the methods that can operate on an
4662 ** sqlite3_file for win32 without performing any locking.
4664 static const sqlite3_io_methods winIoNolockMethod = {
4665 3, /* iVersion */
4666 winClose, /* xClose */
4667 winRead, /* xRead */
4668 winWrite, /* xWrite */
4669 winTruncate, /* xTruncate */
4670 winSync, /* xSync */
4671 winFileSize, /* xFileSize */
4672 winNolockLock, /* xLock */
4673 winNolockUnlock, /* xUnlock */
4674 winNolockCheckReservedLock, /* xCheckReservedLock */
4675 winFileControl, /* xFileControl */
4676 winSectorSize, /* xSectorSize */
4677 winDeviceCharacteristics, /* xDeviceCharacteristics */
4678 winShmMap, /* xShmMap */
4679 winShmLock, /* xShmLock */
4680 winShmBarrier, /* xShmBarrier */
4681 winShmUnmap, /* xShmUnmap */
4682 winFetch, /* xFetch */
4683 winUnfetch /* xUnfetch */
4686 static winVfsAppData winAppData = {
4687 &winIoMethod, /* pMethod */
4688 0, /* pAppData */
4689 0 /* bNoLock */
4692 static winVfsAppData winNolockAppData = {
4693 &winIoNolockMethod, /* pMethod */
4694 0, /* pAppData */
4695 1 /* bNoLock */
4698 /****************************************************************************
4699 **************************** sqlite3_vfs methods ****************************
4701 ** This division contains the implementation of methods on the
4702 ** sqlite3_vfs object.
4705 #if defined(__CYGWIN__)
4707 ** Convert a filename from whatever the underlying operating system
4708 ** supports for filenames into UTF-8. Space to hold the result is
4709 ** obtained from malloc and must be freed by the calling function.
4711 static char *winConvertToUtf8Filename(const void *zFilename){
4712 char *zConverted = 0;
4713 if( osIsNT() ){
4714 zConverted = winUnicodeToUtf8(zFilename);
4716 #ifdef SQLITE_WIN32_HAS_ANSI
4717 else{
4718 zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
4720 #endif
4721 /* caller will handle out of memory */
4722 return zConverted;
4724 #endif
4727 ** Convert a UTF-8 filename into whatever form the underlying
4728 ** operating system wants filenames in. Space to hold the result
4729 ** is obtained from malloc and must be freed by the calling
4730 ** function.
4732 static void *winConvertFromUtf8Filename(const char *zFilename){
4733 void *zConverted = 0;
4734 if( osIsNT() ){
4735 zConverted = winUtf8ToUnicode(zFilename);
4737 #ifdef SQLITE_WIN32_HAS_ANSI
4738 else{
4739 zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
4741 #endif
4742 /* caller will handle out of memory */
4743 return zConverted;
4747 ** This function returns non-zero if the specified UTF-8 string buffer
4748 ** ends with a directory separator character or one was successfully
4749 ** added to it.
4751 static int winMakeEndInDirSep(int nBuf, char *zBuf){
4752 if( zBuf ){
4753 int nLen = sqlite3Strlen30(zBuf);
4754 if( nLen>0 ){
4755 if( winIsDirSep(zBuf[nLen-1]) ){
4756 return 1;
4757 }else if( nLen+1<nBuf ){
4758 zBuf[nLen] = winGetDirSep();
4759 zBuf[nLen+1] = '\0';
4760 return 1;
4764 return 0;
4768 ** Create a temporary file name and store the resulting pointer into pzBuf.
4769 ** The pointer returned in pzBuf must be freed via sqlite3_free().
4771 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
4772 static char zChars[] =
4773 "abcdefghijklmnopqrstuvwxyz"
4774 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4775 "0123456789";
4776 size_t i, j;
4777 int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
4778 int nMax, nBuf, nDir, nLen;
4779 char *zBuf;
4781 /* It's odd to simulate an io-error here, but really this is just
4782 ** using the io-error infrastructure to test that SQLite handles this
4783 ** function failing.
4785 SimulateIOError( return SQLITE_IOERR );
4787 /* Allocate a temporary buffer to store the fully qualified file
4788 ** name for the temporary file. If this fails, we cannot continue.
4790 nMax = pVfs->mxPathname; nBuf = nMax + 2;
4791 zBuf = sqlite3MallocZero( nBuf );
4792 if( !zBuf ){
4793 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4794 return SQLITE_IOERR_NOMEM_BKPT;
4797 /* Figure out the effective temporary directory. First, check if one
4798 ** has been explicitly set by the application; otherwise, use the one
4799 ** configured by the operating system.
4801 nDir = nMax - (nPre + 15);
4802 assert( nDir>0 );
4803 if( sqlite3_temp_directory ){
4804 int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
4805 if( nDirLen>0 ){
4806 if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
4807 nDirLen++;
4809 if( nDirLen>nDir ){
4810 sqlite3_free(zBuf);
4811 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
4812 return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
4814 sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
4817 #if defined(__CYGWIN__)
4818 else{
4819 static const char *azDirs[] = {
4820 0, /* getenv("SQLITE_TMPDIR") */
4821 0, /* getenv("TMPDIR") */
4822 0, /* getenv("TMP") */
4823 0, /* getenv("TEMP") */
4824 0, /* getenv("USERPROFILE") */
4825 "/var/tmp",
4826 "/usr/tmp",
4827 "/tmp",
4828 ".",
4829 0 /* List terminator */
4831 unsigned int i;
4832 const char *zDir = 0;
4834 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
4835 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
4836 if( !azDirs[2] ) azDirs[2] = getenv("TMP");
4837 if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
4838 if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
4839 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
4840 void *zConverted;
4841 if( zDir==0 ) continue;
4842 /* If the path starts with a drive letter followed by the colon
4843 ** character, assume it is already a native Win32 path; otherwise,
4844 ** it must be converted to a native Win32 path via the Cygwin API
4845 ** prior to using it.
4847 if( winIsDriveLetterAndColon(zDir) ){
4848 zConverted = winConvertFromUtf8Filename(zDir);
4849 if( !zConverted ){
4850 sqlite3_free(zBuf);
4851 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4852 return SQLITE_IOERR_NOMEM_BKPT;
4854 if( winIsDir(zConverted) ){
4855 sqlite3_snprintf(nMax, zBuf, "%s", zDir);
4856 sqlite3_free(zConverted);
4857 break;
4859 sqlite3_free(zConverted);
4860 }else{
4861 zConverted = sqlite3MallocZero( nMax+1 );
4862 if( !zConverted ){
4863 sqlite3_free(zBuf);
4864 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4865 return SQLITE_IOERR_NOMEM_BKPT;
4867 if( cygwin_conv_path(
4868 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
4869 zConverted, nMax+1)<0 ){
4870 sqlite3_free(zConverted);
4871 sqlite3_free(zBuf);
4872 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
4873 return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
4874 "winGetTempname2", zDir);
4876 if( winIsDir(zConverted) ){
4877 /* At this point, we know the candidate directory exists and should
4878 ** be used. However, we may need to convert the string containing
4879 ** its name into UTF-8 (i.e. if it is UTF-16 right now).
4881 char *zUtf8 = winConvertToUtf8Filename(zConverted);
4882 if( !zUtf8 ){
4883 sqlite3_free(zConverted);
4884 sqlite3_free(zBuf);
4885 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4886 return SQLITE_IOERR_NOMEM_BKPT;
4888 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
4889 sqlite3_free(zUtf8);
4890 sqlite3_free(zConverted);
4891 break;
4893 sqlite3_free(zConverted);
4897 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
4898 else if( osIsNT() ){
4899 char *zMulti;
4900 LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
4901 if( !zWidePath ){
4902 sqlite3_free(zBuf);
4903 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4904 return SQLITE_IOERR_NOMEM_BKPT;
4906 if( osGetTempPathW(nMax, zWidePath)==0 ){
4907 sqlite3_free(zWidePath);
4908 sqlite3_free(zBuf);
4909 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
4910 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
4911 "winGetTempname2", 0);
4913 zMulti = winUnicodeToUtf8(zWidePath);
4914 if( zMulti ){
4915 sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
4916 sqlite3_free(zMulti);
4917 sqlite3_free(zWidePath);
4918 }else{
4919 sqlite3_free(zWidePath);
4920 sqlite3_free(zBuf);
4921 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4922 return SQLITE_IOERR_NOMEM_BKPT;
4925 #ifdef SQLITE_WIN32_HAS_ANSI
4926 else{
4927 char *zUtf8;
4928 char *zMbcsPath = sqlite3MallocZero( nMax );
4929 if( !zMbcsPath ){
4930 sqlite3_free(zBuf);
4931 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4932 return SQLITE_IOERR_NOMEM_BKPT;
4934 if( osGetTempPathA(nMax, zMbcsPath)==0 ){
4935 sqlite3_free(zBuf);
4936 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
4937 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
4938 "winGetTempname3", 0);
4940 zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
4941 if( zUtf8 ){
4942 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
4943 sqlite3_free(zUtf8);
4944 }else{
4945 sqlite3_free(zBuf);
4946 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4947 return SQLITE_IOERR_NOMEM_BKPT;
4950 #endif /* SQLITE_WIN32_HAS_ANSI */
4951 #endif /* !SQLITE_OS_WINRT */
4954 ** Check to make sure the temporary directory ends with an appropriate
4955 ** separator. If it does not and there is not enough space left to add
4956 ** one, fail.
4958 if( !winMakeEndInDirSep(nDir+1, zBuf) ){
4959 sqlite3_free(zBuf);
4960 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
4961 return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
4965 ** Check that the output buffer is large enough for the temporary file
4966 ** name in the following format:
4968 ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
4970 ** If not, return SQLITE_ERROR. The number 17 is used here in order to
4971 ** account for the space used by the 15 character random suffix and the
4972 ** two trailing NUL characters. The final directory separator character
4973 ** has already added if it was not already present.
4975 nLen = sqlite3Strlen30(zBuf);
4976 if( (nLen + nPre + 17) > nBuf ){
4977 sqlite3_free(zBuf);
4978 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
4979 return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
4982 sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
4984 j = sqlite3Strlen30(zBuf);
4985 sqlite3_randomness(15, &zBuf[j]);
4986 for(i=0; i<15; i++, j++){
4987 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4989 zBuf[j] = 0;
4990 zBuf[j+1] = 0;
4991 *pzBuf = zBuf;
4993 OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
4994 return SQLITE_OK;
4998 ** Return TRUE if the named file is really a directory. Return false if
4999 ** it is something other than a directory, or if there is any kind of memory
5000 ** allocation failure.
5002 static int winIsDir(const void *zConverted){
5003 DWORD attr;
5004 int rc = 0;
5005 DWORD lastErrno;
5007 if( osIsNT() ){
5008 int cnt = 0;
5009 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
5010 memset(&sAttrData, 0, sizeof(sAttrData));
5011 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
5012 GetFileExInfoStandard,
5013 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
5014 if( !rc ){
5015 return 0; /* Invalid name? */
5017 attr = sAttrData.dwFileAttributes;
5018 #if SQLITE_OS_WINCE==0
5019 }else{
5020 attr = osGetFileAttributesA((char*)zConverted);
5021 #endif
5023 return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
5026 /* forward reference */
5027 static int winAccess(
5028 sqlite3_vfs *pVfs, /* Not used on win32 */
5029 const char *zFilename, /* Name of file to check */
5030 int flags, /* Type of test to make on this file */
5031 int *pResOut /* OUT: Result */
5035 ** Open a file.
5037 static int winOpen(
5038 sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
5039 const char *zName, /* Name of the file (UTF-8) */
5040 sqlite3_file *id, /* Write the SQLite file handle here */
5041 int flags, /* Open mode flags */
5042 int *pOutFlags /* Status return flags */
5044 HANDLE h;
5045 DWORD lastErrno = 0;
5046 DWORD dwDesiredAccess;
5047 DWORD dwShareMode;
5048 DWORD dwCreationDisposition;
5049 DWORD dwFlagsAndAttributes = 0;
5050 #if SQLITE_OS_WINCE
5051 int isTemp = 0;
5052 #endif
5053 winVfsAppData *pAppData;
5054 winFile *pFile = (winFile*)id;
5055 void *zConverted; /* Filename in OS encoding */
5056 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
5057 int cnt = 0;
5059 /* If argument zPath is a NULL pointer, this function is required to open
5060 ** a temporary file. Use this buffer to store the file name in.
5062 char *zTmpname = 0; /* For temporary filename, if necessary. */
5064 int rc = SQLITE_OK; /* Function Return Code */
5065 #if !defined(NDEBUG) || SQLITE_OS_WINCE
5066 int eType = flags&0xFFFFFF00; /* Type of file to open */
5067 #endif
5069 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5070 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5071 int isCreate = (flags & SQLITE_OPEN_CREATE);
5072 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5073 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
5075 #ifndef NDEBUG
5076 int isOpenJournal = (isCreate && (
5077 eType==SQLITE_OPEN_MASTER_JOURNAL
5078 || eType==SQLITE_OPEN_MAIN_JOURNAL
5079 || eType==SQLITE_OPEN_WAL
5081 #endif
5083 OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
5084 zUtf8Name, id, flags, pOutFlags));
5086 /* Check the following statements are true:
5088 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5089 ** (b) if CREATE is set, then READWRITE must also be set, and
5090 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
5091 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
5093 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
5094 assert(isCreate==0 || isReadWrite);
5095 assert(isExclusive==0 || isCreate);
5096 assert(isDelete==0 || isCreate);
5098 /* The main DB, main journal, WAL file and master journal are never
5099 ** automatically deleted. Nor are they ever temporary files. */
5100 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5101 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5102 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
5103 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
5105 /* Assert that the upper layer has set one of the "file-type" flags. */
5106 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5107 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5108 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
5109 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
5112 assert( pFile!=0 );
5113 memset(pFile, 0, sizeof(winFile));
5114 pFile->h = INVALID_HANDLE_VALUE;
5116 #if SQLITE_OS_WINRT
5117 if( !zUtf8Name && !sqlite3_temp_directory ){
5118 sqlite3_log(SQLITE_ERROR,
5119 "sqlite3_temp_directory variable should be set for WinRT");
5121 #endif
5123 /* If the second argument to this function is NULL, generate a
5124 ** temporary file name to use
5126 if( !zUtf8Name ){
5127 assert( isDelete && !isOpenJournal );
5128 rc = winGetTempname(pVfs, &zTmpname);
5129 if( rc!=SQLITE_OK ){
5130 OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
5131 return rc;
5133 zUtf8Name = zTmpname;
5136 /* Database filenames are double-zero terminated if they are not
5137 ** URIs with parameters. Hence, they can always be passed into
5138 ** sqlite3_uri_parameter().
5140 assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
5141 zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
5143 /* Convert the filename to the system encoding. */
5144 zConverted = winConvertFromUtf8Filename(zUtf8Name);
5145 if( zConverted==0 ){
5146 sqlite3_free(zTmpname);
5147 OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
5148 return SQLITE_IOERR_NOMEM_BKPT;
5151 if( winIsDir(zConverted) ){
5152 sqlite3_free(zConverted);
5153 sqlite3_free(zTmpname);
5154 OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
5155 return SQLITE_CANTOPEN_ISDIR;
5158 if( isReadWrite ){
5159 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
5160 }else{
5161 dwDesiredAccess = GENERIC_READ;
5164 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
5165 ** created. SQLite doesn't use it to indicate "exclusive access"
5166 ** as it is usually understood.
5168 if( isExclusive ){
5169 /* Creates a new file, only if it does not already exist. */
5170 /* If the file exists, it fails. */
5171 dwCreationDisposition = CREATE_NEW;
5172 }else if( isCreate ){
5173 /* Open existing file, or create if it doesn't exist */
5174 dwCreationDisposition = OPEN_ALWAYS;
5175 }else{
5176 /* Opens a file, only if it exists. */
5177 dwCreationDisposition = OPEN_EXISTING;
5180 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
5182 if( isDelete ){
5183 #if SQLITE_OS_WINCE
5184 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
5185 isTemp = 1;
5186 #else
5187 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
5188 | FILE_ATTRIBUTE_HIDDEN
5189 | FILE_FLAG_DELETE_ON_CLOSE;
5190 #endif
5191 }else{
5192 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
5194 /* Reports from the internet are that performance is always
5195 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
5196 #if SQLITE_OS_WINCE
5197 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
5198 #endif
5200 if( osIsNT() ){
5201 #if SQLITE_OS_WINRT
5202 CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
5203 extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
5204 extendedParameters.dwFileAttributes =
5205 dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
5206 extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
5207 extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
5208 extendedParameters.lpSecurityAttributes = NULL;
5209 extendedParameters.hTemplateFile = NULL;
5211 h = osCreateFile2((LPCWSTR)zConverted,
5212 dwDesiredAccess,
5213 dwShareMode,
5214 dwCreationDisposition,
5215 &extendedParameters);
5216 if( h!=INVALID_HANDLE_VALUE ) break;
5217 if( isReadWrite ){
5218 int isRO = 0;
5219 int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
5220 if( rc2==SQLITE_OK && isRO ) break;
5222 }while( winRetryIoerr(&cnt, &lastErrno) );
5223 #else
5225 h = osCreateFileW((LPCWSTR)zConverted,
5226 dwDesiredAccess,
5227 dwShareMode, NULL,
5228 dwCreationDisposition,
5229 dwFlagsAndAttributes,
5230 NULL);
5231 if( h!=INVALID_HANDLE_VALUE ) break;
5232 if( isReadWrite ){
5233 int isRO = 0;
5234 int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
5235 if( rc2==SQLITE_OK && isRO ) break;
5237 }while( winRetryIoerr(&cnt, &lastErrno) );
5238 #endif
5240 #ifdef SQLITE_WIN32_HAS_ANSI
5241 else{
5243 h = osCreateFileA((LPCSTR)zConverted,
5244 dwDesiredAccess,
5245 dwShareMode, NULL,
5246 dwCreationDisposition,
5247 dwFlagsAndAttributes,
5248 NULL);
5249 if( h!=INVALID_HANDLE_VALUE ) break;
5250 if( isReadWrite ){
5251 int isRO = 0;
5252 int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
5253 if( rc2==SQLITE_OK && isRO ) break;
5255 }while( winRetryIoerr(&cnt, &lastErrno) );
5257 #endif
5258 winLogIoerr(cnt, __LINE__);
5260 OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
5261 dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
5263 if( h==INVALID_HANDLE_VALUE ){
5264 sqlite3_free(zConverted);
5265 sqlite3_free(zTmpname);
5266 if( isReadWrite && !isExclusive ){
5267 return winOpen(pVfs, zName, id,
5268 ((flags|SQLITE_OPEN_READONLY) &
5269 ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
5270 pOutFlags);
5271 }else{
5272 pFile->lastErrno = lastErrno;
5273 winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
5274 return SQLITE_CANTOPEN_BKPT;
5278 if( pOutFlags ){
5279 if( isReadWrite ){
5280 *pOutFlags = SQLITE_OPEN_READWRITE;
5281 }else{
5282 *pOutFlags = SQLITE_OPEN_READONLY;
5286 OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
5287 "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
5288 *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
5290 pAppData = (winVfsAppData*)pVfs->pAppData;
5292 #if SQLITE_OS_WINCE
5294 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
5295 && ((pAppData==NULL) || !pAppData->bNoLock)
5296 && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
5298 osCloseHandle(h);
5299 sqlite3_free(zConverted);
5300 sqlite3_free(zTmpname);
5301 OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
5302 return rc;
5305 if( isTemp ){
5306 pFile->zDeleteOnClose = zConverted;
5307 }else
5308 #endif
5310 sqlite3_free(zConverted);
5313 sqlite3_free(zTmpname);
5314 pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
5315 pFile->pVfs = pVfs;
5316 pFile->h = h;
5317 if( isReadonly ){
5318 pFile->ctrlFlags |= WINFILE_RDONLY;
5320 if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
5321 pFile->ctrlFlags |= WINFILE_PSOW;
5323 pFile->lastErrno = NO_ERROR;
5324 pFile->zPath = zName;
5325 #if SQLITE_MAX_MMAP_SIZE>0
5326 pFile->hMap = NULL;
5327 pFile->pMapRegion = 0;
5328 pFile->mmapSize = 0;
5329 pFile->mmapSizeActual = 0;
5330 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
5331 #endif
5333 OpenCounter(+1);
5334 return rc;
5338 ** Delete the named file.
5340 ** Note that Windows does not allow a file to be deleted if some other
5341 ** process has it open. Sometimes a virus scanner or indexing program
5342 ** will open a journal file shortly after it is created in order to do
5343 ** whatever it does. While this other process is holding the
5344 ** file open, we will be unable to delete it. To work around this
5345 ** problem, we delay 100 milliseconds and try to delete again. Up
5346 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
5347 ** up and returning an error.
5349 static int winDelete(
5350 sqlite3_vfs *pVfs, /* Not used on win32 */
5351 const char *zFilename, /* Name of file to delete */
5352 int syncDir /* Not used on win32 */
5354 int cnt = 0;
5355 int rc;
5356 DWORD attr;
5357 DWORD lastErrno = 0;
5358 void *zConverted;
5359 UNUSED_PARAMETER(pVfs);
5360 UNUSED_PARAMETER(syncDir);
5362 SimulateIOError(return SQLITE_IOERR_DELETE);
5363 OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
5365 zConverted = winConvertFromUtf8Filename(zFilename);
5366 if( zConverted==0 ){
5367 OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
5368 return SQLITE_IOERR_NOMEM_BKPT;
5370 if( osIsNT() ){
5371 do {
5372 #if SQLITE_OS_WINRT
5373 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
5374 memset(&sAttrData, 0, sizeof(sAttrData));
5375 if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
5376 &sAttrData) ){
5377 attr = sAttrData.dwFileAttributes;
5378 }else{
5379 lastErrno = osGetLastError();
5380 if( lastErrno==ERROR_FILE_NOT_FOUND
5381 || lastErrno==ERROR_PATH_NOT_FOUND ){
5382 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
5383 }else{
5384 rc = SQLITE_ERROR;
5386 break;
5388 #else
5389 attr = osGetFileAttributesW(zConverted);
5390 #endif
5391 if ( attr==INVALID_FILE_ATTRIBUTES ){
5392 lastErrno = osGetLastError();
5393 if( lastErrno==ERROR_FILE_NOT_FOUND
5394 || lastErrno==ERROR_PATH_NOT_FOUND ){
5395 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
5396 }else{
5397 rc = SQLITE_ERROR;
5399 break;
5401 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
5402 rc = SQLITE_ERROR; /* Files only. */
5403 break;
5405 if ( osDeleteFileW(zConverted) ){
5406 rc = SQLITE_OK; /* Deleted OK. */
5407 break;
5409 if ( !winRetryIoerr(&cnt, &lastErrno) ){
5410 rc = SQLITE_ERROR; /* No more retries. */
5411 break;
5413 } while(1);
5415 #ifdef SQLITE_WIN32_HAS_ANSI
5416 else{
5417 do {
5418 attr = osGetFileAttributesA(zConverted);
5419 if ( attr==INVALID_FILE_ATTRIBUTES ){
5420 lastErrno = osGetLastError();
5421 if( lastErrno==ERROR_FILE_NOT_FOUND
5422 || lastErrno==ERROR_PATH_NOT_FOUND ){
5423 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
5424 }else{
5425 rc = SQLITE_ERROR;
5427 break;
5429 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
5430 rc = SQLITE_ERROR; /* Files only. */
5431 break;
5433 if ( osDeleteFileA(zConverted) ){
5434 rc = SQLITE_OK; /* Deleted OK. */
5435 break;
5437 if ( !winRetryIoerr(&cnt, &lastErrno) ){
5438 rc = SQLITE_ERROR; /* No more retries. */
5439 break;
5441 } while(1);
5443 #endif
5444 if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
5445 rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
5446 }else{
5447 winLogIoerr(cnt, __LINE__);
5449 sqlite3_free(zConverted);
5450 OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
5451 return rc;
5455 ** Check the existence and status of a file.
5457 static int winAccess(
5458 sqlite3_vfs *pVfs, /* Not used on win32 */
5459 const char *zFilename, /* Name of file to check */
5460 int flags, /* Type of test to make on this file */
5461 int *pResOut /* OUT: Result */
5463 DWORD attr;
5464 int rc = 0;
5465 DWORD lastErrno = 0;
5466 void *zConverted;
5467 UNUSED_PARAMETER(pVfs);
5469 SimulateIOError( return SQLITE_IOERR_ACCESS; );
5470 OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
5471 zFilename, flags, pResOut));
5473 zConverted = winConvertFromUtf8Filename(zFilename);
5474 if( zConverted==0 ){
5475 OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
5476 return SQLITE_IOERR_NOMEM_BKPT;
5478 if( osIsNT() ){
5479 int cnt = 0;
5480 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
5481 memset(&sAttrData, 0, sizeof(sAttrData));
5482 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
5483 GetFileExInfoStandard,
5484 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
5485 if( rc ){
5486 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
5487 ** as if it does not exist.
5489 if( flags==SQLITE_ACCESS_EXISTS
5490 && sAttrData.nFileSizeHigh==0
5491 && sAttrData.nFileSizeLow==0 ){
5492 attr = INVALID_FILE_ATTRIBUTES;
5493 }else{
5494 attr = sAttrData.dwFileAttributes;
5496 }else{
5497 winLogIoerr(cnt, __LINE__);
5498 if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
5499 sqlite3_free(zConverted);
5500 return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
5501 zFilename);
5502 }else{
5503 attr = INVALID_FILE_ATTRIBUTES;
5507 #ifdef SQLITE_WIN32_HAS_ANSI
5508 else{
5509 attr = osGetFileAttributesA((char*)zConverted);
5511 #endif
5512 sqlite3_free(zConverted);
5513 switch( flags ){
5514 case SQLITE_ACCESS_READ:
5515 case SQLITE_ACCESS_EXISTS:
5516 rc = attr!=INVALID_FILE_ATTRIBUTES;
5517 break;
5518 case SQLITE_ACCESS_READWRITE:
5519 rc = attr!=INVALID_FILE_ATTRIBUTES &&
5520 (attr & FILE_ATTRIBUTE_READONLY)==0;
5521 break;
5522 default:
5523 assert(!"Invalid flags argument");
5525 *pResOut = rc;
5526 OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
5527 zFilename, pResOut, *pResOut));
5528 return SQLITE_OK;
5532 ** Returns non-zero if the specified path name starts with a drive letter
5533 ** followed by a colon character.
5535 static BOOL winIsDriveLetterAndColon(
5536 const char *zPathname
5538 return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
5542 ** Returns non-zero if the specified path name should be used verbatim. If
5543 ** non-zero is returned from this function, the calling function must simply
5544 ** use the provided path name verbatim -OR- resolve it into a full path name
5545 ** using the GetFullPathName Win32 API function (if available).
5547 static BOOL winIsVerbatimPathname(
5548 const char *zPathname
5551 ** If the path name starts with a forward slash or a backslash, it is either
5552 ** a legal UNC name, a volume relative path, or an absolute path name in the
5553 ** "Unix" format on Windows. There is no easy way to differentiate between
5554 ** the final two cases; therefore, we return the safer return value of TRUE
5555 ** so that callers of this function will simply use it verbatim.
5557 if ( winIsDirSep(zPathname[0]) ){
5558 return TRUE;
5562 ** If the path name starts with a letter and a colon it is either a volume
5563 ** relative path or an absolute path. Callers of this function must not
5564 ** attempt to treat it as a relative path name (i.e. they should simply use
5565 ** it verbatim).
5567 if ( winIsDriveLetterAndColon(zPathname) ){
5568 return TRUE;
5572 ** If we get to this point, the path name should almost certainly be a purely
5573 ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
5575 return FALSE;
5579 ** Turn a relative pathname into a full pathname. Write the full
5580 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
5581 ** bytes in size.
5583 static int winFullPathname(
5584 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5585 const char *zRelative, /* Possibly relative input path */
5586 int nFull, /* Size of output buffer in bytes */
5587 char *zFull /* Output buffer */
5589 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
5590 DWORD nByte;
5591 void *zConverted;
5592 char *zOut;
5593 #endif
5595 /* If this path name begins with "/X:", where "X" is any alphabetic
5596 ** character, discard the initial "/" from the pathname.
5598 if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
5599 zRelative++;
5602 #if defined(__CYGWIN__)
5603 SimulateIOError( return SQLITE_ERROR );
5604 UNUSED_PARAMETER(nFull);
5605 assert( nFull>=pVfs->mxPathname );
5606 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
5608 ** NOTE: We are dealing with a relative path name and the data
5609 ** directory has been set. Therefore, use it as the basis
5610 ** for converting the relative path name to an absolute
5611 ** one by prepending the data directory and a slash.
5613 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
5614 if( !zOut ){
5615 return SQLITE_IOERR_NOMEM_BKPT;
5617 if( cygwin_conv_path(
5618 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
5619 CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
5620 sqlite3_free(zOut);
5621 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
5622 "winFullPathname1", zRelative);
5623 }else{
5624 char *zUtf8 = winConvertToUtf8Filename(zOut);
5625 if( !zUtf8 ){
5626 sqlite3_free(zOut);
5627 return SQLITE_IOERR_NOMEM_BKPT;
5629 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
5630 sqlite3_data_directory, winGetDirSep(), zUtf8);
5631 sqlite3_free(zUtf8);
5632 sqlite3_free(zOut);
5634 }else{
5635 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
5636 if( !zOut ){
5637 return SQLITE_IOERR_NOMEM_BKPT;
5639 if( cygwin_conv_path(
5640 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
5641 zRelative, zOut, pVfs->mxPathname+1)<0 ){
5642 sqlite3_free(zOut);
5643 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
5644 "winFullPathname2", zRelative);
5645 }else{
5646 char *zUtf8 = winConvertToUtf8Filename(zOut);
5647 if( !zUtf8 ){
5648 sqlite3_free(zOut);
5649 return SQLITE_IOERR_NOMEM_BKPT;
5651 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
5652 sqlite3_free(zUtf8);
5653 sqlite3_free(zOut);
5656 return SQLITE_OK;
5657 #endif
5659 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
5660 SimulateIOError( return SQLITE_ERROR );
5661 /* WinCE has no concept of a relative pathname, or so I am told. */
5662 /* WinRT has no way to convert a relative path to an absolute one. */
5663 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
5665 ** NOTE: We are dealing with a relative path name and the data
5666 ** directory has been set. Therefore, use it as the basis
5667 ** for converting the relative path name to an absolute
5668 ** one by prepending the data directory and a backslash.
5670 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
5671 sqlite3_data_directory, winGetDirSep(), zRelative);
5672 }else{
5673 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
5675 return SQLITE_OK;
5676 #endif
5678 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
5679 /* It's odd to simulate an io-error here, but really this is just
5680 ** using the io-error infrastructure to test that SQLite handles this
5681 ** function failing. This function could fail if, for example, the
5682 ** current working directory has been unlinked.
5684 SimulateIOError( return SQLITE_ERROR );
5685 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
5687 ** NOTE: We are dealing with a relative path name and the data
5688 ** directory has been set. Therefore, use it as the basis
5689 ** for converting the relative path name to an absolute
5690 ** one by prepending the data directory and a backslash.
5692 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
5693 sqlite3_data_directory, winGetDirSep(), zRelative);
5694 return SQLITE_OK;
5696 zConverted = winConvertFromUtf8Filename(zRelative);
5697 if( zConverted==0 ){
5698 return SQLITE_IOERR_NOMEM_BKPT;
5700 if( osIsNT() ){
5701 LPWSTR zTemp;
5702 nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
5703 if( nByte==0 ){
5704 sqlite3_free(zConverted);
5705 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
5706 "winFullPathname1", zRelative);
5708 nByte += 3;
5709 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
5710 if( zTemp==0 ){
5711 sqlite3_free(zConverted);
5712 return SQLITE_IOERR_NOMEM_BKPT;
5714 nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
5715 if( nByte==0 ){
5716 sqlite3_free(zConverted);
5717 sqlite3_free(zTemp);
5718 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
5719 "winFullPathname2", zRelative);
5721 sqlite3_free(zConverted);
5722 zOut = winUnicodeToUtf8(zTemp);
5723 sqlite3_free(zTemp);
5725 #ifdef SQLITE_WIN32_HAS_ANSI
5726 else{
5727 char *zTemp;
5728 nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
5729 if( nByte==0 ){
5730 sqlite3_free(zConverted);
5731 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
5732 "winFullPathname3", zRelative);
5734 nByte += 3;
5735 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
5736 if( zTemp==0 ){
5737 sqlite3_free(zConverted);
5738 return SQLITE_IOERR_NOMEM_BKPT;
5740 nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
5741 if( nByte==0 ){
5742 sqlite3_free(zConverted);
5743 sqlite3_free(zTemp);
5744 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
5745 "winFullPathname4", zRelative);
5747 sqlite3_free(zConverted);
5748 zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
5749 sqlite3_free(zTemp);
5751 #endif
5752 if( zOut ){
5753 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
5754 sqlite3_free(zOut);
5755 return SQLITE_OK;
5756 }else{
5757 return SQLITE_IOERR_NOMEM_BKPT;
5759 #endif
5762 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5764 ** Interfaces for opening a shared library, finding entry points
5765 ** within the shared library, and closing the shared library.
5767 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
5768 HANDLE h;
5769 #if defined(__CYGWIN__)
5770 int nFull = pVfs->mxPathname+1;
5771 char *zFull = sqlite3MallocZero( nFull );
5772 void *zConverted = 0;
5773 if( zFull==0 ){
5774 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
5775 return 0;
5777 if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
5778 sqlite3_free(zFull);
5779 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
5780 return 0;
5782 zConverted = winConvertFromUtf8Filename(zFull);
5783 sqlite3_free(zFull);
5784 #else
5785 void *zConverted = winConvertFromUtf8Filename(zFilename);
5786 UNUSED_PARAMETER(pVfs);
5787 #endif
5788 if( zConverted==0 ){
5789 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
5790 return 0;
5792 if( osIsNT() ){
5793 #if SQLITE_OS_WINRT
5794 h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
5795 #else
5796 h = osLoadLibraryW((LPCWSTR)zConverted);
5797 #endif
5799 #ifdef SQLITE_WIN32_HAS_ANSI
5800 else{
5801 h = osLoadLibraryA((char*)zConverted);
5803 #endif
5804 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
5805 sqlite3_free(zConverted);
5806 return (void*)h;
5808 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
5809 UNUSED_PARAMETER(pVfs);
5810 winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
5812 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
5813 FARPROC proc;
5814 UNUSED_PARAMETER(pVfs);
5815 proc = osGetProcAddressA((HANDLE)pH, zSym);
5816 OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
5817 (void*)pH, zSym, (void*)proc));
5818 return (void(*)(void))proc;
5820 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
5821 UNUSED_PARAMETER(pVfs);
5822 osFreeLibrary((HANDLE)pHandle);
5823 OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
5825 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5826 #define winDlOpen 0
5827 #define winDlError 0
5828 #define winDlSym 0
5829 #define winDlClose 0
5830 #endif
5832 /* State information for the randomness gatherer. */
5833 typedef struct EntropyGatherer EntropyGatherer;
5834 struct EntropyGatherer {
5835 unsigned char *a; /* Gather entropy into this buffer */
5836 int na; /* Size of a[] in bytes */
5837 int i; /* XOR next input into a[i] */
5838 int nXor; /* Number of XOR operations done */
5841 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
5842 /* Mix sz bytes of entropy into p. */
5843 static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
5844 int j, k;
5845 for(j=0, k=p->i; j<sz; j++){
5846 p->a[k++] ^= x[j];
5847 if( k>=p->na ) k = 0;
5849 p->i = k;
5850 p->nXor += sz;
5852 #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
5855 ** Write up to nBuf bytes of randomness into zBuf.
5857 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
5858 #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
5859 UNUSED_PARAMETER(pVfs);
5860 memset(zBuf, 0, nBuf);
5861 return nBuf;
5862 #else
5863 EntropyGatherer e;
5864 UNUSED_PARAMETER(pVfs);
5865 memset(zBuf, 0, nBuf);
5866 e.a = (unsigned char*)zBuf;
5867 e.na = nBuf;
5868 e.nXor = 0;
5869 e.i = 0;
5871 SYSTEMTIME x;
5872 osGetSystemTime(&x);
5873 xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
5876 DWORD pid = osGetCurrentProcessId();
5877 xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
5879 #if SQLITE_OS_WINRT
5881 ULONGLONG cnt = osGetTickCount64();
5882 xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
5884 #else
5886 DWORD cnt = osGetTickCount();
5887 xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
5889 #endif /* SQLITE_OS_WINRT */
5891 LARGE_INTEGER i;
5892 osQueryPerformanceCounter(&i);
5893 xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
5895 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
5897 UUID id;
5898 memset(&id, 0, sizeof(UUID));
5899 osUuidCreate(&id);
5900 xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
5901 memset(&id, 0, sizeof(UUID));
5902 osUuidCreateSequential(&id);
5903 xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
5905 #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
5906 return e.nXor>nBuf ? nBuf : e.nXor;
5907 #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
5912 ** Sleep for a little while. Return the amount of time slept.
5914 static int winSleep(sqlite3_vfs *pVfs, int microsec){
5915 sqlite3_win32_sleep((microsec+999)/1000);
5916 UNUSED_PARAMETER(pVfs);
5917 return ((microsec+999)/1000)*1000;
5921 ** The following variable, if set to a non-zero value, is interpreted as
5922 ** the number of seconds since 1970 and is used to set the result of
5923 ** sqlite3OsCurrentTime() during testing.
5925 #ifdef SQLITE_TEST
5926 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
5927 #endif
5930 ** Find the current time (in Universal Coordinated Time). Write into *piNow
5931 ** the current time and date as a Julian Day number times 86_400_000. In
5932 ** other words, write into *piNow the number of milliseconds since the Julian
5933 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5934 ** proleptic Gregorian calendar.
5936 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5937 ** cannot be found.
5939 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
5940 /* FILETIME structure is a 64-bit value representing the number of
5941 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
5943 FILETIME ft;
5944 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
5945 #ifdef SQLITE_TEST
5946 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5947 #endif
5948 /* 2^32 - to avoid use of LL and warnings in gcc */
5949 static const sqlite3_int64 max32BitValue =
5950 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
5951 (sqlite3_int64)294967296;
5953 #if SQLITE_OS_WINCE
5954 SYSTEMTIME time;
5955 osGetSystemTime(&time);
5956 /* if SystemTimeToFileTime() fails, it returns zero. */
5957 if (!osSystemTimeToFileTime(&time,&ft)){
5958 return SQLITE_ERROR;
5960 #else
5961 osGetSystemTimeAsFileTime( &ft );
5962 #endif
5964 *piNow = winFiletimeEpoch +
5965 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
5966 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
5968 #ifdef SQLITE_TEST
5969 if( sqlite3_current_time ){
5970 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5972 #endif
5973 UNUSED_PARAMETER(pVfs);
5974 return SQLITE_OK;
5978 ** Find the current time (in Universal Coordinated Time). Write the
5979 ** current time and date as a Julian Day number into *prNow and
5980 ** return 0. Return 1 if the time and date cannot be found.
5982 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
5983 int rc;
5984 sqlite3_int64 i;
5985 rc = winCurrentTimeInt64(pVfs, &i);
5986 if( !rc ){
5987 *prNow = i/86400000.0;
5989 return rc;
5993 ** The idea is that this function works like a combination of
5994 ** GetLastError() and FormatMessage() on Windows (or errno and
5995 ** strerror_r() on Unix). After an error is returned by an OS
5996 ** function, SQLite calls this function with zBuf pointing to
5997 ** a buffer of nBuf bytes. The OS layer should populate the
5998 ** buffer with a nul-terminated UTF-8 encoded error message
5999 ** describing the last IO error to have occurred within the calling
6000 ** thread.
6002 ** If the error message is too large for the supplied buffer,
6003 ** it should be truncated. The return value of xGetLastError
6004 ** is zero if the error message fits in the buffer, or non-zero
6005 ** otherwise (if the message was truncated). If non-zero is returned,
6006 ** then it is not necessary to include the nul-terminator character
6007 ** in the output buffer.
6009 ** Not supplying an error message will have no adverse effect
6010 ** on SQLite. It is fine to have an implementation that never
6011 ** returns an error message:
6013 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
6014 ** assert(zBuf[0]=='\0');
6015 ** return 0;
6016 ** }
6018 ** However if an error message is supplied, it will be incorporated
6019 ** by sqlite into the error message available to the user using
6020 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
6022 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
6023 DWORD e = osGetLastError();
6024 UNUSED_PARAMETER(pVfs);
6025 if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
6026 return e;
6030 ** Initialize and deinitialize the operating system interface.
6032 int sqlite3_os_init(void){
6033 static sqlite3_vfs winVfs = {
6034 3, /* iVersion */
6035 sizeof(winFile), /* szOsFile */
6036 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
6037 0, /* pNext */
6038 "win32", /* zName */
6039 &winAppData, /* pAppData */
6040 winOpen, /* xOpen */
6041 winDelete, /* xDelete */
6042 winAccess, /* xAccess */
6043 winFullPathname, /* xFullPathname */
6044 winDlOpen, /* xDlOpen */
6045 winDlError, /* xDlError */
6046 winDlSym, /* xDlSym */
6047 winDlClose, /* xDlClose */
6048 winRandomness, /* xRandomness */
6049 winSleep, /* xSleep */
6050 winCurrentTime, /* xCurrentTime */
6051 winGetLastError, /* xGetLastError */
6052 winCurrentTimeInt64, /* xCurrentTimeInt64 */
6053 winSetSystemCall, /* xSetSystemCall */
6054 winGetSystemCall, /* xGetSystemCall */
6055 winNextSystemCall, /* xNextSystemCall */
6057 #if defined(SQLITE_WIN32_HAS_WIDE)
6058 static sqlite3_vfs winLongPathVfs = {
6059 3, /* iVersion */
6060 sizeof(winFile), /* szOsFile */
6061 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
6062 0, /* pNext */
6063 "win32-longpath", /* zName */
6064 &winAppData, /* pAppData */
6065 winOpen, /* xOpen */
6066 winDelete, /* xDelete */
6067 winAccess, /* xAccess */
6068 winFullPathname, /* xFullPathname */
6069 winDlOpen, /* xDlOpen */
6070 winDlError, /* xDlError */
6071 winDlSym, /* xDlSym */
6072 winDlClose, /* xDlClose */
6073 winRandomness, /* xRandomness */
6074 winSleep, /* xSleep */
6075 winCurrentTime, /* xCurrentTime */
6076 winGetLastError, /* xGetLastError */
6077 winCurrentTimeInt64, /* xCurrentTimeInt64 */
6078 winSetSystemCall, /* xSetSystemCall */
6079 winGetSystemCall, /* xGetSystemCall */
6080 winNextSystemCall, /* xNextSystemCall */
6082 #endif
6083 static sqlite3_vfs winNolockVfs = {
6084 3, /* iVersion */
6085 sizeof(winFile), /* szOsFile */
6086 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
6087 0, /* pNext */
6088 "win32-none", /* zName */
6089 &winNolockAppData, /* pAppData */
6090 winOpen, /* xOpen */
6091 winDelete, /* xDelete */
6092 winAccess, /* xAccess */
6093 winFullPathname, /* xFullPathname */
6094 winDlOpen, /* xDlOpen */
6095 winDlError, /* xDlError */
6096 winDlSym, /* xDlSym */
6097 winDlClose, /* xDlClose */
6098 winRandomness, /* xRandomness */
6099 winSleep, /* xSleep */
6100 winCurrentTime, /* xCurrentTime */
6101 winGetLastError, /* xGetLastError */
6102 winCurrentTimeInt64, /* xCurrentTimeInt64 */
6103 winSetSystemCall, /* xSetSystemCall */
6104 winGetSystemCall, /* xGetSystemCall */
6105 winNextSystemCall, /* xNextSystemCall */
6107 #if defined(SQLITE_WIN32_HAS_WIDE)
6108 static sqlite3_vfs winLongPathNolockVfs = {
6109 3, /* iVersion */
6110 sizeof(winFile), /* szOsFile */
6111 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
6112 0, /* pNext */
6113 "win32-longpath-none", /* zName */
6114 &winNolockAppData, /* pAppData */
6115 winOpen, /* xOpen */
6116 winDelete, /* xDelete */
6117 winAccess, /* xAccess */
6118 winFullPathname, /* xFullPathname */
6119 winDlOpen, /* xDlOpen */
6120 winDlError, /* xDlError */
6121 winDlSym, /* xDlSym */
6122 winDlClose, /* xDlClose */
6123 winRandomness, /* xRandomness */
6124 winSleep, /* xSleep */
6125 winCurrentTime, /* xCurrentTime */
6126 winGetLastError, /* xGetLastError */
6127 winCurrentTimeInt64, /* xCurrentTimeInt64 */
6128 winSetSystemCall, /* xSetSystemCall */
6129 winGetSystemCall, /* xGetSystemCall */
6130 winNextSystemCall, /* xNextSystemCall */
6132 #endif
6134 /* Double-check that the aSyscall[] array has been constructed
6135 ** correctly. See ticket [bb3a86e890c8e96ab] */
6136 assert( ArraySize(aSyscall)==80 );
6138 /* get memory map allocation granularity */
6139 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
6140 #if SQLITE_OS_WINRT
6141 osGetNativeSystemInfo(&winSysInfo);
6142 #else
6143 osGetSystemInfo(&winSysInfo);
6144 #endif
6145 assert( winSysInfo.dwAllocationGranularity>0 );
6146 assert( winSysInfo.dwPageSize>0 );
6148 sqlite3_vfs_register(&winVfs, 1);
6150 #if defined(SQLITE_WIN32_HAS_WIDE)
6151 sqlite3_vfs_register(&winLongPathVfs, 0);
6152 #endif
6154 sqlite3_vfs_register(&winNolockVfs, 0);
6156 #if defined(SQLITE_WIN32_HAS_WIDE)
6157 sqlite3_vfs_register(&winLongPathNolockVfs, 0);
6158 #endif
6160 return SQLITE_OK;
6163 int sqlite3_os_end(void){
6164 #if SQLITE_OS_WINRT
6165 if( sleepObj!=NULL ){
6166 osCloseHandle(sleepObj);
6167 sleepObj = NULL;
6169 #endif
6170 return SQLITE_OK;
6173 #endif /* SQLITE_OS_WIN */