xref: /sqlite-3.40.0/src/os_win.c (revision f2fcd075)
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 
19 /*
20 ** A Note About Memory Allocation:
21 **
22 ** This driver uses malloc()/free() directly rather than going through
23 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
24 ** are designed for use on embedded systems where memory is scarce and
25 ** malloc failures happen frequently.  Win32 does not typically run on
26 ** embedded systems, and when it does the developers normally have bigger
27 ** problems to worry about than running out of memory.  So there is not
28 ** a compelling need to use the wrappers.
29 **
30 ** But there is a good reason to not use the wrappers.  If we use the
31 ** wrappers then we will get simulated malloc() failures within this
32 ** driver.  And that causes all kinds of problems for our tests.  We
33 ** could enhance SQLite to deal with simulated malloc failures within
34 ** the OS driver, but the code to deal with those failure would not
35 ** be exercised on Linux (which does not need to malloc() in the driver)
36 ** and so we would have difficulty writing coverage tests for that
37 ** code.  Better to leave the code out, we think.
38 **
39 ** The point of this discussion is as follows:  When creating a new
40 ** OS layer for an embedded system, if you use this file as an example,
41 ** avoid the use of malloc()/free().  Those routines work ok on windows
42 ** desktops but not so well in embedded systems.
43 */
44 
45 #include <winbase.h>
46 
47 #ifdef __CYGWIN__
48 # include <sys/cygwin.h>
49 #endif
50 
51 /*
52 ** Macros used to determine whether or not to use threads.
53 */
54 #if defined(THREADSAFE) && THREADSAFE
55 # define SQLITE_W32_THREADS 1
56 #endif
57 
58 /*
59 ** Include code that is common to all os_*.c files
60 */
61 #include "os_common.h"
62 
63 /*
64 ** Some microsoft compilers lack this definition.
65 */
66 #ifndef INVALID_FILE_ATTRIBUTES
67 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
68 #endif
69 
70 /*
71 ** Determine if we are dealing with WindowsCE - which has a much
72 ** reduced API.
73 */
74 #if SQLITE_OS_WINCE
75 # define AreFileApisANSI() 1
76 # define FormatMessageW(a,b,c,d,e,f,g) 0
77 #endif
78 
79 /* Forward references */
80 typedef struct winShm winShm;           /* A connection to shared-memory */
81 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
82 
83 /*
84 ** WinCE lacks native support for file locking so we have to fake it
85 ** with some code of our own.
86 */
87 #if SQLITE_OS_WINCE
88 typedef struct winceLock {
89   int nReaders;       /* Number of reader locks obtained */
90   BOOL bPending;      /* Indicates a pending lock has been obtained */
91   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
92   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
93 } winceLock;
94 #endif
95 
96 /*
97 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
98 ** portability layer.
99 */
100 typedef struct winFile winFile;
101 struct winFile {
102   const sqlite3_io_methods *pMethod; /*** Must be first ***/
103   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
104   HANDLE h;               /* Handle for accessing the file */
105   unsigned char locktype; /* Type of lock currently held on this file */
106   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
107   DWORD lastErrno;        /* The Windows errno from the last I/O error */
108   DWORD sectorSize;       /* Sector size of the device file is on */
109   winShm *pShm;           /* Instance of shared memory on this file */
110   const char *zPath;      /* Full pathname of this file */
111   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
112 #if SQLITE_OS_WINCE
113   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
114   HANDLE hMutex;          /* Mutex used to control access to shared lock */
115   HANDLE hShared;         /* Shared memory segment used for locking */
116   winceLock local;        /* Locks obtained by this instance of winFile */
117   winceLock *shared;      /* Global shared lock memory for the file  */
118 #endif
119 };
120 
121 /*
122 ** Forward prototypes.
123 */
124 static int getSectorSize(
125     sqlite3_vfs *pVfs,
126     const char *zRelative     /* UTF-8 file name */
127 );
128 
129 /*
130 ** The following variable is (normally) set once and never changes
131 ** thereafter.  It records whether the operating system is Win95
132 ** or WinNT.
133 **
134 ** 0:   Operating system unknown.
135 ** 1:   Operating system is Win95.
136 ** 2:   Operating system is WinNT.
137 **
138 ** In order to facilitate testing on a WinNT system, the test fixture
139 ** can manually set this value to 1 to emulate Win98 behavior.
140 */
141 #ifdef SQLITE_TEST
142 int sqlite3_os_type = 0;
143 #else
144 static int sqlite3_os_type = 0;
145 #endif
146 
147 /*
148 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
149 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
150 **
151 ** Here is an interesting observation:  Win95, Win98, and WinME lack
152 ** the LockFileEx() API.  But we can still statically link against that
153 ** API as long as we don't call it when running Win95/98/ME.  A call to
154 ** this routine is used to determine if the host is Win95/98/ME or
155 ** WinNT/2K/XP so that we will know whether or not we can safely call
156 ** the LockFileEx() API.
157 */
158 #if SQLITE_OS_WINCE
159 # define isNT()  (1)
160 #else
161   static int isNT(void){
162     if( sqlite3_os_type==0 ){
163       OSVERSIONINFO sInfo;
164       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
165       GetVersionEx(&sInfo);
166       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
167     }
168     return sqlite3_os_type==2;
169   }
170 #endif /* SQLITE_OS_WINCE */
171 
172 /*
173 ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
174 **
175 ** Space to hold the returned string is obtained from malloc.
176 */
177 static WCHAR *utf8ToUnicode(const char *zFilename){
178   int nChar;
179   WCHAR *zWideFilename;
180 
181   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
182   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
183   if( zWideFilename==0 ){
184     return 0;
185   }
186   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
187   if( nChar==0 ){
188     free(zWideFilename);
189     zWideFilename = 0;
190   }
191   return zWideFilename;
192 }
193 
194 /*
195 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
196 ** obtained from malloc().
197 */
198 static char *unicodeToUtf8(const WCHAR *zWideFilename){
199   int nByte;
200   char *zFilename;
201 
202   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
203   zFilename = malloc( nByte );
204   if( zFilename==0 ){
205     return 0;
206   }
207   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
208                               0, 0);
209   if( nByte == 0 ){
210     free(zFilename);
211     zFilename = 0;
212   }
213   return zFilename;
214 }
215 
216 /*
217 ** Convert an ansi string to microsoft unicode, based on the
218 ** current codepage settings for file apis.
219 **
220 ** Space to hold the returned string is obtained
221 ** from malloc.
222 */
223 static WCHAR *mbcsToUnicode(const char *zFilename){
224   int nByte;
225   WCHAR *zMbcsFilename;
226   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
227 
228   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
229   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
230   if( zMbcsFilename==0 ){
231     return 0;
232   }
233   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
234   if( nByte==0 ){
235     free(zMbcsFilename);
236     zMbcsFilename = 0;
237   }
238   return zMbcsFilename;
239 }
240 
241 /*
242 ** Convert microsoft unicode to multibyte character string, based on the
243 ** user's Ansi codepage.
244 **
245 ** Space to hold the returned string is obtained from
246 ** malloc().
247 */
248 static char *unicodeToMbcs(const WCHAR *zWideFilename){
249   int nByte;
250   char *zFilename;
251   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
252 
253   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
254   zFilename = malloc( nByte );
255   if( zFilename==0 ){
256     return 0;
257   }
258   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
259                               0, 0);
260   if( nByte == 0 ){
261     free(zFilename);
262     zFilename = 0;
263   }
264   return zFilename;
265 }
266 
267 /*
268 ** Convert multibyte character string to UTF-8.  Space to hold the
269 ** returned string is obtained from malloc().
270 */
271 char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
272   char *zFilenameUtf8;
273   WCHAR *zTmpWide;
274 
275   zTmpWide = mbcsToUnicode(zFilename);
276   if( zTmpWide==0 ){
277     return 0;
278   }
279   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
280   free(zTmpWide);
281   return zFilenameUtf8;
282 }
283 
284 /*
285 ** Convert UTF-8 to multibyte character string.  Space to hold the
286 ** returned string is obtained from malloc().
287 */
288 static char *utf8ToMbcs(const char *zFilename){
289   char *zFilenameMbcs;
290   WCHAR *zTmpWide;
291 
292   zTmpWide = utf8ToUnicode(zFilename);
293   if( zTmpWide==0 ){
294     return 0;
295   }
296   zFilenameMbcs = unicodeToMbcs(zTmpWide);
297   free(zTmpWide);
298   return zFilenameMbcs;
299 }
300 
301 #if SQLITE_OS_WINCE
302 /*************************************************************************
303 ** This section contains code for WinCE only.
304 */
305 /*
306 ** WindowsCE does not have a localtime() function.  So create a
307 ** substitute.
308 */
309 #include <time.h>
310 struct tm *__cdecl localtime(const time_t *t)
311 {
312   static struct tm y;
313   FILETIME uTm, lTm;
314   SYSTEMTIME pTm;
315   sqlite3_int64 t64;
316   t64 = *t;
317   t64 = (t64 + 11644473600)*10000000;
318   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
319   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
320   FileTimeToLocalFileTime(&uTm,&lTm);
321   FileTimeToSystemTime(&lTm,&pTm);
322   y.tm_year = pTm.wYear - 1900;
323   y.tm_mon = pTm.wMonth - 1;
324   y.tm_wday = pTm.wDayOfWeek;
325   y.tm_mday = pTm.wDay;
326   y.tm_hour = pTm.wHour;
327   y.tm_min = pTm.wMinute;
328   y.tm_sec = pTm.wSecond;
329   return &y;
330 }
331 
332 /* This will never be called, but defined to make the code compile */
333 #define GetTempPathA(a,b)
334 
335 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
336 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
337 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
338 
339 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
340 
341 /*
342 ** Acquire a lock on the handle h
343 */
344 static void winceMutexAcquire(HANDLE h){
345    DWORD dwErr;
346    do {
347      dwErr = WaitForSingleObject(h, INFINITE);
348    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
349 }
350 /*
351 ** Release a lock acquired by winceMutexAcquire()
352 */
353 #define winceMutexRelease(h) ReleaseMutex(h)
354 
355 /*
356 ** Create the mutex and shared memory used for locking in the file
357 ** descriptor pFile
358 */
359 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
360   WCHAR *zTok;
361   WCHAR *zName = utf8ToUnicode(zFilename);
362   BOOL bInit = TRUE;
363 
364   /* Initialize the local lockdata */
365   ZeroMemory(&pFile->local, sizeof(pFile->local));
366 
367   /* Replace the backslashes from the filename and lowercase it
368   ** to derive a mutex name. */
369   zTok = CharLowerW(zName);
370   for (;*zTok;zTok++){
371     if (*zTok == '\\') *zTok = '_';
372   }
373 
374   /* Create/open the named mutex */
375   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
376   if (!pFile->hMutex){
377     pFile->lastErrno = GetLastError();
378     free(zName);
379     return FALSE;
380   }
381 
382   /* Acquire the mutex before continuing */
383   winceMutexAcquire(pFile->hMutex);
384 
385   /* Since the names of named mutexes, semaphores, file mappings etc are
386   ** case-sensitive, take advantage of that by uppercasing the mutex name
387   ** and using that as the shared filemapping name.
388   */
389   CharUpperW(zName);
390   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
391                                        PAGE_READWRITE, 0, sizeof(winceLock),
392                                        zName);
393 
394   /* Set a flag that indicates we're the first to create the memory so it
395   ** must be zero-initialized */
396   if (GetLastError() == ERROR_ALREADY_EXISTS){
397     bInit = FALSE;
398   }
399 
400   free(zName);
401 
402   /* If we succeeded in making the shared memory handle, map it. */
403   if (pFile->hShared){
404     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
405              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
406     /* If mapping failed, close the shared memory handle and erase it */
407     if (!pFile->shared){
408       pFile->lastErrno = GetLastError();
409       CloseHandle(pFile->hShared);
410       pFile->hShared = NULL;
411     }
412   }
413 
414   /* If shared memory could not be created, then close the mutex and fail */
415   if (pFile->hShared == NULL){
416     winceMutexRelease(pFile->hMutex);
417     CloseHandle(pFile->hMutex);
418     pFile->hMutex = NULL;
419     return FALSE;
420   }
421 
422   /* Initialize the shared memory if we're supposed to */
423   if (bInit) {
424     ZeroMemory(pFile->shared, sizeof(winceLock));
425   }
426 
427   winceMutexRelease(pFile->hMutex);
428   return TRUE;
429 }
430 
431 /*
432 ** Destroy the part of winFile that deals with wince locks
433 */
434 static void winceDestroyLock(winFile *pFile){
435   if (pFile->hMutex){
436     /* Acquire the mutex */
437     winceMutexAcquire(pFile->hMutex);
438 
439     /* The following blocks should probably assert in debug mode, but they
440        are to cleanup in case any locks remained open */
441     if (pFile->local.nReaders){
442       pFile->shared->nReaders --;
443     }
444     if (pFile->local.bReserved){
445       pFile->shared->bReserved = FALSE;
446     }
447     if (pFile->local.bPending){
448       pFile->shared->bPending = FALSE;
449     }
450     if (pFile->local.bExclusive){
451       pFile->shared->bExclusive = FALSE;
452     }
453 
454     /* De-reference and close our copy of the shared memory handle */
455     UnmapViewOfFile(pFile->shared);
456     CloseHandle(pFile->hShared);
457 
458     /* Done with the mutex */
459     winceMutexRelease(pFile->hMutex);
460     CloseHandle(pFile->hMutex);
461     pFile->hMutex = NULL;
462   }
463 }
464 
465 /*
466 ** An implementation of the LockFile() API of windows for wince
467 */
468 static BOOL winceLockFile(
469   HANDLE *phFile,
470   DWORD dwFileOffsetLow,
471   DWORD dwFileOffsetHigh,
472   DWORD nNumberOfBytesToLockLow,
473   DWORD nNumberOfBytesToLockHigh
474 ){
475   winFile *pFile = HANDLE_TO_WINFILE(phFile);
476   BOOL bReturn = FALSE;
477 
478   UNUSED_PARAMETER(dwFileOffsetHigh);
479   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
480 
481   if (!pFile->hMutex) return TRUE;
482   winceMutexAcquire(pFile->hMutex);
483 
484   /* Wanting an exclusive lock? */
485   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
486        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
487     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
488        pFile->shared->bExclusive = TRUE;
489        pFile->local.bExclusive = TRUE;
490        bReturn = TRUE;
491     }
492   }
493 
494   /* Want a read-only lock? */
495   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
496            nNumberOfBytesToLockLow == 1){
497     if (pFile->shared->bExclusive == 0){
498       pFile->local.nReaders ++;
499       if (pFile->local.nReaders == 1){
500         pFile->shared->nReaders ++;
501       }
502       bReturn = TRUE;
503     }
504   }
505 
506   /* Want a pending lock? */
507   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
508     /* If no pending lock has been acquired, then acquire it */
509     if (pFile->shared->bPending == 0) {
510       pFile->shared->bPending = TRUE;
511       pFile->local.bPending = TRUE;
512       bReturn = TRUE;
513     }
514   }
515 
516   /* Want a reserved lock? */
517   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
518     if (pFile->shared->bReserved == 0) {
519       pFile->shared->bReserved = TRUE;
520       pFile->local.bReserved = TRUE;
521       bReturn = TRUE;
522     }
523   }
524 
525   winceMutexRelease(pFile->hMutex);
526   return bReturn;
527 }
528 
529 /*
530 ** An implementation of the UnlockFile API of windows for wince
531 */
532 static BOOL winceUnlockFile(
533   HANDLE *phFile,
534   DWORD dwFileOffsetLow,
535   DWORD dwFileOffsetHigh,
536   DWORD nNumberOfBytesToUnlockLow,
537   DWORD nNumberOfBytesToUnlockHigh
538 ){
539   winFile *pFile = HANDLE_TO_WINFILE(phFile);
540   BOOL bReturn = FALSE;
541 
542   UNUSED_PARAMETER(dwFileOffsetHigh);
543   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
544 
545   if (!pFile->hMutex) return TRUE;
546   winceMutexAcquire(pFile->hMutex);
547 
548   /* Releasing a reader lock or an exclusive lock */
549   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
550     /* Did we have an exclusive lock? */
551     if (pFile->local.bExclusive){
552       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
553       pFile->local.bExclusive = FALSE;
554       pFile->shared->bExclusive = FALSE;
555       bReturn = TRUE;
556     }
557 
558     /* Did we just have a reader lock? */
559     else if (pFile->local.nReaders){
560       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
561       pFile->local.nReaders --;
562       if (pFile->local.nReaders == 0)
563       {
564         pFile->shared->nReaders --;
565       }
566       bReturn = TRUE;
567     }
568   }
569 
570   /* Releasing a pending lock */
571   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
572     if (pFile->local.bPending){
573       pFile->local.bPending = FALSE;
574       pFile->shared->bPending = FALSE;
575       bReturn = TRUE;
576     }
577   }
578   /* Releasing a reserved lock */
579   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
580     if (pFile->local.bReserved) {
581       pFile->local.bReserved = FALSE;
582       pFile->shared->bReserved = FALSE;
583       bReturn = TRUE;
584     }
585   }
586 
587   winceMutexRelease(pFile->hMutex);
588   return bReturn;
589 }
590 
591 /*
592 ** An implementation of the LockFileEx() API of windows for wince
593 */
594 static BOOL winceLockFileEx(
595   HANDLE *phFile,
596   DWORD dwFlags,
597   DWORD dwReserved,
598   DWORD nNumberOfBytesToLockLow,
599   DWORD nNumberOfBytesToLockHigh,
600   LPOVERLAPPED lpOverlapped
601 ){
602   UNUSED_PARAMETER(dwReserved);
603   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
604 
605   /* If the caller wants a shared read lock, forward this call
606   ** to winceLockFile */
607   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
608       dwFlags == 1 &&
609       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
610     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
611   }
612   return FALSE;
613 }
614 /*
615 ** End of the special code for wince
616 *****************************************************************************/
617 #endif /* SQLITE_OS_WINCE */
618 
619 /*****************************************************************************
620 ** The next group of routines implement the I/O methods specified
621 ** by the sqlite3_io_methods object.
622 ******************************************************************************/
623 
624 /*
625 ** Some microsoft compilers lack this definition.
626 */
627 #ifndef INVALID_SET_FILE_POINTER
628 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
629 #endif
630 
631 /*
632 ** Move the current position of the file handle passed as the first
633 ** argument to offset iOffset within the file. If successful, return 0.
634 ** Otherwise, set pFile->lastErrno and return non-zero.
635 */
636 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
637   LONG upperBits;                 /* Most sig. 32 bits of new offset */
638   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
639   DWORD dwRet;                    /* Value returned by SetFilePointer() */
640 
641   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
642   lowerBits = (LONG)(iOffset & 0xffffffff);
643 
644   /* API oddity: If successful, SetFilePointer() returns a dword
645   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
646   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
647   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
648   ** whether an error has actually occured, it is also necessary to call
649   ** GetLastError().
650   */
651   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
652   if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
653     pFile->lastErrno = GetLastError();
654     return 1;
655   }
656 
657   return 0;
658 }
659 
660 /*
661 ** Close a file.
662 **
663 ** It is reported that an attempt to close a handle might sometimes
664 ** fail.  This is a very unreasonable result, but windows is notorious
665 ** for being unreasonable so I do not doubt that it might happen.  If
666 ** the close fails, we pause for 100 milliseconds and try again.  As
667 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
668 ** giving up and returning an error.
669 */
670 #define MX_CLOSE_ATTEMPT 3
671 static int winClose(sqlite3_file *id){
672   int rc, cnt = 0;
673   winFile *pFile = (winFile*)id;
674 
675   assert( id!=0 );
676   assert( pFile->pShm==0 );
677   OSTRACE(("CLOSE %d\n", pFile->h));
678   do{
679     rc = CloseHandle(pFile->h);
680     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
681   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
682 #if SQLITE_OS_WINCE
683 #define WINCE_DELETION_ATTEMPTS 3
684   winceDestroyLock(pFile);
685   if( pFile->zDeleteOnClose ){
686     int cnt = 0;
687     while(
688            DeleteFileW(pFile->zDeleteOnClose)==0
689         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
690         && cnt++ < WINCE_DELETION_ATTEMPTS
691     ){
692        Sleep(100);  /* Wait a little before trying again */
693     }
694     free(pFile->zDeleteOnClose);
695   }
696 #endif
697   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
698   OpenCounter(-1);
699   return rc ? SQLITE_OK : SQLITE_IOERR;
700 }
701 
702 /*
703 ** Read data from a file into a buffer.  Return SQLITE_OK if all
704 ** bytes were read successfully and SQLITE_IOERR if anything goes
705 ** wrong.
706 */
707 static int winRead(
708   sqlite3_file *id,          /* File to read from */
709   void *pBuf,                /* Write content into this buffer */
710   int amt,                   /* Number of bytes to read */
711   sqlite3_int64 offset       /* Begin reading at this offset */
712 ){
713   winFile *pFile = (winFile*)id;  /* file handle */
714   DWORD nRead;                    /* Number of bytes actually read from file */
715 
716   assert( id!=0 );
717   SimulateIOError(return SQLITE_IOERR_READ);
718   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
719 
720   if( seekWinFile(pFile, offset) ){
721     return SQLITE_FULL;
722   }
723   if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
724     pFile->lastErrno = GetLastError();
725     return SQLITE_IOERR_READ;
726   }
727   if( nRead<(DWORD)amt ){
728     /* Unread parts of the buffer must be zero-filled */
729     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
730     return SQLITE_IOERR_SHORT_READ;
731   }
732 
733   return SQLITE_OK;
734 }
735 
736 /*
737 ** Write data from a buffer into a file.  Return SQLITE_OK on success
738 ** or some other error code on failure.
739 */
740 static int winWrite(
741   sqlite3_file *id,               /* File to write into */
742   const void *pBuf,               /* The bytes to be written */
743   int amt,                        /* Number of bytes to write */
744   sqlite3_int64 offset            /* Offset into the file to begin writing at */
745 ){
746   int rc;                         /* True if error has occured, else false */
747   winFile *pFile = (winFile*)id;  /* File handle */
748 
749   assert( amt>0 );
750   assert( pFile );
751   SimulateIOError(return SQLITE_IOERR_WRITE);
752   SimulateDiskfullError(return SQLITE_FULL);
753 
754   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
755 
756   rc = seekWinFile(pFile, offset);
757   if( rc==0 ){
758     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
759     int nRem = amt;               /* Number of bytes yet to be written */
760     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
761 
762     while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
763       aRem += nWrite;
764       nRem -= nWrite;
765     }
766     if( nRem>0 ){
767       pFile->lastErrno = GetLastError();
768       rc = 1;
769     }
770   }
771 
772   if( rc ){
773     if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
774       return SQLITE_FULL;
775     }
776     return SQLITE_IOERR_WRITE;
777   }
778   return SQLITE_OK;
779 }
780 
781 /*
782 ** Truncate an open file to a specified size
783 */
784 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
785   winFile *pFile = (winFile*)id;  /* File handle object */
786   int rc = SQLITE_OK;             /* Return code for this function */
787 
788   assert( pFile );
789 
790   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
791   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
792 
793   /* If the user has configured a chunk-size for this file, truncate the
794   ** file so that it consists of an integer number of chunks (i.e. the
795   ** actual file size after the operation may be larger than the requested
796   ** size).
797   */
798   if( pFile->szChunk ){
799     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
800   }
801 
802   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
803   if( seekWinFile(pFile, nByte) ){
804     rc = SQLITE_IOERR_TRUNCATE;
805   }else if( 0==SetEndOfFile(pFile->h) ){
806     pFile->lastErrno = GetLastError();
807     rc = SQLITE_IOERR_TRUNCATE;
808   }
809 
810   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
811   return rc;
812 }
813 
814 #ifdef SQLITE_TEST
815 /*
816 ** Count the number of fullsyncs and normal syncs.  This is used to test
817 ** that syncs and fullsyncs are occuring at the right times.
818 */
819 int sqlite3_sync_count = 0;
820 int sqlite3_fullsync_count = 0;
821 #endif
822 
823 /*
824 ** Make sure all writes to a particular file are committed to disk.
825 */
826 static int winSync(sqlite3_file *id, int flags){
827 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
828   winFile *pFile = (winFile*)id;
829 #else
830   UNUSED_PARAMETER(id);
831 #endif
832 
833   assert( pFile );
834   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
835   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
836       || (flags&0x0F)==SQLITE_SYNC_FULL
837   );
838 
839   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
840 
841 #ifndef SQLITE_TEST
842   UNUSED_PARAMETER(flags);
843 #else
844   if( flags & SQLITE_SYNC_FULL ){
845     sqlite3_fullsync_count++;
846   }
847   sqlite3_sync_count++;
848 #endif
849 
850   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
851   ** line is to test that doing so does not cause any problems.
852   */
853   SimulateDiskfullError( return SQLITE_FULL );
854   SimulateIOError( return SQLITE_IOERR; );
855 
856   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
857   ** no-op
858   */
859 #ifdef SQLITE_NO_SYNC
860   return SQLITE_OK;
861 #else
862   if( FlushFileBuffers(pFile->h) ){
863     return SQLITE_OK;
864   }else{
865     pFile->lastErrno = GetLastError();
866     return SQLITE_IOERR;
867   }
868 #endif
869 }
870 
871 /*
872 ** Determine the current size of a file in bytes
873 */
874 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
875   DWORD upperBits;
876   DWORD lowerBits;
877   winFile *pFile = (winFile*)id;
878   DWORD error;
879 
880   assert( id!=0 );
881   SimulateIOError(return SQLITE_IOERR_FSTAT);
882   lowerBits = GetFileSize(pFile->h, &upperBits);
883   if(   (lowerBits == INVALID_FILE_SIZE)
884      && ((error = GetLastError()) != NO_ERROR) )
885   {
886     pFile->lastErrno = error;
887     return SQLITE_IOERR_FSTAT;
888   }
889   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
890   return SQLITE_OK;
891 }
892 
893 /*
894 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
895 */
896 #ifndef LOCKFILE_FAIL_IMMEDIATELY
897 # define LOCKFILE_FAIL_IMMEDIATELY 1
898 #endif
899 
900 /*
901 ** Acquire a reader lock.
902 ** Different API routines are called depending on whether or not this
903 ** is Win95 or WinNT.
904 */
905 static int getReadLock(winFile *pFile){
906   int res;
907   if( isNT() ){
908     OVERLAPPED ovlp;
909     ovlp.Offset = SHARED_FIRST;
910     ovlp.OffsetHigh = 0;
911     ovlp.hEvent = 0;
912     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
913                      0, SHARED_SIZE, 0, &ovlp);
914 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
915 */
916 #if SQLITE_OS_WINCE==0
917   }else{
918     int lk;
919     sqlite3_randomness(sizeof(lk), &lk);
920     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
921     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
922 #endif
923   }
924   if( res == 0 ){
925     pFile->lastErrno = GetLastError();
926   }
927   return res;
928 }
929 
930 /*
931 ** Undo a readlock
932 */
933 static int unlockReadLock(winFile *pFile){
934   int res;
935   if( isNT() ){
936     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
937 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
938 */
939 #if SQLITE_OS_WINCE==0
940   }else{
941     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
942 #endif
943   }
944   if( res == 0 ){
945     pFile->lastErrno = GetLastError();
946   }
947   return res;
948 }
949 
950 /*
951 ** Lock the file with the lock specified by parameter locktype - one
952 ** of the following:
953 **
954 **     (1) SHARED_LOCK
955 **     (2) RESERVED_LOCK
956 **     (3) PENDING_LOCK
957 **     (4) EXCLUSIVE_LOCK
958 **
959 ** Sometimes when requesting one lock state, additional lock states
960 ** are inserted in between.  The locking might fail on one of the later
961 ** transitions leaving the lock state different from what it started but
962 ** still short of its goal.  The following chart shows the allowed
963 ** transitions and the inserted intermediate states:
964 **
965 **    UNLOCKED -> SHARED
966 **    SHARED -> RESERVED
967 **    SHARED -> (PENDING) -> EXCLUSIVE
968 **    RESERVED -> (PENDING) -> EXCLUSIVE
969 **    PENDING -> EXCLUSIVE
970 **
971 ** This routine will only increase a lock.  The winUnlock() routine
972 ** erases all locks at once and returns us immediately to locking level 0.
973 ** It is not possible to lower the locking level one step at a time.  You
974 ** must go straight to locking level 0.
975 */
976 static int winLock(sqlite3_file *id, int locktype){
977   int rc = SQLITE_OK;    /* Return code from subroutines */
978   int res = 1;           /* Result of a windows lock call */
979   int newLocktype;       /* Set pFile->locktype to this value before exiting */
980   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
981   winFile *pFile = (winFile*)id;
982   DWORD error = NO_ERROR;
983 
984   assert( id!=0 );
985   OSTRACE(("LOCK %d %d was %d(%d)\n",
986            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
987 
988   /* If there is already a lock of this type or more restrictive on the
989   ** OsFile, do nothing. Don't use the end_lock: exit path, as
990   ** sqlite3OsEnterMutex() hasn't been called yet.
991   */
992   if( pFile->locktype>=locktype ){
993     return SQLITE_OK;
994   }
995 
996   /* Make sure the locking sequence is correct
997   */
998   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
999   assert( locktype!=PENDING_LOCK );
1000   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1001 
1002   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
1003   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
1004   ** the PENDING_LOCK byte is temporary.
1005   */
1006   newLocktype = pFile->locktype;
1007   if(   (pFile->locktype==NO_LOCK)
1008      || (   (locktype==EXCLUSIVE_LOCK)
1009          && (pFile->locktype==RESERVED_LOCK))
1010   ){
1011     int cnt = 3;
1012     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
1013       /* Try 3 times to get the pending lock.  The pending lock might be
1014       ** held by another reader process who will release it momentarily.
1015       */
1016       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
1017       Sleep(1);
1018     }
1019     gotPendingLock = res;
1020     if( !res ){
1021       error = GetLastError();
1022     }
1023   }
1024 
1025   /* Acquire a shared lock
1026   */
1027   if( locktype==SHARED_LOCK && res ){
1028     assert( pFile->locktype==NO_LOCK );
1029     res = getReadLock(pFile);
1030     if( res ){
1031       newLocktype = SHARED_LOCK;
1032     }else{
1033       error = GetLastError();
1034     }
1035   }
1036 
1037   /* Acquire a RESERVED lock
1038   */
1039   if( locktype==RESERVED_LOCK && res ){
1040     assert( pFile->locktype==SHARED_LOCK );
1041     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1042     if( res ){
1043       newLocktype = RESERVED_LOCK;
1044     }else{
1045       error = GetLastError();
1046     }
1047   }
1048 
1049   /* Acquire a PENDING lock
1050   */
1051   if( locktype==EXCLUSIVE_LOCK && res ){
1052     newLocktype = PENDING_LOCK;
1053     gotPendingLock = 0;
1054   }
1055 
1056   /* Acquire an EXCLUSIVE lock
1057   */
1058   if( locktype==EXCLUSIVE_LOCK && res ){
1059     assert( pFile->locktype>=SHARED_LOCK );
1060     res = unlockReadLock(pFile);
1061     OSTRACE(("unreadlock = %d\n", res));
1062     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
1063     if( res ){
1064       newLocktype = EXCLUSIVE_LOCK;
1065     }else{
1066       error = GetLastError();
1067       OSTRACE(("error-code = %d\n", error));
1068       getReadLock(pFile);
1069     }
1070   }
1071 
1072   /* If we are holding a PENDING lock that ought to be released, then
1073   ** release it now.
1074   */
1075   if( gotPendingLock && locktype==SHARED_LOCK ){
1076     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
1077   }
1078 
1079   /* Update the state of the lock has held in the file descriptor then
1080   ** return the appropriate result code.
1081   */
1082   if( res ){
1083     rc = SQLITE_OK;
1084   }else{
1085     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
1086            locktype, newLocktype));
1087     pFile->lastErrno = error;
1088     rc = SQLITE_BUSY;
1089   }
1090   pFile->locktype = (u8)newLocktype;
1091   return rc;
1092 }
1093 
1094 /*
1095 ** This routine checks if there is a RESERVED lock held on the specified
1096 ** file by this or any other process. If such a lock is held, return
1097 ** non-zero, otherwise zero.
1098 */
1099 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
1100   int rc;
1101   winFile *pFile = (winFile*)id;
1102 
1103   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1104 
1105   assert( id!=0 );
1106   if( pFile->locktype>=RESERVED_LOCK ){
1107     rc = 1;
1108     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
1109   }else{
1110     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1111     if( rc ){
1112       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1113     }
1114     rc = !rc;
1115     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
1116   }
1117   *pResOut = rc;
1118   return SQLITE_OK;
1119 }
1120 
1121 /*
1122 ** Lower the locking level on file descriptor id to locktype.  locktype
1123 ** must be either NO_LOCK or SHARED_LOCK.
1124 **
1125 ** If the locking level of the file descriptor is already at or below
1126 ** the requested locking level, this routine is a no-op.
1127 **
1128 ** It is not possible for this routine to fail if the second argument
1129 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
1130 ** might return SQLITE_IOERR;
1131 */
1132 static int winUnlock(sqlite3_file *id, int locktype){
1133   int type;
1134   winFile *pFile = (winFile*)id;
1135   int rc = SQLITE_OK;
1136   assert( pFile!=0 );
1137   assert( locktype<=SHARED_LOCK );
1138   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
1139           pFile->locktype, pFile->sharedLockByte));
1140   type = pFile->locktype;
1141   if( type>=EXCLUSIVE_LOCK ){
1142     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
1143     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
1144       /* This should never happen.  We should always be able to
1145       ** reacquire the read lock */
1146       rc = SQLITE_IOERR_UNLOCK;
1147     }
1148   }
1149   if( type>=RESERVED_LOCK ){
1150     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1151   }
1152   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
1153     unlockReadLock(pFile);
1154   }
1155   if( type>=PENDING_LOCK ){
1156     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
1157   }
1158   pFile->locktype = (u8)locktype;
1159   return rc;
1160 }
1161 
1162 /*
1163 ** Control and query of the open file handle.
1164 */
1165 static int winFileControl(sqlite3_file *id, int op, void *pArg){
1166   switch( op ){
1167     case SQLITE_FCNTL_LOCKSTATE: {
1168       *(int*)pArg = ((winFile*)id)->locktype;
1169       return SQLITE_OK;
1170     }
1171     case SQLITE_LAST_ERRNO: {
1172       *(int*)pArg = (int)((winFile*)id)->lastErrno;
1173       return SQLITE_OK;
1174     }
1175     case SQLITE_FCNTL_CHUNK_SIZE: {
1176       ((winFile*)id)->szChunk = *(int *)pArg;
1177       return SQLITE_OK;
1178     }
1179     case SQLITE_FCNTL_SIZE_HINT: {
1180       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
1181       SimulateIOErrorBenign(1);
1182       winTruncate(id, sz);
1183       SimulateIOErrorBenign(0);
1184       return SQLITE_OK;
1185     }
1186   }
1187   return SQLITE_ERROR;
1188 }
1189 
1190 /*
1191 ** Return the sector size in bytes of the underlying block device for
1192 ** the specified file. This is almost always 512 bytes, but may be
1193 ** larger for some devices.
1194 **
1195 ** SQLite code assumes this function cannot fail. It also assumes that
1196 ** if two files are created in the same file-system directory (i.e.
1197 ** a database and its journal file) that the sector size will be the
1198 ** same for both.
1199 */
1200 static int winSectorSize(sqlite3_file *id){
1201   assert( id!=0 );
1202   return (int)(((winFile*)id)->sectorSize);
1203 }
1204 
1205 /*
1206 ** Return a vector of device characteristics.
1207 */
1208 static int winDeviceCharacteristics(sqlite3_file *id){
1209   UNUSED_PARAMETER(id);
1210   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
1211 }
1212 
1213 #ifndef SQLITE_OMIT_WAL
1214 
1215 /*
1216 ** Windows will only let you create file view mappings
1217 ** on allocation size granularity boundaries.
1218 ** During sqlite3_os_init() we do a GetSystemInfo()
1219 ** to get the granularity size.
1220 */
1221 SYSTEM_INFO winSysInfo;
1222 
1223 /*
1224 ** Helper functions to obtain and relinquish the global mutex. The
1225 ** global mutex is used to protect the winLockInfo objects used by
1226 ** this file, all of which may be shared by multiple threads.
1227 **
1228 ** Function winShmMutexHeld() is used to assert() that the global mutex
1229 ** is held when required. This function is only used as part of assert()
1230 ** statements. e.g.
1231 **
1232 **   winShmEnterMutex()
1233 **     assert( winShmMutexHeld() );
1234 **   winShmLeaveMutex()
1235 */
1236 static void winShmEnterMutex(void){
1237   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1238 }
1239 static void winShmLeaveMutex(void){
1240   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1241 }
1242 #ifdef SQLITE_DEBUG
1243 static int winShmMutexHeld(void) {
1244   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1245 }
1246 #endif
1247 
1248 /*
1249 ** Object used to represent a single file opened and mmapped to provide
1250 ** shared memory.  When multiple threads all reference the same
1251 ** log-summary, each thread has its own winFile object, but they all
1252 ** point to a single instance of this object.  In other words, each
1253 ** log-summary is opened only once per process.
1254 **
1255 ** winShmMutexHeld() must be true when creating or destroying
1256 ** this object or while reading or writing the following fields:
1257 **
1258 **      nRef
1259 **      pNext
1260 **
1261 ** The following fields are read-only after the object is created:
1262 **
1263 **      fid
1264 **      zFilename
1265 **
1266 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
1267 ** winShmMutexHeld() is true when reading or writing any other field
1268 ** in this structure.
1269 **
1270 */
1271 struct winShmNode {
1272   sqlite3_mutex *mutex;      /* Mutex to access this object */
1273   char *zFilename;           /* Name of the file */
1274   winFile hFile;             /* File handle from winOpen */
1275 
1276   int szRegion;              /* Size of shared-memory regions */
1277   int nRegion;               /* Size of array apRegion */
1278   struct ShmRegion {
1279     HANDLE hMap;             /* File handle from CreateFileMapping */
1280     void *pMap;
1281   } *aRegion;
1282   DWORD lastErrno;           /* The Windows errno from the last I/O error */
1283 
1284   int nRef;                  /* Number of winShm objects pointing to this */
1285   winShm *pFirst;            /* All winShm objects pointing to this */
1286   winShmNode *pNext;         /* Next in list of all winShmNode objects */
1287 #ifdef SQLITE_DEBUG
1288   u8 nextShmId;              /* Next available winShm.id value */
1289 #endif
1290 };
1291 
1292 /*
1293 ** A global array of all winShmNode objects.
1294 **
1295 ** The winShmMutexHeld() must be true while reading or writing this list.
1296 */
1297 static winShmNode *winShmNodeList = 0;
1298 
1299 /*
1300 ** Structure used internally by this VFS to record the state of an
1301 ** open shared memory connection.
1302 **
1303 ** The following fields are initialized when this object is created and
1304 ** are read-only thereafter:
1305 **
1306 **    winShm.pShmNode
1307 **    winShm.id
1308 **
1309 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
1310 ** while accessing any read/write fields.
1311 */
1312 struct winShm {
1313   winShmNode *pShmNode;      /* The underlying winShmNode object */
1314   winShm *pNext;             /* Next winShm with the same winShmNode */
1315   u8 hasMutex;               /* True if holding the winShmNode mutex */
1316   u16 sharedMask;            /* Mask of shared locks held */
1317   u16 exclMask;              /* Mask of exclusive locks held */
1318 #ifdef SQLITE_DEBUG
1319   u8 id;                     /* Id of this connection with its winShmNode */
1320 #endif
1321 };
1322 
1323 /*
1324 ** Constants used for locking
1325 */
1326 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
1327 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
1328 
1329 /*
1330 ** Apply advisory locks for all n bytes beginning at ofst.
1331 */
1332 #define _SHM_UNLCK  1
1333 #define _SHM_RDLCK  2
1334 #define _SHM_WRLCK  3
1335 static int winShmSystemLock(
1336   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
1337   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
1338   int ofst,             /* Offset to first byte to be locked/unlocked */
1339   int nByte             /* Number of bytes to lock or unlock */
1340 ){
1341   OVERLAPPED ovlp;
1342   DWORD dwFlags;
1343   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
1344 
1345   /* Access to the winShmNode object is serialized by the caller */
1346   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
1347 
1348   /* Initialize the locking parameters */
1349   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
1350   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
1351 
1352   memset(&ovlp, 0, sizeof(OVERLAPPED));
1353   ovlp.Offset = ofst;
1354 
1355   /* Release/Acquire the system-level lock */
1356   if( lockType==_SHM_UNLCK ){
1357     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
1358   }else{
1359     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
1360   }
1361 
1362   if( rc!= 0 ){
1363     rc = SQLITE_OK;
1364   }else{
1365     pFile->lastErrno =  GetLastError();
1366     rc = SQLITE_BUSY;
1367   }
1368 
1369   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
1370            pFile->hFile.h,
1371            rc==SQLITE_OK ? "ok" : "failed",
1372            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
1373            pFile->lastErrno));
1374 
1375   return rc;
1376 }
1377 
1378 /* Forward references to VFS methods */
1379 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
1380 static int winDelete(sqlite3_vfs *,const char*,int);
1381 
1382 /*
1383 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
1384 **
1385 ** This is not a VFS shared-memory method; it is a utility function called
1386 ** by VFS shared-memory methods.
1387 */
1388 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
1389   winShmNode **pp;
1390   winShmNode *p;
1391   BOOL bRc;
1392   assert( winShmMutexHeld() );
1393   pp = &winShmNodeList;
1394   while( (p = *pp)!=0 ){
1395     if( p->nRef==0 ){
1396       int i;
1397       if( p->mutex ) sqlite3_mutex_free(p->mutex);
1398       for(i=0; i<p->nRegion; i++){
1399         bRc = UnmapViewOfFile(p->aRegion[i].pMap);
1400         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
1401                  (int)GetCurrentProcessId(), i,
1402                  bRc ? "ok" : "failed"));
1403         bRc = CloseHandle(p->aRegion[i].hMap);
1404         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
1405                  (int)GetCurrentProcessId(), i,
1406                  bRc ? "ok" : "failed"));
1407       }
1408       if( p->hFile.h != INVALID_HANDLE_VALUE ){
1409         SimulateIOErrorBenign(1);
1410         winClose((sqlite3_file *)&p->hFile);
1411         SimulateIOErrorBenign(0);
1412       }
1413       if( deleteFlag ){
1414         SimulateIOErrorBenign(1);
1415         winDelete(pVfs, p->zFilename, 0);
1416         SimulateIOErrorBenign(0);
1417       }
1418       *pp = p->pNext;
1419       sqlite3_free(p->aRegion);
1420       sqlite3_free(p);
1421     }else{
1422       pp = &p->pNext;
1423     }
1424   }
1425 }
1426 
1427 /*
1428 ** Open the shared-memory area associated with database file pDbFd.
1429 **
1430 ** When opening a new shared-memory file, if no other instances of that
1431 ** file are currently open, in this process or in other processes, then
1432 ** the file must be truncated to zero length or have its header cleared.
1433 */
1434 static int winOpenSharedMemory(winFile *pDbFd){
1435   struct winShm *p;                  /* The connection to be opened */
1436   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
1437   int rc;                            /* Result code */
1438   struct winShmNode *pNew;           /* Newly allocated winShmNode */
1439   int nName;                         /* Size of zName in bytes */
1440 
1441   assert( pDbFd->pShm==0 );    /* Not previously opened */
1442 
1443   /* Allocate space for the new sqlite3_shm object.  Also speculatively
1444   ** allocate space for a new winShmNode and filename.
1445   */
1446   p = sqlite3_malloc( sizeof(*p) );
1447   if( p==0 ) return SQLITE_NOMEM;
1448   memset(p, 0, sizeof(*p));
1449   nName = sqlite3Strlen30(pDbFd->zPath);
1450   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
1451   if( pNew==0 ){
1452     sqlite3_free(p);
1453     return SQLITE_NOMEM;
1454   }
1455   memset(pNew, 0, sizeof(*pNew));
1456   pNew->zFilename = (char*)&pNew[1];
1457   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
1458 
1459   /* Look to see if there is an existing winShmNode that can be used.
1460   ** If no matching winShmNode currently exists, create a new one.
1461   */
1462   winShmEnterMutex();
1463   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
1464     /* TBD need to come up with better match here.  Perhaps
1465     ** use FILE_ID_BOTH_DIR_INFO Structure.
1466     */
1467     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
1468   }
1469   if( pShmNode ){
1470     sqlite3_free(pNew);
1471   }else{
1472     pShmNode = pNew;
1473     pNew = 0;
1474     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
1475     pShmNode->pNext = winShmNodeList;
1476     winShmNodeList = pShmNode;
1477 
1478     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1479     if( pShmNode->mutex==0 ){
1480       rc = SQLITE_NOMEM;
1481       goto shm_open_err;
1482     }
1483 
1484     rc = winOpen(pDbFd->pVfs,
1485                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
1486                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
1487                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
1488                  0);
1489     if( SQLITE_OK!=rc ){
1490       rc = SQLITE_CANTOPEN_BKPT;
1491       goto shm_open_err;
1492     }
1493 
1494     /* Check to see if another process is holding the dead-man switch.
1495     ** If not, truncate the file to zero length.
1496     */
1497     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
1498       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
1499       if( rc!=SQLITE_OK ){
1500         rc = SQLITE_IOERR_SHMOPEN;
1501       }
1502     }
1503     if( rc==SQLITE_OK ){
1504       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
1505       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
1506     }
1507     if( rc ) goto shm_open_err;
1508   }
1509 
1510   /* Make the new connection a child of the winShmNode */
1511   p->pShmNode = pShmNode;
1512 #ifdef SQLITE_DEBUG
1513   p->id = pShmNode->nextShmId++;
1514 #endif
1515   pShmNode->nRef++;
1516   pDbFd->pShm = p;
1517   winShmLeaveMutex();
1518 
1519   /* The reference count on pShmNode has already been incremented under
1520   ** the cover of the winShmEnterMutex() mutex and the pointer from the
1521   ** new (struct winShm) object to the pShmNode has been set. All that is
1522   ** left to do is to link the new object into the linked list starting
1523   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
1524   ** mutex.
1525   */
1526   sqlite3_mutex_enter(pShmNode->mutex);
1527   p->pNext = pShmNode->pFirst;
1528   pShmNode->pFirst = p;
1529   sqlite3_mutex_leave(pShmNode->mutex);
1530   return SQLITE_OK;
1531 
1532   /* Jump here on any error */
1533 shm_open_err:
1534   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
1535   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
1536   sqlite3_free(p);
1537   sqlite3_free(pNew);
1538   winShmLeaveMutex();
1539   return rc;
1540 }
1541 
1542 /*
1543 ** Close a connection to shared-memory.  Delete the underlying
1544 ** storage if deleteFlag is true.
1545 */
1546 static int winShmUnmap(
1547   sqlite3_file *fd,          /* Database holding shared memory */
1548   int deleteFlag             /* Delete after closing if true */
1549 ){
1550   winFile *pDbFd;       /* Database holding shared-memory */
1551   winShm *p;            /* The connection to be closed */
1552   winShmNode *pShmNode; /* The underlying shared-memory file */
1553   winShm **pp;          /* For looping over sibling connections */
1554 
1555   pDbFd = (winFile*)fd;
1556   p = pDbFd->pShm;
1557   if( p==0 ) return SQLITE_OK;
1558   pShmNode = p->pShmNode;
1559 
1560   /* Remove connection p from the set of connections associated
1561   ** with pShmNode */
1562   sqlite3_mutex_enter(pShmNode->mutex);
1563   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
1564   *pp = p->pNext;
1565 
1566   /* Free the connection p */
1567   sqlite3_free(p);
1568   pDbFd->pShm = 0;
1569   sqlite3_mutex_leave(pShmNode->mutex);
1570 
1571   /* If pShmNode->nRef has reached 0, then close the underlying
1572   ** shared-memory file, too */
1573   winShmEnterMutex();
1574   assert( pShmNode->nRef>0 );
1575   pShmNode->nRef--;
1576   if( pShmNode->nRef==0 ){
1577     winShmPurge(pDbFd->pVfs, deleteFlag);
1578   }
1579   winShmLeaveMutex();
1580 
1581   return SQLITE_OK;
1582 }
1583 
1584 /*
1585 ** Change the lock state for a shared-memory segment.
1586 */
1587 static int winShmLock(
1588   sqlite3_file *fd,          /* Database file holding the shared memory */
1589   int ofst,                  /* First lock to acquire or release */
1590   int n,                     /* Number of locks to acquire or release */
1591   int flags                  /* What to do with the lock */
1592 ){
1593   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
1594   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
1595   winShm *pX;                           /* For looping over all siblings */
1596   winShmNode *pShmNode = p->pShmNode;
1597   int rc = SQLITE_OK;                   /* Result code */
1598   u16 mask;                             /* Mask of locks to take or release */
1599 
1600   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
1601   assert( n>=1 );
1602   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
1603        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
1604        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
1605        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
1606   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
1607 
1608   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
1609   assert( n>1 || mask==(1<<ofst) );
1610   sqlite3_mutex_enter(pShmNode->mutex);
1611   if( flags & SQLITE_SHM_UNLOCK ){
1612     u16 allMask = 0; /* Mask of locks held by siblings */
1613 
1614     /* See if any siblings hold this same lock */
1615     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
1616       if( pX==p ) continue;
1617       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
1618       allMask |= pX->sharedMask;
1619     }
1620 
1621     /* Unlock the system-level locks */
1622     if( (mask & allMask)==0 ){
1623       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
1624     }else{
1625       rc = SQLITE_OK;
1626     }
1627 
1628     /* Undo the local locks */
1629     if( rc==SQLITE_OK ){
1630       p->exclMask &= ~mask;
1631       p->sharedMask &= ~mask;
1632     }
1633   }else if( flags & SQLITE_SHM_SHARED ){
1634     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
1635 
1636     /* Find out which shared locks are already held by sibling connections.
1637     ** If any sibling already holds an exclusive lock, go ahead and return
1638     ** SQLITE_BUSY.
1639     */
1640     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
1641       if( (pX->exclMask & mask)!=0 ){
1642         rc = SQLITE_BUSY;
1643         break;
1644       }
1645       allShared |= pX->sharedMask;
1646     }
1647 
1648     /* Get shared locks at the system level, if necessary */
1649     if( rc==SQLITE_OK ){
1650       if( (allShared & mask)==0 ){
1651         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
1652       }else{
1653         rc = SQLITE_OK;
1654       }
1655     }
1656 
1657     /* Get the local shared locks */
1658     if( rc==SQLITE_OK ){
1659       p->sharedMask |= mask;
1660     }
1661   }else{
1662     /* Make sure no sibling connections hold locks that will block this
1663     ** lock.  If any do, return SQLITE_BUSY right away.
1664     */
1665     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
1666       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
1667         rc = SQLITE_BUSY;
1668         break;
1669       }
1670     }
1671 
1672     /* Get the exclusive locks at the system level.  Then if successful
1673     ** also mark the local connection as being locked.
1674     */
1675     if( rc==SQLITE_OK ){
1676       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
1677       if( rc==SQLITE_OK ){
1678         assert( (p->sharedMask & mask)==0 );
1679         p->exclMask |= mask;
1680       }
1681     }
1682   }
1683   sqlite3_mutex_leave(pShmNode->mutex);
1684   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
1685            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
1686            rc ? "failed" : "ok"));
1687   return rc;
1688 }
1689 
1690 /*
1691 ** Implement a memory barrier or memory fence on shared memory.
1692 **
1693 ** All loads and stores begun before the barrier must complete before
1694 ** any load or store begun after the barrier.
1695 */
1696 static void winShmBarrier(
1697   sqlite3_file *fd          /* Database holding the shared memory */
1698 ){
1699   UNUSED_PARAMETER(fd);
1700   /* MemoryBarrier(); // does not work -- do not know why not */
1701   winShmEnterMutex();
1702   winShmLeaveMutex();
1703 }
1704 
1705 /*
1706 ** This function is called to obtain a pointer to region iRegion of the
1707 ** shared-memory associated with the database file fd. Shared-memory regions
1708 ** are numbered starting from zero. Each shared-memory region is szRegion
1709 ** bytes in size.
1710 **
1711 ** If an error occurs, an error code is returned and *pp is set to NULL.
1712 **
1713 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
1714 ** region has not been allocated (by any client, including one running in a
1715 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
1716 ** isWrite is non-zero and the requested shared-memory region has not yet
1717 ** been allocated, it is allocated by this function.
1718 **
1719 ** If the shared-memory region has already been allocated or is allocated by
1720 ** this call as described above, then it is mapped into this processes
1721 ** address space (if it is not already), *pp is set to point to the mapped
1722 ** memory and SQLITE_OK returned.
1723 */
1724 static int winShmMap(
1725   sqlite3_file *fd,               /* Handle open on database file */
1726   int iRegion,                    /* Region to retrieve */
1727   int szRegion,                   /* Size of regions */
1728   int isWrite,                    /* True to extend file if necessary */
1729   void volatile **pp              /* OUT: Mapped memory */
1730 ){
1731   winFile *pDbFd = (winFile*)fd;
1732   winShm *p = pDbFd->pShm;
1733   winShmNode *pShmNode;
1734   int rc = SQLITE_OK;
1735 
1736   if( !p ){
1737     rc = winOpenSharedMemory(pDbFd);
1738     if( rc!=SQLITE_OK ) return rc;
1739     p = pDbFd->pShm;
1740   }
1741   pShmNode = p->pShmNode;
1742 
1743   sqlite3_mutex_enter(pShmNode->mutex);
1744   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
1745 
1746   if( pShmNode->nRegion<=iRegion ){
1747     struct ShmRegion *apNew;           /* New aRegion[] array */
1748     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
1749     sqlite3_int64 sz;                  /* Current size of wal-index file */
1750 
1751     pShmNode->szRegion = szRegion;
1752 
1753     /* The requested region is not mapped into this processes address space.
1754     ** Check to see if it has been allocated (i.e. if the wal-index file is
1755     ** large enough to contain the requested region).
1756     */
1757     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
1758     if( rc!=SQLITE_OK ){
1759       rc = SQLITE_IOERR_SHMSIZE;
1760       goto shmpage_out;
1761     }
1762 
1763     if( sz<nByte ){
1764       /* The requested memory region does not exist. If isWrite is set to
1765       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
1766       **
1767       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
1768       ** the requested memory region.
1769       */
1770       if( !isWrite ) goto shmpage_out;
1771       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
1772       if( rc!=SQLITE_OK ){
1773         rc = SQLITE_IOERR_SHMSIZE;
1774         goto shmpage_out;
1775       }
1776     }
1777 
1778     /* Map the requested memory region into this processes address space. */
1779     apNew = (struct ShmRegion *)sqlite3_realloc(
1780         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
1781     );
1782     if( !apNew ){
1783       rc = SQLITE_IOERR_NOMEM;
1784       goto shmpage_out;
1785     }
1786     pShmNode->aRegion = apNew;
1787 
1788     while( pShmNode->nRegion<=iRegion ){
1789       HANDLE hMap;                /* file-mapping handle */
1790       void *pMap = 0;             /* Mapped memory region */
1791 
1792       hMap = CreateFileMapping(pShmNode->hFile.h,
1793           NULL, PAGE_READWRITE, 0, nByte, NULL
1794       );
1795       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
1796                (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
1797                hMap ? "ok" : "failed"));
1798       if( hMap ){
1799         int iOffset = pShmNode->nRegion*szRegion;
1800         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
1801         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
1802             0, iOffset - iOffsetShift, szRegion + iOffsetShift
1803         );
1804         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
1805                  (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
1806                  pMap ? "ok" : "failed"));
1807       }
1808       if( !pMap ){
1809         pShmNode->lastErrno = GetLastError();
1810         rc = SQLITE_IOERR;
1811         if( hMap ) CloseHandle(hMap);
1812         goto shmpage_out;
1813       }
1814 
1815       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
1816       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
1817       pShmNode->nRegion++;
1818     }
1819   }
1820 
1821 shmpage_out:
1822   if( pShmNode->nRegion>iRegion ){
1823     int iOffset = iRegion*szRegion;
1824     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
1825     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
1826     *pp = (void *)&p[iOffsetShift];
1827   }else{
1828     *pp = 0;
1829   }
1830   sqlite3_mutex_leave(pShmNode->mutex);
1831   return rc;
1832 }
1833 
1834 #else
1835 # define winShmMap     0
1836 # define winShmLock    0
1837 # define winShmBarrier 0
1838 # define winShmUnmap   0
1839 #endif /* #ifndef SQLITE_OMIT_WAL */
1840 
1841 /*
1842 ** Here ends the implementation of all sqlite3_file methods.
1843 **
1844 ********************** End sqlite3_file Methods *******************************
1845 ******************************************************************************/
1846 
1847 /*
1848 ** This vector defines all the methods that can operate on an
1849 ** sqlite3_file for win32.
1850 */
1851 static const sqlite3_io_methods winIoMethod = {
1852   2,                              /* iVersion */
1853   winClose,                       /* xClose */
1854   winRead,                        /* xRead */
1855   winWrite,                       /* xWrite */
1856   winTruncate,                    /* xTruncate */
1857   winSync,                        /* xSync */
1858   winFileSize,                    /* xFileSize */
1859   winLock,                        /* xLock */
1860   winUnlock,                      /* xUnlock */
1861   winCheckReservedLock,           /* xCheckReservedLock */
1862   winFileControl,                 /* xFileControl */
1863   winSectorSize,                  /* xSectorSize */
1864   winDeviceCharacteristics,       /* xDeviceCharacteristics */
1865   winShmMap,                      /* xShmMap */
1866   winShmLock,                     /* xShmLock */
1867   winShmBarrier,                  /* xShmBarrier */
1868   winShmUnmap                     /* xShmUnmap */
1869 };
1870 
1871 /****************************************************************************
1872 **************************** sqlite3_vfs methods ****************************
1873 **
1874 ** This division contains the implementation of methods on the
1875 ** sqlite3_vfs object.
1876 */
1877 
1878 /*
1879 ** Convert a UTF-8 filename into whatever form the underlying
1880 ** operating system wants filenames in.  Space to hold the result
1881 ** is obtained from malloc and must be freed by the calling
1882 ** function.
1883 */
1884 static void *convertUtf8Filename(const char *zFilename){
1885   void *zConverted = 0;
1886   if( isNT() ){
1887     zConverted = utf8ToUnicode(zFilename);
1888 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1889 */
1890 #if SQLITE_OS_WINCE==0
1891   }else{
1892     zConverted = utf8ToMbcs(zFilename);
1893 #endif
1894   }
1895   /* caller will handle out of memory */
1896   return zConverted;
1897 }
1898 
1899 /*
1900 ** Create a temporary file name in zBuf.  zBuf must be big enough to
1901 ** hold at pVfs->mxPathname characters.
1902 */
1903 static int getTempname(int nBuf, char *zBuf){
1904   static char zChars[] =
1905     "abcdefghijklmnopqrstuvwxyz"
1906     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1907     "0123456789";
1908   size_t i, j;
1909   char zTempPath[MAX_PATH+1];
1910 
1911   /* It's odd to simulate an io-error here, but really this is just
1912   ** using the io-error infrastructure to test that SQLite handles this
1913   ** function failing.
1914   */
1915   SimulateIOError( return SQLITE_IOERR );
1916 
1917   if( sqlite3_temp_directory ){
1918     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
1919   }else if( isNT() ){
1920     char *zMulti;
1921     WCHAR zWidePath[MAX_PATH];
1922     GetTempPathW(MAX_PATH-30, zWidePath);
1923     zMulti = unicodeToUtf8(zWidePath);
1924     if( zMulti ){
1925       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
1926       free(zMulti);
1927     }else{
1928       return SQLITE_NOMEM;
1929     }
1930 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1931 ** Since the ASCII version of these Windows API do not exist for WINCE,
1932 ** it's important to not reference them for WINCE builds.
1933 */
1934 #if SQLITE_OS_WINCE==0
1935   }else{
1936     char *zUtf8;
1937     char zMbcsPath[MAX_PATH];
1938     GetTempPathA(MAX_PATH-30, zMbcsPath);
1939     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
1940     if( zUtf8 ){
1941       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
1942       free(zUtf8);
1943     }else{
1944       return SQLITE_NOMEM;
1945     }
1946 #endif
1947   }
1948 
1949   /* Check that the output buffer is large enough for the temporary file
1950   ** name. If it is not, return SQLITE_ERROR.
1951   */
1952   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
1953     return SQLITE_ERROR;
1954   }
1955 
1956   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
1957   zTempPath[i] = 0;
1958 
1959   sqlite3_snprintf(nBuf-17, zBuf,
1960                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
1961   j = sqlite3Strlen30(zBuf);
1962   sqlite3_randomness(15, &zBuf[j]);
1963   for(i=0; i<15; i++, j++){
1964     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
1965   }
1966   zBuf[j] = 0;
1967 
1968   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
1969   return SQLITE_OK;
1970 }
1971 
1972 /*
1973 ** The return value of getLastErrorMsg
1974 ** is zero if the error message fits in the buffer, or non-zero
1975 ** otherwise (if the message was truncated).
1976 */
1977 static int getLastErrorMsg(int nBuf, char *zBuf){
1978   /* FormatMessage returns 0 on failure.  Otherwise it
1979   ** returns the number of TCHARs written to the output
1980   ** buffer, excluding the terminating null char.
1981   */
1982   DWORD error = GetLastError();
1983   DWORD dwLen = 0;
1984   char *zOut = 0;
1985 
1986   if( isNT() ){
1987     WCHAR *zTempWide = NULL;
1988     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1989                            NULL,
1990                            error,
1991                            0,
1992                            (LPWSTR) &zTempWide,
1993                            0,
1994                            0);
1995     if( dwLen > 0 ){
1996       /* allocate a buffer and convert to UTF8 */
1997       zOut = unicodeToUtf8(zTempWide);
1998       /* free the system buffer allocated by FormatMessage */
1999       LocalFree(zTempWide);
2000     }
2001 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2002 ** Since the ASCII version of these Windows API do not exist for WINCE,
2003 ** it's important to not reference them for WINCE builds.
2004 */
2005 #if SQLITE_OS_WINCE==0
2006   }else{
2007     char *zTemp = NULL;
2008     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
2009                            NULL,
2010                            error,
2011                            0,
2012                            (LPSTR) &zTemp,
2013                            0,
2014                            0);
2015     if( dwLen > 0 ){
2016       /* allocate a buffer and convert to UTF8 */
2017       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
2018       /* free the system buffer allocated by FormatMessage */
2019       LocalFree(zTemp);
2020     }
2021 #endif
2022   }
2023   if( 0 == dwLen ){
2024     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
2025   }else{
2026     /* copy a maximum of nBuf chars to output buffer */
2027     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
2028     /* free the UTF8 buffer */
2029     free(zOut);
2030   }
2031   return 0;
2032 }
2033 
2034 /*
2035 ** Open a file.
2036 */
2037 static int winOpen(
2038   sqlite3_vfs *pVfs,        /* Not used */
2039   const char *zName,        /* Name of the file (UTF-8) */
2040   sqlite3_file *id,         /* Write the SQLite file handle here */
2041   int flags,                /* Open mode flags */
2042   int *pOutFlags            /* Status return flags */
2043 ){
2044   HANDLE h;
2045   DWORD dwDesiredAccess;
2046   DWORD dwShareMode;
2047   DWORD dwCreationDisposition;
2048   DWORD dwFlagsAndAttributes = 0;
2049 #if SQLITE_OS_WINCE
2050   int isTemp = 0;
2051 #endif
2052   winFile *pFile = (winFile*)id;
2053   void *zConverted;              /* Filename in OS encoding */
2054   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
2055 
2056   /* If argument zPath is a NULL pointer, this function is required to open
2057   ** a temporary file. Use this buffer to store the file name in.
2058   */
2059   char zTmpname[MAX_PATH+1];     /* Buffer used to create temp filename */
2060 
2061   int rc = SQLITE_OK;            /* Function Return Code */
2062 #if !defined(NDEBUG) || SQLITE_OS_WINCE
2063   int eType = flags&0xFFFFFF00;  /* Type of file to open */
2064 #endif
2065 
2066   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
2067   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
2068   int isCreate     = (flags & SQLITE_OPEN_CREATE);
2069 #ifndef NDEBUG
2070   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
2071 #endif
2072   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
2073 
2074 #ifndef NDEBUG
2075   int isOpenJournal = (isCreate && (
2076         eType==SQLITE_OPEN_MASTER_JOURNAL
2077      || eType==SQLITE_OPEN_MAIN_JOURNAL
2078      || eType==SQLITE_OPEN_WAL
2079   ));
2080 #endif
2081 
2082   /* Check the following statements are true:
2083   **
2084   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
2085   **   (b) if CREATE is set, then READWRITE must also be set, and
2086   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
2087   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
2088   */
2089   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
2090   assert(isCreate==0 || isReadWrite);
2091   assert(isExclusive==0 || isCreate);
2092   assert(isDelete==0 || isCreate);
2093 
2094   /* The main DB, main journal, WAL file and master journal are never
2095   ** automatically deleted. Nor are they ever temporary files.  */
2096   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
2097   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
2098   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
2099   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
2100 
2101   /* Assert that the upper layer has set one of the "file-type" flags. */
2102   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
2103        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
2104        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
2105        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
2106   );
2107 
2108   assert( id!=0 );
2109   UNUSED_PARAMETER(pVfs);
2110 
2111   pFile->h = INVALID_HANDLE_VALUE;
2112 
2113   /* If the second argument to this function is NULL, generate a
2114   ** temporary file name to use
2115   */
2116   if( !zUtf8Name ){
2117     assert(isDelete && !isOpenJournal);
2118     rc = getTempname(MAX_PATH+1, zTmpname);
2119     if( rc!=SQLITE_OK ){
2120       return rc;
2121     }
2122     zUtf8Name = zTmpname;
2123   }
2124 
2125   /* Convert the filename to the system encoding. */
2126   zConverted = convertUtf8Filename(zUtf8Name);
2127   if( zConverted==0 ){
2128     return SQLITE_NOMEM;
2129   }
2130 
2131   if( isReadWrite ){
2132     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
2133   }else{
2134     dwDesiredAccess = GENERIC_READ;
2135   }
2136 
2137   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
2138   ** created. SQLite doesn't use it to indicate "exclusive access"
2139   ** as it is usually understood.
2140   */
2141   if( isExclusive ){
2142     /* Creates a new file, only if it does not already exist. */
2143     /* If the file exists, it fails. */
2144     dwCreationDisposition = CREATE_NEW;
2145   }else if( isCreate ){
2146     /* Open existing file, or create if it doesn't exist */
2147     dwCreationDisposition = OPEN_ALWAYS;
2148   }else{
2149     /* Opens a file, only if it exists. */
2150     dwCreationDisposition = OPEN_EXISTING;
2151   }
2152 
2153   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
2154 
2155   if( isDelete ){
2156 #if SQLITE_OS_WINCE
2157     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
2158     isTemp = 1;
2159 #else
2160     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
2161                                | FILE_ATTRIBUTE_HIDDEN
2162                                | FILE_FLAG_DELETE_ON_CLOSE;
2163 #endif
2164   }else{
2165     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
2166   }
2167   /* Reports from the internet are that performance is always
2168   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
2169 #if SQLITE_OS_WINCE
2170   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
2171 #endif
2172 
2173   if( isNT() ){
2174     h = CreateFileW((WCHAR*)zConverted,
2175        dwDesiredAccess,
2176        dwShareMode,
2177        NULL,
2178        dwCreationDisposition,
2179        dwFlagsAndAttributes,
2180        NULL
2181     );
2182 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2183 ** Since the ASCII version of these Windows API do not exist for WINCE,
2184 ** it's important to not reference them for WINCE builds.
2185 */
2186 #if SQLITE_OS_WINCE==0
2187   }else{
2188     h = CreateFileA((char*)zConverted,
2189        dwDesiredAccess,
2190        dwShareMode,
2191        NULL,
2192        dwCreationDisposition,
2193        dwFlagsAndAttributes,
2194        NULL
2195     );
2196 #endif
2197   }
2198 
2199   OSTRACE(("OPEN %d %s 0x%lx %s\n",
2200            h, zName, dwDesiredAccess,
2201            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
2202 
2203   if( h==INVALID_HANDLE_VALUE ){
2204     pFile->lastErrno = GetLastError();
2205     free(zConverted);
2206     if( isReadWrite ){
2207       return winOpen(pVfs, zName, id,
2208              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
2209     }else{
2210       return SQLITE_CANTOPEN_BKPT;
2211     }
2212   }
2213 
2214   if( pOutFlags ){
2215     if( isReadWrite ){
2216       *pOutFlags = SQLITE_OPEN_READWRITE;
2217     }else{
2218       *pOutFlags = SQLITE_OPEN_READONLY;
2219     }
2220   }
2221 
2222   memset(pFile, 0, sizeof(*pFile));
2223   pFile->pMethod = &winIoMethod;
2224   pFile->h = h;
2225   pFile->lastErrno = NO_ERROR;
2226   pFile->pVfs = pVfs;
2227   pFile->pShm = 0;
2228   pFile->zPath = zName;
2229   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
2230 
2231 #if SQLITE_OS_WINCE
2232   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
2233        && !winceCreateLock(zName, pFile)
2234   ){
2235     CloseHandle(h);
2236     free(zConverted);
2237     return SQLITE_CANTOPEN_BKPT;
2238   }
2239   if( isTemp ){
2240     pFile->zDeleteOnClose = zConverted;
2241   }else
2242 #endif
2243   {
2244     free(zConverted);
2245   }
2246 
2247   OpenCounter(+1);
2248   return rc;
2249 }
2250 
2251 /*
2252 ** Delete the named file.
2253 **
2254 ** Note that windows does not allow a file to be deleted if some other
2255 ** process has it open.  Sometimes a virus scanner or indexing program
2256 ** will open a journal file shortly after it is created in order to do
2257 ** whatever it does.  While this other process is holding the
2258 ** file open, we will be unable to delete it.  To work around this
2259 ** problem, we delay 100 milliseconds and try to delete again.  Up
2260 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
2261 ** up and returning an error.
2262 */
2263 #define MX_DELETION_ATTEMPTS 5
2264 static int winDelete(
2265   sqlite3_vfs *pVfs,          /* Not used on win32 */
2266   const char *zFilename,      /* Name of file to delete */
2267   int syncDir                 /* Not used on win32 */
2268 ){
2269   int cnt = 0;
2270   DWORD rc;
2271   DWORD error = 0;
2272   void *zConverted;
2273   UNUSED_PARAMETER(pVfs);
2274   UNUSED_PARAMETER(syncDir);
2275 
2276   SimulateIOError(return SQLITE_IOERR_DELETE);
2277   zConverted = convertUtf8Filename(zFilename);
2278   if( zConverted==0 ){
2279     return SQLITE_NOMEM;
2280   }
2281   if( isNT() ){
2282     do{
2283       DeleteFileW(zConverted);
2284     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
2285                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
2286            && (++cnt < MX_DELETION_ATTEMPTS)
2287            && (Sleep(100), 1) );
2288 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2289 ** Since the ASCII version of these Windows API do not exist for WINCE,
2290 ** it's important to not reference them for WINCE builds.
2291 */
2292 #if SQLITE_OS_WINCE==0
2293   }else{
2294     do{
2295       DeleteFileA(zConverted);
2296     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
2297                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
2298            && (++cnt < MX_DELETION_ATTEMPTS)
2299            && (Sleep(100), 1) );
2300 #endif
2301   }
2302   free(zConverted);
2303   OSTRACE(("DELETE \"%s\" %s\n", zFilename,
2304        ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
2305          "ok" : "failed" ));
2306 
2307   return (   (rc == INVALID_FILE_ATTRIBUTES)
2308           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
2309 }
2310 
2311 /*
2312 ** Check the existance and status of a file.
2313 */
2314 static int winAccess(
2315   sqlite3_vfs *pVfs,         /* Not used on win32 */
2316   const char *zFilename,     /* Name of file to check */
2317   int flags,                 /* Type of test to make on this file */
2318   int *pResOut               /* OUT: Result */
2319 ){
2320   DWORD attr;
2321   int rc = 0;
2322   void *zConverted;
2323   UNUSED_PARAMETER(pVfs);
2324 
2325   SimulateIOError( return SQLITE_IOERR_ACCESS; );
2326   zConverted = convertUtf8Filename(zFilename);
2327   if( zConverted==0 ){
2328     return SQLITE_NOMEM;
2329   }
2330   if( isNT() ){
2331     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
2332     memset(&sAttrData, 0, sizeof(sAttrData));
2333     if( GetFileAttributesExW((WCHAR*)zConverted,
2334                              GetFileExInfoStandard,
2335                              &sAttrData) ){
2336       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
2337       ** as if it does not exist.
2338       */
2339       if(    flags==SQLITE_ACCESS_EXISTS
2340           && sAttrData.nFileSizeHigh==0
2341           && sAttrData.nFileSizeLow==0 ){
2342         attr = INVALID_FILE_ATTRIBUTES;
2343       }else{
2344         attr = sAttrData.dwFileAttributes;
2345       }
2346     }else{
2347       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
2348         free(zConverted);
2349         return SQLITE_IOERR_ACCESS;
2350       }else{
2351         attr = INVALID_FILE_ATTRIBUTES;
2352       }
2353     }
2354 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2355 ** Since the ASCII version of these Windows API do not exist for WINCE,
2356 ** it's important to not reference them for WINCE builds.
2357 */
2358 #if SQLITE_OS_WINCE==0
2359   }else{
2360     attr = GetFileAttributesA((char*)zConverted);
2361 #endif
2362   }
2363   free(zConverted);
2364   switch( flags ){
2365     case SQLITE_ACCESS_READ:
2366     case SQLITE_ACCESS_EXISTS:
2367       rc = attr!=INVALID_FILE_ATTRIBUTES;
2368       break;
2369     case SQLITE_ACCESS_READWRITE:
2370       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
2371       break;
2372     default:
2373       assert(!"Invalid flags argument");
2374   }
2375   *pResOut = rc;
2376   return SQLITE_OK;
2377 }
2378 
2379 
2380 /*
2381 ** Turn a relative pathname into a full pathname.  Write the full
2382 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
2383 ** bytes in size.
2384 */
2385 static int winFullPathname(
2386   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
2387   const char *zRelative,        /* Possibly relative input path */
2388   int nFull,                    /* Size of output buffer in bytes */
2389   char *zFull                   /* Output buffer */
2390 ){
2391 
2392 #if defined(__CYGWIN__)
2393   SimulateIOError( return SQLITE_ERROR );
2394   UNUSED_PARAMETER(nFull);
2395   cygwin_conv_to_full_win32_path(zRelative, zFull);
2396   return SQLITE_OK;
2397 #endif
2398 
2399 #if SQLITE_OS_WINCE
2400   SimulateIOError( return SQLITE_ERROR );
2401   UNUSED_PARAMETER(nFull);
2402   /* WinCE has no concept of a relative pathname, or so I am told. */
2403   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
2404   return SQLITE_OK;
2405 #endif
2406 
2407 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
2408   int nByte;
2409   void *zConverted;
2410   char *zOut;
2411 
2412   /* It's odd to simulate an io-error here, but really this is just
2413   ** using the io-error infrastructure to test that SQLite handles this
2414   ** function failing. This function could fail if, for example, the
2415   ** current working directory has been unlinked.
2416   */
2417   SimulateIOError( return SQLITE_ERROR );
2418   UNUSED_PARAMETER(nFull);
2419   zConverted = convertUtf8Filename(zRelative);
2420   if( isNT() ){
2421     WCHAR *zTemp;
2422     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
2423     zTemp = malloc( nByte*sizeof(zTemp[0]) );
2424     if( zTemp==0 ){
2425       free(zConverted);
2426       return SQLITE_NOMEM;
2427     }
2428     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
2429     free(zConverted);
2430     zOut = unicodeToUtf8(zTemp);
2431     free(zTemp);
2432 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2433 ** Since the ASCII version of these Windows API do not exist for WINCE,
2434 ** it's important to not reference them for WINCE builds.
2435 */
2436 #if SQLITE_OS_WINCE==0
2437   }else{
2438     char *zTemp;
2439     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
2440     zTemp = malloc( nByte*sizeof(zTemp[0]) );
2441     if( zTemp==0 ){
2442       free(zConverted);
2443       return SQLITE_NOMEM;
2444     }
2445     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
2446     free(zConverted);
2447     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
2448     free(zTemp);
2449 #endif
2450   }
2451   if( zOut ){
2452     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
2453     free(zOut);
2454     return SQLITE_OK;
2455   }else{
2456     return SQLITE_NOMEM;
2457   }
2458 #endif
2459 }
2460 
2461 /*
2462 ** Get the sector size of the device used to store
2463 ** file.
2464 */
2465 static int getSectorSize(
2466     sqlite3_vfs *pVfs,
2467     const char *zRelative     /* UTF-8 file name */
2468 ){
2469   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
2470   /* GetDiskFreeSpace is not supported under WINCE */
2471 #if SQLITE_OS_WINCE
2472   UNUSED_PARAMETER(pVfs);
2473   UNUSED_PARAMETER(zRelative);
2474 #else
2475   char zFullpath[MAX_PATH+1];
2476   int rc;
2477   DWORD dwRet = 0;
2478   DWORD dwDummy;
2479 
2480   /*
2481   ** We need to get the full path name of the file
2482   ** to get the drive letter to look up the sector
2483   ** size.
2484   */
2485   SimulateIOErrorBenign(1);
2486   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
2487   SimulateIOErrorBenign(0);
2488   if( rc == SQLITE_OK )
2489   {
2490     void *zConverted = convertUtf8Filename(zFullpath);
2491     if( zConverted ){
2492       if( isNT() ){
2493         /* trim path to just drive reference */
2494         WCHAR *p = zConverted;
2495         for(;*p;p++){
2496           if( *p == '\\' ){
2497             *p = '\0';
2498             break;
2499           }
2500         }
2501         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
2502                                   &dwDummy,
2503                                   &bytesPerSector,
2504                                   &dwDummy,
2505                                   &dwDummy);
2506       }else{
2507         /* trim path to just drive reference */
2508         char *p = (char *)zConverted;
2509         for(;*p;p++){
2510           if( *p == '\\' ){
2511             *p = '\0';
2512             break;
2513           }
2514         }
2515         dwRet = GetDiskFreeSpaceA((char*)zConverted,
2516                                   &dwDummy,
2517                                   &bytesPerSector,
2518                                   &dwDummy,
2519                                   &dwDummy);
2520       }
2521       free(zConverted);
2522     }
2523     if( !dwRet ){
2524       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
2525     }
2526   }
2527 #endif
2528   return (int) bytesPerSector;
2529 }
2530 
2531 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2532 /*
2533 ** Interfaces for opening a shared library, finding entry points
2534 ** within the shared library, and closing the shared library.
2535 */
2536 /*
2537 ** Interfaces for opening a shared library, finding entry points
2538 ** within the shared library, and closing the shared library.
2539 */
2540 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
2541   HANDLE h;
2542   void *zConverted = convertUtf8Filename(zFilename);
2543   UNUSED_PARAMETER(pVfs);
2544   if( zConverted==0 ){
2545     return 0;
2546   }
2547   if( isNT() ){
2548     h = LoadLibraryW((WCHAR*)zConverted);
2549 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2550 ** Since the ASCII version of these Windows API do not exist for WINCE,
2551 ** it's important to not reference them for WINCE builds.
2552 */
2553 #if SQLITE_OS_WINCE==0
2554   }else{
2555     h = LoadLibraryA((char*)zConverted);
2556 #endif
2557   }
2558   free(zConverted);
2559   return (void*)h;
2560 }
2561 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
2562   UNUSED_PARAMETER(pVfs);
2563   getLastErrorMsg(nBuf, zBufOut);
2564 }
2565 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
2566   UNUSED_PARAMETER(pVfs);
2567 #if SQLITE_OS_WINCE
2568   /* The GetProcAddressA() routine is only available on wince. */
2569   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
2570 #else
2571   /* All other windows platforms expect GetProcAddress() to take
2572   ** an Ansi string regardless of the _UNICODE setting */
2573   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
2574 #endif
2575 }
2576 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
2577   UNUSED_PARAMETER(pVfs);
2578   FreeLibrary((HANDLE)pHandle);
2579 }
2580 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
2581   #define winDlOpen  0
2582   #define winDlError 0
2583   #define winDlSym   0
2584   #define winDlClose 0
2585 #endif
2586 
2587 
2588 /*
2589 ** Write up to nBuf bytes of randomness into zBuf.
2590 */
2591 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
2592   int n = 0;
2593   UNUSED_PARAMETER(pVfs);
2594 #if defined(SQLITE_TEST)
2595   n = nBuf;
2596   memset(zBuf, 0, nBuf);
2597 #else
2598   if( sizeof(SYSTEMTIME)<=nBuf-n ){
2599     SYSTEMTIME x;
2600     GetSystemTime(&x);
2601     memcpy(&zBuf[n], &x, sizeof(x));
2602     n += sizeof(x);
2603   }
2604   if( sizeof(DWORD)<=nBuf-n ){
2605     DWORD pid = GetCurrentProcessId();
2606     memcpy(&zBuf[n], &pid, sizeof(pid));
2607     n += sizeof(pid);
2608   }
2609   if( sizeof(DWORD)<=nBuf-n ){
2610     DWORD cnt = GetTickCount();
2611     memcpy(&zBuf[n], &cnt, sizeof(cnt));
2612     n += sizeof(cnt);
2613   }
2614   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
2615     LARGE_INTEGER i;
2616     QueryPerformanceCounter(&i);
2617     memcpy(&zBuf[n], &i, sizeof(i));
2618     n += sizeof(i);
2619   }
2620 #endif
2621   return n;
2622 }
2623 
2624 
2625 /*
2626 ** Sleep for a little while.  Return the amount of time slept.
2627 */
2628 static int winSleep(sqlite3_vfs *pVfs, int microsec){
2629   Sleep((microsec+999)/1000);
2630   UNUSED_PARAMETER(pVfs);
2631   return ((microsec+999)/1000)*1000;
2632 }
2633 
2634 /*
2635 ** The following variable, if set to a non-zero value, is interpreted as
2636 ** the number of seconds since 1970 and is used to set the result of
2637 ** sqlite3OsCurrentTime() during testing.
2638 */
2639 #ifdef SQLITE_TEST
2640 int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
2641 #endif
2642 
2643 /*
2644 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
2645 ** the current time and date as a Julian Day number times 86_400_000.  In
2646 ** other words, write into *piNow the number of milliseconds since the Julian
2647 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
2648 ** proleptic Gregorian calendar.
2649 **
2650 ** On success, return 0.  Return 1 if the time and date cannot be found.
2651 */
2652 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
2653   /* FILETIME structure is a 64-bit value representing the number of
2654      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
2655   */
2656   FILETIME ft;
2657   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
2658 #ifdef SQLITE_TEST
2659   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
2660 #endif
2661   /* 2^32 - to avoid use of LL and warnings in gcc */
2662   static const sqlite3_int64 max32BitValue =
2663       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
2664 
2665 #if SQLITE_OS_WINCE
2666   SYSTEMTIME time;
2667   GetSystemTime(&time);
2668   /* if SystemTimeToFileTime() fails, it returns zero. */
2669   if (!SystemTimeToFileTime(&time,&ft)){
2670     return 1;
2671   }
2672 #else
2673   GetSystemTimeAsFileTime( &ft );
2674 #endif
2675 
2676   *piNow = winFiletimeEpoch +
2677             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
2678                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
2679 
2680 #ifdef SQLITE_TEST
2681   if( sqlite3_current_time ){
2682     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
2683   }
2684 #endif
2685   UNUSED_PARAMETER(pVfs);
2686   return 0;
2687 }
2688 
2689 /*
2690 ** Find the current time (in Universal Coordinated Time).  Write the
2691 ** current time and date as a Julian Day number into *prNow and
2692 ** return 0.  Return 1 if the time and date cannot be found.
2693 */
2694 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
2695   int rc;
2696   sqlite3_int64 i;
2697   rc = winCurrentTimeInt64(pVfs, &i);
2698   if( !rc ){
2699     *prNow = i/86400000.0;
2700   }
2701   return rc;
2702 }
2703 
2704 /*
2705 ** The idea is that this function works like a combination of
2706 ** GetLastError() and FormatMessage() on windows (or errno and
2707 ** strerror_r() on unix). After an error is returned by an OS
2708 ** function, SQLite calls this function with zBuf pointing to
2709 ** a buffer of nBuf bytes. The OS layer should populate the
2710 ** buffer with a nul-terminated UTF-8 encoded error message
2711 ** describing the last IO error to have occurred within the calling
2712 ** thread.
2713 **
2714 ** If the error message is too large for the supplied buffer,
2715 ** it should be truncated. The return value of xGetLastError
2716 ** is zero if the error message fits in the buffer, or non-zero
2717 ** otherwise (if the message was truncated). If non-zero is returned,
2718 ** then it is not necessary to include the nul-terminator character
2719 ** in the output buffer.
2720 **
2721 ** Not supplying an error message will have no adverse effect
2722 ** on SQLite. It is fine to have an implementation that never
2723 ** returns an error message:
2724 **
2725 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
2726 **     assert(zBuf[0]=='\0');
2727 **     return 0;
2728 **   }
2729 **
2730 ** However if an error message is supplied, it will be incorporated
2731 ** by sqlite into the error message available to the user using
2732 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
2733 */
2734 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
2735   UNUSED_PARAMETER(pVfs);
2736   return getLastErrorMsg(nBuf, zBuf);
2737 }
2738 
2739 
2740 
2741 /*
2742 ** Initialize and deinitialize the operating system interface.
2743 */
2744 int sqlite3_os_init(void){
2745   static sqlite3_vfs winVfs = {
2746     2,                   /* iVersion */
2747     sizeof(winFile),     /* szOsFile */
2748     MAX_PATH,            /* mxPathname */
2749     0,                   /* pNext */
2750     "win32",             /* zName */
2751     0,                   /* pAppData */
2752     winOpen,             /* xOpen */
2753     winDelete,           /* xDelete */
2754     winAccess,           /* xAccess */
2755     winFullPathname,     /* xFullPathname */
2756     winDlOpen,           /* xDlOpen */
2757     winDlError,          /* xDlError */
2758     winDlSym,            /* xDlSym */
2759     winDlClose,          /* xDlClose */
2760     winRandomness,       /* xRandomness */
2761     winSleep,            /* xSleep */
2762     winCurrentTime,      /* xCurrentTime */
2763     winGetLastError,     /* xGetLastError */
2764     winCurrentTimeInt64, /* xCurrentTimeInt64 */
2765   };
2766 
2767 #ifndef SQLITE_OMIT_WAL
2768   /* get memory map allocation granularity */
2769   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
2770   GetSystemInfo(&winSysInfo);
2771   assert(winSysInfo.dwAllocationGranularity > 0);
2772 #endif
2773 
2774   sqlite3_vfs_register(&winVfs, 1);
2775   return SQLITE_OK;
2776 }
2777 int sqlite3_os_end(void){
2778   return SQLITE_OK;
2779 }
2780 
2781 #endif /* SQLITE_OS_WIN */
2782