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 unsigned char locktype; /* Type of lock currently held on this file */
106 short sharedLockByte; /* Randomly chosen byte used as a shared lock */
107 DWORD lastErrno; /* The Windows errno from the last I/O error */
108 DWORD sectorSize; /* Sector size of the device file is on */
109 winShm *pShm; /* Instance of shared memory on this file */
110 const char *zPath; /* Full pathname of this file */
111 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
113 WCHAR *zDeleteOnClose; /* Name of file to delete when closing */
114 HANDLE hMutex; /* Mutex used to control access to shared lock */
115 HANDLE hShared; /* Shared memory segment used for locking */
116 winceLock local; /* Locks obtained by this instance of winFile */
117 winceLock *shared; /* Global shared lock memory for the file */
122 ** Forward prototypes.
124 static int getSectorSize(
126 const char *zRelative /* UTF-8 file name */
130 ** The following variable is (normally) set once and never changes
131 ** thereafter. It records whether the operating system is Win95
134 ** 0: Operating system unknown.
135 ** 1: Operating system is Win95.
136 ** 2: Operating system is WinNT.
138 ** In order to facilitate testing on a WinNT system, the test fixture
139 ** can manually set this value to 1 to emulate Win98 behavior.
142 int sqlite3_os_type = 0;
144 static int sqlite3_os_type = 0;
148 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
149 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
151 ** Here is an interesting observation: Win95, Win98, and WinME lack
152 ** the LockFileEx() API. But we can still statically link against that
153 ** API as long as we don't call it when running Win95/98/ME. A call to
154 ** this routine is used to determine if the host is Win95/98/ME or
155 ** WinNT/2K/XP so that we will know whether or not we can safely call
156 ** the LockFileEx() API.
161 static int isNT(void){
162 if( sqlite3_os_type==0 ){
164 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
165 GetVersionEx(&sInfo);
166 sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
168 return sqlite3_os_type==2;
170 #endif /* SQLITE_OS_WINCE */
173 ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
175 ** Space to hold the returned string is obtained from malloc.
177 static WCHAR *utf8ToUnicode(const char *zFilename){
179 WCHAR *zWideFilename;
181 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
182 zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
183 if( zWideFilename==0 ){
186 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
191 return zWideFilename;
195 ** Convert microsoft unicode to UTF-8. Space to hold the returned string is
196 ** obtained from malloc().
198 static char *unicodeToUtf8(const WCHAR *zWideFilename){
202 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
203 zFilename = malloc( nByte );
207 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
217 ** Convert an ansi string to microsoft unicode, based on the
218 ** current codepage settings for file apis.
220 ** Space to hold the returned string is obtained
223 static WCHAR *mbcsToUnicode(const char *zFilename){
225 WCHAR *zMbcsFilename;
226 int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
228 nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
229 zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
230 if( zMbcsFilename==0 ){
233 nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
238 return zMbcsFilename;
242 ** Convert microsoft unicode to multibyte character string, based on the
243 ** user's Ansi codepage.
245 ** Space to hold the returned string is obtained from
248 static char *unicodeToMbcs(const WCHAR *zWideFilename){
251 int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
253 nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
254 zFilename = malloc( nByte );
258 nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
268 ** Convert multibyte character string to UTF-8. Space to hold the
269 ** returned string is obtained from malloc().
271 char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
275 zTmpWide = mbcsToUnicode(zFilename);
279 zFilenameUtf8 = unicodeToUtf8(zTmpWide);
281 return zFilenameUtf8;
285 ** Convert UTF-8 to multibyte character string. Space to hold the
286 ** returned string is obtained from malloc().
288 static char *utf8ToMbcs(const char *zFilename){
292 zTmpWide = utf8ToUnicode(zFilename);
296 zFilenameMbcs = unicodeToMbcs(zTmpWide);
298 return zFilenameMbcs;
302 /*************************************************************************
303 ** This section contains code for WinCE only.
306 ** WindowsCE does not have a localtime() function. So create a
310 struct tm *__cdecl localtime(const time_t *t)
317 t64 = (t64 + 11644473600)*10000000;
318 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
319 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
320 FileTimeToLocalFileTime(&uTm,&lTm);
321 FileTimeToSystemTime(&lTm,&pTm);
322 y.tm_year = pTm.wYear - 1900;
323 y.tm_mon = pTm.wMonth - 1;
324 y.tm_wday = pTm.wDayOfWeek;
325 y.tm_mday = pTm.wDay;
326 y.tm_hour = pTm.wHour;
327 y.tm_min = pTm.wMinute;
328 y.tm_sec = pTm.wSecond;
332 /* This will never be called, but defined to make the code compile */
333 #define GetTempPathA(a,b)
335 #define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e)
336 #define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e)
337 #define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f)
339 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
342 ** Acquire a lock on the handle h
344 static void winceMutexAcquire(HANDLE h){
347 dwErr = WaitForSingleObject(h, INFINITE);
348 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
351 ** Release a lock acquired by winceMutexAcquire()
353 #define winceMutexRelease(h) ReleaseMutex(h)
356 ** Create the mutex and shared memory used for locking in the file
359 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
361 WCHAR *zName = utf8ToUnicode(zFilename);
364 /* Initialize the local lockdata */
365 ZeroMemory(&pFile->local, sizeof(pFile->local));
367 /* Replace the backslashes from the filename and lowercase it
368 ** to derive a mutex name. */
369 zTok = CharLowerW(zName);
371 if (*zTok == '\\') *zTok = '_';
374 /* Create/open the named mutex */
375 pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
377 pFile->lastErrno = GetLastError();
382 /* Acquire the mutex before continuing */
383 winceMutexAcquire(pFile->hMutex);
385 /* Since the names of named mutexes, semaphores, file mappings etc are
386 ** case-sensitive, take advantage of that by uppercasing the mutex name
387 ** and using that as the shared filemapping name.
390 pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
391 PAGE_READWRITE, 0, sizeof(winceLock),
394 /* Set a flag that indicates we're the first to create the memory so it
395 ** must be zero-initialized */
396 if (GetLastError() == ERROR_ALREADY_EXISTS){
402 /* If we succeeded in making the shared memory handle, map it. */
404 pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
405 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
406 /* If mapping failed, close the shared memory handle and erase it */
408 pFile->lastErrno = GetLastError();
409 CloseHandle(pFile->hShared);
410 pFile->hShared = NULL;
414 /* If shared memory could not be created, then close the mutex and fail */
415 if (pFile->hShared == NULL){
416 winceMutexRelease(pFile->hMutex);
417 CloseHandle(pFile->hMutex);
418 pFile->hMutex = NULL;
422 /* Initialize the shared memory if we're supposed to */
424 ZeroMemory(pFile->shared, sizeof(winceLock));
427 winceMutexRelease(pFile->hMutex);
432 ** Destroy the part of winFile that deals with wince locks
434 static void winceDestroyLock(winFile *pFile){
436 /* Acquire the mutex */
437 winceMutexAcquire(pFile->hMutex);
439 /* The following blocks should probably assert in debug mode, but they
440 are to cleanup in case any locks remained open */
441 if (pFile->local.nReaders){
442 pFile->shared->nReaders --;
444 if (pFile->local.bReserved){
445 pFile->shared->bReserved = FALSE;
447 if (pFile->local.bPending){
448 pFile->shared->bPending = FALSE;
450 if (pFile->local.bExclusive){
451 pFile->shared->bExclusive = FALSE;
454 /* De-reference and close our copy of the shared memory handle */
455 UnmapViewOfFile(pFile->shared);
456 CloseHandle(pFile->hShared);
458 /* Done with the mutex */
459 winceMutexRelease(pFile->hMutex);
460 CloseHandle(pFile->hMutex);
461 pFile->hMutex = NULL;
466 ** An implementation of the LockFile() API of windows for wince
468 static BOOL winceLockFile(
470 DWORD dwFileOffsetLow,
471 DWORD dwFileOffsetHigh,
472 DWORD nNumberOfBytesToLockLow,
473 DWORD nNumberOfBytesToLockHigh
475 winFile *pFile = HANDLE_TO_WINFILE(phFile);
476 BOOL bReturn = FALSE;
478 UNUSED_PARAMETER(dwFileOffsetHigh);
479 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
481 if (!pFile->hMutex) return TRUE;
482 winceMutexAcquire(pFile->hMutex);
484 /* Wanting an exclusive lock? */
485 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
486 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
487 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
488 pFile->shared->bExclusive = TRUE;
489 pFile->local.bExclusive = TRUE;
494 /* Want a read-only lock? */
495 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
496 nNumberOfBytesToLockLow == 1){
497 if (pFile->shared->bExclusive == 0){
498 pFile->local.nReaders ++;
499 if (pFile->local.nReaders == 1){
500 pFile->shared->nReaders ++;
506 /* Want a pending lock? */
507 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
508 /* If no pending lock has been acquired, then acquire it */
509 if (pFile->shared->bPending == 0) {
510 pFile->shared->bPending = TRUE;
511 pFile->local.bPending = TRUE;
516 /* Want a reserved lock? */
517 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
518 if (pFile->shared->bReserved == 0) {
519 pFile->shared->bReserved = TRUE;
520 pFile->local.bReserved = TRUE;
525 winceMutexRelease(pFile->hMutex);
530 ** An implementation of the UnlockFile API of windows for wince
532 static BOOL winceUnlockFile(
534 DWORD dwFileOffsetLow,
535 DWORD dwFileOffsetHigh,
536 DWORD nNumberOfBytesToUnlockLow,
537 DWORD nNumberOfBytesToUnlockHigh
539 winFile *pFile = HANDLE_TO_WINFILE(phFile);
540 BOOL bReturn = FALSE;
542 UNUSED_PARAMETER(dwFileOffsetHigh);
543 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
545 if (!pFile->hMutex) return TRUE;
546 winceMutexAcquire(pFile->hMutex);
548 /* Releasing a reader lock or an exclusive lock */
549 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
550 /* Did we have an exclusive lock? */
551 if (pFile->local.bExclusive){
552 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
553 pFile->local.bExclusive = FALSE;
554 pFile->shared->bExclusive = FALSE;
558 /* Did we just have a reader lock? */
559 else if (pFile->local.nReaders){
560 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
561 pFile->local.nReaders --;
562 if (pFile->local.nReaders == 0)
564 pFile->shared->nReaders --;
570 /* Releasing a pending lock */
571 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
572 if (pFile->local.bPending){
573 pFile->local.bPending = FALSE;
574 pFile->shared->bPending = FALSE;
578 /* Releasing a reserved lock */
579 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
580 if (pFile->local.bReserved) {
581 pFile->local.bReserved = FALSE;
582 pFile->shared->bReserved = FALSE;
587 winceMutexRelease(pFile->hMutex);
592 ** An implementation of the LockFileEx() API of windows for wince
594 static BOOL winceLockFileEx(
598 DWORD nNumberOfBytesToLockLow,
599 DWORD nNumberOfBytesToLockHigh,
600 LPOVERLAPPED lpOverlapped
602 UNUSED_PARAMETER(dwReserved);
603 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
605 /* If the caller wants a shared read lock, forward this call
606 ** to winceLockFile */
607 if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
609 nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
610 return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
615 ** End of the special code for wince
616 *****************************************************************************/
617 #endif /* SQLITE_OS_WINCE */
619 /*****************************************************************************
620 ** The next group of routines implement the I/O methods specified
621 ** by the sqlite3_io_methods object.
622 ******************************************************************************/
625 ** Some microsoft compilers lack this definition.
627 #ifndef INVALID_SET_FILE_POINTER
628 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
632 ** Move the current position of the file handle passed as the first
633 ** argument to offset iOffset within the file. If successful, return 0.
634 ** Otherwise, set pFile->lastErrno and return non-zero.
636 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
637 LONG upperBits; /* Most sig. 32 bits of new offset */
638 LONG lowerBits; /* Least sig. 32 bits of new offset */
639 DWORD dwRet; /* Value returned by SetFilePointer() */
641 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
642 lowerBits = (LONG)(iOffset & 0xffffffff);
644 /* API oddity: If successful, SetFilePointer() returns a dword
645 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
646 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
647 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
648 ** whether an error has actually occured, it is also necessary to call
651 dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
652 if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
653 pFile->lastErrno = GetLastError();
663 ** It is reported that an attempt to close a handle might sometimes
664 ** fail. This is a very unreasonable result, but windows is notorious
665 ** for being unreasonable so I do not doubt that it might happen. If
666 ** the close fails, we pause for 100 milliseconds and try again. As
667 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
668 ** giving up and returning an error.
670 #define MX_CLOSE_ATTEMPT 3
671 static int winClose(sqlite3_file *id){
673 winFile *pFile = (winFile*)id;
676 assert( pFile->pShm==0 );
677 OSTRACE(("CLOSE %d\n", pFile->h));
679 rc = CloseHandle(pFile->h);
680 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
681 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
683 #define WINCE_DELETION_ATTEMPTS 3
684 winceDestroyLock(pFile);
685 if( pFile->zDeleteOnClose ){
688 DeleteFileW(pFile->zDeleteOnClose)==0
689 && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
690 && cnt++ < WINCE_DELETION_ATTEMPTS
692 Sleep(100); /* Wait a little before trying again */
694 free(pFile->zDeleteOnClose);
697 OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
699 return rc ? SQLITE_OK : SQLITE_IOERR;
703 ** Read data from a file into a buffer. Return SQLITE_OK if all
704 ** bytes were read successfully and SQLITE_IOERR if anything goes
708 sqlite3_file *id, /* File to read from */
709 void *pBuf, /* Write content into this buffer */
710 int amt, /* Number of bytes to read */
711 sqlite3_int64 offset /* Begin reading at this offset */
713 winFile *pFile = (winFile*)id; /* file handle */
714 DWORD nRead; /* Number of bytes actually read from file */
717 SimulateIOError(return SQLITE_IOERR_READ);
718 OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
720 if( seekWinFile(pFile, offset) ){
723 if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
724 pFile->lastErrno = GetLastError();
725 return SQLITE_IOERR_READ;
727 if( nRead<(DWORD)amt ){
728 /* Unread parts of the buffer must be zero-filled */
729 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
730 return SQLITE_IOERR_SHORT_READ;
737 ** Write data from a buffer into a file. Return SQLITE_OK on success
738 ** or some other error code on failure.
741 sqlite3_file *id, /* File to write into */
742 const void *pBuf, /* The bytes to be written */
743 int amt, /* Number of bytes to write */
744 sqlite3_int64 offset /* Offset into the file to begin writing at */
746 int rc; /* True if error has occured, else false */
747 winFile *pFile = (winFile*)id; /* File handle */
751 SimulateIOError(return SQLITE_IOERR_WRITE);
752 SimulateDiskfullError(return SQLITE_FULL);
754 OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
756 rc = seekWinFile(pFile, offset);
758 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
759 int nRem = amt; /* Number of bytes yet to be written */
760 DWORD nWrite; /* Bytes written by each WriteFile() call */
762 while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
767 pFile->lastErrno = GetLastError();
773 if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
776 return SQLITE_IOERR_WRITE;
782 ** Truncate an open file to a specified size
784 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
785 winFile *pFile = (winFile*)id; /* File handle object */
786 int rc = SQLITE_OK; /* Return code for this function */
790 OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
791 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
793 /* If the user has configured a chunk-size for this file, truncate the
794 ** file so that it consists of an integer number of chunks (i.e. the
795 ** actual file size after the operation may be larger than the requested
798 if( pFile->szChunk ){
799 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
802 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
803 if( seekWinFile(pFile, nByte) ){
804 rc = SQLITE_IOERR_TRUNCATE;
805 }else if( 0==SetEndOfFile(pFile->h) ){
806 pFile->lastErrno = GetLastError();
807 rc = SQLITE_IOERR_TRUNCATE;
810 OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
816 ** Count the number of fullsyncs and normal syncs. This is used to test
817 ** that syncs and fullsyncs are occuring at the right times.
819 int sqlite3_sync_count = 0;
820 int sqlite3_fullsync_count = 0;
824 ** Make sure all writes to a particular file are committed to disk.
826 static int winSync(sqlite3_file *id, int flags){
827 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
828 winFile *pFile = (winFile*)id;
830 UNUSED_PARAMETER(id);
834 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
835 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
836 || (flags&0x0F)==SQLITE_SYNC_FULL
839 OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
842 UNUSED_PARAMETER(flags);
844 if( flags & SQLITE_SYNC_FULL ){
845 sqlite3_fullsync_count++;
847 sqlite3_sync_count++;
850 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
851 ** line is to test that doing so does not cause any problems.
853 SimulateDiskfullError( return SQLITE_FULL );
854 SimulateIOError( return SQLITE_IOERR; );
856 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
859 #ifdef SQLITE_NO_SYNC
862 if( FlushFileBuffers(pFile->h) ){
865 pFile->lastErrno = GetLastError();
872 ** Determine the current size of a file in bytes
874 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
877 winFile *pFile = (winFile*)id;
881 SimulateIOError(return SQLITE_IOERR_FSTAT);
882 lowerBits = GetFileSize(pFile->h, &upperBits);
883 if( (lowerBits == INVALID_FILE_SIZE)
884 && ((error = GetLastError()) != NO_ERROR) )
886 pFile->lastErrno = error;
887 return SQLITE_IOERR_FSTAT;
889 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
894 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
896 #ifndef LOCKFILE_FAIL_IMMEDIATELY
897 # define LOCKFILE_FAIL_IMMEDIATELY 1
901 ** Acquire a reader lock.
902 ** Different API routines are called depending on whether or not this
903 ** is Win95 or WinNT.
905 static int getReadLock(winFile *pFile){
909 ovlp.Offset = SHARED_FIRST;
912 res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
913 0, SHARED_SIZE, 0, &ovlp);
914 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
916 #if SQLITE_OS_WINCE==0
919 sqlite3_randomness(sizeof(lk), &lk);
920 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
921 res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
925 pFile->lastErrno = GetLastError();
933 static int unlockReadLock(winFile *pFile){
936 res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
937 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
939 #if SQLITE_OS_WINCE==0
941 res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
945 pFile->lastErrno = GetLastError();
951 ** Lock the file with the lock specified by parameter locktype - one
957 ** (4) EXCLUSIVE_LOCK
959 ** Sometimes when requesting one lock state, additional lock states
960 ** are inserted in between. The locking might fail on one of the later
961 ** transitions leaving the lock state different from what it started but
962 ** still short of its goal. The following chart shows the allowed
963 ** transitions and the inserted intermediate states:
965 ** UNLOCKED -> SHARED
966 ** SHARED -> RESERVED
967 ** SHARED -> (PENDING) -> EXCLUSIVE
968 ** RESERVED -> (PENDING) -> EXCLUSIVE
969 ** PENDING -> EXCLUSIVE
971 ** This routine will only increase a lock. The winUnlock() routine
972 ** erases all locks at once and returns us immediately to locking level 0.
973 ** It is not possible to lower the locking level one step at a time. You
974 ** must go straight to locking level 0.
976 static int winLock(sqlite3_file *id, int locktype){
977 int rc = SQLITE_OK; /* Return code from subroutines */
978 int res = 1; /* Result of a windows lock call */
979 int newLocktype; /* Set pFile->locktype to this value before exiting */
980 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
981 winFile *pFile = (winFile*)id;
982 DWORD error = NO_ERROR;
985 OSTRACE(("LOCK %d %d was %d(%d)\n",
986 pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
988 /* If there is already a lock of this type or more restrictive on the
989 ** OsFile, do nothing. Don't use the end_lock: exit path, as
990 ** sqlite3OsEnterMutex() hasn't been called yet.
992 if( pFile->locktype>=locktype ){
996 /* Make sure the locking sequence is correct
998 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
999 assert( locktype!=PENDING_LOCK );
1000 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
1002 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
1003 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
1004 ** the PENDING_LOCK byte is temporary.
1006 newLocktype = pFile->locktype;
1007 if( (pFile->locktype==NO_LOCK)
1008 || ( (locktype==EXCLUSIVE_LOCK)
1009 && (pFile->locktype==RESERVED_LOCK))
1012 while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
1013 /* Try 3 times to get the pending lock. The pending lock might be
1014 ** held by another reader process who will release it momentarily.
1016 OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
1019 gotPendingLock = res;
1021 error = GetLastError();
1025 /* Acquire a shared lock
1027 if( locktype==SHARED_LOCK && res ){
1028 assert( pFile->locktype==NO_LOCK );
1029 res = getReadLock(pFile);
1031 newLocktype = SHARED_LOCK;
1033 error = GetLastError();
1037 /* Acquire a RESERVED lock
1039 if( locktype==RESERVED_LOCK && res ){
1040 assert( pFile->locktype==SHARED_LOCK );
1041 res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1043 newLocktype = RESERVED_LOCK;
1045 error = GetLastError();
1049 /* Acquire a PENDING lock
1051 if( locktype==EXCLUSIVE_LOCK && res ){
1052 newLocktype = PENDING_LOCK;
1056 /* Acquire an EXCLUSIVE lock
1058 if( locktype==EXCLUSIVE_LOCK && res ){
1059 assert( pFile->locktype>=SHARED_LOCK );
1060 res = unlockReadLock(pFile);
1061 OSTRACE(("unreadlock = %d\n", res));
1062 res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
1064 newLocktype = EXCLUSIVE_LOCK;
1066 error = GetLastError();
1067 OSTRACE(("error-code = %d\n", error));
1072 /* If we are holding a PENDING lock that ought to be released, then
1075 if( gotPendingLock && locktype==SHARED_LOCK ){
1076 UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
1079 /* Update the state of the lock has held in the file descriptor then
1080 ** return the appropriate result code.
1085 OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
1086 locktype, newLocktype));
1087 pFile->lastErrno = error;
1090 pFile->locktype = (u8)newLocktype;
1095 ** This routine checks if there is a RESERVED lock held on the specified
1096 ** file by this or any other process. If such a lock is held, return
1097 ** non-zero, otherwise zero.
1099 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
1101 winFile *pFile = (winFile*)id;
1103 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1106 if( pFile->locktype>=RESERVED_LOCK ){
1108 OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
1110 rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1112 UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1115 OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
1122 ** Lower the locking level on file descriptor id to locktype. locktype
1123 ** must be either NO_LOCK or SHARED_LOCK.
1125 ** If the locking level of the file descriptor is already at or below
1126 ** the requested locking level, this routine is a no-op.
1128 ** It is not possible for this routine to fail if the second argument
1129 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
1130 ** might return SQLITE_IOERR;
1132 static int winUnlock(sqlite3_file *id, int locktype){
1134 winFile *pFile = (winFile*)id;
1137 assert( locktype<=SHARED_LOCK );
1138 OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
1139 pFile->locktype, pFile->sharedLockByte));
1140 type = pFile->locktype;
1141 if( type>=EXCLUSIVE_LOCK ){
1142 UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
1143 if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
1144 /* This should never happen. We should always be able to
1145 ** reacquire the read lock */
1146 rc = SQLITE_IOERR_UNLOCK;
1149 if( type>=RESERVED_LOCK ){
1150 UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1152 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
1153 unlockReadLock(pFile);
1155 if( type>=PENDING_LOCK ){
1156 UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
1158 pFile->locktype = (u8)locktype;
1163 ** Control and query of the open file handle.
1165 static int winFileControl(sqlite3_file *id, int op, void *pArg){
1167 case SQLITE_FCNTL_LOCKSTATE: {
1168 *(int*)pArg = ((winFile*)id)->locktype;
1171 case SQLITE_LAST_ERRNO: {
1172 *(int*)pArg = (int)((winFile*)id)->lastErrno;
1175 case SQLITE_FCNTL_CHUNK_SIZE: {
1176 ((winFile*)id)->szChunk = *(int *)pArg;
1179 case SQLITE_FCNTL_SIZE_HINT: {
1180 sqlite3_int64 sz = *(sqlite3_int64*)pArg;
1181 SimulateIOErrorBenign(1);
1182 winTruncate(id, sz);
1183 SimulateIOErrorBenign(0);
1186 case SQLITE_FCNTL_SYNC_OMITTED: {
1190 return SQLITE_NOTFOUND;
1194 ** Return the sector size in bytes of the underlying block device for
1195 ** the specified file. This is almost always 512 bytes, but may be
1196 ** larger for some devices.
1198 ** SQLite code assumes this function cannot fail. It also assumes that
1199 ** if two files are created in the same file-system directory (i.e.
1200 ** a database and its journal file) that the sector size will be the
1203 static int winSectorSize(sqlite3_file *id){
1205 return (int)(((winFile*)id)->sectorSize);
1209 ** Return a vector of device characteristics.
1211 static int winDeviceCharacteristics(sqlite3_file *id){
1212 UNUSED_PARAMETER(id);
1213 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
1216 #ifndef SQLITE_OMIT_WAL
1219 ** Windows will only let you create file view mappings
1220 ** on allocation size granularity boundaries.
1221 ** During sqlite3_os_init() we do a GetSystemInfo()
1222 ** to get the granularity size.
1224 SYSTEM_INFO winSysInfo;
1227 ** Helper functions to obtain and relinquish the global mutex. The
1228 ** global mutex is used to protect the winLockInfo objects used by
1229 ** this file, all of which may be shared by multiple threads.
1231 ** Function winShmMutexHeld() is used to assert() that the global mutex
1232 ** is held when required. This function is only used as part of assert()
1235 ** winShmEnterMutex()
1236 ** assert( winShmMutexHeld() );
1237 ** winShmLeaveMutex()
1239 static void winShmEnterMutex(void){
1240 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1242 static void winShmLeaveMutex(void){
1243 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1246 static int winShmMutexHeld(void) {
1247 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1252 ** Object used to represent a single file opened and mmapped to provide
1253 ** shared memory. When multiple threads all reference the same
1254 ** log-summary, each thread has its own winFile object, but they all
1255 ** point to a single instance of this object. In other words, each
1256 ** log-summary is opened only once per process.
1258 ** winShmMutexHeld() must be true when creating or destroying
1259 ** this object or while reading or writing the following fields:
1264 ** The following fields are read-only after the object is created:
1269 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
1270 ** winShmMutexHeld() is true when reading or writing any other field
1271 ** in this structure.
1275 sqlite3_mutex *mutex; /* Mutex to access this object */
1276 char *zFilename; /* Name of the file */
1277 winFile hFile; /* File handle from winOpen */
1279 int szRegion; /* Size of shared-memory regions */
1280 int nRegion; /* Size of array apRegion */
1282 HANDLE hMap; /* File handle from CreateFileMapping */
1285 DWORD lastErrno; /* The Windows errno from the last I/O error */
1287 int nRef; /* Number of winShm objects pointing to this */
1288 winShm *pFirst; /* All winShm objects pointing to this */
1289 winShmNode *pNext; /* Next in list of all winShmNode objects */
1291 u8 nextShmId; /* Next available winShm.id value */
1296 ** A global array of all winShmNode objects.
1298 ** The winShmMutexHeld() must be true while reading or writing this list.
1300 static winShmNode *winShmNodeList = 0;
1303 ** Structure used internally by this VFS to record the state of an
1304 ** open shared memory connection.
1306 ** The following fields are initialized when this object is created and
1307 ** are read-only thereafter:
1312 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
1313 ** while accessing any read/write fields.
1316 winShmNode *pShmNode; /* The underlying winShmNode object */
1317 winShm *pNext; /* Next winShm with the same winShmNode */
1318 u8 hasMutex; /* True if holding the winShmNode mutex */
1319 u16 sharedMask; /* Mask of shared locks held */
1320 u16 exclMask; /* Mask of exclusive locks held */
1322 u8 id; /* Id of this connection with its winShmNode */
1327 ** Constants used for locking
1329 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
1330 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
1333 ** Apply advisory locks for all n bytes beginning at ofst.
1335 #define _SHM_UNLCK 1
1336 #define _SHM_RDLCK 2
1337 #define _SHM_WRLCK 3
1338 static int winShmSystemLock(
1339 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
1340 int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
1341 int ofst, /* Offset to first byte to be locked/unlocked */
1342 int nByte /* Number of bytes to lock or unlock */
1346 int rc = 0; /* Result code form Lock/UnlockFileEx() */
1348 /* Access to the winShmNode object is serialized by the caller */
1349 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
1351 /* Initialize the locking parameters */
1352 dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
1353 if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
1355 memset(&ovlp, 0, sizeof(OVERLAPPED));
1358 /* Release/Acquire the system-level lock */
1359 if( lockType==_SHM_UNLCK ){
1360 rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
1362 rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
1368 pFile->lastErrno = GetLastError();
1372 OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
1374 rc==SQLITE_OK ? "ok" : "failed",
1375 lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
1381 /* Forward references to VFS methods */
1382 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
1383 static int winDelete(sqlite3_vfs *,const char*,int);
1386 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
1388 ** This is not a VFS shared-memory method; it is a utility function called
1389 ** by VFS shared-memory methods.
1391 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
1395 assert( winShmMutexHeld() );
1396 pp = &winShmNodeList;
1397 while( (p = *pp)!=0 ){
1400 if( p->mutex ) sqlite3_mutex_free(p->mutex);
1401 for(i=0; i<p->nRegion; i++){
1402 bRc = UnmapViewOfFile(p->aRegion[i].pMap);
1403 OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
1404 (int)GetCurrentProcessId(), i,
1405 bRc ? "ok" : "failed"));
1406 bRc = CloseHandle(p->aRegion[i].hMap);
1407 OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
1408 (int)GetCurrentProcessId(), i,
1409 bRc ? "ok" : "failed"));
1411 if( p->hFile.h != INVALID_HANDLE_VALUE ){
1412 SimulateIOErrorBenign(1);
1413 winClose((sqlite3_file *)&p->hFile);
1414 SimulateIOErrorBenign(0);
1417 SimulateIOErrorBenign(1);
1418 winDelete(pVfs, p->zFilename, 0);
1419 SimulateIOErrorBenign(0);
1422 sqlite3_free(p->aRegion);
1431 ** Open the shared-memory area associated with database file pDbFd.
1433 ** When opening a new shared-memory file, if no other instances of that
1434 ** file are currently open, in this process or in other processes, then
1435 ** the file must be truncated to zero length or have its header cleared.
1437 static int winOpenSharedMemory(winFile *pDbFd){
1438 struct winShm *p; /* The connection to be opened */
1439 struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
1440 int rc; /* Result code */
1441 struct winShmNode *pNew; /* Newly allocated winShmNode */
1442 int nName; /* Size of zName in bytes */
1444 assert( pDbFd->pShm==0 ); /* Not previously opened */
1446 /* Allocate space for the new sqlite3_shm object. Also speculatively
1447 ** allocate space for a new winShmNode and filename.
1449 p = sqlite3_malloc( sizeof(*p) );
1450 if( p==0 ) return SQLITE_NOMEM;
1451 memset(p, 0, sizeof(*p));
1452 nName = sqlite3Strlen30(pDbFd->zPath);
1453 pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
1456 return SQLITE_NOMEM;
1458 memset(pNew, 0, sizeof(*pNew));
1459 pNew->zFilename = (char*)&pNew[1];
1460 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
1462 /* Look to see if there is an existing winShmNode that can be used.
1463 ** If no matching winShmNode currently exists, create a new one.
1466 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
1467 /* TBD need to come up with better match here. Perhaps
1468 ** use FILE_ID_BOTH_DIR_INFO Structure.
1470 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
1477 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
1478 pShmNode->pNext = winShmNodeList;
1479 winShmNodeList = pShmNode;
1481 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1482 if( pShmNode->mutex==0 ){
1487 rc = winOpen(pDbFd->pVfs,
1488 pShmNode->zFilename, /* Name of the file (UTF-8) */
1489 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
1490 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
1492 if( SQLITE_OK!=rc ){
1493 rc = SQLITE_CANTOPEN_BKPT;
1497 /* Check to see if another process is holding the dead-man switch.
1498 ** If not, truncate the file to zero length.
1500 if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
1501 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
1502 if( rc!=SQLITE_OK ){
1503 rc = SQLITE_IOERR_SHMOPEN;
1506 if( rc==SQLITE_OK ){
1507 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
1508 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
1510 if( rc ) goto shm_open_err;
1513 /* Make the new connection a child of the winShmNode */
1514 p->pShmNode = pShmNode;
1516 p->id = pShmNode->nextShmId++;
1522 /* The reference count on pShmNode has already been incremented under
1523 ** the cover of the winShmEnterMutex() mutex and the pointer from the
1524 ** new (struct winShm) object to the pShmNode has been set. All that is
1525 ** left to do is to link the new object into the linked list starting
1526 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
1529 sqlite3_mutex_enter(pShmNode->mutex);
1530 p->pNext = pShmNode->pFirst;
1531 pShmNode->pFirst = p;
1532 sqlite3_mutex_leave(pShmNode->mutex);
1535 /* Jump here on any error */
1537 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
1538 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
1546 ** Close a connection to shared-memory. Delete the underlying
1547 ** storage if deleteFlag is true.
1549 static int winShmUnmap(
1550 sqlite3_file *fd, /* Database holding shared memory */
1551 int deleteFlag /* Delete after closing if true */
1553 winFile *pDbFd; /* Database holding shared-memory */
1554 winShm *p; /* The connection to be closed */
1555 winShmNode *pShmNode; /* The underlying shared-memory file */
1556 winShm **pp; /* For looping over sibling connections */
1558 pDbFd = (winFile*)fd;
1560 if( p==0 ) return SQLITE_OK;
1561 pShmNode = p->pShmNode;
1563 /* Remove connection p from the set of connections associated
1565 sqlite3_mutex_enter(pShmNode->mutex);
1566 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
1569 /* Free the connection p */
1572 sqlite3_mutex_leave(pShmNode->mutex);
1574 /* If pShmNode->nRef has reached 0, then close the underlying
1575 ** shared-memory file, too */
1577 assert( pShmNode->nRef>0 );
1579 if( pShmNode->nRef==0 ){
1580 winShmPurge(pDbFd->pVfs, deleteFlag);
1588 ** Change the lock state for a shared-memory segment.
1590 static int winShmLock(
1591 sqlite3_file *fd, /* Database file holding the shared memory */
1592 int ofst, /* First lock to acquire or release */
1593 int n, /* Number of locks to acquire or release */
1594 int flags /* What to do with the lock */
1596 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
1597 winShm *p = pDbFd->pShm; /* The shared memory being locked */
1598 winShm *pX; /* For looping over all siblings */
1599 winShmNode *pShmNode = p->pShmNode;
1600 int rc = SQLITE_OK; /* Result code */
1601 u16 mask; /* Mask of locks to take or release */
1603 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
1605 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
1606 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
1607 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
1608 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
1609 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
1611 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
1612 assert( n>1 || mask==(1<<ofst) );
1613 sqlite3_mutex_enter(pShmNode->mutex);
1614 if( flags & SQLITE_SHM_UNLOCK ){
1615 u16 allMask = 0; /* Mask of locks held by siblings */
1617 /* See if any siblings hold this same lock */
1618 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
1619 if( pX==p ) continue;
1620 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
1621 allMask |= pX->sharedMask;
1624 /* Unlock the system-level locks */
1625 if( (mask & allMask)==0 ){
1626 rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
1631 /* Undo the local locks */
1632 if( rc==SQLITE_OK ){
1633 p->exclMask &= ~mask;
1634 p->sharedMask &= ~mask;
1636 }else if( flags & SQLITE_SHM_SHARED ){
1637 u16 allShared = 0; /* Union of locks held by connections other than "p" */
1639 /* Find out which shared locks are already held by sibling connections.
1640 ** If any sibling already holds an exclusive lock, go ahead and return
1643 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
1644 if( (pX->exclMask & mask)!=0 ){
1648 allShared |= pX->sharedMask;
1651 /* Get shared locks at the system level, if necessary */
1652 if( rc==SQLITE_OK ){
1653 if( (allShared & mask)==0 ){
1654 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
1660 /* Get the local shared locks */
1661 if( rc==SQLITE_OK ){
1662 p->sharedMask |= mask;
1665 /* Make sure no sibling connections hold locks that will block this
1666 ** lock. If any do, return SQLITE_BUSY right away.
1668 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
1669 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
1675 /* Get the exclusive locks at the system level. Then if successful
1676 ** also mark the local connection as being locked.
1678 if( rc==SQLITE_OK ){
1679 rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
1680 if( rc==SQLITE_OK ){
1681 assert( (p->sharedMask & mask)==0 );
1682 p->exclMask |= mask;
1686 sqlite3_mutex_leave(pShmNode->mutex);
1687 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
1688 p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
1689 rc ? "failed" : "ok"));
1694 ** Implement a memory barrier or memory fence on shared memory.
1696 ** All loads and stores begun before the barrier must complete before
1697 ** any load or store begun after the barrier.
1699 static void winShmBarrier(
1700 sqlite3_file *fd /* Database holding the shared memory */
1702 UNUSED_PARAMETER(fd);
1703 /* MemoryBarrier(); // does not work -- do not know why not */
1709 ** This function is called to obtain a pointer to region iRegion of the
1710 ** shared-memory associated with the database file fd. Shared-memory regions
1711 ** are numbered starting from zero. Each shared-memory region is szRegion
1714 ** If an error occurs, an error code is returned and *pp is set to NULL.
1716 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
1717 ** region has not been allocated (by any client, including one running in a
1718 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
1719 ** isWrite is non-zero and the requested shared-memory region has not yet
1720 ** been allocated, it is allocated by this function.
1722 ** If the shared-memory region has already been allocated or is allocated by
1723 ** this call as described above, then it is mapped into this processes
1724 ** address space (if it is not already), *pp is set to point to the mapped
1725 ** memory and SQLITE_OK returned.
1727 static int winShmMap(
1728 sqlite3_file *fd, /* Handle open on database file */
1729 int iRegion, /* Region to retrieve */
1730 int szRegion, /* Size of regions */
1731 int isWrite, /* True to extend file if necessary */
1732 void volatile **pp /* OUT: Mapped memory */
1734 winFile *pDbFd = (winFile*)fd;
1735 winShm *p = pDbFd->pShm;
1736 winShmNode *pShmNode;
1740 rc = winOpenSharedMemory(pDbFd);
1741 if( rc!=SQLITE_OK ) return rc;
1744 pShmNode = p->pShmNode;
1746 sqlite3_mutex_enter(pShmNode->mutex);
1747 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
1749 if( pShmNode->nRegion<=iRegion ){
1750 struct ShmRegion *apNew; /* New aRegion[] array */
1751 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
1752 sqlite3_int64 sz; /* Current size of wal-index file */
1754 pShmNode->szRegion = szRegion;
1756 /* The requested region is not mapped into this processes address space.
1757 ** Check to see if it has been allocated (i.e. if the wal-index file is
1758 ** large enough to contain the requested region).
1760 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
1761 if( rc!=SQLITE_OK ){
1762 rc = SQLITE_IOERR_SHMSIZE;
1767 /* The requested memory region does not exist. If isWrite is set to
1768 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
1770 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
1771 ** the requested memory region.
1773 if( !isWrite ) goto shmpage_out;
1774 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
1775 if( rc!=SQLITE_OK ){
1776 rc = SQLITE_IOERR_SHMSIZE;
1781 /* Map the requested memory region into this processes address space. */
1782 apNew = (struct ShmRegion *)sqlite3_realloc(
1783 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
1786 rc = SQLITE_IOERR_NOMEM;
1789 pShmNode->aRegion = apNew;
1791 while( pShmNode->nRegion<=iRegion ){
1792 HANDLE hMap; /* file-mapping handle */
1793 void *pMap = 0; /* Mapped memory region */
1795 hMap = CreateFileMapping(pShmNode->hFile.h,
1796 NULL, PAGE_READWRITE, 0, nByte, NULL
1798 OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
1799 (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
1800 hMap ? "ok" : "failed"));
1802 int iOffset = pShmNode->nRegion*szRegion;
1803 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
1804 pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
1805 0, iOffset - iOffsetShift, szRegion + iOffsetShift
1807 OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
1808 (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
1809 pMap ? "ok" : "failed"));
1812 pShmNode->lastErrno = GetLastError();
1814 if( hMap ) CloseHandle(hMap);
1818 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
1819 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
1820 pShmNode->nRegion++;
1825 if( pShmNode->nRegion>iRegion ){
1826 int iOffset = iRegion*szRegion;
1827 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
1828 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
1829 *pp = (void *)&p[iOffsetShift];
1833 sqlite3_mutex_leave(pShmNode->mutex);
1838 # define winShmMap 0
1839 # define winShmLock 0
1840 # define winShmBarrier 0
1841 # define winShmUnmap 0
1842 #endif /* #ifndef SQLITE_OMIT_WAL */
1845 ** Here ends the implementation of all sqlite3_file methods.
1847 ********************** End sqlite3_file Methods *******************************
1848 ******************************************************************************/
1851 ** This vector defines all the methods that can operate on an
1852 ** sqlite3_file for win32.
1854 static const sqlite3_io_methods winIoMethod = {
1856 winClose, /* xClose */
1857 winRead, /* xRead */
1858 winWrite, /* xWrite */
1859 winTruncate, /* xTruncate */
1860 winSync, /* xSync */
1861 winFileSize, /* xFileSize */
1862 winLock, /* xLock */
1863 winUnlock, /* xUnlock */
1864 winCheckReservedLock, /* xCheckReservedLock */
1865 winFileControl, /* xFileControl */
1866 winSectorSize, /* xSectorSize */
1867 winDeviceCharacteristics, /* xDeviceCharacteristics */
1868 winShmMap, /* xShmMap */
1869 winShmLock, /* xShmLock */
1870 winShmBarrier, /* xShmBarrier */
1871 winShmUnmap /* xShmUnmap */
1874 /****************************************************************************
1875 **************************** sqlite3_vfs methods ****************************
1877 ** This division contains the implementation of methods on the
1878 ** sqlite3_vfs object.
1882 ** Convert a UTF-8 filename into whatever form the underlying
1883 ** operating system wants filenames in. Space to hold the result
1884 ** is obtained from malloc and must be freed by the calling
1887 static void *convertUtf8Filename(const char *zFilename){
1888 void *zConverted = 0;
1890 zConverted = utf8ToUnicode(zFilename);
1891 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1893 #if SQLITE_OS_WINCE==0
1895 zConverted = utf8ToMbcs(zFilename);
1898 /* caller will handle out of memory */
1903 ** Create a temporary file name in zBuf. zBuf must be big enough to
1904 ** hold at pVfs->mxPathname characters.
1906 static int getTempname(int nBuf, char *zBuf){
1907 static char zChars[] =
1908 "abcdefghijklmnopqrstuvwxyz"
1909 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1912 char zTempPath[MAX_PATH+1];
1914 /* It's odd to simulate an io-error here, but really this is just
1915 ** using the io-error infrastructure to test that SQLite handles this
1916 ** function failing.
1918 SimulateIOError( return SQLITE_IOERR );
1920 if( sqlite3_temp_directory ){
1921 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
1924 WCHAR zWidePath[MAX_PATH];
1925 GetTempPathW(MAX_PATH-30, zWidePath);
1926 zMulti = unicodeToUtf8(zWidePath);
1928 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
1931 return SQLITE_NOMEM;
1933 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
1934 ** Since the ASCII version of these Windows API do not exist for WINCE,
1935 ** it's important to not reference them for WINCE builds.
1937 #if SQLITE_OS_WINCE==0
1940 char zMbcsPath[MAX_PATH];
1941 GetTempPathA(MAX_PATH-30, zMbcsPath);
1942 zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
1944 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
1947 return SQLITE_NOMEM;
1952 /* Check that the output buffer is large enough for the temporary file
1953 ** name. If it is not, return SQLITE_ERROR.
1955 if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
1956 return SQLITE_ERROR;
1959 for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
1962 sqlite3_snprintf(nBuf-17, zBuf,
1963 "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
1964 j = sqlite3Strlen30(zBuf);
1965 sqlite3_randomness(15, &zBuf[j]);
1966 for(i=0; i<15; i++, j++){
1967 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
1971 OSTRACE(("TEMP FILENAME: %s\n", zBuf));
1976 ** The return value of getLastErrorMsg
1977 ** is zero if the error message fits in the buffer, or non-zero
1978 ** otherwise (if the message was truncated).
1980 static int getLastErrorMsg(int nBuf, char *zBuf){
1981 /* FormatMessage returns 0 on failure. Otherwise it
1982 ** returns the number of TCHARs written to the output
1983 ** buffer, excluding the terminating null char.
1985 DWORD error = GetLastError();
1990 WCHAR *zTempWide = NULL;
1991 dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1995 (LPWSTR) &zTempWide,
1999 /* allocate a buffer and convert to UTF8 */
2000 zOut = unicodeToUtf8(zTempWide);
2001 /* free the system buffer allocated by FormatMessage */
2002 LocalFree(zTempWide);
2004 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2005 ** Since the ASCII version of these Windows API do not exist for WINCE,
2006 ** it's important to not reference them for WINCE builds.
2008 #if SQLITE_OS_WINCE==0
2011 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
2019 /* allocate a buffer and convert to UTF8 */
2020 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
2021 /* free the system buffer allocated by FormatMessage */
2027 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
2029 /* copy a maximum of nBuf chars to output buffer */
2030 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
2031 /* free the UTF8 buffer */
2041 sqlite3_vfs *pVfs, /* Not used */
2042 const char *zName, /* Name of the file (UTF-8) */
2043 sqlite3_file *id, /* Write the SQLite file handle here */
2044 int flags, /* Open mode flags */
2045 int *pOutFlags /* Status return flags */
2048 DWORD dwDesiredAccess;
2050 DWORD dwCreationDisposition;
2051 DWORD dwFlagsAndAttributes = 0;
2055 winFile *pFile = (winFile*)id;
2056 void *zConverted; /* Filename in OS encoding */
2057 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
2059 /* If argument zPath is a NULL pointer, this function is required to open
2060 ** a temporary file. Use this buffer to store the file name in.
2062 char zTmpname[MAX_PATH+1]; /* Buffer used to create temp filename */
2064 int rc = SQLITE_OK; /* Function Return Code */
2065 #if !defined(NDEBUG) || SQLITE_OS_WINCE
2066 int eType = flags&0xFFFFFF00; /* Type of file to open */
2069 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
2070 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
2071 int isCreate = (flags & SQLITE_OPEN_CREATE);
2073 int isReadonly = (flags & SQLITE_OPEN_READONLY);
2075 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
2078 int isOpenJournal = (isCreate && (
2079 eType==SQLITE_OPEN_MASTER_JOURNAL
2080 || eType==SQLITE_OPEN_MAIN_JOURNAL
2081 || eType==SQLITE_OPEN_WAL
2085 /* Check the following statements are true:
2087 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
2088 ** (b) if CREATE is set, then READWRITE must also be set, and
2089 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
2090 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
2092 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
2093 assert(isCreate==0 || isReadWrite);
2094 assert(isExclusive==0 || isCreate);
2095 assert(isDelete==0 || isCreate);
2097 /* The main DB, main journal, WAL file and master journal are never
2098 ** automatically deleted. Nor are they ever temporary files. */
2099 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
2100 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
2101 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
2102 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
2104 /* Assert that the upper layer has set one of the "file-type" flags. */
2105 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
2106 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
2107 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
2108 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
2112 UNUSED_PARAMETER(pVfs);
2114 pFile->h = INVALID_HANDLE_VALUE;
2116 /* If the second argument to this function is NULL, generate a
2117 ** temporary file name to use
2120 assert(isDelete && !isOpenJournal);
2121 rc = getTempname(MAX_PATH+1, zTmpname);
2122 if( rc!=SQLITE_OK ){
2125 zUtf8Name = zTmpname;
2128 /* Convert the filename to the system encoding. */
2129 zConverted = convertUtf8Filename(zUtf8Name);
2130 if( zConverted==0 ){
2131 return SQLITE_NOMEM;
2135 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
2137 dwDesiredAccess = GENERIC_READ;
2140 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
2141 ** created. SQLite doesn't use it to indicate "exclusive access"
2142 ** as it is usually understood.
2145 /* Creates a new file, only if it does not already exist. */
2146 /* If the file exists, it fails. */
2147 dwCreationDisposition = CREATE_NEW;
2148 }else if( isCreate ){
2149 /* Open existing file, or create if it doesn't exist */
2150 dwCreationDisposition = OPEN_ALWAYS;
2152 /* Opens a file, only if it exists. */
2153 dwCreationDisposition = OPEN_EXISTING;
2156 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
2160 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
2163 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
2164 | FILE_ATTRIBUTE_HIDDEN
2165 | FILE_FLAG_DELETE_ON_CLOSE;
2168 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
2170 /* Reports from the internet are that performance is always
2171 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
2173 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
2177 h = CreateFileW((WCHAR*)zConverted,
2181 dwCreationDisposition,
2182 dwFlagsAndAttributes,
2185 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2186 ** Since the ASCII version of these Windows API do not exist for WINCE,
2187 ** it's important to not reference them for WINCE builds.
2189 #if SQLITE_OS_WINCE==0
2191 h = CreateFileA((char*)zConverted,
2195 dwCreationDisposition,
2196 dwFlagsAndAttributes,
2202 OSTRACE(("OPEN %d %s 0x%lx %s\n",
2203 h, zName, dwDesiredAccess,
2204 h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
2206 if( h==INVALID_HANDLE_VALUE ){
2207 pFile->lastErrno = GetLastError();
2210 return winOpen(pVfs, zName, id,
2211 ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
2213 return SQLITE_CANTOPEN_BKPT;
2219 *pOutFlags = SQLITE_OPEN_READWRITE;
2221 *pOutFlags = SQLITE_OPEN_READONLY;
2225 memset(pFile, 0, sizeof(*pFile));
2226 pFile->pMethod = &winIoMethod;
2228 pFile->lastErrno = NO_ERROR;
2231 pFile->zPath = zName;
2232 pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
2235 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
2236 && !winceCreateLock(zName, pFile)
2240 return SQLITE_CANTOPEN_BKPT;
2243 pFile->zDeleteOnClose = zConverted;
2255 ** Delete the named file.
2257 ** Note that windows does not allow a file to be deleted if some other
2258 ** process has it open. Sometimes a virus scanner or indexing program
2259 ** will open a journal file shortly after it is created in order to do
2260 ** whatever it does. While this other process is holding the
2261 ** file open, we will be unable to delete it. To work around this
2262 ** problem, we delay 100 milliseconds and try to delete again. Up
2263 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
2264 ** up and returning an error.
2266 #define MX_DELETION_ATTEMPTS 5
2267 static int winDelete(
2268 sqlite3_vfs *pVfs, /* Not used on win32 */
2269 const char *zFilename, /* Name of file to delete */
2270 int syncDir /* Not used on win32 */
2276 UNUSED_PARAMETER(pVfs);
2277 UNUSED_PARAMETER(syncDir);
2279 SimulateIOError(return SQLITE_IOERR_DELETE);
2280 zConverted = convertUtf8Filename(zFilename);
2281 if( zConverted==0 ){
2282 return SQLITE_NOMEM;
2286 DeleteFileW(zConverted);
2287 }while( ( ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
2288 || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
2289 && (++cnt < MX_DELETION_ATTEMPTS)
2290 && (Sleep(100), 1) );
2291 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2292 ** Since the ASCII version of these Windows API do not exist for WINCE,
2293 ** it's important to not reference them for WINCE builds.
2295 #if SQLITE_OS_WINCE==0
2298 DeleteFileA(zConverted);
2299 }while( ( ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
2300 || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
2301 && (++cnt < MX_DELETION_ATTEMPTS)
2302 && (Sleep(100), 1) );
2306 OSTRACE(("DELETE \"%s\" %s\n", zFilename,
2307 ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
2310 return ( (rc == INVALID_FILE_ATTRIBUTES)
2311 && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
2315 ** Check the existance and status of a file.
2317 static int winAccess(
2318 sqlite3_vfs *pVfs, /* Not used on win32 */
2319 const char *zFilename, /* Name of file to check */
2320 int flags, /* Type of test to make on this file */
2321 int *pResOut /* OUT: Result */
2326 UNUSED_PARAMETER(pVfs);
2328 SimulateIOError( return SQLITE_IOERR_ACCESS; );
2329 zConverted = convertUtf8Filename(zFilename);
2330 if( zConverted==0 ){
2331 return SQLITE_NOMEM;
2334 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
2335 memset(&sAttrData, 0, sizeof(sAttrData));
2336 if( GetFileAttributesExW((WCHAR*)zConverted,
2337 GetFileExInfoStandard,
2339 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
2340 ** as if it does not exist.
2342 if( flags==SQLITE_ACCESS_EXISTS
2343 && sAttrData.nFileSizeHigh==0
2344 && sAttrData.nFileSizeLow==0 ){
2345 attr = INVALID_FILE_ATTRIBUTES;
2347 attr = sAttrData.dwFileAttributes;
2350 if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
2352 return SQLITE_IOERR_ACCESS;
2354 attr = INVALID_FILE_ATTRIBUTES;
2357 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2358 ** Since the ASCII version of these Windows API do not exist for WINCE,
2359 ** it's important to not reference them for WINCE builds.
2361 #if SQLITE_OS_WINCE==0
2363 attr = GetFileAttributesA((char*)zConverted);
2368 case SQLITE_ACCESS_READ:
2369 case SQLITE_ACCESS_EXISTS:
2370 rc = attr!=INVALID_FILE_ATTRIBUTES;
2372 case SQLITE_ACCESS_READWRITE:
2373 rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
2376 assert(!"Invalid flags argument");
2384 ** Turn a relative pathname into a full pathname. Write the full
2385 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
2388 static int winFullPathname(
2389 sqlite3_vfs *pVfs, /* Pointer to vfs object */
2390 const char *zRelative, /* Possibly relative input path */
2391 int nFull, /* Size of output buffer in bytes */
2392 char *zFull /* Output buffer */
2395 #if defined(__CYGWIN__)
2396 SimulateIOError( return SQLITE_ERROR );
2397 UNUSED_PARAMETER(nFull);
2398 cygwin_conv_to_full_win32_path(zRelative, zFull);
2403 SimulateIOError( return SQLITE_ERROR );
2404 UNUSED_PARAMETER(nFull);
2405 /* WinCE has no concept of a relative pathname, or so I am told. */
2406 sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
2410 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
2415 /* It's odd to simulate an io-error here, but really this is just
2416 ** using the io-error infrastructure to test that SQLite handles this
2417 ** function failing. This function could fail if, for example, the
2418 ** current working directory has been unlinked.
2420 SimulateIOError( return SQLITE_ERROR );
2421 UNUSED_PARAMETER(nFull);
2422 zConverted = convertUtf8Filename(zRelative);
2425 nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
2426 zTemp = malloc( nByte*sizeof(zTemp[0]) );
2429 return SQLITE_NOMEM;
2431 GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
2433 zOut = unicodeToUtf8(zTemp);
2435 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2436 ** Since the ASCII version of these Windows API do not exist for WINCE,
2437 ** it's important to not reference them for WINCE builds.
2439 #if SQLITE_OS_WINCE==0
2442 nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
2443 zTemp = malloc( nByte*sizeof(zTemp[0]) );
2446 return SQLITE_NOMEM;
2448 GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
2450 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
2455 sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
2459 return SQLITE_NOMEM;
2465 ** Get the sector size of the device used to store
2468 static int getSectorSize(
2470 const char *zRelative /* UTF-8 file name */
2472 DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
2473 /* GetDiskFreeSpace is not supported under WINCE */
2475 UNUSED_PARAMETER(pVfs);
2476 UNUSED_PARAMETER(zRelative);
2478 char zFullpath[MAX_PATH+1];
2484 ** We need to get the full path name of the file
2485 ** to get the drive letter to look up the sector
2488 SimulateIOErrorBenign(1);
2489 rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
2490 SimulateIOErrorBenign(0);
2491 if( rc == SQLITE_OK )
2493 void *zConverted = convertUtf8Filename(zFullpath);
2496 /* trim path to just drive reference */
2497 WCHAR *p = zConverted;
2504 dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
2510 /* trim path to just drive reference */
2511 char *p = (char *)zConverted;
2518 dwRet = GetDiskFreeSpaceA((char*)zConverted,
2527 bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
2531 return (int) bytesPerSector;
2534 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2536 ** Interfaces for opening a shared library, finding entry points
2537 ** within the shared library, and closing the shared library.
2540 ** Interfaces for opening a shared library, finding entry points
2541 ** within the shared library, and closing the shared library.
2543 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
2545 void *zConverted = convertUtf8Filename(zFilename);
2546 UNUSED_PARAMETER(pVfs);
2547 if( zConverted==0 ){
2551 h = LoadLibraryW((WCHAR*)zConverted);
2552 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
2553 ** Since the ASCII version of these Windows API do not exist for WINCE,
2554 ** it's important to not reference them for WINCE builds.
2556 #if SQLITE_OS_WINCE==0
2558 h = LoadLibraryA((char*)zConverted);
2564 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
2565 UNUSED_PARAMETER(pVfs);
2566 getLastErrorMsg(nBuf, zBufOut);
2568 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
2569 UNUSED_PARAMETER(pVfs);
2571 /* The GetProcAddressA() routine is only available on wince. */
2572 return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
2574 /* All other windows platforms expect GetProcAddress() to take
2575 ** an Ansi string regardless of the _UNICODE setting */
2576 return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
2579 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
2580 UNUSED_PARAMETER(pVfs);
2581 FreeLibrary((HANDLE)pHandle);
2583 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
2585 #define winDlError 0
2587 #define winDlClose 0
2592 ** Write up to nBuf bytes of randomness into zBuf.
2594 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
2596 UNUSED_PARAMETER(pVfs);
2597 #if defined(SQLITE_TEST)
2599 memset(zBuf, 0, nBuf);
2601 if( sizeof(SYSTEMTIME)<=nBuf-n ){
2604 memcpy(&zBuf[n], &x, sizeof(x));
2607 if( sizeof(DWORD)<=nBuf-n ){
2608 DWORD pid = GetCurrentProcessId();
2609 memcpy(&zBuf[n], &pid, sizeof(pid));
2612 if( sizeof(DWORD)<=nBuf-n ){
2613 DWORD cnt = GetTickCount();
2614 memcpy(&zBuf[n], &cnt, sizeof(cnt));
2617 if( sizeof(LARGE_INTEGER)<=nBuf-n ){
2619 QueryPerformanceCounter(&i);
2620 memcpy(&zBuf[n], &i, sizeof(i));
2629 ** Sleep for a little while. Return the amount of time slept.
2631 static int winSleep(sqlite3_vfs *pVfs, int microsec){
2632 Sleep((microsec+999)/1000);
2633 UNUSED_PARAMETER(pVfs);
2634 return ((microsec+999)/1000)*1000;
2638 ** The following variable, if set to a non-zero value, is interpreted as
2639 ** the number of seconds since 1970 and is used to set the result of
2640 ** sqlite3OsCurrentTime() during testing.
2643 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
2647 ** Find the current time (in Universal Coordinated Time). Write into *piNow
2648 ** the current time and date as a Julian Day number times 86_400_000. In
2649 ** other words, write into *piNow the number of milliseconds since the Julian
2650 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
2651 ** proleptic Gregorian calendar.
2653 ** On success, return 0. Return 1 if the time and date cannot be found.
2655 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
2656 /* FILETIME structure is a 64-bit value representing the number of
2657 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
2660 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
2662 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
2664 /* 2^32 - to avoid use of LL and warnings in gcc */
2665 static const sqlite3_int64 max32BitValue =
2666 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
2670 GetSystemTime(&time);
2671 /* if SystemTimeToFileTime() fails, it returns zero. */
2672 if (!SystemTimeToFileTime(&time,&ft)){
2676 GetSystemTimeAsFileTime( &ft );
2679 *piNow = winFiletimeEpoch +
2680 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
2681 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
2684 if( sqlite3_current_time ){
2685 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
2688 UNUSED_PARAMETER(pVfs);
2693 ** Find the current time (in Universal Coordinated Time). Write the
2694 ** current time and date as a Julian Day number into *prNow and
2695 ** return 0. Return 1 if the time and date cannot be found.
2697 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
2700 rc = winCurrentTimeInt64(pVfs, &i);
2702 *prNow = i/86400000.0;
2708 ** The idea is that this function works like a combination of
2709 ** GetLastError() and FormatMessage() on windows (or errno and
2710 ** strerror_r() on unix). After an error is returned by an OS
2711 ** function, SQLite calls this function with zBuf pointing to
2712 ** a buffer of nBuf bytes. The OS layer should populate the
2713 ** buffer with a nul-terminated UTF-8 encoded error message
2714 ** describing the last IO error to have occurred within the calling
2717 ** If the error message is too large for the supplied buffer,
2718 ** it should be truncated. The return value of xGetLastError
2719 ** is zero if the error message fits in the buffer, or non-zero
2720 ** otherwise (if the message was truncated). If non-zero is returned,
2721 ** then it is not necessary to include the nul-terminator character
2722 ** in the output buffer.
2724 ** Not supplying an error message will have no adverse effect
2725 ** on SQLite. It is fine to have an implementation that never
2726 ** returns an error message:
2728 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
2729 ** assert(zBuf[0]=='\0');
2733 ** However if an error message is supplied, it will be incorporated
2734 ** by sqlite into the error message available to the user using
2735 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
2737 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
2738 UNUSED_PARAMETER(pVfs);
2739 return getLastErrorMsg(nBuf, zBuf);
2745 ** Initialize and deinitialize the operating system interface.
2747 int sqlite3_os_init(void){
2748 static sqlite3_vfs winVfs = {
2750 sizeof(winFile), /* szOsFile */
2751 MAX_PATH, /* mxPathname */
2753 "win32", /* zName */
2755 winOpen, /* xOpen */
2756 winDelete, /* xDelete */
2757 winAccess, /* xAccess */
2758 winFullPathname, /* xFullPathname */
2759 winDlOpen, /* xDlOpen */
2760 winDlError, /* xDlError */
2761 winDlSym, /* xDlSym */
2762 winDlClose, /* xDlClose */
2763 winRandomness, /* xRandomness */
2764 winSleep, /* xSleep */
2765 winCurrentTime, /* xCurrentTime */
2766 winGetLastError, /* xGetLastError */
2767 winCurrentTimeInt64, /* xCurrentTimeInt64 */
2768 0, /* xSetSystemCall */
2769 0, /* xGetSystemCall */
2770 0, /* xNextSystemCall */
2773 #ifndef SQLITE_OMIT_WAL
2774 /* get memory map allocation granularity */
2775 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
2776 GetSystemInfo(&winSysInfo);
2777 assert(winSysInfo.dwAllocationGranularity > 0);
2780 sqlite3_vfs_register(&winVfs, 1);
2783 int sqlite3_os_end(void){
2787 void chromium_sqlite3_initialize_win_sqlite3_file(sqlite3_file* file, HANDLE handle) {
2788 winFile* winSQLite3File = (winFile*)file;
2789 memset(file, 0, sizeof(*file));
2790 winSQLite3File->pMethod = &winIoMethod;
2791 winSQLite3File->h = handle;
2794 #endif /* SQLITE_OS_WIN */