os_win.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  1. /*
  2. ** 2004 May 22
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. ******************************************************************************
  12. **
  13. ** This file contains code that is specific to windows.
  14. */
  15. #include "sqliteInt.h"
  16. #if OS_WIN /* This file is used for windows only */
  17. /*
  18. ** A Note About Memory Allocation:
  19. **
  20. ** This driver uses malloc()/free() directly rather than going through
  21. ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
  22. ** are designed for use on embedded systems where memory is scarce and
  23. ** malloc failures happen frequently. Win32 does not typically run on
  24. ** embedded systems, and when it does the developers normally have bigger
  25. ** problems to worry about than running out of memory. So there is not
  26. ** a compelling need to use the wrappers.
  27. **
  28. ** But there is a good reason to not use the wrappers. If we use the
  29. ** wrappers then we will get simulated malloc() failures within this
  30. ** driver. And that causes all kinds of problems for our tests. We
  31. ** could enhance SQLite to deal with simulated malloc failures within
  32. ** the OS driver, but the code to deal with those failure would not
  33. ** be exercised on Linux (which does not need to malloc() in the driver)
  34. ** and so we would have difficulty writing coverage tests for that
  35. ** code. Better to leave the code out, we think.
  36. **
  37. ** The point of this discussion is as follows: When creating a new
  38. ** OS layer for an embedded system, if you use this file as an example,
  39. ** avoid the use of malloc()/free(). Those routines work ok on windows
  40. ** desktops but not so well in embedded systems.
  41. */
  42. #include <winbase.h>
  43. #ifdef __CYGWIN__
  44. # include <sys/cygwin.h>
  45. #endif
  46. /*
  47. ** Macros used to determine whether or not to use threads.
  48. */
  49. #if defined(THREADSAFE) && THREADSAFE
  50. # define SQLITE_W32_THREADS 1
  51. #endif
  52. /*
  53. ** Include code that is common to all os_*.c files
  54. */
  55. #include "os_common.h"
  56. /*
  57. ** Determine if we are dealing with WindowsCE - which has a much
  58. ** reduced API.
  59. */
  60. #if defined(_WIN32_WCE)
  61. # define OS_WINCE 1
  62. # define AreFileApisANSI() 1
  63. #else
  64. # define OS_WINCE 0
  65. #endif
  66. /*
  67. ** WinCE lacks native support for file locking so we have to fake it
  68. ** with some code of our own.
  69. */
  70. #if OS_WINCE
  71. typedef struct winceLock {
  72. int nReaders; /* Number of reader locks obtained */
  73. BOOL bPending; /* Indicates a pending lock has been obtained */
  74. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  75. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  76. } winceLock;
  77. #endif
  78. /*
  79. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  80. ** portability layer.
  81. */
  82. typedef struct winFile winFile;
  83. struct winFile {
  84. const sqlite3_io_methods *pMethod;/* Must be first */
  85. HANDLE h; /* Handle for accessing the file */
  86. unsigned char locktype; /* Type of lock currently held on this file */
  87. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  88. #if OS_WINCE
  89. WCHAR *zDeleteOnClose; /* Name of file to delete when closing */
  90. HANDLE hMutex; /* Mutex used to control access to shared lock */
  91. HANDLE hShared; /* Shared memory segment used for locking */
  92. winceLock local; /* Locks obtained by this instance of winFile */
  93. winceLock *shared; /* Global shared lock memory for the file */
  94. #endif
  95. };
  96. /*
  97. ** The following variable is (normally) set once and never changes
  98. ** thereafter. It records whether the operating system is Win95
  99. ** or WinNT.
  100. **
  101. ** 0: Operating system unknown.
  102. ** 1: Operating system is Win95.
  103. ** 2: Operating system is WinNT.
  104. **
  105. ** In order to facilitate testing on a WinNT system, the test fixture
  106. ** can manually set this value to 1 to emulate Win98 behavior.
  107. */
  108. #ifdef SQLITE_TEST
  109. int sqlite3_os_type = 0;
  110. #else
  111. static int sqlite3_os_type = 0;
  112. #endif
  113. /*
  114. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  115. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  116. **
  117. ** Here is an interesting observation: Win95, Win98, and WinME lack
  118. ** the LockFileEx() API. But we can still statically link against that
  119. ** API as long as we don't call it win running Win95/98/ME. A call to
  120. ** this routine is used to determine if the host is Win95/98/ME or
  121. ** WinNT/2K/XP so that we will know whether or not we can safely call
  122. ** the LockFileEx() API.
  123. */
  124. #if OS_WINCE
  125. # define isNT() (1)
  126. #else
  127. static int isNT(void){
  128. if( sqlite3_os_type==0 ){
  129. OSVERSIONINFO sInfo;
  130. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  131. GetVersionEx(&sInfo);
  132. sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  133. }
  134. return sqlite3_os_type==2;
  135. }
  136. #endif /* OS_WINCE */
  137. /*
  138. ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
  139. **
  140. ** Space to hold the returned string is obtained from malloc.
  141. */
  142. static WCHAR *utf8ToUnicode(const char *zFilename){
  143. int nChar;
  144. WCHAR *zWideFilename;
  145. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  146. zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
  147. if( zWideFilename==0 ){
  148. return 0;
  149. }
  150. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
  151. if( nChar==0 ){
  152. free(zWideFilename);
  153. zWideFilename = 0;
  154. }
  155. return zWideFilename;
  156. }
  157. /*
  158. ** Convert microsoft unicode to UTF-8. Space to hold the returned string is
  159. ** obtained from malloc().
  160. */
  161. static char *unicodeToUtf8(const WCHAR *zWideFilename){
  162. int nByte;
  163. char *zFilename;
  164. nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  165. zFilename = malloc( nByte );
  166. if( zFilename==0 ){
  167. return 0;
  168. }
  169. nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  170. 0, 0);
  171. if( nByte == 0 ){
  172. free(zFilename);
  173. zFilename = 0;
  174. }
  175. return zFilename;
  176. }
  177. /*
  178. ** Convert an ansi string to microsoft unicode, based on the
  179. ** current codepage settings for file apis.
  180. **
  181. ** Space to hold the returned string is obtained
  182. ** from malloc.
  183. */
  184. static WCHAR *mbcsToUnicode(const char *zFilename){
  185. int nByte;
  186. WCHAR *zMbcsFilename;
  187. int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
  188. nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
  189. zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
  190. if( zMbcsFilename==0 ){
  191. return 0;
  192. }
  193. nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
  194. if( nByte==0 ){
  195. free(zMbcsFilename);
  196. zMbcsFilename = 0;
  197. }
  198. return zMbcsFilename;
  199. }
  200. /*
  201. ** Convert microsoft unicode to multibyte character string, based on the
  202. ** user's Ansi codepage.
  203. **
  204. ** Space to hold the returned string is obtained from
  205. ** malloc().
  206. */
  207. static char *unicodeToMbcs(const WCHAR *zWideFilename){
  208. int nByte;
  209. char *zFilename;
  210. int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
  211. nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  212. zFilename = malloc( nByte );
  213. if( zFilename==0 ){
  214. return 0;
  215. }
  216. nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
  217. 0, 0);
  218. if( nByte == 0 ){
  219. free(zFilename);
  220. zFilename = 0;
  221. }
  222. return zFilename;
  223. }
  224. /*
  225. ** Convert multibyte character string to UTF-8. Space to hold the
  226. ** returned string is obtained from malloc().
  227. */
  228. static char *mbcsToUtf8(const char *zFilename){
  229. char *zFilenameUtf8;
  230. WCHAR *zTmpWide;
  231. zTmpWide = mbcsToUnicode(zFilename);
  232. if( zTmpWide==0 ){
  233. return 0;
  234. }
  235. zFilenameUtf8 = unicodeToUtf8(zTmpWide);
  236. free(zTmpWide);
  237. return zFilenameUtf8;
  238. }
  239. /*
  240. ** Convert UTF-8 to multibyte character string. Space to hold the
  241. ** returned string is obtained from malloc().
  242. */
  243. static char *utf8ToMbcs(const char *zFilename){
  244. char *zFilenameMbcs;
  245. WCHAR *zTmpWide;
  246. zTmpWide = utf8ToUnicode(zFilename);
  247. if( zTmpWide==0 ){
  248. return 0;
  249. }
  250. zFilenameMbcs = unicodeToMbcs(zTmpWide);
  251. free(zTmpWide);
  252. return zFilenameMbcs;
  253. }
  254. #if OS_WINCE
  255. /*************************************************************************
  256. ** This section contains code for WinCE only.
  257. */
  258. /*
  259. ** WindowsCE does not have a localtime() function. So create a
  260. ** substitute.
  261. */
  262. #include <time.h>
  263. struct tm *__cdecl localtime(const time_t *t)
  264. {
  265. static struct tm y;
  266. FILETIME uTm, lTm;
  267. SYSTEMTIME pTm;
  268. sqlite3_int64 t64;
  269. t64 = *t;
  270. t64 = (t64 + 11644473600)*10000000;
  271. uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
  272. uTm.dwHighDateTime= t64 >> 32;
  273. FileTimeToLocalFileTime(&uTm,&lTm);
  274. FileTimeToSystemTime(&lTm,&pTm);
  275. y.tm_year = pTm.wYear - 1900;
  276. y.tm_mon = pTm.wMonth - 1;
  277. y.tm_wday = pTm.wDayOfWeek;
  278. y.tm_mday = pTm.wDay;
  279. y.tm_hour = pTm.wHour;
  280. y.tm_min = pTm.wMinute;
  281. y.tm_sec = pTm.wSecond;
  282. return &y;
  283. }
  284. /* This will never be called, but defined to make the code compile */
  285. #define GetTempPathA(a,b)
  286. #define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e)
  287. #define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e)
  288. #define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f)
  289. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
  290. /*
  291. ** Acquire a lock on the handle h
  292. */
  293. static void winceMutexAcquire(HANDLE h){
  294. DWORD dwErr;
  295. do {
  296. dwErr = WaitForSingleObject(h, INFINITE);
  297. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  298. }
  299. /*
  300. ** Release a lock acquired by winceMutexAcquire()
  301. */
  302. #define winceMutexRelease(h) ReleaseMutex(h)
  303. /*
  304. ** Create the mutex and shared memory used for locking in the file
  305. ** descriptor pFile
  306. */
  307. static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
  308. WCHAR *zTok;
  309. WCHAR *zName = utf8ToUnicode(zFilename);
  310. BOOL bInit = TRUE;
  311. /* Initialize the local lockdata */
  312. ZeroMemory(&pFile->local, sizeof(pFile->local));
  313. /* Replace the backslashes from the filename and lowercase it
  314. ** to derive a mutex name. */
  315. zTok = CharLowerW(zName);
  316. for (;*zTok;zTok++){
  317. if (*zTok == '\\') *zTok = '_';
  318. }
  319. /* Create/open the named mutex */
  320. pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
  321. if (!pFile->hMutex){
  322. free(zName);
  323. return FALSE;
  324. }
  325. /* Acquire the mutex before continuing */
  326. winceMutexAcquire(pFile->hMutex);
  327. /* Since the names of named mutexes, semaphores, file mappings etc are
  328. ** case-sensitive, take advantage of that by uppercasing the mutex name
  329. ** and using that as the shared filemapping name.
  330. */
  331. CharUpperW(zName);
  332. pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  333. PAGE_READWRITE, 0, sizeof(winceLock),
  334. zName);
  335. /* Set a flag that indicates we're the first to create the memory so it
  336. ** must be zero-initialized */
  337. if (GetLastError() == ERROR_ALREADY_EXISTS){
  338. bInit = FALSE;
  339. }
  340. free(zName);
  341. /* If we succeeded in making the shared memory handle, map it. */
  342. if (pFile->hShared){
  343. pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
  344. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  345. /* If mapping failed, close the shared memory handle and erase it */
  346. if (!pFile->shared){
  347. CloseHandle(pFile->hShared);
  348. pFile->hShared = NULL;
  349. }
  350. }
  351. /* If shared memory could not be created, then close the mutex and fail */
  352. if (pFile->hShared == NULL){
  353. winceMutexRelease(pFile->hMutex);
  354. CloseHandle(pFile->hMutex);
  355. pFile->hMutex = NULL;
  356. return FALSE;
  357. }
  358. /* Initialize the shared memory if we're supposed to */
  359. if (bInit) {
  360. ZeroMemory(pFile->shared, sizeof(winceLock));
  361. }
  362. winceMutexRelease(pFile->hMutex);
  363. return TRUE;
  364. }
  365. /*
  366. ** Destroy the part of winFile that deals with wince locks
  367. */
  368. static void winceDestroyLock(winFile *pFile){
  369. if (pFile->hMutex){
  370. /* Acquire the mutex */
  371. winceMutexAcquire(pFile->hMutex);
  372. /* The following blocks should probably assert in debug mode, but they
  373. are to cleanup in case any locks remained open */
  374. if (pFile->local.nReaders){
  375. pFile->shared->nReaders --;
  376. }
  377. if (pFile->local.bReserved){
  378. pFile->shared->bReserved = FALSE;
  379. }
  380. if (pFile->local.bPending){
  381. pFile->shared->bPending = FALSE;
  382. }
  383. if (pFile->local.bExclusive){
  384. pFile->shared->bExclusive = FALSE;
  385. }
  386. /* De-reference and close our copy of the shared memory handle */
  387. UnmapViewOfFile(pFile->shared);
  388. CloseHandle(pFile->hShared);
  389. /* Done with the mutex */
  390. winceMutexRelease(pFile->hMutex);
  391. CloseHandle(pFile->hMutex);
  392. pFile->hMutex = NULL;
  393. }
  394. }
  395. /*
  396. ** An implementation of the LockFile() API of windows for wince
  397. */
  398. static BOOL winceLockFile(
  399. HANDLE *phFile,
  400. DWORD dwFileOffsetLow,
  401. DWORD dwFileOffsetHigh,
  402. DWORD nNumberOfBytesToLockLow,
  403. DWORD nNumberOfBytesToLockHigh
  404. ){
  405. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  406. BOOL bReturn = FALSE;
  407. if (!pFile->hMutex) return TRUE;
  408. winceMutexAcquire(pFile->hMutex);
  409. /* Wanting an exclusive lock? */
  410. if (dwFileOffsetLow == SHARED_FIRST
  411. && nNumberOfBytesToLockLow == SHARED_SIZE){
  412. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  413. pFile->shared->bExclusive = TRUE;
  414. pFile->local.bExclusive = TRUE;
  415. bReturn = TRUE;
  416. }
  417. }
  418. /* Want a read-only lock? */
  419. else if ((dwFileOffsetLow >= SHARED_FIRST &&
  420. dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
  421. nNumberOfBytesToLockLow == 1){
  422. if (pFile->shared->bExclusive == 0){
  423. pFile->local.nReaders ++;
  424. if (pFile->local.nReaders == 1){
  425. pFile->shared->nReaders ++;
  426. }
  427. bReturn = TRUE;
  428. }
  429. }
  430. /* Want a pending lock? */
  431. else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
  432. /* If no pending lock has been acquired, then acquire it */
  433. if (pFile->shared->bPending == 0) {
  434. pFile->shared->bPending = TRUE;
  435. pFile->local.bPending = TRUE;
  436. bReturn = TRUE;
  437. }
  438. }
  439. /* Want a reserved lock? */
  440. else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
  441. if (pFile->shared->bReserved == 0) {
  442. pFile->shared->bReserved = TRUE;
  443. pFile->local.bReserved = TRUE;
  444. bReturn = TRUE;
  445. }
  446. }
  447. winceMutexRelease(pFile->hMutex);
  448. return bReturn;
  449. }
  450. /*
  451. ** An implementation of the UnlockFile API of windows for wince
  452. */
  453. static BOOL winceUnlockFile(
  454. HANDLE *phFile,
  455. DWORD dwFileOffsetLow,
  456. DWORD dwFileOffsetHigh,
  457. DWORD nNumberOfBytesToUnlockLow,
  458. DWORD nNumberOfBytesToUnlockHigh
  459. ){
  460. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  461. BOOL bReturn = FALSE;
  462. if (!pFile->hMutex) return TRUE;
  463. winceMutexAcquire(pFile->hMutex);
  464. /* Releasing a reader lock or an exclusive lock */
  465. if (dwFileOffsetLow >= SHARED_FIRST &&
  466. dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
  467. /* Did we have an exclusive lock? */
  468. if (pFile->local.bExclusive){
  469. pFile->local.bExclusive = FALSE;
  470. pFile->shared->bExclusive = FALSE;
  471. bReturn = TRUE;
  472. }
  473. /* Did we just have a reader lock? */
  474. else if (pFile->local.nReaders){
  475. pFile->local.nReaders --;
  476. if (pFile->local.nReaders == 0)
  477. {
  478. pFile->shared->nReaders --;
  479. }
  480. bReturn = TRUE;
  481. }
  482. }
  483. /* Releasing a pending lock */
  484. else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
  485. if (pFile->local.bPending){
  486. pFile->local.bPending = FALSE;
  487. pFile->shared->bPending = FALSE;
  488. bReturn = TRUE;
  489. }
  490. }
  491. /* Releasing a reserved lock */
  492. else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
  493. if (pFile->local.bReserved) {
  494. pFile->local.bReserved = FALSE;
  495. pFile->shared->bReserved = FALSE;
  496. bReturn = TRUE;
  497. }
  498. }
  499. winceMutexRelease(pFile->hMutex);
  500. return bReturn;
  501. }
  502. /*
  503. ** An implementation of the LockFileEx() API of windows for wince
  504. */
  505. static BOOL winceLockFileEx(
  506. HANDLE *phFile,
  507. DWORD dwFlags,
  508. DWORD dwReserved,
  509. DWORD nNumberOfBytesToLockLow,
  510. DWORD nNumberOfBytesToLockHigh,
  511. LPOVERLAPPED lpOverlapped
  512. ){
  513. /* If the caller wants a shared read lock, forward this call
  514. ** to winceLockFile */
  515. if (lpOverlapped->Offset == SHARED_FIRST &&
  516. dwFlags == 1 &&
  517. nNumberOfBytesToLockLow == SHARED_SIZE){
  518. return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
  519. }
  520. return FALSE;
  521. }
  522. /*
  523. ** End of the special code for wince
  524. *****************************************************************************/
  525. #endif /* OS_WINCE */
  526. /*****************************************************************************
  527. ** The next group of routines implement the I/O methods specified
  528. ** by the sqlite3_io_methods object.
  529. ******************************************************************************/
  530. /*
  531. ** Close a file.
  532. **
  533. ** It is reported that an attempt to close a handle might sometimes
  534. ** fail. This is a very unreasonable result, but windows is notorious
  535. ** for being unreasonable so I do not doubt that it might happen. If
  536. ** the close fails, we pause for 100 milliseconds and try again. As
  537. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  538. ** giving up and returning an error.
  539. */
  540. #define MX_CLOSE_ATTEMPT 3
  541. static int winClose(sqlite3_file *id){
  542. int rc, cnt = 0;
  543. winFile *pFile = (winFile*)id;
  544. OSTRACE2("CLOSE %d\n", pFile->h);
  545. do{
  546. rc = CloseHandle(pFile->h);
  547. }while( rc==0 && cnt++ < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
  548. #if OS_WINCE
  549. winceDestroyLock(pFile);
  550. if( pFile->zDeleteOnClose ){
  551. DeleteFileW(pFile->zDeleteOnClose);
  552. free(pFile->zDeleteOnClose);
  553. }
  554. #endif
  555. OpenCounter(-1);
  556. return rc ? SQLITE_OK : SQLITE_IOERR;
  557. }
  558. /*
  559. ** Some microsoft compilers lack this definition.
  560. */
  561. #ifndef INVALID_SET_FILE_POINTER
  562. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  563. #endif
  564. /*
  565. ** Read data from a file into a buffer. Return SQLITE_OK if all
  566. ** bytes were read successfully and SQLITE_IOERR if anything goes
  567. ** wrong.
  568. */
  569. static int winRead(
  570. sqlite3_file *id, /* File to read from */
  571. void *pBuf, /* Write content into this buffer */
  572. int amt, /* Number of bytes to read */
  573. sqlite3_int64 offset /* Begin reading at this offset */
  574. ){
  575. LONG upperBits = (offset>>32) & 0x7fffffff;
  576. LONG lowerBits = offset & 0xffffffff;
  577. DWORD rc;
  578. DWORD got;
  579. winFile *pFile = (winFile*)id;
  580. assert( id!=0 );
  581. SimulateIOError(return SQLITE_IOERR_READ);
  582. OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
  583. rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  584. if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
  585. return SQLITE_FULL;
  586. }
  587. if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
  588. return SQLITE_IOERR_READ;
  589. }
  590. if( got==(DWORD)amt ){
  591. return SQLITE_OK;
  592. }else{
  593. memset(&((char*)pBuf)[got], 0, amt-got);
  594. return SQLITE_IOERR_SHORT_READ;
  595. }
  596. }
  597. /*
  598. ** Write data from a buffer into a file. Return SQLITE_OK on success
  599. ** or some other error code on failure.
  600. */
  601. static int winWrite(
  602. sqlite3_file *id, /* File to write into */
  603. const void *pBuf, /* The bytes to be written */
  604. int amt, /* Number of bytes to write */
  605. sqlite3_int64 offset /* Offset into the file to begin writing at */
  606. ){
  607. LONG upperBits = (offset>>32) & 0x7fffffff;
  608. LONG lowerBits = offset & 0xffffffff;
  609. DWORD rc;
  610. DWORD wrote;
  611. winFile *pFile = (winFile*)id;
  612. assert( id!=0 );
  613. SimulateIOError(return SQLITE_IOERR_WRITE);
  614. SimulateDiskfullError(return SQLITE_FULL);
  615. OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
  616. rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  617. if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
  618. return SQLITE_FULL;
  619. }
  620. assert( amt>0 );
  621. while(
  622. amt>0
  623. && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
  624. && wrote>0
  625. ){
  626. amt -= wrote;
  627. pBuf = &((char*)pBuf)[wrote];
  628. }
  629. if( !rc || amt>(int)wrote ){
  630. return SQLITE_FULL;
  631. }
  632. return SQLITE_OK;
  633. }
  634. /*
  635. ** Truncate an open file to a specified size
  636. */
  637. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  638. LONG upperBits = (nByte>>32) & 0x7fffffff;
  639. LONG lowerBits = nByte & 0xffffffff;
  640. winFile *pFile = (winFile*)id;
  641. OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
  642. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  643. SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  644. SetEndOfFile(pFile->h);
  645. return SQLITE_OK;
  646. }
  647. #ifdef SQLITE_TEST
  648. /*
  649. ** Count the number of fullsyncs and normal syncs. This is used to test
  650. ** that syncs and fullsyncs are occuring at the right times.
  651. */
  652. int sqlite3_sync_count = 0;
  653. int sqlite3_fullsync_count = 0;
  654. #endif
  655. /*
  656. ** Make sure all writes to a particular file are committed to disk.
  657. */
  658. static int winSync(sqlite3_file *id, int flags){
  659. winFile *pFile = (winFile*)id;
  660. OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
  661. #ifdef SQLITE_TEST
  662. if( flags & SQLITE_SYNC_FULL ){
  663. sqlite3_fullsync_count++;
  664. }
  665. sqlite3_sync_count++;
  666. #endif
  667. if( FlushFileBuffers(pFile->h) ){
  668. return SQLITE_OK;
  669. }else{
  670. return SQLITE_IOERR;
  671. }
  672. }
  673. /*
  674. ** Determine the current size of a file in bytes
  675. */
  676. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  677. winFile *pFile = (winFile*)id;
  678. DWORD upperBits, lowerBits;
  679. SimulateIOError(return SQLITE_IOERR_FSTAT);
  680. lowerBits = GetFileSize(pFile->h, &upperBits);
  681. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  682. return SQLITE_OK;
  683. }
  684. /*
  685. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  686. */
  687. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  688. # define LOCKFILE_FAIL_IMMEDIATELY 1
  689. #endif
  690. /*
  691. ** Acquire a reader lock.
  692. ** Different API routines are called depending on whether or not this
  693. ** is Win95 or WinNT.
  694. */
  695. static int getReadLock(winFile *pFile){
  696. int res;
  697. if( isNT() ){
  698. OVERLAPPED ovlp;
  699. ovlp.Offset = SHARED_FIRST;
  700. ovlp.OffsetHigh = 0;
  701. ovlp.hEvent = 0;
  702. res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
  703. 0, SHARED_SIZE, 0, &ovlp);
  704. }else{
  705. int lk;
  706. sqlite3Randomness(sizeof(lk), &lk);
  707. pFile->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
  708. res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  709. }
  710. return res;
  711. }
  712. /*
  713. ** Undo a readlock
  714. */
  715. static int unlockReadLock(winFile *pFile){
  716. int res;
  717. if( isNT() ){
  718. res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  719. }else{
  720. res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
  721. }
  722. return res;
  723. }
  724. /*
  725. ** Lock the file with the lock specified by parameter locktype - one
  726. ** of the following:
  727. **
  728. ** (1) SHARED_LOCK
  729. ** (2) RESERVED_LOCK
  730. ** (3) PENDING_LOCK
  731. ** (4) EXCLUSIVE_LOCK
  732. **
  733. ** Sometimes when requesting one lock state, additional lock states
  734. ** are inserted in between. The locking might fail on one of the later
  735. ** transitions leaving the lock state different from what it started but
  736. ** still short of its goal. The following chart shows the allowed
  737. ** transitions and the inserted intermediate states:
  738. **
  739. ** UNLOCKED -> SHARED
  740. ** SHARED -> RESERVED
  741. ** SHARED -> (PENDING) -> EXCLUSIVE
  742. ** RESERVED -> (PENDING) -> EXCLUSIVE
  743. ** PENDING -> EXCLUSIVE
  744. **
  745. ** This routine will only increase a lock. The winUnlock() routine
  746. ** erases all locks at once and returns us immediately to locking level 0.
  747. ** It is not possible to lower the locking level one step at a time. You
  748. ** must go straight to locking level 0.
  749. */
  750. static int winLock(sqlite3_file *id, int locktype){
  751. int rc = SQLITE_OK; /* Return code from subroutines */
  752. int res = 1; /* Result of a windows lock call */
  753. int newLocktype; /* Set pFile->locktype to this value before exiting */
  754. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  755. winFile *pFile = (winFile*)id;
  756. assert( pFile!=0 );
  757. OSTRACE5("LOCK %d %d was %d(%d)\n",
  758. pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
  759. /* If there is already a lock of this type or more restrictive on the
  760. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  761. ** sqlite3OsEnterMutex() hasn't been called yet.
  762. */
  763. if( pFile->locktype>=locktype ){
  764. return SQLITE_OK;
  765. }
  766. /* Make sure the locking sequence is correct
  767. */
  768. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  769. assert( locktype!=PENDING_LOCK );
  770. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  771. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  772. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  773. ** the PENDING_LOCK byte is temporary.
  774. */
  775. newLocktype = pFile->locktype;
  776. if( pFile->locktype==NO_LOCK
  777. || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
  778. ){
  779. int cnt = 3;
  780. while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
  781. /* Try 3 times to get the pending lock. The pending lock might be
  782. ** held by another reader process who will release it momentarily.
  783. */
  784. OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
  785. Sleep(1);
  786. }
  787. gotPendingLock = res;
  788. }
  789. /* Acquire a shared lock
  790. */
  791. if( locktype==SHARED_LOCK && res ){
  792. assert( pFile->locktype==NO_LOCK );
  793. res = getReadLock(pFile);
  794. if( res ){
  795. newLocktype = SHARED_LOCK;
  796. }
  797. }
  798. /* Acquire a RESERVED lock
  799. */
  800. if( locktype==RESERVED_LOCK && res ){
  801. assert( pFile->locktype==SHARED_LOCK );
  802. res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  803. if( res ){
  804. newLocktype = RESERVED_LOCK;
  805. }
  806. }
  807. /* Acquire a PENDING lock
  808. */
  809. if( locktype==EXCLUSIVE_LOCK && res ){
  810. newLocktype = PENDING_LOCK;
  811. gotPendingLock = 0;
  812. }
  813. /* Acquire an EXCLUSIVE lock
  814. */
  815. if( locktype==EXCLUSIVE_LOCK && res ){
  816. assert( pFile->locktype>=SHARED_LOCK );
  817. res = unlockReadLock(pFile);
  818. OSTRACE2("unreadlock = %d\n", res);
  819. res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  820. if( res ){
  821. newLocktype = EXCLUSIVE_LOCK;
  822. }else{
  823. OSTRACE2("error-code = %d\n", GetLastError());
  824. getReadLock(pFile);
  825. }
  826. }
  827. /* If we are holding a PENDING lock that ought to be released, then
  828. ** release it now.
  829. */
  830. if( gotPendingLock && locktype==SHARED_LOCK ){
  831. UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  832. }
  833. /* Update the state of the lock has held in the file descriptor then
  834. ** return the appropriate result code.
  835. */
  836. if( res ){
  837. rc = SQLITE_OK;
  838. }else{
  839. OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
  840. locktype, newLocktype);
  841. rc = SQLITE_BUSY;
  842. }
  843. pFile->locktype = newLocktype;
  844. return rc;
  845. }
  846. /*
  847. ** This routine checks if there is a RESERVED lock held on the specified
  848. ** file by this or any other process. If such a lock is held, return
  849. ** non-zero, otherwise zero.
  850. */
  851. static int winCheckReservedLock(sqlite3_file *id){
  852. int rc;
  853. winFile *pFile = (winFile*)id;
  854. assert( pFile!=0 );
  855. if( pFile->locktype>=RESERVED_LOCK ){
  856. rc = 1;
  857. OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
  858. }else{
  859. rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  860. if( rc ){
  861. UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  862. }
  863. rc = !rc;
  864. OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
  865. }
  866. return rc;
  867. }
  868. /*
  869. ** Lower the locking level on file descriptor id to locktype. locktype
  870. ** must be either NO_LOCK or SHARED_LOCK.
  871. **
  872. ** If the locking level of the file descriptor is already at or below
  873. ** the requested locking level, this routine is a no-op.
  874. **
  875. ** It is not possible for this routine to fail if the second argument
  876. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  877. ** might return SQLITE_IOERR;
  878. */
  879. static int winUnlock(sqlite3_file *id, int locktype){
  880. int type;
  881. winFile *pFile = (winFile*)id;
  882. int rc = SQLITE_OK;
  883. assert( pFile!=0 );
  884. assert( locktype<=SHARED_LOCK );
  885. OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
  886. pFile->locktype, pFile->sharedLockByte);
  887. type = pFile->locktype;
  888. if( type>=EXCLUSIVE_LOCK ){
  889. UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  890. if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
  891. /* This should never happen. We should always be able to
  892. ** reacquire the read lock */
  893. rc = SQLITE_IOERR_UNLOCK;
  894. }
  895. }
  896. if( type>=RESERVED_LOCK ){
  897. UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  898. }
  899. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  900. unlockReadLock(pFile);
  901. }
  902. if( type>=PENDING_LOCK ){
  903. UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  904. }
  905. pFile->locktype = locktype;
  906. return rc;
  907. }
  908. /*
  909. ** Control and query of the open file handle.
  910. */
  911. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  912. switch( op ){
  913. case SQLITE_FCNTL_LOCKSTATE: {
  914. *(int*)pArg = ((winFile*)id)->locktype;
  915. return SQLITE_OK;
  916. }
  917. }
  918. return SQLITE_ERROR;
  919. }
  920. /*
  921. ** Return the sector size in bytes of the underlying block device for
  922. ** the specified file. This is almost always 512 bytes, but may be
  923. ** larger for some devices.
  924. **
  925. ** SQLite code assumes this function cannot fail. It also assumes that
  926. ** if two files are created in the same file-system directory (i.e.
  927. ** a database and its journal file) that the sector size will be the
  928. ** same for both.
  929. */
  930. static int winSectorSize(sqlite3_file *id){
  931. return SQLITE_DEFAULT_SECTOR_SIZE;
  932. }
  933. /*
  934. ** Return a vector of device characteristics.
  935. */
  936. static int winDeviceCharacteristics(sqlite3_file *id){
  937. return 0;
  938. }
  939. /*
  940. ** This vector defines all the methods that can operate on an
  941. ** sqlite3_file for win32.
  942. */
  943. static const sqlite3_io_methods winIoMethod = {
  944. 1, /* iVersion */
  945. winClose,
  946. winRead,
  947. winWrite,
  948. winTruncate,
  949. winSync,
  950. winFileSize,
  951. winLock,
  952. winUnlock,
  953. winCheckReservedLock,
  954. winFileControl,
  955. winSectorSize,
  956. winDeviceCharacteristics
  957. };
  958. /***************************************************************************
  959. ** Here ends the I/O methods that form the sqlite3_io_methods object.
  960. **
  961. ** The next block of code implements the VFS methods.
  962. ****************************************************************************/
  963. /*
  964. ** Convert a UTF-8 filename into whatever form the underlying
  965. ** operating system wants filenames in. Space to hold the result
  966. ** is obtained from malloc and must be freed by the calling
  967. ** function.
  968. */
  969. static void *convertUtf8Filename(const char *zFilename){
  970. void *zConverted = 0;
  971. if( isNT() ){
  972. zConverted = utf8ToUnicode(zFilename);
  973. }else{
  974. zConverted = utf8ToMbcs(zFilename);
  975. }
  976. /* caller will handle out of memory */
  977. return zConverted;
  978. }
  979. /*
  980. ** Open a file.
  981. */
  982. static int winOpen(
  983. sqlite3_vfs *pVfs, /* Not used */
  984. const char *zName, /* Name of the file (UTF-8) */
  985. sqlite3_file *id, /* Write the SQLite file handle here */
  986. int flags, /* Open mode flags */
  987. int *pOutFlags /* Status return flags */
  988. ){
  989. HANDLE h;
  990. DWORD dwDesiredAccess;
  991. DWORD dwShareMode;
  992. DWORD dwCreationDisposition;
  993. DWORD dwFlagsAndAttributes = 0;
  994. int isTemp;
  995. winFile *pFile = (winFile*)id;
  996. void *zConverted = convertUtf8Filename(zName);
  997. if( zConverted==0 ){
  998. return SQLITE_NOMEM;
  999. }
  1000. if( flags & SQLITE_OPEN_READWRITE ){
  1001. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  1002. }else{
  1003. dwDesiredAccess = GENERIC_READ;
  1004. }
  1005. if( flags & SQLITE_OPEN_CREATE ){
  1006. dwCreationDisposition = OPEN_ALWAYS;
  1007. }else{
  1008. dwCreationDisposition = OPEN_EXISTING;
  1009. }
  1010. if( flags & SQLITE_OPEN_MAIN_DB ){
  1011. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  1012. }else{
  1013. dwShareMode = 0;
  1014. }
  1015. if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  1016. #if OS_WINCE
  1017. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  1018. #else
  1019. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  1020. | FILE_ATTRIBUTE_HIDDEN
  1021. | FILE_FLAG_DELETE_ON_CLOSE;
  1022. #endif
  1023. isTemp = 1;
  1024. }else{
  1025. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  1026. isTemp = 0;
  1027. }
  1028. /* Reports from the internet are that performance is always
  1029. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  1030. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  1031. if( isNT() ){
  1032. h = CreateFileW((WCHAR*)zConverted,
  1033. dwDesiredAccess,
  1034. dwShareMode,
  1035. NULL,
  1036. dwCreationDisposition,
  1037. dwFlagsAndAttributes,
  1038. NULL
  1039. );
  1040. }else{
  1041. #if OS_WINCE
  1042. return SQLITE_NOMEM;
  1043. #else
  1044. h = CreateFileA((char*)zConverted,
  1045. dwDesiredAccess,
  1046. dwShareMode,
  1047. NULL,
  1048. dwCreationDisposition,
  1049. dwFlagsAndAttributes,
  1050. NULL
  1051. );
  1052. #endif
  1053. }
  1054. if( h==INVALID_HANDLE_VALUE ){
  1055. free(zConverted);
  1056. if( flags & SQLITE_OPEN_READWRITE ){
  1057. return winOpen(0, zName, id,
  1058. ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
  1059. }else{
  1060. return SQLITE_CANTOPEN;
  1061. }
  1062. }
  1063. if( pOutFlags ){
  1064. if( flags & SQLITE_OPEN_READWRITE ){
  1065. *pOutFlags = SQLITE_OPEN_READWRITE;
  1066. }else{
  1067. *pOutFlags = SQLITE_OPEN_READONLY;
  1068. }
  1069. }
  1070. memset(pFile, 0, sizeof(*pFile));
  1071. pFile->pMethod = &winIoMethod;
  1072. pFile->h = h;
  1073. #if OS_WINCE
  1074. if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
  1075. (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
  1076. && !winceCreateLock(zName, pFile)
  1077. ){
  1078. CloseHandle(h);
  1079. free(zConverted);
  1080. return SQLITE_CANTOPEN;
  1081. }
  1082. if( isTemp ){
  1083. pFile->zDeleteOnClose = zConverted;
  1084. }else
  1085. #endif
  1086. {
  1087. free(zConverted);
  1088. }
  1089. OpenCounter(+1);
  1090. return SQLITE_OK;
  1091. }
  1092. /*
  1093. ** Delete the named file.
  1094. **
  1095. ** Note that windows does not allow a file to be deleted if some other
  1096. ** process has it open. Sometimes a virus scanner or indexing program
  1097. ** will open a journal file shortly after it is created in order to do
  1098. ** whatever does. While this other process is holding the
  1099. ** file open, we will be unable to delete it. To work around this
  1100. ** problem, we delay 100 milliseconds and try to delete again. Up
  1101. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  1102. ** up and returning an error.
  1103. */
  1104. #define MX_DELETION_ATTEMPTS 5
  1105. static int winDelete(
  1106. sqlite3_vfs *pVfs, /* Not used on win32 */
  1107. const char *zFilename, /* Name of file to delete */
  1108. int syncDir /* Not used on win32 */
  1109. ){
  1110. int cnt = 0;
  1111. int rc;
  1112. void *zConverted = convertUtf8Filename(zFilename);
  1113. if( zConverted==0 ){
  1114. return SQLITE_NOMEM;
  1115. }
  1116. SimulateIOError(return SQLITE_IOERR_DELETE);
  1117. if( isNT() ){
  1118. do{
  1119. DeleteFileW(zConverted);
  1120. }while( (rc = GetFileAttributesW(zConverted))!=0xffffffff
  1121. && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
  1122. }else{
  1123. #if OS_WINCE
  1124. return SQLITE_NOMEM;
  1125. #else
  1126. do{
  1127. DeleteFileA(zConverted);
  1128. }while( (rc = GetFileAttributesA(zConverted))!=0xffffffff
  1129. && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
  1130. #endif
  1131. }
  1132. free(zConverted);
  1133. OSTRACE2("DELETE \"%s\"\n", zFilename);
  1134. return rc==0xffffffff ? SQLITE_OK : SQLITE_IOERR_DELETE;
  1135. }
  1136. /*
  1137. ** Check the existance and status of a file.
  1138. */
  1139. static int winAccess(
  1140. sqlite3_vfs *pVfs, /* Not used on win32 */
  1141. const char *zFilename, /* Name of file to check */
  1142. int flags /* Type of test to make on this file */
  1143. ){
  1144. DWORD attr;
  1145. int rc;
  1146. void *zConverted = convertUtf8Filename(zFilename);
  1147. if( zConverted==0 ){
  1148. return SQLITE_NOMEM;
  1149. }
  1150. if( isNT() ){
  1151. attr = GetFileAttributesW((WCHAR*)zConverted);
  1152. }else{
  1153. #if OS_WINCE
  1154. return SQLITE_NOMEM;
  1155. #else
  1156. attr = GetFileAttributesA((char*)zConverted);
  1157. #endif
  1158. }
  1159. free(zConverted);
  1160. switch( flags ){
  1161. case SQLITE_ACCESS_READ:
  1162. case SQLITE_ACCESS_EXISTS:
  1163. rc = attr!=0xffffffff;
  1164. break;
  1165. case SQLITE_ACCESS_READWRITE:
  1166. rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
  1167. break;
  1168. default:
  1169. assert(!"Invalid flags argument");
  1170. }
  1171. return rc;
  1172. }
  1173. /*
  1174. ** Create a temporary file name in zBuf. zBuf must be big enough to
  1175. ** hold at pVfs->mxPathname characters.
  1176. */
  1177. static int winGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  1178. static char zChars[] =
  1179. "abcdefghijklmnopqrstuvwxyz"
  1180. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1181. "0123456789";
  1182. int i, j;
  1183. char zTempPath[MAX_PATH+1];
  1184. if( sqlite3_temp_directory ){
  1185. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
  1186. }else if( isNT() ){
  1187. char *zMulti;
  1188. WCHAR zWidePath[MAX_PATH];
  1189. GetTempPathW(MAX_PATH-30, zWidePath);
  1190. zMulti = unicodeToUtf8(zWidePath);
  1191. if( zMulti ){
  1192. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
  1193. free(zMulti);
  1194. }else{
  1195. return SQLITE_NOMEM;
  1196. }
  1197. }else{
  1198. char *zUtf8;
  1199. char zMbcsPath[MAX_PATH];
  1200. GetTempPathA(MAX_PATH-30, zMbcsPath);
  1201. zUtf8 = mbcsToUtf8(zMbcsPath);
  1202. if( zUtf8 ){
  1203. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
  1204. free(zUtf8);
  1205. }else{
  1206. return SQLITE_NOMEM;
  1207. }
  1208. }
  1209. for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
  1210. zTempPath[i] = 0;
  1211. sqlite3_snprintf(nBuf-30, zBuf,
  1212. "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
  1213. j = strlen(zBuf);
  1214. sqlite3Randomness(20, &zBuf[j]);
  1215. for(i=0; i<20; i++, j++){
  1216. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  1217. }
  1218. zBuf[j] = 0;
  1219. OSTRACE2("TEMP FILENAME: %s\n", zBuf);
  1220. return SQLITE_OK;
  1221. }
  1222. /*
  1223. ** Turn a relative pathname into a full pathname. Write the full
  1224. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  1225. ** bytes in size.
  1226. */
  1227. static int winFullPathname(
  1228. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  1229. const char *zRelative, /* Possibly relative input path */
  1230. int nFull, /* Size of output buffer in bytes */
  1231. char *zFull /* Output buffer */
  1232. ){
  1233. #if defined(__CYGWIN__)
  1234. cygwin_conv_to_full_win32_path(zRelative, zFull);
  1235. return SQLITE_OK;
  1236. #endif
  1237. #if OS_WINCE
  1238. /* WinCE has no concept of a relative pathname, or so I am told. */
  1239. sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
  1240. return SQLITE_OK;
  1241. #endif
  1242. #if !OS_WINCE && !defined(__CYGWIN__)
  1243. int nByte;
  1244. void *zConverted;
  1245. char *zOut;
  1246. zConverted = convertUtf8Filename(zRelative);
  1247. if( isNT() ){
  1248. WCHAR *zTemp;
  1249. nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
  1250. zTemp = malloc( nByte*sizeof(zTemp[0]) );
  1251. if( zTemp==0 ){
  1252. free(zConverted);
  1253. return SQLITE_NOMEM;
  1254. }
  1255. GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
  1256. free(zConverted);
  1257. zOut = unicodeToUtf8(zTemp);
  1258. free(zTemp);
  1259. }else{
  1260. char *zTemp;
  1261. nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
  1262. zTemp = malloc( nByte*sizeof(zTemp[0]) );
  1263. if( zTemp==0 ){
  1264. free(zConverted);
  1265. return SQLITE_NOMEM;
  1266. }
  1267. GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  1268. free(zConverted);
  1269. zOut = mbcsToUtf8(zTemp);
  1270. free(zTemp);
  1271. }
  1272. if( zOut ){
  1273. sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
  1274. free(zOut);
  1275. return SQLITE_OK;
  1276. }else{
  1277. return SQLITE_NOMEM;
  1278. }
  1279. #endif
  1280. }
  1281. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1282. /*
  1283. ** Interfaces for opening a shared library, finding entry points
  1284. ** within the shared library, and closing the shared library.
  1285. */
  1286. /*
  1287. ** Interfaces for opening a shared library, finding entry points
  1288. ** within the shared library, and closing the shared library.
  1289. */
  1290. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  1291. HANDLE h;
  1292. void *zConverted = convertUtf8Filename(zFilename);
  1293. if( zConverted==0 ){
  1294. return 0;
  1295. }
  1296. if( isNT() ){
  1297. h = LoadLibraryW((WCHAR*)zConverted);
  1298. }else{
  1299. #if OS_WINCE
  1300. return 0;
  1301. #else
  1302. h = LoadLibraryA((char*)zConverted);
  1303. #endif
  1304. }
  1305. free(zConverted);
  1306. return (void*)h;
  1307. }
  1308. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  1309. #if OS_WINCE
  1310. int error = GetLastError();
  1311. if( error>0x7FFFFFF ){
  1312. sqlite3_snprintf(nBuf, zBufOut, "OsError 0x%x", error);
  1313. }else{
  1314. sqlite3_snprintf(nBuf, zBufOut, "OsError %d", error);
  1315. }
  1316. #else
  1317. FormatMessageA(
  1318. FORMAT_MESSAGE_FROM_SYSTEM,
  1319. NULL,
  1320. GetLastError(),
  1321. 0,
  1322. zBufOut,
  1323. nBuf-1,
  1324. 0
  1325. );
  1326. #endif
  1327. }
  1328. void *winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
  1329. #if OS_WINCE
  1330. /* The GetProcAddressA() routine is only available on wince. */
  1331. return GetProcAddressA((HANDLE)pHandle, zSymbol);
  1332. #else
  1333. /* All other windows platforms expect GetProcAddress() to take
  1334. ** an Ansi string regardless of the _UNICODE setting */
  1335. return GetProcAddress((HANDLE)pHandle, zSymbol);
  1336. #endif
  1337. }
  1338. void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  1339. FreeLibrary((HANDLE)pHandle);
  1340. }
  1341. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  1342. #define winDlOpen 0
  1343. #define winDlError 0
  1344. #define winDlSym 0
  1345. #define winDlClose 0
  1346. #endif
  1347. /*
  1348. ** Write up to nBuf bytes of randomness into zBuf.
  1349. */
  1350. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  1351. int n = 0;
  1352. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  1353. SYSTEMTIME x;
  1354. GetSystemTime(&x);
  1355. memcpy(&zBuf[n], &x, sizeof(x));
  1356. n += sizeof(x);
  1357. }
  1358. if( sizeof(DWORD)<=nBuf-n ){
  1359. DWORD pid = GetCurrentProcessId();
  1360. memcpy(&zBuf[n], &pid, sizeof(pid));
  1361. n += sizeof(pid);
  1362. }
  1363. if( sizeof(DWORD)<=nBuf-n ){
  1364. DWORD cnt = GetTickCount();
  1365. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  1366. n += sizeof(cnt);
  1367. }
  1368. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  1369. LARGE_INTEGER i;
  1370. QueryPerformanceCounter(&i);
  1371. memcpy(&zBuf[n], &i, sizeof(i));
  1372. n += sizeof(i);
  1373. }
  1374. return n;
  1375. }
  1376. /*
  1377. ** Sleep for a little while. Return the amount of time slept.
  1378. */
  1379. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  1380. Sleep((microsec+999)/1000);
  1381. return ((microsec+999)/1000)*1000;
  1382. }
  1383. /*
  1384. ** The following variable, if set to a non-zero value, becomes the result
  1385. ** returned from sqlite3OsCurrentTime(). This is used for testing.
  1386. */
  1387. #ifdef SQLITE_TEST
  1388. int sqlite3_current_time = 0;
  1389. #endif
  1390. /*
  1391. ** Find the current time (in Universal Coordinated Time). Write the
  1392. ** current time and date as a Julian Day number into *prNow and
  1393. ** return 0. Return 1 if the time and date cannot be found.
  1394. */
  1395. int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  1396. FILETIME ft;
  1397. /* FILETIME structure is a 64-bit value representing the number of
  1398. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  1399. */
  1400. double now;
  1401. #if OS_WINCE
  1402. SYSTEMTIME time;
  1403. GetSystemTime(&time);
  1404. SystemTimeToFileTime(&time,&ft);
  1405. #else
  1406. GetSystemTimeAsFileTime( &ft );
  1407. #endif
  1408. now = ((double)ft.dwHighDateTime) * 4294967296.0;
  1409. *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
  1410. #ifdef SQLITE_TEST
  1411. if( sqlite3_current_time ){
  1412. *prNow = sqlite3_current_time/86400.0 + 2440587.5;
  1413. }
  1414. #endif
  1415. return 0;
  1416. }
  1417. /*
  1418. ** Return a pointer to the sqlite3DefaultVfs structure. We use
  1419. ** a function rather than give the structure global scope because
  1420. ** some compilers (MSVC) do not allow forward declarations of
  1421. ** initialized structures.
  1422. */
  1423. sqlite3_vfs *sqlite3OsDefaultVfs(void){
  1424. static sqlite3_vfs winVfs = {
  1425. 1, /* iVersion */
  1426. sizeof(winFile), /* szOsFile */
  1427. MAX_PATH, /* mxPathname */
  1428. 0, /* pNext */
  1429. "win32", /* zName */
  1430. 0, /* pAppData */
  1431. winOpen, /* xOpen */
  1432. winDelete, /* xDelete */
  1433. winAccess, /* xAccess */
  1434. winGetTempname, /* xGetTempName */
  1435. winFullPathname, /* xFullPathname */
  1436. winDlOpen, /* xDlOpen */
  1437. winDlError, /* xDlError */
  1438. winDlSym, /* xDlSym */
  1439. winDlClose, /* xDlClose */
  1440. winRandomness, /* xRandomness */
  1441. winSleep, /* xSleep */
  1442. winCurrentTime /* xCurrentTime */
  1443. };
  1444. return &winVfs;
  1445. }
  1446. #endif /* OS_WIN */