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 * The value used with sqlite3_win32_set_directory() to specify that
320 * the data directory should be changed.
322 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
323 # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
327 * The value used with sqlite3_win32_set_directory() to specify that
328 * the temporary directory should be changed.
330 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
331 # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
335 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
336 * various Win32 API heap functions instead of our own.
338 #ifdef SQLITE_WIN32_MALLOC
341 * If this is non-zero, an isolated heap will be created by the native Win32
342 * allocator subsystem; otherwise, the default process heap will be used. This
343 * setting has no effect when compiling for WinRT. By default, this is enabled
344 * and an isolated heap will be created to store all allocated data.
346 ******************************************************************************
347 * WARNING: It is important to note that when this setting is non-zero and the
348 * winMemShutdown function is called (e.g. by the sqlite3_shutdown
349 * function), all data that was allocated using the isolated heap will
350 * be freed immediately and any attempt to access any of that freed
351 * data will almost certainly result in an immediate access violation.
352 ******************************************************************************
354 #ifndef SQLITE_WIN32_HEAP_CREATE
355 # define SQLITE_WIN32_HEAP_CREATE (TRUE)
359 * This is cache size used in the calculation of the initial size of the
360 * Win32-specific heap. It cannot be negative.
362 #ifndef SQLITE_WIN32_CACHE_SIZE
363 # if SQLITE_DEFAULT_CACHE_SIZE>=0
364 # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
366 # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
371 * The initial size of the Win32-specific heap. This value may be zero.
373 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
374 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
375 (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
379 * The maximum size of the Win32-specific heap. This value may be zero.
381 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
382 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
386 * The extra flags to use in calls to the Win32 heap APIs. This value may be
387 * zero for the default behavior.
389 #ifndef SQLITE_WIN32_HEAP_FLAGS
390 # define SQLITE_WIN32_HEAP_FLAGS (0)
395 ** The winMemData structure stores information required by the Win32-specific
396 ** sqlite3_mem_methods implementation.
398 typedef struct winMemData winMemData
;
401 u32 magic1
; /* Magic number to detect structure corruption. */
403 HANDLE hHeap
; /* The handle to our heap. */
404 BOOL bOwned
; /* Do we own the heap (i.e. destroy it on shutdown)? */
406 u32 magic2
; /* Magic number to detect structure corruption. */
411 #define WINMEM_MAGIC1 0x42b2830b
412 #define WINMEM_MAGIC2 0xbd4d7cf4
415 static struct winMemData win_mem_data
= {
426 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
427 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
428 #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
430 #define winMemAssertMagic()
433 #define winMemGetDataPtr() &win_mem_data
434 #define winMemGetHeap() win_mem_data.hHeap
435 #define winMemGetOwned() win_mem_data.bOwned
437 static void *winMemMalloc(int nBytes
);
438 static void winMemFree(void *pPrior
);
439 static void *winMemRealloc(void *pPrior
, int nBytes
);
440 static int winMemSize(void *p
);
441 static int winMemRoundup(int n
);
442 static int winMemInit(void *pAppData
);
443 static void winMemShutdown(void *pAppData
);
445 const sqlite3_mem_methods
*sqlite3MemGetWin32(void);
446 #endif /* SQLITE_WIN32_MALLOC */
449 ** The following variable is (normally) set once and never changes
450 ** thereafter. It records whether the operating system is Win9x
453 ** 0: Operating system unknown.
454 ** 1: Operating system is Win9x.
455 ** 2: Operating system is WinNT.
457 ** In order to facilitate testing on a WinNT system, the test fixture
458 ** can manually set this value to 1 to emulate Win98 behavior.
461 LONG SQLITE_WIN32_VOLATILE sqlite3_os_type
= 0;
463 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type
= 0;
467 # define SYSCALL sqlite3_syscall_ptr
471 ** This function is not available on Windows CE or WinRT.
474 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
475 # define osAreFileApisANSI() 1
479 ** Many system calls are accessed through pointer-to-functions so that
480 ** they may be overridden at runtime to facilitate fault injection during
481 ** testing and sandboxing. The following array holds the names and pointers
482 ** to all overrideable system calls.
484 static struct win_syscall
{
485 const char *zName
; /* Name of the system call */
486 sqlite3_syscall_ptr pCurrent
; /* Current value of the system call */
487 sqlite3_syscall_ptr pDefault
; /* Default value */
489 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
490 { "AreFileApisANSI", (SYSCALL
)AreFileApisANSI
, 0 },
492 { "AreFileApisANSI", (SYSCALL
)0, 0 },
495 #ifndef osAreFileApisANSI
496 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
499 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
500 { "CharLowerW", (SYSCALL
)CharLowerW
, 0 },
502 { "CharLowerW", (SYSCALL
)0, 0 },
505 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
507 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
508 { "CharUpperW", (SYSCALL
)CharUpperW
, 0 },
510 { "CharUpperW", (SYSCALL
)0, 0 },
513 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
515 { "CloseHandle", (SYSCALL
)CloseHandle
, 0 },
517 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
519 #if defined(SQLITE_WIN32_HAS_ANSI)
520 { "CreateFileA", (SYSCALL
)CreateFileA
, 0 },
522 { "CreateFileA", (SYSCALL
)0, 0 },
525 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
526 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
528 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
529 { "CreateFileW", (SYSCALL
)CreateFileW
, 0 },
531 { "CreateFileW", (SYSCALL
)0, 0 },
534 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
535 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
537 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
538 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
539 SQLITE_WIN32_CREATEFILEMAPPINGA
540 { "CreateFileMappingA", (SYSCALL
)CreateFileMappingA
, 0 },
542 { "CreateFileMappingA", (SYSCALL
)0, 0 },
545 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
546 DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
548 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
549 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
550 { "CreateFileMappingW", (SYSCALL
)CreateFileMappingW
, 0 },
552 { "CreateFileMappingW", (SYSCALL
)0, 0 },
555 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
556 DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
558 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
559 { "CreateMutexW", (SYSCALL
)CreateMutexW
, 0 },
561 { "CreateMutexW", (SYSCALL
)0, 0 },
564 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
565 LPCWSTR))aSyscall[8].pCurrent)
567 #if defined(SQLITE_WIN32_HAS_ANSI)
568 { "DeleteFileA", (SYSCALL
)DeleteFileA
, 0 },
570 { "DeleteFileA", (SYSCALL
)0, 0 },
573 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
575 #if defined(SQLITE_WIN32_HAS_WIDE)
576 { "DeleteFileW", (SYSCALL
)DeleteFileW
, 0 },
578 { "DeleteFileW", (SYSCALL
)0, 0 },
581 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
584 { "FileTimeToLocalFileTime", (SYSCALL
)FileTimeToLocalFileTime
, 0 },
586 { "FileTimeToLocalFileTime", (SYSCALL
)0, 0 },
589 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
590 LPFILETIME))aSyscall[11].pCurrent)
593 { "FileTimeToSystemTime", (SYSCALL
)FileTimeToSystemTime
, 0 },
595 { "FileTimeToSystemTime", (SYSCALL
)0, 0 },
598 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
599 LPSYSTEMTIME))aSyscall[12].pCurrent)
601 { "FlushFileBuffers", (SYSCALL
)FlushFileBuffers
, 0 },
603 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
605 #if defined(SQLITE_WIN32_HAS_ANSI)
606 { "FormatMessageA", (SYSCALL
)FormatMessageA
, 0 },
608 { "FormatMessageA", (SYSCALL
)0, 0 },
611 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
612 DWORD,va_list*))aSyscall[14].pCurrent)
614 #if defined(SQLITE_WIN32_HAS_WIDE)
615 { "FormatMessageW", (SYSCALL
)FormatMessageW
, 0 },
617 { "FormatMessageW", (SYSCALL
)0, 0 },
620 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
621 DWORD,va_list*))aSyscall[15].pCurrent)
623 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
624 { "FreeLibrary", (SYSCALL
)FreeLibrary
, 0 },
626 { "FreeLibrary", (SYSCALL
)0, 0 },
629 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
631 { "GetCurrentProcessId", (SYSCALL
)GetCurrentProcessId
, 0 },
633 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
635 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
636 { "GetDiskFreeSpaceA", (SYSCALL
)GetDiskFreeSpaceA
, 0 },
638 { "GetDiskFreeSpaceA", (SYSCALL
)0, 0 },
641 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
642 LPDWORD))aSyscall[18].pCurrent)
644 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
645 { "GetDiskFreeSpaceW", (SYSCALL
)GetDiskFreeSpaceW
, 0 },
647 { "GetDiskFreeSpaceW", (SYSCALL
)0, 0 },
650 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
651 LPDWORD))aSyscall[19].pCurrent)
653 #if defined(SQLITE_WIN32_HAS_ANSI)
654 { "GetFileAttributesA", (SYSCALL
)GetFileAttributesA
, 0 },
656 { "GetFileAttributesA", (SYSCALL
)0, 0 },
659 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
661 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
662 { "GetFileAttributesW", (SYSCALL
)GetFileAttributesW
, 0 },
664 { "GetFileAttributesW", (SYSCALL
)0, 0 },
667 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
669 #if defined(SQLITE_WIN32_HAS_WIDE)
670 { "GetFileAttributesExW", (SYSCALL
)GetFileAttributesExW
, 0 },
672 { "GetFileAttributesExW", (SYSCALL
)0, 0 },
675 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
676 LPVOID))aSyscall[22].pCurrent)
679 { "GetFileSize", (SYSCALL
)GetFileSize
, 0 },
681 { "GetFileSize", (SYSCALL
)0, 0 },
684 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
686 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
687 { "GetFullPathNameA", (SYSCALL
)GetFullPathNameA
, 0 },
689 { "GetFullPathNameA", (SYSCALL
)0, 0 },
692 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
693 LPSTR*))aSyscall[24].pCurrent)
695 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
696 { "GetFullPathNameW", (SYSCALL
)GetFullPathNameW
, 0 },
698 { "GetFullPathNameW", (SYSCALL
)0, 0 },
701 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
702 LPWSTR*))aSyscall[25].pCurrent)
704 { "GetLastError", (SYSCALL
)GetLastError
, 0 },
706 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
708 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
710 /* The GetProcAddressA() routine is only available on Windows CE. */
711 { "GetProcAddressA", (SYSCALL
)GetProcAddressA
, 0 },
713 /* All other Windows platforms expect GetProcAddress() to take
714 ** an ANSI string regardless of the _UNICODE setting */
715 { "GetProcAddressA", (SYSCALL
)GetProcAddress
, 0 },
718 { "GetProcAddressA", (SYSCALL
)0, 0 },
721 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
722 LPCSTR))aSyscall[27].pCurrent)
725 { "GetSystemInfo", (SYSCALL
)GetSystemInfo
, 0 },
727 { "GetSystemInfo", (SYSCALL
)0, 0 },
730 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
732 { "GetSystemTime", (SYSCALL
)GetSystemTime
, 0 },
734 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
737 { "GetSystemTimeAsFileTime", (SYSCALL
)GetSystemTimeAsFileTime
, 0 },
739 { "GetSystemTimeAsFileTime", (SYSCALL
)0, 0 },
742 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
743 LPFILETIME))aSyscall[30].pCurrent)
745 #if defined(SQLITE_WIN32_HAS_ANSI)
746 { "GetTempPathA", (SYSCALL
)GetTempPathA
, 0 },
748 { "GetTempPathA", (SYSCALL
)0, 0 },
751 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
753 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
754 { "GetTempPathW", (SYSCALL
)GetTempPathW
, 0 },
756 { "GetTempPathW", (SYSCALL
)0, 0 },
759 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
762 { "GetTickCount", (SYSCALL
)GetTickCount
, 0 },
764 { "GetTickCount", (SYSCALL
)0, 0 },
767 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
769 #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
770 { "GetVersionExA", (SYSCALL
)GetVersionExA
, 0 },
772 { "GetVersionExA", (SYSCALL
)0, 0 },
775 #define osGetVersionExA ((BOOL(WINAPI*)( \
776 LPOSVERSIONINFOA))aSyscall[34].pCurrent)
778 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
779 SQLITE_WIN32_GETVERSIONEX
780 { "GetVersionExW", (SYSCALL
)GetVersionExW
, 0 },
782 { "GetVersionExW", (SYSCALL
)0, 0 },
785 #define osGetVersionExW ((BOOL(WINAPI*)( \
786 LPOSVERSIONINFOW))aSyscall[35].pCurrent)
788 { "HeapAlloc", (SYSCALL
)HeapAlloc
, 0 },
790 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
791 SIZE_T))aSyscall[36].pCurrent)
794 { "HeapCreate", (SYSCALL
)HeapCreate
, 0 },
796 { "HeapCreate", (SYSCALL
)0, 0 },
799 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
800 SIZE_T))aSyscall[37].pCurrent)
803 { "HeapDestroy", (SYSCALL
)HeapDestroy
, 0 },
805 { "HeapDestroy", (SYSCALL
)0, 0 },
808 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
810 { "HeapFree", (SYSCALL
)HeapFree
, 0 },
812 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
814 { "HeapReAlloc", (SYSCALL
)HeapReAlloc
, 0 },
816 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
817 SIZE_T))aSyscall[40].pCurrent)
819 { "HeapSize", (SYSCALL
)HeapSize
, 0 },
821 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
822 LPCVOID))aSyscall[41].pCurrent)
825 { "HeapValidate", (SYSCALL
)HeapValidate
, 0 },
827 { "HeapValidate", (SYSCALL
)0, 0 },
830 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
831 LPCVOID))aSyscall[42].pCurrent)
833 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
834 { "HeapCompact", (SYSCALL
)HeapCompact
, 0 },
836 { "HeapCompact", (SYSCALL
)0, 0 },
839 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
841 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
842 { "LoadLibraryA", (SYSCALL
)LoadLibraryA
, 0 },
844 { "LoadLibraryA", (SYSCALL
)0, 0 },
847 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
849 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
850 !defined(SQLITE_OMIT_LOAD_EXTENSION)
851 { "LoadLibraryW", (SYSCALL
)LoadLibraryW
, 0 },
853 { "LoadLibraryW", (SYSCALL
)0, 0 },
856 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
859 { "LocalFree", (SYSCALL
)LocalFree
, 0 },
861 { "LocalFree", (SYSCALL
)0, 0 },
864 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
866 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
867 { "LockFile", (SYSCALL
)LockFile
, 0 },
869 { "LockFile", (SYSCALL
)0, 0 },
873 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
874 DWORD))aSyscall[47].pCurrent)
878 { "LockFileEx", (SYSCALL
)LockFileEx
, 0 },
880 { "LockFileEx", (SYSCALL
)0, 0 },
884 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
885 LPOVERLAPPED))aSyscall[48].pCurrent)
888 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
889 (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
890 { "MapViewOfFile", (SYSCALL
)MapViewOfFile
, 0 },
892 { "MapViewOfFile", (SYSCALL
)0, 0 },
895 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
896 SIZE_T))aSyscall[49].pCurrent)
898 { "MultiByteToWideChar", (SYSCALL
)MultiByteToWideChar
, 0 },
900 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
901 int))aSyscall[50].pCurrent)
903 { "QueryPerformanceCounter", (SYSCALL
)QueryPerformanceCounter
, 0 },
905 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
906 LARGE_INTEGER*))aSyscall[51].pCurrent)
908 { "ReadFile", (SYSCALL
)ReadFile
, 0 },
910 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
911 LPOVERLAPPED))aSyscall[52].pCurrent)
913 { "SetEndOfFile", (SYSCALL
)SetEndOfFile
, 0 },
915 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
918 { "SetFilePointer", (SYSCALL
)SetFilePointer
, 0 },
920 { "SetFilePointer", (SYSCALL
)0, 0 },
923 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
924 DWORD))aSyscall[54].pCurrent)
927 { "Sleep", (SYSCALL
)Sleep
, 0 },
929 { "Sleep", (SYSCALL
)0, 0 },
932 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
934 { "SystemTimeToFileTime", (SYSCALL
)SystemTimeToFileTime
, 0 },
936 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
937 LPFILETIME))aSyscall[56].pCurrent)
939 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
940 { "UnlockFile", (SYSCALL
)UnlockFile
, 0 },
942 { "UnlockFile", (SYSCALL
)0, 0 },
946 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
947 DWORD))aSyscall[57].pCurrent)
951 { "UnlockFileEx", (SYSCALL
)UnlockFileEx
, 0 },
953 { "UnlockFileEx", (SYSCALL
)0, 0 },
956 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
957 LPOVERLAPPED))aSyscall[58].pCurrent)
959 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
960 { "UnmapViewOfFile", (SYSCALL
)UnmapViewOfFile
, 0 },
962 { "UnmapViewOfFile", (SYSCALL
)0, 0 },
965 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
967 { "WideCharToMultiByte", (SYSCALL
)WideCharToMultiByte
, 0 },
969 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
970 LPCSTR,LPBOOL))aSyscall[60].pCurrent)
972 { "WriteFile", (SYSCALL
)WriteFile
, 0 },
974 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
975 LPOVERLAPPED))aSyscall[61].pCurrent)
978 { "CreateEventExW", (SYSCALL
)CreateEventExW
, 0 },
980 { "CreateEventExW", (SYSCALL
)0, 0 },
983 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
984 DWORD,DWORD))aSyscall[62].pCurrent)
987 { "WaitForSingleObject", (SYSCALL
)WaitForSingleObject
, 0 },
989 { "WaitForSingleObject", (SYSCALL
)0, 0 },
992 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
993 DWORD))aSyscall[63].pCurrent)
996 { "WaitForSingleObjectEx", (SYSCALL
)WaitForSingleObjectEx
, 0 },
998 { "WaitForSingleObjectEx", (SYSCALL
)0, 0 },
1001 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
1002 BOOL))aSyscall[64].pCurrent)
1005 { "SetFilePointerEx", (SYSCALL
)SetFilePointerEx
, 0 },
1007 { "SetFilePointerEx", (SYSCALL
)0, 0 },
1010 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
1011 PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
1014 { "GetFileInformationByHandleEx", (SYSCALL
)GetFileInformationByHandleEx
, 0 },
1016 { "GetFileInformationByHandleEx", (SYSCALL
)0, 0 },
1019 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
1020 FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
1022 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
1023 { "MapViewOfFileFromApp", (SYSCALL
)MapViewOfFileFromApp
, 0 },
1025 { "MapViewOfFileFromApp", (SYSCALL
)0, 0 },
1028 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
1029 SIZE_T))aSyscall[67].pCurrent)
1032 { "CreateFile2", (SYSCALL
)CreateFile2
, 0 },
1034 { "CreateFile2", (SYSCALL
)0, 0 },
1037 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
1038 LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
1040 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
1041 { "LoadPackagedLibrary", (SYSCALL
)LoadPackagedLibrary
, 0 },
1043 { "LoadPackagedLibrary", (SYSCALL
)0, 0 },
1046 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
1047 DWORD))aSyscall[69].pCurrent)
1050 { "GetTickCount64", (SYSCALL
)GetTickCount64
, 0 },
1052 { "GetTickCount64", (SYSCALL
)0, 0 },
1055 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
1058 { "GetNativeSystemInfo", (SYSCALL
)GetNativeSystemInfo
, 0 },
1060 { "GetNativeSystemInfo", (SYSCALL
)0, 0 },
1063 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
1064 LPSYSTEM_INFO))aSyscall[71].pCurrent)
1066 #if defined(SQLITE_WIN32_HAS_ANSI)
1067 { "OutputDebugStringA", (SYSCALL
)OutputDebugStringA
, 0 },
1069 { "OutputDebugStringA", (SYSCALL
)0, 0 },
1072 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
1074 #if defined(SQLITE_WIN32_HAS_WIDE)
1075 { "OutputDebugStringW", (SYSCALL
)OutputDebugStringW
, 0 },
1077 { "OutputDebugStringW", (SYSCALL
)0, 0 },
1080 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
1082 { "GetProcessHeap", (SYSCALL
)GetProcessHeap
, 0 },
1084 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
1086 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
1087 { "CreateFileMappingFromApp", (SYSCALL
)CreateFileMappingFromApp
, 0 },
1089 { "CreateFileMappingFromApp", (SYSCALL
)0, 0 },
1092 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
1093 LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
1096 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
1097 ** is really just a macro that uses a compiler intrinsic (e.g. x64).
1098 ** So do not try to make this is into a redefinable interface.
1100 #if defined(InterlockedCompareExchange)
1101 { "InterlockedCompareExchange", (SYSCALL
)0, 0 },
1103 #define osInterlockedCompareExchange InterlockedCompareExchange
1105 { "InterlockedCompareExchange", (SYSCALL
)InterlockedCompareExchange
, 0 },
1107 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
1108 SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
1109 #endif /* defined(InterlockedCompareExchange) */
1111 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
1112 { "UuidCreate", (SYSCALL
)UuidCreate
, 0 },
1114 { "UuidCreate", (SYSCALL
)0, 0 },
1117 #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
1119 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
1120 { "UuidCreateSequential", (SYSCALL
)UuidCreateSequential
, 0 },
1122 { "UuidCreateSequential", (SYSCALL
)0, 0 },
1125 #define osUuidCreateSequential \
1126 ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
1128 #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
1129 { "FlushViewOfFile", (SYSCALL
)FlushViewOfFile
, 0 },
1131 { "FlushViewOfFile", (SYSCALL
)0, 0 },
1134 #define osFlushViewOfFile \
1135 ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
1137 }; /* End of the overrideable system calls */
1140 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
1141 ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
1142 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
1143 ** system call named zName.
1145 static int winSetSystemCall(
1146 sqlite3_vfs
*pNotUsed
, /* The VFS pointer. Not used */
1147 const char *zName
, /* Name of system call to override */
1148 sqlite3_syscall_ptr pNewFunc
/* Pointer to new system call value */
1151 int rc
= SQLITE_NOTFOUND
;
1153 UNUSED_PARAMETER(pNotUsed
);
1155 /* If no zName is given, restore all system calls to their default
1156 ** settings and return NULL
1159 for(i
=0; i
<sizeof(aSyscall
)/sizeof(aSyscall
[0]); i
++){
1160 if( aSyscall
[i
].pDefault
){
1161 aSyscall
[i
].pCurrent
= aSyscall
[i
].pDefault
;
1165 /* If zName is specified, operate on only the one system call
1168 for(i
=0; i
<sizeof(aSyscall
)/sizeof(aSyscall
[0]); i
++){
1169 if( strcmp(zName
, aSyscall
[i
].zName
)==0 ){
1170 if( aSyscall
[i
].pDefault
==0 ){
1171 aSyscall
[i
].pDefault
= aSyscall
[i
].pCurrent
;
1174 if( pNewFunc
==0 ) pNewFunc
= aSyscall
[i
].pDefault
;
1175 aSyscall
[i
].pCurrent
= pNewFunc
;
1184 ** Return the value of a system call. Return NULL if zName is not a
1185 ** recognized system call name. NULL is also returned if the system call
1186 ** is currently undefined.
1188 static sqlite3_syscall_ptr
winGetSystemCall(
1189 sqlite3_vfs
*pNotUsed
,
1194 UNUSED_PARAMETER(pNotUsed
);
1195 for(i
=0; i
<sizeof(aSyscall
)/sizeof(aSyscall
[0]); i
++){
1196 if( strcmp(zName
, aSyscall
[i
].zName
)==0 ) return aSyscall
[i
].pCurrent
;
1202 ** Return the name of the first system call after zName. If zName==NULL
1203 ** then return the name of the first system call. Return NULL if zName
1204 ** is the last system call or if zName is not the name of a valid
1207 static const char *winNextSystemCall(sqlite3_vfs
*p
, const char *zName
){
1210 UNUSED_PARAMETER(p
);
1212 for(i
=0; i
<ArraySize(aSyscall
)-1; i
++){
1213 if( strcmp(zName
, aSyscall
[i
].zName
)==0 ) break;
1216 for(i
++; i
<ArraySize(aSyscall
); i
++){
1217 if( aSyscall
[i
].pCurrent
!=0 ) return aSyscall
[i
].zName
;
1222 #ifdef SQLITE_WIN32_MALLOC
1224 ** If a Win32 native heap has been configured, this function will attempt to
1225 ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
1226 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
1227 ** "pnLargest" argument, if non-zero, will be used to return the size of the
1228 ** largest committed free block in the heap, in bytes.
1230 int sqlite3_win32_compact_heap(LPUINT pnLargest
){
1235 winMemAssertMagic();
1236 hHeap
= winMemGetHeap();
1238 assert( hHeap
!=INVALID_HANDLE_VALUE
);
1239 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1240 assert( osHeapValidate(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, NULL
) );
1242 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
1243 if( (nLargest
=osHeapCompact(hHeap
, SQLITE_WIN32_HEAP_FLAGS
))==0 ){
1244 DWORD lastErrno
= osGetLastError();
1245 if( lastErrno
==NO_ERROR
){
1246 sqlite3_log(SQLITE_NOMEM
, "failed to HeapCompact (no space), heap=%p",
1248 rc
= SQLITE_NOMEM_BKPT
;
1250 sqlite3_log(SQLITE_ERROR
, "failed to HeapCompact (%lu), heap=%p",
1251 osGetLastError(), (void*)hHeap
);
1256 sqlite3_log(SQLITE_NOTFOUND
, "failed to HeapCompact, heap=%p",
1258 rc
= SQLITE_NOTFOUND
;
1260 if( pnLargest
) *pnLargest
= nLargest
;
1265 ** If a Win32 native heap has been configured, this function will attempt to
1266 ** destroy and recreate it. If the Win32 native heap is not isolated and/or
1267 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
1268 ** be returned and no changes will be made to the Win32 native heap.
1270 int sqlite3_win32_reset_heap(){
1272 MUTEX_LOGIC( sqlite3_mutex
*pMaster
; ) /* The main static mutex */
1273 MUTEX_LOGIC( sqlite3_mutex
*pMem
; ) /* The memsys static mutex */
1274 MUTEX_LOGIC( pMaster
= sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER
); )
1275 MUTEX_LOGIC( pMem
= sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM
); )
1276 sqlite3_mutex_enter(pMaster
);
1277 sqlite3_mutex_enter(pMem
);
1278 winMemAssertMagic();
1279 if( winMemGetHeap()!=NULL
&& winMemGetOwned() && sqlite3_memory_used()==0 ){
1281 ** At this point, there should be no outstanding memory allocations on
1282 ** the heap. Also, since both the master and memsys locks are currently
1283 ** being held by us, no other function (i.e. from another thread) should
1284 ** be able to even access the heap. Attempt to destroy and recreate our
1285 ** isolated Win32 native heap now.
1287 assert( winMemGetHeap()!=NULL
);
1288 assert( winMemGetOwned() );
1289 assert( sqlite3_memory_used()==0 );
1290 winMemShutdown(winMemGetDataPtr());
1291 assert( winMemGetHeap()==NULL
);
1292 assert( !winMemGetOwned() );
1293 assert( sqlite3_memory_used()==0 );
1294 rc
= winMemInit(winMemGetDataPtr());
1295 assert( rc
!=SQLITE_OK
|| winMemGetHeap()!=NULL
);
1296 assert( rc
!=SQLITE_OK
|| winMemGetOwned() );
1297 assert( rc
!=SQLITE_OK
|| sqlite3_memory_used()==0 );
1300 ** The Win32 native heap cannot be modified because it may be in use.
1304 sqlite3_mutex_leave(pMem
);
1305 sqlite3_mutex_leave(pMaster
);
1308 #endif /* SQLITE_WIN32_MALLOC */
1311 ** This function outputs the specified (ANSI) string to the Win32 debugger
1315 void sqlite3_win32_write_debug(const char *zBuf
, int nBuf
){
1316 char zDbgBuf
[SQLITE_WIN32_DBG_BUF_SIZE
];
1317 int nMin
= MIN(nBuf
, (SQLITE_WIN32_DBG_BUF_SIZE
- 1)); /* may be negative. */
1318 if( nMin
<-1 ) nMin
= -1; /* all negative values become -1. */
1319 assert( nMin
==-1 || nMin
==0 || nMin
<SQLITE_WIN32_DBG_BUF_SIZE
);
1320 #ifdef SQLITE_ENABLE_API_ARMOR
1322 (void)SQLITE_MISUSE_BKPT
;
1326 #if defined(SQLITE_WIN32_HAS_ANSI)
1328 memset(zDbgBuf
, 0, SQLITE_WIN32_DBG_BUF_SIZE
);
1329 memcpy(zDbgBuf
, zBuf
, nMin
);
1330 osOutputDebugStringA(zDbgBuf
);
1332 osOutputDebugStringA(zBuf
);
1334 #elif defined(SQLITE_WIN32_HAS_WIDE)
1335 memset(zDbgBuf
, 0, SQLITE_WIN32_DBG_BUF_SIZE
);
1336 if ( osMultiByteToWideChar(
1337 osAreFileApisANSI() ? CP_ACP
: CP_OEMCP
, 0, zBuf
,
1338 nMin
, (LPWSTR
)zDbgBuf
, SQLITE_WIN32_DBG_BUF_SIZE
/sizeof(WCHAR
))<=0 ){
1341 osOutputDebugStringW((LPCWSTR
)zDbgBuf
);
1344 memset(zDbgBuf
, 0, SQLITE_WIN32_DBG_BUF_SIZE
);
1345 memcpy(zDbgBuf
, zBuf
, nMin
);
1346 fprintf(stderr
, "%s", zDbgBuf
);
1348 fprintf(stderr
, "%s", zBuf
);
1354 ** The following routine suspends the current thread for at least ms
1355 ** milliseconds. This is equivalent to the Win32 Sleep() interface.
1358 static HANDLE sleepObj
= NULL
;
1361 void sqlite3_win32_sleep(DWORD milliseconds
){
1363 if ( sleepObj
==NULL
){
1364 sleepObj
= osCreateEventExW(NULL
, NULL
, CREATE_EVENT_MANUAL_RESET
,
1367 assert( sleepObj
!=NULL
);
1368 osWaitForSingleObjectEx(sleepObj
, milliseconds
, FALSE
);
1370 osSleep(milliseconds
);
1374 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
1376 DWORD
sqlite3Win32Wait(HANDLE hObject
){
1378 while( (rc
= osWaitForSingleObjectEx(hObject
, INFINITE
,
1379 TRUE
))==WAIT_IO_COMPLETION
){}
1385 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
1386 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
1388 ** Here is an interesting observation: Win95, Win98, and WinME lack
1389 ** the LockFileEx() API. But we can still statically link against that
1390 ** API as long as we don't call it when running Win95/98/ME. A call to
1391 ** this routine is used to determine if the host is Win95/98/ME or
1392 ** WinNT/2K/XP so that we will know whether or not we can safely call
1393 ** the LockFileEx() API.
1396 #if !SQLITE_WIN32_GETVERSIONEX
1397 # define osIsNT() (1)
1398 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
1399 # define osIsNT() (1)
1400 #elif !defined(SQLITE_WIN32_HAS_WIDE)
1401 # define osIsNT() (0)
1403 # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
1407 ** This function determines if the machine is running a version of Windows
1408 ** based on the NT kernel.
1410 int sqlite3_win32_is_nt(void){
1413 ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
1417 #elif SQLITE_WIN32_GETVERSIONEX
1418 if( osInterlockedCompareExchange(&sqlite3_os_type
, 0, 0)==0 ){
1419 #if defined(SQLITE_WIN32_HAS_ANSI)
1420 OSVERSIONINFOA sInfo
;
1421 sInfo
.dwOSVersionInfoSize
= sizeof(sInfo
);
1422 osGetVersionExA(&sInfo
);
1423 osInterlockedCompareExchange(&sqlite3_os_type
,
1424 (sInfo
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) ? 2 : 1, 0);
1425 #elif defined(SQLITE_WIN32_HAS_WIDE)
1426 OSVERSIONINFOW sInfo
;
1427 sInfo
.dwOSVersionInfoSize
= sizeof(sInfo
);
1428 osGetVersionExW(&sInfo
);
1429 osInterlockedCompareExchange(&sqlite3_os_type
,
1430 (sInfo
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) ? 2 : 1, 0);
1433 return osInterlockedCompareExchange(&sqlite3_os_type
, 2, 2)==2;
1435 return osInterlockedCompareExchange(&sqlite3_os_type
, 2, 2)==2;
1438 ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
1439 ** deprecated are always assumed to be based on the NT kernel.
1445 #ifdef SQLITE_WIN32_MALLOC
1447 ** Allocate nBytes of memory.
1449 static void *winMemMalloc(int nBytes
){
1453 winMemAssertMagic();
1454 hHeap
= winMemGetHeap();
1456 assert( hHeap
!=INVALID_HANDLE_VALUE
);
1457 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1458 assert( osHeapValidate(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, NULL
) );
1460 assert( nBytes
>=0 );
1461 p
= osHeapAlloc(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, (SIZE_T
)nBytes
);
1463 sqlite3_log(SQLITE_NOMEM
, "failed to HeapAlloc %u bytes (%lu), heap=%p",
1464 nBytes
, osGetLastError(), (void*)hHeap
);
1472 static void winMemFree(void *pPrior
){
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
, pPrior
) );
1482 if( !pPrior
) return; /* Passing NULL to HeapFree is undefined. */
1483 if( !osHeapFree(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, pPrior
) ){
1484 sqlite3_log(SQLITE_NOMEM
, "failed to HeapFree block %p (%lu), heap=%p",
1485 pPrior
, osGetLastError(), (void*)hHeap
);
1490 ** Change the size of an existing memory allocation
1492 static void *winMemRealloc(void *pPrior
, int nBytes
){
1496 winMemAssertMagic();
1497 hHeap
= winMemGetHeap();
1499 assert( hHeap
!=INVALID_HANDLE_VALUE
);
1500 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1501 assert( osHeapValidate(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, pPrior
) );
1503 assert( nBytes
>=0 );
1505 p
= osHeapAlloc(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, (SIZE_T
)nBytes
);
1507 p
= osHeapReAlloc(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, pPrior
, (SIZE_T
)nBytes
);
1510 sqlite3_log(SQLITE_NOMEM
, "failed to %s %u bytes (%lu), heap=%p",
1511 pPrior
? "HeapReAlloc" : "HeapAlloc", nBytes
, osGetLastError(),
1518 ** Return the size of an outstanding allocation, in bytes.
1520 static int winMemSize(void *p
){
1524 winMemAssertMagic();
1525 hHeap
= winMemGetHeap();
1527 assert( hHeap
!=INVALID_HANDLE_VALUE
);
1528 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1529 assert( osHeapValidate(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, p
) );
1532 n
= osHeapSize(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, p
);
1533 if( n
==(SIZE_T
)-1 ){
1534 sqlite3_log(SQLITE_NOMEM
, "failed to HeapSize block %p (%lu), heap=%p",
1535 p
, osGetLastError(), (void*)hHeap
);
1542 ** Round up a request size to the next valid allocation size.
1544 static int winMemRoundup(int n
){
1549 ** Initialize this module.
1551 static int winMemInit(void *pAppData
){
1552 winMemData
*pWinMemData
= (winMemData
*)pAppData
;
1554 if( !pWinMemData
) return SQLITE_ERROR
;
1555 assert( pWinMemData
->magic1
==WINMEM_MAGIC1
);
1556 assert( pWinMemData
->magic2
==WINMEM_MAGIC2
);
1558 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
1559 if( !pWinMemData
->hHeap
){
1560 DWORD dwInitialSize
= SQLITE_WIN32_HEAP_INIT_SIZE
;
1561 DWORD dwMaximumSize
= (DWORD
)sqlite3GlobalConfig
.nHeap
;
1562 if( dwMaximumSize
==0 ){
1563 dwMaximumSize
= SQLITE_WIN32_HEAP_MAX_SIZE
;
1564 }else if( dwInitialSize
>dwMaximumSize
){
1565 dwInitialSize
= dwMaximumSize
;
1567 pWinMemData
->hHeap
= osHeapCreate(SQLITE_WIN32_HEAP_FLAGS
,
1568 dwInitialSize
, dwMaximumSize
);
1569 if( !pWinMemData
->hHeap
){
1570 sqlite3_log(SQLITE_NOMEM
,
1571 "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
1572 osGetLastError(), SQLITE_WIN32_HEAP_FLAGS
, dwInitialSize
,
1574 return SQLITE_NOMEM_BKPT
;
1576 pWinMemData
->bOwned
= TRUE
;
1577 assert( pWinMemData
->bOwned
);
1580 pWinMemData
->hHeap
= osGetProcessHeap();
1581 if( !pWinMemData
->hHeap
){
1582 sqlite3_log(SQLITE_NOMEM
,
1583 "failed to GetProcessHeap (%lu)", osGetLastError());
1584 return SQLITE_NOMEM_BKPT
;
1586 pWinMemData
->bOwned
= FALSE
;
1587 assert( !pWinMemData
->bOwned
);
1589 assert( pWinMemData
->hHeap
!=0 );
1590 assert( pWinMemData
->hHeap
!=INVALID_HANDLE_VALUE
);
1591 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1592 assert( osHeapValidate(pWinMemData
->hHeap
, SQLITE_WIN32_HEAP_FLAGS
, NULL
) );
1598 ** Deinitialize this module.
1600 static void winMemShutdown(void *pAppData
){
1601 winMemData
*pWinMemData
= (winMemData
*)pAppData
;
1603 if( !pWinMemData
) return;
1604 assert( pWinMemData
->magic1
==WINMEM_MAGIC1
);
1605 assert( pWinMemData
->magic2
==WINMEM_MAGIC2
);
1607 if( pWinMemData
->hHeap
){
1608 assert( pWinMemData
->hHeap
!=INVALID_HANDLE_VALUE
);
1609 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1610 assert( osHeapValidate(pWinMemData
->hHeap
, SQLITE_WIN32_HEAP_FLAGS
, NULL
) );
1612 if( pWinMemData
->bOwned
){
1613 if( !osHeapDestroy(pWinMemData
->hHeap
) ){
1614 sqlite3_log(SQLITE_NOMEM
, "failed to HeapDestroy (%lu), heap=%p",
1615 osGetLastError(), (void*)pWinMemData
->hHeap
);
1617 pWinMemData
->bOwned
= FALSE
;
1619 pWinMemData
->hHeap
= NULL
;
1624 ** Populate the low-level memory allocation function pointers in
1625 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
1626 ** arguments specify the block of memory to manage.
1628 ** This routine is only called by sqlite3_config(), and therefore
1629 ** is not required to be threadsafe (it is not).
1631 const sqlite3_mem_methods
*sqlite3MemGetWin32(void){
1632 static const sqlite3_mem_methods winMemMethods
= {
1642 return &winMemMethods
;
1645 void sqlite3MemSetDefault(void){
1646 sqlite3_config(SQLITE_CONFIG_MALLOC
, sqlite3MemGetWin32());
1648 #endif /* SQLITE_WIN32_MALLOC */
1651 ** Convert a UTF-8 string to Microsoft Unicode.
1653 ** Space to hold the returned string is obtained from sqlite3_malloc().
1655 static LPWSTR
winUtf8ToUnicode(const char *zText
){
1659 nChar
= osMultiByteToWideChar(CP_UTF8
, 0, zText
, -1, NULL
, 0);
1663 zWideText
= sqlite3MallocZero( nChar
*sizeof(WCHAR
) );
1667 nChar
= osMultiByteToWideChar(CP_UTF8
, 0, zText
, -1, zWideText
,
1670 sqlite3_free(zWideText
);
1677 ** Convert a Microsoft Unicode string to UTF-8.
1679 ** Space to hold the returned string is obtained from sqlite3_malloc().
1681 static char *winUnicodeToUtf8(LPCWSTR zWideText
){
1685 nByte
= osWideCharToMultiByte(CP_UTF8
, 0, zWideText
, -1, 0, 0, 0, 0);
1689 zText
= sqlite3MallocZero( nByte
);
1693 nByte
= osWideCharToMultiByte(CP_UTF8
, 0, zWideText
, -1, zText
, nByte
,
1696 sqlite3_free(zText
);
1703 ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
1706 ** Space to hold the returned string is obtained from sqlite3_malloc().
1708 static LPWSTR
winMbcsToUnicode(const char *zText
, int useAnsi
){
1711 int codepage
= useAnsi
? CP_ACP
: CP_OEMCP
;
1713 nByte
= osMultiByteToWideChar(codepage
, 0, zText
, -1, NULL
,
1718 zMbcsText
= sqlite3MallocZero( nByte
*sizeof(WCHAR
) );
1722 nByte
= osMultiByteToWideChar(codepage
, 0, zText
, -1, zMbcsText
,
1725 sqlite3_free(zMbcsText
);
1732 ** Convert a Microsoft Unicode string to a multi-byte character string,
1733 ** using the ANSI or OEM code page.
1735 ** Space to hold the returned string is obtained from sqlite3_malloc().
1737 static char *winUnicodeToMbcs(LPCWSTR zWideText
, int useAnsi
){
1740 int codepage
= useAnsi
? CP_ACP
: CP_OEMCP
;
1742 nByte
= osWideCharToMultiByte(codepage
, 0, zWideText
, -1, 0, 0, 0, 0);
1746 zText
= sqlite3MallocZero( nByte
);
1750 nByte
= osWideCharToMultiByte(codepage
, 0, zWideText
, -1, zText
,
1753 sqlite3_free(zText
);
1760 ** Convert a multi-byte character string to UTF-8.
1762 ** Space to hold the returned string is obtained from sqlite3_malloc().
1764 static char *winMbcsToUtf8(const char *zText
, int useAnsi
){
1768 zTmpWide
= winMbcsToUnicode(zText
, useAnsi
);
1772 zTextUtf8
= winUnicodeToUtf8(zTmpWide
);
1773 sqlite3_free(zTmpWide
);
1778 ** Convert a UTF-8 string to a multi-byte character string.
1780 ** Space to hold the returned string is obtained from sqlite3_malloc().
1782 static char *winUtf8ToMbcs(const char *zText
, int useAnsi
){
1786 zTmpWide
= winUtf8ToUnicode(zText
);
1790 zTextMbcs
= winUnicodeToMbcs(zTmpWide
, useAnsi
);
1791 sqlite3_free(zTmpWide
);
1796 ** This is a public wrapper for the winUtf8ToUnicode() function.
1798 LPWSTR
sqlite3_win32_utf8_to_unicode(const char *zText
){
1799 #ifdef SQLITE_ENABLE_API_ARMOR
1801 (void)SQLITE_MISUSE_BKPT
;
1805 #ifndef SQLITE_OMIT_AUTOINIT
1806 if( sqlite3_initialize() ) return 0;
1808 return winUtf8ToUnicode(zText
);
1812 ** This is a public wrapper for the winUnicodeToUtf8() function.
1814 char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText
){
1815 #ifdef SQLITE_ENABLE_API_ARMOR
1817 (void)SQLITE_MISUSE_BKPT
;
1821 #ifndef SQLITE_OMIT_AUTOINIT
1822 if( sqlite3_initialize() ) return 0;
1824 return winUnicodeToUtf8(zWideText
);
1828 ** This is a public wrapper for the winMbcsToUtf8() function.
1830 char *sqlite3_win32_mbcs_to_utf8(const char *zText
){
1831 #ifdef SQLITE_ENABLE_API_ARMOR
1833 (void)SQLITE_MISUSE_BKPT
;
1837 #ifndef SQLITE_OMIT_AUTOINIT
1838 if( sqlite3_initialize() ) return 0;
1840 return winMbcsToUtf8(zText
, osAreFileApisANSI());
1844 ** This is a public wrapper for the winMbcsToUtf8() function.
1846 char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText
, int useAnsi
){
1847 #ifdef SQLITE_ENABLE_API_ARMOR
1849 (void)SQLITE_MISUSE_BKPT
;
1853 #ifndef SQLITE_OMIT_AUTOINIT
1854 if( sqlite3_initialize() ) return 0;
1856 return winMbcsToUtf8(zText
, useAnsi
);
1860 ** This is a public wrapper for the winUtf8ToMbcs() function.
1862 char *sqlite3_win32_utf8_to_mbcs(const char *zText
){
1863 #ifdef SQLITE_ENABLE_API_ARMOR
1865 (void)SQLITE_MISUSE_BKPT
;
1869 #ifndef SQLITE_OMIT_AUTOINIT
1870 if( sqlite3_initialize() ) return 0;
1872 return winUtf8ToMbcs(zText
, osAreFileApisANSI());
1876 ** This is a public wrapper for the winUtf8ToMbcs() function.
1878 char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText
, int useAnsi
){
1879 #ifdef SQLITE_ENABLE_API_ARMOR
1881 (void)SQLITE_MISUSE_BKPT
;
1885 #ifndef SQLITE_OMIT_AUTOINIT
1886 if( sqlite3_initialize() ) return 0;
1888 return winUtf8ToMbcs(zText
, useAnsi
);
1892 ** This function sets the data directory or the temporary directory based on
1893 ** the provided arguments. The type argument must be 1 in order to set the
1894 ** data directory or 2 in order to set the temporary directory. The zValue
1895 ** argument is the name of the directory to use. The return value will be
1896 ** SQLITE_OK if successful.
1898 int sqlite3_win32_set_directory(DWORD type
, LPCWSTR zValue
){
1899 char **ppDirectory
= 0;
1900 #ifndef SQLITE_OMIT_AUTOINIT
1901 int rc
= sqlite3_initialize();
1904 if( type
==SQLITE_WIN32_DATA_DIRECTORY_TYPE
){
1905 ppDirectory
= &sqlite3_data_directory
;
1906 }else if( type
==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
){
1907 ppDirectory
= &sqlite3_temp_directory
;
1909 assert( !ppDirectory
|| type
==SQLITE_WIN32_DATA_DIRECTORY_TYPE
1910 || type
==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
1912 assert( !ppDirectory
|| sqlite3MemdebugHasType(*ppDirectory
, MEMTYPE_HEAP
) );
1914 char *zValueUtf8
= 0;
1915 if( zValue
&& zValue
[0] ){
1916 zValueUtf8
= winUnicodeToUtf8(zValue
);
1917 if ( zValueUtf8
==0 ){
1918 return SQLITE_NOMEM_BKPT
;
1921 sqlite3_free(*ppDirectory
);
1922 *ppDirectory
= zValueUtf8
;
1925 return SQLITE_ERROR
;
1929 ** The return value of winGetLastErrorMsg
1930 ** is zero if the error message fits in the buffer, or non-zero
1931 ** otherwise (if the message was truncated).
1933 static int winGetLastErrorMsg(DWORD lastErrno
, int nBuf
, char *zBuf
){
1934 /* FormatMessage returns 0 on failure. Otherwise it
1935 ** returns the number of TCHARs written to the output
1936 ** buffer, excluding the terminating null char.
1943 WCHAR zTempWide
[SQLITE_WIN32_MAX_ERRMSG_CHARS
+1];
1944 dwLen
= osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM
|
1945 FORMAT_MESSAGE_IGNORE_INSERTS
,
1950 SQLITE_WIN32_MAX_ERRMSG_CHARS
,
1953 LPWSTR zTempWide
= NULL
;
1954 dwLen
= osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1955 FORMAT_MESSAGE_FROM_SYSTEM
|
1956 FORMAT_MESSAGE_IGNORE_INSERTS
,
1960 (LPWSTR
) &zTempWide
,
1965 /* allocate a buffer and convert to UTF8 */
1966 sqlite3BeginBenignMalloc();
1967 zOut
= winUnicodeToUtf8(zTempWide
);
1968 sqlite3EndBenignMalloc();
1969 #if !SQLITE_OS_WINRT
1970 /* free the system buffer allocated by FormatMessage */
1971 osLocalFree(zTempWide
);
1975 #ifdef SQLITE_WIN32_HAS_ANSI
1978 dwLen
= osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1979 FORMAT_MESSAGE_FROM_SYSTEM
|
1980 FORMAT_MESSAGE_IGNORE_INSERTS
,
1988 /* allocate a buffer and convert to UTF8 */
1989 sqlite3BeginBenignMalloc();
1990 zOut
= winMbcsToUtf8(zTemp
, osAreFileApisANSI());
1991 sqlite3EndBenignMalloc();
1992 /* free the system buffer allocated by FormatMessage */
1998 sqlite3_snprintf(nBuf
, zBuf
, "OsError 0x%lx (%lu)", lastErrno
, lastErrno
);
2000 /* copy a maximum of nBuf chars to output buffer */
2001 sqlite3_snprintf(nBuf
, zBuf
, "%s", zOut
);
2002 /* free the UTF8 buffer */
2010 ** This function - winLogErrorAtLine() - is only ever called via the macro
2013 ** This routine is invoked after an error occurs in an OS function.
2014 ** It logs a message using sqlite3_log() containing the current value of
2015 ** error code and, if possible, the human-readable equivalent from
2018 ** The first argument passed to the macro should be the error code that
2019 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
2020 ** The two subsequent arguments should be the name of the OS function that
2021 ** failed and the associated file-system path, if any.
2023 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
2024 static int winLogErrorAtLine(
2025 int errcode
, /* SQLite error code */
2026 DWORD lastErrno
, /* Win32 last error */
2027 const char *zFunc
, /* Name of OS function that failed */
2028 const char *zPath
, /* File path associated with error */
2029 int iLine
/* Source line number where error occurred */
2031 char zMsg
[500]; /* Human readable error text */
2032 int i
; /* Loop counter */
2035 winGetLastErrorMsg(lastErrno
, sizeof(zMsg
), zMsg
);
2036 assert( errcode
!=SQLITE_OK
);
2037 if( zPath
==0 ) zPath
= "";
2038 for(i
=0; zMsg
[i
] && zMsg
[i
]!='\r' && zMsg
[i
]!='\n'; i
++){}
2040 sqlite3_log(errcode
,
2041 "os_win.c:%d: (%lu) %s(%s) - %s",
2042 iLine
, lastErrno
, zFunc
, zPath
, zMsg
2049 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
2050 ** will be retried following a locking error - probably caused by
2051 ** antivirus software. Also the initial delay before the first retry.
2052 ** The delay increases linearly with each retry.
2054 #ifndef SQLITE_WIN32_IOERR_RETRY
2055 # define SQLITE_WIN32_IOERR_RETRY 10
2057 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
2058 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
2060 static int winIoerrRetry
= SQLITE_WIN32_IOERR_RETRY
;
2061 static int winIoerrRetryDelay
= SQLITE_WIN32_IOERR_RETRY_DELAY
;
2064 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
2065 ** error code obtained via GetLastError() is eligible to be retried. It
2066 ** must accept the error code DWORD as its only argument and should return
2067 ** non-zero if the error code is transient in nature and the operation
2068 ** responsible for generating the original error might succeed upon being
2069 ** retried. The argument to this macro should be a variable.
2071 ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
2072 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
2073 ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
2074 ** may be used to include additional error codes in the set that should
2075 ** result in the failing I/O operation being retried by the caller. If
2076 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
2077 ** identical to those of the "winIoerrCanRetry1" macro.
2079 #if !defined(winIoerrCanRetry1)
2080 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
2081 ((a)==ERROR_SHARING_VIOLATION) || \
2082 ((a)==ERROR_LOCK_VIOLATION) || \
2083 ((a)==ERROR_DEV_NOT_EXIST) || \
2084 ((a)==ERROR_NETNAME_DELETED) || \
2085 ((a)==ERROR_SEM_TIMEOUT) || \
2086 ((a)==ERROR_NETWORK_UNREACHABLE))
2090 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
2091 ** to see if it should be retried. Return TRUE to retry. Return FALSE
2092 ** to give up with an error.
2094 static int winRetryIoerr(int *pnRetry
, DWORD
*pError
){
2095 DWORD e
= osGetLastError();
2096 if( *pnRetry
>=winIoerrRetry
){
2102 if( winIoerrCanRetry1(e
) ){
2103 sqlite3_win32_sleep(winIoerrRetryDelay
*(1+*pnRetry
));
2107 #if defined(winIoerrCanRetry2)
2108 else if( winIoerrCanRetry2(e
) ){
2109 sqlite3_win32_sleep(winIoerrRetryDelay
*(1+*pnRetry
));
2121 ** Log a I/O error retry episode.
2123 static void winLogIoerr(int nRetry
, int lineno
){
2125 sqlite3_log(SQLITE_NOTICE
,
2126 "delayed %dms for lock/sharing conflict at line %d",
2127 winIoerrRetryDelay
*nRetry
*(nRetry
+1)/2, lineno
2133 ** This #if does not rely on the SQLITE_OS_WINCE define because the
2134 ** corresponding section in "date.c" cannot use it.
2136 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
2137 (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
2139 ** The MSVC CRT on Windows CE may not have a localtime() function.
2140 ** So define a substitute.
2143 struct tm
*__cdecl
localtime(const time_t *t
)
2150 t64
= (t64
+ 11644473600)*10000000;
2151 uTm
.dwLowDateTime
= (DWORD
)(t64
& 0xFFFFFFFF);
2152 uTm
.dwHighDateTime
= (DWORD
)(t64
>> 32);
2153 osFileTimeToLocalFileTime(&uTm
,&lTm
);
2154 osFileTimeToSystemTime(&lTm
,&pTm
);
2155 y
.tm_year
= pTm
.wYear
- 1900;
2156 y
.tm_mon
= pTm
.wMonth
- 1;
2157 y
.tm_wday
= pTm
.wDayOfWeek
;
2158 y
.tm_mday
= pTm
.wDay
;
2159 y
.tm_hour
= pTm
.wHour
;
2160 y
.tm_min
= pTm
.wMinute
;
2161 y
.tm_sec
= pTm
.wSecond
;
2167 /*************************************************************************
2168 ** This section contains code for WinCE only.
2170 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
2173 ** Acquire a lock on the handle h
2175 static void winceMutexAcquire(HANDLE h
){
2178 dwErr
= osWaitForSingleObject(h
, INFINITE
);
2179 } while (dwErr
!= WAIT_OBJECT_0
&& dwErr
!= WAIT_ABANDONED
);
2182 ** Release a lock acquired by winceMutexAcquire()
2184 #define winceMutexRelease(h) ReleaseMutex(h)
2187 ** Create the mutex and shared memory used for locking in the file
2190 static int winceCreateLock(const char *zFilename
, winFile
*pFile
){
2194 BOOL bLogged
= FALSE
;
2197 zName
= winUtf8ToUnicode(zFilename
);
2200 return SQLITE_IOERR_NOMEM_BKPT
;
2203 /* Initialize the local lockdata */
2204 memset(&pFile
->local
, 0, sizeof(pFile
->local
));
2206 /* Replace the backslashes from the filename and lowercase it
2207 ** to derive a mutex name. */
2208 zTok
= osCharLowerW(zName
);
2209 for (;*zTok
;zTok
++){
2210 if (*zTok
== '\\') *zTok
= '_';
2213 /* Create/open the named mutex */
2214 pFile
->hMutex
= osCreateMutexW(NULL
, FALSE
, zName
);
2215 if (!pFile
->hMutex
){
2216 pFile
->lastErrno
= osGetLastError();
2217 sqlite3_free(zName
);
2218 return winLogError(SQLITE_IOERR
, pFile
->lastErrno
,
2219 "winceCreateLock1", zFilename
);
2222 /* Acquire the mutex before continuing */
2223 winceMutexAcquire(pFile
->hMutex
);
2225 /* Since the names of named mutexes, semaphores, file mappings etc are
2226 ** case-sensitive, take advantage of that by uppercasing the mutex name
2227 ** and using that as the shared filemapping name.
2229 osCharUpperW(zName
);
2230 pFile
->hShared
= osCreateFileMappingW(INVALID_HANDLE_VALUE
, NULL
,
2231 PAGE_READWRITE
, 0, sizeof(winceLock
),
2234 /* Set a flag that indicates we're the first to create the memory so it
2235 ** must be zero-initialized */
2236 lastErrno
= osGetLastError();
2237 if (lastErrno
== ERROR_ALREADY_EXISTS
){
2241 sqlite3_free(zName
);
2243 /* If we succeeded in making the shared memory handle, map it. */
2244 if( pFile
->hShared
){
2245 pFile
->shared
= (winceLock
*)osMapViewOfFile(pFile
->hShared
,
2246 FILE_MAP_READ
|FILE_MAP_WRITE
, 0, 0, sizeof(winceLock
));
2247 /* If mapping failed, close the shared memory handle and erase it */
2248 if( !pFile
->shared
){
2249 pFile
->lastErrno
= osGetLastError();
2250 winLogError(SQLITE_IOERR
, pFile
->lastErrno
,
2251 "winceCreateLock2", zFilename
);
2253 osCloseHandle(pFile
->hShared
);
2254 pFile
->hShared
= NULL
;
2258 /* If shared memory could not be created, then close the mutex and fail */
2259 if( pFile
->hShared
==NULL
){
2261 pFile
->lastErrno
= lastErrno
;
2262 winLogError(SQLITE_IOERR
, pFile
->lastErrno
,
2263 "winceCreateLock3", zFilename
);
2266 winceMutexRelease(pFile
->hMutex
);
2267 osCloseHandle(pFile
->hMutex
);
2268 pFile
->hMutex
= NULL
;
2269 return SQLITE_IOERR
;
2272 /* Initialize the shared memory if we're supposed to */
2274 memset(pFile
->shared
, 0, sizeof(winceLock
));
2277 winceMutexRelease(pFile
->hMutex
);
2282 ** Destroy the part of winFile that deals with wince locks
2284 static void winceDestroyLock(winFile
*pFile
){
2286 /* Acquire the mutex */
2287 winceMutexAcquire(pFile
->hMutex
);
2289 /* The following blocks should probably assert in debug mode, but they
2290 are to cleanup in case any locks remained open */
2291 if (pFile
->local
.nReaders
){
2292 pFile
->shared
->nReaders
--;
2294 if (pFile
->local
.bReserved
){
2295 pFile
->shared
->bReserved
= FALSE
;
2297 if (pFile
->local
.bPending
){
2298 pFile
->shared
->bPending
= FALSE
;
2300 if (pFile
->local
.bExclusive
){
2301 pFile
->shared
->bExclusive
= FALSE
;
2304 /* De-reference and close our copy of the shared memory handle */
2305 osUnmapViewOfFile(pFile
->shared
);
2306 osCloseHandle(pFile
->hShared
);
2308 /* Done with the mutex */
2309 winceMutexRelease(pFile
->hMutex
);
2310 osCloseHandle(pFile
->hMutex
);
2311 pFile
->hMutex
= NULL
;
2316 ** An implementation of the LockFile() API of Windows for CE
2318 static BOOL
winceLockFile(
2320 DWORD dwFileOffsetLow
,
2321 DWORD dwFileOffsetHigh
,
2322 DWORD nNumberOfBytesToLockLow
,
2323 DWORD nNumberOfBytesToLockHigh
2325 winFile
*pFile
= HANDLE_TO_WINFILE(phFile
);
2326 BOOL bReturn
= FALSE
;
2328 UNUSED_PARAMETER(dwFileOffsetHigh
);
2329 UNUSED_PARAMETER(nNumberOfBytesToLockHigh
);
2331 if (!pFile
->hMutex
) return TRUE
;
2332 winceMutexAcquire(pFile
->hMutex
);
2334 /* Wanting an exclusive lock? */
2335 if (dwFileOffsetLow
== (DWORD
)SHARED_FIRST
2336 && nNumberOfBytesToLockLow
== (DWORD
)SHARED_SIZE
){
2337 if (pFile
->shared
->nReaders
== 0 && pFile
->shared
->bExclusive
== 0){
2338 pFile
->shared
->bExclusive
= TRUE
;
2339 pFile
->local
.bExclusive
= TRUE
;
2344 /* Want a read-only lock? */
2345 else if (dwFileOffsetLow
== (DWORD
)SHARED_FIRST
&&
2346 nNumberOfBytesToLockLow
== 1){
2347 if (pFile
->shared
->bExclusive
== 0){
2348 pFile
->local
.nReaders
++;
2349 if (pFile
->local
.nReaders
== 1){
2350 pFile
->shared
->nReaders
++;
2356 /* Want a pending lock? */
2357 else if (dwFileOffsetLow
== (DWORD
)PENDING_BYTE
2358 && nNumberOfBytesToLockLow
== 1){
2359 /* If no pending lock has been acquired, then acquire it */
2360 if (pFile
->shared
->bPending
== 0) {
2361 pFile
->shared
->bPending
= TRUE
;
2362 pFile
->local
.bPending
= TRUE
;
2367 /* Want a reserved lock? */
2368 else if (dwFileOffsetLow
== (DWORD
)RESERVED_BYTE
2369 && nNumberOfBytesToLockLow
== 1){
2370 if (pFile
->shared
->bReserved
== 0) {
2371 pFile
->shared
->bReserved
= TRUE
;
2372 pFile
->local
.bReserved
= TRUE
;
2377 winceMutexRelease(pFile
->hMutex
);
2382 ** An implementation of the UnlockFile API of Windows for CE
2384 static BOOL
winceUnlockFile(
2386 DWORD dwFileOffsetLow
,
2387 DWORD dwFileOffsetHigh
,
2388 DWORD nNumberOfBytesToUnlockLow
,
2389 DWORD nNumberOfBytesToUnlockHigh
2391 winFile
*pFile
= HANDLE_TO_WINFILE(phFile
);
2392 BOOL bReturn
= FALSE
;
2394 UNUSED_PARAMETER(dwFileOffsetHigh
);
2395 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh
);
2397 if (!pFile
->hMutex
) return TRUE
;
2398 winceMutexAcquire(pFile
->hMutex
);
2400 /* Releasing a reader lock or an exclusive lock */
2401 if (dwFileOffsetLow
== (DWORD
)SHARED_FIRST
){
2402 /* Did we have an exclusive lock? */
2403 if (pFile
->local
.bExclusive
){
2404 assert(nNumberOfBytesToUnlockLow
== (DWORD
)SHARED_SIZE
);
2405 pFile
->local
.bExclusive
= FALSE
;
2406 pFile
->shared
->bExclusive
= FALSE
;
2410 /* Did we just have a reader lock? */
2411 else if (pFile
->local
.nReaders
){
2412 assert(nNumberOfBytesToUnlockLow
== (DWORD
)SHARED_SIZE
2413 || nNumberOfBytesToUnlockLow
== 1);
2414 pFile
->local
.nReaders
--;
2415 if (pFile
->local
.nReaders
== 0)
2417 pFile
->shared
->nReaders
--;
2423 /* Releasing a pending lock */
2424 else if (dwFileOffsetLow
== (DWORD
)PENDING_BYTE
2425 && nNumberOfBytesToUnlockLow
== 1){
2426 if (pFile
->local
.bPending
){
2427 pFile
->local
.bPending
= FALSE
;
2428 pFile
->shared
->bPending
= FALSE
;
2432 /* Releasing a reserved lock */
2433 else if (dwFileOffsetLow
== (DWORD
)RESERVED_BYTE
2434 && nNumberOfBytesToUnlockLow
== 1){
2435 if (pFile
->local
.bReserved
) {
2436 pFile
->local
.bReserved
= FALSE
;
2437 pFile
->shared
->bReserved
= FALSE
;
2442 winceMutexRelease(pFile
->hMutex
);
2446 ** End of the special code for wince
2447 *****************************************************************************/
2448 #endif /* SQLITE_OS_WINCE */
2451 ** Lock a file region.
2453 static BOOL
winLockFile(
2463 ** NOTE: Windows CE is handled differently here due its lack of the Win32
2466 return winceLockFile(phFile
, offsetLow
, offsetHigh
,
2467 numBytesLow
, numBytesHigh
);
2471 memset(&ovlp
, 0, sizeof(OVERLAPPED
));
2472 ovlp
.Offset
= offsetLow
;
2473 ovlp
.OffsetHigh
= offsetHigh
;
2474 return osLockFileEx(*phFile
, flags
, 0, numBytesLow
, numBytesHigh
, &ovlp
);
2476 return osLockFile(*phFile
, offsetLow
, offsetHigh
, numBytesLow
,
2483 ** Unlock a file region.
2485 static BOOL
winUnlockFile(
2494 ** NOTE: Windows CE is handled differently here due its lack of the Win32
2497 return winceUnlockFile(phFile
, offsetLow
, offsetHigh
,
2498 numBytesLow
, numBytesHigh
);
2502 memset(&ovlp
, 0, sizeof(OVERLAPPED
));
2503 ovlp
.Offset
= offsetLow
;
2504 ovlp
.OffsetHigh
= offsetHigh
;
2505 return osUnlockFileEx(*phFile
, 0, numBytesLow
, numBytesHigh
, &ovlp
);
2507 return osUnlockFile(*phFile
, offsetLow
, offsetHigh
, numBytesLow
,
2513 /*****************************************************************************
2514 ** The next group of routines implement the I/O methods specified
2515 ** by the sqlite3_io_methods object.
2516 ******************************************************************************/
2519 ** Some Microsoft compilers lack this definition.
2521 #ifndef INVALID_SET_FILE_POINTER
2522 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
2526 ** Move the current position of the file handle passed as the first
2527 ** argument to offset iOffset within the file. If successful, return 0.
2528 ** Otherwise, set pFile->lastErrno and return non-zero.
2530 static int winSeekFile(winFile
*pFile
, sqlite3_int64 iOffset
){
2531 #if !SQLITE_OS_WINRT
2532 LONG upperBits
; /* Most sig. 32 bits of new offset */
2533 LONG lowerBits
; /* Least sig. 32 bits of new offset */
2534 DWORD dwRet
; /* Value returned by SetFilePointer() */
2535 DWORD lastErrno
; /* Value returned by GetLastError() */
2537 OSTRACE(("SEEK file=%p, offset=%lld\n", pFile
->h
, iOffset
));
2539 upperBits
= (LONG
)((iOffset
>>32) & 0x7fffffff);
2540 lowerBits
= (LONG
)(iOffset
& 0xffffffff);
2542 /* API oddity: If successful, SetFilePointer() returns a dword
2543 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
2544 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
2545 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
2546 ** whether an error has actually occurred, it is also necessary to call
2549 dwRet
= osSetFilePointer(pFile
->h
, lowerBits
, &upperBits
, FILE_BEGIN
);
2551 if( (dwRet
==INVALID_SET_FILE_POINTER
2552 && ((lastErrno
= osGetLastError())!=NO_ERROR
)) ){
2553 pFile
->lastErrno
= lastErrno
;
2554 winLogError(SQLITE_IOERR_SEEK
, pFile
->lastErrno
,
2555 "winSeekFile", pFile
->zPath
);
2556 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile
->h
));
2560 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile
->h
));
2564 ** Same as above, except that this implementation works for WinRT.
2567 LARGE_INTEGER x
; /* The new offset */
2568 BOOL bRet
; /* Value returned by SetFilePointerEx() */
2570 x
.QuadPart
= iOffset
;
2571 bRet
= osSetFilePointerEx(pFile
->h
, x
, 0, FILE_BEGIN
);
2574 pFile
->lastErrno
= osGetLastError();
2575 winLogError(SQLITE_IOERR_SEEK
, pFile
->lastErrno
,
2576 "winSeekFile", pFile
->zPath
);
2577 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile
->h
));
2581 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile
->h
));
2586 #if SQLITE_MAX_MMAP_SIZE>0
2587 /* Forward references to VFS helper methods used for memory mapped files */
2588 static int winMapfile(winFile
*, sqlite3_int64
);
2589 static int winUnmapfile(winFile
*);
2595 ** It is reported that an attempt to close a handle might sometimes
2596 ** fail. This is a very unreasonable result, but Windows is notorious
2597 ** for being unreasonable so I do not doubt that it might happen. If
2598 ** the close fails, we pause for 100 milliseconds and try again. As
2599 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
2600 ** giving up and returning an error.
2602 #define MX_CLOSE_ATTEMPT 3
2603 static int winClose(sqlite3_file
*id
){
2605 winFile
*pFile
= (winFile
*)id
;
2608 #ifndef SQLITE_OMIT_WAL
2609 assert( pFile
->pShm
==0 );
2611 assert( pFile
->h
!=NULL
&& pFile
->h
!=INVALID_HANDLE_VALUE
);
2612 OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
2613 osGetCurrentProcessId(), pFile
, pFile
->h
));
2615 #if SQLITE_MAX_MMAP_SIZE>0
2616 winUnmapfile(pFile
);
2620 rc
= osCloseHandle(pFile
->h
);
2621 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
2622 }while( rc
==0 && ++cnt
< MX_CLOSE_ATTEMPT
&& (sqlite3_win32_sleep(100), 1) );
2624 #define WINCE_DELETION_ATTEMPTS 3
2626 winVfsAppData
*pAppData
= (winVfsAppData
*)pFile
->pVfs
->pAppData
;
2627 if( pAppData
==NULL
|| !pAppData
->bNoLock
){
2628 winceDestroyLock(pFile
);
2631 if( pFile
->zDeleteOnClose
){
2634 osDeleteFileW(pFile
->zDeleteOnClose
)==0
2635 && osGetFileAttributesW(pFile
->zDeleteOnClose
)!=0xffffffff
2636 && cnt
++ < WINCE_DELETION_ATTEMPTS
2638 sqlite3_win32_sleep(100); /* Wait a little before trying again */
2640 sqlite3_free(pFile
->zDeleteOnClose
);
2647 OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
2648 osGetCurrentProcessId(), pFile
, pFile
->h
, rc
? "ok" : "failed"));
2649 return rc
? SQLITE_OK
2650 : winLogError(SQLITE_IOERR_CLOSE
, osGetLastError(),
2651 "winClose", pFile
->zPath
);
2655 ** Read data from a file into a buffer. Return SQLITE_OK if all
2656 ** bytes were read successfully and SQLITE_IOERR if anything goes
2660 sqlite3_file
*id
, /* File to read from */
2661 void *pBuf
, /* Write content into this buffer */
2662 int amt
, /* Number of bytes to read */
2663 sqlite3_int64 offset
/* Begin reading at this offset */
2665 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2666 OVERLAPPED overlapped
; /* The offset for ReadFile. */
2668 winFile
*pFile
= (winFile
*)id
; /* file handle */
2669 DWORD nRead
; /* Number of bytes actually read from file */
2670 int nRetry
= 0; /* Number of retrys */
2674 assert( offset
>=0 );
2675 SimulateIOError(return SQLITE_IOERR_READ
);
2676 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
2677 "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile
,
2678 pFile
->h
, pBuf
, amt
, offset
, pFile
->locktype
));
2680 #if SQLITE_MAX_MMAP_SIZE>0
2681 /* Deal with as much of this read request as possible by transfering
2682 ** data from the memory mapping using memcpy(). */
2683 if( offset
<pFile
->mmapSize
){
2684 if( offset
+amt
<= pFile
->mmapSize
){
2685 memcpy(pBuf
, &((u8
*)(pFile
->pMapRegion
))[offset
], amt
);
2686 OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2687 osGetCurrentProcessId(), pFile
, pFile
->h
));
2690 int nCopy
= (int)(pFile
->mmapSize
- offset
);
2691 memcpy(pBuf
, &((u8
*)(pFile
->pMapRegion
))[offset
], nCopy
);
2692 pBuf
= &((u8
*)pBuf
)[nCopy
];
2699 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
2700 if( winSeekFile(pFile
, offset
) ){
2701 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
2702 osGetCurrentProcessId(), pFile
, pFile
->h
));
2705 while( !osReadFile(pFile
->h
, pBuf
, amt
, &nRead
, 0) ){
2707 memset(&overlapped
, 0, sizeof(OVERLAPPED
));
2708 overlapped
.Offset
= (LONG
)(offset
& 0xffffffff);
2709 overlapped
.OffsetHigh
= (LONG
)((offset
>>32) & 0x7fffffff);
2710 while( !osReadFile(pFile
->h
, pBuf
, amt
, &nRead
, &overlapped
) &&
2711 osGetLastError()!=ERROR_HANDLE_EOF
){
2714 if( winRetryIoerr(&nRetry
, &lastErrno
) ) continue;
2715 pFile
->lastErrno
= lastErrno
;
2716 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
2717 osGetCurrentProcessId(), pFile
, pFile
->h
));
2718 return winLogError(SQLITE_IOERR_READ
, pFile
->lastErrno
,
2719 "winRead", pFile
->zPath
);
2721 winLogIoerr(nRetry
, __LINE__
);
2722 if( nRead
<(DWORD
)amt
){
2723 /* Unread parts of the buffer must be zero-filled */
2724 memset(&((char*)pBuf
)[nRead
], 0, amt
-nRead
);
2725 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
2726 osGetCurrentProcessId(), pFile
, pFile
->h
));
2727 return SQLITE_IOERR_SHORT_READ
;
2730 OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2731 osGetCurrentProcessId(), pFile
, pFile
->h
));
2736 ** Write data from a buffer into a file. Return SQLITE_OK on success
2737 ** or some other error code on failure.
2739 static int winWrite(
2740 sqlite3_file
*id
, /* File to write into */
2741 const void *pBuf
, /* The bytes to be written */
2742 int amt
, /* Number of bytes to write */
2743 sqlite3_int64 offset
/* Offset into the file to begin writing at */
2745 int rc
= 0; /* True if error has occurred, else false */
2746 winFile
*pFile
= (winFile
*)id
; /* File handle */
2747 int nRetry
= 0; /* Number of retries */
2751 SimulateIOError(return SQLITE_IOERR_WRITE
);
2752 SimulateDiskfullError(return SQLITE_FULL
);
2754 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
2755 "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile
,
2756 pFile
->h
, pBuf
, amt
, offset
, pFile
->locktype
));
2758 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
2759 /* Deal with as much of this write request as possible by transfering
2760 ** data from the memory mapping using memcpy(). */
2761 if( offset
<pFile
->mmapSize
){
2762 if( offset
+amt
<= pFile
->mmapSize
){
2763 memcpy(&((u8
*)(pFile
->pMapRegion
))[offset
], pBuf
, amt
);
2764 OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2765 osGetCurrentProcessId(), pFile
, pFile
->h
));
2768 int nCopy
= (int)(pFile
->mmapSize
- offset
);
2769 memcpy(&((u8
*)(pFile
->pMapRegion
))[offset
], pBuf
, nCopy
);
2770 pBuf
= &((u8
*)pBuf
)[nCopy
];
2777 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
2778 rc
= winSeekFile(pFile
, offset
);
2783 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2784 OVERLAPPED overlapped
; /* The offset for WriteFile. */
2786 u8
*aRem
= (u8
*)pBuf
; /* Data yet to be written */
2787 int nRem
= amt
; /* Number of bytes yet to be written */
2788 DWORD nWrite
; /* Bytes written by each WriteFile() call */
2789 DWORD lastErrno
= NO_ERROR
; /* Value returned by GetLastError() */
2791 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2792 memset(&overlapped
, 0, sizeof(OVERLAPPED
));
2793 overlapped
.Offset
= (LONG
)(offset
& 0xffffffff);
2794 overlapped
.OffsetHigh
= (LONG
)((offset
>>32) & 0x7fffffff);
2798 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
2799 if( !osWriteFile(pFile
->h
, aRem
, nRem
, &nWrite
, 0) ){
2801 if( !osWriteFile(pFile
->h
, aRem
, nRem
, &nWrite
, &overlapped
) ){
2803 if( winRetryIoerr(&nRetry
, &lastErrno
) ) continue;
2806 assert( nWrite
==0 || nWrite
<=(DWORD
)nRem
);
2807 if( nWrite
==0 || nWrite
>(DWORD
)nRem
){
2808 lastErrno
= osGetLastError();
2811 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
2813 overlapped
.Offset
= (LONG
)(offset
& 0xffffffff);
2814 overlapped
.OffsetHigh
= (LONG
)((offset
>>32) & 0x7fffffff);
2820 pFile
->lastErrno
= lastErrno
;
2826 if( ( pFile
->lastErrno
==ERROR_HANDLE_DISK_FULL
)
2827 || ( pFile
->lastErrno
==ERROR_DISK_FULL
)){
2828 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
2829 osGetCurrentProcessId(), pFile
, pFile
->h
));
2830 return winLogError(SQLITE_FULL
, pFile
->lastErrno
,
2831 "winWrite1", pFile
->zPath
);
2833 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
2834 osGetCurrentProcessId(), pFile
, pFile
->h
));
2835 return winLogError(SQLITE_IOERR_WRITE
, pFile
->lastErrno
,
2836 "winWrite2", pFile
->zPath
);
2838 winLogIoerr(nRetry
, __LINE__
);
2840 OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2841 osGetCurrentProcessId(), pFile
, pFile
->h
));
2846 ** Truncate an open file to a specified size
2848 static int winTruncate(sqlite3_file
*id
, sqlite3_int64 nByte
){
2849 winFile
*pFile
= (winFile
*)id
; /* File handle object */
2850 int rc
= SQLITE_OK
; /* Return code for this function */
2854 SimulateIOError(return SQLITE_IOERR_TRUNCATE
);
2855 OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
2856 osGetCurrentProcessId(), pFile
, pFile
->h
, nByte
, pFile
->locktype
));
2858 /* If the user has configured a chunk-size for this file, truncate the
2859 ** file so that it consists of an integer number of chunks (i.e. the
2860 ** actual file size after the operation may be larger than the requested
2863 if( pFile
->szChunk
>0 ){
2864 nByte
= ((nByte
+ pFile
->szChunk
- 1)/pFile
->szChunk
) * pFile
->szChunk
;
2867 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
2868 if( winSeekFile(pFile
, nByte
) ){
2869 rc
= winLogError(SQLITE_IOERR_TRUNCATE
, pFile
->lastErrno
,
2870 "winTruncate1", pFile
->zPath
);
2871 }else if( 0==osSetEndOfFile(pFile
->h
) &&
2872 ((lastErrno
= osGetLastError())!=ERROR_USER_MAPPED_FILE
) ){
2873 pFile
->lastErrno
= lastErrno
;
2874 rc
= winLogError(SQLITE_IOERR_TRUNCATE
, pFile
->lastErrno
,
2875 "winTruncate2", pFile
->zPath
);
2878 #if SQLITE_MAX_MMAP_SIZE>0
2879 /* If the file was truncated to a size smaller than the currently
2880 ** mapped region, reduce the effective mapping size as well. SQLite will
2881 ** use read() and write() to access data beyond this point from now on.
2883 if( pFile
->pMapRegion
&& nByte
<pFile
->mmapSize
){
2884 pFile
->mmapSize
= nByte
;
2888 OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
2889 osGetCurrentProcessId(), pFile
, pFile
->h
, sqlite3ErrName(rc
)));
2895 ** Count the number of fullsyncs and normal syncs. This is used to test
2896 ** that syncs and fullsyncs are occuring at the right times.
2898 int sqlite3_sync_count
= 0;
2899 int sqlite3_fullsync_count
= 0;
2903 ** Make sure all writes to a particular file are committed to disk.
2905 static int winSync(sqlite3_file
*id
, int flags
){
2906 #ifndef SQLITE_NO_SYNC
2908 ** Used only when SQLITE_NO_SYNC is not defined.
2912 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
2913 defined(SQLITE_HAVE_OS_TRACE)
2915 ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
2916 ** OSTRACE() macros.
2918 winFile
*pFile
= (winFile
*)id
;
2920 UNUSED_PARAMETER(id
);
2924 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2925 assert((flags
&0x0F)==SQLITE_SYNC_NORMAL
2926 || (flags
&0x0F)==SQLITE_SYNC_FULL
2929 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2930 ** line is to test that doing so does not cause any problems.
2932 SimulateDiskfullError( return SQLITE_FULL
);
2934 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
2935 osGetCurrentProcessId(), pFile
, pFile
->h
, flags
,
2939 UNUSED_PARAMETER(flags
);
2941 if( (flags
&0x0F)==SQLITE_SYNC_FULL
){
2942 sqlite3_fullsync_count
++;
2944 sqlite3_sync_count
++;
2947 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2950 #ifdef SQLITE_NO_SYNC
2951 OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2952 osGetCurrentProcessId(), pFile
, pFile
->h
));
2955 #if SQLITE_MAX_MMAP_SIZE>0
2956 if( pFile
->pMapRegion
){
2957 if( osFlushViewOfFile(pFile
->pMapRegion
, 0) ){
2958 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
2959 "rc=SQLITE_OK\n", osGetCurrentProcessId(),
2960 pFile
, pFile
->pMapRegion
));
2962 pFile
->lastErrno
= osGetLastError();
2963 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
2964 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
2965 pFile
, pFile
->pMapRegion
));
2966 return winLogError(SQLITE_IOERR_MMAP
, pFile
->lastErrno
,
2967 "winSync1", pFile
->zPath
);
2971 rc
= osFlushFileBuffers(pFile
->h
);
2972 SimulateIOError( rc
=FALSE
);
2974 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
2975 osGetCurrentProcessId(), pFile
, pFile
->h
));
2978 pFile
->lastErrno
= osGetLastError();
2979 OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
2980 osGetCurrentProcessId(), pFile
, pFile
->h
));
2981 return winLogError(SQLITE_IOERR_FSYNC
, pFile
->lastErrno
,
2982 "winSync2", pFile
->zPath
);
2988 ** Determine the current size of a file in bytes
2990 static int winFileSize(sqlite3_file
*id
, sqlite3_int64
*pSize
){
2991 winFile
*pFile
= (winFile
*)id
;
2996 SimulateIOError(return SQLITE_IOERR_FSTAT
);
2997 OSTRACE(("SIZE file=%p, pSize=%p\n", pFile
->h
, pSize
));
3001 FILE_STANDARD_INFO info
;
3002 if( osGetFileInformationByHandleEx(pFile
->h
, FileStandardInfo
,
3003 &info
, sizeof(info
)) ){
3004 *pSize
= info
.EndOfFile
.QuadPart
;
3006 pFile
->lastErrno
= osGetLastError();
3007 rc
= winLogError(SQLITE_IOERR_FSTAT
, pFile
->lastErrno
,
3008 "winFileSize", pFile
->zPath
);
3017 lowerBits
= osGetFileSize(pFile
->h
, &upperBits
);
3018 *pSize
= (((sqlite3_int64
)upperBits
)<<32) + lowerBits
;
3019 if( (lowerBits
== INVALID_FILE_SIZE
)
3020 && ((lastErrno
= osGetLastError())!=NO_ERROR
) ){
3021 pFile
->lastErrno
= lastErrno
;
3022 rc
= winLogError(SQLITE_IOERR_FSTAT
, pFile
->lastErrno
,
3023 "winFileSize", pFile
->zPath
);
3027 OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
3028 pFile
->h
, pSize
, *pSize
, sqlite3ErrName(rc
)));
3033 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
3035 #ifndef LOCKFILE_FAIL_IMMEDIATELY
3036 # define LOCKFILE_FAIL_IMMEDIATELY 1
3039 #ifndef LOCKFILE_EXCLUSIVE_LOCK
3040 # define LOCKFILE_EXCLUSIVE_LOCK 2
3044 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
3045 ** When the LockFile function was used, it was always expected to fail
3046 ** immediately if the lock could not be obtained. Also, it always expected to
3047 ** obtain an exclusive lock. These flags are used with the LockFileEx function
3048 ** and reflect those expectations; therefore, they should not be changed.
3050 #ifndef SQLITE_LOCKFILE_FLAGS
3051 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
3052 LOCKFILE_EXCLUSIVE_LOCK)
3056 ** Currently, SQLite never calls the LockFileEx function without wanting the
3057 ** call to fail immediately if the lock cannot be obtained.
3059 #ifndef SQLITE_LOCKFILEEX_FLAGS
3060 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
3064 ** Acquire a reader lock.
3065 ** Different API routines are called depending on whether or not this
3066 ** is Win9x or WinNT.
3068 static int winGetReadLock(winFile
*pFile
){
3070 OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile
->h
, pFile
->locktype
));
3074 ** NOTE: Windows CE is handled differently here due its lack of the Win32
3077 res
= winceLockFile(&pFile
->h
, SHARED_FIRST
, 0, 1, 0);
3079 res
= winLockFile(&pFile
->h
, SQLITE_LOCKFILEEX_FLAGS
, SHARED_FIRST
, 0,
3083 #ifdef SQLITE_WIN32_HAS_ANSI
3086 sqlite3_randomness(sizeof(lk
), &lk
);
3087 pFile
->sharedLockByte
= (short)((lk
& 0x7fffffff)%(SHARED_SIZE
- 1));
3088 res
= winLockFile(&pFile
->h
, SQLITE_LOCKFILE_FLAGS
,
3089 SHARED_FIRST
+pFile
->sharedLockByte
, 0, 1, 0);
3093 pFile
->lastErrno
= osGetLastError();
3094 /* No need to log a failure to lock */
3096 OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile
->h
, res
));
3103 static int winUnlockReadLock(winFile
*pFile
){
3106 OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile
->h
, pFile
->locktype
));
3108 res
= winUnlockFile(&pFile
->h
, SHARED_FIRST
, 0, SHARED_SIZE
, 0);
3110 #ifdef SQLITE_WIN32_HAS_ANSI
3112 res
= winUnlockFile(&pFile
->h
, SHARED_FIRST
+pFile
->sharedLockByte
, 0, 1, 0);
3115 if( res
==0 && ((lastErrno
= osGetLastError())!=ERROR_NOT_LOCKED
) ){
3116 pFile
->lastErrno
= lastErrno
;
3117 winLogError(SQLITE_IOERR_UNLOCK
, pFile
->lastErrno
,
3118 "winUnlockReadLock", pFile
->zPath
);
3120 OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile
->h
, res
));
3125 ** Lock the file with the lock specified by parameter locktype - one
3126 ** of the following:
3129 ** (2) RESERVED_LOCK
3131 ** (4) EXCLUSIVE_LOCK
3133 ** Sometimes when requesting one lock state, additional lock states
3134 ** are inserted in between. The locking might fail on one of the later
3135 ** transitions leaving the lock state different from what it started but
3136 ** still short of its goal. The following chart shows the allowed
3137 ** transitions and the inserted intermediate states:
3139 ** UNLOCKED -> SHARED
3140 ** SHARED -> RESERVED
3141 ** SHARED -> (PENDING) -> EXCLUSIVE
3142 ** RESERVED -> (PENDING) -> EXCLUSIVE
3143 ** PENDING -> EXCLUSIVE
3145 ** This routine will only increase a lock. The winUnlock() routine
3146 ** erases all locks at once and returns us immediately to locking level 0.
3147 ** It is not possible to lower the locking level one step at a time. You
3148 ** must go straight to locking level 0.
3150 static int winLock(sqlite3_file
*id
, int locktype
){
3151 int rc
= SQLITE_OK
; /* Return code from subroutines */
3152 int res
= 1; /* Result of a Windows lock call */
3153 int newLocktype
; /* Set pFile->locktype to this value before exiting */
3154 int gotPendingLock
= 0;/* True if we acquired a PENDING lock this time */
3155 winFile
*pFile
= (winFile
*)id
;
3156 DWORD lastErrno
= NO_ERROR
;
3159 OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
3160 pFile
->h
, pFile
->locktype
, pFile
->sharedLockByte
, locktype
));
3162 /* If there is already a lock of this type or more restrictive on the
3163 ** OsFile, do nothing. Don't use the end_lock: exit path, as
3164 ** sqlite3OsEnterMutex() hasn't been called yet.
3166 if( pFile
->locktype
>=locktype
){
3167 OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile
->h
));
3171 /* Do not allow any kind of write-lock on a read-only database
3173 if( (pFile
->ctrlFlags
& WINFILE_RDONLY
)!=0 && locktype
>=RESERVED_LOCK
){
3174 return SQLITE_IOERR_LOCK
;
3177 /* Make sure the locking sequence is correct
3179 assert( pFile
->locktype
!=NO_LOCK
|| locktype
==SHARED_LOCK
);
3180 assert( locktype
!=PENDING_LOCK
);
3181 assert( locktype
!=RESERVED_LOCK
|| pFile
->locktype
==SHARED_LOCK
);
3183 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
3184 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
3185 ** the PENDING_LOCK byte is temporary.
3187 newLocktype
= pFile
->locktype
;
3188 if( pFile
->locktype
==NO_LOCK
3189 || (locktype
==EXCLUSIVE_LOCK
&& pFile
->locktype
<=RESERVED_LOCK
)
3192 while( cnt
-->0 && (res
= winLockFile(&pFile
->h
, SQLITE_LOCKFILE_FLAGS
,
3193 PENDING_BYTE
, 0, 1, 0))==0 ){
3194 /* Try 3 times to get the pending lock. This is needed to work
3195 ** around problems caused by indexing and/or anti-virus software on
3197 ** If you are using this code as a model for alternative VFSes, do not
3198 ** copy this retry logic. It is a hack intended for Windows only.
3200 lastErrno
= osGetLastError();
3201 OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
3202 pFile
->h
, cnt
, res
));
3203 if( lastErrno
==ERROR_INVALID_HANDLE
){
3204 pFile
->lastErrno
= lastErrno
;
3205 rc
= SQLITE_IOERR_LOCK
;
3206 OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
3207 pFile
->h
, cnt
, sqlite3ErrName(rc
)));
3210 if( cnt
) sqlite3_win32_sleep(1);
3212 gotPendingLock
= res
;
3214 lastErrno
= osGetLastError();
3218 /* Acquire a shared lock
3220 if( locktype
==SHARED_LOCK
&& res
){
3221 assert( pFile
->locktype
==NO_LOCK
);
3222 res
= winGetReadLock(pFile
);
3224 newLocktype
= SHARED_LOCK
;
3226 lastErrno
= osGetLastError();
3230 /* Acquire a RESERVED lock
3232 if( locktype
==RESERVED_LOCK
&& res
){
3233 assert( pFile
->locktype
==SHARED_LOCK
);
3234 res
= winLockFile(&pFile
->h
, SQLITE_LOCKFILE_FLAGS
, RESERVED_BYTE
, 0, 1, 0);
3236 newLocktype
= RESERVED_LOCK
;
3238 lastErrno
= osGetLastError();
3242 /* Acquire a PENDING lock
3244 if( locktype
==EXCLUSIVE_LOCK
&& res
){
3245 newLocktype
= PENDING_LOCK
;
3249 /* Acquire an EXCLUSIVE lock
3251 if( locktype
==EXCLUSIVE_LOCK
&& res
){
3252 assert( pFile
->locktype
>=SHARED_LOCK
);
3253 res
= winUnlockReadLock(pFile
);
3254 res
= winLockFile(&pFile
->h
, SQLITE_LOCKFILE_FLAGS
, SHARED_FIRST
, 0,
3257 newLocktype
= EXCLUSIVE_LOCK
;
3259 lastErrno
= osGetLastError();
3260 winGetReadLock(pFile
);
3264 /* If we are holding a PENDING lock that ought to be released, then
3267 if( gotPendingLock
&& locktype
==SHARED_LOCK
){
3268 winUnlockFile(&pFile
->h
, PENDING_BYTE
, 0, 1, 0);
3271 /* Update the state of the lock has held in the file descriptor then
3272 ** return the appropriate result code.
3277 pFile
->lastErrno
= lastErrno
;
3279 OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
3280 pFile
->h
, locktype
, newLocktype
));
3282 pFile
->locktype
= (u8
)newLocktype
;
3283 OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
3284 pFile
->h
, pFile
->locktype
, sqlite3ErrName(rc
)));
3289 ** This routine checks if there is a RESERVED lock held on the specified
3290 ** file by this or any other process. If such a lock is held, return
3291 ** non-zero, otherwise zero.
3293 static int winCheckReservedLock(sqlite3_file
*id
, int *pResOut
){
3295 winFile
*pFile
= (winFile
*)id
;
3297 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK
; );
3298 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile
->h
, pResOut
));
3301 if( pFile
->locktype
>=RESERVED_LOCK
){
3303 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile
->h
, res
));
3305 res
= winLockFile(&pFile
->h
, SQLITE_LOCKFILEEX_FLAGS
,RESERVED_BYTE
,0,1,0);
3307 winUnlockFile(&pFile
->h
, RESERVED_BYTE
, 0, 1, 0);
3310 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile
->h
, res
));
3313 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
3314 pFile
->h
, pResOut
, *pResOut
));
3319 ** Lower the locking level on file descriptor id to locktype. locktype
3320 ** must be either NO_LOCK or SHARED_LOCK.
3322 ** If the locking level of the file descriptor is already at or below
3323 ** the requested locking level, this routine is a no-op.
3325 ** It is not possible for this routine to fail if the second argument
3326 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
3327 ** might return SQLITE_IOERR;
3329 static int winUnlock(sqlite3_file
*id
, int locktype
){
3331 winFile
*pFile
= (winFile
*)id
;
3334 assert( locktype
<=SHARED_LOCK
);
3335 OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
3336 pFile
->h
, pFile
->locktype
, pFile
->sharedLockByte
, locktype
));
3337 type
= pFile
->locktype
;
3338 if( type
>=EXCLUSIVE_LOCK
){
3339 winUnlockFile(&pFile
->h
, SHARED_FIRST
, 0, SHARED_SIZE
, 0);
3340 if( locktype
==SHARED_LOCK
&& !winGetReadLock(pFile
) ){
3341 /* This should never happen. We should always be able to
3342 ** reacquire the read lock */
3343 rc
= winLogError(SQLITE_IOERR_UNLOCK
, osGetLastError(),
3344 "winUnlock", pFile
->zPath
);
3347 if( type
>=RESERVED_LOCK
){
3348 winUnlockFile(&pFile
->h
, RESERVED_BYTE
, 0, 1, 0);
3350 if( locktype
==NO_LOCK
&& type
>=SHARED_LOCK
){
3351 winUnlockReadLock(pFile
);
3353 if( type
>=PENDING_LOCK
){
3354 winUnlockFile(&pFile
->h
, PENDING_BYTE
, 0, 1, 0);
3356 pFile
->locktype
= (u8
)locktype
;
3357 OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
3358 pFile
->h
, pFile
->locktype
, sqlite3ErrName(rc
)));
3362 /******************************************************************************
3363 ****************************** No-op Locking **********************************
3365 ** Of the various locking implementations available, this is by far the
3366 ** simplest: locking is ignored. No attempt is made to lock the database
3367 ** file for reading or writing.
3369 ** This locking mode is appropriate for use on read-only databases
3370 ** (ex: databases that are burned into CD-ROM, for example.) It can
3371 ** also be used if the application employs some external mechanism to
3372 ** prevent simultaneous access of the same database by two or more
3373 ** database connections. But there is a serious risk of database
3374 ** corruption if this locking mode is used in situations where multiple
3375 ** database connections are accessing the same database file at the same
3376 ** time and one or more of those connections are writing.
3379 static int winNolockLock(sqlite3_file
*id
, int locktype
){
3380 UNUSED_PARAMETER(id
);
3381 UNUSED_PARAMETER(locktype
);
3385 static int winNolockCheckReservedLock(sqlite3_file
*id
, int *pResOut
){
3386 UNUSED_PARAMETER(id
);
3387 UNUSED_PARAMETER(pResOut
);
3391 static int winNolockUnlock(sqlite3_file
*id
, int locktype
){
3392 UNUSED_PARAMETER(id
);
3393 UNUSED_PARAMETER(locktype
);
3397 /******************* End of the no-op lock implementation *********************
3398 ******************************************************************************/
3401 ** If *pArg is initially negative then this is a query. Set *pArg to
3402 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3404 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3406 static void winModeBit(winFile
*pFile
, unsigned char mask
, int *pArg
){
3408 *pArg
= (pFile
->ctrlFlags
& mask
)!=0;
3409 }else if( (*pArg
)==0 ){
3410 pFile
->ctrlFlags
&= ~mask
;
3412 pFile
->ctrlFlags
|= mask
;
3416 /* Forward references to VFS helper methods used for temporary files */
3417 static int winGetTempname(sqlite3_vfs
*, char **);
3418 static int winIsDir(const void *);
3419 static BOOL
winIsDriveLetterAndColon(const char *);
3422 ** Control and query of the open file handle.
3424 static int winFileControl(sqlite3_file
*id
, int op
, void *pArg
){
3425 winFile
*pFile
= (winFile
*)id
;
3426 OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile
->h
, op
, pArg
));
3428 case SQLITE_FCNTL_LOCKSTATE
: {
3429 *(int*)pArg
= pFile
->locktype
;
3430 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile
->h
));
3433 case SQLITE_FCNTL_LAST_ERRNO
: {
3434 *(int*)pArg
= (int)pFile
->lastErrno
;
3435 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile
->h
));
3438 case SQLITE_FCNTL_CHUNK_SIZE
: {
3439 pFile
->szChunk
= *(int *)pArg
;
3440 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile
->h
));
3443 case SQLITE_FCNTL_SIZE_HINT
: {
3444 if( pFile
->szChunk
>0 ){
3445 sqlite3_int64 oldSz
;
3446 int rc
= winFileSize(id
, &oldSz
);
3447 if( rc
==SQLITE_OK
){
3448 sqlite3_int64 newSz
= *(sqlite3_int64
*)pArg
;
3450 SimulateIOErrorBenign(1);
3451 rc
= winTruncate(id
, newSz
);
3452 SimulateIOErrorBenign(0);
3455 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile
->h
, sqlite3ErrName(rc
)));
3458 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile
->h
));
3461 case SQLITE_FCNTL_PERSIST_WAL
: {
3462 winModeBit(pFile
, WINFILE_PERSIST_WAL
, (int*)pArg
);
3463 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile
->h
));
3466 case SQLITE_FCNTL_POWERSAFE_OVERWRITE
: {
3467 winModeBit(pFile
, WINFILE_PSOW
, (int*)pArg
);
3468 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile
->h
));
3471 case SQLITE_FCNTL_VFSNAME
: {
3472 *(char**)pArg
= sqlite3_mprintf("%s", pFile
->pVfs
->zName
);
3473 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile
->h
));
3476 case SQLITE_FCNTL_WIN32_AV_RETRY
: {
3477 int *a
= (int*)pArg
;
3479 winIoerrRetry
= a
[0];
3481 a
[0] = winIoerrRetry
;
3484 winIoerrRetryDelay
= a
[1];
3486 a
[1] = winIoerrRetryDelay
;
3488 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile
->h
));
3491 case SQLITE_FCNTL_WIN32_GET_HANDLE
: {
3492 LPHANDLE phFile
= (LPHANDLE
)pArg
;
3494 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile
->h
));
3498 case SQLITE_FCNTL_WIN32_SET_HANDLE
: {
3499 LPHANDLE phFile
= (LPHANDLE
)pArg
;
3500 HANDLE hOldFile
= pFile
->h
;
3503 OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
3504 hOldFile
, pFile
->h
));
3508 case SQLITE_FCNTL_TEMPFILENAME
: {
3510 int rc
= winGetTempname(pFile
->pVfs
, &zTFile
);
3511 if( rc
==SQLITE_OK
){
3512 *(char**)pArg
= zTFile
;
3514 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile
->h
, sqlite3ErrName(rc
)));
3517 #if SQLITE_MAX_MMAP_SIZE>0
3518 case SQLITE_FCNTL_MMAP_SIZE
: {
3519 i64 newLimit
= *(i64
*)pArg
;
3521 if( newLimit
>sqlite3GlobalConfig
.mxMmap
){
3522 newLimit
= sqlite3GlobalConfig
.mxMmap
;
3524 *(i64
*)pArg
= pFile
->mmapSizeMax
;
3525 if( newLimit
>=0 && newLimit
!=pFile
->mmapSizeMax
&& pFile
->nFetchOut
==0 ){
3526 pFile
->mmapSizeMax
= newLimit
;
3527 if( pFile
->mmapSize
>0 ){
3528 winUnmapfile(pFile
);
3529 rc
= winMapfile(pFile
, -1);
3532 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile
->h
, sqlite3ErrName(rc
)));
3537 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile
->h
));
3538 return SQLITE_NOTFOUND
;
3542 ** Return the sector size in bytes of the underlying block device for
3543 ** the specified file. This is almost always 512 bytes, but may be
3544 ** larger for some devices.
3546 ** SQLite code assumes this function cannot fail. It also assumes that
3547 ** if two files are created in the same file-system directory (i.e.
3548 ** a database and its journal file) that the sector size will be the
3551 static int winSectorSize(sqlite3_file
*id
){
3553 return SQLITE_DEFAULT_SECTOR_SIZE
;
3557 ** Return a vector of device characteristics.
3559 static int winDeviceCharacteristics(sqlite3_file
*id
){
3560 winFile
*p
= (winFile
*)id
;
3561 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
|
3562 ((p
->ctrlFlags
& WINFILE_PSOW
)?SQLITE_IOCAP_POWERSAFE_OVERWRITE
:0);
3566 ** Windows will only let you create file view mappings
3567 ** on allocation size granularity boundaries.
3568 ** During sqlite3_os_init() we do a GetSystemInfo()
3569 ** to get the granularity size.
3571 static SYSTEM_INFO winSysInfo
;
3573 #ifndef SQLITE_OMIT_WAL
3576 ** Helper functions to obtain and relinquish the global mutex. The
3577 ** global mutex is used to protect the winLockInfo objects used by
3578 ** this file, all of which may be shared by multiple threads.
3580 ** Function winShmMutexHeld() is used to assert() that the global mutex
3581 ** is held when required. This function is only used as part of assert()
3584 ** winShmEnterMutex()
3585 ** assert( winShmMutexHeld() );
3586 ** winShmLeaveMutex()
3588 static void winShmEnterMutex(void){
3589 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1
));
3591 static void winShmLeaveMutex(void){
3592 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1
));
3595 static int winShmMutexHeld(void) {
3596 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1
));
3601 ** Object used to represent a single file opened and mmapped to provide
3602 ** shared memory. When multiple threads all reference the same
3603 ** log-summary, each thread has its own winFile object, but they all
3604 ** point to a single instance of this object. In other words, each
3605 ** log-summary is opened only once per process.
3607 ** winShmMutexHeld() must be true when creating or destroying
3608 ** this object or while reading or writing the following fields:
3613 ** The following fields are read-only after the object is created:
3618 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
3619 ** winShmMutexHeld() is true when reading or writing any other field
3620 ** in this structure.
3624 sqlite3_mutex
*mutex
; /* Mutex to access this object */
3625 char *zFilename
; /* Name of the file */
3626 winFile hFile
; /* File handle from winOpen */
3628 int szRegion
; /* Size of shared-memory regions */
3629 int nRegion
; /* Size of array apRegion */
3631 HANDLE hMap
; /* File handle from CreateFileMapping */
3634 DWORD lastErrno
; /* The Windows errno from the last I/O error */
3636 int nRef
; /* Number of winShm objects pointing to this */
3637 winShm
*pFirst
; /* All winShm objects pointing to this */
3638 winShmNode
*pNext
; /* Next in list of all winShmNode objects */
3639 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
3640 u8 nextShmId
; /* Next available winShm.id value */
3645 ** A global array of all winShmNode objects.
3647 ** The winShmMutexHeld() must be true while reading or writing this list.
3649 static winShmNode
*winShmNodeList
= 0;
3652 ** Structure used internally by this VFS to record the state of an
3653 ** open shared memory connection.
3655 ** The following fields are initialized when this object is created and
3656 ** are read-only thereafter:
3661 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
3662 ** while accessing any read/write fields.
3665 winShmNode
*pShmNode
; /* The underlying winShmNode object */
3666 winShm
*pNext
; /* Next winShm with the same winShmNode */
3667 u8 hasMutex
; /* True if holding the winShmNode mutex */
3668 u16 sharedMask
; /* Mask of shared locks held */
3669 u16 exclMask
; /* Mask of exclusive locks held */
3670 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
3671 u8 id
; /* Id of this connection with its winShmNode */
3676 ** Constants used for locking
3678 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
3679 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
3682 ** Apply advisory locks for all n bytes beginning at ofst.
3684 #define WINSHM_UNLCK 1
3685 #define WINSHM_RDLCK 2
3686 #define WINSHM_WRLCK 3
3687 static int winShmSystemLock(
3688 winShmNode
*pFile
, /* Apply locks to this open shared-memory segment */
3689 int lockType
, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
3690 int ofst
, /* Offset to first byte to be locked/unlocked */
3691 int nByte
/* Number of bytes to lock or unlock */
3693 int rc
= 0; /* Result code form Lock/UnlockFileEx() */
3695 /* Access to the winShmNode object is serialized by the caller */
3696 assert( sqlite3_mutex_held(pFile
->mutex
) || pFile
->nRef
==0 );
3698 OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
3699 pFile
->hFile
.h
, lockType
, ofst
, nByte
));
3701 /* Release/Acquire the system-level lock */
3702 if( lockType
==WINSHM_UNLCK
){
3703 rc
= winUnlockFile(&pFile
->hFile
.h
, ofst
, 0, nByte
, 0);
3705 /* Initialize the locking parameters */
3706 DWORD dwFlags
= LOCKFILE_FAIL_IMMEDIATELY
;
3707 if( lockType
== WINSHM_WRLCK
) dwFlags
|= LOCKFILE_EXCLUSIVE_LOCK
;
3708 rc
= winLockFile(&pFile
->hFile
.h
, dwFlags
, ofst
, 0, nByte
, 0);
3714 pFile
->lastErrno
= osGetLastError();
3718 OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
3719 pFile
->hFile
.h
, (lockType
== WINSHM_UNLCK
) ? "winUnlockFile" :
3720 "winLockFile", pFile
->lastErrno
, sqlite3ErrName(rc
)));
3725 /* Forward references to VFS methods */
3726 static int winOpen(sqlite3_vfs
*,const char*,sqlite3_file
*,int,int*);
3727 static int winDelete(sqlite3_vfs
*,const char*,int);
3730 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
3732 ** This is not a VFS shared-memory method; it is a utility function called
3733 ** by VFS shared-memory methods.
3735 static void winShmPurge(sqlite3_vfs
*pVfs
, int deleteFlag
){
3738 assert( winShmMutexHeld() );
3739 OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
3740 osGetCurrentProcessId(), deleteFlag
));
3741 pp
= &winShmNodeList
;
3742 while( (p
= *pp
)!=0 ){
3745 if( p
->mutex
){ sqlite3_mutex_free(p
->mutex
); }
3746 for(i
=0; i
<p
->nRegion
; i
++){
3747 BOOL bRc
= osUnmapViewOfFile(p
->aRegion
[i
].pMap
);
3748 OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
3749 osGetCurrentProcessId(), i
, bRc
? "ok" : "failed"));
3750 UNUSED_VARIABLE_VALUE(bRc
);
3751 bRc
= osCloseHandle(p
->aRegion
[i
].hMap
);
3752 OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
3753 osGetCurrentProcessId(), i
, bRc
? "ok" : "failed"));
3754 UNUSED_VARIABLE_VALUE(bRc
);
3756 if( p
->hFile
.h
!=NULL
&& p
->hFile
.h
!=INVALID_HANDLE_VALUE
){
3757 SimulateIOErrorBenign(1);
3758 winClose((sqlite3_file
*)&p
->hFile
);
3759 SimulateIOErrorBenign(0);
3762 SimulateIOErrorBenign(1);
3763 sqlite3BeginBenignMalloc();
3764 winDelete(pVfs
, p
->zFilename
, 0);
3765 sqlite3EndBenignMalloc();
3766 SimulateIOErrorBenign(0);
3769 sqlite3_free(p
->aRegion
);
3778 ** Open the shared-memory area associated with database file pDbFd.
3780 ** When opening a new shared-memory file, if no other instances of that
3781 ** file are currently open, in this process or in other processes, then
3782 ** the file must be truncated to zero length or have its header cleared.
3784 static int winOpenSharedMemory(winFile
*pDbFd
){
3785 struct winShm
*p
; /* The connection to be opened */
3786 struct winShmNode
*pShmNode
= 0; /* The underlying mmapped file */
3787 int rc
; /* Result code */
3788 struct winShmNode
*pNew
; /* Newly allocated winShmNode */
3789 int nName
; /* Size of zName in bytes */
3791 assert( pDbFd
->pShm
==0 ); /* Not previously opened */
3793 /* Allocate space for the new sqlite3_shm object. Also speculatively
3794 ** allocate space for a new winShmNode and filename.
3796 p
= sqlite3MallocZero( sizeof(*p
) );
3797 if( p
==0 ) return SQLITE_IOERR_NOMEM_BKPT
;
3798 nName
= sqlite3Strlen30(pDbFd
->zPath
);
3799 pNew
= sqlite3MallocZero( sizeof(*pShmNode
) + nName
+ 17 );
3802 return SQLITE_IOERR_NOMEM_BKPT
;
3804 pNew
->zFilename
= (char*)&pNew
[1];
3805 sqlite3_snprintf(nName
+15, pNew
->zFilename
, "%s-shm", pDbFd
->zPath
);
3806 sqlite3FileSuffix3(pDbFd
->zPath
, pNew
->zFilename
);
3808 /* Look to see if there is an existing winShmNode that can be used.
3809 ** If no matching winShmNode currently exists, create a new one.
3812 for(pShmNode
= winShmNodeList
; pShmNode
; pShmNode
=pShmNode
->pNext
){
3813 /* TBD need to come up with better match here. Perhaps
3814 ** use FILE_ID_BOTH_DIR_INFO Structure.
3816 if( sqlite3StrICmp(pShmNode
->zFilename
, pNew
->zFilename
)==0 ) break;
3823 ((winFile
*)(&pShmNode
->hFile
))->h
= INVALID_HANDLE_VALUE
;
3824 pShmNode
->pNext
= winShmNodeList
;
3825 winShmNodeList
= pShmNode
;
3827 if( sqlite3GlobalConfig
.bCoreMutex
){
3828 pShmNode
->mutex
= sqlite3_mutex_alloc(SQLITE_MUTEX_FAST
);
3829 if( pShmNode
->mutex
==0 ){
3830 rc
= SQLITE_IOERR_NOMEM_BKPT
;
3835 rc
= winOpen(pDbFd
->pVfs
,
3836 pShmNode
->zFilename
, /* Name of the file (UTF-8) */
3837 (sqlite3_file
*)&pShmNode
->hFile
, /* File handle here */
3838 SQLITE_OPEN_WAL
| SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
,
3840 if( SQLITE_OK
!=rc
){
3844 /* Check to see if another process is holding the dead-man switch.
3845 ** If not, truncate the file to zero length.
3847 if( winShmSystemLock(pShmNode
, WINSHM_WRLCK
, WIN_SHM_DMS
, 1)==SQLITE_OK
){
3848 rc
= winTruncate((sqlite3_file
*)&pShmNode
->hFile
, 0);
3849 if( rc
!=SQLITE_OK
){
3850 rc
= winLogError(SQLITE_IOERR_SHMOPEN
, osGetLastError(),
3851 "winOpenShm", pDbFd
->zPath
);
3854 if( rc
==SQLITE_OK
){
3855 winShmSystemLock(pShmNode
, WINSHM_UNLCK
, WIN_SHM_DMS
, 1);
3856 rc
= winShmSystemLock(pShmNode
, WINSHM_RDLCK
, WIN_SHM_DMS
, 1);
3858 if( rc
) goto shm_open_err
;
3861 /* Make the new connection a child of the winShmNode */
3862 p
->pShmNode
= pShmNode
;
3863 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
3864 p
->id
= pShmNode
->nextShmId
++;
3870 /* The reference count on pShmNode has already been incremented under
3871 ** the cover of the winShmEnterMutex() mutex and the pointer from the
3872 ** new (struct winShm) object to the pShmNode has been set. All that is
3873 ** left to do is to link the new object into the linked list starting
3874 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3877 sqlite3_mutex_enter(pShmNode
->mutex
);
3878 p
->pNext
= pShmNode
->pFirst
;
3879 pShmNode
->pFirst
= p
;
3880 sqlite3_mutex_leave(pShmNode
->mutex
);
3883 /* Jump here on any error */
3885 winShmSystemLock(pShmNode
, WINSHM_UNLCK
, WIN_SHM_DMS
, 1);
3886 winShmPurge(pDbFd
->pVfs
, 0); /* This call frees pShmNode if required */
3894 ** Close a connection to shared-memory. Delete the underlying
3895 ** storage if deleteFlag is true.
3897 static int winShmUnmap(
3898 sqlite3_file
*fd
, /* Database holding shared memory */
3899 int deleteFlag
/* Delete after closing if true */
3901 winFile
*pDbFd
; /* Database holding shared-memory */
3902 winShm
*p
; /* The connection to be closed */
3903 winShmNode
*pShmNode
; /* The underlying shared-memory file */
3904 winShm
**pp
; /* For looping over sibling connections */
3906 pDbFd
= (winFile
*)fd
;
3908 if( p
==0 ) return SQLITE_OK
;
3909 pShmNode
= p
->pShmNode
;
3911 /* Remove connection p from the set of connections associated
3913 sqlite3_mutex_enter(pShmNode
->mutex
);
3914 for(pp
=&pShmNode
->pFirst
; (*pp
)!=p
; pp
= &(*pp
)->pNext
){}
3917 /* Free the connection p */
3920 sqlite3_mutex_leave(pShmNode
->mutex
);
3922 /* If pShmNode->nRef has reached 0, then close the underlying
3923 ** shared-memory file, too */
3925 assert( pShmNode
->nRef
>0 );
3927 if( pShmNode
->nRef
==0 ){
3928 winShmPurge(pDbFd
->pVfs
, deleteFlag
);
3936 ** Change the lock state for a shared-memory segment.
3938 static int winShmLock(
3939 sqlite3_file
*fd
, /* Database file holding the shared memory */
3940 int ofst
, /* First lock to acquire or release */
3941 int n
, /* Number of locks to acquire or release */
3942 int flags
/* What to do with the lock */
3944 winFile
*pDbFd
= (winFile
*)fd
; /* Connection holding shared memory */
3945 winShm
*p
= pDbFd
->pShm
; /* The shared memory being locked */
3946 winShm
*pX
; /* For looping over all siblings */
3947 winShmNode
*pShmNode
= p
->pShmNode
;
3948 int rc
= SQLITE_OK
; /* Result code */
3949 u16 mask
; /* Mask of locks to take or release */
3951 assert( ofst
>=0 && ofst
+n
<=SQLITE_SHM_NLOCK
);
3953 assert( flags
==(SQLITE_SHM_LOCK
| SQLITE_SHM_SHARED
)
3954 || flags
==(SQLITE_SHM_LOCK
| SQLITE_SHM_EXCLUSIVE
)
3955 || flags
==(SQLITE_SHM_UNLOCK
| SQLITE_SHM_SHARED
)
3956 || flags
==(SQLITE_SHM_UNLOCK
| SQLITE_SHM_EXCLUSIVE
) );
3957 assert( n
==1 || (flags
& SQLITE_SHM_EXCLUSIVE
)!=0 );
3959 mask
= (u16
)((1U<<(ofst
+n
)) - (1U<<ofst
));
3960 assert( n
>1 || mask
==(1<<ofst
) );
3961 sqlite3_mutex_enter(pShmNode
->mutex
);
3962 if( flags
& SQLITE_SHM_UNLOCK
){
3963 u16 allMask
= 0; /* Mask of locks held by siblings */
3965 /* See if any siblings hold this same lock */
3966 for(pX
=pShmNode
->pFirst
; pX
; pX
=pX
->pNext
){
3967 if( pX
==p
) continue;
3968 assert( (pX
->exclMask
& (p
->exclMask
|p
->sharedMask
))==0 );
3969 allMask
|= pX
->sharedMask
;
3972 /* Unlock the system-level locks */
3973 if( (mask
& allMask
)==0 ){
3974 rc
= winShmSystemLock(pShmNode
, WINSHM_UNLCK
, ofst
+WIN_SHM_BASE
, n
);
3979 /* Undo the local locks */
3980 if( rc
==SQLITE_OK
){
3981 p
->exclMask
&= ~mask
;
3982 p
->sharedMask
&= ~mask
;
3984 }else if( flags
& SQLITE_SHM_SHARED
){
3985 u16 allShared
= 0; /* Union of locks held by connections other than "p" */
3987 /* Find out which shared locks are already held by sibling connections.
3988 ** If any sibling already holds an exclusive lock, go ahead and return
3991 for(pX
=pShmNode
->pFirst
; pX
; pX
=pX
->pNext
){
3992 if( (pX
->exclMask
& mask
)!=0 ){
3996 allShared
|= pX
->sharedMask
;
3999 /* Get shared locks at the system level, if necessary */
4000 if( rc
==SQLITE_OK
){
4001 if( (allShared
& mask
)==0 ){
4002 rc
= winShmSystemLock(pShmNode
, WINSHM_RDLCK
, ofst
+WIN_SHM_BASE
, n
);
4008 /* Get the local shared locks */
4009 if( rc
==SQLITE_OK
){
4010 p
->sharedMask
|= mask
;
4013 /* Make sure no sibling connections hold locks that will block this
4014 ** lock. If any do, return SQLITE_BUSY right away.
4016 for(pX
=pShmNode
->pFirst
; pX
; pX
=pX
->pNext
){
4017 if( (pX
->exclMask
& mask
)!=0 || (pX
->sharedMask
& mask
)!=0 ){
4023 /* Get the exclusive locks at the system level. Then if successful
4024 ** also mark the local connection as being locked.
4026 if( rc
==SQLITE_OK
){
4027 rc
= winShmSystemLock(pShmNode
, WINSHM_WRLCK
, ofst
+WIN_SHM_BASE
, n
);
4028 if( rc
==SQLITE_OK
){
4029 assert( (p
->sharedMask
& mask
)==0 );
4030 p
->exclMask
|= mask
;
4034 sqlite3_mutex_leave(pShmNode
->mutex
);
4035 OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
4036 osGetCurrentProcessId(), p
->id
, p
->sharedMask
, p
->exclMask
,
4037 sqlite3ErrName(rc
)));
4042 ** Implement a memory barrier or memory fence on shared memory.
4044 ** All loads and stores begun before the barrier must complete before
4045 ** any load or store begun after the barrier.
4047 static void winShmBarrier(
4048 sqlite3_file
*fd
/* Database holding the shared memory */
4050 UNUSED_PARAMETER(fd
);
4051 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4052 winShmEnterMutex(); /* Also mutex, for redundancy */
4057 ** This function is called to obtain a pointer to region iRegion of the
4058 ** shared-memory associated with the database file fd. Shared-memory regions
4059 ** are numbered starting from zero. Each shared-memory region is szRegion
4062 ** If an error occurs, an error code is returned and *pp is set to NULL.
4064 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
4065 ** region has not been allocated (by any client, including one running in a
4066 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4067 ** isWrite is non-zero and the requested shared-memory region has not yet
4068 ** been allocated, it is allocated by this function.
4070 ** If the shared-memory region has already been allocated or is allocated by
4071 ** this call as described above, then it is mapped into this processes
4072 ** address space (if it is not already), *pp is set to point to the mapped
4073 ** memory and SQLITE_OK returned.
4075 static int winShmMap(
4076 sqlite3_file
*fd
, /* Handle open on database file */
4077 int iRegion
, /* Region to retrieve */
4078 int szRegion
, /* Size of regions */
4079 int isWrite
, /* True to extend file if necessary */
4080 void volatile **pp
/* OUT: Mapped memory */
4082 winFile
*pDbFd
= (winFile
*)fd
;
4083 winShm
*pShm
= pDbFd
->pShm
;
4084 winShmNode
*pShmNode
;
4088 rc
= winOpenSharedMemory(pDbFd
);
4089 if( rc
!=SQLITE_OK
) return rc
;
4092 pShmNode
= pShm
->pShmNode
;
4094 sqlite3_mutex_enter(pShmNode
->mutex
);
4095 assert( szRegion
==pShmNode
->szRegion
|| pShmNode
->nRegion
==0 );
4097 if( pShmNode
->nRegion
<=iRegion
){
4098 struct ShmRegion
*apNew
; /* New aRegion[] array */
4099 int nByte
= (iRegion
+1)*szRegion
; /* Minimum required file size */
4100 sqlite3_int64 sz
; /* Current size of wal-index file */
4102 pShmNode
->szRegion
= szRegion
;
4104 /* The requested region is not mapped into this processes address space.
4105 ** Check to see if it has been allocated (i.e. if the wal-index file is
4106 ** large enough to contain the requested region).
4108 rc
= winFileSize((sqlite3_file
*)&pShmNode
->hFile
, &sz
);
4109 if( rc
!=SQLITE_OK
){
4110 rc
= winLogError(SQLITE_IOERR_SHMSIZE
, osGetLastError(),
4111 "winShmMap1", pDbFd
->zPath
);
4116 /* The requested memory region does not exist. If isWrite is set to
4117 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
4119 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
4120 ** the requested memory region.
4122 if( !isWrite
) goto shmpage_out
;
4123 rc
= winTruncate((sqlite3_file
*)&pShmNode
->hFile
, nByte
);
4124 if( rc
!=SQLITE_OK
){
4125 rc
= winLogError(SQLITE_IOERR_SHMSIZE
, osGetLastError(),
4126 "winShmMap2", pDbFd
->zPath
);
4131 /* Map the requested memory region into this processes address space. */
4132 apNew
= (struct ShmRegion
*)sqlite3_realloc64(
4133 pShmNode
->aRegion
, (iRegion
+1)*sizeof(apNew
[0])
4136 rc
= SQLITE_IOERR_NOMEM_BKPT
;
4139 pShmNode
->aRegion
= apNew
;
4141 while( pShmNode
->nRegion
<=iRegion
){
4142 HANDLE hMap
= NULL
; /* file-mapping handle */
4143 void *pMap
= 0; /* Mapped memory region */
4146 hMap
= osCreateFileMappingFromApp(pShmNode
->hFile
.h
,
4147 NULL
, PAGE_READWRITE
, nByte
, NULL
4149 #elif defined(SQLITE_WIN32_HAS_WIDE)
4150 hMap
= osCreateFileMappingW(pShmNode
->hFile
.h
,
4151 NULL
, PAGE_READWRITE
, 0, nByte
, NULL
4153 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
4154 hMap
= osCreateFileMappingA(pShmNode
->hFile
.h
,
4155 NULL
, PAGE_READWRITE
, 0, nByte
, NULL
4158 OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
4159 osGetCurrentProcessId(), pShmNode
->nRegion
, nByte
,
4160 hMap
? "ok" : "failed"));
4162 int iOffset
= pShmNode
->nRegion
*szRegion
;
4163 int iOffsetShift
= iOffset
% winSysInfo
.dwAllocationGranularity
;
4165 pMap
= osMapViewOfFileFromApp(hMap
, FILE_MAP_WRITE
| FILE_MAP_READ
,
4166 iOffset
- iOffsetShift
, szRegion
+ iOffsetShift
4169 pMap
= osMapViewOfFile(hMap
, FILE_MAP_WRITE
| FILE_MAP_READ
,
4170 0, iOffset
- iOffsetShift
, szRegion
+ iOffsetShift
4173 OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
4174 osGetCurrentProcessId(), pShmNode
->nRegion
, iOffset
,
4175 szRegion
, pMap
? "ok" : "failed"));
4178 pShmNode
->lastErrno
= osGetLastError();
4179 rc
= winLogError(SQLITE_IOERR_SHMMAP
, pShmNode
->lastErrno
,
4180 "winShmMap3", pDbFd
->zPath
);
4181 if( hMap
) osCloseHandle(hMap
);
4185 pShmNode
->aRegion
[pShmNode
->nRegion
].pMap
= pMap
;
4186 pShmNode
->aRegion
[pShmNode
->nRegion
].hMap
= hMap
;
4187 pShmNode
->nRegion
++;
4192 if( pShmNode
->nRegion
>iRegion
){
4193 int iOffset
= iRegion
*szRegion
;
4194 int iOffsetShift
= iOffset
% winSysInfo
.dwAllocationGranularity
;
4195 char *p
= (char *)pShmNode
->aRegion
[iRegion
].pMap
;
4196 *pp
= (void *)&p
[iOffsetShift
];
4200 sqlite3_mutex_leave(pShmNode
->mutex
);
4205 # define winShmMap 0
4206 # define winShmLock 0
4207 # define winShmBarrier 0
4208 # define winShmUnmap 0
4209 #endif /* #ifndef SQLITE_OMIT_WAL */
4212 ** Cleans up the mapped region of the specified file, if any.
4214 #if SQLITE_MAX_MMAP_SIZE>0
4215 static int winUnmapfile(winFile
*pFile
){
4217 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
4218 "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
4219 osGetCurrentProcessId(), pFile
, pFile
->hMap
, pFile
->pMapRegion
,
4220 pFile
->mmapSize
, pFile
->mmapSizeActual
, pFile
->mmapSizeMax
));
4221 if( pFile
->pMapRegion
){
4222 if( !osUnmapViewOfFile(pFile
->pMapRegion
) ){
4223 pFile
->lastErrno
= osGetLastError();
4224 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
4225 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile
,
4226 pFile
->pMapRegion
));
4227 return winLogError(SQLITE_IOERR_MMAP
, pFile
->lastErrno
,
4228 "winUnmapfile1", pFile
->zPath
);
4230 pFile
->pMapRegion
= 0;
4231 pFile
->mmapSize
= 0;
4232 pFile
->mmapSizeActual
= 0;
4234 if( pFile
->hMap
!=NULL
){
4235 if( !osCloseHandle(pFile
->hMap
) ){
4236 pFile
->lastErrno
= osGetLastError();
4237 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
4238 osGetCurrentProcessId(), pFile
, pFile
->hMap
));
4239 return winLogError(SQLITE_IOERR_MMAP
, pFile
->lastErrno
,
4240 "winUnmapfile2", pFile
->zPath
);
4244 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
4245 osGetCurrentProcessId(), pFile
));
4250 ** Memory map or remap the file opened by file-descriptor pFd (if the file
4251 ** is already mapped, the existing mapping is replaced by the new). Or, if
4252 ** there already exists a mapping for this file, and there are still
4253 ** outstanding xFetch() references to it, this function is a no-op.
4255 ** If parameter nByte is non-negative, then it is the requested size of
4256 ** the mapping to create. Otherwise, if nByte is less than zero, then the
4257 ** requested size is the size of the file on disk. The actual size of the
4258 ** created mapping is either the requested size or the value configured
4259 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
4261 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
4262 ** recreated as a result of outstanding references) or an SQLite error
4265 static int winMapfile(winFile
*pFd
, sqlite3_int64 nByte
){
4266 sqlite3_int64 nMap
= nByte
;
4269 assert( nMap
>=0 || pFd
->nFetchOut
==0 );
4270 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
4271 osGetCurrentProcessId(), pFd
, nByte
));
4273 if( pFd
->nFetchOut
>0 ) return SQLITE_OK
;
4276 rc
= winFileSize((sqlite3_file
*)pFd
, &nMap
);
4278 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
4279 osGetCurrentProcessId(), pFd
));
4280 return SQLITE_IOERR_FSTAT
;
4283 if( nMap
>pFd
->mmapSizeMax
){
4284 nMap
= pFd
->mmapSizeMax
;
4286 nMap
&= ~(sqlite3_int64
)(winSysInfo
.dwPageSize
- 1);
4288 if( nMap
==0 && pFd
->mmapSize
>0 ){
4291 if( nMap
!=pFd
->mmapSize
){
4293 DWORD protect
= PAGE_READONLY
;
4294 DWORD flags
= FILE_MAP_READ
;
4297 #ifdef SQLITE_MMAP_READWRITE
4298 if( (pFd
->ctrlFlags
& WINFILE_RDONLY
)==0 ){
4299 protect
= PAGE_READWRITE
;
4300 flags
|= FILE_MAP_WRITE
;
4304 pFd
->hMap
= osCreateFileMappingFromApp(pFd
->h
, NULL
, protect
, nMap
, NULL
);
4305 #elif defined(SQLITE_WIN32_HAS_WIDE)
4306 pFd
->hMap
= osCreateFileMappingW(pFd
->h
, NULL
, protect
,
4307 (DWORD
)((nMap
>>32) & 0xffffffff),
4308 (DWORD
)(nMap
& 0xffffffff), NULL
);
4309 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
4310 pFd
->hMap
= osCreateFileMappingA(pFd
->h
, NULL
, protect
,
4311 (DWORD
)((nMap
>>32) & 0xffffffff),
4312 (DWORD
)(nMap
& 0xffffffff), NULL
);
4314 if( pFd
->hMap
==NULL
){
4315 pFd
->lastErrno
= osGetLastError();
4316 rc
= winLogError(SQLITE_IOERR_MMAP
, pFd
->lastErrno
,
4317 "winMapfile1", pFd
->zPath
);
4318 /* Log the error, but continue normal operation using xRead/xWrite */
4319 OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
4320 osGetCurrentProcessId(), pFd
, sqlite3ErrName(rc
)));
4323 assert( (nMap
% winSysInfo
.dwPageSize
)==0 );
4324 assert( sizeof(SIZE_T
)==sizeof(sqlite3_int64
) || nMap
<=0xffffffff );
4326 pNew
= osMapViewOfFileFromApp(pFd
->hMap
, flags
, 0, (SIZE_T
)nMap
);
4328 pNew
= osMapViewOfFile(pFd
->hMap
, flags
, 0, 0, (SIZE_T
)nMap
);
4331 osCloseHandle(pFd
->hMap
);
4333 pFd
->lastErrno
= osGetLastError();
4334 rc
= winLogError(SQLITE_IOERR_MMAP
, pFd
->lastErrno
,
4335 "winMapfile2", pFd
->zPath
);
4336 /* Log the error, but continue normal operation using xRead/xWrite */
4337 OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
4338 osGetCurrentProcessId(), pFd
, sqlite3ErrName(rc
)));
4341 pFd
->pMapRegion
= pNew
;
4342 pFd
->mmapSize
= nMap
;
4343 pFd
->mmapSizeActual
= nMap
;
4346 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
4347 osGetCurrentProcessId(), pFd
));
4350 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
4353 ** If possible, return a pointer to a mapping of file fd starting at offset
4354 ** iOff. The mapping must be valid for at least nAmt bytes.
4356 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4357 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4358 ** Finally, if an error does occur, return an SQLite error code. The final
4359 ** value of *pp is undefined in this case.
4361 ** If this function does return a pointer, the caller must eventually
4362 ** release the reference by calling winUnfetch().
4364 static int winFetch(sqlite3_file
*fd
, i64 iOff
, int nAmt
, void **pp
){
4365 #if SQLITE_MAX_MMAP_SIZE>0
4366 winFile
*pFd
= (winFile
*)fd
; /* The underlying database file */
4370 OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
4371 osGetCurrentProcessId(), fd
, iOff
, nAmt
, pp
));
4373 #if SQLITE_MAX_MMAP_SIZE>0
4374 if( pFd
->mmapSizeMax
>0 ){
4375 if( pFd
->pMapRegion
==0 ){
4376 int rc
= winMapfile(pFd
, -1);
4377 if( rc
!=SQLITE_OK
){
4378 OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
4379 osGetCurrentProcessId(), pFd
, sqlite3ErrName(rc
)));
4383 if( pFd
->mmapSize
>= iOff
+nAmt
){
4384 *pp
= &((u8
*)pFd
->pMapRegion
)[iOff
];
4390 OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
4391 osGetCurrentProcessId(), fd
, pp
, *pp
));
4396 ** If the third argument is non-NULL, then this function releases a
4397 ** reference obtained by an earlier call to winFetch(). The second
4398 ** argument passed to this function must be the same as the corresponding
4399 ** argument that was passed to the winFetch() invocation.
4401 ** Or, if the third argument is NULL, then this function is being called
4402 ** to inform the VFS layer that, according to POSIX, any existing mapping
4403 ** may now be invalid and should be unmapped.
4405 static int winUnfetch(sqlite3_file
*fd
, i64 iOff
, void *p
){
4406 #if SQLITE_MAX_MMAP_SIZE>0
4407 winFile
*pFd
= (winFile
*)fd
; /* The underlying database file */
4409 /* If p==0 (unmap the entire file) then there must be no outstanding
4410 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4411 ** then there must be at least one outstanding. */
4412 assert( (p
==0)==(pFd
->nFetchOut
==0) );
4414 /* If p!=0, it must match the iOff value. */
4415 assert( p
==0 || p
==&((u8
*)pFd
->pMapRegion
)[iOff
] );
4417 OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
4418 osGetCurrentProcessId(), pFd
, iOff
, p
));
4423 /* FIXME: If Windows truly always prevents truncating or deleting a
4424 ** file while a mapping is held, then the following winUnmapfile() call
4425 ** is unnecessary can be omitted - potentially improving
4430 assert( pFd
->nFetchOut
>=0 );
4433 OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
4434 osGetCurrentProcessId(), fd
));
4439 ** Here ends the implementation of all sqlite3_file methods.
4441 ********************** End sqlite3_file Methods *******************************
4442 ******************************************************************************/
4445 ** This vector defines all the methods that can operate on an
4446 ** sqlite3_file for win32.
4448 static const sqlite3_io_methods winIoMethod
= {
4450 winClose
, /* xClose */
4451 winRead
, /* xRead */
4452 winWrite
, /* xWrite */
4453 winTruncate
, /* xTruncate */
4454 winSync
, /* xSync */
4455 winFileSize
, /* xFileSize */
4456 winLock
, /* xLock */
4457 winUnlock
, /* xUnlock */
4458 winCheckReservedLock
, /* xCheckReservedLock */
4459 winFileControl
, /* xFileControl */
4460 winSectorSize
, /* xSectorSize */
4461 winDeviceCharacteristics
, /* xDeviceCharacteristics */
4462 winShmMap
, /* xShmMap */
4463 winShmLock
, /* xShmLock */
4464 winShmBarrier
, /* xShmBarrier */
4465 winShmUnmap
, /* xShmUnmap */
4466 winFetch
, /* xFetch */
4467 winUnfetch
/* xUnfetch */
4471 ** This vector defines all the methods that can operate on an
4472 ** sqlite3_file for win32 without performing any locking.
4474 static const sqlite3_io_methods winIoNolockMethod
= {
4476 winClose
, /* xClose */
4477 winRead
, /* xRead */
4478 winWrite
, /* xWrite */
4479 winTruncate
, /* xTruncate */
4480 winSync
, /* xSync */
4481 winFileSize
, /* xFileSize */
4482 winNolockLock
, /* xLock */
4483 winNolockUnlock
, /* xUnlock */
4484 winNolockCheckReservedLock
, /* xCheckReservedLock */
4485 winFileControl
, /* xFileControl */
4486 winSectorSize
, /* xSectorSize */
4487 winDeviceCharacteristics
, /* xDeviceCharacteristics */
4488 winShmMap
, /* xShmMap */
4489 winShmLock
, /* xShmLock */
4490 winShmBarrier
, /* xShmBarrier */
4491 winShmUnmap
, /* xShmUnmap */
4492 winFetch
, /* xFetch */
4493 winUnfetch
/* xUnfetch */
4496 static winVfsAppData winAppData
= {
4497 &winIoMethod
, /* pMethod */
4502 static winVfsAppData winNolockAppData
= {
4503 &winIoNolockMethod
, /* pMethod */
4508 /****************************************************************************
4509 **************************** sqlite3_vfs methods ****************************
4511 ** This division contains the implementation of methods on the
4512 ** sqlite3_vfs object.
4515 #if defined(__CYGWIN__)
4517 ** Convert a filename from whatever the underlying operating system
4518 ** supports for filenames into UTF-8. Space to hold the result is
4519 ** obtained from malloc and must be freed by the calling function.
4521 static char *winConvertToUtf8Filename(const void *zFilename
){
4522 char *zConverted
= 0;
4524 zConverted
= winUnicodeToUtf8(zFilename
);
4526 #ifdef SQLITE_WIN32_HAS_ANSI
4528 zConverted
= winMbcsToUtf8(zFilename
, osAreFileApisANSI());
4531 /* caller will handle out of memory */
4537 ** Convert a UTF-8 filename into whatever form the underlying
4538 ** operating system wants filenames in. Space to hold the result
4539 ** is obtained from malloc and must be freed by the calling
4542 static void *winConvertFromUtf8Filename(const char *zFilename
){
4543 void *zConverted
= 0;
4545 zConverted
= winUtf8ToUnicode(zFilename
);
4547 #ifdef SQLITE_WIN32_HAS_ANSI
4549 zConverted
= winUtf8ToMbcs(zFilename
, osAreFileApisANSI());
4552 /* caller will handle out of memory */
4557 ** This function returns non-zero if the specified UTF-8 string buffer
4558 ** ends with a directory separator character or one was successfully
4561 static int winMakeEndInDirSep(int nBuf
, char *zBuf
){
4563 int nLen
= sqlite3Strlen30(zBuf
);
4565 if( winIsDirSep(zBuf
[nLen
-1]) ){
4567 }else if( nLen
+1<nBuf
){
4568 zBuf
[nLen
] = winGetDirSep();
4569 zBuf
[nLen
+1] = '\0';
4578 ** Create a temporary file name and store the resulting pointer into pzBuf.
4579 ** The pointer returned in pzBuf must be freed via sqlite3_free().
4581 static int winGetTempname(sqlite3_vfs
*pVfs
, char **pzBuf
){
4582 static char zChars
[] =
4583 "abcdefghijklmnopqrstuvwxyz"
4584 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4587 int nPre
= sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX
);
4588 int nMax
, nBuf
, nDir
, nLen
;
4591 /* It's odd to simulate an io-error here, but really this is just
4592 ** using the io-error infrastructure to test that SQLite handles this
4593 ** function failing.
4595 SimulateIOError( return SQLITE_IOERR
);
4597 /* Allocate a temporary buffer to store the fully qualified file
4598 ** name for the temporary file. If this fails, we cannot continue.
4600 nMax
= pVfs
->mxPathname
; nBuf
= nMax
+ 2;
4601 zBuf
= sqlite3MallocZero( nBuf
);
4603 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4604 return SQLITE_IOERR_NOMEM_BKPT
;
4607 /* Figure out the effective temporary directory. First, check if one
4608 ** has been explicitly set by the application; otherwise, use the one
4609 ** configured by the operating system.
4611 nDir
= nMax
- (nPre
+ 15);
4613 if( sqlite3_temp_directory
){
4614 int nDirLen
= sqlite3Strlen30(sqlite3_temp_directory
);
4616 if( !winIsDirSep(sqlite3_temp_directory
[nDirLen
-1]) ){
4621 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
4622 return winLogError(SQLITE_ERROR
, 0, "winGetTempname1", 0);
4624 sqlite3_snprintf(nMax
, zBuf
, "%s", sqlite3_temp_directory
);
4627 #if defined(__CYGWIN__)
4629 static const char *azDirs
[] = {
4630 0, /* getenv("SQLITE_TMPDIR") */
4631 0, /* getenv("TMPDIR") */
4632 0, /* getenv("TMP") */
4633 0, /* getenv("TEMP") */
4634 0, /* getenv("USERPROFILE") */
4639 0 /* List terminator */
4642 const char *zDir
= 0;
4644 if( !azDirs
[0] ) azDirs
[0] = getenv("SQLITE_TMPDIR");
4645 if( !azDirs
[1] ) azDirs
[1] = getenv("TMPDIR");
4646 if( !azDirs
[2] ) azDirs
[2] = getenv("TMP");
4647 if( !azDirs
[3] ) azDirs
[3] = getenv("TEMP");
4648 if( !azDirs
[4] ) azDirs
[4] = getenv("USERPROFILE");
4649 for(i
=0; i
<sizeof(azDirs
)/sizeof(azDirs
[0]); zDir
=azDirs
[i
++]){
4651 if( zDir
==0 ) continue;
4652 /* If the path starts with a drive letter followed by the colon
4653 ** character, assume it is already a native Win32 path; otherwise,
4654 ** it must be converted to a native Win32 path via the Cygwin API
4655 ** prior to using it.
4657 if( winIsDriveLetterAndColon(zDir
) ){
4658 zConverted
= winConvertFromUtf8Filename(zDir
);
4661 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4662 return SQLITE_IOERR_NOMEM_BKPT
;
4664 if( winIsDir(zConverted
) ){
4665 sqlite3_snprintf(nMax
, zBuf
, "%s", zDir
);
4666 sqlite3_free(zConverted
);
4669 sqlite3_free(zConverted
);
4671 zConverted
= sqlite3MallocZero( nMax
+1 );
4674 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4675 return SQLITE_IOERR_NOMEM_BKPT
;
4677 if( cygwin_conv_path(
4678 osIsNT() ? CCP_POSIX_TO_WIN_W
: CCP_POSIX_TO_WIN_A
, zDir
,
4679 zConverted
, nMax
+1)<0 ){
4680 sqlite3_free(zConverted
);
4682 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
4683 return winLogError(SQLITE_IOERR_CONVPATH
, (DWORD
)errno
,
4684 "winGetTempname2", zDir
);
4686 if( winIsDir(zConverted
) ){
4687 /* At this point, we know the candidate directory exists and should
4688 ** be used. However, we may need to convert the string containing
4689 ** its name into UTF-8 (i.e. if it is UTF-16 right now).
4691 char *zUtf8
= winConvertToUtf8Filename(zConverted
);
4693 sqlite3_free(zConverted
);
4695 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4696 return SQLITE_IOERR_NOMEM_BKPT
;
4698 sqlite3_snprintf(nMax
, zBuf
, "%s", zUtf8
);
4699 sqlite3_free(zUtf8
);
4700 sqlite3_free(zConverted
);
4703 sqlite3_free(zConverted
);
4707 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
4708 else if( osIsNT() ){
4710 LPWSTR zWidePath
= sqlite3MallocZero( nMax
*sizeof(WCHAR
) );
4713 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4714 return SQLITE_IOERR_NOMEM_BKPT
;
4716 if( osGetTempPathW(nMax
, zWidePath
)==0 ){
4717 sqlite3_free(zWidePath
);
4719 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
4720 return winLogError(SQLITE_IOERR_GETTEMPPATH
, osGetLastError(),
4721 "winGetTempname2", 0);
4723 zMulti
= winUnicodeToUtf8(zWidePath
);
4725 sqlite3_snprintf(nMax
, zBuf
, "%s", zMulti
);
4726 sqlite3_free(zMulti
);
4727 sqlite3_free(zWidePath
);
4729 sqlite3_free(zWidePath
);
4731 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4732 return SQLITE_IOERR_NOMEM_BKPT
;
4735 #ifdef SQLITE_WIN32_HAS_ANSI
4738 char *zMbcsPath
= sqlite3MallocZero( nMax
);
4741 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4742 return SQLITE_IOERR_NOMEM_BKPT
;
4744 if( osGetTempPathA(nMax
, zMbcsPath
)==0 ){
4746 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
4747 return winLogError(SQLITE_IOERR_GETTEMPPATH
, osGetLastError(),
4748 "winGetTempname3", 0);
4750 zUtf8
= winMbcsToUtf8(zMbcsPath
, osAreFileApisANSI());
4752 sqlite3_snprintf(nMax
, zBuf
, "%s", zUtf8
);
4753 sqlite3_free(zUtf8
);
4756 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
4757 return SQLITE_IOERR_NOMEM_BKPT
;
4760 #endif /* SQLITE_WIN32_HAS_ANSI */
4761 #endif /* !SQLITE_OS_WINRT */
4764 ** Check to make sure the temporary directory ends with an appropriate
4765 ** separator. If it does not and there is not enough space left to add
4768 if( !winMakeEndInDirSep(nDir
+1, zBuf
) ){
4770 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
4771 return winLogError(SQLITE_ERROR
, 0, "winGetTempname4", 0);
4775 ** Check that the output buffer is large enough for the temporary file
4776 ** name in the following format:
4778 ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
4780 ** If not, return SQLITE_ERROR. The number 17 is used here in order to
4781 ** account for the space used by the 15 character random suffix and the
4782 ** two trailing NUL characters. The final directory separator character
4783 ** has already added if it was not already present.
4785 nLen
= sqlite3Strlen30(zBuf
);
4786 if( (nLen
+ nPre
+ 17) > nBuf
){
4788 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
4789 return winLogError(SQLITE_ERROR
, 0, "winGetTempname5", 0);
4792 sqlite3_snprintf(nBuf
-16-nLen
, zBuf
+nLen
, SQLITE_TEMP_FILE_PREFIX
);
4794 j
= sqlite3Strlen30(zBuf
);
4795 sqlite3_randomness(15, &zBuf
[j
]);
4796 for(i
=0; i
<15; i
++, j
++){
4797 zBuf
[j
] = (char)zChars
[ ((unsigned char)zBuf
[j
])%(sizeof(zChars
)-1) ];
4803 OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf
));
4808 ** Return TRUE if the named file is really a directory. Return false if
4809 ** it is something other than a directory, or if there is any kind of memory
4810 ** allocation failure.
4812 static int winIsDir(const void *zConverted
){
4819 WIN32_FILE_ATTRIBUTE_DATA sAttrData
;
4820 memset(&sAttrData
, 0, sizeof(sAttrData
));
4821 while( !(rc
= osGetFileAttributesExW((LPCWSTR
)zConverted
,
4822 GetFileExInfoStandard
,
4823 &sAttrData
)) && winRetryIoerr(&cnt
, &lastErrno
) ){}
4825 return 0; /* Invalid name? */
4827 attr
= sAttrData
.dwFileAttributes
;
4828 #if SQLITE_OS_WINCE==0
4830 attr
= osGetFileAttributesA((char*)zConverted
);
4833 return (attr
!=INVALID_FILE_ATTRIBUTES
) && (attr
&FILE_ATTRIBUTE_DIRECTORY
);
4840 sqlite3_vfs
*pVfs
, /* Used to get maximum path length and AppData */
4841 const char *zName
, /* Name of the file (UTF-8) */
4842 sqlite3_file
*id
, /* Write the SQLite file handle here */
4843 int flags
, /* Open mode flags */
4844 int *pOutFlags
/* Status return flags */
4847 DWORD lastErrno
= 0;
4848 DWORD dwDesiredAccess
;
4850 DWORD dwCreationDisposition
;
4851 DWORD dwFlagsAndAttributes
= 0;
4855 winVfsAppData
*pAppData
;
4856 winFile
*pFile
= (winFile
*)id
;
4857 void *zConverted
; /* Filename in OS encoding */
4858 const char *zUtf8Name
= zName
; /* Filename in UTF-8 encoding */
4861 /* If argument zPath is a NULL pointer, this function is required to open
4862 ** a temporary file. Use this buffer to store the file name in.
4864 char *zTmpname
= 0; /* For temporary filename, if necessary. */
4866 int rc
= SQLITE_OK
; /* Function Return Code */
4867 #if !defined(NDEBUG) || SQLITE_OS_WINCE
4868 int eType
= flags
&0xFFFFFF00; /* Type of file to open */
4871 int isExclusive
= (flags
& SQLITE_OPEN_EXCLUSIVE
);
4872 int isDelete
= (flags
& SQLITE_OPEN_DELETEONCLOSE
);
4873 int isCreate
= (flags
& SQLITE_OPEN_CREATE
);
4874 int isReadonly
= (flags
& SQLITE_OPEN_READONLY
);
4875 int isReadWrite
= (flags
& SQLITE_OPEN_READWRITE
);
4878 int isOpenJournal
= (isCreate
&& (
4879 eType
==SQLITE_OPEN_MASTER_JOURNAL
4880 || eType
==SQLITE_OPEN_MAIN_JOURNAL
4881 || eType
==SQLITE_OPEN_WAL
4885 OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
4886 zUtf8Name
, id
, flags
, pOutFlags
));
4888 /* Check the following statements are true:
4890 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4891 ** (b) if CREATE is set, then READWRITE must also be set, and
4892 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
4893 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
4895 assert((isReadonly
==0 || isReadWrite
==0) && (isReadWrite
|| isReadonly
));
4896 assert(isCreate
==0 || isReadWrite
);
4897 assert(isExclusive
==0 || isCreate
);
4898 assert(isDelete
==0 || isCreate
);
4900 /* The main DB, main journal, WAL file and master journal are never
4901 ** automatically deleted. Nor are they ever temporary files. */
4902 assert( (!isDelete
&& zName
) || eType
!=SQLITE_OPEN_MAIN_DB
);
4903 assert( (!isDelete
&& zName
) || eType
!=SQLITE_OPEN_MAIN_JOURNAL
);
4904 assert( (!isDelete
&& zName
) || eType
!=SQLITE_OPEN_MASTER_JOURNAL
);
4905 assert( (!isDelete
&& zName
) || eType
!=SQLITE_OPEN_WAL
);
4907 /* Assert that the upper layer has set one of the "file-type" flags. */
4908 assert( eType
==SQLITE_OPEN_MAIN_DB
|| eType
==SQLITE_OPEN_TEMP_DB
4909 || eType
==SQLITE_OPEN_MAIN_JOURNAL
|| eType
==SQLITE_OPEN_TEMP_JOURNAL
4910 || eType
==SQLITE_OPEN_SUBJOURNAL
|| eType
==SQLITE_OPEN_MASTER_JOURNAL
4911 || eType
==SQLITE_OPEN_TRANSIENT_DB
|| eType
==SQLITE_OPEN_WAL
4915 memset(pFile
, 0, sizeof(winFile
));
4916 pFile
->h
= INVALID_HANDLE_VALUE
;
4919 if( !zUtf8Name
&& !sqlite3_temp_directory
){
4920 sqlite3_log(SQLITE_ERROR
,
4921 "sqlite3_temp_directory variable should be set for WinRT");
4925 /* If the second argument to this function is NULL, generate a
4926 ** temporary file name to use
4929 assert( isDelete
&& !isOpenJournal
);
4930 rc
= winGetTempname(pVfs
, &zTmpname
);
4931 if( rc
!=SQLITE_OK
){
4932 OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name
, sqlite3ErrName(rc
)));
4935 zUtf8Name
= zTmpname
;
4938 /* Database filenames are double-zero terminated if they are not
4939 ** URIs with parameters. Hence, they can always be passed into
4940 ** sqlite3_uri_parameter().
4942 assert( (eType
!=SQLITE_OPEN_MAIN_DB
) || (flags
& SQLITE_OPEN_URI
) ||
4943 zUtf8Name
[sqlite3Strlen30(zUtf8Name
)+1]==0 );
4945 /* Convert the filename to the system encoding. */
4946 zConverted
= winConvertFromUtf8Filename(zUtf8Name
);
4947 if( zConverted
==0 ){
4948 sqlite3_free(zTmpname
);
4949 OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name
));
4950 return SQLITE_IOERR_NOMEM_BKPT
;
4953 if( winIsDir(zConverted
) ){
4954 sqlite3_free(zConverted
);
4955 sqlite3_free(zTmpname
);
4956 OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name
));
4957 return SQLITE_CANTOPEN_ISDIR
;
4961 dwDesiredAccess
= GENERIC_READ
| GENERIC_WRITE
;
4963 dwDesiredAccess
= GENERIC_READ
;
4966 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
4967 ** created. SQLite doesn't use it to indicate "exclusive access"
4968 ** as it is usually understood.
4971 /* Creates a new file, only if it does not already exist. */
4972 /* If the file exists, it fails. */
4973 dwCreationDisposition
= CREATE_NEW
;
4974 }else if( isCreate
){
4975 /* Open existing file, or create if it doesn't exist */
4976 dwCreationDisposition
= OPEN_ALWAYS
;
4978 /* Opens a file, only if it exists. */
4979 dwCreationDisposition
= OPEN_EXISTING
;
4982 dwShareMode
= FILE_SHARE_READ
| FILE_SHARE_WRITE
;
4986 dwFlagsAndAttributes
= FILE_ATTRIBUTE_HIDDEN
;
4989 dwFlagsAndAttributes
= FILE_ATTRIBUTE_TEMPORARY
4990 | FILE_ATTRIBUTE_HIDDEN
4991 | FILE_FLAG_DELETE_ON_CLOSE
;
4994 dwFlagsAndAttributes
= FILE_ATTRIBUTE_NORMAL
;
4996 /* Reports from the internet are that performance is always
4997 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
4999 dwFlagsAndAttributes
|= FILE_FLAG_RANDOM_ACCESS
;
5004 CREATEFILE2_EXTENDED_PARAMETERS extendedParameters
;
5005 extendedParameters
.dwSize
= sizeof(CREATEFILE2_EXTENDED_PARAMETERS
);
5006 extendedParameters
.dwFileAttributes
=
5007 dwFlagsAndAttributes
& FILE_ATTRIBUTE_MASK
;
5008 extendedParameters
.dwFileFlags
= dwFlagsAndAttributes
& FILE_FLAG_MASK
;
5009 extendedParameters
.dwSecurityQosFlags
= SECURITY_ANONYMOUS
;
5010 extendedParameters
.lpSecurityAttributes
= NULL
;
5011 extendedParameters
.hTemplateFile
= NULL
;
5012 while( (h
= osCreateFile2((LPCWSTR
)zConverted
,
5015 dwCreationDisposition
,
5016 &extendedParameters
))==INVALID_HANDLE_VALUE
&&
5017 winRetryIoerr(&cnt
, &lastErrno
) ){
5021 while( (h
= osCreateFileW((LPCWSTR
)zConverted
,
5024 dwCreationDisposition
,
5025 dwFlagsAndAttributes
,
5026 NULL
))==INVALID_HANDLE_VALUE
&&
5027 winRetryIoerr(&cnt
, &lastErrno
) ){
5032 #ifdef SQLITE_WIN32_HAS_ANSI
5034 while( (h
= osCreateFileA((LPCSTR
)zConverted
,
5037 dwCreationDisposition
,
5038 dwFlagsAndAttributes
,
5039 NULL
))==INVALID_HANDLE_VALUE
&&
5040 winRetryIoerr(&cnt
, &lastErrno
) ){
5045 winLogIoerr(cnt
, __LINE__
);
5047 OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h
, zUtf8Name
,
5048 dwDesiredAccess
, (h
==INVALID_HANDLE_VALUE
) ? "failed" : "ok"));
5050 if( h
==INVALID_HANDLE_VALUE
){
5051 pFile
->lastErrno
= lastErrno
;
5052 winLogError(SQLITE_CANTOPEN
, pFile
->lastErrno
, "winOpen", zUtf8Name
);
5053 sqlite3_free(zConverted
);
5054 sqlite3_free(zTmpname
);
5055 if( isReadWrite
&& !isExclusive
){
5056 return winOpen(pVfs
, zName
, id
,
5057 ((flags
|SQLITE_OPEN_READONLY
) &
5058 ~(SQLITE_OPEN_CREATE
|SQLITE_OPEN_READWRITE
)),
5061 return SQLITE_CANTOPEN_BKPT
;
5067 *pOutFlags
= SQLITE_OPEN_READWRITE
;
5069 *pOutFlags
= SQLITE_OPEN_READONLY
;
5073 OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
5074 "rc=%s\n", h
, zUtf8Name
, dwDesiredAccess
, pOutFlags
, pOutFlags
?
5075 *pOutFlags
: 0, (h
==INVALID_HANDLE_VALUE
) ? "failed" : "ok"));
5077 pAppData
= (winVfsAppData
*)pVfs
->pAppData
;
5081 if( isReadWrite
&& eType
==SQLITE_OPEN_MAIN_DB
5082 && ((pAppData
==NULL
) || !pAppData
->bNoLock
)
5083 && (rc
= winceCreateLock(zName
, pFile
))!=SQLITE_OK
5086 sqlite3_free(zConverted
);
5087 sqlite3_free(zTmpname
);
5088 OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName
, sqlite3ErrName(rc
)));
5093 pFile
->zDeleteOnClose
= zConverted
;
5097 sqlite3_free(zConverted
);
5100 sqlite3_free(zTmpname
);
5101 pFile
->pMethod
= pAppData
? pAppData
->pMethod
: &winIoMethod
;
5105 pFile
->ctrlFlags
|= WINFILE_RDONLY
;
5107 if( sqlite3_uri_boolean(zName
, "psow", SQLITE_POWERSAFE_OVERWRITE
) ){
5108 pFile
->ctrlFlags
|= WINFILE_PSOW
;
5110 pFile
->lastErrno
= NO_ERROR
;
5111 pFile
->zPath
= zName
;
5112 #if SQLITE_MAX_MMAP_SIZE>0
5114 pFile
->pMapRegion
= 0;
5115 pFile
->mmapSize
= 0;
5116 pFile
->mmapSizeActual
= 0;
5117 pFile
->mmapSizeMax
= sqlite3GlobalConfig
.szMmap
;
5125 ** Delete the named file.
5127 ** Note that Windows does not allow a file to be deleted if some other
5128 ** process has it open. Sometimes a virus scanner or indexing program
5129 ** will open a journal file shortly after it is created in order to do
5130 ** whatever it does. While this other process is holding the
5131 ** file open, we will be unable to delete it. To work around this
5132 ** problem, we delay 100 milliseconds and try to delete again. Up
5133 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
5134 ** up and returning an error.
5136 static int winDelete(
5137 sqlite3_vfs
*pVfs
, /* Not used on win32 */
5138 const char *zFilename
, /* Name of file to delete */
5139 int syncDir
/* Not used on win32 */
5144 DWORD lastErrno
= 0;
5146 UNUSED_PARAMETER(pVfs
);
5147 UNUSED_PARAMETER(syncDir
);
5149 SimulateIOError(return SQLITE_IOERR_DELETE
);
5150 OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename
, syncDir
));
5152 zConverted
= winConvertFromUtf8Filename(zFilename
);
5153 if( zConverted
==0 ){
5154 OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename
));
5155 return SQLITE_IOERR_NOMEM_BKPT
;
5160 WIN32_FILE_ATTRIBUTE_DATA sAttrData
;
5161 memset(&sAttrData
, 0, sizeof(sAttrData
));
5162 if ( osGetFileAttributesExW(zConverted
, GetFileExInfoStandard
,
5164 attr
= sAttrData
.dwFileAttributes
;
5166 lastErrno
= osGetLastError();
5167 if( lastErrno
==ERROR_FILE_NOT_FOUND
5168 || lastErrno
==ERROR_PATH_NOT_FOUND
){
5169 rc
= SQLITE_IOERR_DELETE_NOENT
; /* Already gone? */
5176 attr
= osGetFileAttributesW(zConverted
);
5178 if ( attr
==INVALID_FILE_ATTRIBUTES
){
5179 lastErrno
= osGetLastError();
5180 if( lastErrno
==ERROR_FILE_NOT_FOUND
5181 || lastErrno
==ERROR_PATH_NOT_FOUND
){
5182 rc
= SQLITE_IOERR_DELETE_NOENT
; /* Already gone? */
5188 if ( attr
&FILE_ATTRIBUTE_DIRECTORY
){
5189 rc
= SQLITE_ERROR
; /* Files only. */
5192 if ( osDeleteFileW(zConverted
) ){
5193 rc
= SQLITE_OK
; /* Deleted OK. */
5196 if ( !winRetryIoerr(&cnt
, &lastErrno
) ){
5197 rc
= SQLITE_ERROR
; /* No more retries. */
5202 #ifdef SQLITE_WIN32_HAS_ANSI
5205 attr
= osGetFileAttributesA(zConverted
);
5206 if ( attr
==INVALID_FILE_ATTRIBUTES
){
5207 lastErrno
= osGetLastError();
5208 if( lastErrno
==ERROR_FILE_NOT_FOUND
5209 || lastErrno
==ERROR_PATH_NOT_FOUND
){
5210 rc
= SQLITE_IOERR_DELETE_NOENT
; /* Already gone? */
5216 if ( attr
&FILE_ATTRIBUTE_DIRECTORY
){
5217 rc
= SQLITE_ERROR
; /* Files only. */
5220 if ( osDeleteFileA(zConverted
) ){
5221 rc
= SQLITE_OK
; /* Deleted OK. */
5224 if ( !winRetryIoerr(&cnt
, &lastErrno
) ){
5225 rc
= SQLITE_ERROR
; /* No more retries. */
5231 if( rc
&& rc
!=SQLITE_IOERR_DELETE_NOENT
){
5232 rc
= winLogError(SQLITE_IOERR_DELETE
, lastErrno
, "winDelete", zFilename
);
5234 winLogIoerr(cnt
, __LINE__
);
5236 sqlite3_free(zConverted
);
5237 OSTRACE(("DELETE name=%s, rc=%s\n", zFilename
, sqlite3ErrName(rc
)));
5242 ** Check the existence and status of a file.
5244 static int winAccess(
5245 sqlite3_vfs
*pVfs
, /* Not used on win32 */
5246 const char *zFilename
, /* Name of file to check */
5247 int flags
, /* Type of test to make on this file */
5248 int *pResOut
/* OUT: Result */
5252 DWORD lastErrno
= 0;
5254 UNUSED_PARAMETER(pVfs
);
5256 SimulateIOError( return SQLITE_IOERR_ACCESS
; );
5257 OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
5258 zFilename
, flags
, pResOut
));
5260 zConverted
= winConvertFromUtf8Filename(zFilename
);
5261 if( zConverted
==0 ){
5262 OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename
));
5263 return SQLITE_IOERR_NOMEM_BKPT
;
5267 WIN32_FILE_ATTRIBUTE_DATA sAttrData
;
5268 memset(&sAttrData
, 0, sizeof(sAttrData
));
5269 while( !(rc
= osGetFileAttributesExW((LPCWSTR
)zConverted
,
5270 GetFileExInfoStandard
,
5271 &sAttrData
)) && winRetryIoerr(&cnt
, &lastErrno
) ){}
5273 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
5274 ** as if it does not exist.
5276 if( flags
==SQLITE_ACCESS_EXISTS
5277 && sAttrData
.nFileSizeHigh
==0
5278 && sAttrData
.nFileSizeLow
==0 ){
5279 attr
= INVALID_FILE_ATTRIBUTES
;
5281 attr
= sAttrData
.dwFileAttributes
;
5284 winLogIoerr(cnt
, __LINE__
);
5285 if( lastErrno
!=ERROR_FILE_NOT_FOUND
&& lastErrno
!=ERROR_PATH_NOT_FOUND
){
5286 sqlite3_free(zConverted
);
5287 return winLogError(SQLITE_IOERR_ACCESS
, lastErrno
, "winAccess",
5290 attr
= INVALID_FILE_ATTRIBUTES
;
5294 #ifdef SQLITE_WIN32_HAS_ANSI
5296 attr
= osGetFileAttributesA((char*)zConverted
);
5299 sqlite3_free(zConverted
);
5301 case SQLITE_ACCESS_READ
:
5302 case SQLITE_ACCESS_EXISTS
:
5303 rc
= attr
!=INVALID_FILE_ATTRIBUTES
;
5305 case SQLITE_ACCESS_READWRITE
:
5306 rc
= attr
!=INVALID_FILE_ATTRIBUTES
&&
5307 (attr
& FILE_ATTRIBUTE_READONLY
)==0;
5310 assert(!"Invalid flags argument");
5313 OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
5314 zFilename
, pResOut
, *pResOut
));
5319 ** Returns non-zero if the specified path name starts with a drive letter
5320 ** followed by a colon character.
5322 static BOOL
winIsDriveLetterAndColon(
5323 const char *zPathname
5325 return ( sqlite3Isalpha(zPathname
[0]) && zPathname
[1]==':' );
5329 ** Returns non-zero if the specified path name should be used verbatim. If
5330 ** non-zero is returned from this function, the calling function must simply
5331 ** use the provided path name verbatim -OR- resolve it into a full path name
5332 ** using the GetFullPathName Win32 API function (if available).
5334 static BOOL
winIsVerbatimPathname(
5335 const char *zPathname
5338 ** If the path name starts with a forward slash or a backslash, it is either
5339 ** a legal UNC name, a volume relative path, or an absolute path name in the
5340 ** "Unix" format on Windows. There is no easy way to differentiate between
5341 ** the final two cases; therefore, we return the safer return value of TRUE
5342 ** so that callers of this function will simply use it verbatim.
5344 if ( winIsDirSep(zPathname
[0]) ){
5349 ** If the path name starts with a letter and a colon it is either a volume
5350 ** relative path or an absolute path. Callers of this function must not
5351 ** attempt to treat it as a relative path name (i.e. they should simply use
5354 if ( winIsDriveLetterAndColon(zPathname
) ){
5359 ** If we get to this point, the path name should almost certainly be a purely
5360 ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
5366 ** Turn a relative pathname into a full pathname. Write the full
5367 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
5370 static int winFullPathname(
5371 sqlite3_vfs
*pVfs
, /* Pointer to vfs object */
5372 const char *zRelative
, /* Possibly relative input path */
5373 int nFull
, /* Size of output buffer in bytes */
5374 char *zFull
/* Output buffer */
5376 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
5382 /* If this path name begins with "/X:", where "X" is any alphabetic
5383 ** character, discard the initial "/" from the pathname.
5385 if( zRelative
[0]=='/' && winIsDriveLetterAndColon(zRelative
+1) ){
5389 #if defined(__CYGWIN__)
5390 SimulateIOError( return SQLITE_ERROR
);
5391 UNUSED_PARAMETER(nFull
);
5392 assert( nFull
>=pVfs
->mxPathname
);
5393 if ( sqlite3_data_directory
&& !winIsVerbatimPathname(zRelative
) ){
5395 ** NOTE: We are dealing with a relative path name and the data
5396 ** directory has been set. Therefore, use it as the basis
5397 ** for converting the relative path name to an absolute
5398 ** one by prepending the data directory and a slash.
5400 char *zOut
= sqlite3MallocZero( pVfs
->mxPathname
+1 );
5402 return SQLITE_IOERR_NOMEM_BKPT
;
5404 if( cygwin_conv_path(
5405 (osIsNT() ? CCP_POSIX_TO_WIN_W
: CCP_POSIX_TO_WIN_A
) |
5406 CCP_RELATIVE
, zRelative
, zOut
, pVfs
->mxPathname
+1)<0 ){
5408 return winLogError(SQLITE_CANTOPEN_CONVPATH
, (DWORD
)errno
,
5409 "winFullPathname1", zRelative
);
5411 char *zUtf8
= winConvertToUtf8Filename(zOut
);
5414 return SQLITE_IOERR_NOMEM_BKPT
;
5416 sqlite3_snprintf(MIN(nFull
, pVfs
->mxPathname
), zFull
, "%s%c%s",
5417 sqlite3_data_directory
, winGetDirSep(), zUtf8
);
5418 sqlite3_free(zUtf8
);
5422 char *zOut
= sqlite3MallocZero( pVfs
->mxPathname
+1 );
5424 return SQLITE_IOERR_NOMEM_BKPT
;
5426 if( cygwin_conv_path(
5427 (osIsNT() ? CCP_POSIX_TO_WIN_W
: CCP_POSIX_TO_WIN_A
),
5428 zRelative
, zOut
, pVfs
->mxPathname
+1)<0 ){
5430 return winLogError(SQLITE_CANTOPEN_CONVPATH
, (DWORD
)errno
,
5431 "winFullPathname2", zRelative
);
5433 char *zUtf8
= winConvertToUtf8Filename(zOut
);
5436 return SQLITE_IOERR_NOMEM_BKPT
;
5438 sqlite3_snprintf(MIN(nFull
, pVfs
->mxPathname
), zFull
, "%s", zUtf8
);
5439 sqlite3_free(zUtf8
);
5446 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
5447 SimulateIOError( return SQLITE_ERROR
);
5448 /* WinCE has no concept of a relative pathname, or so I am told. */
5449 /* WinRT has no way to convert a relative path to an absolute one. */
5450 if ( sqlite3_data_directory
&& !winIsVerbatimPathname(zRelative
) ){
5452 ** NOTE: We are dealing with a relative path name and the data
5453 ** directory has been set. Therefore, use it as the basis
5454 ** for converting the relative path name to an absolute
5455 ** one by prepending the data directory and a backslash.
5457 sqlite3_snprintf(MIN(nFull
, pVfs
->mxPathname
), zFull
, "%s%c%s",
5458 sqlite3_data_directory
, winGetDirSep(), zRelative
);
5460 sqlite3_snprintf(MIN(nFull
, pVfs
->mxPathname
), zFull
, "%s", zRelative
);
5465 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
5466 /* It's odd to simulate an io-error here, but really this is just
5467 ** using the io-error infrastructure to test that SQLite handles this
5468 ** function failing. This function could fail if, for example, the
5469 ** current working directory has been unlinked.
5471 SimulateIOError( return SQLITE_ERROR
);
5472 if ( sqlite3_data_directory
&& !winIsVerbatimPathname(zRelative
) ){
5474 ** NOTE: We are dealing with a relative path name and the data
5475 ** directory has been set. Therefore, use it as the basis
5476 ** for converting the relative path name to an absolute
5477 ** one by prepending the data directory and a backslash.
5479 sqlite3_snprintf(MIN(nFull
, pVfs
->mxPathname
), zFull
, "%s%c%s",
5480 sqlite3_data_directory
, winGetDirSep(), zRelative
);
5483 zConverted
= winConvertFromUtf8Filename(zRelative
);
5484 if( zConverted
==0 ){
5485 return SQLITE_IOERR_NOMEM_BKPT
;
5489 nByte
= osGetFullPathNameW((LPCWSTR
)zConverted
, 0, 0, 0);
5491 sqlite3_free(zConverted
);
5492 return winLogError(SQLITE_CANTOPEN_FULLPATH
, osGetLastError(),
5493 "winFullPathname1", zRelative
);
5496 zTemp
= sqlite3MallocZero( nByte
*sizeof(zTemp
[0]) );
5498 sqlite3_free(zConverted
);
5499 return SQLITE_IOERR_NOMEM_BKPT
;
5501 nByte
= osGetFullPathNameW((LPCWSTR
)zConverted
, nByte
, zTemp
, 0);
5503 sqlite3_free(zConverted
);
5504 sqlite3_free(zTemp
);
5505 return winLogError(SQLITE_CANTOPEN_FULLPATH
, osGetLastError(),
5506 "winFullPathname2", zRelative
);
5508 sqlite3_free(zConverted
);
5509 zOut
= winUnicodeToUtf8(zTemp
);
5510 sqlite3_free(zTemp
);
5512 #ifdef SQLITE_WIN32_HAS_ANSI
5515 nByte
= osGetFullPathNameA((char*)zConverted
, 0, 0, 0);
5517 sqlite3_free(zConverted
);
5518 return winLogError(SQLITE_CANTOPEN_FULLPATH
, osGetLastError(),
5519 "winFullPathname3", zRelative
);
5522 zTemp
= sqlite3MallocZero( nByte
*sizeof(zTemp
[0]) );
5524 sqlite3_free(zConverted
);
5525 return SQLITE_IOERR_NOMEM_BKPT
;
5527 nByte
= osGetFullPathNameA((char*)zConverted
, nByte
, zTemp
, 0);
5529 sqlite3_free(zConverted
);
5530 sqlite3_free(zTemp
);
5531 return winLogError(SQLITE_CANTOPEN_FULLPATH
, osGetLastError(),
5532 "winFullPathname4", zRelative
);
5534 sqlite3_free(zConverted
);
5535 zOut
= winMbcsToUtf8(zTemp
, osAreFileApisANSI());
5536 sqlite3_free(zTemp
);
5540 sqlite3_snprintf(MIN(nFull
, pVfs
->mxPathname
), zFull
, "%s", zOut
);
5544 return SQLITE_IOERR_NOMEM_BKPT
;
5549 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5551 ** Interfaces for opening a shared library, finding entry points
5552 ** within the shared library, and closing the shared library.
5554 static void *winDlOpen(sqlite3_vfs
*pVfs
, const char *zFilename
){
5556 #if defined(__CYGWIN__)
5557 int nFull
= pVfs
->mxPathname
+1;
5558 char *zFull
= sqlite3MallocZero( nFull
);
5559 void *zConverted
= 0;
5561 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename
, (void*)0));
5564 if( winFullPathname(pVfs
, zFilename
, nFull
, zFull
)!=SQLITE_OK
){
5565 sqlite3_free(zFull
);
5566 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename
, (void*)0));
5569 zConverted
= winConvertFromUtf8Filename(zFull
);
5570 sqlite3_free(zFull
);
5572 void *zConverted
= winConvertFromUtf8Filename(zFilename
);
5573 UNUSED_PARAMETER(pVfs
);
5575 if( zConverted
==0 ){
5576 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename
, (void*)0));
5581 h
= osLoadPackagedLibrary((LPCWSTR
)zConverted
, 0);
5583 h
= osLoadLibraryW((LPCWSTR
)zConverted
);
5586 #ifdef SQLITE_WIN32_HAS_ANSI
5588 h
= osLoadLibraryA((char*)zConverted
);
5591 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename
, (void*)h
));
5592 sqlite3_free(zConverted
);
5595 static void winDlError(sqlite3_vfs
*pVfs
, int nBuf
, char *zBufOut
){
5596 UNUSED_PARAMETER(pVfs
);
5597 winGetLastErrorMsg(osGetLastError(), nBuf
, zBufOut
);
5599 static void (*winDlSym(sqlite3_vfs
*pVfs
,void *pH
,const char *zSym
))(void){
5601 UNUSED_PARAMETER(pVfs
);
5602 proc
= osGetProcAddressA((HANDLE
)pH
, zSym
);
5603 OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
5604 (void*)pH
, zSym
, (void*)proc
));
5605 return (void(*)(void))proc
;
5607 static void winDlClose(sqlite3_vfs
*pVfs
, void *pHandle
){
5608 UNUSED_PARAMETER(pVfs
);
5609 osFreeLibrary((HANDLE
)pHandle
);
5610 OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle
));
5612 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5614 #define winDlError 0
5616 #define winDlClose 0
5619 /* State information for the randomness gatherer. */
5620 typedef struct EntropyGatherer EntropyGatherer
;
5621 struct EntropyGatherer
{
5622 unsigned char *a
; /* Gather entropy into this buffer */
5623 int na
; /* Size of a[] in bytes */
5624 int i
; /* XOR next input into a[i] */
5625 int nXor
; /* Number of XOR operations done */
5628 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
5629 /* Mix sz bytes of entropy into p. */
5630 static void xorMemory(EntropyGatherer
*p
, unsigned char *x
, int sz
){
5632 for(j
=0, k
=p
->i
; j
<sz
; j
++){
5634 if( k
>=p
->na
) k
= 0;
5639 #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
5642 ** Write up to nBuf bytes of randomness into zBuf.
5644 static int winRandomness(sqlite3_vfs
*pVfs
, int nBuf
, char *zBuf
){
5645 #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
5646 UNUSED_PARAMETER(pVfs
);
5647 memset(zBuf
, 0, nBuf
);
5651 UNUSED_PARAMETER(pVfs
);
5652 memset(zBuf
, 0, nBuf
);
5653 #if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE
5654 rand_s((unsigned int*)zBuf
); /* rand_s() is not available with MinGW */
5655 #endif /* defined(_MSC_VER) && _MSC_VER>=1400 */
5656 e
.a
= (unsigned char*)zBuf
;
5662 osGetSystemTime(&x
);
5663 xorMemory(&e
, (unsigned char*)&x
, sizeof(SYSTEMTIME
));
5666 DWORD pid
= osGetCurrentProcessId();
5667 xorMemory(&e
, (unsigned char*)&pid
, sizeof(DWORD
));
5671 ULONGLONG cnt
= osGetTickCount64();
5672 xorMemory(&e
, (unsigned char*)&cnt
, sizeof(ULONGLONG
));
5676 DWORD cnt
= osGetTickCount();
5677 xorMemory(&e
, (unsigned char*)&cnt
, sizeof(DWORD
));
5679 #endif /* SQLITE_OS_WINRT */
5682 osQueryPerformanceCounter(&i
);
5683 xorMemory(&e
, (unsigned char*)&i
, sizeof(LARGE_INTEGER
));
5685 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
5688 memset(&id
, 0, sizeof(UUID
));
5690 xorMemory(&e
, (unsigned char*)&id
, sizeof(UUID
));
5691 memset(&id
, 0, sizeof(UUID
));
5692 osUuidCreateSequential(&id
);
5693 xorMemory(&e
, (unsigned char*)&id
, sizeof(UUID
));
5695 #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
5696 return e
.nXor
>nBuf
? nBuf
: e
.nXor
;
5697 #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
5702 ** Sleep for a little while. Return the amount of time slept.
5704 static int winSleep(sqlite3_vfs
*pVfs
, int microsec
){
5705 sqlite3_win32_sleep((microsec
+999)/1000);
5706 UNUSED_PARAMETER(pVfs
);
5707 return ((microsec
+999)/1000)*1000;
5711 ** The following variable, if set to a non-zero value, is interpreted as
5712 ** the number of seconds since 1970 and is used to set the result of
5713 ** sqlite3OsCurrentTime() during testing.
5716 int sqlite3_current_time
= 0; /* Fake system time in seconds since 1970. */
5720 ** Find the current time (in Universal Coordinated Time). Write into *piNow
5721 ** the current time and date as a Julian Day number times 86_400_000. In
5722 ** other words, write into *piNow the number of milliseconds since the Julian
5723 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5724 ** proleptic Gregorian calendar.
5726 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5729 static int winCurrentTimeInt64(sqlite3_vfs
*pVfs
, sqlite3_int64
*piNow
){
5730 /* FILETIME structure is a 64-bit value representing the number of
5731 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
5734 static const sqlite3_int64 winFiletimeEpoch
= 23058135*(sqlite3_int64
)8640000;
5736 static const sqlite3_int64 unixEpoch
= 24405875*(sqlite3_int64
)8640000;
5738 /* 2^32 - to avoid use of LL and warnings in gcc */
5739 static const sqlite3_int64 max32BitValue
=
5740 (sqlite3_int64
)2000000000 + (sqlite3_int64
)2000000000 +
5741 (sqlite3_int64
)294967296;
5745 osGetSystemTime(&time
);
5746 /* if SystemTimeToFileTime() fails, it returns zero. */
5747 if (!osSystemTimeToFileTime(&time
,&ft
)){
5748 return SQLITE_ERROR
;
5751 osGetSystemTimeAsFileTime( &ft
);
5754 *piNow
= winFiletimeEpoch
+
5755 ((((sqlite3_int64
)ft
.dwHighDateTime
)*max32BitValue
) +
5756 (sqlite3_int64
)ft
.dwLowDateTime
)/(sqlite3_int64
)10000;
5759 if( sqlite3_current_time
){
5760 *piNow
= 1000*(sqlite3_int64
)sqlite3_current_time
+ unixEpoch
;
5763 UNUSED_PARAMETER(pVfs
);
5768 ** Find the current time (in Universal Coordinated Time). Write the
5769 ** current time and date as a Julian Day number into *prNow and
5770 ** return 0. Return 1 if the time and date cannot be found.
5772 static int winCurrentTime(sqlite3_vfs
*pVfs
, double *prNow
){
5775 rc
= winCurrentTimeInt64(pVfs
, &i
);
5777 *prNow
= i
/86400000.0;
5783 ** The idea is that this function works like a combination of
5784 ** GetLastError() and FormatMessage() on Windows (or errno and
5785 ** strerror_r() on Unix). After an error is returned by an OS
5786 ** function, SQLite calls this function with zBuf pointing to
5787 ** a buffer of nBuf bytes. The OS layer should populate the
5788 ** buffer with a nul-terminated UTF-8 encoded error message
5789 ** describing the last IO error to have occurred within the calling
5792 ** If the error message is too large for the supplied buffer,
5793 ** it should be truncated. The return value of xGetLastError
5794 ** is zero if the error message fits in the buffer, or non-zero
5795 ** otherwise (if the message was truncated). If non-zero is returned,
5796 ** then it is not necessary to include the nul-terminator character
5797 ** in the output buffer.
5799 ** Not supplying an error message will have no adverse effect
5800 ** on SQLite. It is fine to have an implementation that never
5801 ** returns an error message:
5803 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
5804 ** assert(zBuf[0]=='\0');
5808 ** However if an error message is supplied, it will be incorporated
5809 ** by sqlite into the error message available to the user using
5810 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
5812 static int winGetLastError(sqlite3_vfs
*pVfs
, int nBuf
, char *zBuf
){
5813 DWORD e
= osGetLastError();
5814 UNUSED_PARAMETER(pVfs
);
5815 if( nBuf
>0 ) winGetLastErrorMsg(e
, nBuf
, zBuf
);
5820 ** Initialize and deinitialize the operating system interface.
5822 int sqlite3_os_init(void){
5823 static sqlite3_vfs winVfs
= {
5825 sizeof(winFile
), /* szOsFile */
5826 SQLITE_WIN32_MAX_PATH_BYTES
, /* mxPathname */
5828 "win32", /* zName */
5829 &winAppData
, /* pAppData */
5830 winOpen
, /* xOpen */
5831 winDelete
, /* xDelete */
5832 winAccess
, /* xAccess */
5833 winFullPathname
, /* xFullPathname */
5834 winDlOpen
, /* xDlOpen */
5835 winDlError
, /* xDlError */
5836 winDlSym
, /* xDlSym */
5837 winDlClose
, /* xDlClose */
5838 winRandomness
, /* xRandomness */
5839 winSleep
, /* xSleep */
5840 winCurrentTime
, /* xCurrentTime */
5841 winGetLastError
, /* xGetLastError */
5842 winCurrentTimeInt64
, /* xCurrentTimeInt64 */
5843 winSetSystemCall
, /* xSetSystemCall */
5844 winGetSystemCall
, /* xGetSystemCall */
5845 winNextSystemCall
, /* xNextSystemCall */
5847 #if defined(SQLITE_WIN32_HAS_WIDE)
5848 static sqlite3_vfs winLongPathVfs
= {
5850 sizeof(winFile
), /* szOsFile */
5851 SQLITE_WINNT_MAX_PATH_BYTES
, /* mxPathname */
5853 "win32-longpath", /* zName */
5854 &winAppData
, /* pAppData */
5855 winOpen
, /* xOpen */
5856 winDelete
, /* xDelete */
5857 winAccess
, /* xAccess */
5858 winFullPathname
, /* xFullPathname */
5859 winDlOpen
, /* xDlOpen */
5860 winDlError
, /* xDlError */
5861 winDlSym
, /* xDlSym */
5862 winDlClose
, /* xDlClose */
5863 winRandomness
, /* xRandomness */
5864 winSleep
, /* xSleep */
5865 winCurrentTime
, /* xCurrentTime */
5866 winGetLastError
, /* xGetLastError */
5867 winCurrentTimeInt64
, /* xCurrentTimeInt64 */
5868 winSetSystemCall
, /* xSetSystemCall */
5869 winGetSystemCall
, /* xGetSystemCall */
5870 winNextSystemCall
, /* xNextSystemCall */
5873 static sqlite3_vfs winNolockVfs
= {
5875 sizeof(winFile
), /* szOsFile */
5876 SQLITE_WIN32_MAX_PATH_BYTES
, /* mxPathname */
5878 "win32-none", /* zName */
5879 &winNolockAppData
, /* pAppData */
5880 winOpen
, /* xOpen */
5881 winDelete
, /* xDelete */
5882 winAccess
, /* xAccess */
5883 winFullPathname
, /* xFullPathname */
5884 winDlOpen
, /* xDlOpen */
5885 winDlError
, /* xDlError */
5886 winDlSym
, /* xDlSym */
5887 winDlClose
, /* xDlClose */
5888 winRandomness
, /* xRandomness */
5889 winSleep
, /* xSleep */
5890 winCurrentTime
, /* xCurrentTime */
5891 winGetLastError
, /* xGetLastError */
5892 winCurrentTimeInt64
, /* xCurrentTimeInt64 */
5893 winSetSystemCall
, /* xSetSystemCall */
5894 winGetSystemCall
, /* xGetSystemCall */
5895 winNextSystemCall
, /* xNextSystemCall */
5897 #if defined(SQLITE_WIN32_HAS_WIDE)
5898 static sqlite3_vfs winLongPathNolockVfs
= {
5900 sizeof(winFile
), /* szOsFile */
5901 SQLITE_WINNT_MAX_PATH_BYTES
, /* mxPathname */
5903 "win32-longpath-none", /* zName */
5904 &winNolockAppData
, /* pAppData */
5905 winOpen
, /* xOpen */
5906 winDelete
, /* xDelete */
5907 winAccess
, /* xAccess */
5908 winFullPathname
, /* xFullPathname */
5909 winDlOpen
, /* xDlOpen */
5910 winDlError
, /* xDlError */
5911 winDlSym
, /* xDlSym */
5912 winDlClose
, /* xDlClose */
5913 winRandomness
, /* xRandomness */
5914 winSleep
, /* xSleep */
5915 winCurrentTime
, /* xCurrentTime */
5916 winGetLastError
, /* xGetLastError */
5917 winCurrentTimeInt64
, /* xCurrentTimeInt64 */
5918 winSetSystemCall
, /* xSetSystemCall */
5919 winGetSystemCall
, /* xGetSystemCall */
5920 winNextSystemCall
, /* xNextSystemCall */
5924 /* Double-check that the aSyscall[] array has been constructed
5925 ** correctly. See ticket [bb3a86e890c8e96ab] */
5926 assert( ArraySize(aSyscall
)==80 );
5928 /* get memory map allocation granularity */
5929 memset(&winSysInfo
, 0, sizeof(SYSTEM_INFO
));
5931 osGetNativeSystemInfo(&winSysInfo
);
5933 osGetSystemInfo(&winSysInfo
);
5935 assert( winSysInfo
.dwAllocationGranularity
>0 );
5936 assert( winSysInfo
.dwPageSize
>0 );
5938 sqlite3_vfs_register(&winVfs
, 1);
5940 #if defined(SQLITE_WIN32_HAS_WIDE)
5941 sqlite3_vfs_register(&winLongPathVfs
, 0);
5944 sqlite3_vfs_register(&winNolockVfs
, 0);
5946 #if defined(SQLITE_WIN32_HAS_WIDE)
5947 sqlite3_vfs_register(&winLongPathNolockVfs
, 0);
5953 int sqlite3_os_end(void){
5955 if( sleepObj
!=NULL
){
5956 osCloseHandle(sleepObj
);
5963 #endif /* SQLITE_OS_WIN */