add pragma cipher_default_use_hmac to toggle global HMAC setting
[sqlcipher.git] / src / os_win.c
blob4518030483f6a095e87e0da0889b10d8a606e11f
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.
11 ******************************************************************************
13 ** This file contains code that is specific to windows.
15 #include "sqliteInt.h"
16 #if SQLITE_OS_WIN /* This file is used for windows only */
20 ** A Note About Memory Allocation:
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.
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.
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.
45 #include <winbase.h>
47 #ifdef __CYGWIN__
48 # include <sys/cygwin.h>
49 #endif
52 ** Macros used to determine whether or not to use threads.
54 #if defined(THREADSAFE) && THREADSAFE
55 # define SQLITE_W32_THREADS 1
56 #endif
59 ** Include code that is common to all os_*.c files
61 #include "os_common.h"
64 ** Some microsoft compilers lack this definition.
66 #ifndef INVALID_FILE_ATTRIBUTES
67 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
68 #endif
71 ** Determine if we are dealing with WindowsCE - which has a much
72 ** reduced API.
74 #if SQLITE_OS_WINCE
75 # define AreFileApisANSI() 1
76 # define FormatMessageW(a,b,c,d,e,f,g) 0
77 #endif
79 /* Forward references */
80 typedef struct winShm winShm; /* A connection to shared-memory */
81 typedef struct winShmNode winShmNode; /* A region of shared-memory */
84 ** WinCE lacks native support for file locking so we have to fake it
85 ** with some code of our own.
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
97 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
98 ** portability layer.
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 u8 locktype; /* Type of lock currently held on this file */
106 short sharedLockByte; /* Randomly chosen byte used as a shared lock */
107 u8 bPersistWal; /* True to persist WAL files */
108 DWORD lastErrno; /* The Windows errno from the last I/O error */
109 DWORD sectorSize; /* Sector size of the device file is on */
110 winShm *pShm; /* Instance of shared memory on this file */
111 const char *zPath; /* Full pathname of this file */
112 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
113 #if SQLITE_OS_WINCE
114 WCHAR *zDeleteOnClose; /* Name of file to delete when closing */
115 HANDLE hMutex; /* Mutex used to control access to shared lock */
116 HANDLE hShared; /* Shared memory segment used for locking */
117 winceLock local; /* Locks obtained by this instance of winFile */
118 winceLock *shared; /* Global shared lock memory for the file */
119 #endif
123 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
124 * various Win32 API heap functions instead of our own.
126 #ifdef SQLITE_WIN32_MALLOC
128 * The initial size of the Win32-specific heap. This value may be zero.
130 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
131 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
132 (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
133 #endif
136 * The maximum size of the Win32-specific heap. This value may be zero.
138 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
139 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
140 #endif
143 * The extra flags to use in calls to the Win32 heap APIs. This value may be
144 * zero for the default behavior.
146 #ifndef SQLITE_WIN32_HEAP_FLAGS
147 # define SQLITE_WIN32_HEAP_FLAGS (0)
148 #endif
151 ** The winMemData structure stores information required by the Win32-specific
152 ** sqlite3_mem_methods implementation.
154 typedef struct winMemData winMemData;
155 struct winMemData {
156 #ifndef NDEBUG
157 u32 magic; /* Magic number to detect structure corruption. */
158 #endif
159 HANDLE hHeap; /* The handle to our heap. */
160 BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
163 #ifndef NDEBUG
164 #define WINMEM_MAGIC 0x42b2830b
165 #endif
167 static struct winMemData win_mem_data = {
168 #ifndef NDEBUG
169 WINMEM_MAGIC,
170 #endif
171 NULL, FALSE
174 #ifndef NDEBUG
175 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
176 #else
177 #define winMemAssertMagic()
178 #endif
180 #define winMemGetHeap() win_mem_data.hHeap
182 static void *winMemMalloc(int nBytes);
183 static void winMemFree(void *pPrior);
184 static void *winMemRealloc(void *pPrior, int nBytes);
185 static int winMemSize(void *p);
186 static int winMemRoundup(int n);
187 static int winMemInit(void *pAppData);
188 static void winMemShutdown(void *pAppData);
190 const sqlite3_mem_methods *sqlite3MemGetWin32(void);
191 #endif /* SQLITE_WIN32_MALLOC */
194 ** Forward prototypes.
196 static int getSectorSize(
197 sqlite3_vfs *pVfs,
198 const char *zRelative /* UTF-8 file name */
202 ** The following variable is (normally) set once and never changes
203 ** thereafter. It records whether the operating system is Win95
204 ** or WinNT.
206 ** 0: Operating system unknown.
207 ** 1: Operating system is Win95.
208 ** 2: Operating system is WinNT.
210 ** In order to facilitate testing on a WinNT system, the test fixture
211 ** can manually set this value to 1 to emulate Win98 behavior.
213 #ifdef SQLITE_TEST
214 int sqlite3_os_type = 0;
215 #else
216 static int sqlite3_os_type = 0;
217 #endif
220 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
221 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
223 ** Here is an interesting observation: Win95, Win98, and WinME lack
224 ** the LockFileEx() API. But we can still statically link against that
225 ** API as long as we don't call it when running Win95/98/ME. A call to
226 ** this routine is used to determine if the host is Win95/98/ME or
227 ** WinNT/2K/XP so that we will know whether or not we can safely call
228 ** the LockFileEx() API.
230 #if SQLITE_OS_WINCE
231 # define isNT() (1)
232 #else
233 static int isNT(void){
234 if( sqlite3_os_type==0 ){
235 OSVERSIONINFO sInfo;
236 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
237 GetVersionEx(&sInfo);
238 sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
240 return sqlite3_os_type==2;
242 #endif /* SQLITE_OS_WINCE */
244 #ifdef SQLITE_WIN32_MALLOC
246 ** Allocate nBytes of memory.
248 static void *winMemMalloc(int nBytes){
249 HANDLE hHeap;
250 void *p;
252 winMemAssertMagic();
253 hHeap = winMemGetHeap();
254 assert( hHeap!=0 );
255 assert( hHeap!=INVALID_HANDLE_VALUE );
256 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
257 assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
258 #endif
259 assert( nBytes>=0 );
260 p = HeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
261 if( !p ){
262 sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
263 nBytes, GetLastError(), (void*)hHeap);
265 return p;
269 ** Free memory.
271 static void winMemFree(void *pPrior){
272 HANDLE hHeap;
274 winMemAssertMagic();
275 hHeap = winMemGetHeap();
276 assert( hHeap!=0 );
277 assert( hHeap!=INVALID_HANDLE_VALUE );
278 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
279 assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
280 #endif
281 if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
282 if( !HeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
283 sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
284 pPrior, GetLastError(), (void*)hHeap);
289 ** Change the size of an existing memory allocation
291 static void *winMemRealloc(void *pPrior, int nBytes){
292 HANDLE hHeap;
293 void *p;
295 winMemAssertMagic();
296 hHeap = winMemGetHeap();
297 assert( hHeap!=0 );
298 assert( hHeap!=INVALID_HANDLE_VALUE );
299 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
300 assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
301 #endif
302 assert( nBytes>=0 );
303 if( !pPrior ){
304 p = HeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
305 }else{
306 p = HeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
308 if( !p ){
309 sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
310 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, GetLastError(),
311 (void*)hHeap);
313 return p;
317 ** Return the size of an outstanding allocation, in bytes.
319 static int winMemSize(void *p){
320 HANDLE hHeap;
321 SIZE_T n;
323 winMemAssertMagic();
324 hHeap = winMemGetHeap();
325 assert( hHeap!=0 );
326 assert( hHeap!=INVALID_HANDLE_VALUE );
327 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
328 assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
329 #endif
330 if( !p ) return 0;
331 n = HeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
332 if( n==(SIZE_T)-1 ){
333 sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
334 p, GetLastError(), (void*)hHeap);
335 return 0;
337 return (int)n;
341 ** Round up a request size to the next valid allocation size.
343 static int winMemRoundup(int n){
344 return n;
348 ** Initialize this module.
350 static int winMemInit(void *pAppData){
351 winMemData *pWinMemData = (winMemData *)pAppData;
353 if( !pWinMemData ) return SQLITE_ERROR;
354 assert( pWinMemData->magic==WINMEM_MAGIC );
355 if( !pWinMemData->hHeap ){
356 pWinMemData->hHeap = HeapCreate(SQLITE_WIN32_HEAP_FLAGS,
357 SQLITE_WIN32_HEAP_INIT_SIZE,
358 SQLITE_WIN32_HEAP_MAX_SIZE);
359 if( !pWinMemData->hHeap ){
360 sqlite3_log(SQLITE_NOMEM,
361 "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
362 GetLastError(), SQLITE_WIN32_HEAP_FLAGS, SQLITE_WIN32_HEAP_INIT_SIZE,
363 SQLITE_WIN32_HEAP_MAX_SIZE);
364 return SQLITE_NOMEM;
366 pWinMemData->bOwned = TRUE;
368 assert( pWinMemData->hHeap!=0 );
369 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
370 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
371 assert( HeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
372 #endif
373 return SQLITE_OK;
377 ** Deinitialize this module.
379 static void winMemShutdown(void *pAppData){
380 winMemData *pWinMemData = (winMemData *)pAppData;
382 if( !pWinMemData ) return;
383 if( pWinMemData->hHeap ){
384 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
385 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
386 assert( HeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
387 #endif
388 if( pWinMemData->bOwned ){
389 if( !HeapDestroy(pWinMemData->hHeap) ){
390 sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
391 GetLastError(), (void*)pWinMemData->hHeap);
393 pWinMemData->bOwned = FALSE;
395 pWinMemData->hHeap = NULL;
400 ** Populate the low-level memory allocation function pointers in
401 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
402 ** arguments specify the block of memory to manage.
404 ** This routine is only called by sqlite3_config(), and therefore
405 ** is not required to be threadsafe (it is not).
407 const sqlite3_mem_methods *sqlite3MemGetWin32(void){
408 static const sqlite3_mem_methods winMemMethods = {
409 winMemMalloc,
410 winMemFree,
411 winMemRealloc,
412 winMemSize,
413 winMemRoundup,
414 winMemInit,
415 winMemShutdown,
416 &win_mem_data
418 return &winMemMethods;
421 void sqlite3MemSetDefault(void){
422 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
424 #endif /* SQLITE_WIN32_MALLOC */
427 ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
429 ** Space to hold the returned string is obtained from malloc.
431 static WCHAR *utf8ToUnicode(const char *zFilename){
432 int nChar;
433 WCHAR *zWideFilename;
435 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
436 zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
437 if( zWideFilename==0 ){
438 return 0;
440 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
441 if( nChar==0 ){
442 free(zWideFilename);
443 zWideFilename = 0;
445 return zWideFilename;
449 ** Convert microsoft unicode to UTF-8. Space to hold the returned string is
450 ** obtained from malloc().
452 static char *unicodeToUtf8(const WCHAR *zWideFilename){
453 int nByte;
454 char *zFilename;
456 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
457 zFilename = malloc( nByte );
458 if( zFilename==0 ){
459 return 0;
461 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
462 0, 0);
463 if( nByte == 0 ){
464 free(zFilename);
465 zFilename = 0;
467 return zFilename;
471 ** Convert an ansi string to microsoft unicode, based on the
472 ** current codepage settings for file apis.
474 ** Space to hold the returned string is obtained
475 ** from malloc.
477 static WCHAR *mbcsToUnicode(const char *zFilename){
478 int nByte;
479 WCHAR *zMbcsFilename;
480 int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
482 nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
483 zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
484 if( zMbcsFilename==0 ){
485 return 0;
487 nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
488 if( nByte==0 ){
489 free(zMbcsFilename);
490 zMbcsFilename = 0;
492 return zMbcsFilename;
496 ** Convert microsoft unicode to multibyte character string, based on the
497 ** user's Ansi codepage.
499 ** Space to hold the returned string is obtained from
500 ** malloc().
502 static char *unicodeToMbcs(const WCHAR *zWideFilename){
503 int nByte;
504 char *zFilename;
505 int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
507 nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
508 zFilename = malloc( nByte );
509 if( zFilename==0 ){
510 return 0;
512 nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
513 0, 0);
514 if( nByte == 0 ){
515 free(zFilename);
516 zFilename = 0;
518 return zFilename;
522 ** Convert multibyte character string to UTF-8. Space to hold the
523 ** returned string is obtained from malloc().
525 char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
526 char *zFilenameUtf8;
527 WCHAR *zTmpWide;
529 zTmpWide = mbcsToUnicode(zFilename);
530 if( zTmpWide==0 ){
531 return 0;
533 zFilenameUtf8 = unicodeToUtf8(zTmpWide);
534 free(zTmpWide);
535 return zFilenameUtf8;
539 ** Convert UTF-8 to multibyte character string. Space to hold the
540 ** returned string is obtained from malloc().
542 char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
543 char *zFilenameMbcs;
544 WCHAR *zTmpWide;
546 zTmpWide = utf8ToUnicode(zFilename);
547 if( zTmpWide==0 ){
548 return 0;
550 zFilenameMbcs = unicodeToMbcs(zTmpWide);
551 free(zTmpWide);
552 return zFilenameMbcs;
557 ** The return value of getLastErrorMsg
558 ** is zero if the error message fits in the buffer, or non-zero
559 ** otherwise (if the message was truncated).
561 static int getLastErrorMsg(int nBuf, char *zBuf){
562 /* FormatMessage returns 0 on failure. Otherwise it
563 ** returns the number of TCHARs written to the output
564 ** buffer, excluding the terminating null char.
566 DWORD error = GetLastError();
567 DWORD dwLen = 0;
568 char *zOut = 0;
570 if( isNT() ){
571 WCHAR *zTempWide = NULL;
572 dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
573 NULL,
574 error,
576 (LPWSTR) &zTempWide,
579 if( dwLen > 0 ){
580 /* allocate a buffer and convert to UTF8 */
581 zOut = unicodeToUtf8(zTempWide);
582 /* free the system buffer allocated by FormatMessage */
583 LocalFree(zTempWide);
585 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
586 ** Since the ASCII version of these Windows API do not exist for WINCE,
587 ** it's important to not reference them for WINCE builds.
589 #if SQLITE_OS_WINCE==0
590 }else{
591 char *zTemp = NULL;
592 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
593 NULL,
594 error,
596 (LPSTR) &zTemp,
599 if( dwLen > 0 ){
600 /* allocate a buffer and convert to UTF8 */
601 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
602 /* free the system buffer allocated by FormatMessage */
603 LocalFree(zTemp);
605 #endif
607 if( 0 == dwLen ){
608 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
609 }else{
610 /* copy a maximum of nBuf chars to output buffer */
611 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
612 /* free the UTF8 buffer */
613 free(zOut);
615 return 0;
620 ** This function - winLogErrorAtLine() - is only ever called via the macro
621 ** winLogError().
623 ** This routine is invoked after an error occurs in an OS function.
624 ** It logs a message using sqlite3_log() containing the current value of
625 ** error code and, if possible, the human-readable equivalent from
626 ** FormatMessage.
628 ** The first argument passed to the macro should be the error code that
629 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
630 ** The two subsequent arguments should be the name of the OS function that
631 ** failed and the the associated file-system path, if any.
633 #define winLogError(a,b,c) winLogErrorAtLine(a,b,c,__LINE__)
634 static int winLogErrorAtLine(
635 int errcode, /* SQLite error code */
636 const char *zFunc, /* Name of OS function that failed */
637 const char *zPath, /* File path associated with error */
638 int iLine /* Source line number where error occurred */
640 char zMsg[500]; /* Human readable error text */
641 int i; /* Loop counter */
642 DWORD iErrno = GetLastError(); /* Error code */
644 zMsg[0] = 0;
645 getLastErrorMsg(sizeof(zMsg), zMsg);
646 assert( errcode!=SQLITE_OK );
647 if( zPath==0 ) zPath = "";
648 for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
649 zMsg[i] = 0;
650 sqlite3_log(errcode,
651 "os_win.c:%d: (%d) %s(%s) - %s",
652 iLine, iErrno, zFunc, zPath, zMsg
655 return errcode;
659 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
660 ** will be retried following a locking error - probably caused by
661 ** antivirus software. Also the initial delay before the first retry.
662 ** The delay increases linearly with each retry.
664 #ifndef SQLITE_WIN32_IOERR_RETRY
665 # define SQLITE_WIN32_IOERR_RETRY 10
666 #endif
667 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
668 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
669 #endif
670 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
671 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
674 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
675 ** to see if it should be retried. Return TRUE to retry. Return FALSE
676 ** to give up with an error.
678 static int retryIoerr(int *pnRetry){
679 DWORD e;
680 if( *pnRetry>=win32IoerrRetry ){
681 return 0;
683 e = GetLastError();
684 if( e==ERROR_ACCESS_DENIED ||
685 e==ERROR_LOCK_VIOLATION ||
686 e==ERROR_SHARING_VIOLATION ){
687 Sleep(win32IoerrRetryDelay*(1+*pnRetry));
688 ++*pnRetry;
689 return 1;
691 return 0;
695 ** Log a I/O error retry episode.
697 static void logIoerr(int nRetry){
698 if( nRetry ){
699 sqlite3_log(SQLITE_IOERR,
700 "delayed %dms for lock/sharing conflict",
701 win32IoerrRetryDelay*nRetry*(nRetry+1)/2
706 #if SQLITE_OS_WINCE
707 /*************************************************************************
708 ** This section contains code for WinCE only.
711 ** WindowsCE does not have a localtime() function. So create a
712 ** substitute.
714 #include <time.h>
715 struct tm *__cdecl localtime(const time_t *t)
717 static struct tm y;
718 FILETIME uTm, lTm;
719 SYSTEMTIME pTm;
720 sqlite3_int64 t64;
721 t64 = *t;
722 t64 = (t64 + 11644473600)*10000000;
723 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
724 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
725 FileTimeToLocalFileTime(&uTm,&lTm);
726 FileTimeToSystemTime(&lTm,&pTm);
727 y.tm_year = pTm.wYear - 1900;
728 y.tm_mon = pTm.wMonth - 1;
729 y.tm_wday = pTm.wDayOfWeek;
730 y.tm_mday = pTm.wDay;
731 y.tm_hour = pTm.wHour;
732 y.tm_min = pTm.wMinute;
733 y.tm_sec = pTm.wSecond;
734 return &y;
737 /* This will never be called, but defined to make the code compile */
738 #define GetTempPathA(a,b)
740 #define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e)
741 #define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e)
742 #define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f)
744 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
747 ** Acquire a lock on the handle h
749 static void winceMutexAcquire(HANDLE h){
750 DWORD dwErr;
751 do {
752 dwErr = WaitForSingleObject(h, INFINITE);
753 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
756 ** Release a lock acquired by winceMutexAcquire()
758 #define winceMutexRelease(h) ReleaseMutex(h)
761 ** Create the mutex and shared memory used for locking in the file
762 ** descriptor pFile
764 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
765 WCHAR *zTok;
766 WCHAR *zName = utf8ToUnicode(zFilename);
767 BOOL bInit = TRUE;
769 /* Initialize the local lockdata */
770 ZeroMemory(&pFile->local, sizeof(pFile->local));
772 /* Replace the backslashes from the filename and lowercase it
773 ** to derive a mutex name. */
774 zTok = CharLowerW(zName);
775 for (;*zTok;zTok++){
776 if (*zTok == '\\') *zTok = '_';
779 /* Create/open the named mutex */
780 pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
781 if (!pFile->hMutex){
782 pFile->lastErrno = GetLastError();
783 winLogError(SQLITE_ERROR, "winceCreateLock1", zFilename);
784 free(zName);
785 return FALSE;
788 /* Acquire the mutex before continuing */
789 winceMutexAcquire(pFile->hMutex);
791 /* Since the names of named mutexes, semaphores, file mappings etc are
792 ** case-sensitive, take advantage of that by uppercasing the mutex name
793 ** and using that as the shared filemapping name.
795 CharUpperW(zName);
796 pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
797 PAGE_READWRITE, 0, sizeof(winceLock),
798 zName);
800 /* Set a flag that indicates we're the first to create the memory so it
801 ** must be zero-initialized */
802 if (GetLastError() == ERROR_ALREADY_EXISTS){
803 bInit = FALSE;
806 free(zName);
808 /* If we succeeded in making the shared memory handle, map it. */
809 if (pFile->hShared){
810 pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
811 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
812 /* If mapping failed, close the shared memory handle and erase it */
813 if (!pFile->shared){
814 pFile->lastErrno = GetLastError();
815 winLogError(SQLITE_ERROR, "winceCreateLock2", zFilename);
816 CloseHandle(pFile->hShared);
817 pFile->hShared = NULL;
821 /* If shared memory could not be created, then close the mutex and fail */
822 if (pFile->hShared == NULL){
823 winceMutexRelease(pFile->hMutex);
824 CloseHandle(pFile->hMutex);
825 pFile->hMutex = NULL;
826 return FALSE;
829 /* Initialize the shared memory if we're supposed to */
830 if (bInit) {
831 ZeroMemory(pFile->shared, sizeof(winceLock));
834 winceMutexRelease(pFile->hMutex);
835 return TRUE;
839 ** Destroy the part of winFile that deals with wince locks
841 static void winceDestroyLock(winFile *pFile){
842 if (pFile->hMutex){
843 /* Acquire the mutex */
844 winceMutexAcquire(pFile->hMutex);
846 /* The following blocks should probably assert in debug mode, but they
847 are to cleanup in case any locks remained open */
848 if (pFile->local.nReaders){
849 pFile->shared->nReaders --;
851 if (pFile->local.bReserved){
852 pFile->shared->bReserved = FALSE;
854 if (pFile->local.bPending){
855 pFile->shared->bPending = FALSE;
857 if (pFile->local.bExclusive){
858 pFile->shared->bExclusive = FALSE;
861 /* De-reference and close our copy of the shared memory handle */
862 UnmapViewOfFile(pFile->shared);
863 CloseHandle(pFile->hShared);
865 /* Done with the mutex */
866 winceMutexRelease(pFile->hMutex);
867 CloseHandle(pFile->hMutex);
868 pFile->hMutex = NULL;
873 ** An implementation of the LockFile() API of windows for wince
875 static BOOL winceLockFile(
876 HANDLE *phFile,
877 DWORD dwFileOffsetLow,
878 DWORD dwFileOffsetHigh,
879 DWORD nNumberOfBytesToLockLow,
880 DWORD nNumberOfBytesToLockHigh
882 winFile *pFile = HANDLE_TO_WINFILE(phFile);
883 BOOL bReturn = FALSE;
885 UNUSED_PARAMETER(dwFileOffsetHigh);
886 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
888 if (!pFile->hMutex) return TRUE;
889 winceMutexAcquire(pFile->hMutex);
891 /* Wanting an exclusive lock? */
892 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
893 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
894 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
895 pFile->shared->bExclusive = TRUE;
896 pFile->local.bExclusive = TRUE;
897 bReturn = TRUE;
901 /* Want a read-only lock? */
902 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
903 nNumberOfBytesToLockLow == 1){
904 if (pFile->shared->bExclusive == 0){
905 pFile->local.nReaders ++;
906 if (pFile->local.nReaders == 1){
907 pFile->shared->nReaders ++;
909 bReturn = TRUE;
913 /* Want a pending lock? */
914 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
915 /* If no pending lock has been acquired, then acquire it */
916 if (pFile->shared->bPending == 0) {
917 pFile->shared->bPending = TRUE;
918 pFile->local.bPending = TRUE;
919 bReturn = TRUE;
923 /* Want a reserved lock? */
924 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
925 if (pFile->shared->bReserved == 0) {
926 pFile->shared->bReserved = TRUE;
927 pFile->local.bReserved = TRUE;
928 bReturn = TRUE;
932 winceMutexRelease(pFile->hMutex);
933 return bReturn;
937 ** An implementation of the UnlockFile API of windows for wince
939 static BOOL winceUnlockFile(
940 HANDLE *phFile,
941 DWORD dwFileOffsetLow,
942 DWORD dwFileOffsetHigh,
943 DWORD nNumberOfBytesToUnlockLow,
944 DWORD nNumberOfBytesToUnlockHigh
946 winFile *pFile = HANDLE_TO_WINFILE(phFile);
947 BOOL bReturn = FALSE;
949 UNUSED_PARAMETER(dwFileOffsetHigh);
950 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
952 if (!pFile->hMutex) return TRUE;
953 winceMutexAcquire(pFile->hMutex);
955 /* Releasing a reader lock or an exclusive lock */
956 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
957 /* Did we have an exclusive lock? */
958 if (pFile->local.bExclusive){
959 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
960 pFile->local.bExclusive = FALSE;
961 pFile->shared->bExclusive = FALSE;
962 bReturn = TRUE;
965 /* Did we just have a reader lock? */
966 else if (pFile->local.nReaders){
967 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
968 pFile->local.nReaders --;
969 if (pFile->local.nReaders == 0)
971 pFile->shared->nReaders --;
973 bReturn = TRUE;
977 /* Releasing a pending lock */
978 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
979 if (pFile->local.bPending){
980 pFile->local.bPending = FALSE;
981 pFile->shared->bPending = FALSE;
982 bReturn = TRUE;
985 /* Releasing a reserved lock */
986 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
987 if (pFile->local.bReserved) {
988 pFile->local.bReserved = FALSE;
989 pFile->shared->bReserved = FALSE;
990 bReturn = TRUE;
994 winceMutexRelease(pFile->hMutex);
995 return bReturn;
999 ** An implementation of the LockFileEx() API of windows for wince
1001 static BOOL winceLockFileEx(
1002 HANDLE *phFile,
1003 DWORD dwFlags,
1004 DWORD dwReserved,
1005 DWORD nNumberOfBytesToLockLow,
1006 DWORD nNumberOfBytesToLockHigh,
1007 LPOVERLAPPED lpOverlapped
1009 UNUSED_PARAMETER(dwReserved);
1010 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
1012 /* If the caller wants a shared read lock, forward this call
1013 ** to winceLockFile */
1014 if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
1015 dwFlags == 1 &&
1016 nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
1017 return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
1019 return FALSE;
1022 ** End of the special code for wince
1023 *****************************************************************************/
1024 #endif /* SQLITE_OS_WINCE */
1026 /*****************************************************************************
1027 ** The next group of routines implement the I/O methods specified
1028 ** by the sqlite3_io_methods object.
1029 ******************************************************************************/
1032 ** Some microsoft compilers lack this definition.
1034 #ifndef INVALID_SET_FILE_POINTER
1035 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
1036 #endif
1039 ** Move the current position of the file handle passed as the first
1040 ** argument to offset iOffset within the file. If successful, return 0.
1041 ** Otherwise, set pFile->lastErrno and return non-zero.
1043 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
1044 LONG upperBits; /* Most sig. 32 bits of new offset */
1045 LONG lowerBits; /* Least sig. 32 bits of new offset */
1046 DWORD dwRet; /* Value returned by SetFilePointer() */
1048 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
1049 lowerBits = (LONG)(iOffset & 0xffffffff);
1051 /* API oddity: If successful, SetFilePointer() returns a dword
1052 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
1053 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
1054 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
1055 ** whether an error has actually occured, it is also necessary to call
1056 ** GetLastError().
1058 dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
1059 if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
1060 pFile->lastErrno = GetLastError();
1061 winLogError(SQLITE_IOERR_SEEK, "seekWinFile", pFile->zPath);
1062 return 1;
1065 return 0;
1069 ** Close a file.
1071 ** It is reported that an attempt to close a handle might sometimes
1072 ** fail. This is a very unreasonable result, but windows is notorious
1073 ** for being unreasonable so I do not doubt that it might happen. If
1074 ** the close fails, we pause for 100 milliseconds and try again. As
1075 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
1076 ** giving up and returning an error.
1078 #define MX_CLOSE_ATTEMPT 3
1079 static int winClose(sqlite3_file *id){
1080 int rc, cnt = 0;
1081 winFile *pFile = (winFile*)id;
1083 assert( id!=0 );
1084 assert( pFile->pShm==0 );
1085 OSTRACE(("CLOSE %d\n", pFile->h));
1087 rc = CloseHandle(pFile->h);
1088 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
1089 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
1090 #if SQLITE_OS_WINCE
1091 #define WINCE_DELETION_ATTEMPTS 3
1092 winceDestroyLock(pFile);
1093 if( pFile->zDeleteOnClose ){
1094 int cnt = 0;
1095 while(
1096 DeleteFileW(pFile->zDeleteOnClose)==0
1097 && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
1098 && cnt++ < WINCE_DELETION_ATTEMPTS
1100 Sleep(100); /* Wait a little before trying again */
1102 free(pFile->zDeleteOnClose);
1104 #endif
1105 OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
1106 OpenCounter(-1);
1107 return rc ? SQLITE_OK
1108 : winLogError(SQLITE_IOERR_CLOSE, "winClose", pFile->zPath);
1112 ** Read data from a file into a buffer. Return SQLITE_OK if all
1113 ** bytes were read successfully and SQLITE_IOERR if anything goes
1114 ** wrong.
1116 static int winRead(
1117 sqlite3_file *id, /* File to read from */
1118 void *pBuf, /* Write content into this buffer */
1119 int amt, /* Number of bytes to read */
1120 sqlite3_int64 offset /* Begin reading at this offset */
1122 winFile *pFile = (winFile*)id; /* file handle */
1123 DWORD nRead; /* Number of bytes actually read from file */
1124 int nRetry = 0; /* Number of retrys */
1126 assert( id!=0 );
1127 SimulateIOError(return SQLITE_IOERR_READ);
1128 OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
1130 if( seekWinFile(pFile, offset) ){
1131 return SQLITE_FULL;
1133 while( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
1134 if( retryIoerr(&nRetry) ) continue;
1135 pFile->lastErrno = GetLastError();
1136 return winLogError(SQLITE_IOERR_READ, "winRead", pFile->zPath);
1138 logIoerr(nRetry);
1139 if( nRead<(DWORD)amt ){
1140 /* Unread parts of the buffer must be zero-filled */
1141 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
1142 return SQLITE_IOERR_SHORT_READ;
1145 return SQLITE_OK;
1149 ** Write data from a buffer into a file. Return SQLITE_OK on success
1150 ** or some other error code on failure.
1152 static int winWrite(
1153 sqlite3_file *id, /* File to write into */
1154 const void *pBuf, /* The bytes to be written */
1155 int amt, /* Number of bytes to write */
1156 sqlite3_int64 offset /* Offset into the file to begin writing at */
1158 int rc; /* True if error has occured, else false */
1159 winFile *pFile = (winFile*)id; /* File handle */
1160 int nRetry = 0; /* Number of retries */
1162 assert( amt>0 );
1163 assert( pFile );
1164 SimulateIOError(return SQLITE_IOERR_WRITE);
1165 SimulateDiskfullError(return SQLITE_FULL);
1167 OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
1169 rc = seekWinFile(pFile, offset);
1170 if( rc==0 ){
1171 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
1172 int nRem = amt; /* Number of bytes yet to be written */
1173 DWORD nWrite; /* Bytes written by each WriteFile() call */
1175 while( nRem>0 ){
1176 if( !WriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
1177 if( retryIoerr(&nRetry) ) continue;
1178 break;
1180 if( nWrite<=0 ) break;
1181 aRem += nWrite;
1182 nRem -= nWrite;
1184 if( nRem>0 ){
1185 pFile->lastErrno = GetLastError();
1186 rc = 1;
1190 if( rc ){
1191 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
1192 || ( pFile->lastErrno==ERROR_DISK_FULL )){
1193 return SQLITE_FULL;
1195 return winLogError(SQLITE_IOERR_WRITE, "winWrite", pFile->zPath);
1196 }else{
1197 logIoerr(nRetry);
1199 return SQLITE_OK;
1203 ** Truncate an open file to a specified size
1205 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
1206 winFile *pFile = (winFile*)id; /* File handle object */
1207 int rc = SQLITE_OK; /* Return code for this function */
1209 assert( pFile );
1211 OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
1212 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
1214 /* If the user has configured a chunk-size for this file, truncate the
1215 ** file so that it consists of an integer number of chunks (i.e. the
1216 ** actual file size after the operation may be larger than the requested
1217 ** size).
1219 if( pFile->szChunk>0 ){
1220 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
1223 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
1224 if( seekWinFile(pFile, nByte) ){
1225 rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate1", pFile->zPath);
1226 }else if( 0==SetEndOfFile(pFile->h) ){
1227 pFile->lastErrno = GetLastError();
1228 rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate2", pFile->zPath);
1231 OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
1232 return rc;
1235 #ifdef SQLITE_TEST
1237 ** Count the number of fullsyncs and normal syncs. This is used to test
1238 ** that syncs and fullsyncs are occuring at the right times.
1240 int sqlite3_sync_count = 0;
1241 int sqlite3_fullsync_count = 0;
1242 #endif
1245 ** Make sure all writes to a particular file are committed to disk.
1247 static int winSync(sqlite3_file *id, int flags){
1248 #ifndef SQLITE_NO_SYNC
1250 ** Used only when SQLITE_NO_SYNC is not defined.
1252 BOOL rc;
1253 #endif
1254 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
1255 (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
1257 ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
1258 ** OSTRACE() macros.
1260 winFile *pFile = (winFile*)id;
1261 #else
1262 UNUSED_PARAMETER(id);
1263 #endif
1265 assert( pFile );
1266 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
1267 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
1268 || (flags&0x0F)==SQLITE_SYNC_FULL
1271 OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
1273 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
1274 ** line is to test that doing so does not cause any problems.
1276 SimulateDiskfullError( return SQLITE_FULL );
1278 #ifndef SQLITE_TEST
1279 UNUSED_PARAMETER(flags);
1280 #else
1281 if( (flags&0x0F)==SQLITE_SYNC_FULL ){
1282 sqlite3_fullsync_count++;
1284 sqlite3_sync_count++;
1285 #endif
1287 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
1288 ** no-op
1290 #ifdef SQLITE_NO_SYNC
1291 return SQLITE_OK;
1292 #else
1293 rc = FlushFileBuffers(pFile->h);
1294 SimulateIOError( rc=FALSE );
1295 if( rc ){
1296 return SQLITE_OK;
1297 }else{
1298 pFile->lastErrno = GetLastError();
1299 return winLogError(SQLITE_IOERR_FSYNC, "winSync", pFile->zPath);
1301 #endif
1305 ** Determine the current size of a file in bytes
1307 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
1308 DWORD upperBits;
1309 DWORD lowerBits;
1310 winFile *pFile = (winFile*)id;
1311 DWORD error;
1313 assert( id!=0 );
1314 SimulateIOError(return SQLITE_IOERR_FSTAT);
1315 lowerBits = GetFileSize(pFile->h, &upperBits);
1316 if( (lowerBits == INVALID_FILE_SIZE)
1317 && ((error = GetLastError()) != NO_ERROR) )
1319 pFile->lastErrno = error;
1320 return winLogError(SQLITE_IOERR_FSTAT, "winFileSize", pFile->zPath);
1322 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
1323 return SQLITE_OK;
1327 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
1329 #ifndef LOCKFILE_FAIL_IMMEDIATELY
1330 # define LOCKFILE_FAIL_IMMEDIATELY 1
1331 #endif
1334 ** Acquire a reader lock.
1335 ** Different API routines are called depending on whether or not this
1336 ** is Win95 or WinNT.
1338 static int getReadLock(winFile *pFile){
1339 int res;
1340 if( isNT() ){
1341 OVERLAPPED ovlp;
1342 ovlp.Offset = SHARED_FIRST;
1343 ovlp.OffsetHigh = 0;
1344 ovlp.hEvent = 0;
1345 res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
1346 0, SHARED_SIZE, 0, &ovlp);
1347 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1349 #if SQLITE_OS_WINCE==0
1350 }else{
1351 int lk;
1352 sqlite3_randomness(sizeof(lk), &lk);
1353 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
1354 res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
1355 #endif
1357 if( res == 0 ){
1358 pFile->lastErrno = GetLastError();
1359 /* No need to log a failure to lock */
1361 return res;
1365 ** Undo a readlock
1367 static int unlockReadLock(winFile *pFile){
1368 int res;
1369 if( isNT() ){
1370 res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
1371 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1373 #if SQLITE_OS_WINCE==0
1374 }else{
1375 res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
1376 #endif
1378 if( res==0 && GetLastError()!=ERROR_NOT_LOCKED ){
1379 pFile->lastErrno = GetLastError();
1380 winLogError(SQLITE_IOERR_UNLOCK, "unlockReadLock", pFile->zPath);
1382 return res;
1386 ** Lock the file with the lock specified by parameter locktype - one
1387 ** of the following:
1389 ** (1) SHARED_LOCK
1390 ** (2) RESERVED_LOCK
1391 ** (3) PENDING_LOCK
1392 ** (4) EXCLUSIVE_LOCK
1394 ** Sometimes when requesting one lock state, additional lock states
1395 ** are inserted in between. The locking might fail on one of the later
1396 ** transitions leaving the lock state different from what it started but
1397 ** still short of its goal. The following chart shows the allowed
1398 ** transitions and the inserted intermediate states:
1400 ** UNLOCKED -> SHARED
1401 ** SHARED -> RESERVED
1402 ** SHARED -> (PENDING) -> EXCLUSIVE
1403 ** RESERVED -> (PENDING) -> EXCLUSIVE
1404 ** PENDING -> EXCLUSIVE
1406 ** This routine will only increase a lock. The winUnlock() routine
1407 ** erases all locks at once and returns us immediately to locking level 0.
1408 ** It is not possible to lower the locking level one step at a time. You
1409 ** must go straight to locking level 0.
1411 static int winLock(sqlite3_file *id, int locktype){
1412 int rc = SQLITE_OK; /* Return code from subroutines */
1413 int res = 1; /* Result of a windows lock call */
1414 int newLocktype; /* Set pFile->locktype to this value before exiting */
1415 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
1416 winFile *pFile = (winFile*)id;
1417 DWORD error = NO_ERROR;
1419 assert( id!=0 );
1420 OSTRACE(("LOCK %d %d was %d(%d)\n",
1421 pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
1423 /* If there is already a lock of this type or more restrictive on the
1424 ** OsFile, do nothing. Don't use the end_lock: exit path, as
1425 ** sqlite3OsEnterMutex() hasn't been called yet.
1427 if( pFile->locktype>=locktype ){
1428 return SQLITE_OK;
1431 /* Make sure the locking sequence is correct
1433 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
1434 assert( locktype!=PENDING_LOCK );
1435 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1437 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
1438 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
1439 ** the PENDING_LOCK byte is temporary.
1441 newLocktype = pFile->locktype;
1442 if( (pFile->locktype==NO_LOCK)
1443 || ( (locktype==EXCLUSIVE_LOCK)
1444 && (pFile->locktype==RESERVED_LOCK))
1446 int cnt = 3;
1447 while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
1448 /* Try 3 times to get the pending lock. The pending lock might be
1449 ** held by another reader process who will release it momentarily.
1451 OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
1452 Sleep(1);
1454 gotPendingLock = res;
1455 if( !res ){
1456 error = GetLastError();
1460 /* Acquire a shared lock
1462 if( locktype==SHARED_LOCK && res ){
1463 assert( pFile->locktype==NO_LOCK );
1464 res = getReadLock(pFile);
1465 if( res ){
1466 newLocktype = SHARED_LOCK;
1467 }else{
1468 error = GetLastError();
1472 /* Acquire a RESERVED lock
1474 if( locktype==RESERVED_LOCK && res ){
1475 assert( pFile->locktype==SHARED_LOCK );
1476 res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1477 if( res ){
1478 newLocktype = RESERVED_LOCK;
1479 }else{
1480 error = GetLastError();
1484 /* Acquire a PENDING lock
1486 if( locktype==EXCLUSIVE_LOCK && res ){
1487 newLocktype = PENDING_LOCK;
1488 gotPendingLock = 0;
1491 /* Acquire an EXCLUSIVE lock
1493 if( locktype==EXCLUSIVE_LOCK && res ){
1494 assert( pFile->locktype>=SHARED_LOCK );
1495 res = unlockReadLock(pFile);
1496 OSTRACE(("unreadlock = %d\n", res));
1497 res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
1498 if( res ){
1499 newLocktype = EXCLUSIVE_LOCK;
1500 }else{
1501 error = GetLastError();
1502 OSTRACE(("error-code = %d\n", error));
1503 getReadLock(pFile);
1507 /* If we are holding a PENDING lock that ought to be released, then
1508 ** release it now.
1510 if( gotPendingLock && locktype==SHARED_LOCK ){
1511 UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
1514 /* Update the state of the lock has held in the file descriptor then
1515 ** return the appropriate result code.
1517 if( res ){
1518 rc = SQLITE_OK;
1519 }else{
1520 OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
1521 locktype, newLocktype));
1522 pFile->lastErrno = error;
1523 rc = SQLITE_BUSY;
1525 pFile->locktype = (u8)newLocktype;
1526 return rc;
1530 ** This routine checks if there is a RESERVED lock held on the specified
1531 ** file by this or any other process. If such a lock is held, return
1532 ** non-zero, otherwise zero.
1534 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
1535 int rc;
1536 winFile *pFile = (winFile*)id;
1538 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1540 assert( id!=0 );
1541 if( pFile->locktype>=RESERVED_LOCK ){
1542 rc = 1;
1543 OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
1544 }else{
1545 rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1546 if( rc ){
1547 UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1549 rc = !rc;
1550 OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
1552 *pResOut = rc;
1553 return SQLITE_OK;
1557 ** Lower the locking level on file descriptor id to locktype. locktype
1558 ** must be either NO_LOCK or SHARED_LOCK.
1560 ** If the locking level of the file descriptor is already at or below
1561 ** the requested locking level, this routine is a no-op.
1563 ** It is not possible for this routine to fail if the second argument
1564 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
1565 ** might return SQLITE_IOERR;
1567 static int winUnlock(sqlite3_file *id, int locktype){
1568 int type;
1569 winFile *pFile = (winFile*)id;
1570 int rc = SQLITE_OK;
1571 assert( pFile!=0 );
1572 assert( locktype<=SHARED_LOCK );
1573 OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
1574 pFile->locktype, pFile->sharedLockByte));
1575 type = pFile->locktype;
1576 if( type>=EXCLUSIVE_LOCK ){
1577 UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
1578 if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
1579 /* This should never happen. We should always be able to
1580 ** reacquire the read lock */
1581 rc = winLogError(SQLITE_IOERR_UNLOCK, "winUnlock", pFile->zPath);
1584 if( type>=RESERVED_LOCK ){
1585 UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1587 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
1588 unlockReadLock(pFile);
1590 if( type>=PENDING_LOCK ){
1591 UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
1593 pFile->locktype = (u8)locktype;
1594 return rc;
1598 ** Control and query of the open file handle.
1600 static int winFileControl(sqlite3_file *id, int op, void *pArg){
1601 winFile *pFile = (winFile*)id;
1602 switch( op ){
1603 case SQLITE_FCNTL_LOCKSTATE: {
1604 *(int*)pArg = pFile->locktype;
1605 return SQLITE_OK;
1607 case SQLITE_LAST_ERRNO: {
1608 *(int*)pArg = (int)pFile->lastErrno;
1609 return SQLITE_OK;
1611 case SQLITE_FCNTL_CHUNK_SIZE: {
1612 pFile->szChunk = *(int *)pArg;
1613 return SQLITE_OK;
1615 case SQLITE_FCNTL_SIZE_HINT: {
1616 if( pFile->szChunk>0 ){
1617 sqlite3_int64 oldSz;
1618 int rc = winFileSize(id, &oldSz);
1619 if( rc==SQLITE_OK ){
1620 sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
1621 if( newSz>oldSz ){
1622 SimulateIOErrorBenign(1);
1623 rc = winTruncate(id, newSz);
1624 SimulateIOErrorBenign(0);
1627 return rc;
1629 return SQLITE_OK;
1631 case SQLITE_FCNTL_PERSIST_WAL: {
1632 int bPersist = *(int*)pArg;
1633 if( bPersist<0 ){
1634 *(int*)pArg = pFile->bPersistWal;
1635 }else{
1636 pFile->bPersistWal = bPersist!=0;
1638 return SQLITE_OK;
1640 case SQLITE_FCNTL_SYNC_OMITTED: {
1641 return SQLITE_OK;
1643 case SQLITE_FCNTL_WIN32_AV_RETRY: {
1644 int *a = (int*)pArg;
1645 if( a[0]>0 ){
1646 win32IoerrRetry = a[0];
1647 }else{
1648 a[0] = win32IoerrRetry;
1650 if( a[1]>0 ){
1651 win32IoerrRetryDelay = a[1];
1652 }else{
1653 a[1] = win32IoerrRetryDelay;
1655 return SQLITE_OK;
1658 return SQLITE_NOTFOUND;
1662 ** Return the sector size in bytes of the underlying block device for
1663 ** the specified file. This is almost always 512 bytes, but may be
1664 ** larger for some devices.
1666 ** SQLite code assumes this function cannot fail. It also assumes that
1667 ** if two files are created in the same file-system directory (i.e.
1668 ** a database and its journal file) that the sector size will be the
1669 ** same for both.
1671 static int winSectorSize(sqlite3_file *id){
1672 assert( id!=0 );
1673 return (int)(((winFile*)id)->sectorSize);
1677 ** Return a vector of device characteristics.
1679 static int winDeviceCharacteristics(sqlite3_file *id){
1680 UNUSED_PARAMETER(id);
1681 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
1684 #ifndef SQLITE_OMIT_WAL
1687 ** Windows will only let you create file view mappings
1688 ** on allocation size granularity boundaries.
1689 ** During sqlite3_os_init() we do a GetSystemInfo()
1690 ** to get the granularity size.
1692 SYSTEM_INFO winSysInfo;
1695 ** Helper functions to obtain and relinquish the global mutex. The
1696 ** global mutex is used to protect the winLockInfo objects used by
1697 ** this file, all of which may be shared by multiple threads.
1699 ** Function winShmMutexHeld() is used to assert() that the global mutex
1700 ** is held when required. This function is only used as part of assert()
1701 ** statements. e.g.
1703 ** winShmEnterMutex()
1704 ** assert( winShmMutexHeld() );
1705 ** winShmLeaveMutex()
1707 static void winShmEnterMutex(void){
1708 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1710 static void winShmLeaveMutex(void){
1711 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1713 #ifdef SQLITE_DEBUG
1714 static int winShmMutexHeld(void) {
1715 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1717 #endif
1720 ** Object used to represent a single file opened and mmapped to provide
1721 ** shared memory. When multiple threads all reference the same
1722 ** log-summary, each thread has its own winFile object, but they all
1723 ** point to a single instance of this object. In other words, each
1724 ** log-summary is opened only once per process.
1726 ** winShmMutexHeld() must be true when creating or destroying
1727 ** this object or while reading or writing the following fields:
1729 ** nRef
1730 ** pNext
1732 ** The following fields are read-only after the object is created:
1734 ** fid
1735 ** zFilename
1737 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
1738 ** winShmMutexHeld() is true when reading or writing any other field
1739 ** in this structure.
1742 struct winShmNode {
1743 sqlite3_mutex *mutex; /* Mutex to access this object */
1744 char *zFilename; /* Name of the file */
1745 winFile hFile; /* File handle from winOpen */
1747 int szRegion; /* Size of shared-memory regions */
1748 int nRegion; /* Size of array apRegion */
1749 struct ShmRegion {
1750 HANDLE hMap; /* File handle from CreateFileMapping */
1751 void *pMap;
1752 } *aRegion;
1753 DWORD lastErrno; /* The Windows errno from the last I/O error */
1755 int nRef; /* Number of winShm objects pointing to this */
1756 winShm *pFirst; /* All winShm objects pointing to this */
1757 winShmNode *pNext; /* Next in list of all winShmNode objects */
1758 #ifdef SQLITE_DEBUG
1759 u8 nextShmId; /* Next available winShm.id value */
1760 #endif
1764 ** A global array of all winShmNode objects.
1766 ** The winShmMutexHeld() must be true while reading or writing this list.
1768 static winShmNode *winShmNodeList = 0;
1771 ** Structure used internally by this VFS to record the state of an
1772 ** open shared memory connection.
1774 ** The following fields are initialized when this object is created and
1775 ** are read-only thereafter:
1777 ** winShm.pShmNode
1778 ** winShm.id
1780 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
1781 ** while accessing any read/write fields.
1783 struct winShm {
1784 winShmNode *pShmNode; /* The underlying winShmNode object */
1785 winShm *pNext; /* Next winShm with the same winShmNode */
1786 u8 hasMutex; /* True if holding the winShmNode mutex */
1787 u16 sharedMask; /* Mask of shared locks held */
1788 u16 exclMask; /* Mask of exclusive locks held */
1789 #ifdef SQLITE_DEBUG
1790 u8 id; /* Id of this connection with its winShmNode */
1791 #endif
1795 ** Constants used for locking
1797 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
1798 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
1801 ** Apply advisory locks for all n bytes beginning at ofst.
1803 #define _SHM_UNLCK 1
1804 #define _SHM_RDLCK 2
1805 #define _SHM_WRLCK 3
1806 static int winShmSystemLock(
1807 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
1808 int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
1809 int ofst, /* Offset to first byte to be locked/unlocked */
1810 int nByte /* Number of bytes to lock or unlock */
1812 OVERLAPPED ovlp;
1813 DWORD dwFlags;
1814 int rc = 0; /* Result code form Lock/UnlockFileEx() */
1816 /* Access to the winShmNode object is serialized by the caller */
1817 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
1819 /* Initialize the locking parameters */
1820 dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
1821 if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
1823 memset(&ovlp, 0, sizeof(OVERLAPPED));
1824 ovlp.Offset = ofst;
1826 /* Release/Acquire the system-level lock */
1827 if( lockType==_SHM_UNLCK ){
1828 rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
1829 }else{
1830 rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
1833 if( rc!= 0 ){
1834 rc = SQLITE_OK;
1835 }else{
1836 pFile->lastErrno = GetLastError();
1837 rc = SQLITE_BUSY;
1840 OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
1841 pFile->hFile.h,
1842 rc==SQLITE_OK ? "ok" : "failed",
1843 lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
1844 pFile->lastErrno));
1846 return rc;
1849 /* Forward references to VFS methods */
1850 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
1851 static int winDelete(sqlite3_vfs *,const char*,int);
1854 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
1856 ** This is not a VFS shared-memory method; it is a utility function called
1857 ** by VFS shared-memory methods.
1859 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
1860 winShmNode **pp;
1861 winShmNode *p;
1862 BOOL bRc;
1863 assert( winShmMutexHeld() );
1864 pp = &winShmNodeList;
1865 while( (p = *pp)!=0 ){
1866 if( p->nRef==0 ){
1867 int i;
1868 if( p->mutex ) sqlite3_mutex_free(p->mutex);
1869 for(i=0; i<p->nRegion; i++){
1870 bRc = UnmapViewOfFile(p->aRegion[i].pMap);
1871 OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
1872 (int)GetCurrentProcessId(), i,
1873 bRc ? "ok" : "failed"));
1874 bRc = CloseHandle(p->aRegion[i].hMap);
1875 OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
1876 (int)GetCurrentProcessId(), i,
1877 bRc ? "ok" : "failed"));
1879 if( p->hFile.h != INVALID_HANDLE_VALUE ){
1880 SimulateIOErrorBenign(1);
1881 winClose((sqlite3_file *)&p->hFile);
1882 SimulateIOErrorBenign(0);
1884 if( deleteFlag ){
1885 SimulateIOErrorBenign(1);
1886 winDelete(pVfs, p->zFilename, 0);
1887 SimulateIOErrorBenign(0);
1889 *pp = p->pNext;
1890 sqlite3_free(p->aRegion);
1891 sqlite3_free(p);
1892 }else{
1893 pp = &p->pNext;
1899 ** Open the shared-memory area associated with database file pDbFd.
1901 ** When opening a new shared-memory file, if no other instances of that
1902 ** file are currently open, in this process or in other processes, then
1903 ** the file must be truncated to zero length or have its header cleared.
1905 static int winOpenSharedMemory(winFile *pDbFd){
1906 struct winShm *p; /* The connection to be opened */
1907 struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
1908 int rc; /* Result code */
1909 struct winShmNode *pNew; /* Newly allocated winShmNode */
1910 int nName; /* Size of zName in bytes */
1912 assert( pDbFd->pShm==0 ); /* Not previously opened */
1914 /* Allocate space for the new sqlite3_shm object. Also speculatively
1915 ** allocate space for a new winShmNode and filename.
1917 p = sqlite3_malloc( sizeof(*p) );
1918 if( p==0 ) return SQLITE_NOMEM;
1919 memset(p, 0, sizeof(*p));
1920 nName = sqlite3Strlen30(pDbFd->zPath);
1921 pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
1922 if( pNew==0 ){
1923 sqlite3_free(p);
1924 return SQLITE_NOMEM;
1926 memset(pNew, 0, sizeof(*pNew));
1927 pNew->zFilename = (char*)&pNew[1];
1928 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
1929 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
1931 /* Look to see if there is an existing winShmNode that can be used.
1932 ** If no matching winShmNode currently exists, create a new one.
1934 winShmEnterMutex();
1935 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
1936 /* TBD need to come up with better match here. Perhaps
1937 ** use FILE_ID_BOTH_DIR_INFO Structure.
1939 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
1941 if( pShmNode ){
1942 sqlite3_free(pNew);
1943 }else{
1944 pShmNode = pNew;
1945 pNew = 0;
1946 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
1947 pShmNode->pNext = winShmNodeList;
1948 winShmNodeList = pShmNode;
1950 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1951 if( pShmNode->mutex==0 ){
1952 rc = SQLITE_NOMEM;
1953 goto shm_open_err;
1956 rc = winOpen(pDbFd->pVfs,
1957 pShmNode->zFilename, /* Name of the file (UTF-8) */
1958 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
1959 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
1961 if( SQLITE_OK!=rc ){
1962 rc = SQLITE_CANTOPEN_BKPT;
1963 goto shm_open_err;
1966 /* Check to see if another process is holding the dead-man switch.
1967 ** If not, truncate the file to zero length.
1969 if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
1970 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
1971 if( rc!=SQLITE_OK ){
1972 rc = winLogError(SQLITE_IOERR_SHMOPEN, "winOpenShm", pDbFd->zPath);
1975 if( rc==SQLITE_OK ){
1976 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
1977 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
1979 if( rc ) goto shm_open_err;
1982 /* Make the new connection a child of the winShmNode */
1983 p->pShmNode = pShmNode;
1984 #ifdef SQLITE_DEBUG
1985 p->id = pShmNode->nextShmId++;
1986 #endif
1987 pShmNode->nRef++;
1988 pDbFd->pShm = p;
1989 winShmLeaveMutex();
1991 /* The reference count on pShmNode has already been incremented under
1992 ** the cover of the winShmEnterMutex() mutex and the pointer from the
1993 ** new (struct winShm) object to the pShmNode has been set. All that is
1994 ** left to do is to link the new object into the linked list starting
1995 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
1996 ** mutex.
1998 sqlite3_mutex_enter(pShmNode->mutex);
1999 p->pNext = pShmNode->pFirst;
2000 pShmNode->pFirst = p;
2001 sqlite3_mutex_leave(pShmNode->mutex);
2002 return SQLITE_OK;
2004 /* Jump here on any error */
2005 shm_open_err:
2006 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
2007 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
2008 sqlite3_free(p);
2009 sqlite3_free(pNew);
2010 winShmLeaveMutex();
2011 return rc;
2015 ** Close a connection to shared-memory. Delete the underlying
2016 ** storage if deleteFlag is true.
2018 static int winShmUnmap(
2019 sqlite3_file *fd, /* Database holding shared memory */
2020 int deleteFlag /* Delete after closing if true */
2022 winFile *pDbFd; /* Database holding shared-memory */
2023 winShm *p; /* The connection to be closed */
2024 winShmNode *pShmNode; /* The underlying shared-memory file */
2025 winShm **pp; /* For looping over sibling connections */
2027 pDbFd = (winFile*)fd;
2028 p = pDbFd->pShm;
2029 if( p==0 ) return SQLITE_OK;
2030 pShmNode = p->pShmNode;
2032 /* Remove connection p from the set of connections associated
2033 ** with pShmNode */
2034 sqlite3_mutex_enter(pShmNode->mutex);
2035 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
2036 *pp = p->pNext;
2038 /* Free the connection p */
2039 sqlite3_free(p);
2040 pDbFd->pShm = 0;
2041 sqlite3_mutex_leave(pShmNode->mutex);
2043 /* If pShmNode->nRef has reached 0, then close the underlying
2044 ** shared-memory file, too */
2045 winShmEnterMutex();
2046 assert( pShmNode->nRef>0 );
2047 pShmNode->nRef--;
2048 if( pShmNode->nRef==0 ){
2049 winShmPurge(pDbFd->pVfs, deleteFlag);
2051 winShmLeaveMutex();
2053 return SQLITE_OK;
2057 ** Change the lock state for a shared-memory segment.
2059 static int winShmLock(
2060 sqlite3_file *fd, /* Database file holding the shared memory */
2061 int ofst, /* First lock to acquire or release */
2062 int n, /* Number of locks to acquire or release */
2063 int flags /* What to do with the lock */
2065 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
2066 winShm *p = pDbFd->pShm; /* The shared memory being locked */
2067 winShm *pX; /* For looping over all siblings */
2068 winShmNode *pShmNode = p->pShmNode;
2069 int rc = SQLITE_OK; /* Result code */
2070 u16 mask; /* Mask of locks to take or release */
2072 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
2073 assert( n>=1 );
2074 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
2075 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
2076 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
2077 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
2078 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
2080 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
2081 assert( n>1 || mask==(1<<ofst) );
2082 sqlite3_mutex_enter(pShmNode->mutex);
2083 if( flags & SQLITE_SHM_UNLOCK ){
2084 u16 allMask = 0; /* Mask of locks held by siblings */
2086 /* See if any siblings hold this same lock */
2087 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
2088 if( pX==p ) continue;
2089 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
2090 allMask |= pX->sharedMask;
2093 /* Unlock the system-level locks */
2094 if( (mask & allMask)==0 ){
2095 rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
2096 }else{
2097 rc = SQLITE_OK;
2100 /* Undo the local locks */
2101 if( rc==SQLITE_OK ){
2102 p->exclMask &= ~mask;
2103 p->sharedMask &= ~mask;
2105 }else if( flags & SQLITE_SHM_SHARED ){
2106 u16 allShared = 0; /* Union of locks held by connections other than "p" */
2108 /* Find out which shared locks are already held by sibling connections.
2109 ** If any sibling already holds an exclusive lock, go ahead and return
2110 ** SQLITE_BUSY.
2112 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
2113 if( (pX->exclMask & mask)!=0 ){
2114 rc = SQLITE_BUSY;
2115 break;
2117 allShared |= pX->sharedMask;
2120 /* Get shared locks at the system level, if necessary */
2121 if( rc==SQLITE_OK ){
2122 if( (allShared & mask)==0 ){
2123 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
2124 }else{
2125 rc = SQLITE_OK;
2129 /* Get the local shared locks */
2130 if( rc==SQLITE_OK ){
2131 p->sharedMask |= mask;
2133 }else{
2134 /* Make sure no sibling connections hold locks that will block this
2135 ** lock. If any do, return SQLITE_BUSY right away.
2137 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
2138 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
2139 rc = SQLITE_BUSY;
2140 break;
2144 /* Get the exclusive locks at the system level. Then if successful
2145 ** also mark the local connection as being locked.
2147 if( rc==SQLITE_OK ){
2148 rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
2149 if( rc==SQLITE_OK ){
2150 assert( (p->sharedMask & mask)==0 );
2151 p->exclMask |= mask;
2155 sqlite3_mutex_leave(pShmNode->mutex);
2156 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
2157 p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
2158 rc ? "failed" : "ok"));
2159 return rc;
2163 ** Implement a memory barrier or memory fence on shared memory.
2165 ** All loads and stores begun before the barrier must complete before
2166 ** any load or store begun after the barrier.
2168 static void winShmBarrier(
2169 sqlite3_file *fd /* Database holding the shared memory */
2171 UNUSED_PARAMETER(fd);
2172 /* MemoryBarrier(); // does not work -- do not know why not */
2173 winShmEnterMutex();
2174 winShmLeaveMutex();
2178 ** This function is called to obtain a pointer to region iRegion of the
2179 ** shared-memory associated with the database file fd. Shared-memory regions
2180 ** are numbered starting from zero. Each shared-memory region is szRegion
2181 ** bytes in size.
2183 ** If an error occurs, an error code is returned and *pp is set to NULL.
2185 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
2186 ** region has not been allocated (by any client, including one running in a
2187 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
2188 ** isWrite is non-zero and the requested shared-memory region has not yet
2189 ** been allocated, it is allocated by this function.
2191 ** If the shared-memory region has already been allocated or is allocated by
2192 ** this call as described above, then it is mapped into this processes
2193 ** address space (if it is not already), *pp is set to point to the mapped
2194 ** memory and SQLITE_OK returned.
2196 static int winShmMap(
2197 sqlite3_file *fd, /* Handle open on database file */
2198 int iRegion, /* Region to retrieve */
2199 int szRegion, /* Size of regions */
2200 int isWrite, /* True to extend file if necessary */
2201 void volatile **pp /* OUT: Mapped memory */
2203 winFile *pDbFd = (winFile*)fd;
2204 winShm *p = pDbFd->pShm;
2205 winShmNode *pShmNode;
2206 int rc = SQLITE_OK;
2208 if( !p ){
2209 rc = winOpenSharedMemory(pDbFd);
2210 if( rc!=SQLITE_OK ) return rc;
2211 p = pDbFd->pShm;
2213 pShmNode = p->pShmNode;
2215 sqlite3_mutex_enter(pShmNode->mutex);
2216 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
2218 if( pShmNode->nRegion<=iRegion ){
2219 struct ShmRegion *apNew; /* New aRegion[] array */
2220 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
2221 sqlite3_int64 sz; /* Current size of wal-index file */
2223 pShmNode->szRegion = szRegion;
2225 /* The requested region is not mapped into this processes address space.
2226 ** Check to see if it has been allocated (i.e. if the wal-index file is
2227 ** large enough to contain the requested region).
2229 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
2230 if( rc!=SQLITE_OK ){
2231 rc = winLogError(SQLITE_IOERR_SHMSIZE, "winShmMap1", pDbFd->zPath);
2232 goto shmpage_out;
2235 if( sz<nByte ){
2236 /* The requested memory region does not exist. If isWrite is set to
2237 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
2239 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
2240 ** the requested memory region.
2242 if( !isWrite ) goto shmpage_out;
2243 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
2244 if( rc!=SQLITE_OK ){
2245 rc = winLogError(SQLITE_IOERR_SHMSIZE, "winShmMap2", pDbFd->zPath);
2246 goto shmpage_out;
2250 /* Map the requested memory region into this processes address space. */
2251 apNew = (struct ShmRegion *)sqlite3_realloc(
2252 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
2254 if( !apNew ){
2255 rc = SQLITE_IOERR_NOMEM;
2256 goto shmpage_out;
2258 pShmNode->aRegion = apNew;
2260 while( pShmNode->nRegion<=iRegion ){
2261 HANDLE hMap; /* file-mapping handle */
2262 void *pMap = 0; /* Mapped memory region */
2264 hMap = CreateFileMapping(pShmNode->hFile.h,
2265 NULL, PAGE_READWRITE, 0, nByte, NULL
2267 OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
2268 (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
2269 hMap ? "ok" : "failed"));
2270 if( hMap ){
2271 int iOffset = pShmNode->nRegion*szRegion;
2272 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
2273 pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
2274 0, iOffset - iOffsetShift, szRegion + iOffsetShift
2276 OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
2277 (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
2278 pMap ? "ok" : "failed"));
2280 if( !pMap ){
2281 pShmNode->lastErrno = GetLastError();
2282 rc = winLogError(SQLITE_IOERR_SHMMAP, "winShmMap3", pDbFd->zPath);
2283 if( hMap ) CloseHandle(hMap);
2284 goto shmpage_out;
2287 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
2288 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
2289 pShmNode->nRegion++;
2293 shmpage_out:
2294 if( pShmNode->nRegion>iRegion ){
2295 int iOffset = iRegion*szRegion;
2296 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
2297 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
2298 *pp = (void *)&p[iOffsetShift];
2299 }else{
2300 *pp = 0;
2302 sqlite3_mutex_leave(pShmNode->mutex);
2303 return rc;
2306 #else
2307 # define winShmMap 0
2308 # define winShmLock 0
2309 # define winShmBarrier 0
2310 # define winShmUnmap 0
2311 #endif /* #ifndef SQLITE_OMIT_WAL */
2314 ** Here ends the implementation of all sqlite3_file methods.
2316 ********************** End sqlite3_file Methods *******************************
2317 ******************************************************************************/
2320 ** This vector defines all the methods that can operate on an
2321 ** sqlite3_file for win32.
2323 static const sqlite3_io_methods winIoMethod = {
2324 2, /* iVersion */
2325 winClose, /* xClose */
2326 winRead, /* xRead */
2327 winWrite, /* xWrite */
2328 winTruncate, /* xTruncate */
2329 winSync, /* xSync */
2330 winFileSize, /* xFileSize */
2331 winLock, /* xLock */
2332 winUnlock, /* xUnlock */
2333 winCheckReservedLock, /* xCheckReservedLock */
2334 winFileControl, /* xFileControl */
2335 winSectorSize, /* xSectorSize */
2336 winDeviceCharacteristics, /* xDeviceCharacteristics */
2337 winShmMap, /* xShmMap */
2338 winShmLock, /* xShmLock */
2339 winShmBarrier, /* xShmBarrier */
2340 winShmUnmap /* xShmUnmap */
2343 /****************************************************************************
2344 **************************** sqlite3_vfs methods ****************************
2346 ** This division contains the implementation of methods on the
2347 ** sqlite3_vfs object.
2351 ** Convert a UTF-8 filename into whatever form the underlying
2352 ** operating system wants filenames in. Space to hold the result
2353 ** is obtained from malloc and must be freed by the calling
2354 ** function.
2356 static void *convertUtf8Filename(const char *zFilename){
2357 void *zConverted = 0;
2358 if( isNT() ){
2359 zConverted = utf8ToUnicode(zFilename);
2360 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2362 #if SQLITE_OS_WINCE==0
2363 }else{
2364 zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
2365 #endif
2367 /* caller will handle out of memory */
2368 return zConverted;
2372 ** Create a temporary file name in zBuf. zBuf must be big enough to
2373 ** hold at pVfs->mxPathname characters.
2375 static int getTempname(int nBuf, char *zBuf){
2376 static char zChars[] =
2377 "abcdefghijklmnopqrstuvwxyz"
2378 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2379 "0123456789";
2380 size_t i, j;
2381 char zTempPath[MAX_PATH+1];
2383 /* It's odd to simulate an io-error here, but really this is just
2384 ** using the io-error infrastructure to test that SQLite handles this
2385 ** function failing.
2387 SimulateIOError( return SQLITE_IOERR );
2389 if( sqlite3_temp_directory ){
2390 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
2391 }else if( isNT() ){
2392 char *zMulti;
2393 WCHAR zWidePath[MAX_PATH];
2394 GetTempPathW(MAX_PATH-30, zWidePath);
2395 zMulti = unicodeToUtf8(zWidePath);
2396 if( zMulti ){
2397 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
2398 free(zMulti);
2399 }else{
2400 return SQLITE_NOMEM;
2402 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2403 ** Since the ASCII version of these Windows API do not exist for WINCE,
2404 ** it's important to not reference them for WINCE builds.
2406 #if SQLITE_OS_WINCE==0
2407 }else{
2408 char *zUtf8;
2409 char zMbcsPath[MAX_PATH];
2410 GetTempPathA(MAX_PATH-30, zMbcsPath);
2411 zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
2412 if( zUtf8 ){
2413 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
2414 free(zUtf8);
2415 }else{
2416 return SQLITE_NOMEM;
2418 #endif
2421 /* Check that the output buffer is large enough for the temporary file
2422 ** name. If it is not, return SQLITE_ERROR.
2424 if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
2425 return SQLITE_ERROR;
2428 for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
2429 zTempPath[i] = 0;
2431 sqlite3_snprintf(nBuf-17, zBuf,
2432 "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
2433 j = sqlite3Strlen30(zBuf);
2434 sqlite3_randomness(15, &zBuf[j]);
2435 for(i=0; i<15; i++, j++){
2436 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
2438 zBuf[j] = 0;
2440 OSTRACE(("TEMP FILENAME: %s\n", zBuf));
2441 return SQLITE_OK;
2445 ** Open a file.
2447 static int winOpen(
2448 sqlite3_vfs *pVfs, /* Not used */
2449 const char *zName, /* Name of the file (UTF-8) */
2450 sqlite3_file *id, /* Write the SQLite file handle here */
2451 int flags, /* Open mode flags */
2452 int *pOutFlags /* Status return flags */
2454 HANDLE h;
2455 DWORD dwDesiredAccess;
2456 DWORD dwShareMode;
2457 DWORD dwCreationDisposition;
2458 DWORD dwFlagsAndAttributes = 0;
2459 #if SQLITE_OS_WINCE
2460 int isTemp = 0;
2461 #endif
2462 winFile *pFile = (winFile*)id;
2463 void *zConverted; /* Filename in OS encoding */
2464 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
2465 int cnt = 0;
2467 /* If argument zPath is a NULL pointer, this function is required to open
2468 ** a temporary file. Use this buffer to store the file name in.
2470 char zTmpname[MAX_PATH+1]; /* Buffer used to create temp filename */
2472 int rc = SQLITE_OK; /* Function Return Code */
2473 #if !defined(NDEBUG) || SQLITE_OS_WINCE
2474 int eType = flags&0xFFFFFF00; /* Type of file to open */
2475 #endif
2477 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
2478 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
2479 int isCreate = (flags & SQLITE_OPEN_CREATE);
2480 #ifndef NDEBUG
2481 int isReadonly = (flags & SQLITE_OPEN_READONLY);
2482 #endif
2483 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
2485 #ifndef NDEBUG
2486 int isOpenJournal = (isCreate && (
2487 eType==SQLITE_OPEN_MASTER_JOURNAL
2488 || eType==SQLITE_OPEN_MAIN_JOURNAL
2489 || eType==SQLITE_OPEN_WAL
2491 #endif
2493 /* Check the following statements are true:
2495 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
2496 ** (b) if CREATE is set, then READWRITE must also be set, and
2497 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
2498 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
2500 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
2501 assert(isCreate==0 || isReadWrite);
2502 assert(isExclusive==0 || isCreate);
2503 assert(isDelete==0 || isCreate);
2505 /* The main DB, main journal, WAL file and master journal are never
2506 ** automatically deleted. Nor are they ever temporary files. */
2507 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
2508 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
2509 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
2510 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
2512 /* Assert that the upper layer has set one of the "file-type" flags. */
2513 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
2514 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
2515 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
2516 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
2519 assert( id!=0 );
2520 UNUSED_PARAMETER(pVfs);
2522 pFile->h = INVALID_HANDLE_VALUE;
2524 /* If the second argument to this function is NULL, generate a
2525 ** temporary file name to use
2527 if( !zUtf8Name ){
2528 assert(isDelete && !isOpenJournal);
2529 rc = getTempname(MAX_PATH+1, zTmpname);
2530 if( rc!=SQLITE_OK ){
2531 return rc;
2533 zUtf8Name = zTmpname;
2536 /* Convert the filename to the system encoding. */
2537 zConverted = convertUtf8Filename(zUtf8Name);
2538 if( zConverted==0 ){
2539 return SQLITE_NOMEM;
2542 if( isReadWrite ){
2543 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
2544 }else{
2545 dwDesiredAccess = GENERIC_READ;
2548 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
2549 ** created. SQLite doesn't use it to indicate "exclusive access"
2550 ** as it is usually understood.
2552 if( isExclusive ){
2553 /* Creates a new file, only if it does not already exist. */
2554 /* If the file exists, it fails. */
2555 dwCreationDisposition = CREATE_NEW;
2556 }else if( isCreate ){
2557 /* Open existing file, or create if it doesn't exist */
2558 dwCreationDisposition = OPEN_ALWAYS;
2559 }else{
2560 /* Opens a file, only if it exists. */
2561 dwCreationDisposition = OPEN_EXISTING;
2564 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
2566 if( isDelete ){
2567 #if SQLITE_OS_WINCE
2568 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
2569 isTemp = 1;
2570 #else
2571 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
2572 | FILE_ATTRIBUTE_HIDDEN
2573 | FILE_FLAG_DELETE_ON_CLOSE;
2574 #endif
2575 }else{
2576 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
2578 /* Reports from the internet are that performance is always
2579 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
2580 #if SQLITE_OS_WINCE
2581 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
2582 #endif
2584 if( isNT() ){
2585 while( (h = CreateFileW((WCHAR*)zConverted,
2586 dwDesiredAccess,
2587 dwShareMode, NULL,
2588 dwCreationDisposition,
2589 dwFlagsAndAttributes,
2590 NULL))==INVALID_HANDLE_VALUE &&
2591 retryIoerr(&cnt) ){}
2592 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2593 ** Since the ASCII version of these Windows API do not exist for WINCE,
2594 ** it's important to not reference them for WINCE builds.
2596 #if SQLITE_OS_WINCE==0
2597 }else{
2598 while( (h = CreateFileA((char*)zConverted,
2599 dwDesiredAccess,
2600 dwShareMode, NULL,
2601 dwCreationDisposition,
2602 dwFlagsAndAttributes,
2603 NULL))==INVALID_HANDLE_VALUE &&
2604 retryIoerr(&cnt) ){}
2605 #endif
2608 logIoerr(cnt);
2610 OSTRACE(("OPEN %d %s 0x%lx %s\n",
2611 h, zName, dwDesiredAccess,
2612 h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
2614 if( h==INVALID_HANDLE_VALUE ){
2615 pFile->lastErrno = GetLastError();
2616 winLogError(SQLITE_CANTOPEN, "winOpen", zUtf8Name);
2617 free(zConverted);
2618 if( isReadWrite && !isExclusive ){
2619 return winOpen(pVfs, zName, id,
2620 ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
2621 }else{
2622 return SQLITE_CANTOPEN_BKPT;
2626 if( pOutFlags ){
2627 if( isReadWrite ){
2628 *pOutFlags = SQLITE_OPEN_READWRITE;
2629 }else{
2630 *pOutFlags = SQLITE_OPEN_READONLY;
2634 memset(pFile, 0, sizeof(*pFile));
2635 pFile->pMethod = &winIoMethod;
2636 pFile->h = h;
2637 pFile->lastErrno = NO_ERROR;
2638 pFile->pVfs = pVfs;
2639 pFile->pShm = 0;
2640 pFile->zPath = zName;
2641 pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
2643 #if SQLITE_OS_WINCE
2644 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
2645 && !winceCreateLock(zName, pFile)
2647 CloseHandle(h);
2648 free(zConverted);
2649 return SQLITE_CANTOPEN_BKPT;
2651 if( isTemp ){
2652 pFile->zDeleteOnClose = zConverted;
2653 }else
2654 #endif
2656 free(zConverted);
2659 OpenCounter(+1);
2660 return rc;
2664 ** Delete the named file.
2666 ** Note that windows does not allow a file to be deleted if some other
2667 ** process has it open. Sometimes a virus scanner or indexing program
2668 ** will open a journal file shortly after it is created in order to do
2669 ** whatever it does. While this other process is holding the
2670 ** file open, we will be unable to delete it. To work around this
2671 ** problem, we delay 100 milliseconds and try to delete again. Up
2672 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
2673 ** up and returning an error.
2675 static int winDelete(
2676 sqlite3_vfs *pVfs, /* Not used on win32 */
2677 const char *zFilename, /* Name of file to delete */
2678 int syncDir /* Not used on win32 */
2680 int cnt = 0;
2681 int rc;
2682 void *zConverted;
2683 UNUSED_PARAMETER(pVfs);
2684 UNUSED_PARAMETER(syncDir);
2686 SimulateIOError(return SQLITE_IOERR_DELETE);
2687 zConverted = convertUtf8Filename(zFilename);
2688 if( zConverted==0 ){
2689 return SQLITE_NOMEM;
2691 if( isNT() ){
2692 rc = 1;
2693 while( GetFileAttributesW(zConverted)!=INVALID_FILE_ATTRIBUTES &&
2694 (rc = DeleteFileW(zConverted))==0 && retryIoerr(&cnt) ){}
2695 rc = rc ? SQLITE_OK : SQLITE_ERROR;
2696 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2697 ** Since the ASCII version of these Windows API do not exist for WINCE,
2698 ** it's important to not reference them for WINCE builds.
2700 #if SQLITE_OS_WINCE==0
2701 }else{
2702 rc = 1;
2703 while( GetFileAttributesA(zConverted)!=INVALID_FILE_ATTRIBUTES &&
2704 (rc = DeleteFileA(zConverted))==0 && retryIoerr(&cnt) ){}
2705 rc = rc ? SQLITE_OK : SQLITE_ERROR;
2706 #endif
2708 if( rc ){
2709 rc = winLogError(SQLITE_IOERR_DELETE, "winDelete", zFilename);
2710 }else{
2711 logIoerr(cnt);
2713 free(zConverted);
2714 OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
2715 return rc;
2719 ** Check the existance and status of a file.
2721 static int winAccess(
2722 sqlite3_vfs *pVfs, /* Not used on win32 */
2723 const char *zFilename, /* Name of file to check */
2724 int flags, /* Type of test to make on this file */
2725 int *pResOut /* OUT: Result */
2727 DWORD attr;
2728 int rc = 0;
2729 void *zConverted;
2730 UNUSED_PARAMETER(pVfs);
2732 SimulateIOError( return SQLITE_IOERR_ACCESS; );
2733 zConverted = convertUtf8Filename(zFilename);
2734 if( zConverted==0 ){
2735 return SQLITE_NOMEM;
2737 if( isNT() ){
2738 int cnt = 0;
2739 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
2740 memset(&sAttrData, 0, sizeof(sAttrData));
2741 while( !(rc = GetFileAttributesExW((WCHAR*)zConverted,
2742 GetFileExInfoStandard,
2743 &sAttrData)) && retryIoerr(&cnt) ){}
2744 if( rc ){
2745 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
2746 ** as if it does not exist.
2748 if( flags==SQLITE_ACCESS_EXISTS
2749 && sAttrData.nFileSizeHigh==0
2750 && sAttrData.nFileSizeLow==0 ){
2751 attr = INVALID_FILE_ATTRIBUTES;
2752 }else{
2753 attr = sAttrData.dwFileAttributes;
2755 }else{
2756 logIoerr(cnt);
2757 if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
2758 winLogError(SQLITE_IOERR_ACCESS, "winAccess", zFilename);
2759 free(zConverted);
2760 return SQLITE_IOERR_ACCESS;
2761 }else{
2762 attr = INVALID_FILE_ATTRIBUTES;
2765 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2766 ** Since the ASCII version of these Windows API do not exist for WINCE,
2767 ** it's important to not reference them for WINCE builds.
2769 #if SQLITE_OS_WINCE==0
2770 }else{
2771 attr = GetFileAttributesA((char*)zConverted);
2772 #endif
2774 free(zConverted);
2775 switch( flags ){
2776 case SQLITE_ACCESS_READ:
2777 case SQLITE_ACCESS_EXISTS:
2778 rc = attr!=INVALID_FILE_ATTRIBUTES;
2779 break;
2780 case SQLITE_ACCESS_READWRITE:
2781 rc = attr!=INVALID_FILE_ATTRIBUTES &&
2782 (attr & FILE_ATTRIBUTE_READONLY)==0;
2783 break;
2784 default:
2785 assert(!"Invalid flags argument");
2787 *pResOut = rc;
2788 return SQLITE_OK;
2793 ** Turn a relative pathname into a full pathname. Write the full
2794 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
2795 ** bytes in size.
2797 static int winFullPathname(
2798 sqlite3_vfs *pVfs, /* Pointer to vfs object */
2799 const char *zRelative, /* Possibly relative input path */
2800 int nFull, /* Size of output buffer in bytes */
2801 char *zFull /* Output buffer */
2804 #if defined(__CYGWIN__)
2805 SimulateIOError( return SQLITE_ERROR );
2806 UNUSED_PARAMETER(nFull);
2807 cygwin_conv_to_full_win32_path(zRelative, zFull);
2808 return SQLITE_OK;
2809 #endif
2811 #if SQLITE_OS_WINCE
2812 SimulateIOError( return SQLITE_ERROR );
2813 UNUSED_PARAMETER(nFull);
2814 /* WinCE has no concept of a relative pathname, or so I am told. */
2815 sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
2816 return SQLITE_OK;
2817 #endif
2819 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
2820 int nByte;
2821 void *zConverted;
2822 char *zOut;
2824 /* If this path name begins with "/X:", where "X" is any alphabetic
2825 ** character, discard the initial "/" from the pathname.
2827 if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
2828 zRelative++;
2831 /* It's odd to simulate an io-error here, but really this is just
2832 ** using the io-error infrastructure to test that SQLite handles this
2833 ** function failing. This function could fail if, for example, the
2834 ** current working directory has been unlinked.
2836 SimulateIOError( return SQLITE_ERROR );
2837 UNUSED_PARAMETER(nFull);
2838 zConverted = convertUtf8Filename(zRelative);
2839 if( isNT() ){
2840 WCHAR *zTemp;
2841 nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
2842 zTemp = malloc( nByte*sizeof(zTemp[0]) );
2843 if( zTemp==0 ){
2844 free(zConverted);
2845 return SQLITE_NOMEM;
2847 GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
2848 free(zConverted);
2849 zOut = unicodeToUtf8(zTemp);
2850 free(zTemp);
2851 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2852 ** Since the ASCII version of these Windows API do not exist for WINCE,
2853 ** it's important to not reference them for WINCE builds.
2855 #if SQLITE_OS_WINCE==0
2856 }else{
2857 char *zTemp;
2858 nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
2859 zTemp = malloc( nByte*sizeof(zTemp[0]) );
2860 if( zTemp==0 ){
2861 free(zConverted);
2862 return SQLITE_NOMEM;
2864 GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
2865 free(zConverted);
2866 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
2867 free(zTemp);
2868 #endif
2870 if( zOut ){
2871 sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
2872 free(zOut);
2873 return SQLITE_OK;
2874 }else{
2875 return SQLITE_NOMEM;
2877 #endif
2881 ** Get the sector size of the device used to store
2882 ** file.
2884 static int getSectorSize(
2885 sqlite3_vfs *pVfs,
2886 const char *zRelative /* UTF-8 file name */
2888 DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
2889 /* GetDiskFreeSpace is not supported under WINCE */
2890 #if SQLITE_OS_WINCE
2891 UNUSED_PARAMETER(pVfs);
2892 UNUSED_PARAMETER(zRelative);
2893 #else
2894 char zFullpath[MAX_PATH+1];
2895 int rc;
2896 DWORD dwRet = 0;
2897 DWORD dwDummy;
2900 ** We need to get the full path name of the file
2901 ** to get the drive letter to look up the sector
2902 ** size.
2904 SimulateIOErrorBenign(1);
2905 rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
2906 SimulateIOErrorBenign(0);
2907 if( rc == SQLITE_OK )
2909 void *zConverted = convertUtf8Filename(zFullpath);
2910 if( zConverted ){
2911 if( isNT() ){
2912 /* trim path to just drive reference */
2913 WCHAR *p = zConverted;
2914 for(;*p;p++){
2915 if( *p == '\\' ){
2916 *p = '\0';
2917 break;
2920 dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
2921 &dwDummy,
2922 &bytesPerSector,
2923 &dwDummy,
2924 &dwDummy);
2925 }else{
2926 /* trim path to just drive reference */
2927 char *p = (char *)zConverted;
2928 for(;*p;p++){
2929 if( *p == '\\' ){
2930 *p = '\0';
2931 break;
2934 dwRet = GetDiskFreeSpaceA((char*)zConverted,
2935 &dwDummy,
2936 &bytesPerSector,
2937 &dwDummy,
2938 &dwDummy);
2940 free(zConverted);
2942 if( !dwRet ){
2943 bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
2946 #endif
2947 return (int) bytesPerSector;
2950 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2952 ** Interfaces for opening a shared library, finding entry points
2953 ** within the shared library, and closing the shared library.
2956 ** Interfaces for opening a shared library, finding entry points
2957 ** within the shared library, and closing the shared library.
2959 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
2960 HANDLE h;
2961 void *zConverted = convertUtf8Filename(zFilename);
2962 UNUSED_PARAMETER(pVfs);
2963 if( zConverted==0 ){
2964 return 0;
2966 if( isNT() ){
2967 h = LoadLibraryW((WCHAR*)zConverted);
2968 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2969 ** Since the ASCII version of these Windows API do not exist for WINCE,
2970 ** it's important to not reference them for WINCE builds.
2972 #if SQLITE_OS_WINCE==0
2973 }else{
2974 h = LoadLibraryA((char*)zConverted);
2975 #endif
2977 free(zConverted);
2978 return (void*)h;
2980 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
2981 UNUSED_PARAMETER(pVfs);
2982 getLastErrorMsg(nBuf, zBufOut);
2984 static void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
2985 UNUSED_PARAMETER(pVfs);
2986 #if SQLITE_OS_WINCE
2987 /* The GetProcAddressA() routine is only available on wince. */
2988 return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
2989 #else
2990 /* All other windows platforms expect GetProcAddress() to take
2991 ** an Ansi string regardless of the _UNICODE setting */
2992 return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
2993 #endif
2995 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
2996 UNUSED_PARAMETER(pVfs);
2997 FreeLibrary((HANDLE)pHandle);
2999 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
3000 #define winDlOpen 0
3001 #define winDlError 0
3002 #define winDlSym 0
3003 #define winDlClose 0
3004 #endif
3008 ** Write up to nBuf bytes of randomness into zBuf.
3010 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
3011 int n = 0;
3012 UNUSED_PARAMETER(pVfs);
3013 #if defined(SQLITE_TEST)
3014 n = nBuf;
3015 memset(zBuf, 0, nBuf);
3016 #else
3017 if( sizeof(SYSTEMTIME)<=nBuf-n ){
3018 SYSTEMTIME x;
3019 GetSystemTime(&x);
3020 memcpy(&zBuf[n], &x, sizeof(x));
3021 n += sizeof(x);
3023 if( sizeof(DWORD)<=nBuf-n ){
3024 DWORD pid = GetCurrentProcessId();
3025 memcpy(&zBuf[n], &pid, sizeof(pid));
3026 n += sizeof(pid);
3028 if( sizeof(DWORD)<=nBuf-n ){
3029 DWORD cnt = GetTickCount();
3030 memcpy(&zBuf[n], &cnt, sizeof(cnt));
3031 n += sizeof(cnt);
3033 if( sizeof(LARGE_INTEGER)<=nBuf-n ){
3034 LARGE_INTEGER i;
3035 QueryPerformanceCounter(&i);
3036 memcpy(&zBuf[n], &i, sizeof(i));
3037 n += sizeof(i);
3039 #endif
3040 return n;
3045 ** Sleep for a little while. Return the amount of time slept.
3047 static int winSleep(sqlite3_vfs *pVfs, int microsec){
3048 Sleep((microsec+999)/1000);
3049 UNUSED_PARAMETER(pVfs);
3050 return ((microsec+999)/1000)*1000;
3054 ** The following variable, if set to a non-zero value, is interpreted as
3055 ** the number of seconds since 1970 and is used to set the result of
3056 ** sqlite3OsCurrentTime() during testing.
3058 #ifdef SQLITE_TEST
3059 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
3060 #endif
3063 ** Find the current time (in Universal Coordinated Time). Write into *piNow
3064 ** the current time and date as a Julian Day number times 86_400_000. In
3065 ** other words, write into *piNow the number of milliseconds since the Julian
3066 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
3067 ** proleptic Gregorian calendar.
3069 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
3070 ** cannot be found.
3072 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
3073 /* FILETIME structure is a 64-bit value representing the number of
3074 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
3076 FILETIME ft;
3077 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
3078 #ifdef SQLITE_TEST
3079 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
3080 #endif
3081 /* 2^32 - to avoid use of LL and warnings in gcc */
3082 static const sqlite3_int64 max32BitValue =
3083 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
3085 #if SQLITE_OS_WINCE
3086 SYSTEMTIME time;
3087 GetSystemTime(&time);
3088 /* if SystemTimeToFileTime() fails, it returns zero. */
3089 if (!SystemTimeToFileTime(&time,&ft)){
3090 return SQLITE_ERROR;
3092 #else
3093 GetSystemTimeAsFileTime( &ft );
3094 #endif
3096 *piNow = winFiletimeEpoch +
3097 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
3098 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
3100 #ifdef SQLITE_TEST
3101 if( sqlite3_current_time ){
3102 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
3104 #endif
3105 UNUSED_PARAMETER(pVfs);
3106 return SQLITE_OK;
3110 ** Find the current time (in Universal Coordinated Time). Write the
3111 ** current time and date as a Julian Day number into *prNow and
3112 ** return 0. Return 1 if the time and date cannot be found.
3114 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
3115 int rc;
3116 sqlite3_int64 i;
3117 rc = winCurrentTimeInt64(pVfs, &i);
3118 if( !rc ){
3119 *prNow = i/86400000.0;
3121 return rc;
3125 ** The idea is that this function works like a combination of
3126 ** GetLastError() and FormatMessage() on windows (or errno and
3127 ** strerror_r() on unix). After an error is returned by an OS
3128 ** function, SQLite calls this function with zBuf pointing to
3129 ** a buffer of nBuf bytes. The OS layer should populate the
3130 ** buffer with a nul-terminated UTF-8 encoded error message
3131 ** describing the last IO error to have occurred within the calling
3132 ** thread.
3134 ** If the error message is too large for the supplied buffer,
3135 ** it should be truncated. The return value of xGetLastError
3136 ** is zero if the error message fits in the buffer, or non-zero
3137 ** otherwise (if the message was truncated). If non-zero is returned,
3138 ** then it is not necessary to include the nul-terminator character
3139 ** in the output buffer.
3141 ** Not supplying an error message will have no adverse effect
3142 ** on SQLite. It is fine to have an implementation that never
3143 ** returns an error message:
3145 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
3146 ** assert(zBuf[0]=='\0');
3147 ** return 0;
3148 ** }
3150 ** However if an error message is supplied, it will be incorporated
3151 ** by sqlite into the error message available to the user using
3152 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
3154 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
3155 UNUSED_PARAMETER(pVfs);
3156 return getLastErrorMsg(nBuf, zBuf);
3162 ** Initialize and deinitialize the operating system interface.
3164 int sqlite3_os_init(void){
3165 static sqlite3_vfs winVfs = {
3166 3, /* iVersion */
3167 sizeof(winFile), /* szOsFile */
3168 MAX_PATH, /* mxPathname */
3169 0, /* pNext */
3170 "win32", /* zName */
3171 0, /* pAppData */
3172 winOpen, /* xOpen */
3173 winDelete, /* xDelete */
3174 winAccess, /* xAccess */
3175 winFullPathname, /* xFullPathname */
3176 winDlOpen, /* xDlOpen */
3177 winDlError, /* xDlError */
3178 winDlSym, /* xDlSym */
3179 winDlClose, /* xDlClose */
3180 winRandomness, /* xRandomness */
3181 winSleep, /* xSleep */
3182 winCurrentTime, /* xCurrentTime */
3183 winGetLastError, /* xGetLastError */
3184 winCurrentTimeInt64, /* xCurrentTimeInt64 */
3185 0, /* xSetSystemCall */
3186 0, /* xGetSystemCall */
3187 0, /* xNextSystemCall */
3190 #ifndef SQLITE_OMIT_WAL
3191 /* get memory map allocation granularity */
3192 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
3193 GetSystemInfo(&winSysInfo);
3194 assert(winSysInfo.dwAllocationGranularity > 0);
3195 #endif
3197 sqlite3_vfs_register(&winVfs, 1);
3198 return SQLITE_OK;
3200 int sqlite3_os_end(void){
3201 return SQLITE_OK;
3204 #endif /* SQLITE_OS_WIN */