xref: /sqlite-3.40.0/src/test_journal.c (revision b7e8ea20)
1 /*
2 ** 2008 Jan 22
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 ******************************************************************************
12 **
13 ** This file contains code for a VFS layer that acts as a wrapper around
14 ** an existing VFS. The code in this file attempts to verify that SQLite
15 ** correctly populates and syncs a journal file before writing to a
16 ** corresponding database file.
17 */
18 #if SQLITE_TEST          /* This file is used for testing only */
19 
20 #include "sqlite3.h"
21 #include "sqliteInt.h"
22 
23 /*
24 ** INTERFACE
25 **
26 **   The public interface to this wrapper VFS is two functions:
27 **
28 **     jt_register()
29 **     jt_unregister()
30 **
31 **   See header comments associated with those two functions below for
32 **   details.
33 **
34 ** LIMITATIONS
35 **
36 **   This wrapper will not work if "PRAGMA synchronous = off" is used.
37 **
38 ** OPERATION
39 **
40 **  Starting a Transaction:
41 **
42 **   When a write-transaction is started, the contents of the database is
43 **   inspected and the following data stored as part of the database file
44 **   handle (type struct jt_file):
45 **
46 **     a) The page-size of the database file.
47 **     b) The number of pages that are in the database file.
48 **     c) The set of page numbers corresponding to free-list leaf pages.
49 **     d) A check-sum for every page in the database file.
50 **
51 **   The start of a write-transaction is deemed to have occurred when a
52 **   28-byte journal header is written to byte offset 0 of the journal
53 **   file.
54 **
55 **  Syncing the Journal File:
56 **
57 **   Whenever the xSync method is invoked to sync a journal-file, the
58 **   contents of the journal file are read. For each page written to
59 **   the journal file, a check-sum is calculated and compared to the
60 **   check-sum calculated for the corresponding database page when the
61 **   write-transaction was initialized. The success of the comparison
62 **   is assert()ed. So if SQLite has written something other than the
63 **   original content to the database file, an assert() will fail.
64 **
65 **   Additionally, the set of page numbers for which records exist in
66 **   the journal file is added to (unioned with) the set of page numbers
67 **   corresponding to free-list leaf pages collected when the
68 **   write-transaction was initialized. This set comprises the page-numbers
69 **   corresponding to those pages that SQLite may now safely modify.
70 **
71 **  Writing to the Database File:
72 **
73 **   When a block of data is written to a database file, the following
74 **   invariants are asserted:
75 **
76 **     a) That the block of data is an aligned block of page-size bytes.
77 **
78 **     b) That if the page being written did not exist when the
79 **        transaction was started (i.e. the database file is growing), then
80 **        the journal-file must have been synced at least once since
81 **        the start of the transaction.
82 **
83 **     c) That if the page being written did exist when the transaction
84 **        was started, then the page must have either been a free-list
85 **        leaf page at the start of the transaction, or else must have
86 **        been stored in the journal file prior to the most recent sync.
87 **
88 **  Closing a Transaction:
89 **
90 **   When a transaction is closed, all data collected at the start of
91 **   the transaction, or following an xSync of a journal-file, is
92 **   discarded. The end of a transaction is recognized when any one
93 **   of the following occur:
94 **
95 **     a) A block of zeroes (or anything else that is not a valid
96 **        journal-header) is written to the start of the journal file.
97 **
98 **     b) A journal file is truncated to zero bytes in size using xTruncate.
99 **
100 **     c) The journal file is deleted using xDelete.
101 */
102 
103 /*
104 ** Maximum pathname length supported by the jt backend.
105 */
106 #define JT_MAX_PATHNAME 512
107 
108 /*
109 ** Name used to identify this VFS.
110 */
111 #define JT_VFS_NAME "jt"
112 
113 typedef struct jt_file jt_file;
114 struct jt_file {
115   sqlite3_file base;
116   const char *zName;       /* Name of open file */
117   int flags;               /* Flags the file was opened with */
118 
119   /* The following are only used by database file file handles */
120   int eLock;               /* Current lock held on the file */
121   u32 nPage;               /* Size of file in pages when transaction started */
122   u32 nPagesize;           /* Page size when transaction started */
123   Bitvec *pWritable;       /* Bitvec of pages that may be written to the file */
124   u32 *aCksum;             /* Checksum for first nPage pages */
125   int nSync;               /* Number of times journal file has been synced */
126 
127   /* Only used by journal file-handles */
128   sqlite3_int64 iMaxOff;   /* Maximum offset written to this transaction */
129 
130   jt_file *pNext;          /* All files are stored in a linked list */
131   sqlite3_file *pReal;     /* The file handle for the underlying vfs */
132 };
133 
134 /*
135 ** Method declarations for jt_file.
136 */
137 static int jtClose(sqlite3_file*);
138 static int jtRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
139 static int jtWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
140 static int jtTruncate(sqlite3_file*, sqlite3_int64 size);
141 static int jtSync(sqlite3_file*, int flags);
142 static int jtFileSize(sqlite3_file*, sqlite3_int64 *pSize);
143 static int jtLock(sqlite3_file*, int);
144 static int jtUnlock(sqlite3_file*, int);
145 static int jtCheckReservedLock(sqlite3_file*, int *);
146 static int jtFileControl(sqlite3_file*, int op, void *pArg);
147 static int jtSectorSize(sqlite3_file*);
148 static int jtDeviceCharacteristics(sqlite3_file*);
149 
150 /*
151 ** Method declarations for jt_vfs.
152 */
153 static int jtOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
154 static int jtDelete(sqlite3_vfs*, const char *zName, int syncDir);
155 static int jtAccess(sqlite3_vfs*, const char *zName, int flags, int *);
156 static int jtFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
157 static void *jtDlOpen(sqlite3_vfs*, const char *zFilename);
158 static void jtDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
159 static void (*jtDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void);
160 static void jtDlClose(sqlite3_vfs*, void*);
161 static int jtRandomness(sqlite3_vfs*, int nByte, char *zOut);
162 static int jtSleep(sqlite3_vfs*, int microseconds);
163 static int jtCurrentTime(sqlite3_vfs*, double*);
164 
165 static sqlite3_vfs jt_vfs = {
166   1,                             /* iVersion */
167   sizeof(jt_file),               /* szOsFile */
168   JT_MAX_PATHNAME,               /* mxPathname */
169   0,                             /* pNext */
170   JT_VFS_NAME,                   /* zName */
171   0,                             /* pAppData */
172   jtOpen,                        /* xOpen */
173   jtDelete,                      /* xDelete */
174   jtAccess,                      /* xAccess */
175   jtFullPathname,                /* xFullPathname */
176   jtDlOpen,                      /* xDlOpen */
177   jtDlError,                     /* xDlError */
178   jtDlSym,                       /* xDlSym */
179   jtDlClose,                     /* xDlClose */
180   jtRandomness,                  /* xRandomness */
181   jtSleep,                       /* xSleep */
182   jtCurrentTime,                 /* xCurrentTime */
183 };
184 
185 static sqlite3_io_methods jt_io_methods = {
186   1,                             /* iVersion */
187   jtClose,                       /* xClose */
188   jtRead,                        /* xRead */
189   jtWrite,                       /* xWrite */
190   jtTruncate,                    /* xTruncate */
191   jtSync,                        /* xSync */
192   jtFileSize,                    /* xFileSize */
193   jtLock,                        /* xLock */
194   jtUnlock,                      /* xUnlock */
195   jtCheckReservedLock,           /* xCheckReservedLock */
196   jtFileControl,                 /* xFileControl */
197   jtSectorSize,                  /* xSectorSize */
198   jtDeviceCharacteristics        /* xDeviceCharacteristics */
199 };
200 
201 struct JtGlobal {
202   sqlite3_vfs *pVfs;             /* Parent VFS */
203   jt_file *pList;                /* List of all open files */
204 };
205 static struct JtGlobal g = {0, 0};
206 
207 /*
208 ** Functions to obtain and relinquish a mutex to protect g.pList. The
209 ** STATIC_PRNG mutex is reused, purely for the sake of convenience.
210 */
211 static void enterJtMutex(void){
212   sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PRNG));
213 }
214 static void leaveJtMutex(void){
215   sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PRNG));
216 }
217 
218 extern int sqlite3_io_error_pending;
219 extern int sqlite3_io_error_hit;
220 static void stop_ioerr_simulation(int *piSave, int *piSave2){
221   *piSave = sqlite3_io_error_pending;
222   *piSave2 = sqlite3_io_error_hit;
223   sqlite3_io_error_pending = -1;
224   sqlite3_io_error_hit = 0;
225 }
226 static void start_ioerr_simulation(int iSave, int iSave2){
227   sqlite3_io_error_pending = iSave;
228   sqlite3_io_error_hit = iSave2;
229 }
230 
231 /*
232 ** The jt_file pointed to by the argument may or may not be a file-handle
233 ** open on a main database file. If it is, and a transaction is currently
234 ** opened on the file, then discard all transaction related data.
235 */
236 static void closeTransaction(jt_file *p){
237   sqlite3BitvecDestroy(p->pWritable);
238   sqlite3_free(p->aCksum);
239   p->pWritable = 0;
240   p->aCksum = 0;
241   p->nSync = 0;
242 }
243 
244 /*
245 ** Close an jt-file.
246 */
247 static int jtClose(sqlite3_file *pFile){
248   jt_file **pp;
249   jt_file *p = (jt_file *)pFile;
250 
251   closeTransaction(p);
252   enterJtMutex();
253   if( p->zName ){
254     for(pp=&g.pList; *pp!=p; pp=&(*pp)->pNext);
255     *pp = p->pNext;
256   }
257   leaveJtMutex();
258   return sqlite3OsClose(p->pReal);
259 }
260 
261 /*
262 ** Read data from an jt-file.
263 */
264 static int jtRead(
265   sqlite3_file *pFile,
266   void *zBuf,
267   int iAmt,
268   sqlite_int64 iOfst
269 ){
270   jt_file *p = (jt_file *)pFile;
271   return sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
272 }
273 
274 /*
275 ** Parameter zJournal is the name of a journal file that is currently
276 ** open. This function locates and returns the handle opened on the
277 ** corresponding database file by the pager that currently has the
278 ** journal file opened. This file-handle is identified by the
279 ** following properties:
280 **
281 **   a) SQLITE_OPEN_MAIN_DB was specified when the file was opened.
282 **
283 **   b) The file-name specified when the file was opened matches
284 **      all but the final 8 characters of the journal file name.
285 **
286 **   c) There is currently a reserved lock on the file.
287 **/
288 static jt_file *locateDatabaseHandle(const char *zJournal){
289   jt_file *pMain = 0;
290   enterJtMutex();
291   for(pMain=g.pList; pMain; pMain=pMain->pNext){
292     int nName = strlen(zJournal) - strlen("-journal");
293     if( (pMain->flags&SQLITE_OPEN_MAIN_DB)
294      && (strlen(pMain->zName)==nName)
295      && 0==memcmp(pMain->zName, zJournal, nName)
296      && (pMain->eLock>=SQLITE_LOCK_RESERVED)
297     ){
298       break;
299     }
300   }
301   leaveJtMutex();
302   return pMain;
303 }
304 
305 /*
306 ** Parameter z points to a buffer of 4 bytes in size containing a
307 ** unsigned 32-bit integer stored in big-endian format. Decode the
308 ** integer and return its value.
309 */
310 static u32 decodeUint32(const unsigned char *z){
311   return (z[0]<<24) + (z[1]<<16) + (z[2]<<8) + z[3];
312 }
313 
314 /*
315 ** Calculate a checksum from the buffer of length n bytes pointed to
316 ** by parameter z.
317 */
318 static u32 genCksum(const unsigned char *z, int n){
319   int i;
320   u32 cksum = 0;
321   for(i=0; i<n; i++){
322     cksum = cksum + z[i] + (cksum<<3);
323   }
324   return cksum;
325 }
326 
327 /*
328 ** The first argument, zBuf, points to a buffer containing a 28 byte
329 ** serialized journal header. This function deserializes four of the
330 ** integer fields contained in the journal header and writes their
331 ** values to the output variables.
332 **
333 ** SQLITE_OK is returned if the journal-header is successfully
334 ** decoded. Otherwise, SQLITE_ERROR.
335 */
336 static int decodeJournalHdr(
337   const unsigned char *zBuf,         /* Input: 28 byte journal header */
338   u32 *pnRec,                        /* Out: Number of journalled records */
339   u32 *pnPage,                       /* Out: Original database page count */
340   u32 *pnSector,                     /* Out: Sector size in bytes */
341   u32 *pnPagesize                    /* Out: Page size in bytes */
342 ){
343   unsigned char aMagic[] = { 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7 };
344   if( memcmp(aMagic, zBuf, 8) ) return SQLITE_ERROR;
345   if( pnRec ) *pnRec = decodeUint32(&zBuf[8]);
346   if( pnPage ) *pnPage = decodeUint32(&zBuf[16]);
347   if( pnSector ) *pnSector = decodeUint32(&zBuf[20]);
348   if( pnPagesize ) *pnPagesize = decodeUint32(&zBuf[24]);
349   return SQLITE_OK;
350 }
351 
352 /*
353 ** This function is called when a new transaction is opened, just after
354 ** the first journal-header is written to the journal file.
355 */
356 static int openTransaction(jt_file *pMain, jt_file *pJournal){
357   unsigned char *aData;
358   sqlite3_file *p = pMain->pReal;
359   int rc = SQLITE_OK;
360 
361   aData = sqlite3_malloc(pMain->nPagesize);
362   pMain->pWritable = sqlite3BitvecCreate(pMain->nPage);
363   pMain->aCksum = sqlite3_malloc(sizeof(u32) * (pMain->nPage + 1));
364   pJournal->iMaxOff = 0;
365 
366   if( !pMain->pWritable || !pMain->aCksum || !aData ){
367     rc = SQLITE_IOERR_NOMEM;
368   }else if( pMain->nPage>0 ){
369     u32 iTrunk;
370     int iSave;
371     int iSave2;
372 
373     stop_ioerr_simulation(&iSave, &iSave2);
374 
375     /* Read the database free-list. Add the page-number for each free-list
376     ** leaf to the jt_file.pWritable bitvec.
377     */
378     rc = sqlite3OsRead(p, aData, pMain->nPagesize, 0);
379     iTrunk = decodeUint32(&aData[32]);
380     while( rc==SQLITE_OK && iTrunk>0 ){
381       u32 nLeaf;
382       u32 iLeaf;
383       sqlite3_int64 iOff = (iTrunk-1)*pMain->nPagesize;
384       rc = sqlite3OsRead(p, aData, pMain->nPagesize, iOff);
385       nLeaf = decodeUint32(&aData[4]);
386       for(iLeaf=0; rc==SQLITE_OK && iLeaf<nLeaf; iLeaf++){
387         u32 pgno = decodeUint32(&aData[8+4*iLeaf]);
388         sqlite3BitvecSet(pMain->pWritable, pgno);
389       }
390       iTrunk = decodeUint32(aData);
391     }
392 
393     /* Calculate and store a checksum for each page in the database file. */
394     if( rc==SQLITE_OK ){
395       int ii;
396       for(ii=0; rc==SQLITE_OK && ii<pMain->nPage; ii++){
397         i64 iOff = (i64)(pMain->nPagesize) * (i64)ii;
398         if( iOff==PENDING_BYTE ) continue;
399         rc = sqlite3OsRead(pMain->pReal, aData, pMain->nPagesize, iOff);
400         pMain->aCksum[ii] = genCksum(aData, pMain->nPagesize);
401       }
402     }
403 
404     start_ioerr_simulation(iSave, iSave2);
405   }
406 
407   sqlite3_free(aData);
408   return rc;
409 }
410 
411 /*
412 ** The first argument to this function is a handle open on a journal file.
413 ** This function reads the journal file and adds the page number for each
414 ** page in the journal to the Bitvec object passed as the second argument.
415 */
416 static int readJournalFile(jt_file *p, jt_file *pMain){
417   int rc = SQLITE_OK;
418   unsigned char zBuf[28];
419   sqlite3_file *pReal = p->pReal;
420   sqlite3_int64 iOff = 0;
421   sqlite3_int64 iSize = p->iMaxOff;
422   unsigned char *aPage;
423   int iSave;
424   int iSave2;
425 
426   aPage = sqlite3_malloc(pMain->nPagesize);
427   if( !aPage ){
428     return SQLITE_IOERR_NOMEM;
429   }
430 
431   stop_ioerr_simulation(&iSave, &iSave2);
432 
433   while( rc==SQLITE_OK && iOff<iSize ){
434     u32 nRec, nPage, nSector, nPagesize;
435     u32 ii;
436 
437     /* Read and decode the next journal-header from the journal file. */
438     rc = sqlite3OsRead(pReal, zBuf, 28, iOff);
439     if( rc!=SQLITE_OK
440      || decodeJournalHdr(zBuf, &nRec, &nPage, &nSector, &nPagesize)
441     ){
442       goto finish_rjf;
443     }
444     iOff += nSector;
445 
446     if( nRec==0 ){
447       /* A trick. There might be another journal-header immediately
448       ** following this one. In this case, 0 records means 0 records,
449       ** not "read until the end of the file". See also ticket #2565.
450       */
451       if( iSize>=(iOff+nSector) ){
452         rc = sqlite3OsRead(pReal, zBuf, 28, iOff);
453         if( rc!=SQLITE_OK || 0==decodeJournalHdr(zBuf, 0, 0, 0, 0) ){
454           continue;
455         }
456       }
457       nRec = (iSize-iOff) / (pMain->nPagesize+8);
458     }
459 
460     /* Read all the records that follow the journal-header just read. */
461     for(ii=0; rc==SQLITE_OK && ii<nRec && iOff<iSize; ii++){
462       u32 pgno;
463       rc = sqlite3OsRead(pReal, zBuf, 4, iOff);
464       if( rc==SQLITE_OK ){
465         pgno = decodeUint32(zBuf);
466         if( pgno>0 && pgno<=pMain->nPage ){
467           if( 0==sqlite3BitvecTest(pMain->pWritable, pgno) ){
468             rc = sqlite3OsRead(pReal, aPage, pMain->nPagesize, iOff+4);
469             if( rc==SQLITE_OK ){
470               u32 cksum = genCksum(aPage, pMain->nPagesize);
471               assert( cksum==pMain->aCksum[pgno-1] );
472             }
473           }
474           sqlite3BitvecSet(pMain->pWritable, pgno);
475         }
476         iOff += (8 + pMain->nPagesize);
477       }
478     }
479 
480     iOff = ((iOff + (nSector-1)) / nSector) * nSector;
481   }
482 
483 finish_rjf:
484   start_ioerr_simulation(iSave, iSave2);
485   sqlite3_free(aPage);
486   if( rc==SQLITE_IOERR_SHORT_READ ){
487     rc = SQLITE_OK;
488   }
489   return rc;
490 }
491 
492 
493 /*
494 ** Write data to an jt-file.
495 */
496 static int jtWrite(
497   sqlite3_file *pFile,
498   const void *zBuf,
499   int iAmt,
500   sqlite_int64 iOfst
501 ){
502   int rc;
503   jt_file *p = (jt_file *)pFile;
504   if( p->flags&SQLITE_OPEN_MAIN_JOURNAL ){
505     if( iOfst==0 ){
506       jt_file *pMain = locateDatabaseHandle(p->zName);
507       assert( pMain );
508 
509       if( iAmt==28 ){
510         /* Zeroing the first journal-file header. This is the end of a
511         ** transaction. */
512         closeTransaction(pMain);
513       }else if( iAmt!=12 ){
514         /* Writing the first journal header to a journal file. This happens
515         ** when a transaction is first started.  */
516         u8 *z = (u8 *)zBuf;
517         pMain->nPage = decodeUint32(&z[16]);
518         pMain->nPagesize = decodeUint32(&z[24]);
519         if( SQLITE_OK!=(rc=openTransaction(pMain, p)) ){
520           return rc;
521         }
522       }
523     }
524     if( p->iMaxOff<(iOfst + iAmt) ){
525       p->iMaxOff = iOfst + iAmt;
526     }
527   }
528 
529   if( p->flags&SQLITE_OPEN_MAIN_DB && p->pWritable ){
530     if( iAmt<p->nPagesize
531      && p->nPagesize%iAmt==0
532      && iOfst>=(PENDING_BYTE+512)
533      && iOfst+iAmt<=PENDING_BYTE+p->nPagesize
534     ){
535       /* No-op. This special case is hit when the backup code is copying a
536       ** to a database with a larger page-size than the source database and
537       ** it needs to fill in the non-locking-region part of the original
538       ** pending-byte page.
539       */
540     }else{
541       u32 pgno = iOfst/p->nPagesize + 1;
542       assert( (iAmt==1||iAmt==p->nPagesize) && ((iOfst+iAmt)%p->nPagesize)==0 );
543       assert( pgno<=p->nPage || p->nSync>0 );
544       assert( pgno>p->nPage || sqlite3BitvecTest(p->pWritable, pgno) );
545     }
546   }
547 
548   rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
549   if( (p->flags&SQLITE_OPEN_MAIN_JOURNAL) && iAmt==12 ){
550     jt_file *pMain = locateDatabaseHandle(p->zName);
551     int rc2 = readJournalFile(p, pMain);
552     if( rc==SQLITE_OK ) rc = rc2;
553   }
554   return rc;
555 }
556 
557 /*
558 ** Truncate an jt-file.
559 */
560 static int jtTruncate(sqlite3_file *pFile, sqlite_int64 size){
561   jt_file *p = (jt_file *)pFile;
562   if( p->flags&SQLITE_OPEN_MAIN_JOURNAL && size==0 ){
563     /* Truncating a journal file. This is the end of a transaction. */
564     jt_file *pMain = locateDatabaseHandle(p->zName);
565     closeTransaction(pMain);
566   }
567   if( p->flags&SQLITE_OPEN_MAIN_DB && p->pWritable ){
568     u32 pgno;
569     u32 locking_page = (u32)(PENDING_BYTE/p->nPagesize+1);
570     for(pgno=size/p->nPagesize+1; pgno<=p->nPage; pgno++){
571       assert( pgno==locking_page || sqlite3BitvecTest(p->pWritable, pgno) );
572     }
573   }
574   return sqlite3OsTruncate(p->pReal, size);
575 }
576 
577 /*
578 ** Sync an jt-file.
579 */
580 static int jtSync(sqlite3_file *pFile, int flags){
581   jt_file *p = (jt_file *)pFile;
582 
583   if( p->flags&SQLITE_OPEN_MAIN_JOURNAL ){
584     int rc;
585     jt_file *pMain;                   /* The associated database file */
586 
587     /* The journal file is being synced. At this point, we inspect the
588     ** contents of the file up to this point and set each bit in the
589     ** jt_file.pWritable bitvec of the main database file associated with
590     ** this journal file.
591     */
592     pMain = locateDatabaseHandle(p->zName);
593     assert(pMain);
594 
595     /* Set the bitvec values */
596     if( pMain->pWritable ){
597       pMain->nSync++;
598       rc = readJournalFile(p, pMain);
599       if( rc!=SQLITE_OK ){
600         return rc;
601       }
602     }
603   }
604 
605   return sqlite3OsSync(p->pReal, flags);
606 }
607 
608 /*
609 ** Return the current file-size of an jt-file.
610 */
611 static int jtFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
612   jt_file *p = (jt_file *)pFile;
613   return sqlite3OsFileSize(p->pReal, pSize);
614 }
615 
616 /*
617 ** Lock an jt-file.
618 */
619 static int jtLock(sqlite3_file *pFile, int eLock){
620   int rc;
621   jt_file *p = (jt_file *)pFile;
622   rc = sqlite3OsLock(p->pReal, eLock);
623   if( rc==SQLITE_OK && eLock>p->eLock ){
624     p->eLock = eLock;
625   }
626   return rc;
627 }
628 
629 /*
630 ** Unlock an jt-file.
631 */
632 static int jtUnlock(sqlite3_file *pFile, int eLock){
633   int rc;
634   jt_file *p = (jt_file *)pFile;
635   rc = sqlite3OsUnlock(p->pReal, eLock);
636   if( rc==SQLITE_OK && eLock<p->eLock ){
637     p->eLock = eLock;
638   }
639   return rc;
640 }
641 
642 /*
643 ** Check if another file-handle holds a RESERVED lock on an jt-file.
644 */
645 static int jtCheckReservedLock(sqlite3_file *pFile, int *pResOut){
646   jt_file *p = (jt_file *)pFile;
647   return sqlite3OsCheckReservedLock(p->pReal, pResOut);
648 }
649 
650 /*
651 ** File control method. For custom operations on an jt-file.
652 */
653 static int jtFileControl(sqlite3_file *pFile, int op, void *pArg){
654   jt_file *p = (jt_file *)pFile;
655   return sqlite3OsFileControl(p->pReal, op, pArg);
656 }
657 
658 /*
659 ** Return the sector-size in bytes for an jt-file.
660 */
661 static int jtSectorSize(sqlite3_file *pFile){
662   jt_file *p = (jt_file *)pFile;
663   return sqlite3OsSectorSize(p->pReal);
664 }
665 
666 /*
667 ** Return the device characteristic flags supported by an jt-file.
668 */
669 static int jtDeviceCharacteristics(sqlite3_file *pFile){
670   jt_file *p = (jt_file *)pFile;
671   return sqlite3OsDeviceCharacteristics(p->pReal);
672 }
673 
674 /*
675 ** Open an jt file handle.
676 */
677 static int jtOpen(
678   sqlite3_vfs *pVfs,
679   const char *zName,
680   sqlite3_file *pFile,
681   int flags,
682   int *pOutFlags
683 ){
684   int rc;
685   jt_file *p = (jt_file *)pFile;
686   pFile->pMethods = 0;
687   p->pReal = (sqlite3_file *)&p[1];
688   p->pReal->pMethods = 0;
689   rc = sqlite3OsOpen(g.pVfs, zName, p->pReal, flags, pOutFlags);
690   assert( rc==SQLITE_OK || p->pReal->pMethods==0 );
691   if( rc==SQLITE_OK ){
692     pFile->pMethods = &jt_io_methods;
693     p->eLock = 0;
694     p->zName = zName;
695     p->flags = flags;
696     p->pNext = 0;
697     p->pWritable = 0;
698     p->aCksum = 0;
699     enterJtMutex();
700     if( zName ){
701       p->pNext = g.pList;
702       g.pList = p;
703     }
704     leaveJtMutex();
705   }
706   return rc;
707 }
708 
709 /*
710 ** Delete the file located at zPath. If the dirSync argument is true,
711 ** ensure the file-system modifications are synced to disk before
712 ** returning.
713 */
714 static int jtDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
715   int nPath = strlen(zPath);
716   if( nPath>8 && 0==strcmp("-journal", &zPath[nPath-8]) ){
717     /* Deleting a journal file. The end of a transaction. */
718     jt_file *pMain = locateDatabaseHandle(zPath);
719     if( pMain ){
720       closeTransaction(pMain);
721     }
722   }
723 
724   return sqlite3OsDelete(g.pVfs, zPath, dirSync);
725 }
726 
727 /*
728 ** Test for access permissions. Return true if the requested permission
729 ** is available, or false otherwise.
730 */
731 static int jtAccess(
732   sqlite3_vfs *pVfs,
733   const char *zPath,
734   int flags,
735   int *pResOut
736 ){
737   return sqlite3OsAccess(g.pVfs, zPath, flags, pResOut);
738 }
739 
740 /*
741 ** Populate buffer zOut with the full canonical pathname corresponding
742 ** to the pathname in zPath. zOut is guaranteed to point to a buffer
743 ** of at least (JT_MAX_PATHNAME+1) bytes.
744 */
745 static int jtFullPathname(
746   sqlite3_vfs *pVfs,
747   const char *zPath,
748   int nOut,
749   char *zOut
750 ){
751   return sqlite3OsFullPathname(g.pVfs, zPath, nOut, zOut);
752 }
753 
754 /*
755 ** Open the dynamic library located at zPath and return a handle.
756 */
757 static void *jtDlOpen(sqlite3_vfs *pVfs, const char *zPath){
758   return g.pVfs->xDlOpen(g.pVfs, zPath);
759 }
760 
761 /*
762 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
763 ** utf-8 string describing the most recent error encountered associated
764 ** with dynamic libraries.
765 */
766 static void jtDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
767   g.pVfs->xDlError(g.pVfs, nByte, zErrMsg);
768 }
769 
770 /*
771 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
772 */
773 static void (*jtDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
774   return g.pVfs->xDlSym(g.pVfs, p, zSym);
775 }
776 
777 /*
778 ** Close the dynamic library handle pHandle.
779 */
780 static void jtDlClose(sqlite3_vfs *pVfs, void *pHandle){
781   g.pVfs->xDlClose(g.pVfs, pHandle);
782 }
783 
784 /*
785 ** Populate the buffer pointed to by zBufOut with nByte bytes of
786 ** random data.
787 */
788 static int jtRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
789   return sqlite3OsRandomness(g.pVfs, nByte, zBufOut);
790 }
791 
792 /*
793 ** Sleep for nMicro microseconds. Return the number of microseconds
794 ** actually slept.
795 */
796 static int jtSleep(sqlite3_vfs *pVfs, int nMicro){
797   return sqlite3OsSleep(g.pVfs, nMicro);
798 }
799 
800 /*
801 ** Return the current time as a Julian Day number in *pTimeOut.
802 */
803 static int jtCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
804   return g.pVfs->xCurrentTime(g.pVfs, pTimeOut);
805 }
806 
807 /**************************************************************************
808 ** Start of public API.
809 */
810 
811 /*
812 ** Configure the jt VFS as a wrapper around the VFS named by parameter
813 ** zWrap. If the isDefault parameter is true, then the jt VFS is installed
814 ** as the new default VFS for SQLite connections. If isDefault is not
815 ** true, then the jt VFS is installed as non-default. In this case it
816 ** is available via its name, "jt".
817 */
818 int jt_register(char *zWrap, int isDefault){
819   g.pVfs = sqlite3_vfs_find(zWrap);
820   if( g.pVfs==0 ){
821     return SQLITE_ERROR;
822   }
823   jt_vfs.szOsFile = sizeof(jt_file) + g.pVfs->szOsFile;
824   sqlite3_vfs_register(&jt_vfs, isDefault);
825   return SQLITE_OK;
826 }
827 
828 /*
829 ** Uninstall the jt VFS, if it is installed.
830 */
831 void jt_unregister(void){
832   sqlite3_vfs_unregister(&jt_vfs);
833 }
834 
835 #endif
836