~ubuntu-branches/ubuntu/maverick/sqlite3/maverick-updates

« back to all changes in this revision

Viewing changes to src/os_win.c

  • Committer: Bazaar Package Importer
  • Author(s): Laszlo Boszormenyi (GCS)
  • Date: 2008-10-01 20:16:18 UTC
  • mfrom: (3.1.20 intrepid)
  • Revision ID: james.westby@ubuntu.com-20081001201618-yfvqqj1qs29wdtcc
Tags: 3.5.9-5
Backport fix for distinct on indexes (closes: #500792).

Show diffs side-by-side

added added

removed removed

Lines of Context:
13
13
** This file contains code that is specific to windows.
14
14
*/
15
15
#include "sqliteInt.h"
16
 
#include "os.h"
17
16
#if OS_WIN               /* This file is used for windows only */
18
17
 
 
18
 
 
19
/*
 
20
** A Note About Memory Allocation:
 
21
**
 
22
** This driver uses malloc()/free() directly rather than going through
 
23
** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
 
24
** are designed for use on embedded systems where memory is scarce and
 
25
** malloc failures happen frequently.  Win32 does not typically run on
 
26
** embedded systems, and when it does the developers normally have bigger
 
27
** problems to worry about than running out of memory.  So there is not
 
28
** a compelling need to use the wrappers.
 
29
**
 
30
** But there is a good reason to not use the wrappers.  If we use the
 
31
** wrappers then we will get simulated malloc() failures within this
 
32
** driver.  And that causes all kinds of problems for our tests.  We
 
33
** could enhance SQLite to deal with simulated malloc failures within
 
34
** the OS driver, but the code to deal with those failure would not
 
35
** be exercised on Linux (which does not need to malloc() in the driver)
 
36
** and so we would have difficulty writing coverage tests for that
 
37
** code.  Better to leave the code out, we think.
 
38
**
 
39
** The point of this discussion is as follows:  When creating a new
 
40
** OS layer for an embedded system, if you use this file as an example,
 
41
** avoid the use of malloc()/free().  Those routines work ok on windows
 
42
** desktops but not so well in embedded systems.
 
43
*/
 
44
 
19
45
#include <winbase.h>
20
46
 
21
47
#ifdef __CYGWIN__
40
66
*/
41
67
#if defined(_WIN32_WCE)
42
68
# define OS_WINCE 1
 
69
# define AreFileApisANSI() 1
43
70
#else
44
71
# define OS_WINCE 0
45
72
#endif
58
85
#endif
59
86
 
60
87
/*
61
 
** The winFile structure is a subclass of OsFile specific to the win32
 
88
** The winFile structure is a subclass of sqlite3_file* specific to the win32
62
89
** portability layer.
63
90
*/
64
91
typedef struct winFile winFile;
65
92
struct winFile {
66
 
  IoMethod const *pMethod;/* Must be first */
 
93
  const sqlite3_io_methods *pMethod;/* Must be first */
67
94
  HANDLE h;               /* Handle for accessing the file */
68
95
  unsigned char locktype; /* Type of lock currently held on this file */
69
96
  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
78
105
 
79
106
 
80
107
/*
81
 
** Do not include any of the File I/O interface procedures if the
82
 
** SQLITE_OMIT_DISKIO macro is defined (indicating that there database
83
 
** will be in-memory only)
84
 
*/
85
 
#ifndef SQLITE_OMIT_DISKIO
86
 
 
87
 
/*
88
108
** The following variable is (normally) set once and never changes
89
109
** thereafter.  It records whether the operating system is Win95
90
110
** or WinNT.
96
116
** In order to facilitate testing on a WinNT system, the test fixture
97
117
** can manually set this value to 1 to emulate Win98 behavior.
98
118
*/
 
119
#ifdef SQLITE_TEST
99
120
int sqlite3_os_type = 0;
 
121
#else
 
122
static int sqlite3_os_type = 0;
 
123
#endif
100
124
 
101
125
/*
102
126
** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
124
148
#endif /* OS_WINCE */
125
149
 
126
150
/*
127
 
** Convert a UTF-8 string to UTF-32.  Space to hold the returned string
128
 
** is obtained from sqliteMalloc.
 
151
** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
 
152
**
 
153
** Space to hold the returned string is obtained from malloc.
129
154
*/
130
155
static WCHAR *utf8ToUnicode(const char *zFilename){
131
156
  int nChar;
132
157
  WCHAR *zWideFilename;
133
158
 
134
 
  if( !isNT() ){
135
 
    return 0;
136
 
  }
137
159
  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
138
 
  zWideFilename = sqliteMalloc( nChar*sizeof(zWideFilename[0]) );
 
160
  zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
139
161
  if( zWideFilename==0 ){
140
162
    return 0;
141
163
  }
142
164
  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
143
165
  if( nChar==0 ){
144
 
    sqliteFree(zWideFilename);
 
166
    free(zWideFilename);
145
167
    zWideFilename = 0;
146
168
  }
147
169
  return zWideFilename;
148
170
}
149
171
 
150
172
/*
151
 
** Convert UTF-32 to UTF-8.  Space to hold the returned string is
152
 
** obtained from sqliteMalloc().
 
173
** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
 
174
** obtained from malloc().
153
175
*/
154
176
static char *unicodeToUtf8(const WCHAR *zWideFilename){
155
177
  int nByte;
156
178
  char *zFilename;
157
179
 
158
180
  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
159
 
  zFilename = sqliteMalloc( nByte );
 
181
  zFilename = malloc( nByte );
160
182
  if( zFilename==0 ){
161
183
    return 0;
162
184
  }
163
185
  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
164
186
                              0, 0);
165
187
  if( nByte == 0 ){
166
 
    sqliteFree(zFilename);
167
 
    zFilename = 0;
168
 
  }
169
 
  return zFilename;
 
188
    free(zFilename);
 
189
    zFilename = 0;
 
190
  }
 
191
  return zFilename;
 
192
}
 
193
 
 
194
/*
 
195
** Convert an ansi string to microsoft unicode, based on the
 
196
** current codepage settings for file apis.
 
197
** 
 
198
** Space to hold the returned string is obtained
 
199
** from malloc.
 
200
*/
 
201
static WCHAR *mbcsToUnicode(const char *zFilename){
 
202
  int nByte;
 
203
  WCHAR *zMbcsFilename;
 
204
  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
 
205
 
 
206
  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
 
207
  zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
 
208
  if( zMbcsFilename==0 ){
 
209
    return 0;
 
210
  }
 
211
  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
 
212
  if( nByte==0 ){
 
213
    free(zMbcsFilename);
 
214
    zMbcsFilename = 0;
 
215
  }
 
216
  return zMbcsFilename;
 
217
}
 
218
 
 
219
/*
 
220
** Convert microsoft unicode to multibyte character string, based on the
 
221
** user's Ansi codepage.
 
222
**
 
223
** Space to hold the returned string is obtained from
 
224
** malloc().
 
225
*/
 
226
static char *unicodeToMbcs(const WCHAR *zWideFilename){
 
227
  int nByte;
 
228
  char *zFilename;
 
229
  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
 
230
 
 
231
  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
 
232
  zFilename = malloc( nByte );
 
233
  if( zFilename==0 ){
 
234
    return 0;
 
235
  }
 
236
  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
 
237
                              0, 0);
 
238
  if( nByte == 0 ){
 
239
    free(zFilename);
 
240
    zFilename = 0;
 
241
  }
 
242
  return zFilename;
 
243
}
 
244
 
 
245
/*
 
246
** Convert multibyte character string to UTF-8.  Space to hold the
 
247
** returned string is obtained from malloc().
 
248
*/
 
249
static char *mbcsToUtf8(const char *zFilename){
 
250
  char *zFilenameUtf8;
 
251
  WCHAR *zTmpWide;
 
252
 
 
253
  zTmpWide = mbcsToUnicode(zFilename);
 
254
  if( zTmpWide==0 ){
 
255
    return 0;
 
256
  }
 
257
  zFilenameUtf8 = unicodeToUtf8(zTmpWide);
 
258
  free(zTmpWide);
 
259
  return zFilenameUtf8;
 
260
}
 
261
 
 
262
/*
 
263
** Convert UTF-8 to multibyte character string.  Space to hold the 
 
264
** returned string is obtained from malloc().
 
265
*/
 
266
static char *utf8ToMbcs(const char *zFilename){
 
267
  char *zFilenameMbcs;
 
268
  WCHAR *zTmpWide;
 
269
 
 
270
  zTmpWide = utf8ToUnicode(zFilename);
 
271
  if( zTmpWide==0 ){
 
272
    return 0;
 
273
  }
 
274
  zFilenameMbcs = unicodeToMbcs(zTmpWide);
 
275
  free(zTmpWide);
 
276
  return zFilenameMbcs;
170
277
}
171
278
 
172
279
#if OS_WINCE
183
290
  static struct tm y;
184
291
  FILETIME uTm, lTm;
185
292
  SYSTEMTIME pTm;
186
 
  i64 t64;
 
293
  sqlite3_int64 t64;
187
294
  t64 = *t;
188
295
  t64 = (t64 + 11644473600)*10000000;
189
296
  uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
245
352
  /* Create/open the named mutex */
246
353
  pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
247
354
  if (!pFile->hMutex){
248
 
    sqliteFree(zName);
 
355
    free(zName);
249
356
    return FALSE;
250
357
  }
251
358
 
267
374
    bInit = FALSE;
268
375
  }
269
376
 
270
 
  sqliteFree(zName);
 
377
  free(zName);
271
378
 
272
379
  /* If we succeeded in making the shared memory handle, map it. */
273
380
  if (pFile->hShared){
475
582
*****************************************************************************/
476
583
#endif /* OS_WINCE */
477
584
 
478
 
/*
479
 
** Delete the named file.
480
 
**
481
 
** Note that windows does not allow a file to be deleted if some other
482
 
** process has it open.  Sometimes a virus scanner or indexing program
483
 
** will open a journal file shortly after it is created in order to do
484
 
** whatever it is it does.  While this other process is holding the
485
 
** file open, we will be unable to delete it.  To work around this
486
 
** problem, we delay 100 milliseconds and try to delete again.  Up
487
 
** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
488
 
** up and returning an error.
489
 
*/
490
 
#define MX_DELETION_ATTEMPTS 3
491
 
int sqlite3WinDelete(const char *zFilename){
492
 
  WCHAR *zWide = utf8ToUnicode(zFilename);
493
 
  int cnt = 0;
494
 
  int rc;
495
 
  if( zWide ){
496
 
    do{
497
 
      rc = DeleteFileW(zWide);
498
 
    }while( rc==0 && GetFileAttributesW(zWide)!=0xffffffff 
499
 
            && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
500
 
    sqliteFree(zWide);
501
 
  }else{
502
 
#if OS_WINCE
503
 
    return SQLITE_NOMEM;
504
 
#else
505
 
    do{
506
 
      rc = DeleteFileA(zFilename);
507
 
    }while( rc==0 && GetFileAttributesA(zFilename)!=0xffffffff
508
 
            && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
509
 
#endif
510
 
  }
511
 
  TRACE2("DELETE \"%s\"\n", zFilename);
512
 
  return rc!=0 ? SQLITE_OK : SQLITE_IOERR;
513
 
}
514
 
 
515
 
/*
516
 
** Return TRUE if the named file exists.
517
 
*/
518
 
int sqlite3WinFileExists(const char *zFilename){
519
 
  int exists = 0;
520
 
  WCHAR *zWide = utf8ToUnicode(zFilename);
521
 
  if( zWide ){
522
 
    exists = GetFileAttributesW(zWide) != 0xffffffff;
523
 
    sqliteFree(zWide);
524
 
  }else{
525
 
#if OS_WINCE
526
 
    return SQLITE_NOMEM;
527
 
#else
528
 
    exists = GetFileAttributesA(zFilename) != 0xffffffff;
529
 
#endif
530
 
  }
531
 
  return exists;
532
 
}
533
 
 
534
 
/* Forward declaration */
535
 
static int allocateWinFile(winFile *pInit, OsFile **pId);
536
 
 
537
 
/*
538
 
** Attempt to open a file for both reading and writing.  If that
539
 
** fails, try opening it read-only.  If the file does not exist,
540
 
** try to create it.
541
 
**
542
 
** On success, a handle for the open file is written to *id
543
 
** and *pReadonly is set to 0 if the file was opened for reading and
544
 
** writing or 1 if the file was opened read-only.  The function returns
545
 
** SQLITE_OK.
546
 
**
547
 
** On failure, the function returns SQLITE_CANTOPEN and leaves
548
 
** *id and *pReadonly unchanged.
549
 
*/
550
 
int sqlite3WinOpenReadWrite(
551
 
  const char *zFilename,
552
 
  OsFile **pId,
553
 
  int *pReadonly
554
 
){
555
 
  winFile f;
556
 
  HANDLE h;
557
 
  WCHAR *zWide = utf8ToUnicode(zFilename);
558
 
  assert( *pId==0 );
559
 
  if( zWide ){
560
 
    h = CreateFileW(zWide,
561
 
       GENERIC_READ | GENERIC_WRITE,
562
 
       FILE_SHARE_READ | FILE_SHARE_WRITE,
563
 
       NULL,
564
 
       OPEN_ALWAYS,
565
 
       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
566
 
       NULL
567
 
    );
568
 
    if( h==INVALID_HANDLE_VALUE ){
569
 
      h = CreateFileW(zWide,
570
 
         GENERIC_READ,
571
 
         FILE_SHARE_READ | FILE_SHARE_WRITE,
572
 
         NULL,
573
 
         OPEN_ALWAYS,
574
 
         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
575
 
         NULL
576
 
      );
577
 
      if( h==INVALID_HANDLE_VALUE ){
578
 
        sqliteFree(zWide);
579
 
        return SQLITE_CANTOPEN;
580
 
      }
581
 
      *pReadonly = 1;
582
 
    }else{
583
 
      *pReadonly = 0;
584
 
    }
585
 
#if OS_WINCE
586
 
    if (!winceCreateLock(zFilename, &f)){
587
 
      CloseHandle(h);
588
 
      sqliteFree(zWide);
589
 
      return SQLITE_CANTOPEN;
590
 
    }
591
 
#endif
592
 
    sqliteFree(zWide);
593
 
  }else{
594
 
#if OS_WINCE
595
 
    return SQLITE_NOMEM;
596
 
#else
597
 
    h = CreateFileA(zFilename,
598
 
       GENERIC_READ | GENERIC_WRITE,
599
 
       FILE_SHARE_READ | FILE_SHARE_WRITE,
600
 
       NULL,
601
 
       OPEN_ALWAYS,
602
 
       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
603
 
       NULL
604
 
    );
605
 
    if( h==INVALID_HANDLE_VALUE ){
606
 
      h = CreateFileA(zFilename,
607
 
         GENERIC_READ,
608
 
         FILE_SHARE_READ | FILE_SHARE_WRITE,
609
 
         NULL,
610
 
         OPEN_ALWAYS,
611
 
         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
612
 
         NULL
613
 
      );
614
 
      if( h==INVALID_HANDLE_VALUE ){
615
 
        return SQLITE_CANTOPEN;
616
 
      }
617
 
      *pReadonly = 1;
618
 
    }else{
619
 
      *pReadonly = 0;
620
 
    }
621
 
#endif /* OS_WINCE */
622
 
  }
623
 
  f.h = h;
624
 
#if OS_WINCE
625
 
  f.zDeleteOnClose = 0;
626
 
#endif
627
 
  TRACE3("OPEN R/W %d \"%s\"\n", h, zFilename);
628
 
  return allocateWinFile(&f, pId);
629
 
}
630
 
 
631
 
 
632
 
/*
633
 
** Attempt to open a new file for exclusive access by this process.
634
 
** The file will be opened for both reading and writing.  To avoid
635
 
** a potential security problem, we do not allow the file to have
636
 
** previously existed.  Nor do we allow the file to be a symbolic
637
 
** link.
638
 
**
639
 
** If delFlag is true, then make arrangements to automatically delete
640
 
** the file when it is closed.
641
 
**
642
 
** On success, write the file handle into *id and return SQLITE_OK.
643
 
**
644
 
** On failure, return SQLITE_CANTOPEN.
645
 
**
646
 
** Sometimes if we have just deleted a prior journal file, windows
647
 
** will fail to open a new one because there is a "pending delete".
648
 
** To work around this bug, we pause for 100 milliseconds and attempt
649
 
** a second open after the first one fails.  The whole operation only
650
 
** fails if both open attempts are unsuccessful.
651
 
*/
652
 
int sqlite3WinOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
653
 
  winFile f;
654
 
  HANDLE h;
655
 
  int fileflags;
656
 
  WCHAR *zWide = utf8ToUnicode(zFilename);
657
 
  assert( *pId == 0 );
658
 
  fileflags = FILE_FLAG_RANDOM_ACCESS;
659
 
#if !OS_WINCE
660
 
  if( delFlag ){
661
 
    fileflags |= FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE;
662
 
  }
663
 
#endif
664
 
  if( zWide ){
665
 
    int cnt = 0;
666
 
    do{
667
 
      h = CreateFileW(zWide,
668
 
         GENERIC_READ | GENERIC_WRITE,
669
 
         0,
670
 
         NULL,
671
 
         CREATE_ALWAYS,
672
 
         fileflags,
673
 
         NULL
674
 
      );
675
 
    }while( h==INVALID_HANDLE_VALUE && cnt++ < 2 && (Sleep(100), 1) );
676
 
    sqliteFree(zWide);
677
 
  }else{
678
 
#if OS_WINCE
679
 
    return SQLITE_NOMEM;
680
 
#else
681
 
    int cnt = 0;
682
 
    do{
683
 
      h = CreateFileA(zFilename,
684
 
        GENERIC_READ | GENERIC_WRITE,
685
 
        0,
686
 
        NULL,
687
 
        CREATE_ALWAYS,
688
 
        fileflags,
689
 
        NULL
690
 
      );
691
 
    }while( h==INVALID_HANDLE_VALUE && cnt++ < 2 && (Sleep(100), 1) );
692
 
#endif /* OS_WINCE */
693
 
  }
694
 
  if( h==INVALID_HANDLE_VALUE ){
695
 
    return SQLITE_CANTOPEN;
696
 
  }
697
 
  f.h = h;
698
 
#if OS_WINCE
699
 
  f.zDeleteOnClose = delFlag ? utf8ToUnicode(zFilename) : 0;
700
 
  f.hMutex = NULL;
701
 
#endif
702
 
  TRACE3("OPEN EX %d \"%s\"\n", h, zFilename);
703
 
  return allocateWinFile(&f, pId);
704
 
}
705
 
 
706
 
/*
707
 
** Attempt to open a new file for read-only access.
708
 
**
709
 
** On success, write the file handle into *id and return SQLITE_OK.
710
 
**
711
 
** On failure, return SQLITE_CANTOPEN.
712
 
*/
713
 
int sqlite3WinOpenReadOnly(const char *zFilename, OsFile **pId){
714
 
  winFile f;
715
 
  HANDLE h;
716
 
  WCHAR *zWide = utf8ToUnicode(zFilename);
717
 
  assert( *pId==0 );
718
 
  if( zWide ){
719
 
    h = CreateFileW(zWide,
720
 
       GENERIC_READ,
721
 
       0,
722
 
       NULL,
723
 
       OPEN_EXISTING,
724
 
       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
725
 
       NULL
726
 
    );
727
 
    sqliteFree(zWide);
728
 
  }else{
729
 
#if OS_WINCE
730
 
    return SQLITE_NOMEM;
731
 
#else
732
 
    h = CreateFileA(zFilename,
733
 
       GENERIC_READ,
734
 
       0,
735
 
       NULL,
736
 
       OPEN_EXISTING,
737
 
       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
738
 
       NULL
739
 
    );
740
 
#endif
741
 
  }
742
 
  if( h==INVALID_HANDLE_VALUE ){
743
 
    return SQLITE_CANTOPEN;
744
 
  }
745
 
  f.h = h;
746
 
#if OS_WINCE
747
 
  f.zDeleteOnClose = 0;
748
 
  f.hMutex = NULL;
749
 
#endif
750
 
  TRACE3("OPEN RO %d \"%s\"\n", h, zFilename);
751
 
  return allocateWinFile(&f, pId);
752
 
}
753
 
 
754
 
/*
755
 
** Attempt to open a file descriptor for the directory that contains a
756
 
** file.  This file descriptor can be used to fsync() the directory
757
 
** in order to make sure the creation of a new file is actually written
758
 
** to disk.
759
 
**
760
 
** This routine is only meaningful for Unix.  It is a no-op under
761
 
** windows since windows does not support hard links.
762
 
**
763
 
** On success, a handle for a previously open file is at *id is
764
 
** updated with the new directory file descriptor and SQLITE_OK is
765
 
** returned.
766
 
**
767
 
** On failure, the function returns SQLITE_CANTOPEN and leaves
768
 
** *id unchanged.
769
 
*/
770
 
static int winOpenDirectory(
771
 
  OsFile *id,
772
 
  const char *zDirname
773
 
){
774
 
  return SQLITE_OK;
775
 
}
776
 
 
777
 
/*
778
 
** If the following global variable points to a string which is the
779
 
** name of a directory, then that directory will be used to store
780
 
** temporary files.
781
 
*/
782
 
char *sqlite3_temp_directory = 0;
783
 
 
784
 
/*
785
 
** Create a temporary file name in zBuf.  zBuf must be big enough to
786
 
** hold at least SQLITE_TEMPNAME_SIZE characters.
787
 
*/
788
 
int sqlite3WinTempFileName(char *zBuf){
789
 
  static char zChars[] =
790
 
    "abcdefghijklmnopqrstuvwxyz"
791
 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
792
 
    "0123456789";
793
 
  int i, j;
794
 
  char zTempPath[SQLITE_TEMPNAME_SIZE];
795
 
  if( sqlite3_temp_directory ){
796
 
    strncpy(zTempPath, sqlite3_temp_directory, SQLITE_TEMPNAME_SIZE-30);
797
 
    zTempPath[SQLITE_TEMPNAME_SIZE-30] = 0;
798
 
  }else if( isNT() ){
799
 
    char *zMulti;
800
 
    WCHAR zWidePath[SQLITE_TEMPNAME_SIZE];
801
 
    GetTempPathW(SQLITE_TEMPNAME_SIZE-30, zWidePath);
802
 
    zMulti = unicodeToUtf8(zWidePath);
803
 
    if( zMulti ){
804
 
      strncpy(zTempPath, zMulti, SQLITE_TEMPNAME_SIZE-30);
805
 
      zTempPath[SQLITE_TEMPNAME_SIZE-30] = 0;
806
 
      sqliteFree(zMulti);
807
 
    }
808
 
  }else{
809
 
    GetTempPathA(SQLITE_TEMPNAME_SIZE-30, zTempPath);
810
 
  }
811
 
  for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
812
 
  zTempPath[i] = 0;
813
 
  for(;;){
814
 
    sprintf(zBuf, "%s\\"TEMP_FILE_PREFIX, zTempPath);
815
 
    j = strlen(zBuf);
816
 
    sqlite3Randomness(15, &zBuf[j]);
817
 
    for(i=0; i<15; i++, j++){
818
 
      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
819
 
    }
820
 
    zBuf[j] = 0;
821
 
    if( !sqlite3OsFileExists(zBuf) ) break;
822
 
  }
823
 
  TRACE2("TEMP FILENAME: %s\n", zBuf);
824
 
  return SQLITE_OK; 
825
 
}
 
585
/*****************************************************************************
 
586
** The next group of routines implement the I/O methods specified
 
587
** by the sqlite3_io_methods object.
 
588
******************************************************************************/
826
589
 
827
590
/*
828
591
** Close a file.
835
598
** giving up and returning an error.
836
599
*/
837
600
#define MX_CLOSE_ATTEMPT 3
838
 
static int winClose(OsFile **pId){
839
 
  winFile *pFile;
840
 
  int rc = 1;
841
 
  if( pId && (pFile = (winFile*)*pId)!=0 ){
842
 
    int rc, cnt = 0;
843
 
    TRACE2("CLOSE %d\n", pFile->h);
844
 
    do{
845
 
      rc = CloseHandle(pFile->h);
846
 
    }while( rc==0 && cnt++ < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
 
601
static int winClose(sqlite3_file *id){
 
602
  int rc, cnt = 0;
 
603
  winFile *pFile = (winFile*)id;
 
604
  OSTRACE2("CLOSE %d\n", pFile->h);
 
605
  do{
 
606
    rc = CloseHandle(pFile->h);
 
607
  }while( rc==0 && cnt++ < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
847
608
#if OS_WINCE
848
 
    winceDestroyLock(pFile);
849
 
    if( pFile->zDeleteOnClose ){
850
 
      DeleteFileW(pFile->zDeleteOnClose);
851
 
      sqliteFree(pFile->zDeleteOnClose);
 
609
#define WINCE_DELETION_ATTEMPTS 3
 
610
  winceDestroyLock(pFile);
 
611
  if( pFile->zDeleteOnClose ){
 
612
    int cnt = 0;
 
613
    while(
 
614
           DeleteFileW(pFile->zDeleteOnClose)==0
 
615
        && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
 
616
        && cnt++ < WINCE_DELETION_ATTEMPTS
 
617
    ){
 
618
       Sleep(100);  /* Wait a little before trying again */
852
619
    }
 
620
    free(pFile->zDeleteOnClose);
 
621
  }
853
622
#endif
854
 
    OpenCounter(-1);
855
 
    sqliteFree(pFile);
856
 
    *pId = 0;
857
 
  }
 
623
  OpenCounter(-1);
858
624
  return rc ? SQLITE_OK : SQLITE_IOERR;
859
625
}
860
626
 
861
627
/*
 
628
** Some microsoft compilers lack this definition.
 
629
*/
 
630
#ifndef INVALID_SET_FILE_POINTER
 
631
# define INVALID_SET_FILE_POINTER ((DWORD)-1)
 
632
#endif
 
633
 
 
634
/*
862
635
** Read data from a file into a buffer.  Return SQLITE_OK if all
863
636
** bytes were read successfully and SQLITE_IOERR if anything goes
864
637
** wrong.
865
638
*/
866
 
static int winRead(OsFile *id, void *pBuf, int amt){
 
639
static int winRead(
 
640
  sqlite3_file *id,          /* File to read from */
 
641
  void *pBuf,                /* Write content into this buffer */
 
642
  int amt,                   /* Number of bytes to read */
 
643
  sqlite3_int64 offset       /* Begin reading at this offset */
 
644
){
 
645
  LONG upperBits = (offset>>32) & 0x7fffffff;
 
646
  LONG lowerBits = offset & 0xffffffff;
 
647
  DWORD rc;
867
648
  DWORD got;
 
649
  winFile *pFile = (winFile*)id;
868
650
  assert( id!=0 );
869
 
  SimulateIOError(return SQLITE_IOERR);
870
 
  TRACE3("READ %d lock=%d\n", ((winFile*)id)->h, ((winFile*)id)->locktype);
871
 
  if( !ReadFile(((winFile*)id)->h, pBuf, amt, &got, 0) ){
872
 
    got = 0;
 
651
  SimulateIOError(return SQLITE_IOERR_READ);
 
652
  OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
 
653
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
 
654
  if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
 
655
    return SQLITE_FULL;
 
656
  }
 
657
  if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
 
658
    return SQLITE_IOERR_READ;
873
659
  }
874
660
  if( got==(DWORD)amt ){
875
661
    return SQLITE_OK;
876
662
  }else{
877
 
    return SQLITE_IOERR;
 
663
    memset(&((char*)pBuf)[got], 0, amt-got);
 
664
    return SQLITE_IOERR_SHORT_READ;
878
665
  }
879
666
}
880
667
 
882
669
** Write data from a buffer into a file.  Return SQLITE_OK on success
883
670
** or some other error code on failure.
884
671
*/
885
 
static int winWrite(OsFile *id, const void *pBuf, int amt){
886
 
  int rc = 0;
 
672
static int winWrite(
 
673
  sqlite3_file *id,         /* File to write into */
 
674
  const void *pBuf,         /* The bytes to be written */
 
675
  int amt,                  /* Number of bytes to write */
 
676
  sqlite3_int64 offset      /* Offset into the file to begin writing at */
 
677
){
 
678
  LONG upperBits = (offset>>32) & 0x7fffffff;
 
679
  LONG lowerBits = offset & 0xffffffff;
 
680
  DWORD rc;
887
681
  DWORD wrote;
 
682
  winFile *pFile = (winFile*)id;
888
683
  assert( id!=0 );
889
 
  SimulateIOError(return SQLITE_IOERR);
 
684
  SimulateIOError(return SQLITE_IOERR_WRITE);
890
685
  SimulateDiskfullError(return SQLITE_FULL);
891
 
  TRACE3("WRITE %d lock=%d\n", ((winFile*)id)->h, ((winFile*)id)->locktype);
 
686
  OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
 
687
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
 
688
  if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
 
689
    return SQLITE_FULL;
 
690
  }
892
691
  assert( amt>0 );
893
 
  while( amt>0 && (rc = WriteFile(((winFile*)id)->h, pBuf, amt, &wrote, 0))!=0
894
 
         && wrote>0 ){
 
692
  while(
 
693
     amt>0
 
694
     && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
 
695
     && wrote>0
 
696
  ){
895
697
    amt -= wrote;
896
698
    pBuf = &((char*)pBuf)[wrote];
897
699
  }
902
704
}
903
705
 
904
706
/*
905
 
** Some microsoft compilers lack this definition.
 
707
** Truncate an open file to a specified size
906
708
*/
907
 
#ifndef INVALID_SET_FILE_POINTER
908
 
# define INVALID_SET_FILE_POINTER ((DWORD)-1)
909
 
#endif
 
709
static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
 
710
  LONG upperBits = (nByte>>32) & 0x7fffffff;
 
711
  LONG lowerBits = nByte & 0xffffffff;
 
712
  winFile *pFile = (winFile*)id;
 
713
  OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
 
714
  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
 
715
  SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
 
716
  SetEndOfFile(pFile->h);
 
717
  return SQLITE_OK;
 
718
}
910
719
 
911
 
/*
912
 
** Move the read/write pointer in a file.
913
 
*/
914
 
static int winSeek(OsFile *id, i64 offset){
915
 
  LONG upperBits = offset>>32;
916
 
  LONG lowerBits = offset & 0xffffffff;
917
 
  DWORD rc;
918
 
  assert( id!=0 );
919
720
#ifdef SQLITE_TEST
920
 
  if( offset ) SimulateDiskfullError(return SQLITE_FULL);
 
721
/*
 
722
** Count the number of fullsyncs and normal syncs.  This is used to test
 
723
** that syncs and fullsyncs are occuring at the right times.
 
724
*/
 
725
int sqlite3_sync_count = 0;
 
726
int sqlite3_fullsync_count = 0;
921
727
#endif
922
 
  SEEK(offset/1024 + 1);
923
 
  rc = SetFilePointer(((winFile*)id)->h, lowerBits, &upperBits, FILE_BEGIN);
924
 
  TRACE3("SEEK %d %lld\n", ((winFile*)id)->h, offset);
925
 
  if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
926
 
    return SQLITE_FULL;
927
 
  }
928
 
  return SQLITE_OK;
929
 
}
930
728
 
931
729
/*
932
730
** Make sure all writes to a particular file are committed to disk.
933
731
*/
934
 
static int winSync(OsFile *id, int dataOnly){
935
 
  assert( id!=0 );
936
 
  TRACE3("SYNC %d lock=%d\n", ((winFile*)id)->h, ((winFile*)id)->locktype);
937
 
  if( FlushFileBuffers(((winFile*)id)->h) ){
 
732
static int winSync(sqlite3_file *id, int flags){
 
733
  winFile *pFile = (winFile*)id;
 
734
  OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
 
735
#ifdef SQLITE_TEST
 
736
  if( flags & SQLITE_SYNC_FULL ){
 
737
    sqlite3_fullsync_count++;
 
738
  }
 
739
  sqlite3_sync_count++;
 
740
#endif
 
741
  if( FlushFileBuffers(pFile->h) ){
938
742
    return SQLITE_OK;
939
743
  }else{
940
744
    return SQLITE_IOERR;
942
746
}
943
747
 
944
748
/*
945
 
** Sync the directory zDirname. This is a no-op on operating systems other
946
 
** than UNIX.
947
 
*/
948
 
int sqlite3WinSyncDirectory(const char *zDirname){
949
 
  SimulateIOError(return SQLITE_IOERR);
950
 
  return SQLITE_OK;
951
 
}
952
 
 
953
 
/*
954
 
** Truncate an open file to a specified size
955
 
*/
956
 
static int winTruncate(OsFile *id, i64 nByte){
957
 
  LONG upperBits = nByte>>32;
958
 
  assert( id!=0 );
959
 
  TRACE3("TRUNCATE %d %lld\n", ((winFile*)id)->h, nByte);
960
 
  SimulateIOError(return SQLITE_IOERR);
961
 
  SetFilePointer(((winFile*)id)->h, nByte, &upperBits, FILE_BEGIN);
962
 
  SetEndOfFile(((winFile*)id)->h);
963
 
  return SQLITE_OK;
964
 
}
965
 
 
966
 
/*
967
749
** Determine the current size of a file in bytes
968
750
*/
969
 
static int winFileSize(OsFile *id, i64 *pSize){
 
751
static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
 
752
  winFile *pFile = (winFile*)id;
970
753
  DWORD upperBits, lowerBits;
971
 
  assert( id!=0 );
972
 
  SimulateIOError(return SQLITE_IOERR);
973
 
  lowerBits = GetFileSize(((winFile*)id)->h, &upperBits);
974
 
  *pSize = (((i64)upperBits)<<32) + lowerBits;
 
754
  SimulateIOError(return SQLITE_IOERR_FSTAT);
 
755
  lowerBits = GetFileSize(pFile->h, &upperBits);
 
756
  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
975
757
  return SQLITE_OK;
976
758
}
977
759
 
987
769
** Different API routines are called depending on whether or not this
988
770
** is Win95 or WinNT.
989
771
*/
990
 
static int getReadLock(winFile *id){
 
772
static int getReadLock(winFile *pFile){
991
773
  int res;
992
774
  if( isNT() ){
993
775
    OVERLAPPED ovlp;
994
776
    ovlp.Offset = SHARED_FIRST;
995
777
    ovlp.OffsetHigh = 0;
996
778
    ovlp.hEvent = 0;
997
 
    res = LockFileEx(id->h, LOCKFILE_FAIL_IMMEDIATELY, 0, SHARED_SIZE,0,&ovlp);
 
779
    res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
 
780
                     0, SHARED_SIZE, 0, &ovlp);
998
781
  }else{
999
782
    int lk;
1000
 
    sqlite3Randomness(sizeof(lk), &lk);
1001
 
    id->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
1002
 
    res = LockFile(id->h, SHARED_FIRST+id->sharedLockByte, 0, 1, 0);
 
783
    sqlite3_randomness(sizeof(lk), &lk);
 
784
    pFile->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
 
785
    res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
1003
786
  }
1004
787
  return res;
1005
788
}
1017
800
  return res;
1018
801
}
1019
802
 
1020
 
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
1021
 
/*
1022
 
** Check that a given pathname is a directory and is writable 
1023
 
**
1024
 
*/
1025
 
int sqlite3WinIsDirWritable(char *zDirname){
1026
 
  int fileAttr;
1027
 
  WCHAR *zWide;
1028
 
  if( zDirname==0 ) return 0;
1029
 
  if( !isNT() && strlen(zDirname)>MAX_PATH ) return 0;
1030
 
  zWide = utf8ToUnicode(zDirname);
1031
 
  if( zWide ){
1032
 
    fileAttr = GetFileAttributesW(zWide);
1033
 
    sqliteFree(zWide);
1034
 
  }else{
1035
 
#if OS_WINCE
1036
 
    return 0;
1037
 
#else
1038
 
    fileAttr = GetFileAttributesA(zDirname);
1039
 
#endif
1040
 
  }
1041
 
  if( fileAttr == 0xffffffff ) return 0;
1042
 
  if( (fileAttr & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY ){
1043
 
    return 0;
1044
 
  }
1045
 
  return 1;
1046
 
}
1047
 
#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
1048
 
 
1049
803
/*
1050
804
** Lock the file with the lock specified by parameter locktype - one
1051
805
** of the following:
1072
826
** It is not possible to lower the locking level one step at a time.  You
1073
827
** must go straight to locking level 0.
1074
828
*/
1075
 
static int winLock(OsFile *id, int locktype){
 
829
static int winLock(sqlite3_file *id, int locktype){
1076
830
  int rc = SQLITE_OK;    /* Return code from subroutines */
1077
831
  int res = 1;           /* Result of a windows lock call */
1078
 
  int newLocktype;       /* Set id->locktype to this value before exiting */
 
832
  int newLocktype;       /* Set pFile->locktype to this value before exiting */
1079
833
  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
1080
834
  winFile *pFile = (winFile*)id;
1081
835
 
1082
836
  assert( pFile!=0 );
1083
 
  TRACE5("LOCK %d %d was %d(%d)\n",
 
837
  OSTRACE5("LOCK %d %d was %d(%d)\n",
1084
838
          pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
1085
839
 
1086
840
  /* If there is already a lock of this type or more restrictive on the
1110
864
      /* Try 3 times to get the pending lock.  The pending lock might be
1111
865
      ** held by another reader process who will release it momentarily.
1112
866
      */
1113
 
      TRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
 
867
      OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
1114
868
      Sleep(1);
1115
869
    }
1116
870
    gotPendingLock = res;
1148
902
  if( locktype==EXCLUSIVE_LOCK && res ){
1149
903
    assert( pFile->locktype>=SHARED_LOCK );
1150
904
    res = unlockReadLock(pFile);
1151
 
    TRACE2("unreadlock = %d\n", res);
 
905
    OSTRACE2("unreadlock = %d\n", res);
1152
906
    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
1153
907
    if( res ){
1154
908
      newLocktype = EXCLUSIVE_LOCK;
1155
909
    }else{
1156
 
      TRACE2("error-code = %d\n", GetLastError());
 
910
      OSTRACE2("error-code = %d\n", GetLastError());
 
911
      getReadLock(pFile);
1157
912
    }
1158
913
  }
1159
914
 
1170
925
  if( res ){
1171
926
    rc = SQLITE_OK;
1172
927
  }else{
1173
 
    TRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
 
928
    OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
1174
929
           locktype, newLocktype);
1175
930
    rc = SQLITE_BUSY;
1176
931
  }
1183
938
** file by this or any other process. If such a lock is held, return
1184
939
** non-zero, otherwise zero.
1185
940
*/
1186
 
static int winCheckReservedLock(OsFile *id){
 
941
static int winCheckReservedLock(sqlite3_file *id){
1187
942
  int rc;
1188
943
  winFile *pFile = (winFile*)id;
1189
944
  assert( pFile!=0 );
1190
945
  if( pFile->locktype>=RESERVED_LOCK ){
1191
946
    rc = 1;
1192
 
    TRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
 
947
    OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
1193
948
  }else{
1194
949
    rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1195
950
    if( rc ){
1196
951
      UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
1197
952
    }
1198
953
    rc = !rc;
1199
 
    TRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
 
954
    OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
1200
955
  }
1201
956
  return rc;
1202
957
}
1212
967
** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
1213
968
** might return SQLITE_IOERR;
1214
969
*/
1215
 
static int winUnlock(OsFile *id, int locktype){
 
970
static int winUnlock(sqlite3_file *id, int locktype){
1216
971
  int type;
 
972
  winFile *pFile = (winFile*)id;
1217
973
  int rc = SQLITE_OK;
1218
 
  winFile *pFile = (winFile*)id;
1219
974
  assert( pFile!=0 );
1220
975
  assert( locktype<=SHARED_LOCK );
1221
 
  TRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
 
976
  OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
1222
977
          pFile->locktype, pFile->sharedLockByte);
1223
978
  type = pFile->locktype;
1224
979
  if( type>=EXCLUSIVE_LOCK ){
1226
981
    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
1227
982
      /* This should never happen.  We should always be able to
1228
983
      ** reacquire the read lock */
1229
 
      rc = SQLITE_IOERR;
 
984
      rc = SQLITE_IOERR_UNLOCK;
1230
985
    }
1231
986
  }
1232
987
  if( type>=RESERVED_LOCK ){
1243
998
}
1244
999
 
1245
1000
/*
1246
 
** Turn a relative pathname into a full pathname.  Return a pointer
1247
 
** to the full pathname stored in space obtained from sqliteMalloc().
1248
 
** The calling function is responsible for freeing this space once it
1249
 
** is no longer needed.
 
1001
** Control and query of the open file handle.
1250
1002
*/
1251
 
char *sqlite3WinFullPathname(const char *zRelative){
1252
 
  char *zFull;
1253
 
#if defined(__CYGWIN__)
1254
 
  int nByte;
1255
 
  nByte = strlen(zRelative) + MAX_PATH + 1001;
1256
 
  zFull = sqliteMalloc( nByte );
1257
 
  if( zFull==0 ) return 0;
1258
 
  if( cygwin_conv_to_full_win32_path(zRelative, zFull) ) return 0;
1259
 
#elif OS_WINCE
1260
 
  /* WinCE has no concept of a relative pathname, or so I am told. */
1261
 
  zFull = sqliteStrDup(zRelative);
1262
 
#else
1263
 
  char *zNotUsed;
1264
 
  WCHAR *zWide;
1265
 
  int nByte;
1266
 
  zWide = utf8ToUnicode(zRelative);
1267
 
  if( zWide ){
1268
 
    WCHAR *zTemp, *zNotUsedW;
1269
 
    nByte = GetFullPathNameW(zWide, 0, 0, &zNotUsedW) + 1;
1270
 
    zTemp = sqliteMalloc( nByte*sizeof(zTemp[0]) );
1271
 
    if( zTemp==0 ) return 0;
1272
 
    GetFullPathNameW(zWide, nByte, zTemp, &zNotUsedW);
1273
 
    sqliteFree(zWide);
1274
 
    zFull = unicodeToUtf8(zTemp);
1275
 
    sqliteFree(zTemp);
1276
 
  }else{
1277
 
    nByte = GetFullPathNameA(zRelative, 0, 0, &zNotUsed) + 1;
1278
 
    zFull = sqliteMalloc( nByte*sizeof(zFull[0]) );
1279
 
    if( zFull==0 ) return 0;
1280
 
    GetFullPathNameA(zRelative, nByte, zFull, &zNotUsed);
 
1003
static int winFileControl(sqlite3_file *id, int op, void *pArg){
 
1004
  switch( op ){
 
1005
    case SQLITE_FCNTL_LOCKSTATE: {
 
1006
      *(int*)pArg = ((winFile*)id)->locktype;
 
1007
      return SQLITE_OK;
 
1008
    }
1281
1009
  }
1282
 
#endif
1283
 
  return zFull;
1284
 
}
1285
 
 
1286
 
/*
1287
 
** The fullSync option is meaningless on windows.   This is a no-op.
1288
 
*/
1289
 
static void winSetFullSync(OsFile *id, int v){
1290
 
  return;
1291
 
}
1292
 
 
1293
 
/*
1294
 
** Return the underlying file handle for an OsFile
1295
 
*/
1296
 
static int winFileHandle(OsFile *id){
1297
 
  return (int)((winFile*)id)->h;
1298
 
}
1299
 
 
1300
 
/*
1301
 
** Return an integer that indices the type of lock currently held
1302
 
** by this handle.  (Used for testing and analysis only.)
1303
 
*/
1304
 
static int winLockState(OsFile *id){
1305
 
  return ((winFile*)id)->locktype;
1306
 
}
1307
 
 
1308
 
/*
1309
 
** This vector defines all the methods that can operate on an OsFile
1310
 
** for win32.
1311
 
*/
1312
 
static const IoMethod sqlite3WinIoMethod = {
 
1010
  return SQLITE_ERROR;
 
1011
}
 
1012
 
 
1013
/*
 
1014
** Return the sector size in bytes of the underlying block device for
 
1015
** the specified file. This is almost always 512 bytes, but may be
 
1016
** larger for some devices.
 
1017
**
 
1018
** SQLite code assumes this function cannot fail. It also assumes that
 
1019
** if two files are created in the same file-system directory (i.e.
 
1020
** a database and its journal file) that the sector size will be the
 
1021
** same for both.
 
1022
*/
 
1023
static int winSectorSize(sqlite3_file *id){
 
1024
  return SQLITE_DEFAULT_SECTOR_SIZE;
 
1025
}
 
1026
 
 
1027
/*
 
1028
** Return a vector of device characteristics.
 
1029
*/
 
1030
static int winDeviceCharacteristics(sqlite3_file *id){
 
1031
  return 0;
 
1032
}
 
1033
 
 
1034
/*
 
1035
** This vector defines all the methods that can operate on an
 
1036
** sqlite3_file for win32.
 
1037
*/
 
1038
static const sqlite3_io_methods winIoMethod = {
 
1039
  1,                        /* iVersion */
1313
1040
  winClose,
1314
 
  winOpenDirectory,
1315
1041
  winRead,
1316
1042
  winWrite,
1317
 
  winSeek,
1318
1043
  winTruncate,
1319
1044
  winSync,
1320
 
  winSetFullSync,
1321
 
  winFileHandle,
1322
1045
  winFileSize,
1323
1046
  winLock,
1324
1047
  winUnlock,
1325
 
  winLockState,
1326
1048
  winCheckReservedLock,
 
1049
  winFileControl,
 
1050
  winSectorSize,
 
1051
  winDeviceCharacteristics
1327
1052
};
1328
1053
 
1329
 
/*
1330
 
** Allocate memory for an OsFile.  Initialize the new OsFile
1331
 
** to the value given in pInit and return a pointer to the new
1332
 
** OsFile.  If we run out of memory, close the file and return NULL.
1333
 
*/
1334
 
static int allocateWinFile(winFile *pInit, OsFile **pId){
1335
 
  winFile *pNew;
1336
 
  pNew = sqliteMalloc( sizeof(*pNew) );
1337
 
  if( pNew==0 ){
1338
 
    CloseHandle(pInit->h);
1339
 
#if OS_WINCE
1340
 
    sqliteFree(pInit->zDeleteOnClose);
1341
 
#endif
1342
 
    *pId = 0;
1343
 
    return SQLITE_NOMEM;
1344
 
  }else{
1345
 
    *pNew = *pInit;
1346
 
    pNew->pMethod = &sqlite3WinIoMethod;
1347
 
    pNew->locktype = NO_LOCK;
1348
 
    pNew->sharedLockByte = 0;
1349
 
    *pId = (OsFile*)pNew;
1350
 
    OpenCounter(+1);
1351
 
    return SQLITE_OK;
1352
 
  }
1353
 
}
1354
 
 
1355
 
 
1356
 
#endif /* SQLITE_OMIT_DISKIO */
1357
1054
/***************************************************************************
1358
 
** Everything above deals with file I/O.  Everything that follows deals
1359
 
** with other miscellanous aspects of the operating system interface
 
1055
** Here ends the I/O methods that form the sqlite3_io_methods object.
 
1056
**
 
1057
** The next block of code implements the VFS methods.
1360
1058
****************************************************************************/
1361
1059
 
1362
1060
/*
1363
 
** Get information to seed the random number generator.  The seed
1364
 
** is written into the buffer zBuf[256].  The calling function must
1365
 
** supply a sufficiently large buffer.
1366
 
*/
1367
 
int sqlite3WinRandomSeed(char *zBuf){
1368
 
  /* We have to initialize zBuf to prevent valgrind from reporting
1369
 
  ** errors.  The reports issued by valgrind are incorrect - we would
1370
 
  ** prefer that the randomness be increased by making use of the
1371
 
  ** uninitialized space in zBuf - but valgrind errors tend to worry
1372
 
  ** some users.  Rather than argue, it seems easier just to initialize
1373
 
  ** the whole array and silence valgrind, even if that means less randomness
1374
 
  ** in the random seed.
1375
 
  **
1376
 
  ** When testing, initializing zBuf[] to zero is all we do.  That means
1377
 
  ** that we always use the same random number sequence.* This makes the
1378
 
  ** tests repeatable.
1379
 
  */
1380
 
  memset(zBuf, 0, 256);
1381
 
  GetSystemTime((LPSYSTEMTIME)zBuf);
1382
 
  return SQLITE_OK;
1383
 
}
 
1061
** Convert a UTF-8 filename into whatever form the underlying
 
1062
** operating system wants filenames in.  Space to hold the result
 
1063
** is obtained from malloc and must be freed by the calling
 
1064
** function.
 
1065
*/
 
1066
static void *convertUtf8Filename(const char *zFilename){
 
1067
  void *zConverted = 0;
 
1068
  if( isNT() ){
 
1069
    zConverted = utf8ToUnicode(zFilename);
 
1070
  }else{
 
1071
    zConverted = utf8ToMbcs(zFilename);
 
1072
  }
 
1073
  /* caller will handle out of memory */
 
1074
  return zConverted;
 
1075
}
 
1076
 
 
1077
/*
 
1078
** Open a file.
 
1079
*/
 
1080
static int winOpen(
 
1081
  sqlite3_vfs *pVfs,        /* Not used */
 
1082
  const char *zName,        /* Name of the file (UTF-8) */
 
1083
  sqlite3_file *id,         /* Write the SQLite file handle here */
 
1084
  int flags,                /* Open mode flags */
 
1085
  int *pOutFlags            /* Status return flags */
 
1086
){
 
1087
  HANDLE h;
 
1088
  DWORD dwDesiredAccess;
 
1089
  DWORD dwShareMode;
 
1090
  DWORD dwCreationDisposition;
 
1091
  DWORD dwFlagsAndAttributes = 0;
 
1092
  int isTemp;
 
1093
  winFile *pFile = (winFile*)id;
 
1094
  void *zConverted = convertUtf8Filename(zName);
 
1095
  if( zConverted==0 ){
 
1096
    return SQLITE_NOMEM;
 
1097
  }
 
1098
 
 
1099
  if( flags & SQLITE_OPEN_READWRITE ){
 
1100
    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
 
1101
  }else{
 
1102
    dwDesiredAccess = GENERIC_READ;
 
1103
  }
 
1104
  if( flags & SQLITE_OPEN_CREATE ){
 
1105
    dwCreationDisposition = OPEN_ALWAYS;
 
1106
  }else{
 
1107
    dwCreationDisposition = OPEN_EXISTING;
 
1108
  }
 
1109
  if( flags & SQLITE_OPEN_MAIN_DB ){
 
1110
    dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
 
1111
  }else{
 
1112
    dwShareMode = 0;
 
1113
  }
 
1114
  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
 
1115
#if OS_WINCE
 
1116
    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
 
1117
#else
 
1118
    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
 
1119
                               | FILE_ATTRIBUTE_HIDDEN
 
1120
                               | FILE_FLAG_DELETE_ON_CLOSE;
 
1121
#endif
 
1122
    isTemp = 1;
 
1123
  }else{
 
1124
    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
 
1125
    isTemp = 0;
 
1126
  }
 
1127
  /* Reports from the internet are that performance is always
 
1128
  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
 
1129
  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
 
1130
  if( isNT() ){
 
1131
    h = CreateFileW((WCHAR*)zConverted,
 
1132
       dwDesiredAccess,
 
1133
       dwShareMode,
 
1134
       NULL,
 
1135
       dwCreationDisposition,
 
1136
       dwFlagsAndAttributes,
 
1137
       NULL
 
1138
    );
 
1139
  }else{
 
1140
#if OS_WINCE
 
1141
    return SQLITE_NOMEM;
 
1142
#else
 
1143
    h = CreateFileA((char*)zConverted,
 
1144
       dwDesiredAccess,
 
1145
       dwShareMode,
 
1146
       NULL,
 
1147
       dwCreationDisposition,
 
1148
       dwFlagsAndAttributes,
 
1149
       NULL
 
1150
    );
 
1151
#endif
 
1152
  }
 
1153
  if( h==INVALID_HANDLE_VALUE ){
 
1154
    free(zConverted);
 
1155
    if( flags & SQLITE_OPEN_READWRITE ){
 
1156
      return winOpen(0, zName, id, 
 
1157
             ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
 
1158
    }else{
 
1159
      return SQLITE_CANTOPEN;
 
1160
    }
 
1161
  }
 
1162
  if( pOutFlags ){
 
1163
    if( flags & SQLITE_OPEN_READWRITE ){
 
1164
      *pOutFlags = SQLITE_OPEN_READWRITE;
 
1165
    }else{
 
1166
      *pOutFlags = SQLITE_OPEN_READONLY;
 
1167
    }
 
1168
  }
 
1169
  memset(pFile, 0, sizeof(*pFile));
 
1170
  pFile->pMethod = &winIoMethod;
 
1171
  pFile->h = h;
 
1172
#if OS_WINCE
 
1173
  if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
 
1174
               (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
 
1175
       && !winceCreateLock(zName, pFile)
 
1176
  ){
 
1177
    CloseHandle(h);
 
1178
    free(zConverted);
 
1179
    return SQLITE_CANTOPEN;
 
1180
  }
 
1181
  if( isTemp ){
 
1182
    pFile->zDeleteOnClose = zConverted;
 
1183
  }else
 
1184
#endif
 
1185
  {
 
1186
    free(zConverted);
 
1187
  }
 
1188
  OpenCounter(+1);
 
1189
  return SQLITE_OK;
 
1190
}
 
1191
 
 
1192
/*
 
1193
** Delete the named file.
 
1194
**
 
1195
** Note that windows does not allow a file to be deleted if some other
 
1196
** process has it open.  Sometimes a virus scanner or indexing program
 
1197
** will open a journal file shortly after it is created in order to do
 
1198
** whatever does.  While this other process is holding the
 
1199
** file open, we will be unable to delete it.  To work around this
 
1200
** problem, we delay 100 milliseconds and try to delete again.  Up
 
1201
** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
 
1202
** up and returning an error.
 
1203
*/
 
1204
#define MX_DELETION_ATTEMPTS 5
 
1205
static int winDelete(
 
1206
  sqlite3_vfs *pVfs,          /* Not used on win32 */
 
1207
  const char *zFilename,      /* Name of file to delete */
 
1208
  int syncDir                 /* Not used on win32 */
 
1209
){
 
1210
  int cnt = 0;
 
1211
  int rc;
 
1212
  void *zConverted = convertUtf8Filename(zFilename);
 
1213
  if( zConverted==0 ){
 
1214
    return SQLITE_NOMEM;
 
1215
  }
 
1216
  SimulateIOError(return SQLITE_IOERR_DELETE);
 
1217
  if( isNT() ){
 
1218
    do{
 
1219
      DeleteFileW(zConverted);
 
1220
    }while( (rc = GetFileAttributesW(zConverted))!=0xffffffff 
 
1221
            && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
 
1222
  }else{
 
1223
#if OS_WINCE
 
1224
    return SQLITE_NOMEM;
 
1225
#else
 
1226
    do{
 
1227
      DeleteFileA(zConverted);
 
1228
    }while( (rc = GetFileAttributesA(zConverted))!=0xffffffff
 
1229
            && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
 
1230
#endif
 
1231
  }
 
1232
  free(zConverted);
 
1233
  OSTRACE2("DELETE \"%s\"\n", zFilename);
 
1234
  return rc==0xffffffff ? SQLITE_OK : SQLITE_IOERR_DELETE;
 
1235
}
 
1236
 
 
1237
/*
 
1238
** Check the existance and status of a file.
 
1239
*/
 
1240
static int winAccess(
 
1241
  sqlite3_vfs *pVfs,         /* Not used on win32 */
 
1242
  const char *zFilename,     /* Name of file to check */
 
1243
  int flags                  /* Type of test to make on this file */
 
1244
){
 
1245
  DWORD attr;
 
1246
  int rc;
 
1247
  void *zConverted = convertUtf8Filename(zFilename);
 
1248
  if( zConverted==0 ){
 
1249
    return SQLITE_NOMEM;
 
1250
  }
 
1251
  if( isNT() ){
 
1252
    attr = GetFileAttributesW((WCHAR*)zConverted);
 
1253
  }else{
 
1254
#if OS_WINCE
 
1255
    return SQLITE_NOMEM;
 
1256
#else
 
1257
    attr = GetFileAttributesA((char*)zConverted);
 
1258
#endif
 
1259
  }
 
1260
  free(zConverted);
 
1261
  switch( flags ){
 
1262
    case SQLITE_ACCESS_READ:
 
1263
    case SQLITE_ACCESS_EXISTS:
 
1264
      rc = attr!=0xffffffff;
 
1265
      break;
 
1266
    case SQLITE_ACCESS_READWRITE:
 
1267
      rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
 
1268
      break;
 
1269
    default:
 
1270
      assert(!"Invalid flags argument");
 
1271
  }
 
1272
  return rc;
 
1273
}
 
1274
 
 
1275
 
 
1276
/*
 
1277
** Create a temporary file name in zBuf.  zBuf must be big enough to
 
1278
** hold at pVfs->mxPathname characters.
 
1279
*/
 
1280
static int winGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
 
1281
  static char zChars[] =
 
1282
    "abcdefghijklmnopqrstuvwxyz"
 
1283
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1284
    "0123456789";
 
1285
  int i, j;
 
1286
  char zTempPath[MAX_PATH+1];
 
1287
  if( sqlite3_temp_directory ){
 
1288
    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
 
1289
  }else if( isNT() ){
 
1290
    char *zMulti;
 
1291
    WCHAR zWidePath[MAX_PATH];
 
1292
    GetTempPathW(MAX_PATH-30, zWidePath);
 
1293
    zMulti = unicodeToUtf8(zWidePath);
 
1294
    if( zMulti ){
 
1295
      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
 
1296
      free(zMulti);
 
1297
    }else{
 
1298
      return SQLITE_NOMEM;
 
1299
    }
 
1300
  }else{
 
1301
    char *zUtf8;
 
1302
    char zMbcsPath[MAX_PATH];
 
1303
    GetTempPathA(MAX_PATH-30, zMbcsPath);
 
1304
    zUtf8 = mbcsToUtf8(zMbcsPath);
 
1305
    if( zUtf8 ){
 
1306
      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
 
1307
      free(zUtf8);
 
1308
    }else{
 
1309
      return SQLITE_NOMEM;
 
1310
    }
 
1311
  }
 
1312
  for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
 
1313
  zTempPath[i] = 0;
 
1314
  sqlite3_snprintf(nBuf-30, zBuf,
 
1315
                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
 
1316
  j = strlen(zBuf);
 
1317
  sqlite3_randomness(20, &zBuf[j]);
 
1318
  for(i=0; i<20; i++, j++){
 
1319
    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
 
1320
  }
 
1321
  zBuf[j] = 0;
 
1322
  OSTRACE2("TEMP FILENAME: %s\n", zBuf);
 
1323
  return SQLITE_OK; 
 
1324
}
 
1325
 
 
1326
/*
 
1327
** Turn a relative pathname into a full pathname.  Write the full
 
1328
** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
 
1329
** bytes in size.
 
1330
*/
 
1331
static int winFullPathname(
 
1332
  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
 
1333
  const char *zRelative,        /* Possibly relative input path */
 
1334
  int nFull,                    /* Size of output buffer in bytes */
 
1335
  char *zFull                   /* Output buffer */
 
1336
){
 
1337
 
 
1338
#if defined(__CYGWIN__)
 
1339
  cygwin_conv_to_full_win32_path(zRelative, zFull);
 
1340
  return SQLITE_OK;
 
1341
#endif
 
1342
 
 
1343
#if OS_WINCE
 
1344
  /* WinCE has no concept of a relative pathname, or so I am told. */
 
1345
  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
 
1346
  return SQLITE_OK;
 
1347
#endif
 
1348
 
 
1349
#if !OS_WINCE && !defined(__CYGWIN__)
 
1350
  int nByte;
 
1351
  void *zConverted;
 
1352
  char *zOut;
 
1353
  zConverted = convertUtf8Filename(zRelative);
 
1354
  if( isNT() ){
 
1355
    WCHAR *zTemp;
 
1356
    nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
 
1357
    zTemp = malloc( nByte*sizeof(zTemp[0]) );
 
1358
    if( zTemp==0 ){
 
1359
      free(zConverted);
 
1360
      return SQLITE_NOMEM;
 
1361
    }
 
1362
    GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
 
1363
    free(zConverted);
 
1364
    zOut = unicodeToUtf8(zTemp);
 
1365
    free(zTemp);
 
1366
  }else{
 
1367
    char *zTemp;
 
1368
    nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
 
1369
    zTemp = malloc( nByte*sizeof(zTemp[0]) );
 
1370
    if( zTemp==0 ){
 
1371
      free(zConverted);
 
1372
      return SQLITE_NOMEM;
 
1373
    }
 
1374
    GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
 
1375
    free(zConverted);
 
1376
    zOut = mbcsToUtf8(zTemp);
 
1377
    free(zTemp);
 
1378
  }
 
1379
  if( zOut ){
 
1380
    sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
 
1381
    free(zOut);
 
1382
    return SQLITE_OK;
 
1383
  }else{
 
1384
    return SQLITE_NOMEM;
 
1385
  }
 
1386
#endif
 
1387
}
 
1388
 
 
1389
#ifndef SQLITE_OMIT_LOAD_EXTENSION
 
1390
/*
 
1391
** Interfaces for opening a shared library, finding entry points
 
1392
** within the shared library, and closing the shared library.
 
1393
*/
 
1394
/*
 
1395
** Interfaces for opening a shared library, finding entry points
 
1396
** within the shared library, and closing the shared library.
 
1397
*/
 
1398
static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
 
1399
  HANDLE h;
 
1400
  void *zConverted = convertUtf8Filename(zFilename);
 
1401
  if( zConverted==0 ){
 
1402
    return 0;
 
1403
  }
 
1404
  if( isNT() ){
 
1405
    h = LoadLibraryW((WCHAR*)zConverted);
 
1406
  }else{
 
1407
#if OS_WINCE
 
1408
    return 0;
 
1409
#else
 
1410
    h = LoadLibraryA((char*)zConverted);
 
1411
#endif
 
1412
  }
 
1413
  free(zConverted);
 
1414
  return (void*)h;
 
1415
}
 
1416
static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
 
1417
#if OS_WINCE
 
1418
  int error = GetLastError();
 
1419
  if( error>0x7FFFFFF ){
 
1420
    sqlite3_snprintf(nBuf, zBufOut, "OsError 0x%x", error);
 
1421
  }else{
 
1422
    sqlite3_snprintf(nBuf, zBufOut, "OsError %d", error);
 
1423
  }
 
1424
#else
 
1425
  FormatMessageA(
 
1426
    FORMAT_MESSAGE_FROM_SYSTEM,
 
1427
    NULL,
 
1428
    GetLastError(),
 
1429
    0,
 
1430
    zBufOut,
 
1431
    nBuf-1,
 
1432
    0
 
1433
  );
 
1434
#endif
 
1435
}
 
1436
void *winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
 
1437
#if OS_WINCE
 
1438
  /* The GetProcAddressA() routine is only available on wince. */
 
1439
  return GetProcAddressA((HANDLE)pHandle, zSymbol);
 
1440
#else
 
1441
  /* All other windows platforms expect GetProcAddress() to take
 
1442
  ** an Ansi string regardless of the _UNICODE setting */
 
1443
  return GetProcAddress((HANDLE)pHandle, zSymbol);
 
1444
#endif
 
1445
}
 
1446
void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
 
1447
  FreeLibrary((HANDLE)pHandle);
 
1448
}
 
1449
#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
 
1450
  #define winDlOpen  0
 
1451
  #define winDlError 0
 
1452
  #define winDlSym   0
 
1453
  #define winDlClose 0
 
1454
#endif
 
1455
 
 
1456
 
 
1457
/*
 
1458
** Write up to nBuf bytes of randomness into zBuf.
 
1459
*/
 
1460
static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
 
1461
  int n = 0;
 
1462
  if( sizeof(SYSTEMTIME)<=nBuf-n ){
 
1463
    SYSTEMTIME x;
 
1464
    GetSystemTime(&x);
 
1465
    memcpy(&zBuf[n], &x, sizeof(x));
 
1466
    n += sizeof(x);
 
1467
  }
 
1468
  if( sizeof(DWORD)<=nBuf-n ){
 
1469
    DWORD pid = GetCurrentProcessId();
 
1470
    memcpy(&zBuf[n], &pid, sizeof(pid));
 
1471
    n += sizeof(pid);
 
1472
  }
 
1473
  if( sizeof(DWORD)<=nBuf-n ){
 
1474
    DWORD cnt = GetTickCount();
 
1475
    memcpy(&zBuf[n], &cnt, sizeof(cnt));
 
1476
    n += sizeof(cnt);
 
1477
  }
 
1478
  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
 
1479
    LARGE_INTEGER i;
 
1480
    QueryPerformanceCounter(&i);
 
1481
    memcpy(&zBuf[n], &i, sizeof(i));
 
1482
    n += sizeof(i);
 
1483
  }
 
1484
  return n;
 
1485
}
 
1486
 
1384
1487
 
1385
1488
/*
1386
1489
** Sleep for a little while.  Return the amount of time slept.
1387
1490
*/
1388
 
int sqlite3WinSleep(int ms){
1389
 
  Sleep(ms);
1390
 
  return ms;
1391
 
}
1392
 
 
1393
 
/*
1394
 
** Static variables used for thread synchronization
1395
 
*/
1396
 
static int inMutex = 0;
1397
 
#ifdef SQLITE_W32_THREADS
1398
 
  static DWORD mutexOwner;
1399
 
  static CRITICAL_SECTION cs;
1400
 
#endif
1401
 
 
1402
 
/*
1403
 
** The following pair of routines implement mutual exclusion for
1404
 
** multi-threaded processes.  Only a single thread is allowed to
1405
 
** executed code that is surrounded by EnterMutex() and LeaveMutex().
1406
 
**
1407
 
** SQLite uses only a single Mutex.  There is not much critical
1408
 
** code and what little there is executes quickly and without blocking.
1409
 
**
1410
 
** Version 3.3.1 and earlier used a simple mutex.  Beginning with
1411
 
** version 3.3.2, a recursive mutex is required.
1412
 
*/
1413
 
void sqlite3WinEnterMutex(){
1414
 
#ifdef SQLITE_W32_THREADS
1415
 
  static int isInit = 0;
1416
 
  while( !isInit ){
1417
 
    static long lock = 0;
1418
 
    if( InterlockedIncrement(&lock)==1 ){
1419
 
      InitializeCriticalSection(&cs);
1420
 
      isInit = 1;
1421
 
    }else{
1422
 
      Sleep(1);
1423
 
    }
1424
 
  }
1425
 
  EnterCriticalSection(&cs);
1426
 
  mutexOwner = GetCurrentThreadId();
1427
 
#endif
1428
 
  inMutex++;
1429
 
}
1430
 
void sqlite3WinLeaveMutex(){
1431
 
  assert( inMutex );
1432
 
  inMutex--;
1433
 
#ifdef SQLITE_W32_THREADS
1434
 
  assert( mutexOwner==GetCurrentThreadId() );
1435
 
  LeaveCriticalSection(&cs);
1436
 
#endif
1437
 
}
1438
 
 
1439
 
/*
1440
 
** Return TRUE if the mutex is currently held.
1441
 
**
1442
 
** If the thisThreadOnly parameter is true, return true if and only if the
1443
 
** calling thread holds the mutex.  If the parameter is false, return
1444
 
** true if any thread holds the mutex.
1445
 
*/
1446
 
int sqlite3WinInMutex(int thisThreadOnly){
1447
 
#ifdef SQLITE_W32_THREADS
1448
 
  return inMutex>0 && (thisThreadOnly==0 || mutexOwner==GetCurrentThreadId());
1449
 
#else
1450
 
  return inMutex>0;
1451
 
#endif
1452
 
}
1453
 
 
 
1491
static int winSleep(sqlite3_vfs *pVfs, int microsec){
 
1492
  Sleep((microsec+999)/1000);
 
1493
  return ((microsec+999)/1000)*1000;
 
1494
}
1454
1495
 
1455
1496
/*
1456
1497
** The following variable, if set to a non-zero value, becomes the result
1465
1506
** current time and date as a Julian Day number into *prNow and
1466
1507
** return 0.  Return 1 if the time and date cannot be found.
1467
1508
*/
1468
 
int sqlite3WinCurrentTime(double *prNow){
 
1509
int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
1469
1510
  FILETIME ft;
1470
1511
  /* FILETIME structure is a 64-bit value representing the number of 
1471
1512
     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
1488
1529
  return 0;
1489
1530
}
1490
1531
 
1491
 
/*
1492
 
** Remember the number of thread-specific-data blocks allocated.
1493
 
** Use this to verify that we are not leaking thread-specific-data.
1494
 
** Ticket #1601
1495
 
*/
1496
 
#ifdef SQLITE_TEST
1497
 
int sqlite3_tsd_count = 0;
1498
 
# define TSD_COUNTER_INCR InterlockedIncrement(&sqlite3_tsd_count)
1499
 
# define TSD_COUNTER_DECR InterlockedDecrement(&sqlite3_tsd_count)
1500
 
#else
1501
 
# define TSD_COUNTER_INCR  /* no-op */
1502
 
# define TSD_COUNTER_DECR  /* no-op */
1503
 
#endif
1504
 
 
1505
 
 
1506
 
 
1507
 
/*
1508
 
** If called with allocateFlag>1, then return a pointer to thread
1509
 
** specific data for the current thread.  Allocate and zero the
1510
 
** thread-specific data if it does not already exist necessary.
1511
 
**
1512
 
** If called with allocateFlag==0, then check the current thread
1513
 
** specific data.  Return it if it exists.  If it does not exist,
1514
 
** then return NULL.
1515
 
**
1516
 
** If called with allocateFlag<0, check to see if the thread specific
1517
 
** data is allocated and is all zero.  If it is then deallocate it.
1518
 
** Return a pointer to the thread specific data or NULL if it is
1519
 
** unallocated or gets deallocated.
1520
 
*/
1521
 
ThreadData *sqlite3WinThreadSpecificData(int allocateFlag){
1522
 
  static int key;
1523
 
  static int keyInit = 0;
1524
 
  static const ThreadData zeroData = {0};
1525
 
  ThreadData *pTsd;
1526
 
 
1527
 
  if( !keyInit ){
1528
 
    sqlite3OsEnterMutex();
1529
 
    if( !keyInit ){
1530
 
      key = TlsAlloc();
1531
 
      if( key==0xffffffff ){
1532
 
        sqlite3OsLeaveMutex();
1533
 
        return 0;
1534
 
      }
1535
 
      keyInit = 1;
1536
 
    }
1537
 
    sqlite3OsLeaveMutex();
1538
 
  }
1539
 
  pTsd = TlsGetValue(key);
1540
 
  if( allocateFlag>0 ){
1541
 
    if( !pTsd ){
1542
 
      pTsd = sqlite3OsMalloc( sizeof(zeroData) );
1543
 
      if( pTsd ){
1544
 
        *pTsd = zeroData;
1545
 
        TlsSetValue(key, pTsd);
1546
 
        TSD_COUNTER_INCR;
1547
 
      }
1548
 
    }
1549
 
  }else if( pTsd!=0 && allocateFlag<0 
1550
 
              && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
1551
 
    sqlite3OsFree(pTsd);
1552
 
    TlsSetValue(key, 0);
1553
 
    TSD_COUNTER_DECR;
1554
 
    pTsd = 0;
1555
 
  }
1556
 
  return pTsd;
 
1532
 
 
1533
/*
 
1534
** Return a pointer to the sqlite3DefaultVfs structure.   We use
 
1535
** a function rather than give the structure global scope because
 
1536
** some compilers (MSVC) do not allow forward declarations of
 
1537
** initialized structures.
 
1538
*/
 
1539
sqlite3_vfs *sqlite3OsDefaultVfs(void){
 
1540
  static sqlite3_vfs winVfs = {
 
1541
    1,                 /* iVersion */
 
1542
    sizeof(winFile),   /* szOsFile */
 
1543
    MAX_PATH,          /* mxPathname */
 
1544
    0,                 /* pNext */
 
1545
    "win32",           /* zName */
 
1546
    0,                 /* pAppData */
 
1547
  
 
1548
    winOpen,           /* xOpen */
 
1549
    winDelete,         /* xDelete */
 
1550
    winAccess,         /* xAccess */
 
1551
    winGetTempname,    /* xGetTempName */
 
1552
    winFullPathname,   /* xFullPathname */
 
1553
    winDlOpen,         /* xDlOpen */
 
1554
    winDlError,        /* xDlError */
 
1555
    winDlSym,          /* xDlSym */
 
1556
    winDlClose,        /* xDlClose */
 
1557
    winRandomness,     /* xRandomness */
 
1558
    winSleep,          /* xSleep */
 
1559
    winCurrentTime     /* xCurrentTime */
 
1560
  };
 
1561
  
 
1562
  return &winVfs;
1557
1563
}
 
1564
 
1558
1565
#endif /* OS_WIN */