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