4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 ******************************************************************************
13 ** This file contains code that is specific to windows.
15 #include "sqliteInt.h"
16 #if SQLITE_OS_WIN /* This file is used for windows only */
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.
48 # include <sys/cygwin.h>
52 ** Macros used to determine whether or not to use threads.
54 #if defined(THREADSAFE) && THREADSAFE
55 # define SQLITE_W32_THREADS 1
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)
71 ** Determine if we are dealing with WindowsCE - which has a much
75 # define AreFileApisANSI() 1
76 # define FormatMessageW(a,b,c,d,e,f,g) 0
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.
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 */
97 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
100 typedef struct winFile 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 */
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 */
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)
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)
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)
151 ** The winMemData structure stores information required by the Win32-specific
152 ** sqlite3_mem_methods implementation.
154 typedef struct winMemData winMemData
;
157 u32 magic
; /* Magic number to detect structure corruption. */
159 HANDLE hHeap
; /* The handle to our heap. */
160 BOOL bOwned
; /* Do we own the heap (i.e. destroy it on shutdown)? */
164 #define WINMEM_MAGIC 0x42b2830b
167 static struct winMemData win_mem_data
= {
175 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
177 #define winMemAssertMagic()
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(
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
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.
214 int sqlite3_os_type
= 0;
216 static int sqlite3_os_type
= 0;
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.
233 static int isNT(void){
234 if( sqlite3_os_type
==0 ){
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
){
253 hHeap
= winMemGetHeap();
255 assert( hHeap
!=INVALID_HANDLE_VALUE
);
256 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
257 assert ( HeapValidate(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, NULL
) );
260 p
= HeapAlloc(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, (SIZE_T
)nBytes
);
262 sqlite3_log(SQLITE_NOMEM
, "failed to HeapAlloc %u bytes (%d), heap=%p",
263 nBytes
, GetLastError(), (void*)hHeap
);
271 static void winMemFree(void *pPrior
){
275 hHeap
= winMemGetHeap();
277 assert( hHeap
!=INVALID_HANDLE_VALUE
);
278 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
279 assert ( HeapValidate(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, pPrior
) );
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
){
296 hHeap
= winMemGetHeap();
298 assert( hHeap
!=INVALID_HANDLE_VALUE
);
299 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
300 assert ( HeapValidate(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, pPrior
) );
304 p
= HeapAlloc(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, (SIZE_T
)nBytes
);
306 p
= HeapReAlloc(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, pPrior
, (SIZE_T
)nBytes
);
309 sqlite3_log(SQLITE_NOMEM
, "failed to %s %u bytes (%d), heap=%p",
310 pPrior
? "HeapReAlloc" : "HeapAlloc", nBytes
, GetLastError(),
317 ** Return the size of an outstanding allocation, in bytes.
319 static int winMemSize(void *p
){
324 hHeap
= winMemGetHeap();
326 assert( hHeap
!=INVALID_HANDLE_VALUE
);
327 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
328 assert ( HeapValidate(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, NULL
) );
331 n
= HeapSize(hHeap
, SQLITE_WIN32_HEAP_FLAGS
, p
);
333 sqlite3_log(SQLITE_NOMEM
, "failed to HeapSize block %p (%d), heap=%p",
334 p
, GetLastError(), (void*)hHeap
);
341 ** Round up a request size to the next valid allocation size.
343 static int winMemRoundup(int 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
);
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
) );
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
) );
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
= {
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
){
433 WCHAR
*zWideFilename
;
435 nChar
= MultiByteToWideChar(CP_UTF8
, 0, zFilename
, -1, NULL
, 0);
436 zWideFilename
= malloc( nChar
*sizeof(zWideFilename
[0]) );
437 if( zWideFilename
==0 ){
440 nChar
= MultiByteToWideChar(CP_UTF8
, 0, zFilename
, -1, zWideFilename
, nChar
);
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
){
456 nByte
= WideCharToMultiByte(CP_UTF8
, 0, zWideFilename
, -1, 0, 0, 0, 0);
457 zFilename
= malloc( nByte
);
461 nByte
= WideCharToMultiByte(CP_UTF8
, 0, zWideFilename
, -1, zFilename
, nByte
,
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
477 static WCHAR
*mbcsToUnicode(const char *zFilename
){
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 ){
487 nByte
= MultiByteToWideChar(codepage
, 0, zFilename
, -1, zMbcsFilename
, nByte
);
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
502 static char *unicodeToMbcs(const WCHAR
*zWideFilename
){
505 int codepage
= AreFileApisANSI() ? CP_ACP
: CP_OEMCP
;
507 nByte
= WideCharToMultiByte(codepage
, 0, zWideFilename
, -1, 0, 0, 0, 0);
508 zFilename
= malloc( nByte
);
512 nByte
= WideCharToMultiByte(codepage
, 0, zWideFilename
, -1, zFilename
, nByte
,
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
){
529 zTmpWide
= mbcsToUnicode(zFilename
);
533 zFilenameUtf8
= unicodeToUtf8(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
){
546 zTmpWide
= utf8ToUnicode(zFilename
);
550 zFilenameMbcs
= unicodeToMbcs(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();
571 WCHAR
*zTempWide
= NULL
;
572 dwLen
= FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
,
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
592 dwLen
= FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
,
600 /* allocate a buffer and convert to UTF8 */
601 zOut
= sqlite3_win32_mbcs_to_utf8(zTemp
);
602 /* free the system buffer allocated by FormatMessage */
608 sqlite3_snprintf(nBuf
, zBuf
, "OsError 0x%x (%u)", error
, error
);
610 /* copy a maximum of nBuf chars to output buffer */
611 sqlite3_snprintf(nBuf
, zBuf
, "%s", zOut
);
612 /* free the UTF8 buffer */
620 ** This function - winLogErrorAtLine() - is only ever called via the macro
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
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 */
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
++){}
651 "os_win.c:%d: (%d) %s(%s) - %s",
652 iLine
, iErrno
, zFunc
, zPath
, zMsg
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
667 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
668 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
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
){
680 if( *pnRetry
>=win32IoerrRetry
){
684 if( e
==ERROR_ACCESS_DENIED
||
685 e
==ERROR_LOCK_VIOLATION
||
686 e
==ERROR_SHARING_VIOLATION
){
687 Sleep(win32IoerrRetryDelay
*(1+*pnRetry
));
695 ** Log a I/O error retry episode.
697 static void logIoerr(int nRetry
){
699 sqlite3_log(SQLITE_IOERR
,
700 "delayed %dms for lock/sharing conflict",
701 win32IoerrRetryDelay
*nRetry
*(nRetry
+1)/2
707 /*************************************************************************
708 ** This section contains code for WinCE only.
711 ** WindowsCE does not have a localtime() function. So create a
715 struct tm
*__cdecl
localtime(const time_t *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
;
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
){
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
764 static BOOL
winceCreateLock(const char *zFilename
, winFile
*pFile
){
766 WCHAR
*zName
= utf8ToUnicode(zFilename
);
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
);
776 if (*zTok
== '\\') *zTok
= '_';
779 /* Create/open the named mutex */
780 pFile
->hMutex
= CreateMutexW(NULL
, FALSE
, zName
);
782 pFile
->lastErrno
= GetLastError();
783 winLogError(SQLITE_ERROR
, "winceCreateLock1", zFilename
);
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.
796 pFile
->hShared
= CreateFileMappingW(INVALID_HANDLE_VALUE
, NULL
,
797 PAGE_READWRITE
, 0, sizeof(winceLock
),
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
){
808 /* If we succeeded in making the shared memory handle, map it. */
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 */
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
;
829 /* Initialize the shared memory if we're supposed to */
831 ZeroMemory(pFile
->shared
, sizeof(winceLock
));
834 winceMutexRelease(pFile
->hMutex
);
839 ** Destroy the part of winFile that deals with wince locks
841 static void winceDestroyLock(winFile
*pFile
){
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(
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
;
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
++;
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
;
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
;
932 winceMutexRelease(pFile
->hMutex
);
937 ** An implementation of the UnlockFile API of windows for wince
939 static BOOL
winceUnlockFile(
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
;
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
--;
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
;
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
;
994 winceMutexRelease(pFile
->hMutex
);
999 ** An implementation of the LockFileEx() API of windows for wince
1001 static BOOL
winceLockFileEx(
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
&&
1016 nNumberOfBytesToLockLow
== (DWORD
)SHARED_SIZE
){
1017 return winceLockFile(phFile
, SHARED_FIRST
, 0, 1, 0);
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)
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
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
);
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
){
1081 winFile
*pFile
= (winFile
*)id
;
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) );
1091 #define WINCE_DELETION_ATTEMPTS 3
1092 winceDestroyLock(pFile
);
1093 if( pFile
->zDeleteOnClose
){
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
);
1105 OSTRACE(("CLOSE %d %s\n", pFile
->h
, rc
? "ok" : "failed"));
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
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 */
1127 SimulateIOError(return SQLITE_IOERR_READ
);
1128 OSTRACE(("READ %d lock=%d\n", pFile
->h
, pFile
->locktype
));
1130 if( seekWinFile(pFile
, offset
) ){
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
);
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
;
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 */
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
);
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 */
1176 if( !WriteFile(pFile
->h
, aRem
, nRem
, &nWrite
, 0) ){
1177 if( retryIoerr(&nRetry
) ) continue;
1180 if( nWrite
<=0 ) break;
1185 pFile
->lastErrno
= GetLastError();
1191 if( ( pFile
->lastErrno
==ERROR_HANDLE_DISK_FULL
)
1192 || ( pFile
->lastErrno
==ERROR_DISK_FULL
)){
1195 return winLogError(SQLITE_IOERR_WRITE
, "winWrite", pFile
->zPath
);
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 */
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
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"));
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;
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.
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
;
1262 UNUSED_PARAMETER(id
);
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
);
1279 UNUSED_PARAMETER(flags
);
1281 if( (flags
&0x0F)==SQLITE_SYNC_FULL
){
1282 sqlite3_fullsync_count
++;
1284 sqlite3_sync_count
++;
1287 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
1290 #ifdef SQLITE_NO_SYNC
1293 rc
= FlushFileBuffers(pFile
->h
);
1294 SimulateIOError( rc
=FALSE
);
1298 pFile
->lastErrno
= GetLastError();
1299 return winLogError(SQLITE_IOERR_FSYNC
, "winSync", pFile
->zPath
);
1305 ** Determine the current size of a file in bytes
1307 static int winFileSize(sqlite3_file
*id
, sqlite3_int64
*pSize
){
1310 winFile
*pFile
= (winFile
*)id
;
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
;
1327 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
1329 #ifndef LOCKFILE_FAIL_IMMEDIATELY
1330 # define LOCKFILE_FAIL_IMMEDIATELY 1
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
){
1342 ovlp
.Offset
= SHARED_FIRST
;
1343 ovlp
.OffsetHigh
= 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
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);
1358 pFile
->lastErrno
= GetLastError();
1359 /* No need to log a failure to lock */
1367 static int unlockReadLock(winFile
*pFile
){
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
1375 res
= UnlockFile(pFile
->h
, SHARED_FIRST
+ pFile
->sharedLockByte
, 0, 1, 0);
1378 if( res
==0 && GetLastError()!=ERROR_NOT_LOCKED
){
1379 pFile
->lastErrno
= GetLastError();
1380 winLogError(SQLITE_IOERR_UNLOCK
, "unlockReadLock", pFile
->zPath
);
1386 ** Lock the file with the lock specified by parameter locktype - one
1387 ** of the following:
1390 ** (2) RESERVED_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
;
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
){
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
))
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
));
1454 gotPendingLock
= 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
);
1466 newLocktype
= SHARED_LOCK
;
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);
1478 newLocktype
= RESERVED_LOCK
;
1480 error
= GetLastError();
1484 /* Acquire a PENDING lock
1486 if( locktype
==EXCLUSIVE_LOCK
&& res
){
1487 newLocktype
= PENDING_LOCK
;
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);
1499 newLocktype
= EXCLUSIVE_LOCK
;
1501 error
= GetLastError();
1502 OSTRACE(("error-code = %d\n", error
));
1507 /* If we are holding a PENDING lock that ought to be released, then
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.
1520 OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile
->h
,
1521 locktype
, newLocktype
));
1522 pFile
->lastErrno
= error
;
1525 pFile
->locktype
= (u8
)newLocktype
;
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
){
1536 winFile
*pFile
= (winFile
*)id
;
1538 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK
; );
1541 if( pFile
->locktype
>=RESERVED_LOCK
){
1543 OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile
->h
, rc
));
1545 rc
= LockFile(pFile
->h
, RESERVED_BYTE
, 0, 1, 0);
1547 UnlockFile(pFile
->h
, RESERVED_BYTE
, 0, 1, 0);
1550 OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile
->h
, rc
));
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
){
1569 winFile
*pFile
= (winFile
*)id
;
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
;
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
;
1603 case SQLITE_FCNTL_LOCKSTATE
: {
1604 *(int*)pArg
= pFile
->locktype
;
1607 case SQLITE_LAST_ERRNO
: {
1608 *(int*)pArg
= (int)pFile
->lastErrno
;
1611 case SQLITE_FCNTL_CHUNK_SIZE
: {
1612 pFile
->szChunk
= *(int *)pArg
;
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
;
1622 SimulateIOErrorBenign(1);
1623 rc
= winTruncate(id
, newSz
);
1624 SimulateIOErrorBenign(0);
1631 case SQLITE_FCNTL_PERSIST_WAL
: {
1632 int bPersist
= *(int*)pArg
;
1634 *(int*)pArg
= pFile
->bPersistWal
;
1636 pFile
->bPersistWal
= bPersist
!=0;
1640 case SQLITE_FCNTL_SYNC_OMITTED
: {
1643 case SQLITE_FCNTL_WIN32_AV_RETRY
: {
1644 int *a
= (int*)pArg
;
1646 win32IoerrRetry
= a
[0];
1648 a
[0] = win32IoerrRetry
;
1651 win32IoerrRetryDelay
= a
[1];
1653 a
[1] = win32IoerrRetryDelay
;
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
1671 static int winSectorSize(sqlite3_file
*id
){
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()
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
));
1714 static int winShmMutexHeld(void) {
1715 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER
));
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:
1732 ** The following fields are read-only after the object is created:
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.
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 */
1750 HANDLE hMap
; /* File handle from CreateFileMapping */
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 */
1759 u8 nextShmId
; /* Next available winShm.id value */
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:
1780 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
1781 ** while accessing any read/write fields.
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 */
1790 u8 id
; /* Id of this connection with its winShmNode */
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 */
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
));
1826 /* Release/Acquire the system-level lock */
1827 if( lockType
==_SHM_UNLCK
){
1828 rc
= UnlockFileEx(pFile
->hFile
.h
, 0, nByte
, 0, &ovlp
);
1830 rc
= LockFileEx(pFile
->hFile
.h
, dwFlags
, 0, nByte
, 0, &ovlp
);
1836 pFile
->lastErrno
= GetLastError();
1840 OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
1842 rc
==SQLITE_OK
? "ok" : "failed",
1843 lockType
==_SHM_UNLCK
? "UnlockFileEx" : "LockFileEx",
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
){
1863 assert( winShmMutexHeld() );
1864 pp
= &winShmNodeList
;
1865 while( (p
= *pp
)!=0 ){
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);
1885 SimulateIOErrorBenign(1);
1886 winDelete(pVfs
, p
->zFilename
, 0);
1887 SimulateIOErrorBenign(0);
1890 sqlite3_free(p
->aRegion
);
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 );
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.
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;
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 ){
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
;
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
;
1985 p
->id
= pShmNode
->nextShmId
++;
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
1998 sqlite3_mutex_enter(pShmNode
->mutex
);
1999 p
->pNext
= pShmNode
->pFirst
;
2000 pShmNode
->pFirst
= p
;
2001 sqlite3_mutex_leave(pShmNode
->mutex
);
2004 /* Jump here on any error */
2006 winShmSystemLock(pShmNode
, _SHM_UNLCK
, WIN_SHM_DMS
, 1);
2007 winShmPurge(pDbFd
->pVfs
, 0); /* This call frees pShmNode if required */
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
;
2029 if( p
==0 ) return SQLITE_OK
;
2030 pShmNode
= p
->pShmNode
;
2032 /* Remove connection p from the set of connections associated
2034 sqlite3_mutex_enter(pShmNode
->mutex
);
2035 for(pp
=&pShmNode
->pFirst
; (*pp
)!=p
; pp
= &(*pp
)->pNext
){}
2038 /* Free the connection p */
2041 sqlite3_mutex_leave(pShmNode
->mutex
);
2043 /* If pShmNode->nRef has reached 0, then close the underlying
2044 ** shared-memory file, too */
2046 assert( pShmNode
->nRef
>0 );
2048 if( pShmNode
->nRef
==0 ){
2049 winShmPurge(pDbFd
->pVfs
, deleteFlag
);
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
);
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
);
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
2112 for(pX
=pShmNode
->pFirst
; pX
; pX
=pX
->pNext
){
2113 if( (pX
->exclMask
& mask
)!=0 ){
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
);
2129 /* Get the local shared locks */
2130 if( rc
==SQLITE_OK
){
2131 p
->sharedMask
|= mask
;
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 ){
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"));
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 */
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
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
;
2209 rc
= winOpenSharedMemory(pDbFd
);
2210 if( rc
!=SQLITE_OK
) return rc
;
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
);
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
);
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])
2255 rc
= SQLITE_IOERR_NOMEM
;
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"));
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"));
2281 pShmNode
->lastErrno
= GetLastError();
2282 rc
= winLogError(SQLITE_IOERR_SHMMAP
, "winShmMap3", pDbFd
->zPath
);
2283 if( hMap
) CloseHandle(hMap
);
2287 pShmNode
->aRegion
[pShmNode
->nRegion
].pMap
= pMap
;
2288 pShmNode
->aRegion
[pShmNode
->nRegion
].hMap
= hMap
;
2289 pShmNode
->nRegion
++;
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
];
2302 sqlite3_mutex_leave(pShmNode
->mutex
);
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
= {
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
2356 static void *convertUtf8Filename(const char *zFilename
){
2357 void *zConverted
= 0;
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
2364 zConverted
= sqlite3_win32_utf8_to_mbcs(zFilename
);
2367 /* caller will handle out of memory */
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"
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
);
2393 WCHAR zWidePath
[MAX_PATH
];
2394 GetTempPathW(MAX_PATH
-30, zWidePath
);
2395 zMulti
= unicodeToUtf8(zWidePath
);
2397 sqlite3_snprintf(MAX_PATH
-30, zTempPath
, "%s", zMulti
);
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
2409 char zMbcsPath
[MAX_PATH
];
2410 GetTempPathA(MAX_PATH
-30, zMbcsPath
);
2411 zUtf8
= sqlite3_win32_mbcs_to_utf8(zMbcsPath
);
2413 sqlite3_snprintf(MAX_PATH
-30, zTempPath
, "%s", zUtf8
);
2416 return SQLITE_NOMEM
;
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
--){}
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) ];
2440 OSTRACE(("TEMP FILENAME: %s\n", zBuf
));
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 */
2455 DWORD dwDesiredAccess
;
2457 DWORD dwCreationDisposition
;
2458 DWORD dwFlagsAndAttributes
= 0;
2462 winFile
*pFile
= (winFile
*)id
;
2463 void *zConverted
; /* Filename in OS encoding */
2464 const char *zUtf8Name
= zName
; /* Filename in UTF-8 encoding */
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 */
2477 int isExclusive
= (flags
& SQLITE_OPEN_EXCLUSIVE
);
2478 int isDelete
= (flags
& SQLITE_OPEN_DELETEONCLOSE
);
2479 int isCreate
= (flags
& SQLITE_OPEN_CREATE
);
2481 int isReadonly
= (flags
& SQLITE_OPEN_READONLY
);
2483 int isReadWrite
= (flags
& SQLITE_OPEN_READWRITE
);
2486 int isOpenJournal
= (isCreate
&& (
2487 eType
==SQLITE_OPEN_MASTER_JOURNAL
2488 || eType
==SQLITE_OPEN_MAIN_JOURNAL
2489 || eType
==SQLITE_OPEN_WAL
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
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
2528 assert(isDelete
&& !isOpenJournal
);
2529 rc
= getTempname(MAX_PATH
+1, zTmpname
);
2530 if( rc
!=SQLITE_OK
){
2533 zUtf8Name
= zTmpname
;
2536 /* Convert the filename to the system encoding. */
2537 zConverted
= convertUtf8Filename(zUtf8Name
);
2538 if( zConverted
==0 ){
2539 return SQLITE_NOMEM
;
2543 dwDesiredAccess
= GENERIC_READ
| GENERIC_WRITE
;
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.
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
;
2560 /* Opens a file, only if it exists. */
2561 dwCreationDisposition
= OPEN_EXISTING
;
2564 dwShareMode
= FILE_SHARE_READ
| FILE_SHARE_WRITE
;
2568 dwFlagsAndAttributes
= FILE_ATTRIBUTE_HIDDEN
;
2571 dwFlagsAndAttributes
= FILE_ATTRIBUTE_TEMPORARY
2572 | FILE_ATTRIBUTE_HIDDEN
2573 | FILE_FLAG_DELETE_ON_CLOSE
;
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. */
2581 dwFlagsAndAttributes
|= FILE_FLAG_RANDOM_ACCESS
;
2585 while( (h
= CreateFileW((WCHAR
*)zConverted
,
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
2598 while( (h
= CreateFileA((char*)zConverted
,
2601 dwCreationDisposition
,
2602 dwFlagsAndAttributes
,
2603 NULL
))==INVALID_HANDLE_VALUE
&&
2604 retryIoerr(&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
);
2618 if( isReadWrite
&& !isExclusive
){
2619 return winOpen(pVfs
, zName
, id
,
2620 ((flags
|SQLITE_OPEN_READONLY
)&~(SQLITE_OPEN_CREATE
|SQLITE_OPEN_READWRITE
)), pOutFlags
);
2622 return SQLITE_CANTOPEN_BKPT
;
2628 *pOutFlags
= SQLITE_OPEN_READWRITE
;
2630 *pOutFlags
= SQLITE_OPEN_READONLY
;
2634 memset(pFile
, 0, sizeof(*pFile
));
2635 pFile
->pMethod
= &winIoMethod
;
2637 pFile
->lastErrno
= NO_ERROR
;
2640 pFile
->zPath
= zName
;
2641 pFile
->sectorSize
= getSectorSize(pVfs
, zUtf8Name
);
2644 if( isReadWrite
&& eType
==SQLITE_OPEN_MAIN_DB
2645 && !winceCreateLock(zName
, pFile
)
2649 return SQLITE_CANTOPEN_BKPT
;
2652 pFile
->zDeleteOnClose
= zConverted
;
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 */
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
;
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
2703 while( GetFileAttributesA(zConverted
)!=INVALID_FILE_ATTRIBUTES
&&
2704 (rc
= DeleteFileA(zConverted
))==0 && retryIoerr(&cnt
) ){}
2705 rc
= rc
? SQLITE_OK
: SQLITE_ERROR
;
2709 rc
= winLogError(SQLITE_IOERR_DELETE
, "winDelete", zFilename
);
2714 OSTRACE(("DELETE \"%s\" %s\n", zFilename
, (rc
? "failed" : "ok" )));
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 */
2730 UNUSED_PARAMETER(pVfs
);
2732 SimulateIOError( return SQLITE_IOERR_ACCESS
; );
2733 zConverted
= convertUtf8Filename(zFilename
);
2734 if( zConverted
==0 ){
2735 return SQLITE_NOMEM
;
2739 WIN32_FILE_ATTRIBUTE_DATA sAttrData
;
2740 memset(&sAttrData
, 0, sizeof(sAttrData
));
2741 while( !(rc
= GetFileAttributesExW((WCHAR
*)zConverted
,
2742 GetFileExInfoStandard
,
2743 &sAttrData
)) && retryIoerr(&cnt
) ){}
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
;
2753 attr
= sAttrData
.dwFileAttributes
;
2757 if( GetLastError()!=ERROR_FILE_NOT_FOUND
){
2758 winLogError(SQLITE_IOERR_ACCESS
, "winAccess", zFilename
);
2760 return SQLITE_IOERR_ACCESS
;
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
2771 attr
= GetFileAttributesA((char*)zConverted
);
2776 case SQLITE_ACCESS_READ
:
2777 case SQLITE_ACCESS_EXISTS
:
2778 rc
= attr
!=INVALID_FILE_ATTRIBUTES
;
2780 case SQLITE_ACCESS_READWRITE
:
2781 rc
= attr
!=INVALID_FILE_ATTRIBUTES
&&
2782 (attr
& FILE_ATTRIBUTE_READONLY
)==0;
2785 assert(!"Invalid flags argument");
2793 ** Turn a relative pathname into a full pathname. Write the full
2794 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
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
);
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
);
2819 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
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]==':' ){
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
);
2841 nByte
= GetFullPathNameW((WCHAR
*)zConverted
, 0, 0, 0) + 3;
2842 zTemp
= malloc( nByte
*sizeof(zTemp
[0]) );
2845 return SQLITE_NOMEM
;
2847 GetFullPathNameW((WCHAR
*)zConverted
, nByte
, zTemp
, 0);
2849 zOut
= unicodeToUtf8(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
2858 nByte
= GetFullPathNameA((char*)zConverted
, 0, 0, 0) + 3;
2859 zTemp
= malloc( nByte
*sizeof(zTemp
[0]) );
2862 return SQLITE_NOMEM
;
2864 GetFullPathNameA((char*)zConverted
, nByte
, zTemp
, 0);
2866 zOut
= sqlite3_win32_mbcs_to_utf8(zTemp
);
2871 sqlite3_snprintf(pVfs
->mxPathname
, zFull
, "%s", zOut
);
2875 return SQLITE_NOMEM
;
2881 ** Get the sector size of the device used to store
2884 static int getSectorSize(
2886 const char *zRelative
/* UTF-8 file name */
2888 DWORD bytesPerSector
= SQLITE_DEFAULT_SECTOR_SIZE
;
2889 /* GetDiskFreeSpace is not supported under WINCE */
2891 UNUSED_PARAMETER(pVfs
);
2892 UNUSED_PARAMETER(zRelative
);
2894 char zFullpath
[MAX_PATH
+1];
2900 ** We need to get the full path name of the file
2901 ** to get the drive letter to look up the sector
2904 SimulateIOErrorBenign(1);
2905 rc
= winFullPathname(pVfs
, zRelative
, MAX_PATH
, zFullpath
);
2906 SimulateIOErrorBenign(0);
2907 if( rc
== SQLITE_OK
)
2909 void *zConverted
= convertUtf8Filename(zFullpath
);
2912 /* trim path to just drive reference */
2913 WCHAR
*p
= zConverted
;
2920 dwRet
= GetDiskFreeSpaceW((WCHAR
*)zConverted
,
2926 /* trim path to just drive reference */
2927 char *p
= (char *)zConverted
;
2934 dwRet
= GetDiskFreeSpaceA((char*)zConverted
,
2943 bytesPerSector
= SQLITE_DEFAULT_SECTOR_SIZE
;
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
){
2961 void *zConverted
= convertUtf8Filename(zFilename
);
2962 UNUSED_PARAMETER(pVfs
);
2963 if( zConverted
==0 ){
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
2974 h
= LoadLibraryA((char*)zConverted
);
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
);
2987 /* The GetProcAddressA() routine is only available on wince. */
2988 return (void(*)(void))GetProcAddressA((HANDLE
)pHandle
, zSymbol
);
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
);
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: */
3001 #define winDlError 0
3003 #define winDlClose 0
3008 ** Write up to nBuf bytes of randomness into zBuf.
3010 static int winRandomness(sqlite3_vfs
*pVfs
, int nBuf
, char *zBuf
){
3012 UNUSED_PARAMETER(pVfs
);
3013 #if defined(SQLITE_TEST)
3015 memset(zBuf
, 0, nBuf
);
3017 if( sizeof(SYSTEMTIME
)<=nBuf
-n
){
3020 memcpy(&zBuf
[n
], &x
, sizeof(x
));
3023 if( sizeof(DWORD
)<=nBuf
-n
){
3024 DWORD pid
= GetCurrentProcessId();
3025 memcpy(&zBuf
[n
], &pid
, sizeof(pid
));
3028 if( sizeof(DWORD
)<=nBuf
-n
){
3029 DWORD cnt
= GetTickCount();
3030 memcpy(&zBuf
[n
], &cnt
, sizeof(cnt
));
3033 if( sizeof(LARGE_INTEGER
)<=nBuf
-n
){
3035 QueryPerformanceCounter(&i
);
3036 memcpy(&zBuf
[n
], &i
, sizeof(i
));
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.
3059 int sqlite3_current_time
= 0; /* Fake system time in seconds since 1970. */
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
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).
3077 static const sqlite3_int64 winFiletimeEpoch
= 23058135*(sqlite3_int64
)8640000;
3079 static const sqlite3_int64 unixEpoch
= 24405875*(sqlite3_int64
)8640000;
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;
3087 GetSystemTime(&time
);
3088 /* if SystemTimeToFileTime() fails, it returns zero. */
3089 if (!SystemTimeToFileTime(&time
,&ft
)){
3090 return SQLITE_ERROR
;
3093 GetSystemTimeAsFileTime( &ft
);
3096 *piNow
= winFiletimeEpoch
+
3097 ((((sqlite3_int64
)ft
.dwHighDateTime
)*max32BitValue
) +
3098 (sqlite3_int64
)ft
.dwLowDateTime
)/(sqlite3_int64
)10000;
3101 if( sqlite3_current_time
){
3102 *piNow
= 1000*(sqlite3_int64
)sqlite3_current_time
+ unixEpoch
;
3105 UNUSED_PARAMETER(pVfs
);
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
){
3117 rc
= winCurrentTimeInt64(pVfs
, &i
);
3119 *prNow
= i
/86400000.0;
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
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');
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
= {
3167 sizeof(winFile
), /* szOsFile */
3168 MAX_PATH
, /* mxPathname */
3170 "win32", /* zName */
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);
3197 sqlite3_vfs_register(&winVfs
, 1);
3200 int sqlite3_os_end(void){
3204 #endif /* SQLITE_OS_WIN */