xref: /sqlite-3.40.0/src/os_win.c (revision 87f9caa8)
1 /*
2 ** 2004 May 22
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 ******************************************************************************
12 **
13 ** This file contains code that is specific to Windows.
14 */
15 #include "sqliteInt.h"
16 #if SQLITE_OS_WIN               /* This file is used for Windows only */
17 
18 #ifdef __CYGWIN__
19 # include <sys/cygwin.h>
20 #endif
21 
22 /*
23 ** Include code that is common to all os_*.c files
24 */
25 #include "os_common.h"
26 
27 /*
28 ** Compiling and using WAL mode requires several APIs that are only
29 ** available in Windows platforms based on the NT kernel.
30 */
31 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
32 # error "WAL mode requires support from the Windows NT kernel, compile\
33  with SQLITE_OMIT_WAL."
34 #endif
35 
36 /*
37 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
38 ** based on the sub-platform)?
39 */
40 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
41 #  define SQLITE_WIN32_HAS_ANSI
42 #endif
43 
44 /*
45 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
46 ** based on the sub-platform)?
47 */
48 #if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT
49 #  define SQLITE_WIN32_HAS_WIDE
50 #endif
51 
52 /*
53 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
54 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
55 ** are not present in the header file)?
56 */
57 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
58 /*
59 ** Two of the file mapping APIs are different under WinRT.  Figure out which
60 ** set we need.
61 */
62 #if SQLITE_OS_WINRT
63 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
64         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
65 
66 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
67 #else
68 #if defined(SQLITE_WIN32_HAS_ANSI)
69 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
70         DWORD, DWORD, DWORD, LPCSTR);
71 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
72 
73 #if defined(SQLITE_WIN32_HAS_WIDE)
74 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
75         DWORD, DWORD, DWORD, LPCWSTR);
76 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
77 
78 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
79 #endif /* SQLITE_OS_WINRT */
80 
81 /*
82 ** This file mapping API is common to both Win32 and WinRT.
83 */
84 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
85 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
86 
87 /*
88 ** Macro to find the minimum of two numeric values.
89 */
90 #ifndef MIN
91 # define MIN(x,y) ((x)<(y)?(x):(y))
92 #endif
93 
94 /*
95 ** Some Microsoft compilers lack this definition.
96 */
97 #ifndef INVALID_FILE_ATTRIBUTES
98 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
99 #endif
100 
101 #ifndef FILE_FLAG_MASK
102 # define FILE_FLAG_MASK          (0xFF3C0000)
103 #endif
104 
105 #ifndef FILE_ATTRIBUTE_MASK
106 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
107 #endif
108 
109 #ifndef SQLITE_OMIT_WAL
110 /* Forward references */
111 typedef struct winShm winShm;           /* A connection to shared-memory */
112 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
113 #endif
114 
115 /*
116 ** WinCE lacks native support for file locking so we have to fake it
117 ** with some code of our own.
118 */
119 #if SQLITE_OS_WINCE
120 typedef struct winceLock {
121   int nReaders;       /* Number of reader locks obtained */
122   BOOL bPending;      /* Indicates a pending lock has been obtained */
123   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
124   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
125 } winceLock;
126 #endif
127 
128 /*
129 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
130 ** portability layer.
131 */
132 typedef struct winFile winFile;
133 struct winFile {
134   const sqlite3_io_methods *pMethod; /*** Must be first ***/
135   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
136   HANDLE h;               /* Handle for accessing the file */
137   u8 locktype;            /* Type of lock currently held on this file */
138   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
139   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
140   DWORD lastErrno;        /* The Windows errno from the last I/O error */
141 #ifndef SQLITE_OMIT_WAL
142   winShm *pShm;           /* Instance of shared memory on this file */
143 #endif
144   const char *zPath;      /* Full pathname of this file */
145   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
146 #if SQLITE_OS_WINCE
147   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
148   HANDLE hMutex;          /* Mutex used to control access to shared lock */
149   HANDLE hShared;         /* Shared memory segment used for locking */
150   winceLock local;        /* Locks obtained by this instance of winFile */
151   winceLock *shared;      /* Global shared lock memory for the file  */
152 #endif
153 #if SQLITE_MAX_MMAP_SIZE>0
154   int nFetchOut;                /* Number of outstanding xFetch references */
155   HANDLE hMap;                  /* Handle for accessing memory mapping */
156   void *pMapRegion;             /* Area memory mapped */
157   sqlite3_int64 mmapSize;       /* Usable size of mapped region */
158   sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
159   sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
160 #endif
161 };
162 
163 /*
164 ** Allowed values for winFile.ctrlFlags
165 */
166 #define WINFILE_RDONLY          0x02   /* Connection is read only */
167 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
168 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
169 
170 /*
171  * The size of the buffer used by sqlite3_win32_write_debug().
172  */
173 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
174 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
175 #endif
176 
177 /*
178  * The value used with sqlite3_win32_set_directory() to specify that
179  * the data directory should be changed.
180  */
181 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
182 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
183 #endif
184 
185 /*
186  * The value used with sqlite3_win32_set_directory() to specify that
187  * the temporary directory should be changed.
188  */
189 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
190 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
191 #endif
192 
193 /*
194  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
195  * various Win32 API heap functions instead of our own.
196  */
197 #ifdef SQLITE_WIN32_MALLOC
198 
199 /*
200  * If this is non-zero, an isolated heap will be created by the native Win32
201  * allocator subsystem; otherwise, the default process heap will be used.  This
202  * setting has no effect when compiling for WinRT.  By default, this is enabled
203  * and an isolated heap will be created to store all allocated data.
204  *
205  ******************************************************************************
206  * WARNING: It is important to note that when this setting is non-zero and the
207  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
208  *          function), all data that was allocated using the isolated heap will
209  *          be freed immediately and any attempt to access any of that freed
210  *          data will almost certainly result in an immediate access violation.
211  ******************************************************************************
212  */
213 #ifndef SQLITE_WIN32_HEAP_CREATE
214 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
215 #endif
216 
217 /*
218  * The initial size of the Win32-specific heap.  This value may be zero.
219  */
220 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
221 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
222                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
223 #endif
224 
225 /*
226  * The maximum size of the Win32-specific heap.  This value may be zero.
227  */
228 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
229 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
230 #endif
231 
232 /*
233  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
234  * zero for the default behavior.
235  */
236 #ifndef SQLITE_WIN32_HEAP_FLAGS
237 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
238 #endif
239 
240 /*
241 ** The winMemData structure stores information required by the Win32-specific
242 ** sqlite3_mem_methods implementation.
243 */
244 typedef struct winMemData winMemData;
245 struct winMemData {
246 #ifndef NDEBUG
247   u32 magic;    /* Magic number to detect structure corruption. */
248 #endif
249   HANDLE hHeap; /* The handle to our heap. */
250   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
251 };
252 
253 #ifndef NDEBUG
254 #define WINMEM_MAGIC     0x42b2830b
255 #endif
256 
257 static struct winMemData win_mem_data = {
258 #ifndef NDEBUG
259   WINMEM_MAGIC,
260 #endif
261   NULL, FALSE
262 };
263 
264 #ifndef NDEBUG
265 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
266 #else
267 #define winMemAssertMagic()
268 #endif
269 
270 #define winMemGetHeap() win_mem_data.hHeap
271 
272 static void *winMemMalloc(int nBytes);
273 static void winMemFree(void *pPrior);
274 static void *winMemRealloc(void *pPrior, int nBytes);
275 static int winMemSize(void *p);
276 static int winMemRoundup(int n);
277 static int winMemInit(void *pAppData);
278 static void winMemShutdown(void *pAppData);
279 
280 const sqlite3_mem_methods *sqlite3MemGetWin32(void);
281 #endif /* SQLITE_WIN32_MALLOC */
282 
283 /*
284 ** The following variable is (normally) set once and never changes
285 ** thereafter.  It records whether the operating system is Win9x
286 ** or WinNT.
287 **
288 ** 0:   Operating system unknown.
289 ** 1:   Operating system is Win9x.
290 ** 2:   Operating system is WinNT.
291 **
292 ** In order to facilitate testing on a WinNT system, the test fixture
293 ** can manually set this value to 1 to emulate Win98 behavior.
294 */
295 #ifdef SQLITE_TEST
296 int sqlite3_os_type = 0;
297 #else
298 static int sqlite3_os_type = 0;
299 #endif
300 
301 #ifndef SYSCALL
302 #  define SYSCALL sqlite3_syscall_ptr
303 #endif
304 
305 /*
306 ** This function is not available on Windows CE or WinRT.
307  */
308 
309 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
310 #  define osAreFileApisANSI()       1
311 #endif
312 
313 /*
314 ** Many system calls are accessed through pointer-to-functions so that
315 ** they may be overridden at runtime to facilitate fault injection during
316 ** testing and sandboxing.  The following array holds the names and pointers
317 ** to all overrideable system calls.
318 */
319 static struct win_syscall {
320   const char *zName;            /* Name of the system call */
321   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
322   sqlite3_syscall_ptr pDefault; /* Default value */
323 } aSyscall[] = {
324 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
325   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
326 #else
327   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
328 #endif
329 
330 #ifndef osAreFileApisANSI
331 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
332 #endif
333 
334 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
335   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
336 #else
337   { "CharLowerW",              (SYSCALL)0,                       0 },
338 #endif
339 
340 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
341 
342 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
343   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
344 #else
345   { "CharUpperW",              (SYSCALL)0,                       0 },
346 #endif
347 
348 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
349 
350   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
351 
352 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
353 
354 #if defined(SQLITE_WIN32_HAS_ANSI)
355   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
356 #else
357   { "CreateFileA",             (SYSCALL)0,                       0 },
358 #endif
359 
360 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
361         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
362 
363 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
364   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
365 #else
366   { "CreateFileW",             (SYSCALL)0,                       0 },
367 #endif
368 
369 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
370         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
371 
372 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
373         !defined(SQLITE_OMIT_WAL))
374   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
375 #else
376   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
377 #endif
378 
379 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
380         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
381 
382 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
383         !defined(SQLITE_OMIT_WAL))
384   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
385 #else
386   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
387 #endif
388 
389 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
390         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
391 
392 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
393   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
394 #else
395   { "CreateMutexW",            (SYSCALL)0,                       0 },
396 #endif
397 
398 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
399         LPCWSTR))aSyscall[8].pCurrent)
400 
401 #if defined(SQLITE_WIN32_HAS_ANSI)
402   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
403 #else
404   { "DeleteFileA",             (SYSCALL)0,                       0 },
405 #endif
406 
407 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
408 
409 #if defined(SQLITE_WIN32_HAS_WIDE)
410   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
411 #else
412   { "DeleteFileW",             (SYSCALL)0,                       0 },
413 #endif
414 
415 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
416 
417 #if SQLITE_OS_WINCE
418   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
419 #else
420   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
421 #endif
422 
423 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
424         LPFILETIME))aSyscall[11].pCurrent)
425 
426 #if SQLITE_OS_WINCE
427   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
428 #else
429   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
430 #endif
431 
432 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
433         LPSYSTEMTIME))aSyscall[12].pCurrent)
434 
435   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
436 
437 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
438 
439 #if defined(SQLITE_WIN32_HAS_ANSI)
440   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
441 #else
442   { "FormatMessageA",          (SYSCALL)0,                       0 },
443 #endif
444 
445 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
446         DWORD,va_list*))aSyscall[14].pCurrent)
447 
448 #if defined(SQLITE_WIN32_HAS_WIDE)
449   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
450 #else
451   { "FormatMessageW",          (SYSCALL)0,                       0 },
452 #endif
453 
454 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
455         DWORD,va_list*))aSyscall[15].pCurrent)
456 
457 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
458   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
459 #else
460   { "FreeLibrary",             (SYSCALL)0,                       0 },
461 #endif
462 
463 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
464 
465   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
466 
467 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
468 
469 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
470   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
471 #else
472   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
473 #endif
474 
475 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
476         LPDWORD))aSyscall[18].pCurrent)
477 
478 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
479   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
480 #else
481   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
482 #endif
483 
484 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
485         LPDWORD))aSyscall[19].pCurrent)
486 
487 #if defined(SQLITE_WIN32_HAS_ANSI)
488   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
489 #else
490   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
491 #endif
492 
493 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
494 
495 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
496   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
497 #else
498   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
499 #endif
500 
501 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
502 
503 #if defined(SQLITE_WIN32_HAS_WIDE)
504   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
505 #else
506   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
507 #endif
508 
509 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
510         LPVOID))aSyscall[22].pCurrent)
511 
512 #if !SQLITE_OS_WINRT
513   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
514 #else
515   { "GetFileSize",             (SYSCALL)0,                       0 },
516 #endif
517 
518 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
519 
520 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
521   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
522 #else
523   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
524 #endif
525 
526 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
527         LPSTR*))aSyscall[24].pCurrent)
528 
529 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
530   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
531 #else
532   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
533 #endif
534 
535 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
536         LPWSTR*))aSyscall[25].pCurrent)
537 
538   { "GetLastError",            (SYSCALL)GetLastError,            0 },
539 
540 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
541 
542 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
543 #if SQLITE_OS_WINCE
544   /* The GetProcAddressA() routine is only available on Windows CE. */
545   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
546 #else
547   /* All other Windows platforms expect GetProcAddress() to take
548   ** an ANSI string regardless of the _UNICODE setting */
549   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
550 #endif
551 #else
552   { "GetProcAddressA",         (SYSCALL)0,                       0 },
553 #endif
554 
555 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
556         LPCSTR))aSyscall[27].pCurrent)
557 
558 #if !SQLITE_OS_WINRT
559   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
560 #else
561   { "GetSystemInfo",           (SYSCALL)0,                       0 },
562 #endif
563 
564 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
565 
566   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
567 
568 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
569 
570 #if !SQLITE_OS_WINCE
571   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
572 #else
573   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
574 #endif
575 
576 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
577         LPFILETIME))aSyscall[30].pCurrent)
578 
579 #if defined(SQLITE_WIN32_HAS_ANSI)
580   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
581 #else
582   { "GetTempPathA",            (SYSCALL)0,                       0 },
583 #endif
584 
585 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
586 
587 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
588   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
589 #else
590   { "GetTempPathW",            (SYSCALL)0,                       0 },
591 #endif
592 
593 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
594 
595 #if !SQLITE_OS_WINRT
596   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
597 #else
598   { "GetTickCount",            (SYSCALL)0,                       0 },
599 #endif
600 
601 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
602 
603 #if defined(SQLITE_WIN32_HAS_ANSI)
604   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
605 #else
606   { "GetVersionExA",           (SYSCALL)0,                       0 },
607 #endif
608 
609 #define osGetVersionExA ((BOOL(WINAPI*)( \
610         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
611 
612   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
613 
614 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
615         SIZE_T))aSyscall[35].pCurrent)
616 
617 #if !SQLITE_OS_WINRT
618   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
619 #else
620   { "HeapCreate",              (SYSCALL)0,                       0 },
621 #endif
622 
623 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
624         SIZE_T))aSyscall[36].pCurrent)
625 
626 #if !SQLITE_OS_WINRT
627   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
628 #else
629   { "HeapDestroy",             (SYSCALL)0,                       0 },
630 #endif
631 
632 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
633 
634   { "HeapFree",                (SYSCALL)HeapFree,                0 },
635 
636 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
637 
638   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
639 
640 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
641         SIZE_T))aSyscall[39].pCurrent)
642 
643   { "HeapSize",                (SYSCALL)HeapSize,                0 },
644 
645 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
646         LPCVOID))aSyscall[40].pCurrent)
647 
648 #if !SQLITE_OS_WINRT
649   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
650 #else
651   { "HeapValidate",            (SYSCALL)0,                       0 },
652 #endif
653 
654 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
655         LPCVOID))aSyscall[41].pCurrent)
656 
657 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
658   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
659 #else
660   { "LoadLibraryA",            (SYSCALL)0,                       0 },
661 #endif
662 
663 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
664 
665 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
666         !defined(SQLITE_OMIT_LOAD_EXTENSION)
667   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
668 #else
669   { "LoadLibraryW",            (SYSCALL)0,                       0 },
670 #endif
671 
672 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
673 
674 #if !SQLITE_OS_WINRT
675   { "LocalFree",               (SYSCALL)LocalFree,               0 },
676 #else
677   { "LocalFree",               (SYSCALL)0,                       0 },
678 #endif
679 
680 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
681 
682 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
683   { "LockFile",                (SYSCALL)LockFile,                0 },
684 #else
685   { "LockFile",                (SYSCALL)0,                       0 },
686 #endif
687 
688 #ifndef osLockFile
689 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
690         DWORD))aSyscall[45].pCurrent)
691 #endif
692 
693 #if !SQLITE_OS_WINCE
694   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
695 #else
696   { "LockFileEx",              (SYSCALL)0,                       0 },
697 #endif
698 
699 #ifndef osLockFileEx
700 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
701         LPOVERLAPPED))aSyscall[46].pCurrent)
702 #endif
703 
704 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
705   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
706 #else
707   { "MapViewOfFile",           (SYSCALL)0,                       0 },
708 #endif
709 
710 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
711         SIZE_T))aSyscall[47].pCurrent)
712 
713   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
714 
715 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
716         int))aSyscall[48].pCurrent)
717 
718   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
719 
720 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
721         LARGE_INTEGER*))aSyscall[49].pCurrent)
722 
723   { "ReadFile",                (SYSCALL)ReadFile,                0 },
724 
725 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
726         LPOVERLAPPED))aSyscall[50].pCurrent)
727 
728   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
729 
730 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
731 
732 #if !SQLITE_OS_WINRT
733   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
734 #else
735   { "SetFilePointer",          (SYSCALL)0,                       0 },
736 #endif
737 
738 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
739         DWORD))aSyscall[52].pCurrent)
740 
741 #if !SQLITE_OS_WINRT
742   { "Sleep",                   (SYSCALL)Sleep,                   0 },
743 #else
744   { "Sleep",                   (SYSCALL)0,                       0 },
745 #endif
746 
747 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
748 
749   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
750 
751 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
752         LPFILETIME))aSyscall[54].pCurrent)
753 
754 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
755   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
756 #else
757   { "UnlockFile",              (SYSCALL)0,                       0 },
758 #endif
759 
760 #ifndef osUnlockFile
761 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
762         DWORD))aSyscall[55].pCurrent)
763 #endif
764 
765 #if !SQLITE_OS_WINCE
766   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
767 #else
768   { "UnlockFileEx",            (SYSCALL)0,                       0 },
769 #endif
770 
771 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
772         LPOVERLAPPED))aSyscall[56].pCurrent)
773 
774 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
775   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
776 #else
777   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
778 #endif
779 
780 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
781 
782   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
783 
784 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
785         LPCSTR,LPBOOL))aSyscall[58].pCurrent)
786 
787   { "WriteFile",               (SYSCALL)WriteFile,               0 },
788 
789 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
790         LPOVERLAPPED))aSyscall[59].pCurrent)
791 
792 #if SQLITE_OS_WINRT
793   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
794 #else
795   { "CreateEventExW",          (SYSCALL)0,                       0 },
796 #endif
797 
798 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
799         DWORD,DWORD))aSyscall[60].pCurrent)
800 
801 #if !SQLITE_OS_WINRT
802   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
803 #else
804   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
805 #endif
806 
807 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
808         DWORD))aSyscall[61].pCurrent)
809 
810 #if SQLITE_OS_WINRT
811   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
812 #else
813   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
814 #endif
815 
816 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
817         BOOL))aSyscall[62].pCurrent)
818 
819 #if SQLITE_OS_WINRT
820   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
821 #else
822   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
823 #endif
824 
825 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
826         PLARGE_INTEGER,DWORD))aSyscall[63].pCurrent)
827 
828 #if SQLITE_OS_WINRT
829   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
830 #else
831   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
832 #endif
833 
834 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
835         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[64].pCurrent)
836 
837 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
838   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
839 #else
840   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
841 #endif
842 
843 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
844         SIZE_T))aSyscall[65].pCurrent)
845 
846 #if SQLITE_OS_WINRT
847   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
848 #else
849   { "CreateFile2",             (SYSCALL)0,                       0 },
850 #endif
851 
852 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
853         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[66].pCurrent)
854 
855 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
856   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
857 #else
858   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
859 #endif
860 
861 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
862         DWORD))aSyscall[67].pCurrent)
863 
864 #if SQLITE_OS_WINRT
865   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
866 #else
867   { "GetTickCount64",          (SYSCALL)0,                       0 },
868 #endif
869 
870 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[68].pCurrent)
871 
872 #if SQLITE_OS_WINRT
873   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
874 #else
875   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
876 #endif
877 
878 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
879         LPSYSTEM_INFO))aSyscall[69].pCurrent)
880 
881 #if defined(SQLITE_WIN32_HAS_ANSI)
882   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
883 #else
884   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
885 #endif
886 
887 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[70].pCurrent)
888 
889 #if defined(SQLITE_WIN32_HAS_WIDE)
890   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
891 #else
892   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
893 #endif
894 
895 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[71].pCurrent)
896 
897   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
898 
899 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[72].pCurrent)
900 
901 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
902   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
903 #else
904   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
905 #endif
906 
907 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
908         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[73].pCurrent)
909 
910 }; /* End of the overrideable system calls */
911 
912 /*
913 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
914 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
915 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
916 ** system call named zName.
917 */
918 static int winSetSystemCall(
919   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
920   const char *zName,            /* Name of system call to override */
921   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
922 ){
923   unsigned int i;
924   int rc = SQLITE_NOTFOUND;
925 
926   UNUSED_PARAMETER(pNotUsed);
927   if( zName==0 ){
928     /* If no zName is given, restore all system calls to their default
929     ** settings and return NULL
930     */
931     rc = SQLITE_OK;
932     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
933       if( aSyscall[i].pDefault ){
934         aSyscall[i].pCurrent = aSyscall[i].pDefault;
935       }
936     }
937   }else{
938     /* If zName is specified, operate on only the one system call
939     ** specified.
940     */
941     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
942       if( strcmp(zName, aSyscall[i].zName)==0 ){
943         if( aSyscall[i].pDefault==0 ){
944           aSyscall[i].pDefault = aSyscall[i].pCurrent;
945         }
946         rc = SQLITE_OK;
947         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
948         aSyscall[i].pCurrent = pNewFunc;
949         break;
950       }
951     }
952   }
953   return rc;
954 }
955 
956 /*
957 ** Return the value of a system call.  Return NULL if zName is not a
958 ** recognized system call name.  NULL is also returned if the system call
959 ** is currently undefined.
960 */
961 static sqlite3_syscall_ptr winGetSystemCall(
962   sqlite3_vfs *pNotUsed,
963   const char *zName
964 ){
965   unsigned int i;
966 
967   UNUSED_PARAMETER(pNotUsed);
968   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
969     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
970   }
971   return 0;
972 }
973 
974 /*
975 ** Return the name of the first system call after zName.  If zName==NULL
976 ** then return the name of the first system call.  Return NULL if zName
977 ** is the last system call or if zName is not the name of a valid
978 ** system call.
979 */
980 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
981   int i = -1;
982 
983   UNUSED_PARAMETER(p);
984   if( zName ){
985     for(i=0; i<ArraySize(aSyscall)-1; i++){
986       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
987     }
988   }
989   for(i++; i<ArraySize(aSyscall); i++){
990     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
991   }
992   return 0;
993 }
994 
995 /*
996 ** This function outputs the specified (ANSI) string to the Win32 debugger
997 ** (if available).
998 */
999 
1000 void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
1001   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
1002   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
1003   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
1004   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
1005 #if defined(SQLITE_WIN32_HAS_ANSI)
1006   if( nMin>0 ){
1007     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
1008     memcpy(zDbgBuf, zBuf, nMin);
1009     osOutputDebugStringA(zDbgBuf);
1010   }else{
1011     osOutputDebugStringA(zBuf);
1012   }
1013 #elif defined(SQLITE_WIN32_HAS_WIDE)
1014   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
1015   if ( osMultiByteToWideChar(
1016           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
1017           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
1018     return;
1019   }
1020   osOutputDebugStringW((LPCWSTR)zDbgBuf);
1021 #else
1022   if( nMin>0 ){
1023     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
1024     memcpy(zDbgBuf, zBuf, nMin);
1025     fprintf(stderr, "%s", zDbgBuf);
1026   }else{
1027     fprintf(stderr, "%s", zBuf);
1028   }
1029 #endif
1030 }
1031 
1032 /*
1033 ** The following routine suspends the current thread for at least ms
1034 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
1035 */
1036 #if SQLITE_OS_WINRT
1037 static HANDLE sleepObj = NULL;
1038 #endif
1039 
1040 void sqlite3_win32_sleep(DWORD milliseconds){
1041 #if SQLITE_OS_WINRT
1042   if ( sleepObj==NULL ){
1043     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
1044                                 SYNCHRONIZE);
1045   }
1046   assert( sleepObj!=NULL );
1047   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
1048 #else
1049   osSleep(milliseconds);
1050 #endif
1051 }
1052 
1053 /*
1054 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
1055 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
1056 **
1057 ** Here is an interesting observation:  Win95, Win98, and WinME lack
1058 ** the LockFileEx() API.  But we can still statically link against that
1059 ** API as long as we don't call it when running Win95/98/ME.  A call to
1060 ** this routine is used to determine if the host is Win95/98/ME or
1061 ** WinNT/2K/XP so that we will know whether or not we can safely call
1062 ** the LockFileEx() API.
1063 */
1064 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
1065 # define isNT()  (1)
1066 #elif !defined(SQLITE_WIN32_HAS_WIDE)
1067 # define isNT()  (0)
1068 #else
1069   static int isNT(void){
1070     if( sqlite3_os_type==0 ){
1071       OSVERSIONINFOA sInfo;
1072       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
1073       osGetVersionExA(&sInfo);
1074       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
1075     }
1076     return sqlite3_os_type==2;
1077   }
1078 #endif
1079 
1080 #ifdef SQLITE_WIN32_MALLOC
1081 /*
1082 ** Allocate nBytes of memory.
1083 */
1084 static void *winMemMalloc(int nBytes){
1085   HANDLE hHeap;
1086   void *p;
1087 
1088   winMemAssertMagic();
1089   hHeap = winMemGetHeap();
1090   assert( hHeap!=0 );
1091   assert( hHeap!=INVALID_HANDLE_VALUE );
1092 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1093   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1094 #endif
1095   assert( nBytes>=0 );
1096   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
1097   if( !p ){
1098     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
1099                 nBytes, osGetLastError(), (void*)hHeap);
1100   }
1101   return p;
1102 }
1103 
1104 /*
1105 ** Free memory.
1106 */
1107 static void winMemFree(void *pPrior){
1108   HANDLE hHeap;
1109 
1110   winMemAssertMagic();
1111   hHeap = winMemGetHeap();
1112   assert( hHeap!=0 );
1113   assert( hHeap!=INVALID_HANDLE_VALUE );
1114 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1115   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
1116 #endif
1117   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
1118   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
1119     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
1120                 pPrior, osGetLastError(), (void*)hHeap);
1121   }
1122 }
1123 
1124 /*
1125 ** Change the size of an existing memory allocation
1126 */
1127 static void *winMemRealloc(void *pPrior, int nBytes){
1128   HANDLE hHeap;
1129   void *p;
1130 
1131   winMemAssertMagic();
1132   hHeap = winMemGetHeap();
1133   assert( hHeap!=0 );
1134   assert( hHeap!=INVALID_HANDLE_VALUE );
1135 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1136   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
1137 #endif
1138   assert( nBytes>=0 );
1139   if( !pPrior ){
1140     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
1141   }else{
1142     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
1143   }
1144   if( !p ){
1145     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
1146                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
1147                 (void*)hHeap);
1148   }
1149   return p;
1150 }
1151 
1152 /*
1153 ** Return the size of an outstanding allocation, in bytes.
1154 */
1155 static int winMemSize(void *p){
1156   HANDLE hHeap;
1157   SIZE_T n;
1158 
1159   winMemAssertMagic();
1160   hHeap = winMemGetHeap();
1161   assert( hHeap!=0 );
1162   assert( hHeap!=INVALID_HANDLE_VALUE );
1163 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1164   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1165 #endif
1166   if( !p ) return 0;
1167   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
1168   if( n==(SIZE_T)-1 ){
1169     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
1170                 p, osGetLastError(), (void*)hHeap);
1171     return 0;
1172   }
1173   return (int)n;
1174 }
1175 
1176 /*
1177 ** Round up a request size to the next valid allocation size.
1178 */
1179 static int winMemRoundup(int n){
1180   return n;
1181 }
1182 
1183 /*
1184 ** Initialize this module.
1185 */
1186 static int winMemInit(void *pAppData){
1187   winMemData *pWinMemData = (winMemData *)pAppData;
1188 
1189   if( !pWinMemData ) return SQLITE_ERROR;
1190   assert( pWinMemData->magic==WINMEM_MAGIC );
1191 
1192 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
1193   if( !pWinMemData->hHeap ){
1194     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
1195                                       SQLITE_WIN32_HEAP_INIT_SIZE,
1196                                       SQLITE_WIN32_HEAP_MAX_SIZE);
1197     if( !pWinMemData->hHeap ){
1198       sqlite3_log(SQLITE_NOMEM,
1199           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
1200           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
1201           SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
1202       return SQLITE_NOMEM;
1203     }
1204     pWinMemData->bOwned = TRUE;
1205     assert( pWinMemData->bOwned );
1206   }
1207 #else
1208   pWinMemData->hHeap = osGetProcessHeap();
1209   if( !pWinMemData->hHeap ){
1210     sqlite3_log(SQLITE_NOMEM,
1211         "failed to GetProcessHeap (%d)", osGetLastError());
1212     return SQLITE_NOMEM;
1213   }
1214   pWinMemData->bOwned = FALSE;
1215   assert( !pWinMemData->bOwned );
1216 #endif
1217   assert( pWinMemData->hHeap!=0 );
1218   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
1219 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1220   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1221 #endif
1222   return SQLITE_OK;
1223 }
1224 
1225 /*
1226 ** Deinitialize this module.
1227 */
1228 static void winMemShutdown(void *pAppData){
1229   winMemData *pWinMemData = (winMemData *)pAppData;
1230 
1231   if( !pWinMemData ) return;
1232   if( pWinMemData->hHeap ){
1233     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
1234 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
1235     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
1236 #endif
1237     if( pWinMemData->bOwned ){
1238       if( !osHeapDestroy(pWinMemData->hHeap) ){
1239         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
1240                     osGetLastError(), (void*)pWinMemData->hHeap);
1241       }
1242       pWinMemData->bOwned = FALSE;
1243     }
1244     pWinMemData->hHeap = NULL;
1245   }
1246 }
1247 
1248 /*
1249 ** Populate the low-level memory allocation function pointers in
1250 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
1251 ** arguments specify the block of memory to manage.
1252 **
1253 ** This routine is only called by sqlite3_config(), and therefore
1254 ** is not required to be threadsafe (it is not).
1255 */
1256 const sqlite3_mem_methods *sqlite3MemGetWin32(void){
1257   static const sqlite3_mem_methods winMemMethods = {
1258     winMemMalloc,
1259     winMemFree,
1260     winMemRealloc,
1261     winMemSize,
1262     winMemRoundup,
1263     winMemInit,
1264     winMemShutdown,
1265     &win_mem_data
1266   };
1267   return &winMemMethods;
1268 }
1269 
1270 void sqlite3MemSetDefault(void){
1271   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
1272 }
1273 #endif /* SQLITE_WIN32_MALLOC */
1274 
1275 /*
1276 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
1277 **
1278 ** Space to hold the returned string is obtained from malloc.
1279 */
1280 static LPWSTR utf8ToUnicode(const char *zFilename){
1281   int nChar;
1282   LPWSTR zWideFilename;
1283 
1284   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
1285   if( nChar==0 ){
1286     return 0;
1287   }
1288   zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
1289   if( zWideFilename==0 ){
1290     return 0;
1291   }
1292   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
1293                                 nChar);
1294   if( nChar==0 ){
1295     sqlite3_free(zWideFilename);
1296     zWideFilename = 0;
1297   }
1298   return zWideFilename;
1299 }
1300 
1301 /*
1302 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
1303 ** obtained from sqlite3_malloc().
1304 */
1305 static char *unicodeToUtf8(LPCWSTR zWideFilename){
1306   int nByte;
1307   char *zFilename;
1308 
1309   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
1310   if( nByte == 0 ){
1311     return 0;
1312   }
1313   zFilename = sqlite3MallocZero( nByte );
1314   if( zFilename==0 ){
1315     return 0;
1316   }
1317   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
1318                                 0, 0);
1319   if( nByte == 0 ){
1320     sqlite3_free(zFilename);
1321     zFilename = 0;
1322   }
1323   return zFilename;
1324 }
1325 
1326 /*
1327 ** Convert an ANSI string to Microsoft Unicode, based on the
1328 ** current codepage settings for file apis.
1329 **
1330 ** Space to hold the returned string is obtained
1331 ** from sqlite3_malloc.
1332 */
1333 static LPWSTR mbcsToUnicode(const char *zFilename){
1334   int nByte;
1335   LPWSTR zMbcsFilename;
1336   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
1337 
1338   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
1339                                 0)*sizeof(WCHAR);
1340   if( nByte==0 ){
1341     return 0;
1342   }
1343   zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
1344   if( zMbcsFilename==0 ){
1345     return 0;
1346   }
1347   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
1348                                 nByte);
1349   if( nByte==0 ){
1350     sqlite3_free(zMbcsFilename);
1351     zMbcsFilename = 0;
1352   }
1353   return zMbcsFilename;
1354 }
1355 
1356 /*
1357 ** Convert Microsoft Unicode to multi-byte character string, based on the
1358 ** user's ANSI codepage.
1359 **
1360 ** Space to hold the returned string is obtained from
1361 ** sqlite3_malloc().
1362 */
1363 static char *unicodeToMbcs(LPCWSTR zWideFilename){
1364   int nByte;
1365   char *zFilename;
1366   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
1367 
1368   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
1369   if( nByte == 0 ){
1370     return 0;
1371   }
1372   zFilename = sqlite3MallocZero( nByte );
1373   if( zFilename==0 ){
1374     return 0;
1375   }
1376   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
1377                                 nByte, 0, 0);
1378   if( nByte == 0 ){
1379     sqlite3_free(zFilename);
1380     zFilename = 0;
1381   }
1382   return zFilename;
1383 }
1384 
1385 /*
1386 ** Convert multibyte character string to UTF-8.  Space to hold the
1387 ** returned string is obtained from sqlite3_malloc().
1388 */
1389 char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
1390   char *zFilenameUtf8;
1391   LPWSTR zTmpWide;
1392 
1393   zTmpWide = mbcsToUnicode(zFilename);
1394   if( zTmpWide==0 ){
1395     return 0;
1396   }
1397   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
1398   sqlite3_free(zTmpWide);
1399   return zFilenameUtf8;
1400 }
1401 
1402 /*
1403 ** Convert UTF-8 to multibyte character string.  Space to hold the
1404 ** returned string is obtained from sqlite3_malloc().
1405 */
1406 char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
1407   char *zFilenameMbcs;
1408   LPWSTR zTmpWide;
1409 
1410   zTmpWide = utf8ToUnicode(zFilename);
1411   if( zTmpWide==0 ){
1412     return 0;
1413   }
1414   zFilenameMbcs = unicodeToMbcs(zTmpWide);
1415   sqlite3_free(zTmpWide);
1416   return zFilenameMbcs;
1417 }
1418 
1419 /*
1420 ** This function sets the data directory or the temporary directory based on
1421 ** the provided arguments.  The type argument must be 1 in order to set the
1422 ** data directory or 2 in order to set the temporary directory.  The zValue
1423 ** argument is the name of the directory to use.  The return value will be
1424 ** SQLITE_OK if successful.
1425 */
1426 int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
1427   char **ppDirectory = 0;
1428 #ifndef SQLITE_OMIT_AUTOINIT
1429   int rc = sqlite3_initialize();
1430   if( rc ) return rc;
1431 #endif
1432   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
1433     ppDirectory = &sqlite3_data_directory;
1434   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
1435     ppDirectory = &sqlite3_temp_directory;
1436   }
1437   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
1438           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
1439   );
1440   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
1441   if( ppDirectory ){
1442     char *zValueUtf8 = 0;
1443     if( zValue && zValue[0] ){
1444       zValueUtf8 = unicodeToUtf8(zValue);
1445       if ( zValueUtf8==0 ){
1446         return SQLITE_NOMEM;
1447       }
1448     }
1449     sqlite3_free(*ppDirectory);
1450     *ppDirectory = zValueUtf8;
1451     return SQLITE_OK;
1452   }
1453   return SQLITE_ERROR;
1454 }
1455 
1456 /*
1457 ** The return value of getLastErrorMsg
1458 ** is zero if the error message fits in the buffer, or non-zero
1459 ** otherwise (if the message was truncated).
1460 */
1461 static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
1462   /* FormatMessage returns 0 on failure.  Otherwise it
1463   ** returns the number of TCHARs written to the output
1464   ** buffer, excluding the terminating null char.
1465   */
1466   DWORD dwLen = 0;
1467   char *zOut = 0;
1468 
1469   if( isNT() ){
1470 #if SQLITE_OS_WINRT
1471     WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */
1472     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
1473                              FORMAT_MESSAGE_IGNORE_INSERTS,
1474                              NULL,
1475                              lastErrno,
1476                              0,
1477                              zTempWide,
1478                              MAX_PATH,
1479                              0);
1480 #else
1481     LPWSTR zTempWide = NULL;
1482     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1483                              FORMAT_MESSAGE_FROM_SYSTEM |
1484                              FORMAT_MESSAGE_IGNORE_INSERTS,
1485                              NULL,
1486                              lastErrno,
1487                              0,
1488                              (LPWSTR) &zTempWide,
1489                              0,
1490                              0);
1491 #endif
1492     if( dwLen > 0 ){
1493       /* allocate a buffer and convert to UTF8 */
1494       sqlite3BeginBenignMalloc();
1495       zOut = unicodeToUtf8(zTempWide);
1496       sqlite3EndBenignMalloc();
1497 #if !SQLITE_OS_WINRT
1498       /* free the system buffer allocated by FormatMessage */
1499       osLocalFree(zTempWide);
1500 #endif
1501     }
1502   }
1503 #ifdef SQLITE_WIN32_HAS_ANSI
1504   else{
1505     char *zTemp = NULL;
1506     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1507                              FORMAT_MESSAGE_FROM_SYSTEM |
1508                              FORMAT_MESSAGE_IGNORE_INSERTS,
1509                              NULL,
1510                              lastErrno,
1511                              0,
1512                              (LPSTR) &zTemp,
1513                              0,
1514                              0);
1515     if( dwLen > 0 ){
1516       /* allocate a buffer and convert to UTF8 */
1517       sqlite3BeginBenignMalloc();
1518       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
1519       sqlite3EndBenignMalloc();
1520       /* free the system buffer allocated by FormatMessage */
1521       osLocalFree(zTemp);
1522     }
1523   }
1524 #endif
1525   if( 0 == dwLen ){
1526     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
1527   }else{
1528     /* copy a maximum of nBuf chars to output buffer */
1529     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
1530     /* free the UTF8 buffer */
1531     sqlite3_free(zOut);
1532   }
1533   return 0;
1534 }
1535 
1536 /*
1537 **
1538 ** This function - winLogErrorAtLine() - is only ever called via the macro
1539 ** winLogError().
1540 **
1541 ** This routine is invoked after an error occurs in an OS function.
1542 ** It logs a message using sqlite3_log() containing the current value of
1543 ** error code and, if possible, the human-readable equivalent from
1544 ** FormatMessage.
1545 **
1546 ** The first argument passed to the macro should be the error code that
1547 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1548 ** The two subsequent arguments should be the name of the OS function that
1549 ** failed and the associated file-system path, if any.
1550 */
1551 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
1552 static int winLogErrorAtLine(
1553   int errcode,                    /* SQLite error code */
1554   DWORD lastErrno,                /* Win32 last error */
1555   const char *zFunc,              /* Name of OS function that failed */
1556   const char *zPath,              /* File path associated with error */
1557   int iLine                       /* Source line number where error occurred */
1558 ){
1559   char zMsg[500];                 /* Human readable error text */
1560   int i;                          /* Loop counter */
1561 
1562   zMsg[0] = 0;
1563   getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
1564   assert( errcode!=SQLITE_OK );
1565   if( zPath==0 ) zPath = "";
1566   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
1567   zMsg[i] = 0;
1568   sqlite3_log(errcode,
1569       "os_win.c:%d: (%d) %s(%s) - %s",
1570       iLine, lastErrno, zFunc, zPath, zMsg
1571   );
1572 
1573   return errcode;
1574 }
1575 
1576 /*
1577 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
1578 ** will be retried following a locking error - probably caused by
1579 ** antivirus software.  Also the initial delay before the first retry.
1580 ** The delay increases linearly with each retry.
1581 */
1582 #ifndef SQLITE_WIN32_IOERR_RETRY
1583 # define SQLITE_WIN32_IOERR_RETRY 10
1584 #endif
1585 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
1586 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
1587 #endif
1588 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
1589 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
1590 
1591 /*
1592 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
1593 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
1594 ** to give up with an error.
1595 */
1596 static int retryIoerr(int *pnRetry, DWORD *pError){
1597   DWORD e = osGetLastError();
1598   if( *pnRetry>=win32IoerrRetry ){
1599     if( pError ){
1600       *pError = e;
1601     }
1602     return 0;
1603   }
1604   if( e==ERROR_ACCESS_DENIED ||
1605       e==ERROR_LOCK_VIOLATION ||
1606       e==ERROR_SHARING_VIOLATION ){
1607     sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));
1608     ++*pnRetry;
1609     return 1;
1610   }
1611   if( pError ){
1612     *pError = e;
1613   }
1614   return 0;
1615 }
1616 
1617 /*
1618 ** Log a I/O error retry episode.
1619 */
1620 static void logIoerr(int nRetry){
1621   if( nRetry ){
1622     sqlite3_log(SQLITE_IOERR,
1623       "delayed %dms for lock/sharing conflict",
1624       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
1625     );
1626   }
1627 }
1628 
1629 #if SQLITE_OS_WINCE
1630 /*************************************************************************
1631 ** This section contains code for WinCE only.
1632 */
1633 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
1634 /*
1635 ** The MSVC CRT on Windows CE may not have a localtime() function.  So
1636 ** create a substitute.
1637 */
1638 #include <time.h>
1639 struct tm *__cdecl localtime(const time_t *t)
1640 {
1641   static struct tm y;
1642   FILETIME uTm, lTm;
1643   SYSTEMTIME pTm;
1644   sqlite3_int64 t64;
1645   t64 = *t;
1646   t64 = (t64 + 11644473600)*10000000;
1647   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
1648   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
1649   osFileTimeToLocalFileTime(&uTm,&lTm);
1650   osFileTimeToSystemTime(&lTm,&pTm);
1651   y.tm_year = pTm.wYear - 1900;
1652   y.tm_mon = pTm.wMonth - 1;
1653   y.tm_wday = pTm.wDayOfWeek;
1654   y.tm_mday = pTm.wDay;
1655   y.tm_hour = pTm.wHour;
1656   y.tm_min = pTm.wMinute;
1657   y.tm_sec = pTm.wSecond;
1658   return &y;
1659 }
1660 #endif
1661 
1662 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
1663 
1664 /*
1665 ** Acquire a lock on the handle h
1666 */
1667 static void winceMutexAcquire(HANDLE h){
1668    DWORD dwErr;
1669    do {
1670      dwErr = osWaitForSingleObject(h, INFINITE);
1671    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
1672 }
1673 /*
1674 ** Release a lock acquired by winceMutexAcquire()
1675 */
1676 #define winceMutexRelease(h) ReleaseMutex(h)
1677 
1678 /*
1679 ** Create the mutex and shared memory used for locking in the file
1680 ** descriptor pFile
1681 */
1682 static int winceCreateLock(const char *zFilename, winFile *pFile){
1683   LPWSTR zTok;
1684   LPWSTR zName;
1685   DWORD lastErrno;
1686   BOOL bLogged = FALSE;
1687   BOOL bInit = TRUE;
1688 
1689   zName = utf8ToUnicode(zFilename);
1690   if( zName==0 ){
1691     /* out of memory */
1692     return SQLITE_IOERR_NOMEM;
1693   }
1694 
1695   /* Initialize the local lockdata */
1696   memset(&pFile->local, 0, sizeof(pFile->local));
1697 
1698   /* Replace the backslashes from the filename and lowercase it
1699   ** to derive a mutex name. */
1700   zTok = osCharLowerW(zName);
1701   for (;*zTok;zTok++){
1702     if (*zTok == '\\') *zTok = '_';
1703   }
1704 
1705   /* Create/open the named mutex */
1706   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
1707   if (!pFile->hMutex){
1708     pFile->lastErrno = osGetLastError();
1709     winLogError(SQLITE_IOERR, pFile->lastErrno,
1710                 "winceCreateLock1", zFilename);
1711     sqlite3_free(zName);
1712     return SQLITE_IOERR;
1713   }
1714 
1715   /* Acquire the mutex before continuing */
1716   winceMutexAcquire(pFile->hMutex);
1717 
1718   /* Since the names of named mutexes, semaphores, file mappings etc are
1719   ** case-sensitive, take advantage of that by uppercasing the mutex name
1720   ** and using that as the shared filemapping name.
1721   */
1722   osCharUpperW(zName);
1723   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
1724                                         PAGE_READWRITE, 0, sizeof(winceLock),
1725                                         zName);
1726 
1727   /* Set a flag that indicates we're the first to create the memory so it
1728   ** must be zero-initialized */
1729   lastErrno = osGetLastError();
1730   if (lastErrno == ERROR_ALREADY_EXISTS){
1731     bInit = FALSE;
1732   }
1733 
1734   sqlite3_free(zName);
1735 
1736   /* If we succeeded in making the shared memory handle, map it. */
1737   if( pFile->hShared ){
1738     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
1739              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
1740     /* If mapping failed, close the shared memory handle and erase it */
1741     if( !pFile->shared ){
1742       pFile->lastErrno = osGetLastError();
1743       winLogError(SQLITE_IOERR, pFile->lastErrno,
1744                   "winceCreateLock2", zFilename);
1745       bLogged = TRUE;
1746       osCloseHandle(pFile->hShared);
1747       pFile->hShared = NULL;
1748     }
1749   }
1750 
1751   /* If shared memory could not be created, then close the mutex and fail */
1752   if( pFile->hShared==NULL ){
1753     if( !bLogged ){
1754       pFile->lastErrno = lastErrno;
1755       winLogError(SQLITE_IOERR, pFile->lastErrno,
1756                   "winceCreateLock3", zFilename);
1757       bLogged = TRUE;
1758     }
1759     winceMutexRelease(pFile->hMutex);
1760     osCloseHandle(pFile->hMutex);
1761     pFile->hMutex = NULL;
1762     return SQLITE_IOERR;
1763   }
1764 
1765   /* Initialize the shared memory if we're supposed to */
1766   if( bInit ){
1767     memset(pFile->shared, 0, sizeof(winceLock));
1768   }
1769 
1770   winceMutexRelease(pFile->hMutex);
1771   return SQLITE_OK;
1772 }
1773 
1774 /*
1775 ** Destroy the part of winFile that deals with wince locks
1776 */
1777 static void winceDestroyLock(winFile *pFile){
1778   if (pFile->hMutex){
1779     /* Acquire the mutex */
1780     winceMutexAcquire(pFile->hMutex);
1781 
1782     /* The following blocks should probably assert in debug mode, but they
1783        are to cleanup in case any locks remained open */
1784     if (pFile->local.nReaders){
1785       pFile->shared->nReaders --;
1786     }
1787     if (pFile->local.bReserved){
1788       pFile->shared->bReserved = FALSE;
1789     }
1790     if (pFile->local.bPending){
1791       pFile->shared->bPending = FALSE;
1792     }
1793     if (pFile->local.bExclusive){
1794       pFile->shared->bExclusive = FALSE;
1795     }
1796 
1797     /* De-reference and close our copy of the shared memory handle */
1798     osUnmapViewOfFile(pFile->shared);
1799     osCloseHandle(pFile->hShared);
1800 
1801     /* Done with the mutex */
1802     winceMutexRelease(pFile->hMutex);
1803     osCloseHandle(pFile->hMutex);
1804     pFile->hMutex = NULL;
1805   }
1806 }
1807 
1808 /*
1809 ** An implementation of the LockFile() API of Windows for CE
1810 */
1811 static BOOL winceLockFile(
1812   LPHANDLE phFile,
1813   DWORD dwFileOffsetLow,
1814   DWORD dwFileOffsetHigh,
1815   DWORD nNumberOfBytesToLockLow,
1816   DWORD nNumberOfBytesToLockHigh
1817 ){
1818   winFile *pFile = HANDLE_TO_WINFILE(phFile);
1819   BOOL bReturn = FALSE;
1820 
1821   UNUSED_PARAMETER(dwFileOffsetHigh);
1822   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
1823 
1824   if (!pFile->hMutex) return TRUE;
1825   winceMutexAcquire(pFile->hMutex);
1826 
1827   /* Wanting an exclusive lock? */
1828   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
1829        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
1830     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
1831        pFile->shared->bExclusive = TRUE;
1832        pFile->local.bExclusive = TRUE;
1833        bReturn = TRUE;
1834     }
1835   }
1836 
1837   /* Want a read-only lock? */
1838   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
1839            nNumberOfBytesToLockLow == 1){
1840     if (pFile->shared->bExclusive == 0){
1841       pFile->local.nReaders ++;
1842       if (pFile->local.nReaders == 1){
1843         pFile->shared->nReaders ++;
1844       }
1845       bReturn = TRUE;
1846     }
1847   }
1848 
1849   /* Want a pending lock? */
1850   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
1851            && nNumberOfBytesToLockLow == 1){
1852     /* If no pending lock has been acquired, then acquire it */
1853     if (pFile->shared->bPending == 0) {
1854       pFile->shared->bPending = TRUE;
1855       pFile->local.bPending = TRUE;
1856       bReturn = TRUE;
1857     }
1858   }
1859 
1860   /* Want a reserved lock? */
1861   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
1862            && nNumberOfBytesToLockLow == 1){
1863     if (pFile->shared->bReserved == 0) {
1864       pFile->shared->bReserved = TRUE;
1865       pFile->local.bReserved = TRUE;
1866       bReturn = TRUE;
1867     }
1868   }
1869 
1870   winceMutexRelease(pFile->hMutex);
1871   return bReturn;
1872 }
1873 
1874 /*
1875 ** An implementation of the UnlockFile API of Windows for CE
1876 */
1877 static BOOL winceUnlockFile(
1878   LPHANDLE phFile,
1879   DWORD dwFileOffsetLow,
1880   DWORD dwFileOffsetHigh,
1881   DWORD nNumberOfBytesToUnlockLow,
1882   DWORD nNumberOfBytesToUnlockHigh
1883 ){
1884   winFile *pFile = HANDLE_TO_WINFILE(phFile);
1885   BOOL bReturn = FALSE;
1886 
1887   UNUSED_PARAMETER(dwFileOffsetHigh);
1888   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
1889 
1890   if (!pFile->hMutex) return TRUE;
1891   winceMutexAcquire(pFile->hMutex);
1892 
1893   /* Releasing a reader lock or an exclusive lock */
1894   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
1895     /* Did we have an exclusive lock? */
1896     if (pFile->local.bExclusive){
1897       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
1898       pFile->local.bExclusive = FALSE;
1899       pFile->shared->bExclusive = FALSE;
1900       bReturn = TRUE;
1901     }
1902 
1903     /* Did we just have a reader lock? */
1904     else if (pFile->local.nReaders){
1905       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
1906              || nNumberOfBytesToUnlockLow == 1);
1907       pFile->local.nReaders --;
1908       if (pFile->local.nReaders == 0)
1909       {
1910         pFile->shared->nReaders --;
1911       }
1912       bReturn = TRUE;
1913     }
1914   }
1915 
1916   /* Releasing a pending lock */
1917   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
1918            && nNumberOfBytesToUnlockLow == 1){
1919     if (pFile->local.bPending){
1920       pFile->local.bPending = FALSE;
1921       pFile->shared->bPending = FALSE;
1922       bReturn = TRUE;
1923     }
1924   }
1925   /* Releasing a reserved lock */
1926   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
1927            && nNumberOfBytesToUnlockLow == 1){
1928     if (pFile->local.bReserved) {
1929       pFile->local.bReserved = FALSE;
1930       pFile->shared->bReserved = FALSE;
1931       bReturn = TRUE;
1932     }
1933   }
1934 
1935   winceMutexRelease(pFile->hMutex);
1936   return bReturn;
1937 }
1938 /*
1939 ** End of the special code for wince
1940 *****************************************************************************/
1941 #endif /* SQLITE_OS_WINCE */
1942 
1943 /*
1944 ** Lock a file region.
1945 */
1946 static BOOL winLockFile(
1947   LPHANDLE phFile,
1948   DWORD flags,
1949   DWORD offsetLow,
1950   DWORD offsetHigh,
1951   DWORD numBytesLow,
1952   DWORD numBytesHigh
1953 ){
1954 #if SQLITE_OS_WINCE
1955   /*
1956   ** NOTE: Windows CE is handled differently here due its lack of the Win32
1957   **       API LockFile.
1958   */
1959   return winceLockFile(phFile, offsetLow, offsetHigh,
1960                        numBytesLow, numBytesHigh);
1961 #else
1962   if( isNT() ){
1963     OVERLAPPED ovlp;
1964     memset(&ovlp, 0, sizeof(OVERLAPPED));
1965     ovlp.Offset = offsetLow;
1966     ovlp.OffsetHigh = offsetHigh;
1967     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
1968   }else{
1969     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
1970                       numBytesHigh);
1971   }
1972 #endif
1973 }
1974 
1975 /*
1976 ** Unlock a file region.
1977  */
1978 static BOOL winUnlockFile(
1979   LPHANDLE phFile,
1980   DWORD offsetLow,
1981   DWORD offsetHigh,
1982   DWORD numBytesLow,
1983   DWORD numBytesHigh
1984 ){
1985 #if SQLITE_OS_WINCE
1986   /*
1987   ** NOTE: Windows CE is handled differently here due its lack of the Win32
1988   **       API UnlockFile.
1989   */
1990   return winceUnlockFile(phFile, offsetLow, offsetHigh,
1991                          numBytesLow, numBytesHigh);
1992 #else
1993   if( isNT() ){
1994     OVERLAPPED ovlp;
1995     memset(&ovlp, 0, sizeof(OVERLAPPED));
1996     ovlp.Offset = offsetLow;
1997     ovlp.OffsetHigh = offsetHigh;
1998     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
1999   }else{
2000     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
2001                         numBytesHigh);
2002   }
2003 #endif
2004 }
2005 
2006 /*****************************************************************************
2007 ** The next group of routines implement the I/O methods specified
2008 ** by the sqlite3_io_methods object.
2009 ******************************************************************************/
2010 
2011 /*
2012 ** Some Microsoft compilers lack this definition.
2013 */
2014 #ifndef INVALID_SET_FILE_POINTER
2015 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
2016 #endif
2017 
2018 /*
2019 ** Move the current position of the file handle passed as the first
2020 ** argument to offset iOffset within the file. If successful, return 0.
2021 ** Otherwise, set pFile->lastErrno and return non-zero.
2022 */
2023 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
2024 #if !SQLITE_OS_WINRT
2025   LONG upperBits;                 /* Most sig. 32 bits of new offset */
2026   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
2027   DWORD dwRet;                    /* Value returned by SetFilePointer() */
2028   DWORD lastErrno;                /* Value returned by GetLastError() */
2029 
2030   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
2031   lowerBits = (LONG)(iOffset & 0xffffffff);
2032 
2033   /* API oddity: If successful, SetFilePointer() returns a dword
2034   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
2035   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
2036   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
2037   ** whether an error has actually occurred, it is also necessary to call
2038   ** GetLastError().
2039   */
2040   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
2041 
2042   if( (dwRet==INVALID_SET_FILE_POINTER
2043       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
2044     pFile->lastErrno = lastErrno;
2045     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
2046              "seekWinFile", pFile->zPath);
2047     return 1;
2048   }
2049 
2050   return 0;
2051 #else
2052   /*
2053   ** Same as above, except that this implementation works for WinRT.
2054   */
2055 
2056   LARGE_INTEGER x;                /* The new offset */
2057   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
2058 
2059   x.QuadPart = iOffset;
2060   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
2061 
2062   if(!bRet){
2063     pFile->lastErrno = osGetLastError();
2064     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
2065              "seekWinFile", pFile->zPath);
2066     return 1;
2067   }
2068 
2069   return 0;
2070 #endif
2071 }
2072 
2073 #if SQLITE_MAX_MMAP_SIZE>0
2074 /* Forward references to VFS methods */
2075 static int winUnmapfile(winFile*);
2076 #endif
2077 
2078 /*
2079 ** Close a file.
2080 **
2081 ** It is reported that an attempt to close a handle might sometimes
2082 ** fail.  This is a very unreasonable result, but Windows is notorious
2083 ** for being unreasonable so I do not doubt that it might happen.  If
2084 ** the close fails, we pause for 100 milliseconds and try again.  As
2085 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
2086 ** giving up and returning an error.
2087 */
2088 #define MX_CLOSE_ATTEMPT 3
2089 static int winClose(sqlite3_file *id){
2090   int rc, cnt = 0;
2091   winFile *pFile = (winFile*)id;
2092 
2093   assert( id!=0 );
2094 #ifndef SQLITE_OMIT_WAL
2095   assert( pFile->pShm==0 );
2096 #endif
2097   OSTRACE(("CLOSE %d\n", pFile->h));
2098   assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
2099 
2100 #if SQLITE_MAX_MMAP_SIZE>0
2101   rc = winUnmapfile(pFile);
2102   if( rc!=SQLITE_OK ) return rc;
2103 #endif
2104 
2105   do{
2106     rc = osCloseHandle(pFile->h);
2107     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
2108   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
2109 #if SQLITE_OS_WINCE
2110 #define WINCE_DELETION_ATTEMPTS 3
2111   winceDestroyLock(pFile);
2112   if( pFile->zDeleteOnClose ){
2113     int cnt = 0;
2114     while(
2115            osDeleteFileW(pFile->zDeleteOnClose)==0
2116         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
2117         && cnt++ < WINCE_DELETION_ATTEMPTS
2118     ){
2119        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
2120     }
2121     sqlite3_free(pFile->zDeleteOnClose);
2122   }
2123 #endif
2124   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
2125   if( rc ){
2126     pFile->h = NULL;
2127   }
2128   OpenCounter(-1);
2129   return rc ? SQLITE_OK
2130             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
2131                           "winClose", pFile->zPath);
2132 }
2133 
2134 /*
2135 ** Read data from a file into a buffer.  Return SQLITE_OK if all
2136 ** bytes were read successfully and SQLITE_IOERR if anything goes
2137 ** wrong.
2138 */
2139 static int winRead(
2140   sqlite3_file *id,          /* File to read from */
2141   void *pBuf,                /* Write content into this buffer */
2142   int amt,                   /* Number of bytes to read */
2143   sqlite3_int64 offset       /* Begin reading at this offset */
2144 ){
2145 #if !SQLITE_OS_WINCE
2146   OVERLAPPED overlapped;          /* The offset for ReadFile. */
2147 #endif
2148   winFile *pFile = (winFile*)id;  /* file handle */
2149   DWORD nRead;                    /* Number of bytes actually read from file */
2150   int nRetry = 0;                 /* Number of retrys */
2151 
2152   assert( id!=0 );
2153   assert( amt>0 );
2154   SimulateIOError(return SQLITE_IOERR_READ);
2155   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
2156 
2157 #if SQLITE_MAX_MMAP_SIZE>0
2158   /* Deal with as much of this read request as possible by transfering
2159   ** data from the memory mapping using memcpy().  */
2160   if( offset<pFile->mmapSize ){
2161     if( offset+amt <= pFile->mmapSize ){
2162       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
2163       return SQLITE_OK;
2164     }else{
2165       int nCopy = (int)(pFile->mmapSize - offset);
2166       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
2167       pBuf = &((u8 *)pBuf)[nCopy];
2168       amt -= nCopy;
2169       offset += nCopy;
2170     }
2171   }
2172 #endif
2173 
2174 #if SQLITE_OS_WINCE
2175   if( seekWinFile(pFile, offset) ){
2176     return SQLITE_FULL;
2177   }
2178   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
2179 #else
2180   memset(&overlapped, 0, sizeof(OVERLAPPED));
2181   overlapped.Offset = (LONG)(offset & 0xffffffff);
2182   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
2183   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
2184          osGetLastError()!=ERROR_HANDLE_EOF ){
2185 #endif
2186     DWORD lastErrno;
2187     if( retryIoerr(&nRetry, &lastErrno) ) continue;
2188     pFile->lastErrno = lastErrno;
2189     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
2190              "winRead", pFile->zPath);
2191   }
2192   logIoerr(nRetry);
2193   if( nRead<(DWORD)amt ){
2194     /* Unread parts of the buffer must be zero-filled */
2195     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
2196     return SQLITE_IOERR_SHORT_READ;
2197   }
2198 
2199   return SQLITE_OK;
2200 }
2201 
2202 /*
2203 ** Write data from a buffer into a file.  Return SQLITE_OK on success
2204 ** or some other error code on failure.
2205 */
2206 static int winWrite(
2207   sqlite3_file *id,               /* File to write into */
2208   const void *pBuf,               /* The bytes to be written */
2209   int amt,                        /* Number of bytes to write */
2210   sqlite3_int64 offset            /* Offset into the file to begin writing at */
2211 ){
2212   int rc = 0;                     /* True if error has occurred, else false */
2213   winFile *pFile = (winFile*)id;  /* File handle */
2214   int nRetry = 0;                 /* Number of retries */
2215 
2216   assert( amt>0 );
2217   assert( pFile );
2218   SimulateIOError(return SQLITE_IOERR_WRITE);
2219   SimulateDiskfullError(return SQLITE_FULL);
2220 
2221   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
2222 
2223 #if SQLITE_MAX_MMAP_SIZE>0
2224   /* Deal with as much of this write request as possible by transfering
2225   ** data from the memory mapping using memcpy().  */
2226   if( offset<pFile->mmapSize ){
2227     if( offset+amt <= pFile->mmapSize ){
2228       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
2229       return SQLITE_OK;
2230     }else{
2231       int nCopy = (int)(pFile->mmapSize - offset);
2232       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
2233       pBuf = &((u8 *)pBuf)[nCopy];
2234       amt -= nCopy;
2235       offset += nCopy;
2236     }
2237   }
2238 #endif
2239 
2240 #if SQLITE_OS_WINCE
2241   rc = seekWinFile(pFile, offset);
2242   if( rc==0 ){
2243 #else
2244   {
2245 #endif
2246 #if !SQLITE_OS_WINCE
2247     OVERLAPPED overlapped;        /* The offset for WriteFile. */
2248 #endif
2249     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
2250     int nRem = amt;               /* Number of bytes yet to be written */
2251     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
2252     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
2253 
2254 #if !SQLITE_OS_WINCE
2255     memset(&overlapped, 0, sizeof(OVERLAPPED));
2256     overlapped.Offset = (LONG)(offset & 0xffffffff);
2257     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
2258 #endif
2259 
2260     while( nRem>0 ){
2261 #if SQLITE_OS_WINCE
2262       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
2263 #else
2264       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
2265 #endif
2266         if( retryIoerr(&nRetry, &lastErrno) ) continue;
2267         break;
2268       }
2269       assert( nWrite==0 || nWrite<=(DWORD)nRem );
2270       if( nWrite==0 || nWrite>(DWORD)nRem ){
2271         lastErrno = osGetLastError();
2272         break;
2273       }
2274 #if !SQLITE_OS_WINCE
2275       offset += nWrite;
2276       overlapped.Offset = (LONG)(offset & 0xffffffff);
2277       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
2278 #endif
2279       aRem += nWrite;
2280       nRem -= nWrite;
2281     }
2282     if( nRem>0 ){
2283       pFile->lastErrno = lastErrno;
2284       rc = 1;
2285     }
2286   }
2287 
2288   if( rc ){
2289     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
2290        || ( pFile->lastErrno==ERROR_DISK_FULL )){
2291       return SQLITE_FULL;
2292     }
2293     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
2294              "winWrite", pFile->zPath);
2295   }else{
2296     logIoerr(nRetry);
2297   }
2298   return SQLITE_OK;
2299 }
2300 
2301 /*
2302 ** Truncate an open file to a specified size
2303 */
2304 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
2305   winFile *pFile = (winFile*)id;  /* File handle object */
2306   int rc = SQLITE_OK;             /* Return code for this function */
2307   DWORD lastErrno;
2308 
2309   assert( pFile );
2310 
2311   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
2312   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
2313 
2314   /* If the user has configured a chunk-size for this file, truncate the
2315   ** file so that it consists of an integer number of chunks (i.e. the
2316   ** actual file size after the operation may be larger than the requested
2317   ** size).
2318   */
2319   if( pFile->szChunk>0 ){
2320     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
2321   }
2322 
2323   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
2324   if( seekWinFile(pFile, nByte) ){
2325     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
2326                      "winTruncate1", pFile->zPath);
2327   }else if( 0==osSetEndOfFile(pFile->h) &&
2328             ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
2329     pFile->lastErrno = lastErrno;
2330     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
2331                      "winTruncate2", pFile->zPath);
2332   }
2333 
2334 #if SQLITE_MAX_MMAP_SIZE>0
2335   /* If the file was truncated to a size smaller than the currently
2336   ** mapped region, reduce the effective mapping size as well. SQLite will
2337   ** use read() and write() to access data beyond this point from now on.
2338   */
2339   if( pFile->pMapRegion && nByte<pFile->mmapSize ){
2340     pFile->mmapSize = nByte;
2341   }
2342 #endif
2343 
2344   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
2345   return rc;
2346 }
2347 
2348 #ifdef SQLITE_TEST
2349 /*
2350 ** Count the number of fullsyncs and normal syncs.  This is used to test
2351 ** that syncs and fullsyncs are occuring at the right times.
2352 */
2353 int sqlite3_sync_count = 0;
2354 int sqlite3_fullsync_count = 0;
2355 #endif
2356 
2357 /*
2358 ** Make sure all writes to a particular file are committed to disk.
2359 */
2360 static int winSync(sqlite3_file *id, int flags){
2361 #ifndef SQLITE_NO_SYNC
2362   /*
2363   ** Used only when SQLITE_NO_SYNC is not defined.
2364    */
2365   BOOL rc;
2366 #endif
2367 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
2368     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
2369   /*
2370   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
2371   ** OSTRACE() macros.
2372    */
2373   winFile *pFile = (winFile*)id;
2374 #else
2375   UNUSED_PARAMETER(id);
2376 #endif
2377 
2378   assert( pFile );
2379   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
2380   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
2381       || (flags&0x0F)==SQLITE_SYNC_FULL
2382   );
2383 
2384   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
2385 
2386   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
2387   ** line is to test that doing so does not cause any problems.
2388   */
2389   SimulateDiskfullError( return SQLITE_FULL );
2390 
2391 #ifndef SQLITE_TEST
2392   UNUSED_PARAMETER(flags);
2393 #else
2394   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
2395     sqlite3_fullsync_count++;
2396   }
2397   sqlite3_sync_count++;
2398 #endif
2399 
2400   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
2401   ** no-op
2402   */
2403 #ifdef SQLITE_NO_SYNC
2404   return SQLITE_OK;
2405 #else
2406   rc = osFlushFileBuffers(pFile->h);
2407   SimulateIOError( rc=FALSE );
2408   if( rc ){
2409     return SQLITE_OK;
2410   }else{
2411     pFile->lastErrno = osGetLastError();
2412     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
2413              "winSync", pFile->zPath);
2414   }
2415 #endif
2416 }
2417 
2418 /*
2419 ** Determine the current size of a file in bytes
2420 */
2421 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
2422   winFile *pFile = (winFile*)id;
2423   int rc = SQLITE_OK;
2424 
2425   assert( id!=0 );
2426   SimulateIOError(return SQLITE_IOERR_FSTAT);
2427 #if SQLITE_OS_WINRT
2428   {
2429     FILE_STANDARD_INFO info;
2430     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
2431                                      &info, sizeof(info)) ){
2432       *pSize = info.EndOfFile.QuadPart;
2433     }else{
2434       pFile->lastErrno = osGetLastError();
2435       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
2436                        "winFileSize", pFile->zPath);
2437     }
2438   }
2439 #else
2440   {
2441     DWORD upperBits;
2442     DWORD lowerBits;
2443     DWORD lastErrno;
2444 
2445     lowerBits = osGetFileSize(pFile->h, &upperBits);
2446     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
2447     if(   (lowerBits == INVALID_FILE_SIZE)
2448        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
2449       pFile->lastErrno = lastErrno;
2450       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
2451              "winFileSize", pFile->zPath);
2452     }
2453   }
2454 #endif
2455   return rc;
2456 }
2457 
2458 /*
2459 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
2460 */
2461 #ifndef LOCKFILE_FAIL_IMMEDIATELY
2462 # define LOCKFILE_FAIL_IMMEDIATELY 1
2463 #endif
2464 
2465 #ifndef LOCKFILE_EXCLUSIVE_LOCK
2466 # define LOCKFILE_EXCLUSIVE_LOCK 2
2467 #endif
2468 
2469 /*
2470 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
2471 ** When the LockFile function was used, it was always expected to fail
2472 ** immediately if the lock could not be obtained.  Also, it always expected to
2473 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
2474 ** and reflect those expectations; therefore, they should not be changed.
2475 */
2476 #ifndef SQLITE_LOCKFILE_FLAGS
2477 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
2478                                   LOCKFILE_EXCLUSIVE_LOCK)
2479 #endif
2480 
2481 /*
2482 ** Currently, SQLite never calls the LockFileEx function without wanting the
2483 ** call to fail immediately if the lock cannot be obtained.
2484 */
2485 #ifndef SQLITE_LOCKFILEEX_FLAGS
2486 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
2487 #endif
2488 
2489 /*
2490 ** Acquire a reader lock.
2491 ** Different API routines are called depending on whether or not this
2492 ** is Win9x or WinNT.
2493 */
2494 static int getReadLock(winFile *pFile){
2495   int res;
2496   if( isNT() ){
2497 #if SQLITE_OS_WINCE
2498     /*
2499     ** NOTE: Windows CE is handled differently here due its lack of the Win32
2500     **       API LockFileEx.
2501     */
2502     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
2503 #else
2504     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
2505                       SHARED_SIZE, 0);
2506 #endif
2507   }
2508 #ifdef SQLITE_WIN32_HAS_ANSI
2509   else{
2510     int lk;
2511     sqlite3_randomness(sizeof(lk), &lk);
2512     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
2513     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
2514                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
2515   }
2516 #endif
2517   if( res == 0 ){
2518     pFile->lastErrno = osGetLastError();
2519     /* No need to log a failure to lock */
2520   }
2521   return res;
2522 }
2523 
2524 /*
2525 ** Undo a readlock
2526 */
2527 static int unlockReadLock(winFile *pFile){
2528   int res;
2529   DWORD lastErrno;
2530   if( isNT() ){
2531     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
2532   }
2533 #ifdef SQLITE_WIN32_HAS_ANSI
2534   else{
2535     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
2536   }
2537 #endif
2538   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
2539     pFile->lastErrno = lastErrno;
2540     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
2541              "unlockReadLock", pFile->zPath);
2542   }
2543   return res;
2544 }
2545 
2546 /*
2547 ** Lock the file with the lock specified by parameter locktype - one
2548 ** of the following:
2549 **
2550 **     (1) SHARED_LOCK
2551 **     (2) RESERVED_LOCK
2552 **     (3) PENDING_LOCK
2553 **     (4) EXCLUSIVE_LOCK
2554 **
2555 ** Sometimes when requesting one lock state, additional lock states
2556 ** are inserted in between.  The locking might fail on one of the later
2557 ** transitions leaving the lock state different from what it started but
2558 ** still short of its goal.  The following chart shows the allowed
2559 ** transitions and the inserted intermediate states:
2560 **
2561 **    UNLOCKED -> SHARED
2562 **    SHARED -> RESERVED
2563 **    SHARED -> (PENDING) -> EXCLUSIVE
2564 **    RESERVED -> (PENDING) -> EXCLUSIVE
2565 **    PENDING -> EXCLUSIVE
2566 **
2567 ** This routine will only increase a lock.  The winUnlock() routine
2568 ** erases all locks at once and returns us immediately to locking level 0.
2569 ** It is not possible to lower the locking level one step at a time.  You
2570 ** must go straight to locking level 0.
2571 */
2572 static int winLock(sqlite3_file *id, int locktype){
2573   int rc = SQLITE_OK;    /* Return code from subroutines */
2574   int res = 1;           /* Result of a Windows lock call */
2575   int newLocktype;       /* Set pFile->locktype to this value before exiting */
2576   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
2577   winFile *pFile = (winFile*)id;
2578   DWORD lastErrno = NO_ERROR;
2579 
2580   assert( id!=0 );
2581   OSTRACE(("LOCK %d %d was %d(%d)\n",
2582            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
2583 
2584   /* If there is already a lock of this type or more restrictive on the
2585   ** OsFile, do nothing. Don't use the end_lock: exit path, as
2586   ** sqlite3OsEnterMutex() hasn't been called yet.
2587   */
2588   if( pFile->locktype>=locktype ){
2589     return SQLITE_OK;
2590   }
2591 
2592   /* Make sure the locking sequence is correct
2593   */
2594   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
2595   assert( locktype!=PENDING_LOCK );
2596   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
2597 
2598   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
2599   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
2600   ** the PENDING_LOCK byte is temporary.
2601   */
2602   newLocktype = pFile->locktype;
2603   if(   (pFile->locktype==NO_LOCK)
2604      || (   (locktype==EXCLUSIVE_LOCK)
2605          && (pFile->locktype==RESERVED_LOCK))
2606   ){
2607     int cnt = 3;
2608     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
2609                                          PENDING_BYTE, 0, 1, 0))==0 ){
2610       /* Try 3 times to get the pending lock.  This is needed to work
2611       ** around problems caused by indexing and/or anti-virus software on
2612       ** Windows systems.
2613       ** If you are using this code as a model for alternative VFSes, do not
2614       ** copy this retry logic.  It is a hack intended for Windows only.
2615       */
2616       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
2617       if( cnt ) sqlite3_win32_sleep(1);
2618     }
2619     gotPendingLock = res;
2620     if( !res ){
2621       lastErrno = osGetLastError();
2622     }
2623   }
2624 
2625   /* Acquire a shared lock
2626   */
2627   if( locktype==SHARED_LOCK && res ){
2628     assert( pFile->locktype==NO_LOCK );
2629     res = getReadLock(pFile);
2630     if( res ){
2631       newLocktype = SHARED_LOCK;
2632     }else{
2633       lastErrno = osGetLastError();
2634     }
2635   }
2636 
2637   /* Acquire a RESERVED lock
2638   */
2639   if( locktype==RESERVED_LOCK && res ){
2640     assert( pFile->locktype==SHARED_LOCK );
2641     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
2642     if( res ){
2643       newLocktype = RESERVED_LOCK;
2644     }else{
2645       lastErrno = osGetLastError();
2646     }
2647   }
2648 
2649   /* Acquire a PENDING lock
2650   */
2651   if( locktype==EXCLUSIVE_LOCK && res ){
2652     newLocktype = PENDING_LOCK;
2653     gotPendingLock = 0;
2654   }
2655 
2656   /* Acquire an EXCLUSIVE lock
2657   */
2658   if( locktype==EXCLUSIVE_LOCK && res ){
2659     assert( pFile->locktype>=SHARED_LOCK );
2660     res = unlockReadLock(pFile);
2661     OSTRACE(("unreadlock = %d\n", res));
2662     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
2663                       SHARED_SIZE, 0);
2664     if( res ){
2665       newLocktype = EXCLUSIVE_LOCK;
2666     }else{
2667       lastErrno = osGetLastError();
2668       OSTRACE(("error-code = %d\n", lastErrno));
2669       getReadLock(pFile);
2670     }
2671   }
2672 
2673   /* If we are holding a PENDING lock that ought to be released, then
2674   ** release it now.
2675   */
2676   if( gotPendingLock && locktype==SHARED_LOCK ){
2677     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
2678   }
2679 
2680   /* Update the state of the lock has held in the file descriptor then
2681   ** return the appropriate result code.
2682   */
2683   if( res ){
2684     rc = SQLITE_OK;
2685   }else{
2686     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
2687            locktype, newLocktype));
2688     pFile->lastErrno = lastErrno;
2689     rc = SQLITE_BUSY;
2690   }
2691   pFile->locktype = (u8)newLocktype;
2692   return rc;
2693 }
2694 
2695 /*
2696 ** This routine checks if there is a RESERVED lock held on the specified
2697 ** file by this or any other process. If such a lock is held, return
2698 ** non-zero, otherwise zero.
2699 */
2700 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
2701   int rc;
2702   winFile *pFile = (winFile*)id;
2703 
2704   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2705 
2706   assert( id!=0 );
2707   if( pFile->locktype>=RESERVED_LOCK ){
2708     rc = 1;
2709     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
2710   }else{
2711     rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
2712     if( rc ){
2713       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
2714     }
2715     rc = !rc;
2716     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
2717   }
2718   *pResOut = rc;
2719   return SQLITE_OK;
2720 }
2721 
2722 /*
2723 ** Lower the locking level on file descriptor id to locktype.  locktype
2724 ** must be either NO_LOCK or SHARED_LOCK.
2725 **
2726 ** If the locking level of the file descriptor is already at or below
2727 ** the requested locking level, this routine is a no-op.
2728 **
2729 ** It is not possible for this routine to fail if the second argument
2730 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
2731 ** might return SQLITE_IOERR;
2732 */
2733 static int winUnlock(sqlite3_file *id, int locktype){
2734   int type;
2735   winFile *pFile = (winFile*)id;
2736   int rc = SQLITE_OK;
2737   assert( pFile!=0 );
2738   assert( locktype<=SHARED_LOCK );
2739   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
2740           pFile->locktype, pFile->sharedLockByte));
2741   type = pFile->locktype;
2742   if( type>=EXCLUSIVE_LOCK ){
2743     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
2744     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
2745       /* This should never happen.  We should always be able to
2746       ** reacquire the read lock */
2747       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
2748                "winUnlock", pFile->zPath);
2749     }
2750   }
2751   if( type>=RESERVED_LOCK ){
2752     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
2753   }
2754   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
2755     unlockReadLock(pFile);
2756   }
2757   if( type>=PENDING_LOCK ){
2758     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
2759   }
2760   pFile->locktype = (u8)locktype;
2761   return rc;
2762 }
2763 
2764 /*
2765 ** If *pArg is inititially negative then this is a query.  Set *pArg to
2766 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
2767 **
2768 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
2769 */
2770 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
2771   if( *pArg<0 ){
2772     *pArg = (pFile->ctrlFlags & mask)!=0;
2773   }else if( (*pArg)==0 ){
2774     pFile->ctrlFlags &= ~mask;
2775   }else{
2776     pFile->ctrlFlags |= mask;
2777   }
2778 }
2779 
2780 /* Forward declaration */
2781 static int getTempname(int nBuf, char *zBuf);
2782 
2783 /*
2784 ** Control and query of the open file handle.
2785 */
2786 static int winFileControl(sqlite3_file *id, int op, void *pArg){
2787   winFile *pFile = (winFile*)id;
2788   switch( op ){
2789     case SQLITE_FCNTL_LOCKSTATE: {
2790       *(int*)pArg = pFile->locktype;
2791       return SQLITE_OK;
2792     }
2793     case SQLITE_LAST_ERRNO: {
2794       *(int*)pArg = (int)pFile->lastErrno;
2795       return SQLITE_OK;
2796     }
2797     case SQLITE_FCNTL_CHUNK_SIZE: {
2798       pFile->szChunk = *(int *)pArg;
2799       return SQLITE_OK;
2800     }
2801     case SQLITE_FCNTL_SIZE_HINT: {
2802       if( pFile->szChunk>0 ){
2803         sqlite3_int64 oldSz;
2804         int rc = winFileSize(id, &oldSz);
2805         if( rc==SQLITE_OK ){
2806           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
2807           if( newSz>oldSz ){
2808             SimulateIOErrorBenign(1);
2809             rc = winTruncate(id, newSz);
2810             SimulateIOErrorBenign(0);
2811           }
2812         }
2813         return rc;
2814       }
2815       return SQLITE_OK;
2816     }
2817     case SQLITE_FCNTL_PERSIST_WAL: {
2818       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
2819       return SQLITE_OK;
2820     }
2821     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
2822       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
2823       return SQLITE_OK;
2824     }
2825     case SQLITE_FCNTL_VFSNAME: {
2826       *(char**)pArg = sqlite3_mprintf("win32");
2827       return SQLITE_OK;
2828     }
2829     case SQLITE_FCNTL_WIN32_AV_RETRY: {
2830       int *a = (int*)pArg;
2831       if( a[0]>0 ){
2832         win32IoerrRetry = a[0];
2833       }else{
2834         a[0] = win32IoerrRetry;
2835       }
2836       if( a[1]>0 ){
2837         win32IoerrRetryDelay = a[1];
2838       }else{
2839         a[1] = win32IoerrRetryDelay;
2840       }
2841       return SQLITE_OK;
2842     }
2843     case SQLITE_FCNTL_TEMPFILENAME: {
2844       char *zTFile = sqlite3MallocZero( pFile->pVfs->mxPathname );
2845       if( zTFile ){
2846         getTempname(pFile->pVfs->mxPathname, zTFile);
2847         *(char**)pArg = zTFile;
2848       }
2849       return SQLITE_OK;
2850     }
2851 #if SQLITE_MAX_MMAP_SIZE>0
2852     case SQLITE_FCNTL_MMAP_SIZE: {
2853       i64 newLimit = *(i64*)pArg;
2854       if( newLimit>sqlite3GlobalConfig.mxMmap ){
2855         newLimit = sqlite3GlobalConfig.mxMmap;
2856       }
2857       *(i64*)pArg = pFile->mmapSizeMax;
2858       if( newLimit>=0 ) pFile->mmapSizeMax = newLimit;
2859       return SQLITE_OK;
2860     }
2861 #endif
2862   }
2863   return SQLITE_NOTFOUND;
2864 }
2865 
2866 /*
2867 ** Return the sector size in bytes of the underlying block device for
2868 ** the specified file. This is almost always 512 bytes, but may be
2869 ** larger for some devices.
2870 **
2871 ** SQLite code assumes this function cannot fail. It also assumes that
2872 ** if two files are created in the same file-system directory (i.e.
2873 ** a database and its journal file) that the sector size will be the
2874 ** same for both.
2875 */
2876 static int winSectorSize(sqlite3_file *id){
2877   (void)id;
2878   return SQLITE_DEFAULT_SECTOR_SIZE;
2879 }
2880 
2881 /*
2882 ** Return a vector of device characteristics.
2883 */
2884 static int winDeviceCharacteristics(sqlite3_file *id){
2885   winFile *p = (winFile*)id;
2886   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
2887          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
2888 }
2889 
2890 #ifndef SQLITE_OMIT_WAL
2891 
2892 /*
2893 ** Windows will only let you create file view mappings
2894 ** on allocation size granularity boundaries.
2895 ** During sqlite3_os_init() we do a GetSystemInfo()
2896 ** to get the granularity size.
2897 */
2898 SYSTEM_INFO winSysInfo;
2899 
2900 /*
2901 ** Helper functions to obtain and relinquish the global mutex. The
2902 ** global mutex is used to protect the winLockInfo objects used by
2903 ** this file, all of which may be shared by multiple threads.
2904 **
2905 ** Function winShmMutexHeld() is used to assert() that the global mutex
2906 ** is held when required. This function is only used as part of assert()
2907 ** statements. e.g.
2908 **
2909 **   winShmEnterMutex()
2910 **     assert( winShmMutexHeld() );
2911 **   winShmLeaveMutex()
2912 */
2913 static void winShmEnterMutex(void){
2914   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
2915 }
2916 static void winShmLeaveMutex(void){
2917   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
2918 }
2919 #ifdef SQLITE_DEBUG
2920 static int winShmMutexHeld(void) {
2921   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
2922 }
2923 #endif
2924 
2925 /*
2926 ** Object used to represent a single file opened and mmapped to provide
2927 ** shared memory.  When multiple threads all reference the same
2928 ** log-summary, each thread has its own winFile object, but they all
2929 ** point to a single instance of this object.  In other words, each
2930 ** log-summary is opened only once per process.
2931 **
2932 ** winShmMutexHeld() must be true when creating or destroying
2933 ** this object or while reading or writing the following fields:
2934 **
2935 **      nRef
2936 **      pNext
2937 **
2938 ** The following fields are read-only after the object is created:
2939 **
2940 **      fid
2941 **      zFilename
2942 **
2943 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
2944 ** winShmMutexHeld() is true when reading or writing any other field
2945 ** in this structure.
2946 **
2947 */
2948 struct winShmNode {
2949   sqlite3_mutex *mutex;      /* Mutex to access this object */
2950   char *zFilename;           /* Name of the file */
2951   winFile hFile;             /* File handle from winOpen */
2952 
2953   int szRegion;              /* Size of shared-memory regions */
2954   int nRegion;               /* Size of array apRegion */
2955   struct ShmRegion {
2956     HANDLE hMap;             /* File handle from CreateFileMapping */
2957     void *pMap;
2958   } *aRegion;
2959   DWORD lastErrno;           /* The Windows errno from the last I/O error */
2960 
2961   int nRef;                  /* Number of winShm objects pointing to this */
2962   winShm *pFirst;            /* All winShm objects pointing to this */
2963   winShmNode *pNext;         /* Next in list of all winShmNode objects */
2964 #ifdef SQLITE_DEBUG
2965   u8 nextShmId;              /* Next available winShm.id value */
2966 #endif
2967 };
2968 
2969 /*
2970 ** A global array of all winShmNode objects.
2971 **
2972 ** The winShmMutexHeld() must be true while reading or writing this list.
2973 */
2974 static winShmNode *winShmNodeList = 0;
2975 
2976 /*
2977 ** Structure used internally by this VFS to record the state of an
2978 ** open shared memory connection.
2979 **
2980 ** The following fields are initialized when this object is created and
2981 ** are read-only thereafter:
2982 **
2983 **    winShm.pShmNode
2984 **    winShm.id
2985 **
2986 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
2987 ** while accessing any read/write fields.
2988 */
2989 struct winShm {
2990   winShmNode *pShmNode;      /* The underlying winShmNode object */
2991   winShm *pNext;             /* Next winShm with the same winShmNode */
2992   u8 hasMutex;               /* True if holding the winShmNode mutex */
2993   u16 sharedMask;            /* Mask of shared locks held */
2994   u16 exclMask;              /* Mask of exclusive locks held */
2995 #ifdef SQLITE_DEBUG
2996   u8 id;                     /* Id of this connection with its winShmNode */
2997 #endif
2998 };
2999 
3000 /*
3001 ** Constants used for locking
3002 */
3003 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
3004 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
3005 
3006 /*
3007 ** Apply advisory locks for all n bytes beginning at ofst.
3008 */
3009 #define _SHM_UNLCK  1
3010 #define _SHM_RDLCK  2
3011 #define _SHM_WRLCK  3
3012 static int winShmSystemLock(
3013   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
3014   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
3015   int ofst,             /* Offset to first byte to be locked/unlocked */
3016   int nByte             /* Number of bytes to lock or unlock */
3017 ){
3018   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
3019 
3020   /* Access to the winShmNode object is serialized by the caller */
3021   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
3022 
3023   /* Release/Acquire the system-level lock */
3024   if( lockType==_SHM_UNLCK ){
3025     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
3026   }else{
3027     /* Initialize the locking parameters */
3028     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
3029     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
3030     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
3031   }
3032 
3033   if( rc!= 0 ){
3034     rc = SQLITE_OK;
3035   }else{
3036     pFile->lastErrno =  osGetLastError();
3037     rc = SQLITE_BUSY;
3038   }
3039 
3040   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
3041            pFile->hFile.h,
3042            rc==SQLITE_OK ? "ok" : "failed",
3043            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
3044            pFile->lastErrno));
3045 
3046   return rc;
3047 }
3048 
3049 /* Forward references to VFS methods */
3050 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
3051 static int winDelete(sqlite3_vfs *,const char*,int);
3052 
3053 /*
3054 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
3055 **
3056 ** This is not a VFS shared-memory method; it is a utility function called
3057 ** by VFS shared-memory methods.
3058 */
3059 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
3060   winShmNode **pp;
3061   winShmNode *p;
3062   BOOL bRc;
3063   assert( winShmMutexHeld() );
3064   pp = &winShmNodeList;
3065   while( (p = *pp)!=0 ){
3066     if( p->nRef==0 ){
3067       int i;
3068       if( p->mutex ) sqlite3_mutex_free(p->mutex);
3069       for(i=0; i<p->nRegion; i++){
3070         bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
3071         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
3072                  (int)osGetCurrentProcessId(), i,
3073                  bRc ? "ok" : "failed"));
3074         bRc = osCloseHandle(p->aRegion[i].hMap);
3075         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
3076                  (int)osGetCurrentProcessId(), i,
3077                  bRc ? "ok" : "failed"));
3078       }
3079       if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
3080         SimulateIOErrorBenign(1);
3081         winClose((sqlite3_file *)&p->hFile);
3082         SimulateIOErrorBenign(0);
3083       }
3084       if( deleteFlag ){
3085         SimulateIOErrorBenign(1);
3086         sqlite3BeginBenignMalloc();
3087         winDelete(pVfs, p->zFilename, 0);
3088         sqlite3EndBenignMalloc();
3089         SimulateIOErrorBenign(0);
3090       }
3091       *pp = p->pNext;
3092       sqlite3_free(p->aRegion);
3093       sqlite3_free(p);
3094     }else{
3095       pp = &p->pNext;
3096     }
3097   }
3098 }
3099 
3100 /*
3101 ** Open the shared-memory area associated with database file pDbFd.
3102 **
3103 ** When opening a new shared-memory file, if no other instances of that
3104 ** file are currently open, in this process or in other processes, then
3105 ** the file must be truncated to zero length or have its header cleared.
3106 */
3107 static int winOpenSharedMemory(winFile *pDbFd){
3108   struct winShm *p;                  /* The connection to be opened */
3109   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
3110   int rc;                            /* Result code */
3111   struct winShmNode *pNew;           /* Newly allocated winShmNode */
3112   int nName;                         /* Size of zName in bytes */
3113 
3114   assert( pDbFd->pShm==0 );    /* Not previously opened */
3115 
3116   /* Allocate space for the new sqlite3_shm object.  Also speculatively
3117   ** allocate space for a new winShmNode and filename.
3118   */
3119   p = sqlite3MallocZero( sizeof(*p) );
3120   if( p==0 ) return SQLITE_IOERR_NOMEM;
3121   nName = sqlite3Strlen30(pDbFd->zPath);
3122   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
3123   if( pNew==0 ){
3124     sqlite3_free(p);
3125     return SQLITE_IOERR_NOMEM;
3126   }
3127   pNew->zFilename = (char*)&pNew[1];
3128   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
3129   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
3130 
3131   /* Look to see if there is an existing winShmNode that can be used.
3132   ** If no matching winShmNode currently exists, create a new one.
3133   */
3134   winShmEnterMutex();
3135   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
3136     /* TBD need to come up with better match here.  Perhaps
3137     ** use FILE_ID_BOTH_DIR_INFO Structure.
3138     */
3139     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
3140   }
3141   if( pShmNode ){
3142     sqlite3_free(pNew);
3143   }else{
3144     pShmNode = pNew;
3145     pNew = 0;
3146     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
3147     pShmNode->pNext = winShmNodeList;
3148     winShmNodeList = pShmNode;
3149 
3150     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3151     if( pShmNode->mutex==0 ){
3152       rc = SQLITE_IOERR_NOMEM;
3153       goto shm_open_err;
3154     }
3155 
3156     rc = winOpen(pDbFd->pVfs,
3157                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
3158                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
3159                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
3160                  0);
3161     if( SQLITE_OK!=rc ){
3162       goto shm_open_err;
3163     }
3164 
3165     /* Check to see if another process is holding the dead-man switch.
3166     ** If not, truncate the file to zero length.
3167     */
3168     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
3169       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
3170       if( rc!=SQLITE_OK ){
3171         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
3172                  "winOpenShm", pDbFd->zPath);
3173       }
3174     }
3175     if( rc==SQLITE_OK ){
3176       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
3177       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
3178     }
3179     if( rc ) goto shm_open_err;
3180   }
3181 
3182   /* Make the new connection a child of the winShmNode */
3183   p->pShmNode = pShmNode;
3184 #ifdef SQLITE_DEBUG
3185   p->id = pShmNode->nextShmId++;
3186 #endif
3187   pShmNode->nRef++;
3188   pDbFd->pShm = p;
3189   winShmLeaveMutex();
3190 
3191   /* The reference count on pShmNode has already been incremented under
3192   ** the cover of the winShmEnterMutex() mutex and the pointer from the
3193   ** new (struct winShm) object to the pShmNode has been set. All that is
3194   ** left to do is to link the new object into the linked list starting
3195   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3196   ** mutex.
3197   */
3198   sqlite3_mutex_enter(pShmNode->mutex);
3199   p->pNext = pShmNode->pFirst;
3200   pShmNode->pFirst = p;
3201   sqlite3_mutex_leave(pShmNode->mutex);
3202   return SQLITE_OK;
3203 
3204   /* Jump here on any error */
3205 shm_open_err:
3206   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
3207   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
3208   sqlite3_free(p);
3209   sqlite3_free(pNew);
3210   winShmLeaveMutex();
3211   return rc;
3212 }
3213 
3214 /*
3215 ** Close a connection to shared-memory.  Delete the underlying
3216 ** storage if deleteFlag is true.
3217 */
3218 static int winShmUnmap(
3219   sqlite3_file *fd,          /* Database holding shared memory */
3220   int deleteFlag             /* Delete after closing if true */
3221 ){
3222   winFile *pDbFd;       /* Database holding shared-memory */
3223   winShm *p;            /* The connection to be closed */
3224   winShmNode *pShmNode; /* The underlying shared-memory file */
3225   winShm **pp;          /* For looping over sibling connections */
3226 
3227   pDbFd = (winFile*)fd;
3228   p = pDbFd->pShm;
3229   if( p==0 ) return SQLITE_OK;
3230   pShmNode = p->pShmNode;
3231 
3232   /* Remove connection p from the set of connections associated
3233   ** with pShmNode */
3234   sqlite3_mutex_enter(pShmNode->mutex);
3235   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3236   *pp = p->pNext;
3237 
3238   /* Free the connection p */
3239   sqlite3_free(p);
3240   pDbFd->pShm = 0;
3241   sqlite3_mutex_leave(pShmNode->mutex);
3242 
3243   /* If pShmNode->nRef has reached 0, then close the underlying
3244   ** shared-memory file, too */
3245   winShmEnterMutex();
3246   assert( pShmNode->nRef>0 );
3247   pShmNode->nRef--;
3248   if( pShmNode->nRef==0 ){
3249     winShmPurge(pDbFd->pVfs, deleteFlag);
3250   }
3251   winShmLeaveMutex();
3252 
3253   return SQLITE_OK;
3254 }
3255 
3256 /*
3257 ** Change the lock state for a shared-memory segment.
3258 */
3259 static int winShmLock(
3260   sqlite3_file *fd,          /* Database file holding the shared memory */
3261   int ofst,                  /* First lock to acquire or release */
3262   int n,                     /* Number of locks to acquire or release */
3263   int flags                  /* What to do with the lock */
3264 ){
3265   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
3266   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
3267   winShm *pX;                           /* For looping over all siblings */
3268   winShmNode *pShmNode = p->pShmNode;
3269   int rc = SQLITE_OK;                   /* Result code */
3270   u16 mask;                             /* Mask of locks to take or release */
3271 
3272   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
3273   assert( n>=1 );
3274   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3275        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3276        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3277        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3278   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
3279 
3280   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
3281   assert( n>1 || mask==(1<<ofst) );
3282   sqlite3_mutex_enter(pShmNode->mutex);
3283   if( flags & SQLITE_SHM_UNLOCK ){
3284     u16 allMask = 0; /* Mask of locks held by siblings */
3285 
3286     /* See if any siblings hold this same lock */
3287     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3288       if( pX==p ) continue;
3289       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3290       allMask |= pX->sharedMask;
3291     }
3292 
3293     /* Unlock the system-level locks */
3294     if( (mask & allMask)==0 ){
3295       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
3296     }else{
3297       rc = SQLITE_OK;
3298     }
3299 
3300     /* Undo the local locks */
3301     if( rc==SQLITE_OK ){
3302       p->exclMask &= ~mask;
3303       p->sharedMask &= ~mask;
3304     }
3305   }else if( flags & SQLITE_SHM_SHARED ){
3306     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
3307 
3308     /* Find out which shared locks are already held by sibling connections.
3309     ** If any sibling already holds an exclusive lock, go ahead and return
3310     ** SQLITE_BUSY.
3311     */
3312     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3313       if( (pX->exclMask & mask)!=0 ){
3314         rc = SQLITE_BUSY;
3315         break;
3316       }
3317       allShared |= pX->sharedMask;
3318     }
3319 
3320     /* Get shared locks at the system level, if necessary */
3321     if( rc==SQLITE_OK ){
3322       if( (allShared & mask)==0 ){
3323         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
3324       }else{
3325         rc = SQLITE_OK;
3326       }
3327     }
3328 
3329     /* Get the local shared locks */
3330     if( rc==SQLITE_OK ){
3331       p->sharedMask |= mask;
3332     }
3333   }else{
3334     /* Make sure no sibling connections hold locks that will block this
3335     ** lock.  If any do, return SQLITE_BUSY right away.
3336     */
3337     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3338       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3339         rc = SQLITE_BUSY;
3340         break;
3341       }
3342     }
3343 
3344     /* Get the exclusive locks at the system level.  Then if successful
3345     ** also mark the local connection as being locked.
3346     */
3347     if( rc==SQLITE_OK ){
3348       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
3349       if( rc==SQLITE_OK ){
3350         assert( (p->sharedMask & mask)==0 );
3351         p->exclMask |= mask;
3352       }
3353     }
3354   }
3355   sqlite3_mutex_leave(pShmNode->mutex);
3356   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
3357            p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
3358            rc ? "failed" : "ok"));
3359   return rc;
3360 }
3361 
3362 /*
3363 ** Implement a memory barrier or memory fence on shared memory.
3364 **
3365 ** All loads and stores begun before the barrier must complete before
3366 ** any load or store begun after the barrier.
3367 */
3368 static void winShmBarrier(
3369   sqlite3_file *fd          /* Database holding the shared memory */
3370 ){
3371   UNUSED_PARAMETER(fd);
3372   /* MemoryBarrier(); // does not work -- do not know why not */
3373   winShmEnterMutex();
3374   winShmLeaveMutex();
3375 }
3376 
3377 /*
3378 ** This function is called to obtain a pointer to region iRegion of the
3379 ** shared-memory associated with the database file fd. Shared-memory regions
3380 ** are numbered starting from zero. Each shared-memory region is szRegion
3381 ** bytes in size.
3382 **
3383 ** If an error occurs, an error code is returned and *pp is set to NULL.
3384 **
3385 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
3386 ** region has not been allocated (by any client, including one running in a
3387 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3388 ** isWrite is non-zero and the requested shared-memory region has not yet
3389 ** been allocated, it is allocated by this function.
3390 **
3391 ** If the shared-memory region has already been allocated or is allocated by
3392 ** this call as described above, then it is mapped into this processes
3393 ** address space (if it is not already), *pp is set to point to the mapped
3394 ** memory and SQLITE_OK returned.
3395 */
3396 static int winShmMap(
3397   sqlite3_file *fd,               /* Handle open on database file */
3398   int iRegion,                    /* Region to retrieve */
3399   int szRegion,                   /* Size of regions */
3400   int isWrite,                    /* True to extend file if necessary */
3401   void volatile **pp              /* OUT: Mapped memory */
3402 ){
3403   winFile *pDbFd = (winFile*)fd;
3404   winShm *p = pDbFd->pShm;
3405   winShmNode *pShmNode;
3406   int rc = SQLITE_OK;
3407 
3408   if( !p ){
3409     rc = winOpenSharedMemory(pDbFd);
3410     if( rc!=SQLITE_OK ) return rc;
3411     p = pDbFd->pShm;
3412   }
3413   pShmNode = p->pShmNode;
3414 
3415   sqlite3_mutex_enter(pShmNode->mutex);
3416   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
3417 
3418   if( pShmNode->nRegion<=iRegion ){
3419     struct ShmRegion *apNew;           /* New aRegion[] array */
3420     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
3421     sqlite3_int64 sz;                  /* Current size of wal-index file */
3422 
3423     pShmNode->szRegion = szRegion;
3424 
3425     /* The requested region is not mapped into this processes address space.
3426     ** Check to see if it has been allocated (i.e. if the wal-index file is
3427     ** large enough to contain the requested region).
3428     */
3429     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
3430     if( rc!=SQLITE_OK ){
3431       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
3432                "winShmMap1", pDbFd->zPath);
3433       goto shmpage_out;
3434     }
3435 
3436     if( sz<nByte ){
3437       /* The requested memory region does not exist. If isWrite is set to
3438       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
3439       **
3440       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
3441       ** the requested memory region.
3442       */
3443       if( !isWrite ) goto shmpage_out;
3444       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
3445       if( rc!=SQLITE_OK ){
3446         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
3447                  "winShmMap2", pDbFd->zPath);
3448         goto shmpage_out;
3449       }
3450     }
3451 
3452     /* Map the requested memory region into this processes address space. */
3453     apNew = (struct ShmRegion *)sqlite3_realloc(
3454         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
3455     );
3456     if( !apNew ){
3457       rc = SQLITE_IOERR_NOMEM;
3458       goto shmpage_out;
3459     }
3460     pShmNode->aRegion = apNew;
3461 
3462     while( pShmNode->nRegion<=iRegion ){
3463       HANDLE hMap = NULL;         /* file-mapping handle */
3464       void *pMap = 0;             /* Mapped memory region */
3465 
3466 #if SQLITE_OS_WINRT
3467       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
3468           NULL, PAGE_READWRITE, nByte, NULL
3469       );
3470 #elif defined(SQLITE_WIN32_HAS_WIDE)
3471       hMap = osCreateFileMappingW(pShmNode->hFile.h,
3472           NULL, PAGE_READWRITE, 0, nByte, NULL
3473       );
3474 #elif defined(SQLITE_WIN32_HAS_ANSI)
3475       hMap = osCreateFileMappingA(pShmNode->hFile.h,
3476           NULL, PAGE_READWRITE, 0, nByte, NULL
3477       );
3478 #endif
3479       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
3480                (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
3481                hMap ? "ok" : "failed"));
3482       if( hMap ){
3483         int iOffset = pShmNode->nRegion*szRegion;
3484         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
3485 #if SQLITE_OS_WINRT
3486         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
3487             iOffset - iOffsetShift, szRegion + iOffsetShift
3488         );
3489 #else
3490         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
3491             0, iOffset - iOffsetShift, szRegion + iOffsetShift
3492         );
3493 #endif
3494         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
3495                  (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
3496                  szRegion, pMap ? "ok" : "failed"));
3497       }
3498       if( !pMap ){
3499         pShmNode->lastErrno = osGetLastError();
3500         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
3501                  "winShmMap3", pDbFd->zPath);
3502         if( hMap ) osCloseHandle(hMap);
3503         goto shmpage_out;
3504       }
3505 
3506       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
3507       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
3508       pShmNode->nRegion++;
3509     }
3510   }
3511 
3512 shmpage_out:
3513   if( pShmNode->nRegion>iRegion ){
3514     int iOffset = iRegion*szRegion;
3515     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
3516     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
3517     *pp = (void *)&p[iOffsetShift];
3518   }else{
3519     *pp = 0;
3520   }
3521   sqlite3_mutex_leave(pShmNode->mutex);
3522   return rc;
3523 }
3524 
3525 #else
3526 # define winShmMap     0
3527 # define winShmLock    0
3528 # define winShmBarrier 0
3529 # define winShmUnmap   0
3530 #endif /* #ifndef SQLITE_OMIT_WAL */
3531 
3532 /*
3533 ** Cleans up the mapped region of the specified file, if any.
3534 */
3535 #if SQLITE_MAX_MMAP_SIZE>0
3536 static int winUnmapfile(winFile *pFile){
3537   assert( pFile!=0 );
3538   if( pFile->pMapRegion ){
3539     if( !osUnmapViewOfFile(pFile->pMapRegion) ){
3540       pFile->lastErrno = osGetLastError();
3541       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
3542                          "winUnmap1", pFile->zPath);
3543     }
3544     pFile->pMapRegion = 0;
3545     pFile->mmapSize = 0;
3546     pFile->mmapSizeActual = 0;
3547   }
3548   if( pFile->hMap!=NULL ){
3549     if( !osCloseHandle(pFile->hMap) ){
3550       pFile->lastErrno = osGetLastError();
3551       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
3552                          "winUnmap2", pFile->zPath);
3553     }
3554     pFile->hMap = NULL;
3555   }
3556   return SQLITE_OK;
3557 }
3558 
3559 /*
3560 ** Memory map or remap the file opened by file-descriptor pFd (if the file
3561 ** is already mapped, the existing mapping is replaced by the new). Or, if
3562 ** there already exists a mapping for this file, and there are still
3563 ** outstanding xFetch() references to it, this function is a no-op.
3564 **
3565 ** If parameter nByte is non-negative, then it is the requested size of
3566 ** the mapping to create. Otherwise, if nByte is less than zero, then the
3567 ** requested size is the size of the file on disk. The actual size of the
3568 ** created mapping is either the requested size or the value configured
3569 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
3570 **
3571 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
3572 ** recreated as a result of outstanding references) or an SQLite error
3573 ** code otherwise.
3574 */
3575 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
3576   sqlite3_int64 nMap = nByte;
3577   int rc;
3578 
3579   assert( nMap>=0 || pFd->nFetchOut==0 );
3580   if( pFd->nFetchOut>0 ) return SQLITE_OK;
3581 
3582   if( nMap<0 ){
3583     rc = winFileSize((sqlite3_file*)pFd, &nMap);
3584     if( rc ){
3585       return SQLITE_IOERR_FSTAT;
3586     }
3587   }
3588   if( nMap>pFd->mmapSizeMax ){
3589     nMap = pFd->mmapSizeMax;
3590   }
3591   nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
3592 
3593   if( nMap==0 && pFd->mmapSize>0 ){
3594     winUnmapfile(pFd);
3595   }
3596   if( nMap!=pFd->mmapSize ){
3597     void *pNew = 0;
3598     DWORD protect = PAGE_READONLY;
3599     DWORD flags = FILE_MAP_READ;
3600 
3601     winUnmapfile(pFd);
3602     if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
3603       protect = PAGE_READWRITE;
3604       flags |= FILE_MAP_WRITE;
3605     }
3606 #if SQLITE_OS_WINRT
3607     pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
3608 #elif defined(SQLITE_WIN32_HAS_WIDE)
3609     pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
3610                                 (DWORD)((nMap>>32) & 0xffffffff),
3611                                 (DWORD)(nMap & 0xffffffff), NULL);
3612 #elif defined(SQLITE_WIN32_HAS_ANSI)
3613     pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
3614                                 (DWORD)((nMap>>32) & 0xffffffff),
3615                                 (DWORD)(nMap & 0xffffffff), NULL);
3616 #endif
3617     if( pFd->hMap==NULL ){
3618       pFd->lastErrno = osGetLastError();
3619       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
3620                        "winMapfile", pFd->zPath);
3621       /* Log the error, but continue normal operation using xRead/xWrite */
3622       return SQLITE_OK;
3623     }
3624     assert( (nMap % winSysInfo.dwPageSize)==0 );
3625 #if SQLITE_OS_WINRT
3626     pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, nMap);
3627 #else
3628     assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
3629     pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
3630 #endif
3631     if( pNew==NULL ){
3632       osCloseHandle(pFd->hMap);
3633       pFd->hMap = NULL;
3634       pFd->lastErrno = osGetLastError();
3635       winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
3636                   "winMapfile", pFd->zPath);
3637       return SQLITE_OK;
3638     }
3639     pFd->pMapRegion = pNew;
3640     pFd->mmapSize = nMap;
3641     pFd->mmapSizeActual = nMap;
3642   }
3643 
3644   return SQLITE_OK;
3645 }
3646 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
3647 
3648 /*
3649 ** If possible, return a pointer to a mapping of file fd starting at offset
3650 ** iOff. The mapping must be valid for at least nAmt bytes.
3651 **
3652 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
3653 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
3654 ** Finally, if an error does occur, return an SQLite error code. The final
3655 ** value of *pp is undefined in this case.
3656 **
3657 ** If this function does return a pointer, the caller must eventually
3658 ** release the reference by calling unixUnfetch().
3659 */
3660 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
3661 #if SQLITE_MAX_MMAP_SIZE>0
3662   winFile *pFd = (winFile*)fd;   /* The underlying database file */
3663 #endif
3664   *pp = 0;
3665 
3666 #if SQLITE_MAX_MMAP_SIZE>0
3667   if( pFd->mmapSizeMax>0 ){
3668     if( pFd->pMapRegion==0 ){
3669       int rc = winMapfile(pFd, -1);
3670       if( rc!=SQLITE_OK ) return rc;
3671     }
3672     if( pFd->mmapSize >= iOff+nAmt ){
3673       *pp = &((u8 *)pFd->pMapRegion)[iOff];
3674       pFd->nFetchOut++;
3675     }
3676   }
3677 #endif
3678   return SQLITE_OK;
3679 }
3680 
3681 /*
3682 ** If the third argument is non-NULL, then this function releases a
3683 ** reference obtained by an earlier call to unixFetch(). The second
3684 ** argument passed to this function must be the same as the corresponding
3685 ** argument that was passed to the unixFetch() invocation.
3686 **
3687 ** Or, if the third argument is NULL, then this function is being called
3688 ** to inform the VFS layer that, according to POSIX, any existing mapping
3689 ** may now be invalid and should be unmapped.
3690 */
3691 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
3692 #if SQLITE_MAX_MMAP_SIZE>0
3693   winFile *pFd = (winFile*)fd;   /* The underlying database file */
3694 
3695   /* If p==0 (unmap the entire file) then there must be no outstanding
3696   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
3697   ** then there must be at least one outstanding.  */
3698   assert( (p==0)==(pFd->nFetchOut==0) );
3699 
3700   /* If p!=0, it must match the iOff value. */
3701   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
3702 
3703   if( p ){
3704     pFd->nFetchOut--;
3705   }else{
3706     /* FIXME:  If Windows truly always prevents truncating or deleting a
3707     ** file while a mapping is held, then the following winUnmapfile() call
3708     ** is unnecessary can can be omitted - potentially improving
3709     ** performance.  */
3710     winUnmapfile(pFd);
3711   }
3712 
3713   assert( pFd->nFetchOut>=0 );
3714 #endif
3715   return SQLITE_OK;
3716 }
3717 
3718 /*
3719 ** Here ends the implementation of all sqlite3_file methods.
3720 **
3721 ********************** End sqlite3_file Methods *******************************
3722 ******************************************************************************/
3723 
3724 /*
3725 ** This vector defines all the methods that can operate on an
3726 ** sqlite3_file for win32.
3727 */
3728 static const sqlite3_io_methods winIoMethod = {
3729   3,                              /* iVersion */
3730   winClose,                       /* xClose */
3731   winRead,                        /* xRead */
3732   winWrite,                       /* xWrite */
3733   winTruncate,                    /* xTruncate */
3734   winSync,                        /* xSync */
3735   winFileSize,                    /* xFileSize */
3736   winLock,                        /* xLock */
3737   winUnlock,                      /* xUnlock */
3738   winCheckReservedLock,           /* xCheckReservedLock */
3739   winFileControl,                 /* xFileControl */
3740   winSectorSize,                  /* xSectorSize */
3741   winDeviceCharacteristics,       /* xDeviceCharacteristics */
3742   winShmMap,                      /* xShmMap */
3743   winShmLock,                     /* xShmLock */
3744   winShmBarrier,                  /* xShmBarrier */
3745   winShmUnmap,                    /* xShmUnmap */
3746   winFetch,                       /* xFetch */
3747   winUnfetch                      /* xUnfetch */
3748 };
3749 
3750 /****************************************************************************
3751 **************************** sqlite3_vfs methods ****************************
3752 **
3753 ** This division contains the implementation of methods on the
3754 ** sqlite3_vfs object.
3755 */
3756 
3757 /*
3758 ** Convert a UTF-8 filename into whatever form the underlying
3759 ** operating system wants filenames in.  Space to hold the result
3760 ** is obtained from malloc and must be freed by the calling
3761 ** function.
3762 */
3763 static void *convertUtf8Filename(const char *zFilename){
3764   void *zConverted = 0;
3765   if( isNT() ){
3766     zConverted = utf8ToUnicode(zFilename);
3767   }
3768 #ifdef SQLITE_WIN32_HAS_ANSI
3769   else{
3770     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
3771   }
3772 #endif
3773   /* caller will handle out of memory */
3774   return zConverted;
3775 }
3776 
3777 /*
3778 ** Create a temporary file name in zBuf.  zBuf must be big enough to
3779 ** hold at pVfs->mxPathname characters.
3780 */
3781 static int getTempname(int nBuf, char *zBuf){
3782   static char zChars[] =
3783     "abcdefghijklmnopqrstuvwxyz"
3784     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3785     "0123456789";
3786   size_t i, j;
3787   int nTempPath;
3788   char zTempPath[MAX_PATH+2];
3789 
3790   /* It's odd to simulate an io-error here, but really this is just
3791   ** using the io-error infrastructure to test that SQLite handles this
3792   ** function failing.
3793   */
3794   SimulateIOError( return SQLITE_IOERR );
3795 
3796   memset(zTempPath, 0, MAX_PATH+2);
3797 
3798   if( sqlite3_temp_directory ){
3799     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
3800   }
3801 #if !SQLITE_OS_WINRT
3802   else if( isNT() ){
3803     char *zMulti;
3804     WCHAR zWidePath[MAX_PATH];
3805     osGetTempPathW(MAX_PATH-30, zWidePath);
3806     zMulti = unicodeToUtf8(zWidePath);
3807     if( zMulti ){
3808       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
3809       sqlite3_free(zMulti);
3810     }else{
3811       return SQLITE_IOERR_NOMEM;
3812     }
3813   }
3814 #ifdef SQLITE_WIN32_HAS_ANSI
3815   else{
3816     char *zUtf8;
3817     char zMbcsPath[MAX_PATH];
3818     osGetTempPathA(MAX_PATH-30, zMbcsPath);
3819     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
3820     if( zUtf8 ){
3821       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
3822       sqlite3_free(zUtf8);
3823     }else{
3824       return SQLITE_IOERR_NOMEM;
3825     }
3826   }
3827 #endif
3828 #endif
3829 
3830   /* Check that the output buffer is large enough for the temporary file
3831   ** name. If it is not, return SQLITE_ERROR.
3832   */
3833   nTempPath = sqlite3Strlen30(zTempPath);
3834 
3835   if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
3836     return SQLITE_ERROR;
3837   }
3838 
3839   for(i=nTempPath; i>0 && zTempPath[i-1]=='\\'; i--){}
3840   zTempPath[i] = 0;
3841 
3842   sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?
3843                        "%s\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,
3844                    zTempPath);
3845   j = sqlite3Strlen30(zBuf);
3846   sqlite3_randomness(15, &zBuf[j]);
3847   for(i=0; i<15; i++, j++){
3848     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
3849   }
3850   zBuf[j] = 0;
3851   zBuf[j+1] = 0;
3852 
3853   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
3854   return SQLITE_OK;
3855 }
3856 
3857 /*
3858 ** Return TRUE if the named file is really a directory.  Return false if
3859 ** it is something other than a directory, or if there is any kind of memory
3860 ** allocation failure.
3861 */
3862 static int winIsDir(const void *zConverted){
3863   DWORD attr;
3864   int rc = 0;
3865   DWORD lastErrno;
3866 
3867   if( isNT() ){
3868     int cnt = 0;
3869     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
3870     memset(&sAttrData, 0, sizeof(sAttrData));
3871     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
3872                              GetFileExInfoStandard,
3873                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
3874     if( !rc ){
3875       return 0; /* Invalid name? */
3876     }
3877     attr = sAttrData.dwFileAttributes;
3878 #if SQLITE_OS_WINCE==0
3879   }else{
3880     attr = osGetFileAttributesA((char*)zConverted);
3881 #endif
3882   }
3883   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
3884 }
3885 
3886 /*
3887 ** Open a file.
3888 */
3889 static int winOpen(
3890   sqlite3_vfs *pVfs,        /* Not used */
3891   const char *zName,        /* Name of the file (UTF-8) */
3892   sqlite3_file *id,         /* Write the SQLite file handle here */
3893   int flags,                /* Open mode flags */
3894   int *pOutFlags            /* Status return flags */
3895 ){
3896   HANDLE h;
3897   DWORD lastErrno;
3898   DWORD dwDesiredAccess;
3899   DWORD dwShareMode;
3900   DWORD dwCreationDisposition;
3901   DWORD dwFlagsAndAttributes = 0;
3902 #if SQLITE_OS_WINCE
3903   int isTemp = 0;
3904 #endif
3905   winFile *pFile = (winFile*)id;
3906   void *zConverted;              /* Filename in OS encoding */
3907   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
3908   int cnt = 0;
3909 
3910   /* If argument zPath is a NULL pointer, this function is required to open
3911   ** a temporary file. Use this buffer to store the file name in.
3912   */
3913   char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
3914 
3915   int rc = SQLITE_OK;            /* Function Return Code */
3916 #if !defined(NDEBUG) || SQLITE_OS_WINCE
3917   int eType = flags&0xFFFFFF00;  /* Type of file to open */
3918 #endif
3919 
3920   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
3921   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
3922   int isCreate     = (flags & SQLITE_OPEN_CREATE);
3923   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
3924   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
3925 
3926 #ifndef NDEBUG
3927   int isOpenJournal = (isCreate && (
3928         eType==SQLITE_OPEN_MASTER_JOURNAL
3929      || eType==SQLITE_OPEN_MAIN_JOURNAL
3930      || eType==SQLITE_OPEN_WAL
3931   ));
3932 #endif
3933 
3934   /* Check the following statements are true:
3935   **
3936   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
3937   **   (b) if CREATE is set, then READWRITE must also be set, and
3938   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
3939   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
3940   */
3941   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
3942   assert(isCreate==0 || isReadWrite);
3943   assert(isExclusive==0 || isCreate);
3944   assert(isDelete==0 || isCreate);
3945 
3946   /* The main DB, main journal, WAL file and master journal are never
3947   ** automatically deleted. Nor are they ever temporary files.  */
3948   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
3949   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
3950   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
3951   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
3952 
3953   /* Assert that the upper layer has set one of the "file-type" flags. */
3954   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
3955        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3956        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
3957        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
3958   );
3959 
3960   assert( pFile!=0 );
3961   memset(pFile, 0, sizeof(winFile));
3962   pFile->h = INVALID_HANDLE_VALUE;
3963 
3964 #if SQLITE_OS_WINRT
3965   if( !sqlite3_temp_directory ){
3966     sqlite3_log(SQLITE_ERROR,
3967         "sqlite3_temp_directory variable should be set for WinRT");
3968   }
3969 #endif
3970 
3971   /* If the second argument to this function is NULL, generate a
3972   ** temporary file name to use
3973   */
3974   if( !zUtf8Name ){
3975     assert(isDelete && !isOpenJournal);
3976     memset(zTmpname, 0, MAX_PATH+2);
3977     rc = getTempname(MAX_PATH+2, zTmpname);
3978     if( rc!=SQLITE_OK ){
3979       return rc;
3980     }
3981     zUtf8Name = zTmpname;
3982   }
3983 
3984   /* Database filenames are double-zero terminated if they are not
3985   ** URIs with parameters.  Hence, they can always be passed into
3986   ** sqlite3_uri_parameter().
3987   */
3988   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
3989         zUtf8Name[strlen(zUtf8Name)+1]==0 );
3990 
3991   /* Convert the filename to the system encoding. */
3992   zConverted = convertUtf8Filename(zUtf8Name);
3993   if( zConverted==0 ){
3994     return SQLITE_IOERR_NOMEM;
3995   }
3996 
3997   if( winIsDir(zConverted) ){
3998     sqlite3_free(zConverted);
3999     return SQLITE_CANTOPEN_ISDIR;
4000   }
4001 
4002   if( isReadWrite ){
4003     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
4004   }else{
4005     dwDesiredAccess = GENERIC_READ;
4006   }
4007 
4008   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
4009   ** created. SQLite doesn't use it to indicate "exclusive access"
4010   ** as it is usually understood.
4011   */
4012   if( isExclusive ){
4013     /* Creates a new file, only if it does not already exist. */
4014     /* If the file exists, it fails. */
4015     dwCreationDisposition = CREATE_NEW;
4016   }else if( isCreate ){
4017     /* Open existing file, or create if it doesn't exist */
4018     dwCreationDisposition = OPEN_ALWAYS;
4019   }else{
4020     /* Opens a file, only if it exists. */
4021     dwCreationDisposition = OPEN_EXISTING;
4022   }
4023 
4024   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
4025 
4026   if( isDelete ){
4027 #if SQLITE_OS_WINCE
4028     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
4029     isTemp = 1;
4030 #else
4031     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
4032                                | FILE_ATTRIBUTE_HIDDEN
4033                                | FILE_FLAG_DELETE_ON_CLOSE;
4034 #endif
4035   }else{
4036     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
4037   }
4038   /* Reports from the internet are that performance is always
4039   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
4040 #if SQLITE_OS_WINCE
4041   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
4042 #endif
4043 
4044   if( isNT() ){
4045 #if SQLITE_OS_WINRT
4046     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
4047     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
4048     extendedParameters.dwFileAttributes =
4049             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
4050     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
4051     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
4052     extendedParameters.lpSecurityAttributes = NULL;
4053     extendedParameters.hTemplateFile = NULL;
4054     while( (h = osCreateFile2((LPCWSTR)zConverted,
4055                               dwDesiredAccess,
4056                               dwShareMode,
4057                               dwCreationDisposition,
4058                               &extendedParameters))==INVALID_HANDLE_VALUE &&
4059                               retryIoerr(&cnt, &lastErrno) ){
4060                /* Noop */
4061     }
4062 #else
4063     while( (h = osCreateFileW((LPCWSTR)zConverted,
4064                               dwDesiredAccess,
4065                               dwShareMode, NULL,
4066                               dwCreationDisposition,
4067                               dwFlagsAndAttributes,
4068                               NULL))==INVALID_HANDLE_VALUE &&
4069                               retryIoerr(&cnt, &lastErrno) ){
4070                /* Noop */
4071     }
4072 #endif
4073   }
4074 #ifdef SQLITE_WIN32_HAS_ANSI
4075   else{
4076     while( (h = osCreateFileA((LPCSTR)zConverted,
4077                               dwDesiredAccess,
4078                               dwShareMode, NULL,
4079                               dwCreationDisposition,
4080                               dwFlagsAndAttributes,
4081                               NULL))==INVALID_HANDLE_VALUE &&
4082                               retryIoerr(&cnt, &lastErrno) ){
4083                /* Noop */
4084     }
4085   }
4086 #endif
4087   logIoerr(cnt);
4088 
4089   OSTRACE(("OPEN %d %s 0x%lx %s\n",
4090            h, zName, dwDesiredAccess,
4091            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
4092 
4093   if( h==INVALID_HANDLE_VALUE ){
4094     pFile->lastErrno = lastErrno;
4095     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
4096     sqlite3_free(zConverted);
4097     if( isReadWrite && !isExclusive ){
4098       return winOpen(pVfs, zName, id,
4099          ((flags|SQLITE_OPEN_READONLY) &
4100                      ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
4101          pOutFlags);
4102     }else{
4103       return SQLITE_CANTOPEN_BKPT;
4104     }
4105   }
4106 
4107   if( pOutFlags ){
4108     if( isReadWrite ){
4109       *pOutFlags = SQLITE_OPEN_READWRITE;
4110     }else{
4111       *pOutFlags = SQLITE_OPEN_READONLY;
4112     }
4113   }
4114 
4115 #if SQLITE_OS_WINCE
4116   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
4117        && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
4118   ){
4119     osCloseHandle(h);
4120     sqlite3_free(zConverted);
4121     return rc;
4122   }
4123   if( isTemp ){
4124     pFile->zDeleteOnClose = zConverted;
4125   }else
4126 #endif
4127   {
4128     sqlite3_free(zConverted);
4129   }
4130 
4131   pFile->pMethod = &winIoMethod;
4132   pFile->pVfs = pVfs;
4133   pFile->h = h;
4134   if( isReadonly ){
4135     pFile->ctrlFlags |= WINFILE_RDONLY;
4136   }
4137   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
4138     pFile->ctrlFlags |= WINFILE_PSOW;
4139   }
4140   pFile->lastErrno = NO_ERROR;
4141   pFile->zPath = zName;
4142 #if SQLITE_MAX_MMAP_SIZE>0
4143   pFile->hMap = NULL;
4144   pFile->pMapRegion = 0;
4145   pFile->mmapSize = 0;
4146   pFile->mmapSizeActual = 0;
4147   pFile->mmapSizeMax = sqlite3GlobalConfig.mxMmap;
4148 #endif
4149 
4150   OpenCounter(+1);
4151   return rc;
4152 }
4153 
4154 /*
4155 ** Delete the named file.
4156 **
4157 ** Note that Windows does not allow a file to be deleted if some other
4158 ** process has it open.  Sometimes a virus scanner or indexing program
4159 ** will open a journal file shortly after it is created in order to do
4160 ** whatever it does.  While this other process is holding the
4161 ** file open, we will be unable to delete it.  To work around this
4162 ** problem, we delay 100 milliseconds and try to delete again.  Up
4163 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
4164 ** up and returning an error.
4165 */
4166 static int winDelete(
4167   sqlite3_vfs *pVfs,          /* Not used on win32 */
4168   const char *zFilename,      /* Name of file to delete */
4169   int syncDir                 /* Not used on win32 */
4170 ){
4171   int cnt = 0;
4172   int rc;
4173   DWORD attr;
4174   DWORD lastErrno;
4175   void *zConverted;
4176   UNUSED_PARAMETER(pVfs);
4177   UNUSED_PARAMETER(syncDir);
4178 
4179   SimulateIOError(return SQLITE_IOERR_DELETE);
4180   zConverted = convertUtf8Filename(zFilename);
4181   if( zConverted==0 ){
4182     return SQLITE_IOERR_NOMEM;
4183   }
4184   if( isNT() ){
4185     do {
4186 #if SQLITE_OS_WINRT
4187       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
4188       memset(&sAttrData, 0, sizeof(sAttrData));
4189       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
4190                                   &sAttrData) ){
4191         attr = sAttrData.dwFileAttributes;
4192       }else{
4193         lastErrno = osGetLastError();
4194         if( lastErrno==ERROR_FILE_NOT_FOUND
4195          || lastErrno==ERROR_PATH_NOT_FOUND ){
4196           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
4197         }else{
4198           rc = SQLITE_ERROR;
4199         }
4200         break;
4201       }
4202 #else
4203       attr = osGetFileAttributesW(zConverted);
4204 #endif
4205       if ( attr==INVALID_FILE_ATTRIBUTES ){
4206         lastErrno = osGetLastError();
4207         if( lastErrno==ERROR_FILE_NOT_FOUND
4208          || lastErrno==ERROR_PATH_NOT_FOUND ){
4209           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
4210         }else{
4211           rc = SQLITE_ERROR;
4212         }
4213         break;
4214       }
4215       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
4216         rc = SQLITE_ERROR; /* Files only. */
4217         break;
4218       }
4219       if ( osDeleteFileW(zConverted) ){
4220         rc = SQLITE_OK; /* Deleted OK. */
4221         break;
4222       }
4223       if ( !retryIoerr(&cnt, &lastErrno) ){
4224         rc = SQLITE_ERROR; /* No more retries. */
4225         break;
4226       }
4227     } while(1);
4228   }
4229 #ifdef SQLITE_WIN32_HAS_ANSI
4230   else{
4231     do {
4232       attr = osGetFileAttributesA(zConverted);
4233       if ( attr==INVALID_FILE_ATTRIBUTES ){
4234         lastErrno = osGetLastError();
4235         if( lastErrno==ERROR_FILE_NOT_FOUND
4236          || lastErrno==ERROR_PATH_NOT_FOUND ){
4237           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
4238         }else{
4239           rc = SQLITE_ERROR;
4240         }
4241         break;
4242       }
4243       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
4244         rc = SQLITE_ERROR; /* Files only. */
4245         break;
4246       }
4247       if ( osDeleteFileA(zConverted) ){
4248         rc = SQLITE_OK; /* Deleted OK. */
4249         break;
4250       }
4251       if ( !retryIoerr(&cnt, &lastErrno) ){
4252         rc = SQLITE_ERROR; /* No more retries. */
4253         break;
4254       }
4255     } while(1);
4256   }
4257 #endif
4258   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
4259     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
4260              "winDelete", zFilename);
4261   }else{
4262     logIoerr(cnt);
4263   }
4264   sqlite3_free(zConverted);
4265   OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
4266   return rc;
4267 }
4268 
4269 /*
4270 ** Check the existence and status of a file.
4271 */
4272 static int winAccess(
4273   sqlite3_vfs *pVfs,         /* Not used on win32 */
4274   const char *zFilename,     /* Name of file to check */
4275   int flags,                 /* Type of test to make on this file */
4276   int *pResOut               /* OUT: Result */
4277 ){
4278   DWORD attr;
4279   int rc = 0;
4280   DWORD lastErrno;
4281   void *zConverted;
4282   UNUSED_PARAMETER(pVfs);
4283 
4284   SimulateIOError( return SQLITE_IOERR_ACCESS; );
4285   zConverted = convertUtf8Filename(zFilename);
4286   if( zConverted==0 ){
4287     return SQLITE_IOERR_NOMEM;
4288   }
4289   if( isNT() ){
4290     int cnt = 0;
4291     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
4292     memset(&sAttrData, 0, sizeof(sAttrData));
4293     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
4294                              GetFileExInfoStandard,
4295                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
4296     if( rc ){
4297       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
4298       ** as if it does not exist.
4299       */
4300       if(    flags==SQLITE_ACCESS_EXISTS
4301           && sAttrData.nFileSizeHigh==0
4302           && sAttrData.nFileSizeLow==0 ){
4303         attr = INVALID_FILE_ATTRIBUTES;
4304       }else{
4305         attr = sAttrData.dwFileAttributes;
4306       }
4307     }else{
4308       logIoerr(cnt);
4309       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
4310         winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
4311         sqlite3_free(zConverted);
4312         return SQLITE_IOERR_ACCESS;
4313       }else{
4314         attr = INVALID_FILE_ATTRIBUTES;
4315       }
4316     }
4317   }
4318 #ifdef SQLITE_WIN32_HAS_ANSI
4319   else{
4320     attr = osGetFileAttributesA((char*)zConverted);
4321   }
4322 #endif
4323   sqlite3_free(zConverted);
4324   switch( flags ){
4325     case SQLITE_ACCESS_READ:
4326     case SQLITE_ACCESS_EXISTS:
4327       rc = attr!=INVALID_FILE_ATTRIBUTES;
4328       break;
4329     case SQLITE_ACCESS_READWRITE:
4330       rc = attr!=INVALID_FILE_ATTRIBUTES &&
4331              (attr & FILE_ATTRIBUTE_READONLY)==0;
4332       break;
4333     default:
4334       assert(!"Invalid flags argument");
4335   }
4336   *pResOut = rc;
4337   return SQLITE_OK;
4338 }
4339 
4340 
4341 /*
4342 ** Returns non-zero if the specified path name should be used verbatim.  If
4343 ** non-zero is returned from this function, the calling function must simply
4344 ** use the provided path name verbatim -OR- resolve it into a full path name
4345 ** using the GetFullPathName Win32 API function (if available).
4346 */
4347 static BOOL winIsVerbatimPathname(
4348   const char *zPathname
4349 ){
4350   /*
4351   ** If the path name starts with a forward slash or a backslash, it is either
4352   ** a legal UNC name, a volume relative path, or an absolute path name in the
4353   ** "Unix" format on Windows.  There is no easy way to differentiate between
4354   ** the final two cases; therefore, we return the safer return value of TRUE
4355   ** so that callers of this function will simply use it verbatim.
4356   */
4357   if ( zPathname[0]=='/' || zPathname[0]=='\\' ){
4358     return TRUE;
4359   }
4360 
4361   /*
4362   ** If the path name starts with a letter and a colon it is either a volume
4363   ** relative path or an absolute path.  Callers of this function must not
4364   ** attempt to treat it as a relative path name (i.e. they should simply use
4365   ** it verbatim).
4366   */
4367   if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){
4368     return TRUE;
4369   }
4370 
4371   /*
4372   ** If we get to this point, the path name should almost certainly be a purely
4373   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
4374   */
4375   return FALSE;
4376 }
4377 
4378 /*
4379 ** Turn a relative pathname into a full pathname.  Write the full
4380 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
4381 ** bytes in size.
4382 */
4383 static int winFullPathname(
4384   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
4385   const char *zRelative,        /* Possibly relative input path */
4386   int nFull,                    /* Size of output buffer in bytes */
4387   char *zFull                   /* Output buffer */
4388 ){
4389 
4390 #if defined(__CYGWIN__)
4391   SimulateIOError( return SQLITE_ERROR );
4392   UNUSED_PARAMETER(nFull);
4393   assert( pVfs->mxPathname>=MAX_PATH );
4394   assert( nFull>=pVfs->mxPathname );
4395   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
4396     /*
4397     ** NOTE: We are dealing with a relative path name and the data
4398     **       directory has been set.  Therefore, use it as the basis
4399     **       for converting the relative path name to an absolute
4400     **       one by prepending the data directory and a slash.
4401     */
4402     char zOut[MAX_PATH+1];
4403     memset(zOut, 0, MAX_PATH+1);
4404     cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
4405                      MAX_PATH+1);
4406     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
4407                      sqlite3_data_directory, zOut);
4408   }else{
4409     cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull);
4410   }
4411   return SQLITE_OK;
4412 #endif
4413 
4414 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
4415   SimulateIOError( return SQLITE_ERROR );
4416   /* WinCE has no concept of a relative pathname, or so I am told. */
4417   /* WinRT has no way to convert a relative path to an absolute one. */
4418   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
4419     /*
4420     ** NOTE: We are dealing with a relative path name and the data
4421     **       directory has been set.  Therefore, use it as the basis
4422     **       for converting the relative path name to an absolute
4423     **       one by prepending the data directory and a backslash.
4424     */
4425     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
4426                      sqlite3_data_directory, zRelative);
4427   }else{
4428     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
4429   }
4430   return SQLITE_OK;
4431 #endif
4432 
4433 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
4434   DWORD nByte;
4435   void *zConverted;
4436   char *zOut;
4437 
4438   /* If this path name begins with "/X:", where "X" is any alphabetic
4439   ** character, discard the initial "/" from the pathname.
4440   */
4441   if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
4442     zRelative++;
4443   }
4444 
4445   /* It's odd to simulate an io-error here, but really this is just
4446   ** using the io-error infrastructure to test that SQLite handles this
4447   ** function failing. This function could fail if, for example, the
4448   ** current working directory has been unlinked.
4449   */
4450   SimulateIOError( return SQLITE_ERROR );
4451   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
4452     /*
4453     ** NOTE: We are dealing with a relative path name and the data
4454     **       directory has been set.  Therefore, use it as the basis
4455     **       for converting the relative path name to an absolute
4456     **       one by prepending the data directory and a backslash.
4457     */
4458     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
4459                      sqlite3_data_directory, zRelative);
4460     return SQLITE_OK;
4461   }
4462   zConverted = convertUtf8Filename(zRelative);
4463   if( zConverted==0 ){
4464     return SQLITE_IOERR_NOMEM;
4465   }
4466   if( isNT() ){
4467     LPWSTR zTemp;
4468     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
4469     if( nByte==0 ){
4470       winLogError(SQLITE_ERROR, osGetLastError(),
4471                   "GetFullPathNameW1", zConverted);
4472       sqlite3_free(zConverted);
4473       return SQLITE_CANTOPEN_FULLPATH;
4474     }
4475     nByte += 3;
4476     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
4477     if( zTemp==0 ){
4478       sqlite3_free(zConverted);
4479       return SQLITE_IOERR_NOMEM;
4480     }
4481     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
4482     if( nByte==0 ){
4483       winLogError(SQLITE_ERROR, osGetLastError(),
4484                   "GetFullPathNameW2", zConverted);
4485       sqlite3_free(zConverted);
4486       sqlite3_free(zTemp);
4487       return SQLITE_CANTOPEN_FULLPATH;
4488     }
4489     sqlite3_free(zConverted);
4490     zOut = unicodeToUtf8(zTemp);
4491     sqlite3_free(zTemp);
4492   }
4493 #ifdef SQLITE_WIN32_HAS_ANSI
4494   else{
4495     char *zTemp;
4496     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
4497     if( nByte==0 ){
4498       winLogError(SQLITE_ERROR, osGetLastError(),
4499                   "GetFullPathNameA1", zConverted);
4500       sqlite3_free(zConverted);
4501       return SQLITE_CANTOPEN_FULLPATH;
4502     }
4503     nByte += 3;
4504     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
4505     if( zTemp==0 ){
4506       sqlite3_free(zConverted);
4507       return SQLITE_IOERR_NOMEM;
4508     }
4509     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
4510     if( nByte==0 ){
4511       winLogError(SQLITE_ERROR, osGetLastError(),
4512                   "GetFullPathNameA2", zConverted);
4513       sqlite3_free(zConverted);
4514       sqlite3_free(zTemp);
4515       return SQLITE_CANTOPEN_FULLPATH;
4516     }
4517     sqlite3_free(zConverted);
4518     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
4519     sqlite3_free(zTemp);
4520   }
4521 #endif
4522   if( zOut ){
4523     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
4524     sqlite3_free(zOut);
4525     return SQLITE_OK;
4526   }else{
4527     return SQLITE_IOERR_NOMEM;
4528   }
4529 #endif
4530 }
4531 
4532 #ifndef SQLITE_OMIT_LOAD_EXTENSION
4533 /*
4534 ** Interfaces for opening a shared library, finding entry points
4535 ** within the shared library, and closing the shared library.
4536 */
4537 /*
4538 ** Interfaces for opening a shared library, finding entry points
4539 ** within the shared library, and closing the shared library.
4540 */
4541 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
4542   HANDLE h;
4543   void *zConverted = convertUtf8Filename(zFilename);
4544   UNUSED_PARAMETER(pVfs);
4545   if( zConverted==0 ){
4546     return 0;
4547   }
4548   if( isNT() ){
4549 #if SQLITE_OS_WINRT
4550     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
4551 #else
4552     h = osLoadLibraryW((LPCWSTR)zConverted);
4553 #endif
4554   }
4555 #ifdef SQLITE_WIN32_HAS_ANSI
4556   else{
4557     h = osLoadLibraryA((char*)zConverted);
4558   }
4559 #endif
4560   sqlite3_free(zConverted);
4561   return (void*)h;
4562 }
4563 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
4564   UNUSED_PARAMETER(pVfs);
4565   getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
4566 }
4567 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
4568   UNUSED_PARAMETER(pVfs);
4569   return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
4570 }
4571 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
4572   UNUSED_PARAMETER(pVfs);
4573   osFreeLibrary((HANDLE)pHandle);
4574 }
4575 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
4576   #define winDlOpen  0
4577   #define winDlError 0
4578   #define winDlSym   0
4579   #define winDlClose 0
4580 #endif
4581 
4582 
4583 /*
4584 ** Write up to nBuf bytes of randomness into zBuf.
4585 */
4586 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
4587   int n = 0;
4588   UNUSED_PARAMETER(pVfs);
4589 #if defined(SQLITE_TEST)
4590   n = nBuf;
4591   memset(zBuf, 0, nBuf);
4592 #else
4593   if( sizeof(SYSTEMTIME)<=nBuf-n ){
4594     SYSTEMTIME x;
4595     osGetSystemTime(&x);
4596     memcpy(&zBuf[n], &x, sizeof(x));
4597     n += sizeof(x);
4598   }
4599   if( sizeof(DWORD)<=nBuf-n ){
4600     DWORD pid = osGetCurrentProcessId();
4601     memcpy(&zBuf[n], &pid, sizeof(pid));
4602     n += sizeof(pid);
4603   }
4604 #if SQLITE_OS_WINRT
4605   if( sizeof(ULONGLONG)<=nBuf-n ){
4606     ULONGLONG cnt = osGetTickCount64();
4607     memcpy(&zBuf[n], &cnt, sizeof(cnt));
4608     n += sizeof(cnt);
4609   }
4610 #else
4611   if( sizeof(DWORD)<=nBuf-n ){
4612     DWORD cnt = osGetTickCount();
4613     memcpy(&zBuf[n], &cnt, sizeof(cnt));
4614     n += sizeof(cnt);
4615   }
4616 #endif
4617   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
4618     LARGE_INTEGER i;
4619     osQueryPerformanceCounter(&i);
4620     memcpy(&zBuf[n], &i, sizeof(i));
4621     n += sizeof(i);
4622   }
4623 #endif
4624   return n;
4625 }
4626 
4627 
4628 /*
4629 ** Sleep for a little while.  Return the amount of time slept.
4630 */
4631 static int winSleep(sqlite3_vfs *pVfs, int microsec){
4632   sqlite3_win32_sleep((microsec+999)/1000);
4633   UNUSED_PARAMETER(pVfs);
4634   return ((microsec+999)/1000)*1000;
4635 }
4636 
4637 /*
4638 ** The following variable, if set to a non-zero value, is interpreted as
4639 ** the number of seconds since 1970 and is used to set the result of
4640 ** sqlite3OsCurrentTime() during testing.
4641 */
4642 #ifdef SQLITE_TEST
4643 int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
4644 #endif
4645 
4646 /*
4647 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
4648 ** the current time and date as a Julian Day number times 86_400_000.  In
4649 ** other words, write into *piNow the number of milliseconds since the Julian
4650 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
4651 ** proleptic Gregorian calendar.
4652 **
4653 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
4654 ** cannot be found.
4655 */
4656 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
4657   /* FILETIME structure is a 64-bit value representing the number of
4658      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
4659   */
4660   FILETIME ft;
4661   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
4662 #ifdef SQLITE_TEST
4663   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
4664 #endif
4665   /* 2^32 - to avoid use of LL and warnings in gcc */
4666   static const sqlite3_int64 max32BitValue =
4667       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
4668       (sqlite3_int64)294967296;
4669 
4670 #if SQLITE_OS_WINCE
4671   SYSTEMTIME time;
4672   osGetSystemTime(&time);
4673   /* if SystemTimeToFileTime() fails, it returns zero. */
4674   if (!osSystemTimeToFileTime(&time,&ft)){
4675     return SQLITE_ERROR;
4676   }
4677 #else
4678   osGetSystemTimeAsFileTime( &ft );
4679 #endif
4680 
4681   *piNow = winFiletimeEpoch +
4682             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
4683                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
4684 
4685 #ifdef SQLITE_TEST
4686   if( sqlite3_current_time ){
4687     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
4688   }
4689 #endif
4690   UNUSED_PARAMETER(pVfs);
4691   return SQLITE_OK;
4692 }
4693 
4694 /*
4695 ** Find the current time (in Universal Coordinated Time).  Write the
4696 ** current time and date as a Julian Day number into *prNow and
4697 ** return 0.  Return 1 if the time and date cannot be found.
4698 */
4699 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
4700   int rc;
4701   sqlite3_int64 i;
4702   rc = winCurrentTimeInt64(pVfs, &i);
4703   if( !rc ){
4704     *prNow = i/86400000.0;
4705   }
4706   return rc;
4707 }
4708 
4709 /*
4710 ** The idea is that this function works like a combination of
4711 ** GetLastError() and FormatMessage() on Windows (or errno and
4712 ** strerror_r() on Unix). After an error is returned by an OS
4713 ** function, SQLite calls this function with zBuf pointing to
4714 ** a buffer of nBuf bytes. The OS layer should populate the
4715 ** buffer with a nul-terminated UTF-8 encoded error message
4716 ** describing the last IO error to have occurred within the calling
4717 ** thread.
4718 **
4719 ** If the error message is too large for the supplied buffer,
4720 ** it should be truncated. The return value of xGetLastError
4721 ** is zero if the error message fits in the buffer, or non-zero
4722 ** otherwise (if the message was truncated). If non-zero is returned,
4723 ** then it is not necessary to include the nul-terminator character
4724 ** in the output buffer.
4725 **
4726 ** Not supplying an error message will have no adverse effect
4727 ** on SQLite. It is fine to have an implementation that never
4728 ** returns an error message:
4729 **
4730 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
4731 **     assert(zBuf[0]=='\0');
4732 **     return 0;
4733 **   }
4734 **
4735 ** However if an error message is supplied, it will be incorporated
4736 ** by sqlite into the error message available to the user using
4737 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
4738 */
4739 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
4740   UNUSED_PARAMETER(pVfs);
4741   return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
4742 }
4743 
4744 /*
4745 ** Initialize and deinitialize the operating system interface.
4746 */
4747 int sqlite3_os_init(void){
4748   static sqlite3_vfs winVfs = {
4749     3,                   /* iVersion */
4750     sizeof(winFile),     /* szOsFile */
4751     MAX_PATH,            /* mxPathname */
4752     0,                   /* pNext */
4753     "win32",             /* zName */
4754     0,                   /* pAppData */
4755     winOpen,             /* xOpen */
4756     winDelete,           /* xDelete */
4757     winAccess,           /* xAccess */
4758     winFullPathname,     /* xFullPathname */
4759     winDlOpen,           /* xDlOpen */
4760     winDlError,          /* xDlError */
4761     winDlSym,            /* xDlSym */
4762     winDlClose,          /* xDlClose */
4763     winRandomness,       /* xRandomness */
4764     winSleep,            /* xSleep */
4765     winCurrentTime,      /* xCurrentTime */
4766     winGetLastError,     /* xGetLastError */
4767     winCurrentTimeInt64, /* xCurrentTimeInt64 */
4768     winSetSystemCall,    /* xSetSystemCall */
4769     winGetSystemCall,    /* xGetSystemCall */
4770     winNextSystemCall,   /* xNextSystemCall */
4771   };
4772 
4773   /* Double-check that the aSyscall[] array has been constructed
4774   ** correctly.  See ticket [bb3a86e890c8e96ab] */
4775   assert( ArraySize(aSyscall)==74 );
4776 
4777   /* get memory map allocation granularity */
4778   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
4779 #if SQLITE_OS_WINRT
4780   osGetNativeSystemInfo(&winSysInfo);
4781 #else
4782   osGetSystemInfo(&winSysInfo);
4783 #endif
4784   assert( winSysInfo.dwAllocationGranularity>0 );
4785   assert( winSysInfo.dwPageSize>0 );
4786 
4787   sqlite3_vfs_register(&winVfs, 1);
4788   return SQLITE_OK;
4789 }
4790 
4791 int sqlite3_os_end(void){
4792 #if SQLITE_OS_WINRT
4793   if( sleepObj!=NULL ){
4794     osCloseHandle(sleepObj);
4795     sleepObj = NULL;
4796   }
4797 #endif
4798   return SQLITE_OK;
4799 }
4800 
4801 #endif /* SQLITE_OS_WIN */
4802