os_win.c

Go to the documentation of this file.
00001 /*
00002 ** 2004 May 22
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 ******************************************************************************
00012 **
00013 ** This file contains code that is specific to windows.
00014 **
00015 ** $Id: os_win.c,v 1.137 2008/11/07 00:06:18 drh Exp $
00016 */
00017 #include "sqliteInt.h"
00018 #if SQLITE_OS_WIN               /* This file is used for windows only */
00019 
00020 
00021 /*
00022 ** A Note About Memory Allocation:
00023 **
00024 ** This driver uses malloc()/free() directly rather than going through
00025 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
00026 ** are designed for use on embedded systems where memory is scarce and
00027 ** malloc failures happen frequently.  Win32 does not typically run on
00028 ** embedded systems, and when it does the developers normally have bigger
00029 ** problems to worry about than running out of memory.  So there is not
00030 ** a compelling need to use the wrappers.
00031 **
00032 ** But there is a good reason to not use the wrappers.  If we use the
00033 ** wrappers then we will get simulated malloc() failures within this
00034 ** driver.  And that causes all kinds of problems for our tests.  We
00035 ** could enhance SQLite to deal with simulated malloc failures within
00036 ** the OS driver, but the code to deal with those failure would not
00037 ** be exercised on Linux (which does not need to malloc() in the driver)
00038 ** and so we would have difficulty writing coverage tests for that
00039 ** code.  Better to leave the code out, we think.
00040 **
00041 ** The point of this discussion is as follows:  When creating a new
00042 ** OS layer for an embedded system, if you use this file as an example,
00043 ** avoid the use of malloc()/free().  Those routines work ok on windows
00044 ** desktops but not so well in embedded systems.
00045 */
00046 
00047 #include <winbase.h>
00048 
00049 #ifdef __CYGWIN__
00050 # include <sys/cygwin.h>
00051 #endif
00052 
00053 /*
00054 ** Macros used to determine whether or not to use threads.
00055 */
00056 #if defined(THREADSAFE) && THREADSAFE
00057 # define SQLITE_W32_THREADS 1
00058 #endif
00059 
00060 /*
00061 ** Include code that is common to all os_*.c files
00062 */
00063 #include "os_common.h"
00064 
00065 /*
00066 ** Some microsoft compilers lack this definition.
00067 */
00068 #ifndef INVALID_FILE_ATTRIBUTES
00069 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
00070 #endif
00071 
00072 /*
00073 ** Determine if we are dealing with WindowsCE - which has a much
00074 ** reduced API.
00075 */
00076 #if SQLITE_OS_WINCE
00077 # define AreFileApisANSI() 1
00078 #endif
00079 
00080 /*
00081 ** WinCE lacks native support for file locking so we have to fake it
00082 ** with some code of our own.
00083 */
00084 #if SQLITE_OS_WINCE
00085 typedef struct winceLock {
00086   int nReaders;       /* Number of reader locks obtained */
00087   BOOL bPending;      /* Indicates a pending lock has been obtained */
00088   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
00089   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
00090 } winceLock;
00091 #endif
00092 
00093 /*
00094 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
00095 ** portability layer.
00096 */
00097 typedef struct winFile winFile;
00098 struct winFile {
00099   const sqlite3_io_methods *pMethod;/* Must be first */
00100   HANDLE h;               /* Handle for accessing the file */
00101   unsigned char locktype; /* Type of lock currently held on this file */
00102   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
00103 #if SQLITE_OS_WINCE
00104   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
00105   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
00106   HANDLE hShared;         /* Shared memory segment used for locking */
00107   winceLock local;        /* Locks obtained by this instance of winFile */
00108   winceLock *shared;      /* Global shared lock memory for the file  */
00109 #endif
00110 };
00111 
00112 
00113 /*
00114 ** The following variable is (normally) set once and never changes
00115 ** thereafter.  It records whether the operating system is Win95
00116 ** or WinNT.
00117 **
00118 ** 0:   Operating system unknown.
00119 ** 1:   Operating system is Win95.
00120 ** 2:   Operating system is WinNT.
00121 **
00122 ** In order to facilitate testing on a WinNT system, the test fixture
00123 ** can manually set this value to 1 to emulate Win98 behavior.
00124 */
00125 #ifdef SQLITE_TEST
00126 int sqlite3_os_type = 0;
00127 #else
00128 static int sqlite3_os_type = 0;
00129 #endif
00130 
00131 /*
00132 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
00133 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
00134 **
00135 ** Here is an interesting observation:  Win95, Win98, and WinME lack
00136 ** the LockFileEx() API.  But we can still statically link against that
00137 ** API as long as we don't call it win running Win95/98/ME.  A call to
00138 ** this routine is used to determine if the host is Win95/98/ME or
00139 ** WinNT/2K/XP so that we will know whether or not we can safely call
00140 ** the LockFileEx() API.
00141 */
00142 #if SQLITE_OS_WINCE
00143 # define isNT()  (1)
00144 #else
00145   static int isNT(void){
00146     if( sqlite3_os_type==0 ){
00147       OSVERSIONINFO sInfo;
00148       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
00149       GetVersionEx(&sInfo);
00150       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
00151     }
00152     return sqlite3_os_type==2;
00153   }
00154 #endif /* SQLITE_OS_WINCE */
00155 
00156 /*
00157 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
00158 **
00159 ** Space to hold the returned string is obtained from malloc.
00160 */
00161 static WCHAR *utf8ToUnicode(const char *zFilename){
00162   int nChar;
00163   WCHAR *zWideFilename;
00164 
00165   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
00166   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
00167   if( zWideFilename==0 ){
00168     return 0;
00169   }
00170   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
00171   if( nChar==0 ){
00172     free(zWideFilename);
00173     zWideFilename = 0;
00174   }
00175   return zWideFilename;
00176 }
00177 
00178 /*
00179 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
00180 ** obtained from malloc().
00181 */
00182 static char *unicodeToUtf8(const WCHAR *zWideFilename){
00183   int nByte;
00184   char *zFilename;
00185 
00186   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
00187   zFilename = malloc( nByte );
00188   if( zFilename==0 ){
00189     return 0;
00190   }
00191   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
00192                               0, 0);
00193   if( nByte == 0 ){
00194     free(zFilename);
00195     zFilename = 0;
00196   }
00197   return zFilename;
00198 }
00199 
00200 /*
00201 ** Convert an ansi string to microsoft unicode, based on the
00202 ** current codepage settings for file apis.
00203 ** 
00204 ** Space to hold the returned string is obtained
00205 ** from malloc.
00206 */
00207 static WCHAR *mbcsToUnicode(const char *zFilename){
00208   int nByte;
00209   WCHAR *zMbcsFilename;
00210   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
00211 
00212   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
00213   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
00214   if( zMbcsFilename==0 ){
00215     return 0;
00216   }
00217   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
00218   if( nByte==0 ){
00219     free(zMbcsFilename);
00220     zMbcsFilename = 0;
00221   }
00222   return zMbcsFilename;
00223 }
00224 
00225 /*
00226 ** Convert microsoft unicode to multibyte character string, based on the
00227 ** user's Ansi codepage.
00228 **
00229 ** Space to hold the returned string is obtained from
00230 ** malloc().
00231 */
00232 static char *unicodeToMbcs(const WCHAR *zWideFilename){
00233   int nByte;
00234   char *zFilename;
00235   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
00236 
00237   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
00238   zFilename = malloc( nByte );
00239   if( zFilename==0 ){
00240     return 0;
00241   }
00242   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
00243                               0, 0);
00244   if( nByte == 0 ){
00245     free(zFilename);
00246     zFilename = 0;
00247   }
00248   return zFilename;
00249 }
00250 
00251 /*
00252 ** Convert multibyte character string to UTF-8.  Space to hold the
00253 ** returned string is obtained from malloc().
00254 */
00255 static char *mbcsToUtf8(const char *zFilename){
00256   char *zFilenameUtf8;
00257   WCHAR *zTmpWide;
00258 
00259   zTmpWide = mbcsToUnicode(zFilename);
00260   if( zTmpWide==0 ){
00261     return 0;
00262   }
00263   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
00264   free(zTmpWide);
00265   return zFilenameUtf8;
00266 }
00267 
00268 /*
00269 ** Convert UTF-8 to multibyte character string.  Space to hold the 
00270 ** returned string is obtained from malloc().
00271 */
00272 static char *utf8ToMbcs(const char *zFilename){
00273   char *zFilenameMbcs;
00274   WCHAR *zTmpWide;
00275 
00276   zTmpWide = utf8ToUnicode(zFilename);
00277   if( zTmpWide==0 ){
00278     return 0;
00279   }
00280   zFilenameMbcs = unicodeToMbcs(zTmpWide);
00281   free(zTmpWide);
00282   return zFilenameMbcs;
00283 }
00284 
00285 #if SQLITE_OS_WINCE
00286 /*************************************************************************
00287 ** This section contains code for WinCE only.
00288 */
00289 /*
00290 ** WindowsCE does not have a localtime() function.  So create a
00291 ** substitute.
00292 */
00293 #include <time.h>
00294 struct tm *__cdecl localtime(const time_t *t)
00295 {
00296   static struct tm y;
00297   FILETIME uTm, lTm;
00298   SYSTEMTIME pTm;
00299   sqlite3_int64 t64;
00300   t64 = *t;
00301   t64 = (t64 + 11644473600)*10000000;
00302   uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
00303   uTm.dwHighDateTime= t64 >> 32;
00304   FileTimeToLocalFileTime(&uTm,&lTm);
00305   FileTimeToSystemTime(&lTm,&pTm);
00306   y.tm_year = pTm.wYear - 1900;
00307   y.tm_mon = pTm.wMonth - 1;
00308   y.tm_wday = pTm.wDayOfWeek;
00309   y.tm_mday = pTm.wDay;
00310   y.tm_hour = pTm.wHour;
00311   y.tm_min = pTm.wMinute;
00312   y.tm_sec = pTm.wSecond;
00313   return &y;
00314 }
00315 
00316 /* This will never be called, but defined to make the code compile */
00317 #define GetTempPathA(a,b)
00318 
00319 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
00320 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
00321 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
00322 
00323 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
00324 
00325 /*
00326 ** Acquire a lock on the handle h
00327 */
00328 static void winceMutexAcquire(HANDLE h){
00329    DWORD dwErr;
00330    do {
00331      dwErr = WaitForSingleObject(h, INFINITE);
00332    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
00333 }
00334 /*
00335 ** Release a lock acquired by winceMutexAcquire()
00336 */
00337 #define winceMutexRelease(h) ReleaseMutex(h)
00338 
00339 /*
00340 ** Create the mutex and shared memory used for locking in the file
00341 ** descriptor pFile
00342 */
00343 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
00344   WCHAR *zTok;
00345   WCHAR *zName = utf8ToUnicode(zFilename);
00346   BOOL bInit = TRUE;
00347 
00348   /* Initialize the local lockdata */
00349   ZeroMemory(&pFile->local, sizeof(pFile->local));
00350 
00351   /* Replace the backslashes from the filename and lowercase it
00352   ** to derive a mutex name. */
00353   zTok = CharLowerW(zName);
00354   for (;*zTok;zTok++){
00355     if (*zTok == '\\') *zTok = '_';
00356   }
00357 
00358   /* Create/open the named mutex */
00359   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
00360   if (!pFile->hMutex){
00361     free(zName);
00362     return FALSE;
00363   }
00364 
00365   /* Acquire the mutex before continuing */
00366   winceMutexAcquire(pFile->hMutex);
00367   
00368   /* Since the names of named mutexes, semaphores, file mappings etc are 
00369   ** case-sensitive, take advantage of that by uppercasing the mutex name
00370   ** and using that as the shared filemapping name.
00371   */
00372   CharUpperW(zName);
00373   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
00374                                        PAGE_READWRITE, 0, sizeof(winceLock),
00375                                        zName);  
00376 
00377   /* Set a flag that indicates we're the first to create the memory so it 
00378   ** must be zero-initialized */
00379   if (GetLastError() == ERROR_ALREADY_EXISTS){
00380     bInit = FALSE;
00381   }
00382 
00383   free(zName);
00384 
00385   /* If we succeeded in making the shared memory handle, map it. */
00386   if (pFile->hShared){
00387     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
00388              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
00389     /* If mapping failed, close the shared memory handle and erase it */
00390     if (!pFile->shared){
00391       CloseHandle(pFile->hShared);
00392       pFile->hShared = NULL;
00393     }
00394   }
00395 
00396   /* If shared memory could not be created, then close the mutex and fail */
00397   if (pFile->hShared == NULL){
00398     winceMutexRelease(pFile->hMutex);
00399     CloseHandle(pFile->hMutex);
00400     pFile->hMutex = NULL;
00401     return FALSE;
00402   }
00403   
00404   /* Initialize the shared memory if we're supposed to */
00405   if (bInit) {
00406     ZeroMemory(pFile->shared, sizeof(winceLock));
00407   }
00408 
00409   winceMutexRelease(pFile->hMutex);
00410   return TRUE;
00411 }
00412 
00413 /*
00414 ** Destroy the part of winFile that deals with wince locks
00415 */
00416 static void winceDestroyLock(winFile *pFile){
00417   if (pFile->hMutex){
00418     /* Acquire the mutex */
00419     winceMutexAcquire(pFile->hMutex);
00420 
00421     /* The following blocks should probably assert in debug mode, but they
00422        are to cleanup in case any locks remained open */
00423     if (pFile->local.nReaders){
00424       pFile->shared->nReaders --;
00425     }
00426     if (pFile->local.bReserved){
00427       pFile->shared->bReserved = FALSE;
00428     }
00429     if (pFile->local.bPending){
00430       pFile->shared->bPending = FALSE;
00431     }
00432     if (pFile->local.bExclusive){
00433       pFile->shared->bExclusive = FALSE;
00434     }
00435 
00436     /* De-reference and close our copy of the shared memory handle */
00437     UnmapViewOfFile(pFile->shared);
00438     CloseHandle(pFile->hShared);
00439 
00440     /* Done with the mutex */
00441     winceMutexRelease(pFile->hMutex);    
00442     CloseHandle(pFile->hMutex);
00443     pFile->hMutex = NULL;
00444   }
00445 }
00446 
00447 /* 
00448 ** An implementation of the LockFile() API of windows for wince
00449 */
00450 static BOOL winceLockFile(
00451   HANDLE *phFile,
00452   DWORD dwFileOffsetLow,
00453   DWORD dwFileOffsetHigh,
00454   DWORD nNumberOfBytesToLockLow,
00455   DWORD nNumberOfBytesToLockHigh
00456 ){
00457   winFile *pFile = HANDLE_TO_WINFILE(phFile);
00458   BOOL bReturn = FALSE;
00459 
00460   if (!pFile->hMutex) return TRUE;
00461   winceMutexAcquire(pFile->hMutex);
00462 
00463   /* Wanting an exclusive lock? */
00464   if (dwFileOffsetLow == SHARED_FIRST
00465        && nNumberOfBytesToLockLow == SHARED_SIZE){
00466     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
00467        pFile->shared->bExclusive = TRUE;
00468        pFile->local.bExclusive = TRUE;
00469        bReturn = TRUE;
00470     }
00471   }
00472 
00473   /* Want a read-only lock? */
00474   else if ((dwFileOffsetLow >= SHARED_FIRST &&
00475             dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
00476             nNumberOfBytesToLockLow == 1){
00477     if (pFile->shared->bExclusive == 0){
00478       pFile->local.nReaders ++;
00479       if (pFile->local.nReaders == 1){
00480         pFile->shared->nReaders ++;
00481       }
00482       bReturn = TRUE;
00483     }
00484   }
00485 
00486   /* Want a pending lock? */
00487   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
00488     /* If no pending lock has been acquired, then acquire it */
00489     if (pFile->shared->bPending == 0) {
00490       pFile->shared->bPending = TRUE;
00491       pFile->local.bPending = TRUE;
00492       bReturn = TRUE;
00493     }
00494   }
00495   /* Want a reserved lock? */
00496   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
00497     if (pFile->shared->bReserved == 0) {
00498       pFile->shared->bReserved = TRUE;
00499       pFile->local.bReserved = TRUE;
00500       bReturn = TRUE;
00501     }
00502   }
00503 
00504   winceMutexRelease(pFile->hMutex);
00505   return bReturn;
00506 }
00507 
00508 /*
00509 ** An implementation of the UnlockFile API of windows for wince
00510 */
00511 static BOOL winceUnlockFile(
00512   HANDLE *phFile,
00513   DWORD dwFileOffsetLow,
00514   DWORD dwFileOffsetHigh,
00515   DWORD nNumberOfBytesToUnlockLow,
00516   DWORD nNumberOfBytesToUnlockHigh
00517 ){
00518   winFile *pFile = HANDLE_TO_WINFILE(phFile);
00519   BOOL bReturn = FALSE;
00520 
00521   if (!pFile->hMutex) return TRUE;
00522   winceMutexAcquire(pFile->hMutex);
00523 
00524   /* Releasing a reader lock or an exclusive lock */
00525   if (dwFileOffsetLow >= SHARED_FIRST &&
00526        dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
00527     /* Did we have an exclusive lock? */
00528     if (pFile->local.bExclusive){
00529       pFile->local.bExclusive = FALSE;
00530       pFile->shared->bExclusive = FALSE;
00531       bReturn = TRUE;
00532     }
00533 
00534     /* Did we just have a reader lock? */
00535     else if (pFile->local.nReaders){
00536       pFile->local.nReaders --;
00537       if (pFile->local.nReaders == 0)
00538       {
00539         pFile->shared->nReaders --;
00540       }
00541       bReturn = TRUE;
00542     }
00543   }
00544 
00545   /* Releasing a pending lock */
00546   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
00547     if (pFile->local.bPending){
00548       pFile->local.bPending = FALSE;
00549       pFile->shared->bPending = FALSE;
00550       bReturn = TRUE;
00551     }
00552   }
00553   /* Releasing a reserved lock */
00554   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
00555     if (pFile->local.bReserved) {
00556       pFile->local.bReserved = FALSE;
00557       pFile->shared->bReserved = FALSE;
00558       bReturn = TRUE;
00559     }
00560   }
00561 
00562   winceMutexRelease(pFile->hMutex);
00563   return bReturn;
00564 }
00565 
00566 /*
00567 ** An implementation of the LockFileEx() API of windows for wince
00568 */
00569 static BOOL winceLockFileEx(
00570   HANDLE *phFile,
00571   DWORD dwFlags,
00572   DWORD dwReserved,
00573   DWORD nNumberOfBytesToLockLow,
00574   DWORD nNumberOfBytesToLockHigh,
00575   LPOVERLAPPED lpOverlapped
00576 ){
00577   /* If the caller wants a shared read lock, forward this call
00578   ** to winceLockFile */
00579   if (lpOverlapped->Offset == SHARED_FIRST &&
00580       dwFlags == 1 &&
00581       nNumberOfBytesToLockLow == SHARED_SIZE){
00582     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
00583   }
00584   return FALSE;
00585 }
00586 /*
00587 ** End of the special code for wince
00588 *****************************************************************************/
00589 #endif /* SQLITE_OS_WINCE */
00590 
00591 /*****************************************************************************
00592 ** The next group of routines implement the I/O methods specified
00593 ** by the sqlite3_io_methods object.
00594 ******************************************************************************/
00595 
00596 /*
00597 ** Close a file.
00598 **
00599 ** It is reported that an attempt to close a handle might sometimes
00600 ** fail.  This is a very unreasonable result, but windows is notorious
00601 ** for being unreasonable so I do not doubt that it might happen.  If
00602 ** the close fails, we pause for 100 milliseconds and try again.  As
00603 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
00604 ** giving up and returning an error.
00605 */
00606 #define MX_CLOSE_ATTEMPT 3
00607 static int winClose(sqlite3_file *id){
00608   int rc, cnt = 0;
00609   winFile *pFile = (winFile*)id;
00610   OSTRACE2("CLOSE %d\n", pFile->h);
00611   do{
00612     rc = CloseHandle(pFile->h);
00613   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
00614 #if SQLITE_OS_WINCE
00615 #define WINCE_DELETION_ATTEMPTS 3
00616   winceDestroyLock(pFile);
00617   if( pFile->zDeleteOnClose ){
00618     int cnt = 0;
00619     while(
00620            DeleteFileW(pFile->zDeleteOnClose)==0
00621         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
00622         && cnt++ < WINCE_DELETION_ATTEMPTS
00623     ){
00624        Sleep(100);  /* Wait a little before trying again */
00625     }
00626     free(pFile->zDeleteOnClose);
00627   }
00628 #endif
00629   OpenCounter(-1);
00630   return rc ? SQLITE_OK : SQLITE_IOERR;
00631 }
00632 
00633 /*
00634 ** Some microsoft compilers lack this definition.
00635 */
00636 #ifndef INVALID_SET_FILE_POINTER
00637 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
00638 #endif
00639 
00640 /*
00641 ** Read data from a file into a buffer.  Return SQLITE_OK if all
00642 ** bytes were read successfully and SQLITE_IOERR if anything goes
00643 ** wrong.
00644 */
00645 static int winRead(
00646   sqlite3_file *id,          /* File to read from */
00647   void *pBuf,                /* Write content into this buffer */
00648   int amt,                   /* Number of bytes to read */
00649   sqlite3_int64 offset       /* Begin reading at this offset */
00650 ){
00651   LONG upperBits = (offset>>32) & 0x7fffffff;
00652   LONG lowerBits = offset & 0xffffffff;
00653   DWORD rc;
00654   DWORD got;
00655   winFile *pFile = (winFile*)id;
00656   assert( id!=0 );
00657   SimulateIOError(return SQLITE_IOERR_READ);
00658   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
00659   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
00660   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
00661     return SQLITE_FULL;
00662   }
00663   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
00664     return SQLITE_IOERR_READ;
00665   }
00666   if( got==(DWORD)amt ){
00667     return SQLITE_OK;
00668   }else{
00669     /* Unread parts of the buffer must be zero-filled */
00670     memset(&((char*)pBuf)[got], 0, amt-got);
00671     return SQLITE_IOERR_SHORT_READ;
00672   }
00673 }
00674 
00675 /*
00676 ** Write data from a buffer into a file.  Return SQLITE_OK on success
00677 ** or some other error code on failure.
00678 */
00679 static int winWrite(
00680   sqlite3_file *id,         /* File to write into */
00681   const void *pBuf,         /* The bytes to be written */
00682   int amt,                  /* Number of bytes to write */
00683   sqlite3_int64 offset      /* Offset into the file to begin writing at */
00684 ){
00685   LONG upperBits = (offset>>32) & 0x7fffffff;
00686   LONG lowerBits = offset & 0xffffffff;
00687   DWORD rc;
00688   DWORD wrote;
00689   winFile *pFile = (winFile*)id;
00690   assert( id!=0 );
00691   SimulateIOError(return SQLITE_IOERR_WRITE);
00692   SimulateDiskfullError(return SQLITE_FULL);
00693   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
00694   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
00695   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
00696     return SQLITE_FULL;
00697   }
00698   assert( amt>0 );
00699   while(
00700      amt>0
00701      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
00702      && wrote>0
00703   ){
00704     amt -= wrote;
00705     pBuf = &((char*)pBuf)[wrote];
00706   }
00707   if( !rc || amt>(int)wrote ){
00708     return SQLITE_FULL;
00709   }
00710   return SQLITE_OK;
00711 }
00712 
00713 /*
00714 ** Truncate an open file to a specified size
00715 */
00716 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
00717   DWORD rc;
00718   LONG upperBits = (nByte>>32) & 0x7fffffff;
00719   LONG lowerBits = nByte & 0xffffffff;
00720   winFile *pFile = (winFile*)id;
00721   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
00722   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
00723   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
00724   if( INVALID_SET_FILE_POINTER != rc ){
00725     /* SetEndOfFile will fail if nByte is negative */
00726     if( SetEndOfFile(pFile->h) ){
00727       return SQLITE_OK;
00728     }
00729   }
00730   return SQLITE_IOERR_TRUNCATE;
00731 }
00732 
00733 #ifdef SQLITE_TEST
00734 /*
00735 ** Count the number of fullsyncs and normal syncs.  This is used to test
00736 ** that syncs and fullsyncs are occuring at the right times.
00737 */
00738 int sqlite3_sync_count = 0;
00739 int sqlite3_fullsync_count = 0;
00740 #endif
00741 
00742 /*
00743 ** Make sure all writes to a particular file are committed to disk.
00744 */
00745 static int winSync(sqlite3_file *id, int flags){
00746   winFile *pFile = (winFile*)id;
00747   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
00748 #ifdef SQLITE_TEST
00749   if( flags & SQLITE_SYNC_FULL ){
00750     sqlite3_fullsync_count++;
00751   }
00752   sqlite3_sync_count++;
00753 #endif
00754   if( FlushFileBuffers(pFile->h) ){
00755     return SQLITE_OK;
00756   }else{
00757     return SQLITE_IOERR;
00758   }
00759 }
00760 
00761 /*
00762 ** Determine the current size of a file in bytes
00763 */
00764 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
00765   winFile *pFile = (winFile*)id;
00766   DWORD upperBits, lowerBits;
00767   SimulateIOError(return SQLITE_IOERR_FSTAT);
00768   lowerBits = GetFileSize(pFile->h, &upperBits);
00769   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
00770   return SQLITE_OK;
00771 }
00772 
00773 /*
00774 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
00775 */
00776 #ifndef LOCKFILE_FAIL_IMMEDIATELY
00777 # define LOCKFILE_FAIL_IMMEDIATELY 1
00778 #endif
00779 
00780 /*
00781 ** Acquire a reader lock.
00782 ** Different API routines are called depending on whether or not this
00783 ** is Win95 or WinNT.
00784 */
00785 static int getReadLock(winFile *pFile){
00786   int res;
00787   if( isNT() ){
00788     OVERLAPPED ovlp;
00789     ovlp.Offset = SHARED_FIRST;
00790     ovlp.OffsetHigh = 0;
00791     ovlp.hEvent = 0;
00792     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
00793                      0, SHARED_SIZE, 0, &ovlp);
00794 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
00795 */
00796 #if SQLITE_OS_WINCE==0
00797   }else{
00798     int lk;
00799     sqlite3_randomness(sizeof(lk), &lk);
00800     pFile->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
00801     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
00802 #endif
00803   }
00804   return res;
00805 }
00806 
00807 /*
00808 ** Undo a readlock
00809 */
00810 static int unlockReadLock(winFile *pFile){
00811   int res;
00812   if( isNT() ){
00813     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
00814 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
00815 */
00816 #if SQLITE_OS_WINCE==0
00817   }else{
00818     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
00819 #endif
00820   }
00821   return res;
00822 }
00823 
00824 /*
00825 ** Lock the file with the lock specified by parameter locktype - one
00826 ** of the following:
00827 **
00828 **     (1) SHARED_LOCK
00829 **     (2) RESERVED_LOCK
00830 **     (3) PENDING_LOCK
00831 **     (4) EXCLUSIVE_LOCK
00832 **
00833 ** Sometimes when requesting one lock state, additional lock states
00834 ** are inserted in between.  The locking might fail on one of the later
00835 ** transitions leaving the lock state different from what it started but
00836 ** still short of its goal.  The following chart shows the allowed
00837 ** transitions and the inserted intermediate states:
00838 **
00839 **    UNLOCKED -> SHARED
00840 **    SHARED -> RESERVED
00841 **    SHARED -> (PENDING) -> EXCLUSIVE
00842 **    RESERVED -> (PENDING) -> EXCLUSIVE
00843 **    PENDING -> EXCLUSIVE
00844 **
00845 ** This routine will only increase a lock.  The winUnlock() routine
00846 ** erases all locks at once and returns us immediately to locking level 0.
00847 ** It is not possible to lower the locking level one step at a time.  You
00848 ** must go straight to locking level 0.
00849 */
00850 static int winLock(sqlite3_file *id, int locktype){
00851   int rc = SQLITE_OK;    /* Return code from subroutines */
00852   int res = 1;           /* Result of a windows lock call */
00853   int newLocktype;       /* Set pFile->locktype to this value before exiting */
00854   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
00855   winFile *pFile = (winFile*)id;
00856 
00857   assert( pFile!=0 );
00858   OSTRACE5("LOCK %d %d was %d(%d)\n",
00859           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
00860 
00861   /* If there is already a lock of this type or more restrictive on the
00862   ** OsFile, do nothing. Don't use the end_lock: exit path, as
00863   ** sqlite3OsEnterMutex() hasn't been called yet.
00864   */
00865   if( pFile->locktype>=locktype ){
00866     return SQLITE_OK;
00867   }
00868 
00869   /* Make sure the locking sequence is correct
00870   */
00871   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
00872   assert( locktype!=PENDING_LOCK );
00873   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
00874 
00875   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
00876   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
00877   ** the PENDING_LOCK byte is temporary.
00878   */
00879   newLocktype = pFile->locktype;
00880   if( pFile->locktype==NO_LOCK
00881    || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
00882   ){
00883     int cnt = 3;
00884     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
00885       /* Try 3 times to get the pending lock.  The pending lock might be
00886       ** held by another reader process who will release it momentarily.
00887       */
00888       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
00889       Sleep(1);
00890     }
00891     gotPendingLock = res;
00892   }
00893 
00894   /* Acquire a shared lock
00895   */
00896   if( locktype==SHARED_LOCK && res ){
00897     assert( pFile->locktype==NO_LOCK );
00898     res = getReadLock(pFile);
00899     if( res ){
00900       newLocktype = SHARED_LOCK;
00901     }
00902   }
00903 
00904   /* Acquire a RESERVED lock
00905   */
00906   if( locktype==RESERVED_LOCK && res ){
00907     assert( pFile->locktype==SHARED_LOCK );
00908     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
00909     if( res ){
00910       newLocktype = RESERVED_LOCK;
00911     }
00912   }
00913 
00914   /* Acquire a PENDING lock
00915   */
00916   if( locktype==EXCLUSIVE_LOCK && res ){
00917     newLocktype = PENDING_LOCK;
00918     gotPendingLock = 0;
00919   }
00920 
00921   /* Acquire an EXCLUSIVE lock
00922   */
00923   if( locktype==EXCLUSIVE_LOCK && res ){
00924     assert( pFile->locktype>=SHARED_LOCK );
00925     res = unlockReadLock(pFile);
00926     OSTRACE2("unreadlock = %d\n", res);
00927     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
00928     if( res ){
00929       newLocktype = EXCLUSIVE_LOCK;
00930     }else{
00931       OSTRACE2("error-code = %d\n", GetLastError());
00932       getReadLock(pFile);
00933     }
00934   }
00935 
00936   /* If we are holding a PENDING lock that ought to be released, then
00937   ** release it now.
00938   */
00939   if( gotPendingLock && locktype==SHARED_LOCK ){
00940     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
00941   }
00942 
00943   /* Update the state of the lock has held in the file descriptor then
00944   ** return the appropriate result code.
00945   */
00946   if( res ){
00947     rc = SQLITE_OK;
00948   }else{
00949     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
00950            locktype, newLocktype);
00951     rc = SQLITE_BUSY;
00952   }
00953   pFile->locktype = newLocktype;
00954   return rc;
00955 }
00956 
00957 /*
00958 ** This routine checks if there is a RESERVED lock held on the specified
00959 ** file by this or any other process. If such a lock is held, return
00960 ** non-zero, otherwise zero.
00961 */
00962 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
00963   int rc;
00964   winFile *pFile = (winFile*)id;
00965   assert( pFile!=0 );
00966   if( pFile->locktype>=RESERVED_LOCK ){
00967     rc = 1;
00968     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
00969   }else{
00970     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
00971     if( rc ){
00972       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
00973     }
00974     rc = !rc;
00975     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
00976   }
00977   *pResOut = rc;
00978   return SQLITE_OK;
00979 }
00980 
00981 /*
00982 ** Lower the locking level on file descriptor id to locktype.  locktype
00983 ** must be either NO_LOCK or SHARED_LOCK.
00984 **
00985 ** If the locking level of the file descriptor is already at or below
00986 ** the requested locking level, this routine is a no-op.
00987 **
00988 ** It is not possible for this routine to fail if the second argument
00989 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
00990 ** might return SQLITE_IOERR;
00991 */
00992 static int winUnlock(sqlite3_file *id, int locktype){
00993   int type;
00994   winFile *pFile = (winFile*)id;
00995   int rc = SQLITE_OK;
00996   assert( pFile!=0 );
00997   assert( locktype<=SHARED_LOCK );
00998   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
00999           pFile->locktype, pFile->sharedLockByte);
01000   type = pFile->locktype;
01001   if( type>=EXCLUSIVE_LOCK ){
01002     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
01003     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
01004       /* This should never happen.  We should always be able to
01005       ** reacquire the read lock */
01006       rc = SQLITE_IOERR_UNLOCK;
01007     }
01008   }
01009   if( type>=RESERVED_LOCK ){
01010     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
01011   }
01012   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
01013     unlockReadLock(pFile);
01014   }
01015   if( type>=PENDING_LOCK ){
01016     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
01017   }
01018   pFile->locktype = locktype;
01019   return rc;
01020 }
01021 
01022 /*
01023 ** Control and query of the open file handle.
01024 */
01025 static int winFileControl(sqlite3_file *id, int op, void *pArg){
01026   switch( op ){
01027     case SQLITE_FCNTL_LOCKSTATE: {
01028       *(int*)pArg = ((winFile*)id)->locktype;
01029       return SQLITE_OK;
01030     }
01031   }
01032   return SQLITE_ERROR;
01033 }
01034 
01035 /*
01036 ** Return the sector size in bytes of the underlying block device for
01037 ** the specified file. This is almost always 512 bytes, but may be
01038 ** larger for some devices.
01039 **
01040 ** SQLite code assumes this function cannot fail. It also assumes that
01041 ** if two files are created in the same file-system directory (i.e.
01042 ** a database and its journal file) that the sector size will be the
01043 ** same for both.
01044 */
01045 static int winSectorSize(sqlite3_file *id){
01046   return SQLITE_DEFAULT_SECTOR_SIZE;
01047 }
01048 
01049 /*
01050 ** Return a vector of device characteristics.
01051 */
01052 static int winDeviceCharacteristics(sqlite3_file *id){
01053   return 0;
01054 }
01055 
01056 /*
01057 ** This vector defines all the methods that can operate on an
01058 ** sqlite3_file for win32.
01059 */
01060 static const sqlite3_io_methods winIoMethod = {
01061   1,                        /* iVersion */
01062   winClose,
01063   winRead,
01064   winWrite,
01065   winTruncate,
01066   winSync,
01067   winFileSize,
01068   winLock,
01069   winUnlock,
01070   winCheckReservedLock,
01071   winFileControl,
01072   winSectorSize,
01073   winDeviceCharacteristics
01074 };
01075 
01076 /***************************************************************************
01077 ** Here ends the I/O methods that form the sqlite3_io_methods object.
01078 **
01079 ** The next block of code implements the VFS methods.
01080 ****************************************************************************/
01081 
01082 /*
01083 ** Convert a UTF-8 filename into whatever form the underlying
01084 ** operating system wants filenames in.  Space to hold the result
01085 ** is obtained from malloc and must be freed by the calling
01086 ** function.
01087 */
01088 static void *convertUtf8Filename(const char *zFilename){
01089   void *zConverted = 0;
01090   if( isNT() ){
01091     zConverted = utf8ToUnicode(zFilename);
01092 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
01093 */
01094 #if SQLITE_OS_WINCE==0
01095   }else{
01096     zConverted = utf8ToMbcs(zFilename);
01097 #endif
01098   }
01099   /* caller will handle out of memory */
01100   return zConverted;
01101 }
01102 
01103 /*
01104 ** Create a temporary file name in zBuf.  zBuf must be big enough to
01105 ** hold at pVfs->mxPathname characters.
01106 */
01107 static int getTempname(int nBuf, char *zBuf){
01108   static char zChars[] =
01109     "abcdefghijklmnopqrstuvwxyz"
01110     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
01111     "0123456789";
01112   size_t i, j;
01113   char zTempPath[MAX_PATH+1];
01114   if( sqlite3_temp_directory ){
01115     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
01116   }else if( isNT() ){
01117     char *zMulti;
01118     WCHAR zWidePath[MAX_PATH];
01119     GetTempPathW(MAX_PATH-30, zWidePath);
01120     zMulti = unicodeToUtf8(zWidePath);
01121     if( zMulti ){
01122       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
01123       free(zMulti);
01124     }else{
01125       return SQLITE_NOMEM;
01126     }
01127 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
01128 ** Since the ASCII version of these Windows API do not exist for WINCE,
01129 ** it's important to not reference them for WINCE builds.
01130 */
01131 #if SQLITE_OS_WINCE==0
01132   }else{
01133     char *zUtf8;
01134     char zMbcsPath[MAX_PATH];
01135     GetTempPathA(MAX_PATH-30, zMbcsPath);
01136     zUtf8 = mbcsToUtf8(zMbcsPath);
01137     if( zUtf8 ){
01138       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
01139       free(zUtf8);
01140     }else{
01141       return SQLITE_NOMEM;
01142     }
01143 #endif
01144   }
01145   for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
01146   zTempPath[i] = 0;
01147   sqlite3_snprintf(nBuf-30, zBuf,
01148                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
01149   j = strlen(zBuf);
01150   sqlite3_randomness(20, &zBuf[j]);
01151   for(i=0; i<20; i++, j++){
01152     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
01153   }
01154   zBuf[j] = 0;
01155   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
01156   return SQLITE_OK; 
01157 }
01158 
01159 /*
01160 ** The return value of getLastErrorMsg
01161 ** is zero if the error message fits in the buffer, or non-zero
01162 ** otherwise (if the message was truncated).
01163 */
01164 static int getLastErrorMsg(int nBuf, char *zBuf){
01165   DWORD error = GetLastError();
01166 
01167 #if SQLITE_OS_WINCE
01168   sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
01169 #else
01170   /* FormatMessage returns 0 on failure.  Otherwise it
01171   ** returns the number of TCHARs written to the output
01172   ** buffer, excluding the terminating null char.
01173   */
01174   if (!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
01175                       NULL,
01176                       error,
01177                       0,
01178                       zBuf,
01179                       nBuf-1,
01180                       0))
01181   {
01182     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
01183   }
01184 #endif
01185 
01186   return 0;
01187 }
01188 
01189 
01190 /*
01191 ** Open a file.
01192 */
01193 static int winOpen(
01194   sqlite3_vfs *pVfs,        /* Not used */
01195   const char *zName,        /* Name of the file (UTF-8) */
01196   sqlite3_file *id,         /* Write the SQLite file handle here */
01197   int flags,                /* Open mode flags */
01198   int *pOutFlags            /* Status return flags */
01199 ){
01200   HANDLE h;
01201   DWORD dwDesiredAccess;
01202   DWORD dwShareMode;
01203   DWORD dwCreationDisposition;
01204   DWORD dwFlagsAndAttributes = 0;
01205 #if SQLITE_OS_WINCE
01206   int isTemp = 0;
01207 #endif
01208   winFile *pFile = (winFile*)id;
01209   void *zConverted;                 /* Filename in OS encoding */
01210   const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
01211   char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
01212 
01213   /* If the second argument to this function is NULL, generate a 
01214   ** temporary file name to use 
01215   */
01216   if( !zUtf8Name ){
01217     int rc = getTempname(MAX_PATH+1, zTmpname);
01218     if( rc!=SQLITE_OK ){
01219       return rc;
01220     }
01221     zUtf8Name = zTmpname;
01222   }
01223 
01224   /* Convert the filename to the system encoding. */
01225   zConverted = convertUtf8Filename(zUtf8Name);
01226   if( zConverted==0 ){
01227     return SQLITE_NOMEM;
01228   }
01229 
01230   if( flags & SQLITE_OPEN_READWRITE ){
01231     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
01232   }else{
01233     dwDesiredAccess = GENERIC_READ;
01234   }
01235   if( flags & SQLITE_OPEN_CREATE ){
01236     dwCreationDisposition = OPEN_ALWAYS;
01237   }else{
01238     dwCreationDisposition = OPEN_EXISTING;
01239   }
01240   if( flags & SQLITE_OPEN_MAIN_DB ){
01241     dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
01242   }else{
01243     dwShareMode = 0;
01244   }
01245   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
01246 #if SQLITE_OS_WINCE
01247     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
01248     isTemp = 1;
01249 #else
01250     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
01251                                | FILE_ATTRIBUTE_HIDDEN
01252                                | FILE_FLAG_DELETE_ON_CLOSE;
01253 #endif
01254   }else{
01255     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
01256   }
01257   /* Reports from the internet are that performance is always
01258   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
01259 #if SQLITE_OS_WINCE
01260   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
01261 #endif
01262   if( isNT() ){
01263     h = CreateFileW((WCHAR*)zConverted,
01264        dwDesiredAccess,
01265        dwShareMode,
01266        NULL,
01267        dwCreationDisposition,
01268        dwFlagsAndAttributes,
01269        NULL
01270     );
01271 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
01272 ** Since the ASCII version of these Windows API do not exist for WINCE,
01273 ** it's important to not reference them for WINCE builds.
01274 */
01275 #if SQLITE_OS_WINCE==0
01276   }else{
01277     h = CreateFileA((char*)zConverted,
01278        dwDesiredAccess,
01279        dwShareMode,
01280        NULL,
01281        dwCreationDisposition,
01282        dwFlagsAndAttributes,
01283        NULL
01284     );
01285 #endif
01286   }
01287   if( h==INVALID_HANDLE_VALUE ){
01288     free(zConverted);
01289     if( flags & SQLITE_OPEN_READWRITE ){
01290       return winOpen(0, zName, id, 
01291              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
01292     }else{
01293       return SQLITE_CANTOPEN;
01294     }
01295   }
01296   if( pOutFlags ){
01297     if( flags & SQLITE_OPEN_READWRITE ){
01298       *pOutFlags = SQLITE_OPEN_READWRITE;
01299     }else{
01300       *pOutFlags = SQLITE_OPEN_READONLY;
01301     }
01302   }
01303   memset(pFile, 0, sizeof(*pFile));
01304   pFile->pMethod = &winIoMethod;
01305   pFile->h = h;
01306 #if SQLITE_OS_WINCE
01307   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
01308                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
01309        && !winceCreateLock(zName, pFile)
01310   ){
01311     CloseHandle(h);
01312     free(zConverted);
01313     return SQLITE_CANTOPEN;
01314   }
01315   if( isTemp ){
01316     pFile->zDeleteOnClose = zConverted;
01317   }else
01318 #endif
01319   {
01320     free(zConverted);
01321   }
01322   OpenCounter(+1);
01323   return SQLITE_OK;
01324 }
01325 
01326 /*
01327 ** Delete the named file.
01328 **
01329 ** Note that windows does not allow a file to be deleted if some other
01330 ** process has it open.  Sometimes a virus scanner or indexing program
01331 ** will open a journal file shortly after it is created in order to do
01332 ** whatever it does.  While this other process is holding the
01333 ** file open, we will be unable to delete it.  To work around this
01334 ** problem, we delay 100 milliseconds and try to delete again.  Up
01335 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
01336 ** up and returning an error.
01337 */
01338 #define MX_DELETION_ATTEMPTS 5
01339 static int winDelete(
01340   sqlite3_vfs *pVfs,          /* Not used on win32 */
01341   const char *zFilename,      /* Name of file to delete */
01342   int syncDir                 /* Not used on win32 */
01343 ){
01344   int cnt = 0;
01345   DWORD rc;
01346   DWORD error;
01347   void *zConverted = convertUtf8Filename(zFilename);
01348   if( zConverted==0 ){
01349     return SQLITE_NOMEM;
01350   }
01351   SimulateIOError(return SQLITE_IOERR_DELETE);
01352   if( isNT() ){
01353     do{
01354       DeleteFileW(zConverted);
01355     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
01356                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
01357            && (++cnt < MX_DELETION_ATTEMPTS)
01358            && (Sleep(100), 1) );
01359 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
01360 ** Since the ASCII version of these Windows API do not exist for WINCE,
01361 ** it's important to not reference them for WINCE builds.
01362 */
01363 #if SQLITE_OS_WINCE==0
01364   }else{
01365     do{
01366       DeleteFileA(zConverted);
01367     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
01368                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
01369            && (++cnt < MX_DELETION_ATTEMPTS)
01370            && (Sleep(100), 1) );
01371 #endif
01372   }
01373   free(zConverted);
01374   OSTRACE2("DELETE \"%s\"\n", zFilename);
01375   return (   (rc == INVALID_FILE_ATTRIBUTES) 
01376           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
01377 }
01378 
01379 /*
01380 ** Check the existance and status of a file.
01381 */
01382 static int winAccess(
01383   sqlite3_vfs *pVfs,         /* Not used on win32 */
01384   const char *zFilename,     /* Name of file to check */
01385   int flags,                 /* Type of test to make on this file */
01386   int *pResOut               /* OUT: Result */
01387 ){
01388   DWORD attr;
01389   int rc;
01390   void *zConverted = convertUtf8Filename(zFilename);
01391   if( zConverted==0 ){
01392     return SQLITE_NOMEM;
01393   }
01394   if( isNT() ){
01395     attr = GetFileAttributesW((WCHAR*)zConverted);
01396 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
01397 ** Since the ASCII version of these Windows API do not exist for WINCE,
01398 ** it's important to not reference them for WINCE builds.
01399 */
01400 #if SQLITE_OS_WINCE==0
01401   }else{
01402     attr = GetFileAttributesA((char*)zConverted);
01403 #endif
01404   }
01405   free(zConverted);
01406   switch( flags ){
01407     case SQLITE_ACCESS_READ:
01408     case SQLITE_ACCESS_EXISTS:
01409       rc = attr!=INVALID_FILE_ATTRIBUTES;
01410       break;
01411     case SQLITE_ACCESS_READWRITE:
01412       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
01413       break;
01414     default:
01415       assert(!"Invalid flags argument");
01416   }
01417   *pResOut = rc;
01418   return SQLITE_OK;
01419 }
01420 
01421 
01422 /*
01423 ** Turn a relative pathname into a full pathname.  Write the full
01424 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
01425 ** bytes in size.
01426 */
01427 static int winFullPathname(
01428   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
01429   const char *zRelative,        /* Possibly relative input path */
01430   int nFull,                    /* Size of output buffer in bytes */
01431   char *zFull                   /* Output buffer */
01432 ){
01433 
01434 #if defined(__CYGWIN__)
01435   cygwin_conv_to_full_win32_path(zRelative, zFull);
01436   return SQLITE_OK;
01437 #endif
01438 
01439 #if SQLITE_OS_WINCE
01440   /* WinCE has no concept of a relative pathname, or so I am told. */
01441   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
01442   return SQLITE_OK;
01443 #endif
01444 
01445 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
01446   int nByte;
01447   void *zConverted;
01448   char *zOut;
01449   zConverted = convertUtf8Filename(zRelative);
01450   if( isNT() ){
01451     WCHAR *zTemp;
01452     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
01453     zTemp = malloc( nByte*sizeof(zTemp[0]) );
01454     if( zTemp==0 ){
01455       free(zConverted);
01456       return SQLITE_NOMEM;
01457     }
01458     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
01459     free(zConverted);
01460     zOut = unicodeToUtf8(zTemp);
01461     free(zTemp);
01462 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
01463 ** Since the ASCII version of these Windows API do not exist for WINCE,
01464 ** it's important to not reference them for WINCE builds.
01465 */
01466 #if SQLITE_OS_WINCE==0
01467   }else{
01468     char *zTemp;
01469     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
01470     zTemp = malloc( nByte*sizeof(zTemp[0]) );
01471     if( zTemp==0 ){
01472       free(zConverted);
01473       return SQLITE_NOMEM;
01474     }
01475     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
01476     free(zConverted);
01477     zOut = mbcsToUtf8(zTemp);
01478     free(zTemp);
01479 #endif
01480   }
01481   if( zOut ){
01482     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
01483     free(zOut);
01484     return SQLITE_OK;
01485   }else{
01486     return SQLITE_NOMEM;
01487   }
01488 #endif
01489 }
01490 
01491 #ifndef SQLITE_OMIT_LOAD_EXTENSION
01492 /*
01493 ** Interfaces for opening a shared library, finding entry points
01494 ** within the shared library, and closing the shared library.
01495 */
01496 /*
01497 ** Interfaces for opening a shared library, finding entry points
01498 ** within the shared library, and closing the shared library.
01499 */
01500 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
01501   HANDLE h;
01502   void *zConverted = convertUtf8Filename(zFilename);
01503   if( zConverted==0 ){
01504     return 0;
01505   }
01506   if( isNT() ){
01507     h = LoadLibraryW((WCHAR*)zConverted);
01508 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
01509 ** Since the ASCII version of these Windows API do not exist for WINCE,
01510 ** it's important to not reference them for WINCE builds.
01511 */
01512 #if SQLITE_OS_WINCE==0
01513   }else{
01514     h = LoadLibraryA((char*)zConverted);
01515 #endif
01516   }
01517   free(zConverted);
01518   return (void*)h;
01519 }
01520 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
01521   getLastErrorMsg(nBuf, zBufOut);
01522 }
01523 void *winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
01524 #if SQLITE_OS_WINCE
01525   /* The GetProcAddressA() routine is only available on wince. */
01526   return GetProcAddressA((HANDLE)pHandle, zSymbol);
01527 #else
01528   /* All other windows platforms expect GetProcAddress() to take
01529   ** an Ansi string regardless of the _UNICODE setting */
01530   return GetProcAddress((HANDLE)pHandle, zSymbol);
01531 #endif
01532 }
01533 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
01534   FreeLibrary((HANDLE)pHandle);
01535 }
01536 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
01537   #define winDlOpen  0
01538   #define winDlError 0
01539   #define winDlSym   0
01540   #define winDlClose 0
01541 #endif
01542 
01543 
01544 /*
01545 ** Write up to nBuf bytes of randomness into zBuf.
01546 */
01547 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
01548   int n = 0;
01549   if( sizeof(SYSTEMTIME)<=nBuf-n ){
01550     SYSTEMTIME x;
01551     GetSystemTime(&x);
01552     memcpy(&zBuf[n], &x, sizeof(x));
01553     n += sizeof(x);
01554   }
01555   if( sizeof(DWORD)<=nBuf-n ){
01556     DWORD pid = GetCurrentProcessId();
01557     memcpy(&zBuf[n], &pid, sizeof(pid));
01558     n += sizeof(pid);
01559   }
01560   if( sizeof(DWORD)<=nBuf-n ){
01561     DWORD cnt = GetTickCount();
01562     memcpy(&zBuf[n], &cnt, sizeof(cnt));
01563     n += sizeof(cnt);
01564   }
01565   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
01566     LARGE_INTEGER i;
01567     QueryPerformanceCounter(&i);
01568     memcpy(&zBuf[n], &i, sizeof(i));
01569     n += sizeof(i);
01570   }
01571   return n;
01572 }
01573 
01574 
01575 /*
01576 ** Sleep for a little while.  Return the amount of time slept.
01577 */
01578 static int winSleep(sqlite3_vfs *pVfs, int microsec){
01579   Sleep((microsec+999)/1000);
01580   return ((microsec+999)/1000)*1000;
01581 }
01582 
01583 /*
01584 ** The following variable, if set to a non-zero value, becomes the result
01585 ** returned from sqlite3OsCurrentTime().  This is used for testing.
01586 */
01587 #ifdef SQLITE_TEST
01588 int sqlite3_current_time = 0;
01589 #endif
01590 
01591 /*
01592 ** Find the current time (in Universal Coordinated Time).  Write the
01593 ** current time and date as a Julian Day number into *prNow and
01594 ** return 0.  Return 1 if the time and date cannot be found.
01595 */
01596 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
01597   FILETIME ft;
01598   /* FILETIME structure is a 64-bit value representing the number of 
01599      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
01600   */
01601   double now;
01602 #if SQLITE_OS_WINCE
01603   SYSTEMTIME time;
01604   GetSystemTime(&time);
01605   /* if SystemTimeToFileTime() fails, it returns zero. */
01606   if (!SystemTimeToFileTime(&time,&ft)){
01607     return 1;
01608   }
01609 #else
01610   GetSystemTimeAsFileTime( &ft );
01611 #endif
01612   now = ((double)ft.dwHighDateTime) * 4294967296.0; 
01613   *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
01614 #ifdef SQLITE_TEST
01615   if( sqlite3_current_time ){
01616     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
01617   }
01618 #endif
01619   return 0;
01620 }
01621 
01622 /*
01623 ** The idea is that this function works like a combination of
01624 ** GetLastError() and FormatMessage() on windows (or errno and
01625 ** strerror_r() on unix). After an error is returned by an OS
01626 ** function, SQLite calls this function with zBuf pointing to
01627 ** a buffer of nBuf bytes. The OS layer should populate the
01628 ** buffer with a nul-terminated UTF-8 encoded error message
01629 ** describing the last IO error to have occured within the calling
01630 ** thread.
01631 **
01632 ** If the error message is too large for the supplied buffer,
01633 ** it should be truncated. The return value of xGetLastError
01634 ** is zero if the error message fits in the buffer, or non-zero
01635 ** otherwise (if the message was truncated). If non-zero is returned,
01636 ** then it is not necessary to include the nul-terminator character
01637 ** in the output buffer.
01638 **
01639 ** Not supplying an error message will have no adverse effect
01640 ** on SQLite. It is fine to have an implementation that never
01641 ** returns an error message:
01642 **
01643 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
01644 **     assert(zBuf[0]=='\0');
01645 **     return 0;
01646 **   }
01647 **
01648 ** However if an error message is supplied, it will be incorporated
01649 ** by sqlite into the error message available to the user using
01650 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
01651 */
01652 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
01653   return getLastErrorMsg(nBuf, zBuf);
01654 }
01655 
01656 /*
01657 ** Initialize and deinitialize the operating system interface.
01658 */
01659 int sqlite3_os_init(void){
01660   static sqlite3_vfs winVfs = {
01661     1,                 /* iVersion */
01662     sizeof(winFile),   /* szOsFile */
01663     MAX_PATH,          /* mxPathname */
01664     0,                 /* pNext */
01665     "win32",           /* zName */
01666     0,                 /* pAppData */
01667  
01668     winOpen,           /* xOpen */
01669     winDelete,         /* xDelete */
01670     winAccess,         /* xAccess */
01671     winFullPathname,   /* xFullPathname */
01672     winDlOpen,         /* xDlOpen */
01673     winDlError,        /* xDlError */
01674     winDlSym,          /* xDlSym */
01675     winDlClose,        /* xDlClose */
01676     winRandomness,     /* xRandomness */
01677     winSleep,          /* xSleep */
01678     winCurrentTime,    /* xCurrentTime */
01679     winGetLastError    /* xGetLastError */
01680   };
01681   sqlite3_vfs_register(&winVfs, 1);
01682   return SQLITE_OK; 
01683 }
01684 int sqlite3_os_end(void){ 
01685   return SQLITE_OK;
01686 }
01687 
01688 #endif /* SQLITE_OS_WIN */

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:55 2011 by Doxygen 1.6.1