SQLite

Changes On Branch win32-enable-setlk
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Changes In Branch win32-enable-setlk Excluding Merge-Ins

This is equivalent to a diff from 742827f049 to 55324d1c86

2025-02-24
21:27
Support SQLITE_ENABLE_SETLK_TIMEOUT on windows. (check-in: e88212b10a user: dan tags: trunk)
10:52
Merge latest changes from trunk into this branch. (Closed-Leaf check-in: 55324d1c86 user: dan tags: win32-enable-setlk)
2025-02-22
23:18
Prototype implementation of the unistr() SQL function. (check-in: 7cc302de05 user: drh tags: unistr)
16:44
Tamp down various harmless compiler warnings. Use "int" in places instead of "u16" or "i16" since the compiler complains less and generates faster code. (check-in: 742827f049 user: drh tags: trunk)
11:40
Fix an incorrect assert added by [d7729dbbf231d57c]. (check-in: eeea11278b user: drh tags: trunk)
2025-02-12
17:21
Have the win32 VFS take a temporary shared lock (instead of the current exclusive) on the pending-byte when taking a SHARED lock on a db. Do not lock the pending-byte at all when taking an EXCLUSIVE lock if RESERVED is not already held. (check-in: 5127509abb user: dan tags: win32-enable-setlk)

Changes to Makefile.msc.
289
290
291
292
293
294
295






296
297
298
299
300
301
302
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308







+
+
+
+
+
+







!ENDIF

# Set this to non-0 to enable support for the rbu extension.
#
!IFNDEF RBU
RBU = 0
!ENDIF

# Set this to non-0 to enable support for blocking locks.
#
!IFNDEF SETLK_TIMEOUT
SETLK_TIMEOUT = 0
!ENDIF

# Set the source code file to be used by executables and libraries when
# they need the amalgamation.
#
!IFNDEF SQLITE3C
!IF $(SPLIT_AMALGAMATION)!=0
SQLITE3C = sqlite3-all.c
445
446
447
448
449
450
451




452
453
454
455
456
457
458
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468







+
+
+
+







EXT_FEATURE_FLAGS = $(EXT_FEATURE_FLAGS) -DSQLITE_ENABLE_FTS4=1
EXT_FEATURE_FLAGS = $(EXT_FEATURE_FLAGS) -DSQLITE_SYSTEM_MALLOC=1
EXT_FEATURE_FLAGS = $(EXT_FEATURE_FLAGS) -DSQLITE_OMIT_LOCALTIME=1
!ELSE
EXT_FEATURE_FLAGS =
!ENDIF
!ENDIF

!IF $(SETLK_TIMEOUT)!=0
OPT_FEATURE_FLAGS = $(OPT_FEATURE_FLAGS) -DSQLITE_ENABLE_SETLK_TIMEOUT
!ENDIF

###############################################################################
############################### END OF OPTIONS ################################
###############################################################################

# When compiling for the Windows 10 platform, the PLATFORM macro must be set
# to an appropriate value (e.g. x86, x64, arm, arm64, etc).
Changes to src/attach.c.
223
224
225
226
227
228
229







230
231
232
233
234
235
236
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243







+
+
+
+
+
+
+







  ** remove the entry from the db->aDb[] array. i.e. put everything back the
  ** way we found it.
  */
  if( rc==SQLITE_OK ){
    sqlite3BtreeEnterAll(db);
    db->init.iDb = 0;
    db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
    if( db->setlkFlags & SQLITE_SETLK_BLOCK_ON_CONNECT ){
      int val = 1;
      sqlite3_file *fd = sqlite3PagerFile(sqlite3BtreePager(pNew->pBt));
      sqlite3OsFileControlHint(fd, SQLITE_FCNTL_BLOCK_ON_CONNECT, &val);
    }
#endif
    if( !REOPEN_AS_MEMDB(db) ){
      rc = sqlite3Init(db, &zErrDyn);
    }
    sqlite3BtreeLeaveAll(db);
    assert( zErrDyn==0 || rc!=SQLITE_OK );
  }
  if( rc ){
Changes to src/main.c.
1775
1776
1777
1778
1779
1780
1781



1782
1783
1784
1785
1786
1787
1788
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791







+
+
+







  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
  sqlite3_mutex_enter(db->mutex);
  db->busyHandler.xBusyHandler = xBusy;
  db->busyHandler.pBusyArg = pArg;
  db->busyHandler.nBusy = 0;
  db->busyTimeout = 0;
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  db->setlkTimeout = 0;
#endif
  sqlite3_mutex_leave(db->mutex);
  return SQLITE_OK;
}

#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
/*
** This routine sets the progress callback for an Sqlite database to the
1824
1825
1826
1827
1828
1829
1830



1831
1832
1833
1834
1835




























1836
1837
1838
1839
1840
1841
1842
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876







+
+
+





+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







#ifdef SQLITE_ENABLE_API_ARMOR
  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
  if( ms>0 ){
    sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
                             (void*)db);
    db->busyTimeout = ms;
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
    db->setlkTimeout = ms;
#endif
  }else{
    sqlite3_busy_handler(db, 0, 0);
  }
  return SQLITE_OK;
}

/*
** Set the setlk timeout value.
*/
int sqlite3_setlk_timeout(sqlite3 *db, int ms, int flags){
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  int iDb;
  int bBOC = ((flags & SQLITE_SETLK_BLOCK_ON_CONNECT) ? 1 : 0);
#endif
#ifdef SQLITE_ENABLE_API_ARMOR
  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
#endif
  if( ms<-1 ) return SQLITE_RANGE;
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  db->setlkTimeout = ms;
  db->setlkFlags = flags;
  sqlite3BtreeEnterAll(db);
  for(iDb=0; iDb<db->nDb; iDb++){
    Btree *pBt = db->aDb[iDb].pBt;
    if( pBt ){
      sqlite3_file *fd = sqlite3PagerFile(sqlite3BtreePager(pBt));
      sqlite3OsFileControlHint(fd, SQLITE_FCNTL_BLOCK_ON_CONNECT, (void*)&bBOC);
    }
  }
  sqlite3BtreeLeaveAll(db);
#endif
  return SQLITE_OK;
}

/*
** Cause any pending operation to stop at its earliest opportunity.
*/
void sqlite3_interrupt(sqlite3 *db){
#ifdef SQLITE_ENABLE_API_ARMOR
  if( !sqlite3SafetyCheckOk(db)
Changes to src/os_unix.c.
280
281
282
283
284
285
286

287
288
289
290
291
292
293
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294







+







  int openFlags;                      /* The flags specified at open() */
#endif
#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  unsigned fsFlags;                   /* cached details from statfs() */
#endif
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  unsigned iBusyTimeout;              /* Wait this many millisec on locks */
  int bBlockOnConnect;                /* True to block for SHARED locks */
#endif
#if OS_VXWORKS
  struct vxworksFileId *pId;          /* Unique file ID */
#endif
#ifdef SQLITE_DEBUG
  /* The next group of variables are used to track whether or not the
  ** transaction counter in bytes 24-27 of database files are updated
1673
1674
1675
1676
1677
1678
1679







1680
1681
1682
1683
1684
1685
1686
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694







+
+
+
+
+
+
+







      if( rc<0 ) return rc;
      pInode->bProcessLock = 1;
      pInode->nLock++;
    }else{
      rc = 0;
    }
  }else{
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
    if( pFile->bBlockOnConnect && pLock->l_type==F_RDLCK 
     && pLock->l_start==SHARED_FIRST && pLock->l_len==SHARED_SIZE
    ){
      rc = osFcntl(pFile->h, F_SETLKW, pLock);
    }else
#endif
    rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
  }
  return rc;
}

/*
** Lock the file with the lock specified by parameter eFileLock - one
4034
4035
4036
4037
4038
4039
4040

4041
4042

4043
4044
4045
4046
4047
4048
4049
4050





4051

4052
4053
4054
4055
4056
4057
4058
4042
4043
4044
4045
4046
4047
4048
4049
4050

4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064

4065
4066
4067
4068
4069
4070
4071
4072







+

-
+








+
+
+
+
+
-
+







    case SQLITE_FCNTL_HAS_MOVED: {
      *(int*)pArg = fileHasMoved(pFile);
      return SQLITE_OK;
    }
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
    case SQLITE_FCNTL_LOCK_TIMEOUT: {
      int iOld = pFile->iBusyTimeout;
      int iNew = *(int*)pArg;
#if SQLITE_ENABLE_SETLK_TIMEOUT==1
      pFile->iBusyTimeout = *(int*)pArg;
      pFile->iBusyTimeout = iNew<0 ? 0x7FFFFFFF : (unsigned)iNew;
#elif SQLITE_ENABLE_SETLK_TIMEOUT==2
      pFile->iBusyTimeout = !!(*(int*)pArg);
#else
# error "SQLITE_ENABLE_SETLK_TIMEOUT must be set to 1 or 2"
#endif
      *(int*)pArg = iOld;
      return SQLITE_OK;
    }
    case SQLITE_FCNTL_BLOCK_ON_CONNECT: {
      int iNew = *(int*)pArg;
      pFile->bBlockOnConnect = iNew;
      return SQLITE_OK;
    }
#endif
#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
#if SQLITE_MAX_MMAP_SIZE>0
    case SQLITE_FCNTL_MMAP_SIZE: {
      i64 newLimit = *(i64*)pArg;
      int rc = SQLITE_OK;
      if( newLimit>sqlite3GlobalConfig.mxMmap ){
        newLimit = sqlite3GlobalConfig.mxMmap;
      }
5027
5028
5029
5030
5031
5032
5033
5034

5035
5036
5037
5038
5039
5040
5041
5041
5042
5043
5044
5045
5046
5047

5048
5049
5050
5051
5052
5053
5054
5055







-
+







  **
  ** In other words, if this is a blocking lock, none of the locks that
  ** occur later in the above list than the lock being obtained may be
  ** held.
  **
  ** It is not permitted to block on the RECOVER lock.
  */
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
#if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && defined(SQLITE_DEBUG)
  {
    u16 lockMask = (p->exclMask|p->sharedMask);
    assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
          (ofst!=2)                                   /* not RECOVER */
       && (ofst!=1 || lockMask==0 || lockMask==2)
       && (ofst!=0 || lockMask<3)
       && (ofst<3  || lockMask<(1<<ofst))
Changes to src/os_win.c.
283
284
285
286
287
288
289




290






291
292
293
294
295
296
297
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







+
+
+
+

+
+
+
+
+
+







#if SQLITE_MAX_MMAP_SIZE>0
  int nFetchOut;                /* Number of outstanding xFetch references */
  HANDLE hMap;                  /* Handle for accessing memory mapping */
  void *pMapRegion;             /* Area memory mapped */
  sqlite3_int64 mmapSize;       /* Size of mapped region */
  sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
#endif
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  DWORD iBusyTimeout;        /* Wait this many millisec on locks */
  int bBlockOnConnect;
#endif
};

#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
# define winFileBusyTimeout(pDbFd) pDbFd->iBusyTimeout
#else
# define winFileBusyTimeout(pDbFd) 0
#endif

/*
** The winVfsAppData structure is used for the pAppData member for all of the
** Win32 VFS variants.
*/
typedef struct winVfsAppData winVfsAppData;
struct winVfsAppData {
718
719
720
721
722
723
724






725
726
727
728
729
730
731
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747







+
+
+
+
+
+







#else
  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
#endif

#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
        LPWSTR*))aSyscall[25].pCurrent)

/*
** For GetLastError(), MSDN says:
**
** Minimum supported client: Windows XP [desktop apps | UWP apps]
** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps]
*/
  { "GetLastError",            (SYSCALL)GetLastError,            0 },

#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)

#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
#if SQLITE_OS_WINCE
  /* The GetProcAddressA() routine is only available on Windows CE. */
1000
1001
1002
1003
1004
1005
1006
1007
1008


1009
1010





1011
1012
1013
1014
1015
1016
1017
1018
1016
1017
1018
1019
1020
1021
1022


1023
1024


1025
1026
1027
1028
1029

1030
1031
1032
1033
1034
1035
1036







-
-
+
+
-
-
+
+
+
+
+
-







#else
  { "CreateEventExW",          (SYSCALL)0,                       0 },
#endif

#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
        DWORD,DWORD))aSyscall[62].pCurrent)

#if !SQLITE_OS_WINRT
  { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
/*
** For WaitForSingleObject(), MSDN says:
#else
  { "WaitForSingleObject",     (SYSCALL)0,                       0 },
**
** Minimum supported client: Windows XP [desktop apps | UWP apps]
** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps]
*/
  { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
#endif

#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
        DWORD))aSyscall[63].pCurrent)

#if !SQLITE_OS_WINCE
  { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
#else
1151
1152
1153
1154
1155
1156
1157


































1158
1159
1160
1161
1162
1163
1164
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







#else
  { "FlushViewOfFile",          (SYSCALL)0,                      0 },
#endif

#define osFlushViewOfFile \
        ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)

/*
** If SQLITE_ENABLE_SETLK_TIMEOUT is defined, we require CreateEvent()
** to implement blocking locks with timeouts. MSDN says:
**
** Minimum supported client: Windows XP [desktop apps | UWP apps]
** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps]
*/
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  { "CreateEvent",              (SYSCALL)CreateEvent,            0 },
#else
  { "CreateEvent",              (SYSCALL)0,                      0 },
#endif

#define osCreateEvent ( \
    (HANDLE(WINAPI*) (LPSECURITY_ATTRIBUTES,BOOL,BOOL,LPCSTR)) \
    aSyscall[80].pCurrent \
)

/*
** If SQLITE_ENABLE_SETLK_TIMEOUT is defined, we require CancelIo()
** for the case where a timeout expires and a lock request must be 
** cancelled.
**
** Minimum supported client: Windows XP [desktop apps | UWP apps]
** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps]
*/
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  { "CancelIo",                 (SYSCALL)CancelIo,               0 },
#else
  { "CancelIo",                 (SYSCALL)0,                      0 },
#endif

#define osCancelIo ((BOOL(WINAPI*)(HANDLE))aSyscall[81].pCurrent)

}; /* End of the overrideable system calls */

/*
** This is the xSetSystemCall() method of sqlite3_vfs for all of the
** "win32" VFSes.  Return SQLITE_OK upon successfully updating the
** system call pointer, or SQLITE_NOTFOUND if there is no configurable
** system call named zName.
1449
1450
1451
1452
1453
1454
1455
1456



1457
1458
1459
1460
1461
1462
1463
1501
1502
1503
1504
1505
1506
1507

1508
1509
1510
1511
1512
1513
1514
1515
1516
1517







-
+
+
+







    osGetVersionExW(&sInfo);
    osInterlockedCompareExchange(&sqlite3_os_type,
        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
#endif
  }
  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
#elif SQLITE_TEST
  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2
      || osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0
  ;
#else
  /*
  ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  **       deprecated are always assumed to be based on the NT kernel.
  */
  return 1;
#endif
2535
2536
2537
2538
2539
2540
2541















































































2542
2543
2544
2545
2546
2547
2548
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







    return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  }else{
    return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
                      numBytesHigh);
  }
#endif
}

/*
** Lock a region of nByte bytes starting at offset offset of file hFile.
** Take an EXCLUSIVE lock if parameter bExclusive is true, or a SHARED lock
** otherwise. If nMs is greater than zero and the lock cannot be obtained
** immediately, block for that many ms before giving up.
**
** This function returns SQLITE_OK if the lock is obtained successfully. If
** some other process holds the lock, SQLITE_BUSY is returned if nMs==0, or
** SQLITE_BUSY_TIMEOUT otherwise. Or, if an error occurs, SQLITE_IOERR.
*/
static int winHandleLockTimeout(
  HANDLE hFile,
  DWORD offset,
  DWORD nByte,
  int bExcl,
  DWORD nMs
){
  DWORD flags = LOCKFILE_FAIL_IMMEDIATELY | (bExcl?LOCKFILE_EXCLUSIVE_LOCK:0);
  int rc = SQLITE_OK;
  BOOL ret;

  if( !osIsNT() ){
    ret = winLockFile(&hFile, flags, offset, 0, nByte, 0);
  }else{
    OVERLAPPED ovlp;
    memset(&ovlp, 0, sizeof(OVERLAPPED));
    ovlp.Offset = offset;

#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
    if( nMs!=0 ){
      flags &= ~LOCKFILE_FAIL_IMMEDIATELY;
    }
    ovlp.hEvent = osCreateEvent(NULL, TRUE, FALSE, NULL);
    if( ovlp.hEvent==NULL ){
      return SQLITE_IOERR_LOCK;
    }
#endif

    ret = osLockFileEx(hFile, flags, 0, nByte, 0, &ovlp);

#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
    /* If SQLITE_ENABLE_SETLK_TIMEOUT is defined, then the file-handle was
    ** opened with FILE_FLAG_OVERHEAD specified. In this case, the call to
    ** LockFileEx() may fail because the request is still pending. This can
    ** happen even if LOCKFILE_FAIL_IMMEDIATELY was specified.  
    **
    ** If nMs is 0, then LOCKFILE_FAIL_IMMEDIATELY was set in the flags 
    ** passed to LockFileEx(). In this case, if the operation is pending,
    ** block indefinitely until it is finished.
    **
    ** Otherwise, wait for up to nMs ms for the operation to finish. nMs
    ** may be set to INFINITE.
    */
    if( !ret && GetLastError()==ERROR_IO_PENDING ){
      DWORD nDelay = (nMs==0 ? INFINITE : nMs);
      DWORD res = osWaitForSingleObject(ovlp.hEvent, nDelay);
      if( res==WAIT_OBJECT_0 ){
        ret = TRUE;
      }else if( res==WAIT_TIMEOUT ){
        rc = SQLITE_BUSY_TIMEOUT;
      }else{
        /* Some other error has occurred */
        rc = SQLITE_IOERR_LOCK;
      }

      /* If it is still pending, cancel the LockFileEx() call. */
      osCancelIo(hFile);
    }

    osCloseHandle(ovlp.hEvent);
#endif
  }

  if( rc==SQLITE_OK && !ret ){
    rc = SQLITE_BUSY;
  }
  return rc;
}

/*
** Unlock a file region.
 */
static BOOL winUnlockFile(
  LPHANDLE phFile,
  DWORD offsetLow,
2566
2567
2568
2569
2570
2571
2572








2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588



2589

2590
2591



2592
2593
2594
2595
2596
2597
2598
2599
2600
2601


2602
2603
2604
2605
2606
2607
2608

2609
2610
2611
2612
2613
2614
2615




2616
2617
2618
2619
2620


2621
2622
2623
2624
2625

2626
2627
2628
2629
2630
2631
2632

2633
2634
2635
2636
2637
2638
2639
2640







2641







2642
2643







2644
2645

2646
2647
2648
2649
2650
2651
2652
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727


2728
2729
2730

2731
2732

2733
2734
2735
2736
2737
2738
2739



2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750

2751







2752
2753
2754
2755





2756
2757


2758


2759


2760
2761
2762
2763

2764
2765
2766






2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781


2782
2783
2784
2785
2786
2787
2788

2789
2790
2791
2792
2793
2794
2795
2796
2797







+
+
+
+
+
+
+
+














-
-
+
+
+
-
+

-
+
+
+




-
-
-



+
+






-
+
-
-
-
-
-
-
-
+
+
+
+
-
-
-
-
-
+
+
-
-

-
-
+
-
-




-
+


-
-
-
-
-
-
+
+
+
+
+
+
+

+
+
+
+
+
+
+
-
-
+
+
+
+
+
+
+
-

+







    return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  }else{
    return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
                        numBytesHigh);
  }
#endif
}

/*
** Remove an nByte lock starting at offset iOff from HANDLE h.
*/
static int winHandleUnlock(HANDLE h, int iOff, int nByte){
  BOOL ret = winUnlockFile(&h, iOff, 0, nByte, 0);
  return (ret ? SQLITE_OK : SQLITE_IOERR_UNLOCK);
}

/*****************************************************************************
** The next group of routines implement the I/O methods specified
** by the sqlite3_io_methods object.
******************************************************************************/

/*
** Some Microsoft compilers lack this definition.
*/
#ifndef INVALID_SET_FILE_POINTER
# define INVALID_SET_FILE_POINTER ((DWORD)-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.
** Seek the file handle h to offset nByte of the file.
**
** If successful, return SQLITE_OK. Or, if an error occurs, return an SQLite
** Otherwise, set pFile->lastErrno and return non-zero.
** error code. 
*/
static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
static int winHandleSeek(HANDLE h, sqlite3_int64 iOffset){
  int rc = SQLITE_OK;             /* Return value */

#if !SQLITE_OS_WINRT
  LONG upperBits;                 /* Most sig. 32 bits of new offset */
  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
  DWORD dwRet;                    /* Value returned by SetFilePointer() */
  DWORD lastErrno;                /* Value returned by GetLastError() */

  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));

  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  lowerBits = (LONG)(iOffset & 0xffffffff);

  dwRet = osSetFilePointer(h, lowerBits, &upperBits, FILE_BEGIN);

  /* 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 occurred, it is also necessary to call
  ** GetLastError().
  ** GetLastError().  */
  */
  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);

  if( (dwRet==INVALID_SET_FILE_POINTER
      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
    pFile->lastErrno = lastErrno;
    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  if( dwRet==INVALID_SET_FILE_POINTER ){
    DWORD lastErrno = osGetLastError();
    if( lastErrno!=NO_ERROR ){
      rc = SQLITE_IOERR_SEEK;
                "winSeekFile", pFile->zPath);
    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
    return 1;
  }

    }
  }
  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  return 0;
#else
  /*
  ** Same as above, except that this implementation works for WinRT.
  /* This implementation works for WinRT. */
  */

  LARGE_INTEGER x;                /* The new offset */
  BOOL bRet;                      /* Value returned by SetFilePointerEx() */

  x.QuadPart = iOffset;
  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  bRet = osSetFilePointerEx(h, x, 0, FILE_BEGIN);

  if(!bRet){
    pFile->lastErrno = osGetLastError();
    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
                "winSeekFile", pFile->zPath);
    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
    return 1;
  }
    rc = SQLITE_IOERR_SEEK;
  }
#endif

  OSTRACE(("SEEK file=%p, offset=%lld rc=%s\n", h, iOffset, sqlite3ErrName(rc)));
  return rc;
}

/*
** 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 winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  int rc;
  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  return 0;

  rc = winHandleSeek(pFile->h, iOffset);
  if( rc!=SQLITE_OK ){
    pFile->lastErrno = osGetLastError();
    winLogError(rc, pFile->lastErrno, "winSeekFile", pFile->zPath);
  }
  return rc;
#endif
}


#if SQLITE_MAX_MMAP_SIZE>0
/* Forward references to VFS helper methods used for memory mapped files */
static int winMapfile(winFile*, sqlite3_int64);
static int winUnmapfile(winFile*);
#endif

2898
2899
2900
2901
2902
2903
2904






















































2905
2906
2907
2908
2909
2910
2911
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







  }else{
    winLogIoerr(nRetry, __LINE__);
  }
  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
           osGetCurrentProcessId(), pFile, pFile->h));
  return SQLITE_OK;
}

/*
** Truncate the file opened by handle h to nByte bytes in size.
*/
static int winHandleTruncate(HANDLE h, sqlite3_int64 nByte){ 
  int rc = SQLITE_OK;             /* Return code */
  rc = winHandleSeek(h, nByte);
  if( rc==SQLITE_OK ){
    if( 0==osSetEndOfFile(h) ){
      rc = SQLITE_IOERR_TRUNCATE;
    }
  }
  return rc;
}

/*
** Determine the size in bytes of the file opened by the handle passed as 
** the first argument.
*/
static int winHandleSize(HANDLE h, sqlite3_int64 *pnByte){ 
  int rc = SQLITE_OK;

#if SQLITE_OS_WINRT
  FILE_STANDARD_INFO info;
  BOOL b;
  b = osGetFileInformationByHandleEx(h, FileStandardInfo, &info, sizeof(info));
  if( b ){
    *pnByte = info.EndOfFile.QuadPart;
  }else{
    rc = SQLITE_IOERR_FSTAT;
  }
#else
  DWORD upperBits = 0;
  DWORD lowerBits = 0;

  assert( pnByte );
  lowerBits = osGetFileSize(h, &upperBits);
  *pnByte = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  if( lowerBits==INVALID_FILE_SIZE && osGetLastError()!=NO_ERROR ){
    rc = SQLITE_IOERR_FSTAT;
  }
#endif

  return rc;
}

/*
** Close the handle passed as the only argument.
*/
static void winHandleClose(HANDLE h){
  if( h!=INVALID_HANDLE_VALUE ){
    osCloseHandle(h);
  }
}

/*
** Truncate an open file to a specified size
*/
static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  winFile *pFile = (winFile*)id;  /* File handle object */
  int rc = SQLITE_OK;             /* Return code for this function */
3154
3155
3156
3157
3158
3159
3160
3161

3162

3163
3164
3165
3166
3167
3168
3169
3170
3171
3172

3173
3174
3175
3176
3177
3178
3179
3180
3181

3182
3183
3184
3185
3186
3187
3188
3353
3354
3355
3356
3357
3358
3359

3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371

3372
3373
3374
3375
3376
3377
3378
3379
3380

3381
3382
3383
3384
3385
3386
3387
3388







-
+

+









-
+








-
+







#endif

/*
** Acquire a reader lock.
** Different API routines are called depending on whether or not this
** is Win9x or WinNT.
*/
static int winGetReadLock(winFile *pFile){
static int winGetReadLock(winFile *pFile, int bBlock){
  int res;
  DWORD mask = ~(bBlock ? LOCKFILE_FAIL_IMMEDIATELY : 0);
  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  if( osIsNT() ){
#if SQLITE_OS_WINCE
    /*
    ** NOTE: Windows CE is handled differently here due its lack of the Win32
    **       API LockFileEx.
    */
    res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
#else
    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS&mask, SHARED_FIRST, 0,
                      SHARED_SIZE, 0);
#endif
  }
#ifdef SQLITE_WIN32_HAS_ANSI
  else{
    int lk;
    sqlite3_randomness(sizeof(lk), &lk);
    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS&mask,
                      SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  }
#endif
  if( res == 0 ){
    pFile->lastErrno = osGetLastError();
    /* No need to log a failure to lock */
  }
3269
3270
3271
3272
3273
3274
3275
3276

3277
3278
3279
3280
3281
3282


3283
3284
3285
3286









3287
3288
3289

3290
3291
3292




3293
3294
3295




3296
3297
3298
3299
3300



3301
3302


3303

3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315

3316
3317
3318
3319
3320
3321
3322
3469
3470
3471
3472
3473
3474
3475

3476
3477
3478
3479
3480


3481
3482
3483
3484


3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498


3499
3500
3501
3502
3503


3504
3505
3506
3507
3508
3509
3510


3511
3512
3513
3514
3515
3516
3517

3518
3519
3520



3521
3522
3523
3524
3525
3526

3527
3528
3529
3530
3531
3532
3533
3534







-
+




-
-
+
+


-
-
+
+
+
+
+
+
+
+
+



+

-
-
+
+
+
+

-
-
+
+
+
+



-
-
+
+
+


+
+
-
+


-
-
-






-
+








  /* Make sure the locking sequence is correct
  */
  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  assert( locktype!=PENDING_LOCK );
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );

  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  /* Lock the PENDING_LOCK byte if we need to acquire an EXCLUSIVE lock or
  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
  ** the PENDING_LOCK byte is temporary.
  */
  newLocktype = pFile->locktype;
  if( pFile->locktype==NO_LOCK
   || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
  if( locktype==SHARED_LOCK
   || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
  ){
    int cnt = 3;
    while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
                                         PENDING_BYTE, 0, 1, 0))==0 ){

    /* Flags for the LockFileEx() call. This should be an exclusive lock if
    ** this call is to obtain EXCLUSIVE, or a shared lock if this call is to
    ** obtain SHARED.  */
    int flags = LOCKFILE_FAIL_IMMEDIATELY;
    if( locktype==EXCLUSIVE_LOCK ){
      flags |= LOCKFILE_EXCLUSIVE_LOCK;
    }
    while( cnt>0 ){
      /* Try 3 times to get the pending lock.  This is needed to work
      ** around problems caused by indexing and/or anti-virus software on
      ** Windows systems.
      **
      ** If you are using this code as a model for alternative VFSes, do not
      ** copy this retry logic.  It is a hack intended for Windows only.
      */
      ** copy this retry logic.  It is a hack intended for Windows only.  */
      res = winLockFile(&pFile->h, flags, PENDING_BYTE, 0, 1, 0);
      if( res ) break;

      lastErrno = osGetLastError();
      OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
               pFile->h, cnt, res));
      OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n", 
            pFile->h, cnt, res
      ));

      if( lastErrno==ERROR_INVALID_HANDLE ){
        pFile->lastErrno = lastErrno;
        rc = SQLITE_IOERR_LOCK;
        OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
                 pFile->h, cnt, sqlite3ErrName(rc)));
        OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n", 
              pFile->h, cnt, sqlite3ErrName(rc)
        ));
        return rc;
      }

      cnt--;
      if( cnt ) sqlite3_win32_sleep(1);
      if( cnt>0 ) sqlite3_win32_sleep(1);
    }
    gotPendingLock = res;
    if( !res ){
      lastErrno = osGetLastError();
    }
  }

  /* Acquire a shared lock
  */
  if( locktype==SHARED_LOCK && res ){
    assert( pFile->locktype==NO_LOCK );
    res = winGetReadLock(pFile);
    res = winGetReadLock(pFile, pFile->bBlockOnConnect);
    if( res ){
      newLocktype = SHARED_LOCK;
    }else{
      lastErrno = osGetLastError();
    }
  }

3346
3347
3348
3349
3350
3351
3352
3353

3354
3355
3356
3357
3358
3359
3360
3558
3559
3560
3561
3562
3563
3564

3565
3566
3567
3568
3569
3570
3571
3572







-
+







    (void)winUnlockReadLock(pFile);
    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
                      SHARED_SIZE, 0);
    if( res ){
      newLocktype = EXCLUSIVE_LOCK;
    }else{
      lastErrno = osGetLastError();
      winGetReadLock(pFile);
      winGetReadLock(pFile, 0);
    }
  }

  /* If we are holding a PENDING lock that ought to be released, then
  ** release it now.
  */
  if( gotPendingLock && locktype==SHARED_LOCK ){
3426
3427
3428
3429
3430
3431
3432
3433

3434
3435
3436
3437
3438
3439
3440
3638
3639
3640
3641
3642
3643
3644

3645
3646
3647
3648
3649
3650
3651
3652







-
+







  assert( pFile!=0 );
  assert( locktype<=SHARED_LOCK );
  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  type = pFile->locktype;
  if( type>=EXCLUSIVE_LOCK ){
    winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
    if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
    if( locktype==SHARED_LOCK && !winGetReadLock(pFile, 0) ){
      /* This should never happen.  We should always be able to
      ** reacquire the read lock */
      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
                       "winUnlock", pFile->zPath);
    }
  }
  if( type>=RESERVED_LOCK ){
3636
3637
3638
3639
3640
3641
3642






















3643
3644
3645
3646
3647
3648
3649
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







          rc = winMapfile(pFile, -1);
        }
      }
      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
      return rc;
    }
#endif

#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
    case SQLITE_FCNTL_LOCK_TIMEOUT: {
      int iOld = pFile->iBusyTimeout;
      int iNew = *(int*)pArg;
#if SQLITE_ENABLE_SETLK_TIMEOUT==1
      pFile->iBusyTimeout = (iNew < 0) ? INFINITE : (DWORD)iNew;
#elif SQLITE_ENABLE_SETLK_TIMEOUT==2
      pFile->iBusyTimeout = (DWORD)(!!iNew);
#else
# error "SQLITE_ENABLE_SETLK_TIMEOUT must be set to 1 or 2"
#endif
      *(int*)pArg = iOld;
      return SQLITE_OK;
    }
    case SQLITE_FCNTL_BLOCK_ON_CONNECT: {
      int iNew = *(int*)pArg;
      pFile->bBlockOnConnect = iNew;
      return SQLITE_OK;
    }
#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */

  }
  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  return SQLITE_NOTFOUND;
}

/*
** Return the sector size in bytes of the underlying block device for
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729





3730
3731
3732
3733
3734

3735


3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764

3765
3766
3767
3768
3769
3770

3771
3772
3773
3774
3775
3776
3777
3778
3779
3780


3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3950
3951
3952
3953
3954
3955
3956

3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971

3972
3973
3974
3975
3976
3977


3978
3979
3980
3981
3982
3983
3984
3985

3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000

4001






4002



4003
4004
4005


4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020












































4021
4022
4023
4024
4025
4026
4027







-






+
+
+
+
+




-
+

+
+


-
-








-















-
+
-
-
-
-
-
-
+
-
-
-



-
-


+
+











-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-







** this object or while reading or writing the following fields:
**
**      nRef
**      pNext
**
** The following fields are read-only after the object is created:
**
**      fid
**      zFilename
**
** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
** winShmMutexHeld() is true when reading or writing any other field
** in this structure.
**
** File-handle hSharedShm is used to (a) take the DMS lock, (b) truncate
** the *-shm file if the DMS-locking protocol demands it, and (c) map
** regions of the *-shm file into memory using MapViewOfFile() or 
** similar. Other locks are taken by individual clients using the
** winShm.hShm handles.
*/
struct winShmNode {
  sqlite3_mutex *mutex;      /* Mutex to access this object */
  char *zFilename;           /* Name of the file */
  winFile hFile;             /* File handle from winOpen */
  HANDLE hSharedShm;         /* File handle open on zFilename */

  int isUnlocked;            /* DMS lock has not yet been obtained */
  int isReadonly;            /* True if read-only */
  int szRegion;              /* Size of shared-memory regions */
  int nRegion;               /* Size of array apRegion */
  u8 isReadonly;             /* True if read-only */
  u8 isUnlocked;             /* True if no DMS lock held */

  struct ShmRegion {
    HANDLE hMap;             /* File handle from CreateFileMapping */
    void *pMap;
  } *aRegion;
  DWORD lastErrno;           /* The Windows errno from the last I/O error */

  int nRef;                  /* Number of winShm objects pointing to this */
  winShm *pFirst;            /* All winShm objects pointing to this */
  winShmNode *pNext;         /* Next in list of all winShmNode objects */
#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  u8 nextShmId;              /* Next available winShm.id value */
#endif
};

/*
** A global array of all winShmNode objects.
**
** The winShmMutexHeld() must be true while reading or writing this list.
*/
static winShmNode *winShmNodeList = 0;

/*
** Structure used internally by this VFS to record the state of an
** open shared memory connection.
** open shared memory connection. There is one such structure for each
**
** The following fields are initialized when this object is created and
** are read-only thereafter:
**
**    winShm.pShmNode
**    winShm.id
** winFile open on a wal mode database.
**
** All other fields are read/write.  The winShm.pShmNode->mutex must be held
** while accessing any read/write fields.
*/
struct winShm {
  winShmNode *pShmNode;      /* The underlying winShmNode object */
  winShm *pNext;             /* Next winShm with the same winShmNode */
  u8 hasMutex;               /* True if holding the winShmNode mutex */
  u16 sharedMask;            /* Mask of shared locks held */
  u16 exclMask;              /* Mask of exclusive locks held */
  HANDLE hShm;               /* File-handle on *-shm file. For locking. */
  int bReadonly;             /* True if hShm is opened read-only */
#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  u8 id;                     /* Id of this connection with its winShmNode */
#endif
};

/*
** Constants used for locking
*/
#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */

/*
** Apply advisory locks for all n bytes beginning at ofst.
*/
#define WINSHM_UNLCK  1
#define WINSHM_RDLCK  2
#define WINSHM_WRLCK  3
static int winShmSystemLock(
  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
  int lockType,         /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
  int ofst,             /* Offset to first byte to be locked/unlocked */
  int nByte             /* Number of bytes to lock or unlock */
){
  int rc = 0;           /* Result code form Lock/UnlockFileEx() */

  /* Access to the winShmNode object is serialized by the caller */
  assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );

  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
           pFile->hFile.h, lockType, ofst, nByte));

  /* Release/Acquire the system-level lock */
  if( lockType==WINSHM_UNLCK ){
    rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  }else{
    /* Initialize the locking parameters */
    DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
    if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
    rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  }

  if( rc!= 0 ){
    rc = SQLITE_OK;
  }else{
    pFile->lastErrno =  osGetLastError();
    rc = SQLITE_BUSY;
  }

  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
           pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
           "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));

  return rc;
}

/* Forward references to VFS methods */
static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
static int winDelete(sqlite3_vfs *,const char*,int);

/*
** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
**
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869

3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901






















































3902
3903
3904


3905
3906
3907
3908
3909
3910























3911



















3912
3913
3914
3915
3916




















































3917
3918


3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936

3937
3938
3939
3940
3941
3942
3943
3944
3945
3946


3947
3948
3949






3950
3951

3952
3953
3954
3955
3956

3957
3958
3959
3960

3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971

3972
3973
3974

3975
3976
3977
3978
3979
3980
3981
















3982
3983
3984
3985
3986


3987
3988
3989
3990

3991
3992

3993
3994

3995
3996
3997
3998

3999
4000




4001
4002

4003
4004
4005
4006
4007





4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024


4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048



4049
4050
4051
4052
4053
4054
4055
4056
4057
4058


4059
4060
4061

4062
4063
4064
4065
4066
4067
4068
4069



4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087

4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100



4101
4102


4103
4104
4105
4106










4107
4108
4109
4110

4111
4112
4113
4114
4115




4116
4117
4118
4119
4120



4121
4122

4123
4124
4125

4126
4127
4128
4129
4130





4131
4132
4133
4134
4135







4136
4137
4138

4139


4140
4141
4142

4143
4144
4145

4146
4147
4148






4149
4150
4151
4152
4153
4154






4155
4156

4157
4158


4159
4160
4161
4162
4163
4164







4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175



4176
4177
4178
4179







4180
4181
4182
4183
4184
4185
4186
4045
4046
4047
4048
4049
4050
4051



4052


4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069













4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123



4124
4125






4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168





4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221

4222
4223
4224
4225




4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236

4237

4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258

4259

4260
4261
4262

4263

4264
4265

4266





4267




4268
4269
4270
4271

4272







4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289




4290
4291




4292


4293


4294


4295
4296
4297


4298
4299
4300
4301
4302

4303
4304




4305
4306
4307
4308
4309












4310




4311
4312

4313

4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327

4328
4329
4330
4331


4332
4333
4334





4335




4336
4337
4338
4339

4340

4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364

4365
4366

4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383


4384
4385




4386
4387
4388
4389
4390
4391
4392
4393
4394
4395




4396





4397
4398
4399
4400





4401
4402
4403


4404



4405





4406
4407
4408
4409
4410





4411
4412
4413
4414
4415
4416
4417



4418

4419
4420
4421


4422



4423



4424
4425
4426
4427
4428
4429
4430





4431
4432
4433
4434
4435
4436


4437


4438
4439






4440
4441
4442
4443
4444
4445
4446











4447
4448
4449




4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463







-
-
-
+
-
-

















-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
+
+


-
-
-
-











-
+
-









+
+



+
+
+
+
+
+

-
+
-



-
+
-


-
+
-
-
-
-
-

-
-
-
-

+


-
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
+
+
-
-
-
-
+
-
-
+
-
-
+
-
-


+
-
-
+
+
+
+

-
+

-
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-

-
-
-
-
+
+
-

-














-




-
-
+
+
+
-
-
-
-
-

-
-
-
-
+
+


-
+
-







+
+
+














-


-
+













+
+
+
-
-
+
+
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-
-
-
-
+
-
-
-
-
-
+
+
+
+
-
-
-
-
-
+
+
+
-
-
+
-
-
-
+
-
-
-
-
-
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
+
-
+
+

-
-
+
-
-
-
+
-
-
-
+
+
+
+
+
+

-
-
-
-
-
+
+
+
+
+
+
-
-
+
-
-
+
+
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
+
+
+
-
-
-
-
+
+
+
+
+
+
+







                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
        UNUSED_VARIABLE_VALUE(bRc);
        bRc = osCloseHandle(p->aRegion[i].hMap);
        OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
        UNUSED_VARIABLE_VALUE(bRc);
      }
      if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
        SimulateIOErrorBenign(1);
        winClose((sqlite3_file *)&p->hFile);
      winHandleClose(p->hSharedShm);
        SimulateIOErrorBenign(0);
      }
      if( deleteFlag ){
        SimulateIOErrorBenign(1);
        sqlite3BeginBenignMalloc();
        winDelete(pVfs, p->zFilename, 0);
        sqlite3EndBenignMalloc();
        SimulateIOErrorBenign(0);
      }
      *pp = p->pNext;
      sqlite3_free(p->aRegion);
      sqlite3_free(p);
    }else{
      pp = &p->pNext;
    }
  }
}

/*
** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
** take it now. Return SQLITE_OK if successful, or an SQLite error
** code otherwise.
**
** If the DMS cannot be locked because this is a readonly_shm=1
** connection and no other process already holds a lock, return
** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
*/
static int winLockSharedMemory(winShmNode *pShmNode){
  int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);

  if( rc==SQLITE_OK ){
    if( pShmNode->isReadonly ){
** The DMS lock has not yet been taken on the shm file associated with
** pShmNode. Take the lock. Truncate the *-shm file if required.
** Return SQLITE_OK if successful, or an SQLite error code otherwise.
*/
static int winLockSharedMemory(winShmNode *pShmNode, DWORD nMs){
  HANDLE h = pShmNode->hSharedShm;
  int rc = SQLITE_OK;

  assert( sqlite3_mutex_held(pShmNode->mutex) );
  rc = winHandleLockTimeout(h, WIN_SHM_DMS, 1, 1, 0);
  if( rc==SQLITE_OK ){
    /* We have an EXCLUSIVE lock on the DMS byte. This means that this
    ** is the first process to open the file. Truncate it to zero bytes
    ** in this case.  */
    if( pShmNode->isReadonly ){
      rc = SQLITE_READONLY_CANTINIT;
    }else{
      rc = winHandleTruncate(h, 0);
    }

    /* Release the EXCLUSIVE lock acquired above. */
    winUnlockFile(&h, WIN_SHM_DMS, 0, 1, 0);
  }else if( (rc & 0xFF)==SQLITE_BUSY ){
    rc = SQLITE_OK;
  }

  if( rc==SQLITE_OK ){
    /* Take a SHARED lock on the DMS byte. */
    rc = winHandleLockTimeout(h, WIN_SHM_DMS, 1, 0, nMs);
    if( rc==SQLITE_OK ){
      pShmNode->isUnlocked = 0;
    }
  }

  return rc;
}


/*
** Convert a UTF-8 filename into whatever form the underlying
** operating system wants filenames in.  Space to hold the result
** is obtained from malloc and must be freed by the calling
** function.
*/
static void *winConvertFromUtf8Filename(const char *zFilename){
  void *zConverted = 0;
  if( osIsNT() ){
    zConverted = winUtf8ToUnicode(zFilename);
  }
#ifdef SQLITE_WIN32_HAS_ANSI
  else{
    zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
  }
#endif
      pShmNode->isUnlocked = 1;
      winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
      return SQLITE_READONLY_CANTINIT;
  /* caller will handle out of memory */
  return zConverted;
    }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
      winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
      return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
                         "winLockSharedMemory", pShmNode->zFilename);
    }
  }
}

/*
** This function is used to open a handle on a *-shm file.
**
** If SQLITE_ENABLE_SETLK_TIMEOUT is defined at build time, then the file
** is opened with FILE_FLAG_OVERLAPPED specified. If not, it is not.
*/
static int winHandleOpen(
  const char *zUtf8,              /* File to open */
  int *pbReadonly,                /* IN/OUT: True for readonly handle */
  HANDLE *ph                      /* OUT: New HANDLE for file */
){
  int rc = SQLITE_OK;
  void *zConverted = 0;
  int bReadonly = *pbReadonly;
  HANDLE h = INVALID_HANDLE_VALUE;

#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  const DWORD flag_overlapped = FILE_FLAG_OVERLAPPED;
#else
  const DWORD flag_overlapped = 0;
#endif

  /* Convert the filename to the system encoding. */
  zConverted = winConvertFromUtf8Filename(zUtf8);
  if( zConverted==0 ){
    OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8));
    rc = SQLITE_IOERR_NOMEM_BKPT;
    goto winopenfile_out;
  }

  /* Ensure the file we are trying to open is not actually a directory. */
  if( winIsDir(zConverted) ){
    OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8));
    rc = SQLITE_CANTOPEN_ISDIR;
    goto winopenfile_out;
  }

  /* TODO: platforms.
  ** TODO: retry-on-ioerr.
  */
  if( osIsNT() ){
  if( rc==SQLITE_OK ){
    winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  }

  return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
#if SQLITE_OS_WINRT
    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
    memset(&extendedParameters, 0, sizeof(extendedParameters));
    extendedParameters.dwSize = sizeof(extendedParameters);
    extendedParameters.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
    extendedParameters.dwFileFlags = flag_overlapped;
    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
    h = osCreateFile2((LPCWSTR)zConverted,
        (GENERIC_READ | (bReadonly ? 0 : GENERIC_WRITE)),/* dwDesiredAccess */
        FILE_SHARE_READ | FILE_SHARE_WRITE,      /* dwShareMode */
        OPEN_ALWAYS,                             /* dwCreationDisposition */
        &extendedParameters
    );
#else
    h = osCreateFileW((LPCWSTR)zConverted,         /* lpFileName */
        (GENERIC_READ | (bReadonly ? 0 : GENERIC_WRITE)),  /* dwDesiredAccess */
        FILE_SHARE_READ | FILE_SHARE_WRITE,        /* dwShareMode */
        NULL,                                      /* lpSecurityAttributes */
        OPEN_ALWAYS,                               /* dwCreationDisposition */
        FILE_ATTRIBUTE_NORMAL|flag_overlapped,
        NULL
    );
#endif
  }else{
    /* Due to pre-processor directives earlier in this file, 
    ** SQLITE_WIN32_HAS_ANSI is always defined if osIsNT() is false. */
#ifdef SQLITE_WIN32_HAS_ANSI
    h = osCreateFileA((LPCSTR)zConverted,
        (GENERIC_READ | (bReadonly ? 0 : GENERIC_WRITE)),  /* dwDesiredAccess */
        FILE_SHARE_READ | FILE_SHARE_WRITE,        /* dwShareMode */
        NULL,                                      /* lpSecurityAttributes */
        OPEN_ALWAYS,                               /* dwCreationDisposition */
        FILE_ATTRIBUTE_NORMAL|flag_overlapped,
        NULL
    );
#endif
  }

  if( h==INVALID_HANDLE_VALUE ){
    if( bReadonly==0 ){
      bReadonly = 1;
      rc = winHandleOpen(zUtf8, &bReadonly, &h);
    }else{
      rc = SQLITE_CANTOPEN_BKPT;
    }
  }

 winopenfile_out:
  sqlite3_free(zConverted);
  *pbReadonly = bReadonly;
  *ph = h;
  return rc;
}

 

/*
** Open the shared-memory area associated with database file pDbFd.
**
** When opening a new shared-memory file, if no other instances of that
** file are currently open, in this process or in other processes, then
** the file must be truncated to zero length or have its header cleared.
*/
static int winOpenSharedMemory(winFile *pDbFd){
  struct winShm *p;                  /* The connection to be opened */
  winShmNode *pShmNode = 0;          /* The underlying mmapped file */
  int rc = SQLITE_OK;                /* Result code */
  winShmNode *pNew;                  /* Newly allocated winShmNode */
  int nName;                         /* Size of zName in bytes */

  assert( pDbFd->pShm==0 );    /* Not previously opened */

  /* Allocate space for the new sqlite3_shm object.  Also speculatively
  ** allocate space for a new winShmNode and filename.
  ** allocate space for a new winShmNode and filename.  */
  */
  p = sqlite3MallocZero( sizeof(*p) );
  if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
  nName = sqlite3Strlen30(pDbFd->zPath);
  pNew = sqlite3MallocZero( sizeof(*pShmNode) + (i64)nName + 17 );
  if( pNew==0 ){
    sqlite3_free(p);
    return SQLITE_IOERR_NOMEM_BKPT;
  }
  pNew->zFilename = (char*)&pNew[1];
  pNew->hSharedShm = INVALID_HANDLE_VALUE;
  pNew->isUnlocked = 1;
  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);

  /* Open a file-handle on the *-shm file for this connection. This file-handle
  ** is only used for locking. The mapping of the *-shm file is created using
  ** the shared file handle in winShmNode.hSharedShm.  */
  p->bReadonly = sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0);
  rc = winHandleOpen(pNew->zFilename, &p->bReadonly, &p->hShm);

  /* Look to see if there is an existing winShmNode that can be used.
  ** If no matching winShmNode currently exists, create a new one.
  ** If no matching winShmNode currently exists, then create a new one.  */
  */
  winShmEnterMutex();
  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
    /* TBD need to come up with better match here.  Perhaps
    ** use FILE_ID_BOTH_DIR_INFO Structure.
    ** use FILE_ID_BOTH_DIR_INFO Structure.  */
    */
    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  }
  if( pShmNode ){
  if( pShmNode==0 ){
    sqlite3_free(pNew);
  }else{
    int inFlags = SQLITE_OPEN_WAL;
    int outFlags = 0;

    pShmNode = pNew;
    pNew = 0;
    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
    pShmNode->pNext = winShmNodeList;
    winShmNodeList = pShmNode;

    /* Allocate a mutex for this winShmNode object, if one is required. */
    if( sqlite3GlobalConfig.bCoreMutex ){
      pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
      if( pShmNode->mutex==0 ){
      if( pShmNode->mutex==0 ) rc = SQLITE_IOERR_NOMEM_BKPT;
        rc = SQLITE_IOERR_NOMEM_BKPT;
        goto shm_open_err;
      }
    }

    if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
      inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
    }

    /* Open a file-handle to use for mappings, and for the DMS lock. */
    if( rc==SQLITE_OK ){
      HANDLE h = INVALID_HANDLE_VALUE;
      pShmNode->isReadonly = p->bReadonly;
      rc = winHandleOpen(pNew->zFilename, &pShmNode->isReadonly, &h);
      pShmNode->hSharedShm = h;
    }

    /* If successful, link the new winShmNode into the global list. If an 
    ** error occurred, free the object. */
    if( rc==SQLITE_OK ){
      pShmNode->pNext = winShmNodeList;
      winShmNodeList = pShmNode;
      pNew = 0;
    }else{
      inFlags |= SQLITE_OPEN_READONLY;
    }
    rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
                 (sqlite3_file*)&pShmNode->hFile,
      sqlite3_mutex_free(pShmNode->mutex);
      if( pShmNode->hSharedShm!=INVALID_HANDLE_VALUE ){
                 inFlags, &outFlags);
    if( rc!=SQLITE_OK ){
      rc = winLogError(rc, osGetLastError(), "winOpenShm",
                       pShmNode->zFilename);
        osCloseHandle(pShmNode->hSharedShm);
      goto shm_open_err;
    }
      }
    if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;

    }
    rc = winLockSharedMemory(pShmNode);
    if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  }

  /* If no error has occurred, link the winShm object to the winShmNode and
  /* Make the new connection a child of the winShmNode */
  p->pShmNode = pShmNode;
  ** the winShm to pDbFd.  */
  if( rc==SQLITE_OK ){
    p->pShmNode = pShmNode;
    pShmNode->nRef++;
#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  p->id = pShmNode->nextShmId++;
    p->id = pShmNode->nextShmId++;
#endif
  pShmNode->nRef++;
  pDbFd->pShm = p;
  winShmLeaveMutex();

    pDbFd->pShm = p;
  }else if( p ){
    winHandleClose(p->hShm);
    sqlite3_free(p);
  }
  /* The reference count on pShmNode has already been incremented under
  ** the cover of the winShmEnterMutex() mutex and the pointer from the
  ** new (struct winShm) object to the pShmNode has been set. All that is
  ** left to do is to link the new object into the linked list starting
  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  ** mutex.
  */
  sqlite3_mutex_enter(pShmNode->mutex);
  p->pNext = pShmNode->pFirst;
  pShmNode->pFirst = p;
  sqlite3_mutex_leave(pShmNode->mutex);
  return rc;

  /* Jump here on any error */
shm_open_err:
  winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
  assert( rc!=SQLITE_OK || pShmNode->isUnlocked==0 || pShmNode->nRegion==0 );
  winShmLeaveMutex();
  sqlite3_free(p);
  sqlite3_free(pNew);
  winShmLeaveMutex();
  return rc;
}

/*
** Close a connection to shared-memory.  Delete the underlying
** storage if deleteFlag is true.
*/
static int winShmUnmap(
  sqlite3_file *fd,          /* Database holding shared memory */
  int deleteFlag             /* Delete after closing if true */
){
  winFile *pDbFd;       /* Database holding shared-memory */
  winShm *p;            /* The connection to be closed */
  winShmNode *pShmNode; /* The underlying shared-memory file */
  winShm **pp;          /* For looping over sibling connections */

  pDbFd = (winFile*)fd;
  p = pDbFd->pShm;
  if( p==0 ) return SQLITE_OK;
  pShmNode = p->pShmNode;

  if( p->hShm!=INVALID_HANDLE_VALUE ){
    osCloseHandle(p->hShm);
  }
  /* Remove connection p from the set of connections associated
  ** with pShmNode */
  sqlite3_mutex_enter(pShmNode->mutex);
  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  *pp = p->pNext;

  /* Free the connection p */
  sqlite3_free(p);
  pDbFd->pShm = 0;
  sqlite3_mutex_leave(pShmNode->mutex);
  pShmNode = p->pShmNode;
  winShmEnterMutex();

  /* If pShmNode->nRef has reached 0, then close the underlying
  ** shared-memory file, too */
  ** shared-memory file, too. */
  winShmEnterMutex();
  assert( pShmNode->nRef>0 );
  pShmNode->nRef--;
  if( pShmNode->nRef==0 ){
    winShmPurge(pDbFd->pVfs, deleteFlag);
  }
  winShmLeaveMutex();

  /* Free the connection p */
  sqlite3_free(p);
  pDbFd->pShm = 0;
  return SQLITE_OK;
}

/*
** Change the lock state for a shared-memory segment.
*/
static int winShmLock(
  sqlite3_file *fd,          /* Database file holding the shared memory */
  int ofst,                  /* First lock to acquire or release */
  int n,                     /* Number of locks to acquire or release */
  int flags                  /* What to do with the lock */
){
  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
  winShm *pX;                           /* For looping over all siblings */
  winShmNode *pShmNode;
  int rc = SQLITE_OK;                   /* Result code */
  u16 mask;                             /* Mask of locks to take or release */
  u16 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst)); /* Mask of locks to [un]take */

  if( p==0 ) return SQLITE_IOERR_SHMLOCK;
  pShmNode = p->pShmNode;
  if( NEVER(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK;

  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  assert( n>=1 );
  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );

  /* Check that, if this to be a blocking lock, no locks that occur later
  ** in the following list than the lock being obtained are already held:
  **
  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  assert( n>1 || mask==(1<<ofst) );
  **   1. Checkpointer lock (ofst==1).
  **   2. Write lock (ofst==0).
  sqlite3_mutex_enter(pShmNode->mutex);
  if( flags & SQLITE_SHM_UNLOCK ){
    u16 allMask = 0; /* Mask of locks held by siblings */

  **   3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
  **
  ** In other words, if this is a blocking lock, none of the locks that
  ** occur later in the above list than the lock being obtained may be
  ** held.
  **
  ** It is not permitted to block on the RECOVER lock.
  */
#if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && defined(SQLITE_DEBUG)
  {
    /* See if any siblings hold this same lock */
    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
      if( pX==p ) continue;
      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
    u16 lockMask = (p->exclMask|p->sharedMask);
      allMask |= pX->sharedMask;
    }

    /* Unlock the system-level locks */
    if( (mask & allMask)==0 ){
    assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
          (ofst!=2)                                   /* not RECOVER */
       && (ofst!=1 || lockMask==0 || lockMask==2)
       && (ofst!=0 || lockMask<3)
      rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
    }else{
      rc = SQLITE_OK;
    }

       && (ofst<3  || lockMask<(1<<ofst))
    ));
  }
    /* Undo the local locks */
    if( rc==SQLITE_OK ){
#endif
      p->exclMask &= ~mask;
      p->sharedMask &= ~mask;
    }

  }else if( flags & SQLITE_SHM_SHARED ){
    u16 allShared = 0;  /* Union of locks held by connections other than "p" */

    /* Find out which shared locks are already held by sibling connections.
    ** If any sibling already holds an exclusive lock, go ahead and return
  /* Check if there is any work to do. There are three cases:
  **
  **    a) An unlock operation where there are locks to unlock,
  **    b) An shared lock where the requested lock is not already held
  **    c) An exclusive lock where the requested lock is not already held
    ** SQLITE_BUSY.
    */
    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
      if( (pX->exclMask & mask)!=0 ){
        rc = SQLITE_BUSY;
  **
  ** The SQLite core never requests an exclusive lock that it already holds.
  ** This is assert()ed immediately below.  */
  assert( flags!=(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK) 
       || 0==(p->exclMask & mask)
  );
  if( ((flags & SQLITE_SHM_UNLOCK) && ((p->exclMask|p->sharedMask) & mask))
        break;
      }
      allShared |= pX->sharedMask;
   || (flags==(SQLITE_SHM_SHARED|SQLITE_SHM_LOCK) && 0==(p->sharedMask & mask))
    }
   || (flags==(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK))
  ){

    /* Get shared locks at the system level, if necessary */
    if( rc==SQLITE_OK ){
    if( flags & SQLITE_SHM_UNLOCK ){
      if( (allShared & mask)==0 ){
        rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
      }else{
      /* Case (a) - unlock.  */
        rc = SQLITE_OK;
      }
    }

      assert( (p->exclMask & p->sharedMask)==0 );
      assert( !(flags & SQLITE_SHM_EXCLUSIVE) || (p->exclMask & mask)==mask );
      assert( !(flags & SQLITE_SHM_SHARED) || (p->sharedMask & mask)==mask );

      rc = winHandleUnlock(p->hShm, ofst+WIN_SHM_BASE, n);

    /* Get the local shared locks */
    if( rc==SQLITE_OK ){
      p->sharedMask |= mask;
    }
  }else{
      /* If successful, also clear the bits in sharedMask/exclMask */
      if( rc==SQLITE_OK ){
        p->exclMask = (p->exclMask & ~mask);
        p->sharedMask = (p->sharedMask & ~mask);
      }
    }else{
    /* Make sure no sibling connections hold locks that will block this
    ** lock.  If any do, return SQLITE_BUSY right away.
      int bExcl = ((flags & SQLITE_SHM_EXCLUSIVE) ? 1 : 0);
    */
    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
      DWORD nMs = winFileBusyTimeout(pDbFd);
      rc = winHandleLockTimeout(p->hShm, ofst+WIN_SHM_BASE, n, bExcl, nMs);
      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
        rc = SQLITE_BUSY;
        break;
      }
    }

      if( rc==SQLITE_OK ){
        if( bExcl ){
          p->exclMask = (p->exclMask | mask);
        }else{
          p->sharedMask = (p->sharedMask | mask);
        }
      }
    /* Get the exclusive locks at the system level.  Then if successful
    ** also mark the local connection as being locked.
    */
    if( rc==SQLITE_OK ){
      rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
      if( rc==SQLITE_OK ){
        assert( (p->sharedMask & mask)==0 );
        p->exclMask |= mask;
      }
    }
  }
    }
  }

  sqlite3_mutex_leave(pShmNode->mutex);
  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
           osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
           sqlite3ErrName(rc)));
  OSTRACE((
      "SHM-LOCK(%d,%d,%d) pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x,"
      " rc=%s\n",
      ofst, n, flags, 
      osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
      sqlite3ErrName(rc))
  );
  return rc;
}

/*
** Implement a memory barrier or memory fence on shared memory.
**
** All loads and stores begun before the barrier must complete before
4234
4235
4236
4237
4238
4239
4240


4241

4242
4243
4244
4245
4246

4247

4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258

4259
4260
4261

4262
4263
4264
4265
4266
4267
4268
4269
4270

4271
4272
4273

4274
4275
4276

4277
4278
4279
4280
4281
4282

4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301

4302
4303
4304
4305

4306
4307
4308
4309

4310
4311
4312

4313
4314
4315
4316
4317
4318
4319
4511
4512
4513
4514
4515
4516
4517
4518
4519

4520
4521

4522

4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536

4537
4538


4539
4540
4541
4542
4543
4544
4545
4546
4547

4548

4549

4550
4551


4552
4553
4554
4555
4556
4557

4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576

4577


4578

4579


4580

4581


4582
4583
4584
4585
4586
4587
4588
4589
4590







+
+
-
+

-

-

+

+










-
+

-
-
+








-
+
-

-
+

-
-
+





-
+


















-
+
-
-

-
+
-
-

-
+
-
-

+







    pShm = pDbFd->pShm;
    assert( pShm!=0 );
  }
  pShmNode = pShm->pShmNode;

  sqlite3_mutex_enter(pShmNode->mutex);
  if( pShmNode->isUnlocked ){
    /* Take the DMS lock. */
    assert( pShmNode->nRegion==0 );
    rc = winLockSharedMemory(pShmNode);
    rc = winLockSharedMemory(pShmNode, winFileBusyTimeout(pDbFd));
    if( rc!=SQLITE_OK ) goto shmpage_out;
    pShmNode->isUnlocked = 0;
  }
  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );

  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  if( pShmNode->nRegion<=iRegion ){
    HANDLE hShared = pShmNode->hSharedShm;
    struct ShmRegion *apNew;           /* New aRegion[] array */
    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
    sqlite3_int64 sz;                  /* Current size of wal-index file */

    pShmNode->szRegion = szRegion;

    /* The requested region is not mapped into this processes address space.
    ** Check to see if it has been allocated (i.e. if the wal-index file is
    ** large enough to contain the requested region).
    */
    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
    rc = winHandleSize(hShared, &sz);
    if( rc!=SQLITE_OK ){
      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
                       "winShmMap1", pDbFd->zPath);
      rc = winLogError(rc, osGetLastError(), "winShmMap1", pDbFd->zPath);
      goto shmpage_out;
    }

    if( sz<nByte ){
      /* The requested memory region does not exist. If isWrite is set to
      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
      **
      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
      ** the requested memory region.
      ** the requested memory region.  */
      */
      if( !isWrite ) goto shmpage_out;
      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
      rc = winHandleTruncate(hShared, nByte);
      if( rc!=SQLITE_OK ){
        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
                         "winShmMap2", pDbFd->zPath);
        rc = winLogError(rc, osGetLastError(), "winShmMap2", pDbFd->zPath);
        goto shmpage_out;
      }
    }

    /* Map the requested memory region into this processes address space. */
    apNew = (struct ShmRegion *)sqlite3_realloc64(
    apNew = (struct ShmRegion*)sqlite3_realloc64(
        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
    );
    if( !apNew ){
      rc = SQLITE_IOERR_NOMEM_BKPT;
      goto shmpage_out;
    }
    pShmNode->aRegion = apNew;

    if( pShmNode->isReadonly ){
      protect = PAGE_READONLY;
      flags = FILE_MAP_READ;
    }

    while( pShmNode->nRegion<=iRegion ){
      HANDLE hMap = NULL;         /* file-mapping handle */
      void *pMap = 0;             /* Mapped memory region */

#if SQLITE_OS_WINRT
      hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
      hMap = osCreateFileMappingFromApp(hShared, NULL, protect, nByte, NULL);
          NULL, protect, nByte, NULL
      );
#elif defined(SQLITE_WIN32_HAS_WIDE)
      hMap = osCreateFileMappingW(pShmNode->hFile.h,
      hMap = osCreateFileMappingW(hShared, NULL, protect, 0, nByte, NULL);
          NULL, protect, 0, nByte, NULL
      );
#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
      hMap = osCreateFileMappingA(pShmNode->hFile.h,
      hMap = osCreateFileMappingA(hShared, NULL, protect, 0, nByte, NULL);
          NULL, protect, 0, nByte, NULL
      );
#endif

      OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
               osGetCurrentProcessId(), pShmNode->nRegion, nByte,
               hMap ? "ok" : "failed"));
      if( hMap ){
        int iOffset = pShmNode->nRegion*szRegion;
        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
#if SQLITE_OS_WINRT
4348
4349
4350
4351
4352
4353
4354
4355



4356
4357
4358
4359
4360
4361
4362
4619
4620
4621
4622
4623
4624
4625

4626
4627
4628
4629
4630
4631
4632
4633
4634
4635







-
+
+
+







    int iOffset = iRegion*szRegion;
    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
    *pp = (void *)&p[iOffsetShift];
  }else{
    *pp = 0;
  }
  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  if( pShmNode->isReadonly && rc==SQLITE_OK ){
    rc = SQLITE_READONLY;
  }
  sqlite3_mutex_leave(pShmNode->mutex);
  return rc;
}

#else
# define winShmMap     0
# define winShmLock    0
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4962
4963
4964
4965
4966
4967
4968




















4969
4970
4971
4972
4973
4974
4975







-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-







  }
#endif
  /* caller will handle out of memory */
  return zConverted;
}
#endif

/*
** Convert a UTF-8 filename into whatever form the underlying
** operating system wants filenames in.  Space to hold the result
** is obtained from malloc and must be freed by the calling
** function.
*/
static void *winConvertFromUtf8Filename(const char *zFilename){
  void *zConverted = 0;
  if( osIsNT() ){
    zConverted = winUtf8ToUnicode(zFilename);
  }
#ifdef SQLITE_WIN32_HAS_ANSI
  else{
    zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
  }
#endif
  /* caller will handle out of memory */
  return zConverted;
}

/*
** This function returns non-zero if the specified UTF-8 string buffer
** ends with a directory separator character or one was successfully
** added to it.
*/
static int winMakeEndInDirSep(int nBuf, char *zBuf){
  if( zBuf ){
6162
6163
6164
6165
6166
6167
6168
6169

6170
6171
6172
6173
6174
6175
6176
6415
6416
6417
6418
6419
6420
6421

6422
6423
6424
6425
6426
6427
6428
6429







-
+







    winGetSystemCall,      /* xGetSystemCall */
    winNextSystemCall,     /* xNextSystemCall */
  };
#endif

  /* Double-check that the aSyscall[] array has been constructed
  ** correctly.  See ticket [bb3a86e890c8e96ab] */
  assert( ArraySize(aSyscall)==80 );
  assert( ArraySize(aSyscall)==82 );

  /* get memory map allocation granularity */
  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
#if SQLITE_OS_WINRT
  osGetNativeSystemInfo(&winSysInfo);
#else
  osGetSystemInfo(&winSysInfo);
Changes to src/sqlite.h.in.
1159
1160
1161
1162
1163
1164
1165





1166
1167
1168
1169
1170
1171
1172
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177







+
+
+
+
+







** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS
** to block for up to M milliseconds before failing when attempting to
** obtain a file lock using the xLock or xShmLock methods of the VFS.
** The parameter is a pointer to a 32-bit signed integer that contains
** the value that M is to be set to. Before returning, the 32-bit signed
** integer is overwritten with the previous value of M.
**
** <li>[[SQLITE_FCNTL_BLOCK_ON_CONNECT]]
** The [SQLITE_FCNTL_BLOCK_ON_CONNECT] opcode is used to configure the
** VFS to block when taking SHARED locks. This is used to implement the
** functionality associated with SQLITE_SETLK_BLOCK_ON_CONNECT.
**
** <li>[[SQLITE_FCNTL_DATA_VERSION]]
** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
** a database file.  The argument is a pointer to a 32-bit unsigned integer.
** The "data version" for the pager is written into the pointer.  The
** "data version" changes whenever any change occurs to the corresponding
** database file, either through SQL statements on the same database
** connection or through transactions committed by separate database
1255
1256
1257
1258
1259
1260
1261

1262
1263
1264
1265
1266
1267
1268
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274







+







#define SQLITE_FCNTL_CKPT_DONE              37
#define SQLITE_FCNTL_RESERVE_BYTES          38
#define SQLITE_FCNTL_CKPT_START             39
#define SQLITE_FCNTL_EXTERNAL_READER        40
#define SQLITE_FCNTL_CKSM_FILE              41
#define SQLITE_FCNTL_RESET_CACHE            42
#define SQLITE_FCNTL_NULL_IO                43
#define SQLITE_FCNTL_BLOCK_ON_CONNECT       44

/* deprecated names */
#define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
#define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
#define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO


3011
3012
3013
3014
3015
3016
3017






































3018
3019
3020
3021
3022
3023
3024
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







** was defined  (using [sqlite3_busy_handler()]) prior to calling
** this routine, that other busy handler is cleared.)^
**
** See also:  [PRAGMA busy_timeout]
*/
int sqlite3_busy_timeout(sqlite3*, int ms);

/*
** CAPI3REF: Set the Setlk Timeout
** METHOD: sqlite3
**
** This routine is only useful in SQLITE_ENABLE_SETLK_TIMEOUT builds. If 
** the VFS supports blocking locks, it sets the timeout in ms used by 
** eligible locks taken on wal mode databases by the specified database 
** handle. In non-SQLITE_ENABLE_SETLK_TIMEOUT builds, or if the VFS does
** not support blocking locks, this function is a no-op.
**
** Passing 0 to this function disables blocking locks altogether. Passing 
** -1 to this function requests that the VFS blocks for a long time - 
** indefinitely if possible. The results of passing any other negative value 
** are undefined.
**
** Internally, each SQLite database handle store two timeout values - the
** busy-timeout (used for rollback mode databases, or if the VFS does not
** support blocking locks) and the setlk-timeout (used for blocking locks
** on wal-mode databases). The sqlite3_busy_timeout() method sets both
** values, this function sets only the setlk-timeout value. Therefore,
** to configure separate busy-timeout and setlk-timeout values for a single
** database handle, call sqlite3_busy_timeout() followed by this function.
**
** Whenever the number of connections to a wal mode database falls from
** 1 to 0, the last connection takes an exclusive lock on the database, 
** then checkpoints and deletes the wal file. While it is doing this, any
** new connection that tries to read from the database fails with an
** SQLITE_BUSY error. Or, if the SQLITE_SETLK_BLOCK_ON_CONNECT flag is
** passed to this API, the new connection blocks until the exclusive lock
** has been released.
*/
int sqlite3_setlk_timeout(sqlite3*, int ms, int flags);

/*
** CAPI3REF: Flags for sqlite3_setlk_timeout()
*/
#define SQLITE_SETLK_BLOCK_ON_CONNECT 0x01

/*
** CAPI3REF: Convenience Routines For Running Queries
** METHOD: sqlite3
**
** This is a legacy interface that is preserved for backwards compatibility.
** Use of this interface is not recommended.
**
Changes to src/sqliteInt.h.
1757
1758
1759
1760
1761
1762
1763




1764
1765
1766
1767
1768
1769
1770
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774







+
+
+
+







  Hash aFunc;                   /* Hash table of connection functions */
  Hash aCollSeq;                /* All collating sequences */
  BusyHandler busyHandler;      /* Busy callback */
  Db aDbStatic[2];              /* Static space for the 2 default backends */
  Savepoint *pSavepoint;        /* List of active savepoints */
  int nAnalysisLimit;           /* Number of index rows to ANALYZE */
  int busyTimeout;              /* Busy handler timeout, in msec */
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  int setlkTimeout;             /* Blocking lock timeout, in msec. -1 -> inf. */
  int setlkFlags;               /* Flags passed to setlk_timeout() */
#endif
  int nSavepoint;               /* Number of non-transaction savepoints */
  int nStatement;               /* Number of nested statement-transactions  */
  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
  i64 nDeferredImmCons;         /* Net deferred immediate constraints */
  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
  DbClientData *pDbData;        /* sqlite3_set_clientdata() content */
#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
Changes to src/test1.c.
5941
5942
5943
5944
5945
5946
5947




































5948
5949
5950
5951
5952
5953
5954
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  if( Tcl_GetInt(interp, argv[2], &ms) ) return TCL_ERROR;
  rc = sqlite3_busy_timeout(db, ms);
  Tcl_AppendResult(interp, sqlite3ErrName(rc), 0);
  return TCL_OK;
}

/*
** Usage: sqlite3_setlk_timeout ?-blockonconnect? DB MS
**
** Set the setlk timeout.
*/
static int SQLITE_TCLAPI test_setlk_timeout(
  void * clientData,
  Tcl_Interp *interp,
  int argc,
  char **argv
){
  int rc, ms;
  sqlite3 *db;
  int bBlockOnConnect = 0;

  if( argc==4 ){
    const char *zArg = argv[1];
    int nArg = strlen(zArg);
    if( nArg>=2 && nArg<=15 && memcmp(zArg, "-blockonconnect", nArg)==0 ){
      bBlockOnConnect = 1;
    }
  }
  if( argc!=(3+bBlockOnConnect) ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
        " ?-blockonconnect? DB MS", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[argc-2], &db) ) return TCL_ERROR;
  if( Tcl_GetInt(interp, argv[argc-1], &ms) ) return TCL_ERROR;
  rc = sqlite3_setlk_timeout(
      db, ms, (bBlockOnConnect ? SQLITE_SETLK_BLOCK_ON_CONNECT : 0)
  );
  Tcl_AppendResult(interp, sqlite3ErrName(rc), 0);
  return TCL_OK;
}

/*
** Usage:  tcl_variable_type VARIABLENAME
**
** Return the name of the internal representation for the
** value of the given variable.
*/
7935
7936
7937
7938
7939
7940
7941
7942

7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957


7958
7959
7960
7961
7962
7963
7964
7965

7966

7967
7968

7969
7970
7971
7972
7973
7974



7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994



7995
7996
7997
7998



7999
8000
8001
8002
8003
8004






8005
8006

8007
8008
8009
8010

8011
8012
8013
8014

8015
8016
8017
8018
8019





8020
8021
8022
8023
8024








8025
8026
8027
8028
8029
8030
8031
7971
7972
7973
7974
7975
7976
7977

7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004

8005
8006

8007
8008
8009
8010
8011


8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033

8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056

8057
8058
8059
8060

8061
8062
8063
8064

8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075





8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090







-
+















+
+








+
-
+

-
+




-
-
+
+
+



















-
+
+
+




+
+
+






+
+
+
+
+
+

-
+



-
+



-
+





+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
+
+
+







#if SQLITE_OS_WIN
/*
** Information passed from the main thread into the windows file locker
** background thread.
*/
struct win32FileLocker {
  char *evName;       /* Name of event to signal thread startup */
  HANDLE h;           /* Handle of the file to be locked */
  sqlite3_file *pFd;  /* Handle of the file to be locked */
  int delay1;         /* Delay before locking */
  int delay2;         /* Delay before unlocking */
  int ok;             /* Finished ok */
  int err;            /* True if an error occurs */
};
#endif


#if SQLITE_OS_WIN
#include <process.h>
/*
** The background thread that does file locking.
*/
static void SQLITE_CDECL win32_file_locker(void *pAppData){
  struct win32FileLocker *p = (struct win32FileLocker*)pAppData;
  sqlite3_file *pFd = p->pFd;
  HANDLE h = INVALID_HANDLE_VALUE;
  if( p->evName ){
    HANDLE ev = OpenEvent(EVENT_MODIFY_STATE, FALSE, p->evName);
    if ( ev ){
      SetEvent(ev);
      CloseHandle(ev);
    }
  }
  if( p->delay1 ) Sleep(p->delay1);
  pFd->pMethods->xFileControl(pFd, SQLITE_FCNTL_WIN32_GET_HANDLE, (void*)&h);
  if( LockFile(p->h, 0, 0, 100000000, 0) ){
  if( LockFile(h, 0, 0, 100000000, 0) ){
    Sleep(p->delay2);
    UnlockFile(p->h, 0, 0, 100000000, 0);
    UnlockFile(h, 0, 0, 100000000, 0);
    p->ok = 1;
  }else{
    p->err = 1;
  }
  CloseHandle(p->h);
  p->h = 0;
  pFd->pMethods->xClose(pFd);
  sqlite3_free(pFd);
  p->pFd = 0;
  p->delay1 = 0;
  p->delay2 = 0;
}
#endif

#if SQLITE_OS_WIN
/*
**      lock_win32_file FILENAME DELAY1 DELAY2
**
** Get an exclusive manditory lock on file for DELAY2 milliseconds.
** Wait DELAY1 milliseconds before acquiring the lock.
*/
static int SQLITE_TCLAPI win32_file_lock(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  static struct win32FileLocker x = { "win32_file_lock", 0, 0, 0, 0, 0 };
  const char *zFilename;
  const char *zFilename = 0;
  Tcl_Size nFilename = 0;
  char *zTerm = 0;
  char zBuf[200];
  int retry = 0;
  HANDLE ev;
  DWORD wResult;
  sqlite3_vfs *pVfs = 0;
  int flags = SQLITE_OPEN_MAIN_DB | SQLITE_OPEN_READWRITE;
  int rc = SQLITE_OK;
  
  if( objc!=4 && objc!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, "FILENAME DELAY1 DELAY2");
    return TCL_ERROR;
  }
  if( objc==1 ){
    HANDLE h = INVALID_HANDLE_VALUE;
    if( x.pFd ){
      x.pFd->pMethods->xFileControl(
          x.pFd, SQLITE_FCNTL_WIN32_GET_HANDLE, (void*)&h
      );
    }
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%d %d %d %d %d",
                     x.ok, x.err, x.delay1, x.delay2, x.h);
                     x.ok, x.err, x.delay1, x.delay2, h);
    Tcl_AppendResult(interp, zBuf, (char*)0);
    return TCL_OK;
  }
  while( x.h && retry<30 ){
  while( x.pFd && retry<30 ){
    retry++;
    Sleep(100);
  }
  if( x.h ){
  if( x.pFd ){
    Tcl_AppendResult(interp, "busy", (char*)0);
    return TCL_ERROR;
  }
  if( Tcl_GetIntFromObj(interp, objv[2], &x.delay1) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[3], &x.delay2) ) return TCL_ERROR;
  pVfs = sqlite3_vfs_find(0);
  x.pFd = (sqlite3_file*)sqlite3_malloc(pVfs->szOsFile);

  /* xOpen() must be passed a dual-nul-terminated string preceded in memory
  ** by 4 0x00 bytes.  */
  zFilename = Tcl_GetString(objv[1]);
  x.h = CreateFile(zFilename, GENERIC_READ|GENERIC_WRITE,
              FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_ALWAYS,
              FILE_ATTRIBUTE_NORMAL, 0);
  if( !x.h ){
  zFilename = Tcl_GetStringFromObj(objv[1], &nFilename);
  zTerm = (char*)sqlite3_malloc(nFilename+6);
  memset(zTerm, 0, nFilename+6);
  memcpy(&zTerm[4], zFilename, nFilename);
  rc = pVfs->xOpen(pVfs, &zTerm[4], x.pFd, flags, &flags);
  sqlite3_free(zTerm);

  if( rc!=SQLITE_OK ){
    Tcl_AppendResult(interp, "cannot open file: ", zFilename, (char*)0);
    return TCL_ERROR;
  }
  ev = CreateEvent(NULL, TRUE, FALSE, x.evName);
  if ( !ev ){
    Tcl_AppendResult(interp, "cannot create event: ", x.evName, (char*)0);
    return TCL_ERROR;
8844
8845
8846
8847
8848
8849
8850

8851
8852
8853
8854
8855
8856
8857
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917







+







     { "sqlite3_rekey",                 (Tcl_CmdProc*)test_rekey            },
     { "sqlite3_interrupt",             (Tcl_CmdProc*)test_interrupt        },
     { "sqlite3_is_interrupted",        (Tcl_CmdProc*)test_is_interrupted   },
     { "sqlite_delete_function",        (Tcl_CmdProc*)delete_function       },
     { "sqlite_delete_collation",       (Tcl_CmdProc*)delete_collation      },
     { "sqlite3_get_autocommit",        (Tcl_CmdProc*)get_autocommit        },
     { "sqlite3_busy_timeout",          (Tcl_CmdProc*)test_busy_timeout     },
     { "sqlite3_setlk_timeout",         (Tcl_CmdProc*)test_setlk_timeout    },
     { "printf",                        (Tcl_CmdProc*)test_printf           },
     { "sqlite3IoTrace",              (Tcl_CmdProc*)test_io_trace         },
     { "clang_sanitize_address",        (Tcl_CmdProc*)clang_sanitize_address },
  };
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
Changes to src/test_config.c.
83
84
85
86
87
88
89






90
91
92
93
94
95
96
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102







+
+
+
+
+
+







#endif

#ifdef SQLITE_WIN32_MALLOC
  Tcl_SetVar2(interp, "sqlite_options", "win32malloc", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "win32malloc", "0", TCL_GLOBAL_ONLY);
#endif

#if defined(SQLITE_OS_WINRT) && SQLITE_OS_WINRT
  Tcl_SetVar2(interp, "sqlite_options", "winrt", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "winrt", "0", TCL_GLOBAL_ONLY);
#endif

#ifdef SQLITE_DEBUG
  Tcl_SetVar2(interp, "sqlite_options", "debug", "1", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "debug", "0", TCL_GLOBAL_ONLY);
#endif

776
777
778
779
780
781
782







783
784
785
786
787
788
789
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802







+
+
+
+
+
+
+







#endif

#ifdef SQLITE_OMIT_WINDOWFUNC
  Tcl_SetVar2(interp, "sqlite_options", "windowfunc", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "windowfunc", "1", TCL_GLOBAL_ONLY);
#endif

#if !defined(SQLITE_ENABLE_SETLK_TIMEOUT)
  Tcl_SetVar2(interp, "sqlite_options", "setlk_timeout", "0", TCL_GLOBAL_ONLY);
#else
  Tcl_SetVar2(interp, "sqlite_options", "setlk_timeout", 
      STRINGVALUE(SQLITE_ENABLE_SETLK_TIMEOUT), TCL_GLOBAL_ONLY);
#endif

#define LINKVAR(x) { \
    static const int cv_ ## x = SQLITE_ ## x; \
    Tcl_LinkVar(interp, "SQLITE_" #x, (char *)&(cv_ ## x), \
                TCL_LINK_INT | TCL_LINK_READ_ONLY); }

  LINKVAR( MAX_LENGTH );
Changes to src/test_quota.c.
385
386
387
388
389
390
391



392

393
394
395
396
397
398
399
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403







+
+
+

+








  n = strlen(zUtf8);
  nWide = MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, NULL, 0);
  if( nWide==0 ) return 0;
  zTmpWide = (LPWSTR)sqlite3_malloc( (nWide+1)*sizeof(zTmpWide[0]) );
  if( zTmpWide==0 ) return 0;
  MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, zTmpWide, nWide);
#ifdef SQLITE_OS_WINRT
  codepage = CP_ACP;
#else
  codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
#endif
  nMbcs = WideCharToMultiByte(codepage, 0, zTmpWide, nWide, 0, 0, 0, 0);
  zMbcs = nMbcs ? (char*)sqlite3_malloc( nMbcs+1 ) : 0;
  if( zMbcs ){
    WideCharToMultiByte(codepage, 0, zTmpWide, nWide, zMbcs, nMbcs, 0, 0);
  }
  sqlite3_free(zTmpWide);
  return zMbcs;
Changes to src/test_vfs.c.
126
127
128
129
130
131
132

133
134

135
136
137
138
139
140
141
126
127
128
129
130
131
132
133
134

135
136
137
138
139
140
141
142







+

-
+







#define TESTVFS_ACCESS_MASK       0x00004000
#define TESTVFS_FULLPATHNAME_MASK 0x00008000
#define TESTVFS_READ_MASK         0x00010000
#define TESTVFS_UNLOCK_MASK       0x00020000
#define TESTVFS_LOCK_MASK         0x00040000
#define TESTVFS_CKLOCK_MASK       0x00080000
#define TESTVFS_FCNTL_MASK        0x00100000
#define TESTVFS_SLEEP_MASK        0x00200000

#define TESTVFS_ALL_MASK          0x001FFFFF
#define TESTVFS_ALL_MASK          0x003FFFFF


#define TESTVFS_MAX_PAGES 1024

/*
** A shared-memory buffer. There is one of these objects for each shared
** memory region opened by clients. If two clients open the same file,
809
810
811
812
813
814
815




816
817
818
819
820
821
822
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827







+
+
+
+







}

/*
** Sleep for nMicro microseconds. Return the number of microseconds 
** actually slept.
*/
static int tvfsSleep(sqlite3_vfs *pVfs, int nMicro){
  Testvfs *p = (Testvfs *)pVfs->pAppData;
  if( p->pScript && (p->mask&TESTVFS_SLEEP_MASK) ){
    tvfsExecTcl(p, "xSleep", Tcl_NewIntObj(nMicro), 0, 0, 0);
  }
  return sqlite3OsSleep(PARENTVFS(pVfs), nMicro);
}

/*
** Return the current time as a Julian Day number in *pTimeOut.
*/
static int tvfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
1193
1194
1195
1196
1197
1198
1199

1200
1201
1202
1203
1204
1205
1206
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212







+







        { "xClose",             TESTVFS_CLOSE_MASK },
        { "xAccess",            TESTVFS_ACCESS_MASK },
        { "xFullPathname",      TESTVFS_FULLPATHNAME_MASK },
        { "xUnlock",            TESTVFS_UNLOCK_MASK },
        { "xLock",              TESTVFS_LOCK_MASK },
        { "xCheckReservedLock", TESTVFS_CKLOCK_MASK },
        { "xFileControl",       TESTVFS_FCNTL_MASK },
        { "xSleep",             TESTVFS_SLEEP_MASK },
      };
      Tcl_Obj **apElem = 0;
      Tcl_Size nElem = 0;
      int mask = 0;
      if( objc!=3 ){
        Tcl_WrongNumArgs(interp, 2, objv, "LIST");
        return TCL_ERROR;
Changes to src/wal.c.
498
499
500
501
502
503
504





505
506
507
508
509
510
511
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516







+
+
+
+
+







#define walFrameOffset(iFrame, szPage) (                               \
  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
)

/*
** An open write-ahead log file is represented by an instance of the
** following object.
**
** writeLock:
**   This is usually set to 1 whenever the WRITER lock is held. However,
**   if it is set to 2, then the WRITER lock is held but must be released
**   by walHandleException() if a SEH exception is thrown.
*/
struct Wal {
  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
  sqlite3_file *pDbFd;       /* File handle for the database file */
  sqlite3_file *pWalFd;      /* File handle for WAL file */
  u32 iCallback;             /* Value to pass to log callback (or 0) */
  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
2023
2024
2025
2026
2027
2028
2029
2030

2031
2032
2033
2034
2035
2036
2037
2028
2029
2030
2031
2032
2033
2034

2035
2036
2037
2038
2039
2040
2041
2042







-
+







** they are supported by the VFS, and (b) the database handle is configured
** with a busy-timeout. Return 1 if blocking locks are successfully enabled,
** or 0 otherwise.
*/
static int walEnableBlocking(Wal *pWal){
  int res = 0;
  if( pWal->db ){
    int tmout = pWal->db->busyTimeout;
    int tmout = pWal->db->setlkTimeout;
    if( tmout ){
      res = walEnableBlockingMs(pWal, tmout);
    }
  }
  return res;
}

2409
2410
2411
2412
2413
2414
2415


2416

2417
2418
2419
2420
2421
2422
2423
2414
2415
2416
2417
2418
2419
2420
2421
2422

2423
2424
2425
2426
2427
2428
2429
2430







+
+
-
+







**   4) Returns SQLITE_IOERR.
*/
static int walHandleException(Wal *pWal){
  if( pWal->exclusiveMode==0 ){
    static const int S = 1;
    static const int E = (1<<SQLITE_SHM_NLOCK);
    int ii;
    u32 mUnlock;
    if( pWal->writeLock==2 ) pWal->writeLock = 0;
    u32 mUnlock = pWal->lockMask & ~(
    mUnlock = pWal->lockMask & ~(
        (pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock)))
        | (pWal->writeLock ? (E << WAL_WRITE_LOCK) : 0)
        | (pWal->ckptLock ? (E << WAL_CKPT_LOCK) : 0)
        );
    for(ii=0; ii<SQLITE_SHM_NLOCK; ii++){
      if( (S<<ii) & mUnlock ) walUnlockShared(pWal, ii);
      if( (E<<ii) & mUnlock ) walUnlockExclusive(pWal, ii, 1);
2681
2682
2683
2684
2685
2686
2687





2688

2689
2690
2691
2692
2693
2694
2695
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699

2700
2701
2702
2703
2704
2705
2706
2707







+
+
+
+
+
-
+







        rc = SQLITE_READONLY_RECOVERY;
      }
    }else{
      int bWriteLock = pWal->writeLock;
      if( bWriteLock 
       || SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) 
      ){
        /* If the write-lock was just obtained, set writeLock to 2 instead of
        ** the usual 1. This causes walIndexPage() to behave as if the 
        ** write-lock were held (so that it allocates new pages as required),
        ** and walHandleException() to unlock the write-lock if a SEH exception
        ** is thrown.  */
        pWal->writeLock = 1;
        if( !bWriteLock ) pWal->writeLock = 2;
        if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
          badHdr = walIndexTryHdr(pWal, pChanged);
          if( badHdr ){
            /* If the wal-index header is still malformed even while holding
            ** a WRITE lock, it can only mean that the header is corrupted and
            ** needs to be reconstructed.  So run recovery to do exactly that.
            ** Disable blocking locks first.  */
3466
3467
3468
3469
3470
3471
3472

3473


3474

3475
3476
3477
3478
3479
3480
3481
3478
3479
3480
3481
3482
3483
3484
3485

3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496







+
-
+
+

+







}

/*
** Finish with a read transaction.  All this does is release the
** read-lock.
*/
void sqlite3WalEndReadTransaction(Wal *pWal){
#ifndef SQLITE_ENABLE_SETLK_TIMEOUT
  sqlite3WalEndWriteTransaction(pWal);
  assert( pWal->writeLock==0 || pWal->readLock<0 );
#endif
  if( pWal->readLock>=0 ){
    sqlite3WalEndWriteTransaction(pWal);
    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
    pWal->readLock = -1;
  }
}

/*
** Search the wal file for page pgno. If found, set *piRead to the frame that
3660
3661
3662
3663
3664
3665
3666
3667

3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681

3682
3683
3684
3685
3686
3687
3688
3689







-
+







  int rc;

#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  /* If the write-lock is already held, then it was obtained before the
  ** read-transaction was even opened, making this call a no-op.
  ** Return early. */
  if( pWal->writeLock ){
    assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) );
    assert( !memcmp(&pWal->hdr,(void*)pWal->apWiData[0],sizeof(WalIndexHdr)) );
    return SQLITE_OK;
  }
#endif

  /* Cannot start a write transaction without first holding a read
  ** transaction. */
  assert( pWal->readLock>=0 );
Changes to test/filectrl.test.
32
33
34
35
36
37
38

39
40
41
42
43






44
45
46
47
48
49
50
32
33
34
35
36
37
38
39





40
41
42
43
44
45
46
47
48
49
50
51
52







+
-
-
-
-
-
+
+
+
+
+
+







  file_control_lasterrno_test db
} {}
do_test filectrl-1.5 {
  db close
  sqlite3 db test_control_lockproxy.db
  file_control_lockproxy_test db [get_pwd]
} {}
ifcapable !winrt {
do_test filectrl-1.6 {
  sqlite3 db test.db
  set fn [file_control_tempfilename db]
  set fn
} {/etilqs_/}
  do_test filectrl-1.6 {
    sqlite3 db test.db
    set fn [file_control_tempfilename db]
    set fn
  } {/etilqs_/}
}
db close
forcedelete .test_control_lockproxy.db-conch test.proxy
forcedelete test.db test2.db

if {$tcl_platform(platform)=="windows"} {
  do_test filectrl-2.1 {
    sqlite3 db test2.db
Changes to test/lock_common.tcl.
141
142
143
144
145
146
147

148
149
150
151
152
153
154
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155







+







    append ::tfnb($chan) "ERROR: Child process hung up"
    set line "OVER"
  } else {
    set line [gets $chan]
  }

  if { $line == "OVER" } {
    global $varname
    set $varname [lindex $::tfnb($chan) 1]
    unset ::tfnb($chan)
    close $chan
  } else {
    append ::tfnb($chan) $line
  }
}
Changes to test/shell1.test.
292
293
294
295
296
297
298


299

300
301
302
303
304
305
306
292
293
294
295
296
297
298
299
300

301
302
303
304
305
306
307
308







+
+
-
+







  catchcmd "test.db" ".bail OFF"
} {0 {}}
do_test shell1-3.2.4 {
  # too many arguments
  catchcmd "test.db" ".bail OFF BAD"
} {1 {Usage: .bail on|off}}

# This test will not work on winrt, as winrt has no concept of the absolute
# paths that the test expects in the result. It uses relative paths only.
ifcapable vtab {
ifcapable vtab&&!winrt {
# .databases             List names and files of attached databases
do_test shell1-3.3.1 {
  catchcmd "-csv test.db" ".databases"
} "/0.+main.+[string map {/ ".{1,2}"} [string range [get_pwd] 0 10]].*/"
do_test shell1-3.3.2 {
  # extra arguments ignored
  catchcmd "test.db" ".databases BAD"
740
741
742
743
744
745
746


747
748
749




750
751
752
753
754
755
756
742
743
744
745
746
747
748
749
750



751
752
753
754
755
756
757
758
759
760
761







+
+
-
-
-
+
+
+
+







} {0 {   abcdefg  123456    }}


# .timer ON|OFF          Turn the CPU timer measurement on or off
do_test shell1-3.27.1 {
  catchcmd "test.db" ".timer"
} {1 {Usage: .timer on|off}}
ifcapable !winrt {
  # No timer support on winrt.
do_test shell1-3.27.2 {
  catchcmd "test.db" ".timer ON"
} {0 {}}
  do_test shell1-3.27.2 {
    catchcmd "test.db" ".timer ON"
  } {0 {}}
}
do_test shell1-3.27.3 {
  catchcmd "test.db" ".timer OFF"
} {0 {}}
do_test shell1-3.27.4 {
  # too many arguments
  catchcmd "test.db" ".timer OFF BAD"
} {1 {Usage: .timer on|off}}
Changes to test/tester.tcl.
1772
1773
1774
1775
1776
1777
1778





1779
1780
1781
1782
1783
1784
1785
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790







+
+
+
+
+







    error "Compulsory option -file missing"
  }

  # $crashfile gets compared to the native filename in
  # cfSync(), which can be different then what TCL uses by
  # default, so here we force it to the "nativename" format.
  set cfile [string map {\\ \\\\} [file nativename [file join [get_pwd] $crashfile]]]
  ifcapable winrt {
    # Except on winrt. Winrt has no way to transform a relative path into
    # an absolute one, so it just uses the relative paths.
    set cfile $crashfile
  }

  set f [open crash.tcl w]
  puts $f "sqlite3_initialize ; sqlite3_shutdown"
  puts $f "catch { install_malloc_faultsim 1 }"
  puts $f "sqlite3_crash_enable 1 $dfltvfs"
  puts $f "sqlite3_crashparams $blocksize $dc $crashdelay $cfile"
  puts $f "sqlite3_test_control_pending_byte $::sqlite_pending_byte"
Changes to test/testrunner_data.tcl.
33
34
35
36
37
38
39

40
41
42
43
44
45
46
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47







+







  set tcltest(osx.Apple)                  all_less_no_mutex_try

  set tcltest(win.Stdcall)                veryquick
  set tcltest(win.Have-Not)               veryquick
  set tcltest(win.Windows-Memdebug)       veryquick
  set tcltest(win.Windows-Win32Heap)      veryquick
  set tcltest(win.Windows-Sanitize)       veryquick
  set tcltest(win.Windows-WinRT)          veryquick
  set tcltest(win.Default)                full

  # Extra [make xyz] tests that should be run for various builds.
  #
  set extra(linux.Check-Symbols)          checksymbols
  set extra(linux.Fast-One)               {fuzztest sourcetest}
  set extra(linux.Debug-One)              {fuzztest sourcetest mptest}
354
355
356
357
358
359
360

361
362
363
364
365





366
367
368
369
370
371
372
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







+





+
+
+
+
+







  set build(Windows-Memdebug) {
    MEMDEBUG=1
    DEBUG=3
  }
  set build(Windows-Win32Heap) {
    WIN32HEAP=1
    DEBUG=4
    ENABLE_SETLK=1
  }
  set build(Windows-Sanitize) {
    ASAN=1
  }

  set build(Windows-WinRT) {
    FOR_WINRT=1
    ENABLE_SETLK=1
    -DSQLITE_TEMP_STORE=3
  }
}


#-------------------------------------------------------------------------
proc trd_import {} {
  uplevel {
    variable ::trd::tcltest
Changes to test/walsetlk.test.
76
77
78
79
80
81
82













83
84
85
86
87
88
89
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







+
+
+
+
+
+
+
+
+
+
+
+
+








close $fd
db close
db2 close
#-------------------------------------------------------------------------

do_multiclient_test tn {

  testvfs tvfs -fullshm 1
  db close
  sqlite3 db test.db -vfs tvfs
  tvfs script xSleep_callback
  tvfs filter xSleep

  set ::sleep_count 0
  proc xSleep_callback {xSleep nMs} {
    after [expr $nMs / 1000]
    incr ::sleep_count
  }

  do_test 2.$tn.1 {
    sql1 {
      PRAGMA journal_mode = wal;
      CREATE TABLE t1(s, v);
      INSERT INTO t1 VALUES(1, 2);
      INSERT INTO t1 VALUES(3, 4);
      INSERT INTO t1 VALUES(5, 6);
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
141
142
143
144
145
146
147

148
149
150
151
152
153
154







-







    }
  } {1 2 3 4 5 6 7 8 9 10}

  do_test 2.$tn.8 {
    set us [lindex [time { catch {db eval "PRAGMA wal_checkpoint=RESTART"} }] 0]
    expr $us>1000000 && $us<4000000
  } {1}

  do_test 2.$tn.9 {
    sql3 {
      INSERT INTO t1 VALUES(11, 12);
    }
    sql2 {
      COMMIT;
      BEGIN;
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

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







-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


+
+
+
+
+
+
+
+
+
+
+
+
-
+

+







+
+
+
+
-
+



+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+
    sql1 { INSERT INTO t1 VALUES(17, 18); }
  } {}

  do_test 2.$tn.14 {
    set us [lindex [time { catch {db eval "PRAGMA wal_checkpoint=RESTART"} }] 0]
    expr $us>1000000 && $us<4000000
  } {1}
  
}


  db close
  tvfs delete

  # Set bSleep to true if it is expected that the above used xSleep() to
  # wait for locks. bSleep is true unless SQLITE_ENABLE_SETLK_TIMEOUT is
  # set to 1 and either:
  #
  #   * the OS is windows, or
  #   * the OS is unix and the tests were run with each connection 
  #     in a separate process.
  #
  set bSleep 1
  if {$::sqlite_options(setlk_timeout)==1} {
    if {$::tcl_platform(platform)=="windows"} {
      set bSleep 0
    }
    if {$::tcl_platform(platform)=="unix"} {
      set bSleep [expr $tn==2]
    }
  }

  do_test 2.$tn.15.$bSleep {
    expr $::sleep_count > 0
  } $bSleep
}

#-------------------------------------------------------------------------
reset_db

testvfs tvfs -fullshm 1
tvfs script xSleep_callback
tvfs filter xSleep

set ::sleep_count 0
proc xSleep_callback {xSleep nMs} {
  after [expr $nMs / 1000]
  incr ::sleep_count
  breakpoint
}

sqlite3 db2 test.db
sqlite3 db2 test.db -vfs tvfs
db2 timeout 1000

do_execsql_test 3.0 {
  PRAGMA journal_mode = wal;
  CREATE TABLE x1(x, y);
  BEGIN;
    INSERT INTO x1 VALUES(1, 2);
} {wal}

do_execsql_test -db db2 3.1a {
  SELECT * FROM x1
} {}

do_test 3.1 {
do_test 3.1b {
  list [catch { db2 eval {BEGIN EXCLUSIVE} } msg] $msg
} {1 {database is locked}}

# Set bExpect to true if calls to xSleep() are expected. Such calls are
# expected unless this is an SQLITE_ENABLE_SETLK_TIMEOUT=1 build.
set bExpect 1
if {$tcl_platform(platform)=="windows" && $::sqlite_options(setlk_timeout)==1} {
  set bExpect 0
}
do_test 3.2 {
  expr {$::sleep_count > 0}
} $bExpect
set ::sleep_count 0

do_execsql_test 3.3 {
  COMMIT;
}

# Launch a non-blocking testfixture process to write-lock the 
# database for 2000 ms.
testfixture_nb done {
  sqlite3 db test.db
  db eval {
    BEGIN EXCLUSIVE;
     INSERT INTO x1 VALUES(3, 4);
  }
  after 2000
  db eval {
    COMMIT
  }
}

after 500 {set ok 1}
vwait ok

db2 timeout 5000
do_test 3.4 {
  set t [lindex [time { db2 eval { BEGIN EXCLUSIVE } }] 0]
  expr ($t>1000000)
} {1}

# Set bExpect to true if calls to xSleep() are expected. Such calls are
# expected unless this is an SQLITE_ENABLE_SETLK_TIMEOUT=1 build.
set bExpect 1
if {$::sqlite_options(setlk_timeout)==1} {
  set bExpect 0
}
do_test 3.5 {
  expr {$::sleep_count > 0}
} $bExpect

do_execsql_test -db db2 3.6 {
  INSERT INTO x1 VALUES(5, 6);
  COMMIT;
  SELECT * FROM x1;
} {1 2 3 4 5 6}

# Launch a non-blocking testfixture process to write-lock the 
# database for 2000 ms.
testfixture_nb done {
  sqlite3 db test.db
  db eval {
    BEGIN EXCLUSIVE;
     INSERT INTO x1 VALUES(7, 8);
  }
  after 2000
  db eval {
    COMMIT
  }
}

after 500 {set ok 1}
vwait ok

db2 timeout 0x7FFFFFFF
do_test 3.7 {
  set t [lindex [time { db2 eval { BEGIN EXCLUSIVE } }] 0]
  expr ($t>1000000)
} {1}

# Set bExpect to true if calls to xSleep() are expected. Such calls are
# expected unless this is an SQLITE_ENABLE_SETLK_TIMEOUT=1 build.
set bExpect 1
if {$::sqlite_options(setlk_timeout)==1} {
  set bExpect 0
}
do_test 3.8 {
  expr {$::sleep_count > 0}
} $bExpect

do_execsql_test -db db2 3.9 {
  INSERT INTO x1 VALUES(9, 10);
  COMMIT;
  SELECT * FROM x1;
} {1 2 3 4 5 6 7 8 9 10}

db2 close
tvfs delete

finish_test

Added test/walsetlk2.test.




































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2025 Jan 24
#
# 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.
#
#***********************************************************************
#
# TESTRUNNER: slow
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/lock_common.tcl
set testprefix walsetlk2

ifcapable !wal {finish_test ; return }
ifcapable !setlk_timeout {finish_test ; return }

#-------------------------------------------------------------------------
# Check that xShmLock calls are as expected for write transactions in
# setlk mode.
#
reset_db

do_execsql_test 1.0 {
  PRAGMA journal_mode = wal;
  CREATE TABLE t1(a, b, c);
  INSERT INTO t1 VALUES(1, 2, 3);
} {wal}
db close

testvfs tvfs
tvfs script xShmLock_callback
tvfs filter xShmLock

set ::xshmlock [list]
proc xShmLock_callback {method path name detail} {
  lappend ::xshmlock $detail
}

sqlite3 db test.db -vfs tvfs
db timeout 1000

do_execsql_test 1.1 {
  SELECT * FROM t1
} {1 2 3}

do_execsql_test 1.2 {
  INSERT INTO t1 VALUES(4, 5, 6);
}

set ::xshmlock [list]
do_execsql_test 1.3 {
  INSERT INTO t1 VALUES(7, 8, 9);
}

do_test 1.4 {
  set ::xshmlock
} [list \
  {0 1 lock exclusive}                             \
  {4 1 lock exclusive} {4 1 unlock exclusive}      \
  {4 1 lock shared}                                \
  {0 1 unlock exclusive}                           \
  {4 1 unlock shared}
]

do_execsql_test 1.5.1 { SELECT * FROM t1 } {1 2 3 4 5 6 7 8 9}
set ::xshmlock [list]
do_execsql_test 1.5.2 {
  INSERT INTO t1 VALUES(10, 11, 12);
}
do_test 1.5.3 {
  set ::xshmlock
} [list \
  {0 1 lock exclusive}                             \
  {4 1 lock shared}                                \
  {0 1 unlock exclusive}                           \
  {4 1 unlock shared}
]

db close
tvfs delete

#-------------------------------------------------------------------------
# Check that if sqlite3_setlk_timeout() is used, blocking locks timeout
# but other operations do not use the retry mechanism.
#
reset_db

do_execsql_test 2.0 {
  CREATE TABLE t1(a, b);
  INSERT INTO t1 VALUES(1, 2), (3, 4);
}

sqlite3_setlk_timeout db 2000

# Launch a non-blocking testfixture process to write-lock the 
# database for 2000 ms.
testfixture_nb done {
  sqlite3 db test.db
  db eval {
    BEGIN EXCLUSIVE;
      INSERT INTO t1 VALUES(5, 6);
  }
  after 2000
  db eval {
    COMMIT
  }
  db close
}

after 500 {set ok 1}
vwait ok

do_catchsql_test 2.1 {
  INSERT INTO t1 VALUES(7, 8);
} {1 {database is locked}}

sqlite3_busy_timeout db 2000

do_catchsql_test 2.2 {
  INSERT INTO t1 VALUES(7, 8);
} {0 {}}

do_execsql_test 2.3 {
  SELECT * FROM t1
} {1 2 3 4 5 6 7 8}

do_execsql_test 2.4 {
  PRAGMA journal_mode = wal;
} {wal}

db close
sqlite3 db test.db

do_execsql_test 2.5 {
  INSERT INTO t1 VALUES(9, 10);
}

sqlite3_setlk_timeout db 2000

# Launch a non-blocking testfixture process to write-lock the 
# database for 2000 ms.
testfixture_nb done {
  sqlite3 db test.db
  db eval {
    BEGIN EXCLUSIVE;
      INSERT INTO t1 VALUES(11, 12);
  }
  after 2000
  db eval {
    COMMIT
  }
  db close
}

after 500 {set ok 1}
vwait ok

do_catchsql_test 2.6 {
  INSERT INTO t1 VALUES(13, 14);
} {0 {}}

do_execsql_test 2.7 {
  SELECT * FROM t1
} {1 2 3 4 5 6 7 8 9 10 11 12 13 14}

#-------------------------------------------------------------------------
# Check that if sqlite3_setlk_timeout(-1) is called, blocking locks are
# enabled and last for a few seconds at least. Difficult to test that they
# really do block indefinitely.
#
reset_db

do_execsql_test 3.0 {
  PRAGMA journal_mode = wal;
  CREATE TABLE t1(a INTEGER PRIMARY KEY, b);
  INSERT INTO t1 VALUES(1, 'one'), (3, 'three');
} {wal}

sqlite3_setlk_timeout db -1

# Launch a non-blocking testfixture process to write-lock the 
# database for 2000 ms.
testfixture_nb done {
  sqlite3 db test.db
  db eval {
    BEGIN EXCLUSIVE;
      INSERT INTO t1 VALUES(5, 'five');
  }
  after 2000
  db eval {
    COMMIT
  }
  db close
}

after 500 {set ok 1}
vwait ok

breakpoint
do_catchsql_test 3.1 {
  INSERT INTO t1 VALUES(7, 'seven');
} {0 {}}

# Launch another non-blocking testfixture process to write-lock the 
# database for 2000 ms.
testfixture_nb done {
  sqlite3 db test.db
  db eval {
    BEGIN EXCLUSIVE;
      INSERT INTO t1 VALUES(9, 'nine');
  }
  after 2000
  db eval {
    COMMIT
  }
  db close
}

after 500 {set ok 1}
vwait ok

do_catchsql_test 3.2 {
  INSERT INTO t1 VALUES(9, 'ten');
} {1 {UNIQUE constraint failed: t1.a}}

do_execsql_test 3.3 {
  SELECT * FROM t1
} {1 one 3 three 5 five 7 seven 9 nine}

db close

# Launch another non-blocking testfixture process to write-lock the 
# database for 2000 ms.
testfixture_nb done {
  sqlite3 db test.db
  db eval {
    BEGIN EXCLUSIVE;
      INSERT INTO t1 VALUES(11, 'eleven');
  }
  after 2000
  db eval {
    COMMIT
  }
}

sqlite3 db test.db
sqlite3_setlk_timeout db -1
do_catchsql_test 3.4 {
  INSERT INTO t1 VALUES(13, 'thirteen');
} {0 {}}


finish_test

Added test/walsetlk3.test.







































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# 2020 May 06
#
# 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.
#
#***********************************************************************
#
# TESTRUNNER: slow
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/lock_common.tcl
set testprefix walsetlk3

ifcapable !wal {finish_test ; return }
ifcapable !setlk_timeout {finish_test ; return }

do_execsql_test 1.0 {
  CREATE TABLE t1(x, y);
  PRAGMA journal_mode = wal;
  INSERT INTO t1 VALUES(1, 2);
  INSERT INTO t1 VALUES(3, 4);
} {wal}

db close

proc sql_block_on_close {sql} {
  testfixture_nb done [string map [list %SQL% $sql] {
    testvfs tvfs
    tvfs script xWrite
    tvfs filter xWrite
  
    set ::delay_done 0
    proc xWrite {method fname args} {
      if {[file tail $fname]=="test.db" && $::delay_done==0} {
        after 3000
        set ::delay_done 1
      }
      return 0
    }
  
    sqlite3 db test.db -vfs tvfs
    db eval {%SQL%}
    db close
  }]
}

# Start a second process that writes to the db, then blocks within the
# [db close] holding an EXCLUSIVE on the db in order to checkpoint and 
# delete the wal file. Then try to read the db.
#
# Without the SQLITE_SETLK_BLOCK_ON_CONNECT flag, this should fail with
# SQLITE_BUSY.
#
sql_block_on_close {
  INSERT INTO t1 VALUES(5, 6);
  INSERT INTO t1 VALUES(7, 8);
}
after 500 {set ok 1}
vwait ok
sqlite3 db test.db
sqlite3_setlk_timeout db 2000
do_catchsql_test 1.1 {
  SELECT * FROM t1
} {1 {database is locked}}

vwait ::done

# But with SQLITE_SETLK_BLOCK_ON_CONNECT flag, it should succeed.
#
sql_block_on_close {
  INSERT INTO t1 VALUES(9, 10);
  INSERT INTO t1 VALUES(11, 12);
}
after 500 {set ok 1}
vwait ok
sqlite3 db test.db
sqlite3_setlk_timeout -block db 2000
do_catchsql_test 1.2 {
  SELECT * FROM t1
} {0 {1 2 3 4 5 6 7 8 9 10 11 12}}

vwait ::done

#-------------------------------------------------------------------------
# Check that the SQLITE_SETLK_BLOCK_ON_CONNECT does not cause connections
# to block when taking a SHARED lock on a rollback mode database.
#
reset_db
do_execsql_test 2.1 {
  CREATE TABLE x1(a);
  INSERT INTO x1 VALUES(1), (2), (3);
}

proc sql_block_on_write {sql} {
  testfixture_nb done [string map [list %SQL% $sql] {
    sqlite3 db test.db 
    db eval "BEGIN EXCLUSIVE"
    db eval {%SQL%}
    after 3000
    db eval COMMIT
    db close
  }]
}

db close
sql_block_on_write {
  INSERT INTO x1 VALUES(4);
}

after 500 {set ok 1}
vwait ok

sqlite3 db test.db
sqlite3_setlk_timeout -block db 2000

do_catchsql_test 2.2 {
  SELECT * FROM x1
} {1 {database is locked}}

vwait ::done
after 500 {set ok 1}
vwait ok

do_catchsql_test 2.3 {
  SELECT * FROM x1
} {0 {1 2 3 4}}

finish_test

Changes to test/win32longpath.test.
111
112
113
114
115
116
117





118

119
120
121
122
123
124
125
111
112
113
114
115
116
117
118
119
120
121
122

123
124
125
126
127
128
129
130







+
+
+
+
+
-
+







    SELECT x FROM t1 ORDER BY x;
    COMMIT;
  }
} {5 6 7 8 9 10 11 12}

db3 close

# winrt platforms do not handle paths with unix-style '/' directory separators.
#
set lUri [list 1a 1b 1c 1d 1e 1f]
ifcapable winrt { set lUri [list 1a 1c 1e] }

foreach tn {1a 1b 1c 1d 1e 1f} {
foreach tn $lUri {
  sqlite3 db3 $uri($tn) -vfs win32-longpath -uri 1 -translatefilename 0

  do_test 1.7.$tn {
    db3 eval {
      SELECT x FROM t1 ORDER BY x;
    }
  } {5 6 7 8 9 10 11 12}
Changes to tool/mkctimec.tcl.
163
164
165
166
167
168
169

170
171
172
173
174
175
176
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177







+







  SQLITE_ENABLE_OFFSET_SQL_FUNC
  SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  SQLITE_ENABLE_PREUPDATE_HOOK
  SQLITE_ENABLE_QPSG
  SQLITE_ENABLE_RBU
  SQLITE_ENABLE_RTREE
  SQLITE_ENABLE_SESSION
  SQLITE_ENABLE_SETLK_TIMEOUT
  SQLITE_ENABLE_SNAPSHOT
  SQLITE_ENABLE_SORTER_REFERENCES
  SQLITE_ENABLE_SQLLOG
  SQLITE_ENABLE_STAT4
  SQLITE_ENABLE_STMT_SCANSTATUS
  SQLITE_ENABLE_STMTVTAB
  SQLITE_ENABLE_TREETRACE