xref: /sqlite-3.40.0/src/os_win.c (revision debcfd2d)
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 ** $Id: os_win.c,v 1.156 2009/04/23 19:08:33 shane Exp $
16 */
17 #include "sqliteInt.h"
18 #if SQLITE_OS_WIN               /* This file is used for windows only */
19 
20 
21 /*
22 ** A Note About Memory Allocation:
23 **
24 ** This driver uses malloc()/free() directly rather than going through
25 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
26 ** are designed for use on embedded systems where memory is scarce and
27 ** malloc failures happen frequently.  Win32 does not typically run on
28 ** embedded systems, and when it does the developers normally have bigger
29 ** problems to worry about than running out of memory.  So there is not
30 ** a compelling need to use the wrappers.
31 **
32 ** But there is a good reason to not use the wrappers.  If we use the
33 ** wrappers then we will get simulated malloc() failures within this
34 ** driver.  And that causes all kinds of problems for our tests.  We
35 ** could enhance SQLite to deal with simulated malloc failures within
36 ** the OS driver, but the code to deal with those failure would not
37 ** be exercised on Linux (which does not need to malloc() in the driver)
38 ** and so we would have difficulty writing coverage tests for that
39 ** code.  Better to leave the code out, we think.
40 **
41 ** The point of this discussion is as follows:  When creating a new
42 ** OS layer for an embedded system, if you use this file as an example,
43 ** avoid the use of malloc()/free().  Those routines work ok on windows
44 ** desktops but not so well in embedded systems.
45 */
46 
47 #include <winbase.h>
48 
49 #ifdef __CYGWIN__
50 # include <sys/cygwin.h>
51 #endif
52 
53 /*
54 ** Macros used to determine whether or not to use threads.
55 */
56 #if defined(THREADSAFE) && THREADSAFE
57 # define SQLITE_W32_THREADS 1
58 #endif
59 
60 /*
61 ** Include code that is common to all os_*.c files
62 */
63 #include "os_common.h"
64 
65 /*
66 ** Some microsoft compilers lack this definition.
67 */
68 #ifndef INVALID_FILE_ATTRIBUTES
69 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
70 #endif
71 
72 /*
73 ** Determine if we are dealing with WindowsCE - which has a much
74 ** reduced API.
75 */
76 #if SQLITE_OS_WINCE
77 # define AreFileApisANSI() 1
78 # define GetDiskFreeSpaceW() 0
79 #endif
80 
81 /*
82 ** WinCE lacks native support for file locking so we have to fake it
83 ** with some code of our own.
84 */
85 #if SQLITE_OS_WINCE
86 typedef struct winceLock {
87   int nReaders;       /* Number of reader locks obtained */
88   BOOL bPending;      /* Indicates a pending lock has been obtained */
89   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
90   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
91 } winceLock;
92 #endif
93 
94 /*
95 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
96 ** portability layer.
97 */
98 typedef struct winFile winFile;
99 struct winFile {
100   const sqlite3_io_methods *pMethod;/* Must be first */
101   HANDLE h;               /* Handle for accessing the file */
102   unsigned char locktype; /* Type of lock currently held on this file */
103   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
104   DWORD lastErrno;        /* The Windows errno from the last I/O error */
105   DWORD sectorSize;       /* Sector size of the device file is on */
106 #if SQLITE_OS_WINCE
107   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
108   HANDLE hMutex;          /* Mutex used to control access to shared lock */
109   HANDLE hShared;         /* Shared memory segment used for locking */
110   winceLock local;        /* Locks obtained by this instance of winFile */
111   winceLock *shared;      /* Global shared lock memory for the file  */
112 #endif
113 };
114 
115 /*
116 ** Forward prototypes.
117 */
118 static int getSectorSize(
119     sqlite3_vfs *pVfs,
120     const char *zRelative     /* UTF-8 file name */
121 );
122 
123 /*
124 ** The following variable is (normally) set once and never changes
125 ** thereafter.  It records whether the operating system is Win95
126 ** or WinNT.
127 **
128 ** 0:   Operating system unknown.
129 ** 1:   Operating system is Win95.
130 ** 2:   Operating system is WinNT.
131 **
132 ** In order to facilitate testing on a WinNT system, the test fixture
133 ** can manually set this value to 1 to emulate Win98 behavior.
134 */
135 #ifdef SQLITE_TEST
136 int sqlite3_os_type = 0;
137 #else
138 static int sqlite3_os_type = 0;
139 #endif
140 
141 /*
142 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
143 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
144 **
145 ** Here is an interesting observation:  Win95, Win98, and WinME lack
146 ** the LockFileEx() API.  But we can still statically link against that
147 ** API as long as we don't call it when running Win95/98/ME.  A call to
148 ** this routine is used to determine if the host is Win95/98/ME or
149 ** WinNT/2K/XP so that we will know whether or not we can safely call
150 ** the LockFileEx() API.
151 */
152 #if SQLITE_OS_WINCE
153 # define isNT()  (1)
154 #else
155   static int isNT(void){
156     if( sqlite3_os_type==0 ){
157       OSVERSIONINFO sInfo;
158       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
159       GetVersionEx(&sInfo);
160       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
161     }
162     return sqlite3_os_type==2;
163   }
164 #endif /* SQLITE_OS_WINCE */
165 
166 /*
167 ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
168 **
169 ** Space to hold the returned string is obtained from malloc.
170 */
171 static WCHAR *utf8ToUnicode(const char *zFilename){
172   int nChar;
173   WCHAR *zWideFilename;
174 
175   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
176   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
177   if( zWideFilename==0 ){
178     return 0;
179   }
180   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
181   if( nChar==0 ){
182     free(zWideFilename);
183     zWideFilename = 0;
184   }
185   return zWideFilename;
186 }
187 
188 /*
189 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
190 ** obtained from malloc().
191 */
192 static char *unicodeToUtf8(const WCHAR *zWideFilename){
193   int nByte;
194   char *zFilename;
195 
196   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
197   zFilename = malloc( nByte );
198   if( zFilename==0 ){
199     return 0;
200   }
201   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
202                               0, 0);
203   if( nByte == 0 ){
204     free(zFilename);
205     zFilename = 0;
206   }
207   return zFilename;
208 }
209 
210 /*
211 ** Convert an ansi string to microsoft unicode, based on the
212 ** current codepage settings for file apis.
213 **
214 ** Space to hold the returned string is obtained
215 ** from malloc.
216 */
217 static WCHAR *mbcsToUnicode(const char *zFilename){
218   int nByte;
219   WCHAR *zMbcsFilename;
220   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
221 
222   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
223   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
224   if( zMbcsFilename==0 ){
225     return 0;
226   }
227   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
228   if( nByte==0 ){
229     free(zMbcsFilename);
230     zMbcsFilename = 0;
231   }
232   return zMbcsFilename;
233 }
234 
235 /*
236 ** Convert microsoft unicode to multibyte character string, based on the
237 ** user's Ansi codepage.
238 **
239 ** Space to hold the returned string is obtained from
240 ** malloc().
241 */
242 static char *unicodeToMbcs(const WCHAR *zWideFilename){
243   int nByte;
244   char *zFilename;
245   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
246 
247   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
248   zFilename = malloc( nByte );
249   if( zFilename==0 ){
250     return 0;
251   }
252   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
253                               0, 0);
254   if( nByte == 0 ){
255     free(zFilename);
256     zFilename = 0;
257   }
258   return zFilename;
259 }
260 
261 /*
262 ** Convert multibyte character string to UTF-8.  Space to hold the
263 ** returned string is obtained from malloc().
264 */
265 char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
266   char *zFilenameUtf8;
267   WCHAR *zTmpWide;
268 
269   zTmpWide = mbcsToUnicode(zFilename);
270   if( zTmpWide==0 ){
271     return 0;
272   }
273   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
274   free(zTmpWide);
275   return zFilenameUtf8;
276 }
277 
278 /*
279 ** Convert UTF-8 to multibyte character string.  Space to hold the
280 ** returned string is obtained from malloc().
281 */
282 static char *utf8ToMbcs(const char *zFilename){
283   char *zFilenameMbcs;
284   WCHAR *zTmpWide;
285 
286   zTmpWide = utf8ToUnicode(zFilename);
287   if( zTmpWide==0 ){
288     return 0;
289   }
290   zFilenameMbcs = unicodeToMbcs(zTmpWide);
291   free(zTmpWide);
292   return zFilenameMbcs;
293 }
294 
295 #if SQLITE_OS_WINCE
296 /*************************************************************************
297 ** This section contains code for WinCE only.
298 */
299 /*
300 ** WindowsCE does not have a localtime() function.  So create a
301 ** substitute.
302 */
303 #include <time.h>
304 struct tm *__cdecl localtime(const time_t *t)
305 {
306   static struct tm y;
307   FILETIME uTm, lTm;
308   SYSTEMTIME pTm;
309   sqlite3_int64 t64;
310   t64 = *t;
311   t64 = (t64 + 11644473600)*10000000;
312   uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
313   uTm.dwHighDateTime= t64 >> 32;
314   FileTimeToLocalFileTime(&uTm,&lTm);
315   FileTimeToSystemTime(&lTm,&pTm);
316   y.tm_year = pTm.wYear - 1900;
317   y.tm_mon = pTm.wMonth - 1;
318   y.tm_wday = pTm.wDayOfWeek;
319   y.tm_mday = pTm.wDay;
320   y.tm_hour = pTm.wHour;
321   y.tm_min = pTm.wMinute;
322   y.tm_sec = pTm.wSecond;
323   return &y;
324 }
325 
326 /* This will never be called, but defined to make the code compile */
327 #define GetTempPathA(a,b)
328 
329 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
330 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
331 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
332 
333 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
334 
335 /*
336 ** Acquire a lock on the handle h
337 */
338 static void winceMutexAcquire(HANDLE h){
339    DWORD dwErr;
340    do {
341      dwErr = WaitForSingleObject(h, INFINITE);
342    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
343 }
344 /*
345 ** Release a lock acquired by winceMutexAcquire()
346 */
347 #define winceMutexRelease(h) ReleaseMutex(h)
348 
349 /*
350 ** Create the mutex and shared memory used for locking in the file
351 ** descriptor pFile
352 */
353 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
354   WCHAR *zTok;
355   WCHAR *zName = utf8ToUnicode(zFilename);
356   BOOL bInit = TRUE;
357 
358   /* Initialize the local lockdata */
359   ZeroMemory(&pFile->local, sizeof(pFile->local));
360 
361   /* Replace the backslashes from the filename and lowercase it
362   ** to derive a mutex name. */
363   zTok = CharLowerW(zName);
364   for (;*zTok;zTok++){
365     if (*zTok == '\\') *zTok = '_';
366   }
367 
368   /* Create/open the named mutex */
369   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
370   if (!pFile->hMutex){
371     pFile->lastErrno = GetLastError();
372     free(zName);
373     return FALSE;
374   }
375 
376   /* Acquire the mutex before continuing */
377   winceMutexAcquire(pFile->hMutex);
378 
379   /* Since the names of named mutexes, semaphores, file mappings etc are
380   ** case-sensitive, take advantage of that by uppercasing the mutex name
381   ** and using that as the shared filemapping name.
382   */
383   CharUpperW(zName);
384   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
385                                        PAGE_READWRITE, 0, sizeof(winceLock),
386                                        zName);
387 
388   /* Set a flag that indicates we're the first to create the memory so it
389   ** must be zero-initialized */
390   if (GetLastError() == ERROR_ALREADY_EXISTS){
391     bInit = FALSE;
392   }
393 
394   free(zName);
395 
396   /* If we succeeded in making the shared memory handle, map it. */
397   if (pFile->hShared){
398     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
399              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
400     /* If mapping failed, close the shared memory handle and erase it */
401     if (!pFile->shared){
402       pFile->lastErrno = GetLastError();
403       CloseHandle(pFile->hShared);
404       pFile->hShared = NULL;
405     }
406   }
407 
408   /* If shared memory could not be created, then close the mutex and fail */
409   if (pFile->hShared == NULL){
410     winceMutexRelease(pFile->hMutex);
411     CloseHandle(pFile->hMutex);
412     pFile->hMutex = NULL;
413     return FALSE;
414   }
415 
416   /* Initialize the shared memory if we're supposed to */
417   if (bInit) {
418     ZeroMemory(pFile->shared, sizeof(winceLock));
419   }
420 
421   winceMutexRelease(pFile->hMutex);
422   return TRUE;
423 }
424 
425 /*
426 ** Destroy the part of winFile that deals with wince locks
427 */
428 static void winceDestroyLock(winFile *pFile){
429   if (pFile->hMutex){
430     /* Acquire the mutex */
431     winceMutexAcquire(pFile->hMutex);
432 
433     /* The following blocks should probably assert in debug mode, but they
434        are to cleanup in case any locks remained open */
435     if (pFile->local.nReaders){
436       pFile->shared->nReaders --;
437     }
438     if (pFile->local.bReserved){
439       pFile->shared->bReserved = FALSE;
440     }
441     if (pFile->local.bPending){
442       pFile->shared->bPending = FALSE;
443     }
444     if (pFile->local.bExclusive){
445       pFile->shared->bExclusive = FALSE;
446     }
447 
448     /* De-reference and close our copy of the shared memory handle */
449     UnmapViewOfFile(pFile->shared);
450     CloseHandle(pFile->hShared);
451 
452     /* Done with the mutex */
453     winceMutexRelease(pFile->hMutex);
454     CloseHandle(pFile->hMutex);
455     pFile->hMutex = NULL;
456   }
457 }
458 
459 /*
460 ** An implementation of the LockFile() API of windows for wince
461 */
462 static BOOL winceLockFile(
463   HANDLE *phFile,
464   DWORD dwFileOffsetLow,
465   DWORD dwFileOffsetHigh,
466   DWORD nNumberOfBytesToLockLow,
467   DWORD nNumberOfBytesToLockHigh
468 ){
469   winFile *pFile = HANDLE_TO_WINFILE(phFile);
470   BOOL bReturn = FALSE;
471 
472   if (!pFile->hMutex) return TRUE;
473   winceMutexAcquire(pFile->hMutex);
474 
475   /* Wanting an exclusive lock? */
476   if (dwFileOffsetLow == SHARED_FIRST
477        && nNumberOfBytesToLockLow == SHARED_SIZE){
478     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
479        pFile->shared->bExclusive = TRUE;
480        pFile->local.bExclusive = TRUE;
481        bReturn = TRUE;
482     }
483   }
484 
485   /* Want a read-only lock? */
486   else if ((dwFileOffsetLow >= SHARED_FIRST &&
487             dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
488             nNumberOfBytesToLockLow == 1){
489     if (pFile->shared->bExclusive == 0){
490       pFile->local.nReaders ++;
491       if (pFile->local.nReaders == 1){
492         pFile->shared->nReaders ++;
493       }
494       bReturn = TRUE;
495     }
496   }
497 
498   /* Want a pending lock? */
499   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
500     /* If no pending lock has been acquired, then acquire it */
501     if (pFile->shared->bPending == 0) {
502       pFile->shared->bPending = TRUE;
503       pFile->local.bPending = TRUE;
504       bReturn = TRUE;
505     }
506   }
507   /* Want a reserved lock? */
508   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
509     if (pFile->shared->bReserved == 0) {
510       pFile->shared->bReserved = TRUE;
511       pFile->local.bReserved = TRUE;
512       bReturn = TRUE;
513     }
514   }
515 
516   winceMutexRelease(pFile->hMutex);
517   return bReturn;
518 }
519 
520 /*
521 ** An implementation of the UnlockFile API of windows for wince
522 */
523 static BOOL winceUnlockFile(
524   HANDLE *phFile,
525   DWORD dwFileOffsetLow,
526   DWORD dwFileOffsetHigh,
527   DWORD nNumberOfBytesToUnlockLow,
528   DWORD nNumberOfBytesToUnlockHigh
529 ){
530   winFile *pFile = HANDLE_TO_WINFILE(phFile);
531   BOOL bReturn = FALSE;
532 
533   if (!pFile->hMutex) return TRUE;
534   winceMutexAcquire(pFile->hMutex);
535 
536   /* Releasing a reader lock or an exclusive lock */
537   if (dwFileOffsetLow >= SHARED_FIRST &&
538        dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
539     /* Did we have an exclusive lock? */
540     if (pFile->local.bExclusive){
541       pFile->local.bExclusive = FALSE;
542       pFile->shared->bExclusive = FALSE;
543       bReturn = TRUE;
544     }
545 
546     /* Did we just have a reader lock? */
547     else if (pFile->local.nReaders){
548       pFile->local.nReaders --;
549       if (pFile->local.nReaders == 0)
550       {
551         pFile->shared->nReaders --;
552       }
553       bReturn = TRUE;
554     }
555   }
556 
557   /* Releasing a pending lock */
558   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
559     if (pFile->local.bPending){
560       pFile->local.bPending = FALSE;
561       pFile->shared->bPending = FALSE;
562       bReturn = TRUE;
563     }
564   }
565   /* Releasing a reserved lock */
566   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
567     if (pFile->local.bReserved) {
568       pFile->local.bReserved = FALSE;
569       pFile->shared->bReserved = FALSE;
570       bReturn = TRUE;
571     }
572   }
573 
574   winceMutexRelease(pFile->hMutex);
575   return bReturn;
576 }
577 
578 /*
579 ** An implementation of the LockFileEx() API of windows for wince
580 */
581 static BOOL winceLockFileEx(
582   HANDLE *phFile,
583   DWORD dwFlags,
584   DWORD dwReserved,
585   DWORD nNumberOfBytesToLockLow,
586   DWORD nNumberOfBytesToLockHigh,
587   LPOVERLAPPED lpOverlapped
588 ){
589   /* If the caller wants a shared read lock, forward this call
590   ** to winceLockFile */
591   if (lpOverlapped->Offset == SHARED_FIRST &&
592       dwFlags == 1 &&
593       nNumberOfBytesToLockLow == SHARED_SIZE){
594     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
595   }
596   return FALSE;
597 }
598 /*
599 ** End of the special code for wince
600 *****************************************************************************/
601 #endif /* SQLITE_OS_WINCE */
602 
603 /*****************************************************************************
604 ** The next group of routines implement the I/O methods specified
605 ** by the sqlite3_io_methods object.
606 ******************************************************************************/
607 
608 /*
609 ** Close a file.
610 **
611 ** It is reported that an attempt to close a handle might sometimes
612 ** fail.  This is a very unreasonable result, but windows is notorious
613 ** for being unreasonable so I do not doubt that it might happen.  If
614 ** the close fails, we pause for 100 milliseconds and try again.  As
615 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
616 ** giving up and returning an error.
617 */
618 #define MX_CLOSE_ATTEMPT 3
619 static int winClose(sqlite3_file *id){
620   int rc, cnt = 0;
621   winFile *pFile = (winFile*)id;
622 
623   assert( id!=0 );
624   OSTRACE2("CLOSE %d\n", pFile->h);
625   do{
626     rc = CloseHandle(pFile->h);
627   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
628 #if SQLITE_OS_WINCE
629 #define WINCE_DELETION_ATTEMPTS 3
630   winceDestroyLock(pFile);
631   if( pFile->zDeleteOnClose ){
632     int cnt = 0;
633     while(
634            DeleteFileW(pFile->zDeleteOnClose)==0
635         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
636         && cnt++ < WINCE_DELETION_ATTEMPTS
637     ){
638        Sleep(100);  /* Wait a little before trying again */
639     }
640     free(pFile->zDeleteOnClose);
641   }
642 #endif
643   OpenCounter(-1);
644   return rc ? SQLITE_OK : SQLITE_IOERR;
645 }
646 
647 /*
648 ** Some microsoft compilers lack this definition.
649 */
650 #ifndef INVALID_SET_FILE_POINTER
651 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
652 #endif
653 
654 /*
655 ** Read data from a file into a buffer.  Return SQLITE_OK if all
656 ** bytes were read successfully and SQLITE_IOERR if anything goes
657 ** wrong.
658 */
659 static int winRead(
660   sqlite3_file *id,          /* File to read from */
661   void *pBuf,                /* Write content into this buffer */
662   int amt,                   /* Number of bytes to read */
663   sqlite3_int64 offset       /* Begin reading at this offset */
664 ){
665   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
666   LONG lowerBits = (LONG)(offset & 0xffffffff);
667   DWORD rc;
668   winFile *pFile = (winFile*)id;
669   DWORD error;
670   DWORD got;
671 
672   assert( id!=0 );
673   SimulateIOError(return SQLITE_IOERR_READ);
674   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
675   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
676   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
677     pFile->lastErrno = error;
678     return SQLITE_FULL;
679   }
680   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
681     pFile->lastErrno = GetLastError();
682     return SQLITE_IOERR_READ;
683   }
684   if( got==(DWORD)amt ){
685     return SQLITE_OK;
686   }else{
687     /* Unread parts of the buffer must be zero-filled */
688     memset(&((char*)pBuf)[got], 0, amt-got);
689     return SQLITE_IOERR_SHORT_READ;
690   }
691 }
692 
693 /*
694 ** Write data from a buffer into a file.  Return SQLITE_OK on success
695 ** or some other error code on failure.
696 */
697 static int winWrite(
698   sqlite3_file *id,         /* File to write into */
699   const void *pBuf,         /* The bytes to be written */
700   int amt,                  /* Number of bytes to write */
701   sqlite3_int64 offset      /* Offset into the file to begin writing at */
702 ){
703   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
704   LONG lowerBits = (LONG)(offset & 0xffffffff);
705   DWORD rc;
706   winFile *pFile = (winFile*)id;
707   DWORD error;
708   DWORD wrote = 0;
709 
710   assert( id!=0 );
711   SimulateIOError(return SQLITE_IOERR_WRITE);
712   SimulateDiskfullError(return SQLITE_FULL);
713   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
714   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
715   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
716     pFile->lastErrno = error;
717     return SQLITE_FULL;
718   }
719   assert( amt>0 );
720   while(
721      amt>0
722      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
723      && wrote>0
724   ){
725     amt -= wrote;
726     pBuf = &((char*)pBuf)[wrote];
727   }
728   if( !rc || amt>(int)wrote ){
729     pFile->lastErrno = GetLastError();
730     return SQLITE_FULL;
731   }
732   return SQLITE_OK;
733 }
734 
735 /*
736 ** Truncate an open file to a specified size
737 */
738 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
739   LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
740   LONG lowerBits = (LONG)(nByte & 0xffffffff);
741   DWORD rc;
742   winFile *pFile = (winFile*)id;
743   DWORD error;
744 
745   assert( id!=0 );
746   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
747   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
748   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
749   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
750     pFile->lastErrno = error;
751     return SQLITE_IOERR_TRUNCATE;
752   }
753   /* SetEndOfFile will fail if nByte is negative */
754   if( !SetEndOfFile(pFile->h) ){
755     pFile->lastErrno = GetLastError();
756     return SQLITE_IOERR_TRUNCATE;
757   }
758   return SQLITE_OK;
759 }
760 
761 #ifdef SQLITE_TEST
762 /*
763 ** Count the number of fullsyncs and normal syncs.  This is used to test
764 ** that syncs and fullsyncs are occuring at the right times.
765 */
766 int sqlite3_sync_count = 0;
767 int sqlite3_fullsync_count = 0;
768 #endif
769 
770 /*
771 ** Make sure all writes to a particular file are committed to disk.
772 */
773 static int winSync(sqlite3_file *id, int flags){
774 #ifndef SQLITE_NO_SYNC
775   winFile *pFile = (winFile*)id;
776 
777   assert( id!=0 );
778   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
779 #else
780   UNUSED_PARAMETER(id);
781 #endif
782 #ifndef SQLITE_TEST
783   UNUSED_PARAMETER(flags);
784 #else
785   if( flags & SQLITE_SYNC_FULL ){
786     sqlite3_fullsync_count++;
787   }
788   sqlite3_sync_count++;
789 #endif
790   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
791   ** no-op
792   */
793 #ifdef SQLITE_NO_SYNC
794     return SQLITE_OK;
795 #else
796   if( FlushFileBuffers(pFile->h) ){
797     return SQLITE_OK;
798   }else{
799     pFile->lastErrno = GetLastError();
800     return SQLITE_IOERR;
801   }
802 #endif
803 }
804 
805 /*
806 ** Determine the current size of a file in bytes
807 */
808 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
809   DWORD upperBits;
810   DWORD lowerBits;
811   winFile *pFile = (winFile*)id;
812   DWORD error;
813 
814   assert( id!=0 );
815   SimulateIOError(return SQLITE_IOERR_FSTAT);
816   lowerBits = GetFileSize(pFile->h, &upperBits);
817   if(   (lowerBits == INVALID_FILE_SIZE)
818      && ((error = GetLastError()) != NO_ERROR) )
819   {
820     pFile->lastErrno = error;
821     return SQLITE_IOERR_FSTAT;
822   }
823   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
824   return SQLITE_OK;
825 }
826 
827 /*
828 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
829 */
830 #ifndef LOCKFILE_FAIL_IMMEDIATELY
831 # define LOCKFILE_FAIL_IMMEDIATELY 1
832 #endif
833 
834 /*
835 ** Acquire a reader lock.
836 ** Different API routines are called depending on whether or not this
837 ** is Win95 or WinNT.
838 */
839 static int getReadLock(winFile *pFile){
840   int res;
841   if( isNT() ){
842     OVERLAPPED ovlp;
843     ovlp.Offset = SHARED_FIRST;
844     ovlp.OffsetHigh = 0;
845     ovlp.hEvent = 0;
846     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
847                      0, SHARED_SIZE, 0, &ovlp);
848 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
849 */
850 #if SQLITE_OS_WINCE==0
851   }else{
852     int lk;
853     sqlite3_randomness(sizeof(lk), &lk);
854     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
855     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
856 #endif
857   }
858   if( res == 0 ){
859     pFile->lastErrno = GetLastError();
860   }
861   return res;
862 }
863 
864 /*
865 ** Undo a readlock
866 */
867 static int unlockReadLock(winFile *pFile){
868   int res;
869   if( isNT() ){
870     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
871 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
872 */
873 #if SQLITE_OS_WINCE==0
874   }else{
875     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
876 #endif
877   }
878   if( res == 0 ){
879     pFile->lastErrno = GetLastError();
880   }
881   return res;
882 }
883 
884 /*
885 ** Lock the file with the lock specified by parameter locktype - one
886 ** of the following:
887 **
888 **     (1) SHARED_LOCK
889 **     (2) RESERVED_LOCK
890 **     (3) PENDING_LOCK
891 **     (4) EXCLUSIVE_LOCK
892 **
893 ** Sometimes when requesting one lock state, additional lock states
894 ** are inserted in between.  The locking might fail on one of the later
895 ** transitions leaving the lock state different from what it started but
896 ** still short of its goal.  The following chart shows the allowed
897 ** transitions and the inserted intermediate states:
898 **
899 **    UNLOCKED -> SHARED
900 **    SHARED -> RESERVED
901 **    SHARED -> (PENDING) -> EXCLUSIVE
902 **    RESERVED -> (PENDING) -> EXCLUSIVE
903 **    PENDING -> EXCLUSIVE
904 **
905 ** This routine will only increase a lock.  The winUnlock() routine
906 ** erases all locks at once and returns us immediately to locking level 0.
907 ** It is not possible to lower the locking level one step at a time.  You
908 ** must go straight to locking level 0.
909 */
910 static int winLock(sqlite3_file *id, int locktype){
911   int rc = SQLITE_OK;    /* Return code from subroutines */
912   int res = 1;           /* Result of a windows lock call */
913   int newLocktype;       /* Set pFile->locktype to this value before exiting */
914   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
915   winFile *pFile = (winFile*)id;
916   DWORD error = NO_ERROR;
917 
918   assert( id!=0 );
919   OSTRACE5("LOCK %d %d was %d(%d)\n",
920           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
921 
922   /* If there is already a lock of this type or more restrictive on the
923   ** OsFile, do nothing. Don't use the end_lock: exit path, as
924   ** sqlite3OsEnterMutex() hasn't been called yet.
925   */
926   if( pFile->locktype>=locktype ){
927     return SQLITE_OK;
928   }
929 
930   /* Make sure the locking sequence is correct
931   */
932   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
933   assert( locktype!=PENDING_LOCK );
934   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
935 
936   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
937   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
938   ** the PENDING_LOCK byte is temporary.
939   */
940   newLocktype = pFile->locktype;
941   if(   (pFile->locktype==NO_LOCK)
942      || (   (locktype==EXCLUSIVE_LOCK)
943          && (pFile->locktype==RESERVED_LOCK))
944   ){
945     int cnt = 3;
946     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
947       /* Try 3 times to get the pending lock.  The pending lock might be
948       ** held by another reader process who will release it momentarily.
949       */
950       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
951       Sleep(1);
952     }
953     gotPendingLock = res;
954     if( !res ){
955       error = GetLastError();
956     }
957   }
958 
959   /* Acquire a shared lock
960   */
961   if( locktype==SHARED_LOCK && res ){
962     assert( pFile->locktype==NO_LOCK );
963     res = getReadLock(pFile);
964     if( res ){
965       newLocktype = SHARED_LOCK;
966     }else{
967       error = GetLastError();
968     }
969   }
970 
971   /* Acquire a RESERVED lock
972   */
973   if( locktype==RESERVED_LOCK && res ){
974     assert( pFile->locktype==SHARED_LOCK );
975     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
976     if( res ){
977       newLocktype = RESERVED_LOCK;
978     }else{
979       error = GetLastError();
980     }
981   }
982 
983   /* Acquire a PENDING lock
984   */
985   if( locktype==EXCLUSIVE_LOCK && res ){
986     newLocktype = PENDING_LOCK;
987     gotPendingLock = 0;
988   }
989 
990   /* Acquire an EXCLUSIVE lock
991   */
992   if( locktype==EXCLUSIVE_LOCK && res ){
993     assert( pFile->locktype>=SHARED_LOCK );
994     res = unlockReadLock(pFile);
995     OSTRACE2("unreadlock = %d\n", res);
996     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
997     if( res ){
998       newLocktype = EXCLUSIVE_LOCK;
999     }else{
1000       error = GetLastError();
1001       OSTRACE2("error-code = %d\n", error);
1002       getReadLock(pFile);
1003     }
1004   }
1005 
1006   /* If we are holding a PENDING lock that ought to be released, then
1007   ** release it now.
1008   */
1009   if( gotPendingLock && locktype==SHARED_LOCK ){
1010     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
1011   }
1012 
1013   /* Update the state of the lock has held in the file descriptor then
1014   ** return the appropriate result code.
1015   */
1016   if( res ){
1017     rc = SQLITE_OK;
1018   }else{
1019     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
1020            locktype, newLocktype);
1021     pFile->lastErrno = error;
1022     rc = SQLITE_BUSY;
1023   }
1024   pFile->locktype = (u8)newLocktype;
1025   return rc;
1026 }
1027 
1028 /*
1029 ** This routine checks if there is a RESERVED lock held on the specified
1030 ** file by this or any other process. If such a lock is held, return
1031 ** non-zero, otherwise zero.
1032 */
1033 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
1034   int rc;
1035   winFile *pFile = (winFile*)id;
1036 
1037   assert( id!=0 );
1038   if( pFile->locktype>=RESERVED_LOCK ){
1039     rc = 1;
1040     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
1041   }else{
1042     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1043     if( rc ){
1044       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1045     }
1046     rc = !rc;
1047     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
1048   }
1049   *pResOut = rc;
1050   return SQLITE_OK;
1051 }
1052 
1053 /*
1054 ** Lower the locking level on file descriptor id to locktype.  locktype
1055 ** must be either NO_LOCK or SHARED_LOCK.
1056 **
1057 ** If the locking level of the file descriptor is already at or below
1058 ** the requested locking level, this routine is a no-op.
1059 **
1060 ** It is not possible for this routine to fail if the second argument
1061 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
1062 ** might return SQLITE_IOERR;
1063 */
1064 static int winUnlock(sqlite3_file *id, int locktype){
1065   int type;
1066   winFile *pFile = (winFile*)id;
1067   int rc = SQLITE_OK;
1068   assert( pFile!=0 );
1069   assert( locktype<=SHARED_LOCK );
1070   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
1071           pFile->locktype, pFile->sharedLockByte);
1072   type = pFile->locktype;
1073   if( type>=EXCLUSIVE_LOCK ){
1074     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
1075     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
1076       /* This should never happen.  We should always be able to
1077       ** reacquire the read lock */
1078       rc = SQLITE_IOERR_UNLOCK;
1079     }
1080   }
1081   if( type>=RESERVED_LOCK ){
1082     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1083   }
1084   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
1085     unlockReadLock(pFile);
1086   }
1087   if( type>=PENDING_LOCK ){
1088     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
1089   }
1090   pFile->locktype = (u8)locktype;
1091   return rc;
1092 }
1093 
1094 /*
1095 ** Control and query of the open file handle.
1096 */
1097 static int winFileControl(sqlite3_file *id, int op, void *pArg){
1098   switch( op ){
1099     case SQLITE_FCNTL_LOCKSTATE: {
1100       *(int*)pArg = ((winFile*)id)->locktype;
1101       return SQLITE_OK;
1102     }
1103     case SQLITE_LAST_ERRNO: {
1104       *(int*)pArg = (int)((winFile*)id)->lastErrno;
1105       return SQLITE_OK;
1106     }
1107   }
1108   return SQLITE_ERROR;
1109 }
1110 
1111 /*
1112 ** Return the sector size in bytes of the underlying block device for
1113 ** the specified file. This is almost always 512 bytes, but may be
1114 ** larger for some devices.
1115 **
1116 ** SQLite code assumes this function cannot fail. It also assumes that
1117 ** if two files are created in the same file-system directory (i.e.
1118 ** a database and its journal file) that the sector size will be the
1119 ** same for both.
1120 */
1121 static int winSectorSize(sqlite3_file *id){
1122   assert( id!=0 );
1123   return (int)(((winFile*)id)->sectorSize);
1124 }
1125 
1126 /*
1127 ** Return a vector of device characteristics.
1128 */
1129 static int winDeviceCharacteristics(sqlite3_file *id){
1130   UNUSED_PARAMETER(id);
1131   return 0;
1132 }
1133 
1134 /*
1135 ** This vector defines all the methods that can operate on an
1136 ** sqlite3_file for win32.
1137 */
1138 static const sqlite3_io_methods winIoMethod = {
1139   1,                        /* iVersion */
1140   winClose,
1141   winRead,
1142   winWrite,
1143   winTruncate,
1144   winSync,
1145   winFileSize,
1146   winLock,
1147   winUnlock,
1148   winCheckReservedLock,
1149   winFileControl,
1150   winSectorSize,
1151   winDeviceCharacteristics
1152 };
1153 
1154 /***************************************************************************
1155 ** Here ends the I/O methods that form the sqlite3_io_methods object.
1156 **
1157 ** The next block of code implements the VFS methods.
1158 ****************************************************************************/
1159 
1160 /*
1161 ** Convert a UTF-8 filename into whatever form the underlying
1162 ** operating system wants filenames in.  Space to hold the result
1163 ** is obtained from malloc and must be freed by the calling
1164 ** function.
1165 */
1166 static void *convertUtf8Filename(const char *zFilename){
1167   void *zConverted = 0;
1168   if( isNT() ){
1169     zConverted = utf8ToUnicode(zFilename);
1170 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1171 */
1172 #if SQLITE_OS_WINCE==0
1173   }else{
1174     zConverted = utf8ToMbcs(zFilename);
1175 #endif
1176   }
1177   /* caller will handle out of memory */
1178   return zConverted;
1179 }
1180 
1181 /*
1182 ** Create a temporary file name in zBuf.  zBuf must be big enough to
1183 ** hold at pVfs->mxPathname characters.
1184 */
1185 static int getTempname(int nBuf, char *zBuf){
1186   static char zChars[] =
1187     "abcdefghijklmnopqrstuvwxyz"
1188     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1189     "0123456789";
1190   size_t i, j;
1191   char zTempPath[MAX_PATH+1];
1192   if( sqlite3_temp_directory ){
1193     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
1194   }else if( isNT() ){
1195     char *zMulti;
1196     WCHAR zWidePath[MAX_PATH];
1197     GetTempPathW(MAX_PATH-30, zWidePath);
1198     zMulti = unicodeToUtf8(zWidePath);
1199     if( zMulti ){
1200       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
1201       free(zMulti);
1202     }else{
1203       return SQLITE_NOMEM;
1204     }
1205 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1206 ** Since the ASCII version of these Windows API do not exist for WINCE,
1207 ** it's important to not reference them for WINCE builds.
1208 */
1209 #if SQLITE_OS_WINCE==0
1210   }else{
1211     char *zUtf8;
1212     char zMbcsPath[MAX_PATH];
1213     GetTempPathA(MAX_PATH-30, zMbcsPath);
1214     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
1215     if( zUtf8 ){
1216       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
1217       free(zUtf8);
1218     }else{
1219       return SQLITE_NOMEM;
1220     }
1221 #endif
1222   }
1223   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
1224   zTempPath[i] = 0;
1225   sqlite3_snprintf(nBuf-30, zBuf,
1226                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
1227   j = sqlite3Strlen30(zBuf);
1228   sqlite3_randomness(20, &zBuf[j]);
1229   for(i=0; i<20; i++, j++){
1230     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
1231   }
1232   zBuf[j] = 0;
1233   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
1234   return SQLITE_OK;
1235 }
1236 
1237 /*
1238 ** The return value of getLastErrorMsg
1239 ** is zero if the error message fits in the buffer, or non-zero
1240 ** otherwise (if the message was truncated).
1241 */
1242 static int getLastErrorMsg(int nBuf, char *zBuf){
1243   DWORD error = GetLastError();
1244 
1245 #if SQLITE_OS_WINCE
1246   sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
1247 #else
1248   /* FormatMessage returns 0 on failure.  Otherwise it
1249   ** returns the number of TCHARs written to the output
1250   ** buffer, excluding the terminating null char.
1251   */
1252   if (!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
1253                       NULL,
1254                       error,
1255                       0,
1256                       zBuf,
1257                       nBuf-1,
1258                       0))
1259   {
1260     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
1261   }
1262 #endif
1263 
1264   return 0;
1265 }
1266 
1267 /*
1268 ** Open a file.
1269 */
1270 static int winOpen(
1271   sqlite3_vfs *pVfs,        /* Not used */
1272   const char *zName,        /* Name of the file (UTF-8) */
1273   sqlite3_file *id,         /* Write the SQLite file handle here */
1274   int flags,                /* Open mode flags */
1275   int *pOutFlags            /* Status return flags */
1276 ){
1277   HANDLE h;
1278   DWORD dwDesiredAccess;
1279   DWORD dwShareMode;
1280   DWORD dwCreationDisposition;
1281   DWORD dwFlagsAndAttributes = 0;
1282 #if SQLITE_OS_WINCE
1283   int isTemp = 0;
1284 #endif
1285   winFile *pFile = (winFile*)id;
1286   void *zConverted;                 /* Filename in OS encoding */
1287   const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
1288   char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
1289 
1290   assert( id!=0 );
1291   UNUSED_PARAMETER(pVfs);
1292 
1293   /* If the second argument to this function is NULL, generate a
1294   ** temporary file name to use
1295   */
1296   if( !zUtf8Name ){
1297     int rc = getTempname(MAX_PATH+1, zTmpname);
1298     if( rc!=SQLITE_OK ){
1299       return rc;
1300     }
1301     zUtf8Name = zTmpname;
1302   }
1303 
1304   /* Convert the filename to the system encoding. */
1305   zConverted = convertUtf8Filename(zUtf8Name);
1306   if( zConverted==0 ){
1307     return SQLITE_NOMEM;
1308   }
1309 
1310   if( flags & SQLITE_OPEN_READWRITE ){
1311     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
1312   }else{
1313     dwDesiredAccess = GENERIC_READ;
1314   }
1315   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
1316   ** created. SQLite doesn't use it to indicate "exclusive access"
1317   ** as it is usually understood.
1318   */
1319   assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
1320   if( flags & SQLITE_OPEN_EXCLUSIVE ){
1321     /* Creates a new file, only if it does not already exist. */
1322     /* If the file exists, it fails. */
1323     dwCreationDisposition = CREATE_NEW;
1324   }else if( flags & SQLITE_OPEN_CREATE ){
1325     /* Open existing file, or create if it doesn't exist */
1326     dwCreationDisposition = OPEN_ALWAYS;
1327   }else{
1328     /* Opens a file, only if it exists. */
1329     dwCreationDisposition = OPEN_EXISTING;
1330   }
1331   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
1332   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
1333 #if SQLITE_OS_WINCE
1334     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
1335     isTemp = 1;
1336 #else
1337     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
1338                                | FILE_ATTRIBUTE_HIDDEN
1339                                | FILE_FLAG_DELETE_ON_CLOSE;
1340 #endif
1341   }else{
1342     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
1343   }
1344   /* Reports from the internet are that performance is always
1345   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
1346 #if SQLITE_OS_WINCE
1347   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
1348 #endif
1349   if( isNT() ){
1350     h = CreateFileW((WCHAR*)zConverted,
1351        dwDesiredAccess,
1352        dwShareMode,
1353        NULL,
1354        dwCreationDisposition,
1355        dwFlagsAndAttributes,
1356        NULL
1357     );
1358 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1359 ** Since the ASCII version of these Windows API do not exist for WINCE,
1360 ** it's important to not reference them for WINCE builds.
1361 */
1362 #if SQLITE_OS_WINCE==0
1363   }else{
1364     h = CreateFileA((char*)zConverted,
1365        dwDesiredAccess,
1366        dwShareMode,
1367        NULL,
1368        dwCreationDisposition,
1369        dwFlagsAndAttributes,
1370        NULL
1371     );
1372 #endif
1373   }
1374   if( h==INVALID_HANDLE_VALUE ){
1375     free(zConverted);
1376     if( flags & SQLITE_OPEN_READWRITE ){
1377       return winOpen(pVfs, zName, id,
1378              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
1379     }else{
1380       return SQLITE_CANTOPEN;
1381     }
1382   }
1383   if( pOutFlags ){
1384     if( flags & SQLITE_OPEN_READWRITE ){
1385       *pOutFlags = SQLITE_OPEN_READWRITE;
1386     }else{
1387       *pOutFlags = SQLITE_OPEN_READONLY;
1388     }
1389   }
1390   memset(pFile, 0, sizeof(*pFile));
1391   pFile->pMethod = &winIoMethod;
1392   pFile->h = h;
1393   pFile->lastErrno = NO_ERROR;
1394   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
1395 #if SQLITE_OS_WINCE
1396   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
1397                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
1398        && !winceCreateLock(zName, pFile)
1399   ){
1400     CloseHandle(h);
1401     free(zConverted);
1402     return SQLITE_CANTOPEN;
1403   }
1404   if( isTemp ){
1405     pFile->zDeleteOnClose = zConverted;
1406   }else
1407 #endif
1408   {
1409     free(zConverted);
1410   }
1411   OpenCounter(+1);
1412   return SQLITE_OK;
1413 }
1414 
1415 /*
1416 ** Delete the named file.
1417 **
1418 ** Note that windows does not allow a file to be deleted if some other
1419 ** process has it open.  Sometimes a virus scanner or indexing program
1420 ** will open a journal file shortly after it is created in order to do
1421 ** whatever it does.  While this other process is holding the
1422 ** file open, we will be unable to delete it.  To work around this
1423 ** problem, we delay 100 milliseconds and try to delete again.  Up
1424 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
1425 ** up and returning an error.
1426 */
1427 #define MX_DELETION_ATTEMPTS 5
1428 static int winDelete(
1429   sqlite3_vfs *pVfs,          /* Not used on win32 */
1430   const char *zFilename,      /* Name of file to delete */
1431   int syncDir                 /* Not used on win32 */
1432 ){
1433   int cnt = 0;
1434   DWORD rc;
1435   DWORD error = 0;
1436   void *zConverted = convertUtf8Filename(zFilename);
1437   UNUSED_PARAMETER(pVfs);
1438   UNUSED_PARAMETER(syncDir);
1439   if( zConverted==0 ){
1440     return SQLITE_NOMEM;
1441   }
1442   SimulateIOError(return SQLITE_IOERR_DELETE);
1443   if( isNT() ){
1444     do{
1445       DeleteFileW(zConverted);
1446     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
1447                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
1448            && (++cnt < MX_DELETION_ATTEMPTS)
1449            && (Sleep(100), 1) );
1450 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1451 ** Since the ASCII version of these Windows API do not exist for WINCE,
1452 ** it's important to not reference them for WINCE builds.
1453 */
1454 #if SQLITE_OS_WINCE==0
1455   }else{
1456     do{
1457       DeleteFileA(zConverted);
1458     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
1459                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
1460            && (++cnt < MX_DELETION_ATTEMPTS)
1461            && (Sleep(100), 1) );
1462 #endif
1463   }
1464   free(zConverted);
1465   OSTRACE2("DELETE \"%s\"\n", zFilename);
1466   return (   (rc == INVALID_FILE_ATTRIBUTES)
1467           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
1468 }
1469 
1470 /*
1471 ** Check the existance and status of a file.
1472 */
1473 static int winAccess(
1474   sqlite3_vfs *pVfs,         /* Not used on win32 */
1475   const char *zFilename,     /* Name of file to check */
1476   int flags,                 /* Type of test to make on this file */
1477   int *pResOut               /* OUT: Result */
1478 ){
1479   DWORD attr;
1480   int rc = 0;
1481   void *zConverted = convertUtf8Filename(zFilename);
1482   UNUSED_PARAMETER(pVfs);
1483   if( zConverted==0 ){
1484     return SQLITE_NOMEM;
1485   }
1486   if( isNT() ){
1487     attr = GetFileAttributesW((WCHAR*)zConverted);
1488 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1489 ** Since the ASCII version of these Windows API do not exist for WINCE,
1490 ** it's important to not reference them for WINCE builds.
1491 */
1492 #if SQLITE_OS_WINCE==0
1493   }else{
1494     attr = GetFileAttributesA((char*)zConverted);
1495 #endif
1496   }
1497   free(zConverted);
1498   switch( flags ){
1499     case SQLITE_ACCESS_READ:
1500     case SQLITE_ACCESS_EXISTS:
1501       rc = attr!=INVALID_FILE_ATTRIBUTES;
1502       break;
1503     case SQLITE_ACCESS_READWRITE:
1504       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
1505       break;
1506     default:
1507       assert(!"Invalid flags argument");
1508   }
1509   *pResOut = rc;
1510   return SQLITE_OK;
1511 }
1512 
1513 
1514 /*
1515 ** Turn a relative pathname into a full pathname.  Write the full
1516 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
1517 ** bytes in size.
1518 */
1519 static int winFullPathname(
1520   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
1521   const char *zRelative,        /* Possibly relative input path */
1522   int nFull,                    /* Size of output buffer in bytes */
1523   char *zFull                   /* Output buffer */
1524 ){
1525 
1526 #if defined(__CYGWIN__)
1527   UNUSED_PARAMETER(nFull);
1528   cygwin_conv_to_full_win32_path(zRelative, zFull);
1529   return SQLITE_OK;
1530 #endif
1531 
1532 #if SQLITE_OS_WINCE
1533   UNUSED_PARAMETER(nFull);
1534   /* WinCE has no concept of a relative pathname, or so I am told. */
1535   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
1536   return SQLITE_OK;
1537 #endif
1538 
1539 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
1540   int nByte;
1541   void *zConverted;
1542   char *zOut;
1543   UNUSED_PARAMETER(nFull);
1544   zConverted = convertUtf8Filename(zRelative);
1545   if( isNT() ){
1546     WCHAR *zTemp;
1547     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
1548     zTemp = malloc( nByte*sizeof(zTemp[0]) );
1549     if( zTemp==0 ){
1550       free(zConverted);
1551       return SQLITE_NOMEM;
1552     }
1553     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
1554     free(zConverted);
1555     zOut = unicodeToUtf8(zTemp);
1556     free(zTemp);
1557 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1558 ** Since the ASCII version of these Windows API do not exist for WINCE,
1559 ** it's important to not reference them for WINCE builds.
1560 */
1561 #if SQLITE_OS_WINCE==0
1562   }else{
1563     char *zTemp;
1564     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
1565     zTemp = malloc( nByte*sizeof(zTemp[0]) );
1566     if( zTemp==0 ){
1567       free(zConverted);
1568       return SQLITE_NOMEM;
1569     }
1570     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
1571     free(zConverted);
1572     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
1573     free(zTemp);
1574 #endif
1575   }
1576   if( zOut ){
1577     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
1578     free(zOut);
1579     return SQLITE_OK;
1580   }else{
1581     return SQLITE_NOMEM;
1582   }
1583 #endif
1584 }
1585 
1586 /*
1587 ** Get the sector size of the device used to store
1588 ** file.
1589 */
1590 static int getSectorSize(
1591     sqlite3_vfs *pVfs,
1592     const char *zRelative     /* UTF-8 file name */
1593 ){
1594   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
1595   char zFullpath[MAX_PATH+1];
1596   int rc;
1597   DWORD dwRet = 0, dwDummy;
1598 
1599   /*
1600   ** We need to get the full path name of the file
1601   ** to get the drive letter to look up the sector
1602   ** size.
1603   */
1604   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
1605   if( rc == SQLITE_OK )
1606   {
1607     void *zConverted = convertUtf8Filename(zFullpath);
1608     if( zConverted ){
1609       if( isNT() ){
1610         /* trim path to just drive reference */
1611         WCHAR *p = zConverted;
1612         for(;*p;p++){
1613           if( *p == '\\' ){
1614             *p = '\0';
1615             break;
1616           }
1617         }
1618         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
1619                                   &dwDummy,
1620                                   &bytesPerSector,
1621                                   &dwDummy,
1622                                   &dwDummy);
1623 #if SQLITE_OS_WINCE==0
1624       }else{
1625         /* trim path to just drive reference */
1626         CHAR *p = (CHAR *)zConverted;
1627         for(;*p;p++){
1628           if( *p == '\\' ){
1629             *p = '\0';
1630             break;
1631           }
1632         }
1633         dwRet = GetDiskFreeSpaceA((CHAR*)zConverted,
1634                                   &dwDummy,
1635                                   &bytesPerSector,
1636                                   &dwDummy,
1637                                   &dwDummy);
1638 #endif
1639       }
1640       free(zConverted);
1641     }
1642     if( !dwRet ){
1643       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
1644     }
1645   }
1646   return (int) bytesPerSector;
1647 }
1648 
1649 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1650 /*
1651 ** Interfaces for opening a shared library, finding entry points
1652 ** within the shared library, and closing the shared library.
1653 */
1654 /*
1655 ** Interfaces for opening a shared library, finding entry points
1656 ** within the shared library, and closing the shared library.
1657 */
1658 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
1659   HANDLE h;
1660   void *zConverted = convertUtf8Filename(zFilename);
1661   UNUSED_PARAMETER(pVfs);
1662   if( zConverted==0 ){
1663     return 0;
1664   }
1665   if( isNT() ){
1666     h = LoadLibraryW((WCHAR*)zConverted);
1667 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1668 ** Since the ASCII version of these Windows API do not exist for WINCE,
1669 ** it's important to not reference them for WINCE builds.
1670 */
1671 #if SQLITE_OS_WINCE==0
1672   }else{
1673     h = LoadLibraryA((char*)zConverted);
1674 #endif
1675   }
1676   free(zConverted);
1677   return (void*)h;
1678 }
1679 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
1680   UNUSED_PARAMETER(pVfs);
1681   getLastErrorMsg(nBuf, zBufOut);
1682 }
1683 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
1684   UNUSED_PARAMETER(pVfs);
1685 #if SQLITE_OS_WINCE
1686   /* The GetProcAddressA() routine is only available on wince. */
1687   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
1688 #else
1689   /* All other windows platforms expect GetProcAddress() to take
1690   ** an Ansi string regardless of the _UNICODE setting */
1691   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
1692 #endif
1693 }
1694 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
1695   UNUSED_PARAMETER(pVfs);
1696   FreeLibrary((HANDLE)pHandle);
1697 }
1698 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
1699   #define winDlOpen  0
1700   #define winDlError 0
1701   #define winDlSym   0
1702   #define winDlClose 0
1703 #endif
1704 
1705 
1706 /*
1707 ** Write up to nBuf bytes of randomness into zBuf.
1708 */
1709 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
1710   int n = 0;
1711   UNUSED_PARAMETER(pVfs);
1712 #if defined(SQLITE_TEST)
1713   n = nBuf;
1714   memset(zBuf, 0, nBuf);
1715 #else
1716   if( sizeof(SYSTEMTIME)<=nBuf-n ){
1717     SYSTEMTIME x;
1718     GetSystemTime(&x);
1719     memcpy(&zBuf[n], &x, sizeof(x));
1720     n += sizeof(x);
1721   }
1722   if( sizeof(DWORD)<=nBuf-n ){
1723     DWORD pid = GetCurrentProcessId();
1724     memcpy(&zBuf[n], &pid, sizeof(pid));
1725     n += sizeof(pid);
1726   }
1727   if( sizeof(DWORD)<=nBuf-n ){
1728     DWORD cnt = GetTickCount();
1729     memcpy(&zBuf[n], &cnt, sizeof(cnt));
1730     n += sizeof(cnt);
1731   }
1732   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
1733     LARGE_INTEGER i;
1734     QueryPerformanceCounter(&i);
1735     memcpy(&zBuf[n], &i, sizeof(i));
1736     n += sizeof(i);
1737   }
1738 #endif
1739   return n;
1740 }
1741 
1742 
1743 /*
1744 ** Sleep for a little while.  Return the amount of time slept.
1745 */
1746 static int winSleep(sqlite3_vfs *pVfs, int microsec){
1747   Sleep((microsec+999)/1000);
1748   UNUSED_PARAMETER(pVfs);
1749   return ((microsec+999)/1000)*1000;
1750 }
1751 
1752 /*
1753 ** The following variable, if set to a non-zero value, becomes the result
1754 ** returned from sqlite3OsCurrentTime().  This is used for testing.
1755 */
1756 #ifdef SQLITE_TEST
1757 int sqlite3_current_time = 0;
1758 #endif
1759 
1760 /*
1761 ** Find the current time (in Universal Coordinated Time).  Write the
1762 ** current time and date as a Julian Day number into *prNow and
1763 ** return 0.  Return 1 if the time and date cannot be found.
1764 */
1765 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
1766   FILETIME ft;
1767   /* FILETIME structure is a 64-bit value representing the number of
1768      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
1769   */
1770   sqlite3_int64 timeW;   /* Whole days */
1771   sqlite3_int64 timeF;   /* Fractional Days */
1772 
1773   /* Number of 100-nanosecond intervals in a single day */
1774   static const sqlite3_int64 ntuPerDay =
1775       10000000*(sqlite3_int64)86400;
1776 
1777   /* Number of 100-nanosecond intervals in half of a day */
1778   static const sqlite3_int64 ntuPerHalfDay =
1779       10000000*(sqlite3_int64)43200;
1780 
1781   /* 2^32 - to avoid use of LL and warnings in gcc */
1782   static const sqlite3_int64 max32BitValue =
1783       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
1784 
1785 #if SQLITE_OS_WINCE
1786   SYSTEMTIME time;
1787   GetSystemTime(&time);
1788   /* if SystemTimeToFileTime() fails, it returns zero. */
1789   if (!SystemTimeToFileTime(&time,&ft)){
1790     return 1;
1791   }
1792 #else
1793   GetSystemTimeAsFileTime( &ft );
1794 #endif
1795   UNUSED_PARAMETER(pVfs);
1796   timeW = (((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime;
1797   timeF = timeW % ntuPerDay;          /* fractional days (100-nanoseconds) */
1798   timeW = timeW / ntuPerDay;          /* whole days */
1799   timeW = timeW + 2305813;            /* add whole days (from 2305813.5) */
1800   timeF = timeF + ntuPerHalfDay;      /* add half a day (from 2305813.5) */
1801   timeW = timeW + (timeF/ntuPerDay);  /* add whole day if half day made one */
1802   timeF = timeF % ntuPerDay;          /* compute new fractional days */
1803   *prNow = (double)timeW + ((double)timeF / (double)ntuPerDay);
1804 #ifdef SQLITE_TEST
1805   if( sqlite3_current_time ){
1806     *prNow = ((double)sqlite3_current_time + (double)43200) / (double)86400 + (double)2440587;
1807   }
1808 #endif
1809   return 0;
1810 }
1811 
1812 /*
1813 ** The idea is that this function works like a combination of
1814 ** GetLastError() and FormatMessage() on windows (or errno and
1815 ** strerror_r() on unix). After an error is returned by an OS
1816 ** function, SQLite calls this function with zBuf pointing to
1817 ** a buffer of nBuf bytes. The OS layer should populate the
1818 ** buffer with a nul-terminated UTF-8 encoded error message
1819 ** describing the last IO error to have occurred within the calling
1820 ** thread.
1821 **
1822 ** If the error message is too large for the supplied buffer,
1823 ** it should be truncated. The return value of xGetLastError
1824 ** is zero if the error message fits in the buffer, or non-zero
1825 ** otherwise (if the message was truncated). If non-zero is returned,
1826 ** then it is not necessary to include the nul-terminator character
1827 ** in the output buffer.
1828 **
1829 ** Not supplying an error message will have no adverse effect
1830 ** on SQLite. It is fine to have an implementation that never
1831 ** returns an error message:
1832 **
1833 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
1834 **     assert(zBuf[0]=='\0');
1835 **     return 0;
1836 **   }
1837 **
1838 ** However if an error message is supplied, it will be incorporated
1839 ** by sqlite into the error message available to the user using
1840 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
1841 */
1842 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
1843   UNUSED_PARAMETER(pVfs);
1844   return getLastErrorMsg(nBuf, zBuf);
1845 }
1846 
1847 /*
1848 ** Initialize and deinitialize the operating system interface.
1849 */
1850 int sqlite3_os_init(void){
1851   static sqlite3_vfs winVfs = {
1852     1,                 /* iVersion */
1853     sizeof(winFile),   /* szOsFile */
1854     MAX_PATH,          /* mxPathname */
1855     0,                 /* pNext */
1856     "win32",           /* zName */
1857     0,                 /* pAppData */
1858 
1859     winOpen,           /* xOpen */
1860     winDelete,         /* xDelete */
1861     winAccess,         /* xAccess */
1862     winFullPathname,   /* xFullPathname */
1863     winDlOpen,         /* xDlOpen */
1864     winDlError,        /* xDlError */
1865     winDlSym,          /* xDlSym */
1866     winDlClose,        /* xDlClose */
1867     winRandomness,     /* xRandomness */
1868     winSleep,          /* xSleep */
1869     winCurrentTime,    /* xCurrentTime */
1870     winGetLastError    /* xGetLastError */
1871   };
1872   sqlite3_vfs_register(&winVfs, 1);
1873   return SQLITE_OK;
1874 }
1875 int sqlite3_os_end(void){
1876   return SQLITE_OK;
1877 }
1878 
1879 #endif /* SQLITE_OS_WIN */
1880