forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathos_win_c.cs
More file actions
3846 lines (3570 loc) · 119 KB
/
os_win_c.cs
File metadata and controls
3846 lines (3570 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define SQLITE_OS_WIN
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using DWORD = System.UInt64;
using HANDLE = System.IntPtr;
using i64 = System.Int64;
using sqlite3_int64 = System.Int64;
using u32 = System.UInt32;
using u8 = System.Byte;
#if SQLITE_WINRT
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;
#elif WINDOWS_PHONE || SQLITE_SILVERLIGHT
using System.IO.IsolatedStorage;
#endif
#if !FEATURE_RUNTIMEINFORMATION
using IronPython;
#endif
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2004 May 22
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains code that is specific to windows.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
#if SQLITE_OS_WIN // * This file is used for windows only */
/*
** A Note About Memory Allocation:
**
** This driver uses malloc()/free() directly rather than going through
** the SQLite-wrappers sqlite3Malloc()/sqlite3DbFree(db,ref ). Those wrappers
** are designed for use on embedded systems where memory is scarce and
** malloc failures happen frequently. Win32 does not typically run on
** embedded systems, and when it does the developers normally have bigger
** problems to worry about than running out of memory. So there is not
** a compelling need to use the wrappers.
**
** But there is a good reason to not use the wrappers. If we use the
** wrappers then we will get simulated malloc() failures within this
** driver. And that causes all kinds of problems for our tests. We
** could enhance SQLite to deal with simulated malloc failures within
** the OS driver, but the code to deal with those failure would not
** be exercised on Linux (which does not need to malloc() in the driver)
** and so we would have difficulty writing coverage tests for that
** code. Better to leave the code out, we think.
**
** The point of this discussion is as follows: When creating a new
** OS layer for an embedded system, if you use this file as an example,
** avoid the use of malloc()/free(). Those routines work ok on windows
** desktops but not so well in embedded systems.
*/
//#include <winbase.h>
#if __CYGWIN__
//# include <sys/cygwin.h>
#endif
/*
** Macros used to determine whether or not to use threads.
*/
#if THREADSAFE
//# define SQLITE_W32_THREADS 1
#endif
/*
** Include code that is common to all os_*.c files
*/
//#include "os_common.h"
/*
** Some microsoft compilers lack this definition.
*/
#if !INVALID_FILE_ATTRIBUTES
//# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
const int INVALID_FILE_ATTRIBUTES = -1;
#endif
/*
** Determine if we are dealing with WindowsCE - which has a much
** reduced API.
*/
#if SQLITE_OS_WINCE
//# define AreFileApisANSI() 1
//# define GetDiskFreeSpaceW() 0
#endif
/* Forward references */
//typedef struct winShm winShm; /* A connection to shared-memory */
//typedef struct winShmNode winShmNode; /* A region of shared-memory */
/*
** WinCE lacks native support for file locking so we have to fake it
** with some code of our own.
*/
#if SQLITE_OS_WINCE
typedef struct winceLock {
int nReaders; /* Number of reader locks obtained */
BOOL bPending; /* Indicates a pending lock has been obtained */
BOOL bReserved; /* Indicates a reserved lock has been obtained */
BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
} winceLock;
#endif
private static LockingStrategy lockingStrategy = HelperMethods.IsRunningMediumTrust() ? new MediumTrustLockingStrategy() : new LockingStrategy();
/*
** The winFile structure is a subclass of sqlite3_file* specific to the win32
** portability layer.
*/
//typedef struct sqlite3_file sqlite3_file;
public partial class sqlite3_file
{
public sqlite3_vfs pVfs; /* The VFS used to open this file */
#if SQLITE_WINRT
public IRandomAccessStream fs;
#else
public FileStream fs; /* Filestream access to this file*/
#endif
// public HANDLE h; /* Handle for accessing the file */
public int locktype; /* Type of lock currently held on this file */
public int sharedLockByte; /* Randomly chosen byte used as a shared lock */
public DWORD lastErrno; /* The Windows errno from the last I/O error */
public DWORD sectorSize; /* Sector size of the device file is on */
#if !SQLITE_OMIT_WAL
public winShm pShm; /* Instance of shared memory on this file */
#else
public object pShm; /* DUMMY Instance of shared memory on this file */
#endif
public string zPath; /* Full pathname of this file */
public int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
#if SQLITE_OS_WINCE
Wstring zDeleteOnClose; /* Name of file to delete when closing */
HANDLE hMutex; /* Mutex used to control access to shared lock */
HANDLE hShared; /* Shared memory segment used for locking */
winceLock local; /* Locks obtained by this instance of sqlite3_file */
winceLock *shared; /* Global shared lock memory for the file */
#endif
public void Clear()
{
pMethods = null;
fs = null;
locktype = 0;
sharedLockByte = 0;
lastErrno = 0;
sectorSize = 0;
}
};
/*
** Forward prototypes.
*/
//static int getSectorSize(
// sqlite3_vfs *pVfs,
// string zRelative /* UTF-8 file name */
//);
/*
** The following variable is (normally) set once and never changes
** thereafter. It records whether the operating system is Win95
** or WinNT.
**
** 0: Operating system unknown.
** 1: Operating system is Win95.
** 2: Operating system is WinNT.
**
** In order to facilitate testing on a WinNT system, the test fixture
** can manually set this value to 1 to emulate Win98 behavior.
*/
#if SQLITE_TEST
int sqlite3_os_type = 0;
#else
static int sqlite3_os_type = 0;
#endif
/*
** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
** or WinCE. Return false (zero) for Win95, Win98, or WinME.
**
** Here is an interesting observation: Win95, Win98, and WinME lack
** the LockFileEx() API. But we can still statically link against that
** API as long as we don't call it when running Win95/98/ME. A call to
** this routine is used to determine if the host is Win95/98/ME or
** WinNT/2K/XP so that we will know whether or not we can safely call
** the LockFileEx() API.
*/
#if SQLITE_OS_WINCE
//# define isNT() (1)
#elif SQLITE_WINRT
static bool isNT() { return true; }
#else
static bool isNT()
{
//if (sqlite3_os_type == 0)
//{
// OSVERSIONINFO sInfo;
// sInfo.dwOSVersionInfoSize = sInfo.Length;
// GetVersionEx(&sInfo);
// sqlite3_os_type = sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT ? 2 : 1;
//}
//return sqlite3_os_type == 2;
return Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Unix;
}
#endif // * SQLITE_OS_WINCE */
/*
** Convert a UTF-8 string to microsoft unicode (UTF-16?).
**
** Space to hold the returned string is obtained from malloc.
*/
//static WCHAR *utf8ToUnicode(string zFilename){
// int nChar;
// Wstring zWideFilename;
// nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
// zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
// if( zWideFilename==0 ){
// return 0;
// }
// nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
// if( nChar==0 ){
// free(zWideFilename);
// zWideFileName = "";
// }
// return zWideFilename;
//}
/*
** Convert microsoft unicode to UTF-8. Space to hold the returned string is
** obtained from malloc().
*/
//static char *unicodeToUtf8(const Wstring zWideFilename){
// int nByte;
// string zFilename;
// nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
// zFilename = malloc( nByte );
// if( zFilename==0 ){
// return 0;
// }
// nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
// 0, 0);
// if( nByte == 0 ){
// free(zFilename);
// zFileName = "";
// }
// return zFilename;
//}
/*
** Convert an ansi string to microsoft unicode, based on the
** current codepage settings for file apis.
**
** Space to hold the returned string is obtained
** from malloc.
*/
//static WCHAR *mbcsToUnicode(string zFilename){
// int nByte;
// Wstring zMbcsFilename;
// int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
// nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*WCHAR.Length;
// zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
// if( zMbcsFilename==0 ){
// return 0;
// }
// nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
// if( nByte==0 ){
// free(zMbcsFilename);
// zMbcsFileName = "";
// }
// return zMbcsFilename;
//}
/*
** Convert microsoft unicode to multibyte character string, based on the
** user's Ansi codepage.
**
** Space to hold the returned string is obtained from
** malloc().
*/
//static char *unicodeToMbcs(const Wstring zWideFilename){
// int nByte;
// string zFilename;
// int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
// nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
// zFilename = malloc( nByte );
// if( zFilename==0 ){
// return 0;
// }
// nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
// 0, 0);
// if( nByte == 0 ){
// free(zFilename);
// zFileName = "";
// }
// return zFilename;
//}
/*
** Convert multibyte character string to UTF-8. Space to hold the
** returned string is obtained from malloc().
*/
//static char *sqlite3_win32_mbcs_to_utf8(string zFilename){
// string zFilenameUtf8;
// Wstring zTmpWide;
// zTmpWide = mbcsToUnicode(zFilename);
// if( zTmpWide==0 ){
// return 0;
// }
// zFilenameUtf8 = unicodeToUtf8(zTmpWide);
// free(zTmpWide);
// return zFilenameUtf8;
//}
/*
** Convert UTF-8 to multibyte character string. Space to hold the
** returned string is obtained from malloc().
*/
//char *sqlite3_win32_utf8_to_mbcs(string zFilename){
// string zFilenameMbcs;
// Wstring zTmpWide;
// zTmpWide = utf8ToUnicode(zFilename);
// if( zTmpWide==0 ){
// return 0;
// }
// zFilenameMbcs = unicodeToMbcs(zTmpWide);
// free(zTmpWide);
// return zFilenameMbcs;
//}
/*
** The return value of getLastErrorMsg
** is zero if the error message fits in the buffer, or non-zero
** otherwise (if the message was truncated).
*/
static int getLastErrorMsg(int nBuf, ref string zBuf){
/* FormatMessage returns 0 on failure. Otherwise it
** returns the number of TCHARs written to the output
** buffer, excluding the terminating null char.
*/
//DWORD error = GetLastError();
//DWORD dwLen = 0;
//string zOut = "";
//if( isNT() ){
//Wstring zTempWide = NULL;
//dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
// NULL,
// error,
// 0,
// (LPWSTR) &zTempWide,
// 0,
// 0);
zBuf = HelperMethods.GetLastError().ToString();//new Win32Exception( Marshal.GetLastWin32Error() ).Message;
//if( dwLen > 0 ){
// /* allocate a buffer and convert to UTF8 */
// zOut = unicodeToUtf8(zTempWide);
// /* free the system buffer allocated by FormatMessage */
// LocalFree(zTempWide);
//}
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
** Since the ASCII version of these Windows API do not exist for WINCE,
** it's important to not reference them for WINCE builds.
*/
//#if !SQLITE_OS_WINCE //==0
// }else{
// string zTemp = null;
// dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
// null,
// error,
// 0,
// ref zTemp,
// 0,
// 0);
// if( dwLen > 0 ){
// /* allocate a buffer and convert to UTF8 */
// zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
// /* free the system buffer allocated by FormatMessage */
// LocalFree(zTemp);
// }
//#endif
// }
//if( 0 == dwLen ){
// sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
//}else{
// /* copy a maximum of nBuf chars to output buffer */
// sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
// /* free the UTF8 buffer */
// free(zOut);
//}
return 0;
}
/*
**
** This function - winLogErrorAtLine() - is only ever called via the macro
** winLogError().
**
** This routine is invoked after an error occurs in an OS function.
** It logs a message using sqlite3_log() containing the current value of
** error code and, if possible, the human-readable equivalent from
** FormatMessage.
**
** The first argument passed to the macro should be the error code that
** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
** The two subsequent arguments should be the name of the OS function that
** failed and the the associated file-system path, if any.
*/
//#define winLogError(a,b,c) winLogErrorAtLine(a,b,c,__LINE__)
static int winLogError( int a, string b, string c )
{
StackTrace st = new StackTrace( new StackFrame( true ) );
StackFrame sf = st.GetFrame( 0 );
return winLogErrorAtLine( a, b, c, sf.GetFileLineNumber() );
}
static int winLogErrorAtLine(
int errcode, /* SQLite error code */
string zFunc, /* Name of OS function that failed */
string zPath, /* File path associated with error */
int iLine /* Source line number where error occurred */
){
string zMsg = null; /* Human readable error text */
int i; /* Loop counter */
DWORD iErrno;// = GetLastError(); /* Error code */
#if SQLITE_SILVERLIGHT || SQLITE_WINRT
iErrno = (int)ERROR_NOT_SUPPORTED;
#else
iErrno = (u32)HelperMethods.GetLastError();
#endif
//zMsg[0] = 0;
getLastErrorMsg( 500, ref zMsg );
Debug.Assert( errcode != SQLITE_OK );
if ( zPath == null )
zPath = "";
for ( i = 0; i < zMsg.Length && zMsg[i] != '\r' && zMsg[i] != '\n'; i++ )
{
}
zMsg = zMsg.Substring( 0, i );
sqlite3_log(errcode,
"os_win.c:%d: (%d) %s(%s) - %s",
iLine, iErrno, zFunc, zPath, zMsg
);
return errcode;
}
#if SQLITE_OS_WINCE
/*************************************************************************
** This section contains code for WinCE only.
*/
/*
** WindowsCE does not have a localtime() function. So create a
** substitute.
*/
//#include <time.h>
struct tm *__cdecl localtime(const time_t *t)
{
static struct tm y;
FILETIME uTm, lTm;
SYSTEMTIME pTm;
sqlite3_int64 t64;
t64 = *t;
t64 = (t64 + 11644473600)*10000000;
uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
uTm.dwHighDateTime= (DWORD)(t64 >> 32);
FileTimeToLocalFileTime(&uTm,&lTm);
FileTimeToSystemTime(&lTm,&pTm);
y.tm_year = pTm.wYear - 1900;
y.tm_mon = pTm.wMonth - 1;
y.tm_wday = pTm.wDayOfWeek;
y.tm_mday = pTm.wDay;
y.tm_hour = pTm.wHour;
y.tm_min = pTm.wMinute;
y.tm_sec = pTm.wSecond;
return &y;
}
/* This will never be called, but defined to make the code compile */
//#define GetTempPathA(a,b)
//#define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e)
//#define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e)
//#define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f)
//#define HANDLE_TO_WINFILE(a) (winFile)&((char)a)[-(int)offsetof(winFile,h)]
/*
** Acquire a lock on the handle h
*/
static void winceMutexAcquire(HANDLE h){
DWORD dwErr;
do {
dwErr = WaitForSingleObject(h, INFINITE);
} while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
}
/*
** Release a lock acquired by winceMutexAcquire()
*/
//#define winceMutexRelease(h) ReleaseMutex(h)
/*
** Create the mutex and shared memory used for locking in the file
** descriptor pFile
*/
static BOOL winceCreateLock(string zFilename, sqlite3_file pFile){
Wstring zTok;
Wstring zName = utf8ToUnicode(zFilename);
BOOL bInit = TRUE;
/* Initialize the local lockdata */
ZeroMemory(pFile.local, pFile.local).Length;
/* Replace the backslashes from the filename and lowercase it
** to derive a mutex name. */
zTok = CharLowerW(zName);
for (;*zTok;zTok++){
if (*zTok == '\\') *zTok = '_';
}
/* Create/open the named mutex */
pFile.hMutex = CreateMutexW(NULL, FALSE, zName);
if (!pFile.hMutex){
pFile.lastErrno = (u32)GetLastError();
winLogError(SQLITE_ERROR, "winceCreateLock1", zFilename);
free(zName);
return FALSE;
}
/* Acquire the mutex before continuing */
winceMutexAcquire(pFile.hMutex);
/* Since the names of named mutexes, semaphores, file mappings etc are
** case-sensitive, take advantage of that by uppercasing the mutex name
** and using that as the shared filemapping name.
*/
CharUpperW(zName);
pFile.hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
PAGE_READWRITE, 0, winceLock.Length,
zName);
/* Set a flag that indicates we're the first to create the memory so it
** must be zero-initialized */
if (GetLastError() == ERROR_ALREADY_EXISTS){
bInit = FALSE;
}
free(zName);
/* If we succeeded in making the shared memory handle, map it. */
if (pFile.hShared){
pFile.shared = (winceLock)MapViewOfFile(pFile.hShared,
FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, winceLock).Length;
/* If mapping failed, close the shared memory handle and erase it */
if (!pFile.shared){
pFile.lastErrno = (u32)GetLastError();
winLogError(SQLITE_ERROR, "winceCreateLock2", zFilename);
CloseHandle(pFile.hShared);
pFile.hShared = NULL;
}
}
/* If shared memory could not be created, then close the mutex and fail */
if (pFile.hShared == NULL){
winceMutexRelease(pFile.hMutex);
CloseHandle(pFile.hMutex);
pFile.hMutex = NULL;
return FALSE;
}
/* Initialize the shared memory if we're supposed to */
if (bInit) {
ZeroMemory(pFile.shared, winceLock).Length;
}
winceMutexRelease(pFile.hMutex);
return TRUE;
}
/*
** Destroy the part of sqlite3_file that deals with wince locks
*/
static void winceDestroyLock(sqlite3_file pFile){
if (pFile.hMutex){
/* Acquire the mutex */
winceMutexAcquire(pFile.hMutex);
/* The following blocks should probably Debug.Assert in debug mode, but they
are to cleanup in case any locks remained open */
if (pFile.local.nReaders){
pFile.shared.nReaders --;
}
if (pFile.local.bReserved){
pFile.shared.bReserved = FALSE;
}
if (pFile.local.bPending){
pFile.shared.bPending = FALSE;
}
if (pFile.local.bExclusive){
pFile.shared.bExclusive = FALSE;
}
/* De-reference and close our copy of the shared memory handle */
UnmapViewOfFile(pFile.shared);
CloseHandle(pFile.hShared);
/* Done with the mutex */
winceMutexRelease(pFile.hMutex);
CloseHandle(pFile.hMutex);
pFile.hMutex = NULL;
}
}
/*
** An implementation of the LockFile() API of windows for wince
*/
static BOOL winceLockFile(
HANDLE *phFile,
DWORD dwFileOffsetLow,
DWORD dwFileOffsetHigh,
DWORD nNumberOfBytesToLockLow,
DWORD nNumberOfBytesToLockHigh
){
winFile *pFile = HANDLE_TO_WINFILE(phFile);
BOOL bReturn = FALSE;
UNUSED_PARAMETER(dwFileOffsetHigh);
UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
if (!pFile.hMutex) return TRUE;
winceMutexAcquire(pFile.hMutex);
/* Wanting an exclusive lock? */
if (dwFileOffsetLow == (DWORD)SHARED_FIRST
&& nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
if (pFile.shared.nReaders == 0 && pFile.shared.bExclusive == 0){
pFile.shared.bExclusive = TRUE;
pFile.local.bExclusive = TRUE;
bReturn = TRUE;
}
}
/* Want a read-only lock? */
else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
nNumberOfBytesToLockLow == 1){
if (pFile.shared.bExclusive == 0){
pFile.local.nReaders ++;
if (pFile.local.nReaders == 1){
pFile.shared.nReaders ++;
}
bReturn = TRUE;
}
}
/* Want a pending lock? */
else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
/* If no pending lock has been acquired, then acquire it */
if (pFile.shared.bPending == 0) {
pFile.shared.bPending = TRUE;
pFile.local.bPending = TRUE;
bReturn = TRUE;
}
}
/* Want a reserved lock? */
else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
if (pFile.shared.bReserved == 0) {
pFile.shared.bReserved = TRUE;
pFile.local.bReserved = TRUE;
bReturn = TRUE;
}
}
winceMutexRelease(pFile.hMutex);
return bReturn;
}
/*
** An implementation of the UnlockFile API of windows for wince
*/
static BOOL winceUnlockFile(
HANDLE *phFile,
DWORD dwFileOffsetLow,
DWORD dwFileOffsetHigh,
DWORD nNumberOfBytesToUnlockLow,
DWORD nNumberOfBytesToUnlockHigh
){
winFile *pFile = HANDLE_TO_WINFILE(phFile);
BOOL bReturn = FALSE;
UNUSED_PARAMETER(dwFileOffsetHigh);
UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
if (!pFile.hMutex) return TRUE;
winceMutexAcquire(pFile.hMutex);
/* Releasing a reader lock or an exclusive lock */
if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
/* Did we have an exclusive lock? */
if (pFile.local.bExclusive){
Debug.Assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
pFile.local.bExclusive = FALSE;
pFile.shared.bExclusive = FALSE;
bReturn = TRUE;
}
/* Did we just have a reader lock? */
else if (pFile.local.nReaders){
Debug.Assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
pFile.local.nReaders --;
if (pFile.local.nReaders == 0)
{
pFile.shared.nReaders --;
}
bReturn = TRUE;
}
}
/* Releasing a pending lock */
else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
if (pFile.local.bPending){
pFile.local.bPending = FALSE;
pFile.shared.bPending = FALSE;
bReturn = TRUE;
}
}
/* Releasing a reserved lock */
else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
if (pFile.local.bReserved) {
pFile.local.bReserved = FALSE;
pFile.shared.bReserved = FALSE;
bReturn = TRUE;
}
}
winceMutexRelease(pFile.hMutex);
return bReturn;
}
/*
** An implementation of the LockFileEx() API of windows for wince
*/
static BOOL winceLockFileEx(
HANDLE *phFile,
DWORD dwFlags,
DWORD dwReserved,
DWORD nNumberOfBytesToLockLow,
DWORD nNumberOfBytesToLockHigh,
LPOVERLAPPED lpOverlapped
){
UNUSED_PARAMETER(dwReserved);
UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
/* If the caller wants a shared read lock, forward this call
** to winceLockFile */
if (lpOverlapped.Offset == (DWORD)SHARED_FIRST &&
dwFlags == 1 &&
nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
}
return FALSE;
}
/*
** End of the special code for wince
*****************************************************************************/
#endif // * SQLITE_OS_WINCE */
/*****************************************************************************
** The next group of routines implement the I/O methods specified
** by the sqlite3_io_methods object.
******************************************************************************/
/*
** Some microsoft compilers lack this definition.
*/
#if !INVALID_SET_FILE_POINTER
//# define INVALID_SET_FILE_POINTER ((DWORD)-1)
const int INVALID_SET_FILE_POINTER = -1;
#endif
/*
** Move the current position of the file handle passed as the first
** argument to offset iOffset within the file. If successful, return 0.
** Otherwise, set pFile->lastErrno and return non-zero.
*/
static int seekWinFile( sqlite3_file id, sqlite3_int64 iOffset )
{
//LONG upperBits; /* Most sig. 32 bits of new offset */
//LONG lowerBits; /* Least sig. 32 bits of new offset */
DWORD dwRet; /* Value returned by SetFilePointer() */
sqlite3_file pFile = id;
//upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
//lowerBits = (LONG)(iOffset & 0xffffffff);
/* API oddity: If successful, SetFilePointer() returns a dword
** containing the lower 32-bits of the new file-offset. Or, if it fails,
** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
** whether an error has actually occured, it is also necessary to call
** GetLastError().
*/
//dwRet = SetFilePointer(id, lowerBits, &upperBits, FILE_BEGIN);
//if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
// pFile->lastErrno = GetLastError();
// winLogError(SQLITE_IOERR_SEEK, "seekWinFile", pFile->zPath);
try
{
#if SQLITE_WINRT
id.fs.Seek( (ulong)iOffset ); // SetFilePointer(pFile.fs.Name, lowerBits, upperBits, FILE_BEGIN);
#else
id.fs.Seek( iOffset, SeekOrigin.Begin ); // SetFilePointer(pFile.fs.Name, lowerBits, upperBits, FILE_BEGIN);
#endif
}
catch ( Exception e )
{
#if SQLITE_SILVERLIGHT || SQLITE_WINRT
pFile.lastErrno = 1;
#else
pFile.lastErrno = (u32)HelperMethods.GetLastError();
#endif
winLogError(SQLITE_IOERR_SEEK, "seekWinFile", pFile.zPath);
return 1;
}
return 0;
}
/*
** Close a file.
**
** It is reported that an attempt to close a handle might sometimes
** fail. This is a very unreasonable result, but windows is notorious
** for being unreasonable so I do not doubt that it might happen. If
** the close fails, we pause for 100 milliseconds and try again. As
** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
** giving up and returning an error.
*/
public static int MX_CLOSE_ATTEMPT = 3;
static int winClose( sqlite3_file id )
{
bool rc;
int cnt = 0;
sqlite3_file pFile = (sqlite3_file)id;
Debug.Assert( id != null );
Debug.Assert( pFile.pShm == null );
#if SQLITE_DEBUG
OSTRACE( "CLOSE %d (%s)\n", pFile.fs.GetHashCode(), pFile.fs.Name );
#endif
do
{
#if SQLITE_WINRT
pFile.fs.Dispose();
#else
pFile.fs.Close();
#endif
rc = true;
// rc = CloseHandle(pFile.h);
/* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
// if (!rc && ++cnt < MX_CLOSE_ATTEMPT) Thread.Sleep(100); //, 1) );
} while ( !rc && ++cnt < MX_CLOSE_ATTEMPT ); //, 1) );
#if SQLITE_OS_WINCE
//#define WINCE_DELETION_ATTEMPTS 3
winceDestroyLock(pFile);
if( pFile.zDeleteOnClose ){
int cnt = 0;
while(
DeleteFileW(pFile.zDeleteOnClose)==0
&& GetFileAttributesW(pFile.zDeleteOnClose)!=0xffffffff
&& cnt++ < WINCE_DELETION_ATTEMPTS
){
Sleep(100); /* Wait a little before trying again */
}
free(pFile.zDeleteOnClose);
}
#endif
#if SQLITE_TEST
OSTRACE( "CLOSE %d %s\n", pFile.fs.GetHashCode(), rc ? "ok" : "failed" );
OpenCounter( -1 );
#endif
return rc ? SQLITE_OK : winLogError(SQLITE_IOERR_CLOSE, "winClose", pFile.zPath);
}
/*
** Read data from a file into a buffer. Return SQLITE_OK if all
** bytes were read successfully and SQLITE_IOERR if anything goes
** wrong.
*/
static int winRead(
sqlite3_file id, /* File to read from */
byte[] pBuf, /* Write content into this buffer */
int amt, /* Number of bytes to read */
sqlite3_int64 offset /* Begin reading at this offset */
)
{
long rc;
sqlite3_file pFile = id;
int nRead; /* Number of bytes actually read from file */
Debug.Assert( id != null );
#if SQLITE_TEST
if ( SimulateIOError() )
return SQLITE_IOERR_READ;
#endif
#if SQLITE_DEBUG
OSTRACE( "READ %d lock=%d\n", pFile.fs.GetHashCode(), pFile.locktype );
#endif
if ( !id.fs.CanRead )
return SQLITE_IOERR_READ;
if ( seekWinFile( pFile, offset ) != 0 )
{
return SQLITE_FULL;
}
try
{
#if SQLITE_WINRT
using (IInputStream inputStream = id.fs.GetInputStreamAt((ulong)offset))
{
IBuffer buffer = pBuf.AsBuffer(0,0,pBuf.Length);
inputStream.ReadAsync(buffer, (uint)amt, InputStreamOptions.None).AsTask().Wait();
nRead = (int)buffer.Length;
}
#else
nRead = id.fs.Read( pBuf, 0, amt ); // i if( null==ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
#endif
}
catch ( Exception e )
{
#if SQLITE_SILVERLIGHT || SQLITE_WINRT
pFile.lastErrno = 1;
#else
pFile.lastErrno = (u32)HelperMethods.GetLastError();
#endif
return winLogError(SQLITE_IOERR_READ, "winRead", pFile.zPath);
}
if ( nRead < amt )
{
/* Unread parts of the buffer must be zero-filled */
Array.Clear( pBuf, (int)nRead, (int)( amt - nRead ) ); // memset(&((char)pBuf)[nRead], 0, amt-nRead);
return SQLITE_IOERR_SHORT_READ;
}
return SQLITE_OK;
}
/*
** Write data from a buffer into a file. Return SQLITE_OK on success
** or some other error code on failure.
*/
static int winWrite(
sqlite3_file id, /* File to write into */
byte[] pBuf, /* The bytes to be written */
int amt, /* Number of bytes to write */
sqlite3_int64 offset /* Offset into the file to begin writing at */
)
{
int rc; /* True if error has occured, else false */
sqlite3_file pFile = id; /* File handle */
Debug.Assert( amt > 0 );