xref: /sqlite-3.40.0/src/test_journal.c (revision 007d6c3a)
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 static int jtCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
165 
166 static sqlite3_vfs jt_vfs = {
167   2,                             /* iVersion */
168   sizeof(jt_file),               /* szOsFile */
169   JT_MAX_PATHNAME,               /* mxPathname */
170   0,                             /* pNext */
171   JT_VFS_NAME,                   /* zName */
172   0,                             /* pAppData */
173   jtOpen,                        /* xOpen */
174   jtDelete,                      /* xDelete */
175   jtAccess,                      /* xAccess */
176   jtFullPathname,                /* xFullPathname */
177   jtDlOpen,                      /* xDlOpen */
178   jtDlError,                     /* xDlError */
179   jtDlSym,                       /* xDlSym */
180   jtDlClose,                     /* xDlClose */
181   jtRandomness,                  /* xRandomness */
182   jtSleep,                       /* xSleep */
183   jtCurrentTime,                 /* xCurrentTime */
184   0,                             /* xGetLastError */
185   0,                             /* xRename */
186   jtCurrentTimeInt64             /* xCurrentTimeInt64 */
187 };
188 
189 static sqlite3_io_methods jt_io_methods = {
190   1,                             /* iVersion */
191   jtClose,                       /* xClose */
192   jtRead,                        /* xRead */
193   jtWrite,                       /* xWrite */
194   jtTruncate,                    /* xTruncate */
195   jtSync,                        /* xSync */
196   jtFileSize,                    /* xFileSize */
197   jtLock,                        /* xLock */
198   jtUnlock,                      /* xUnlock */
199   jtCheckReservedLock,           /* xCheckReservedLock */
200   jtFileControl,                 /* xFileControl */
201   jtSectorSize,                  /* xSectorSize */
202   jtDeviceCharacteristics        /* xDeviceCharacteristics */
203 };
204 
205 struct JtGlobal {
206   sqlite3_vfs *pVfs;             /* Parent VFS */
207   jt_file *pList;                /* List of all open files */
208 };
209 static struct JtGlobal g = {0, 0};
210 
211 /*
212 ** Functions to obtain and relinquish a mutex to protect g.pList. The
213 ** STATIC_PRNG mutex is reused, purely for the sake of convenience.
214 */
215 static void enterJtMutex(void){
216   sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PRNG));
217 }
218 static void leaveJtMutex(void){
219   sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PRNG));
220 }
221 
222 extern int sqlite3_io_error_pending;
223 extern int sqlite3_io_error_hit;
224 static void stop_ioerr_simulation(int *piSave, int *piSave2){
225   *piSave = sqlite3_io_error_pending;
226   *piSave2 = sqlite3_io_error_hit;
227   sqlite3_io_error_pending = -1;
228   sqlite3_io_error_hit = 0;
229 }
230 static void start_ioerr_simulation(int iSave, int iSave2){
231   sqlite3_io_error_pending = iSave;
232   sqlite3_io_error_hit = iSave2;
233 }
234 
235 /*
236 ** The jt_file pointed to by the argument may or may not be a file-handle
237 ** open on a main database file. If it is, and a transaction is currently
238 ** opened on the file, then discard all transaction related data.
239 */
240 static void closeTransaction(jt_file *p){
241   sqlite3BitvecDestroy(p->pWritable);
242   sqlite3_free(p->aCksum);
243   p->pWritable = 0;
244   p->aCksum = 0;
245   p->nSync = 0;
246 }
247 
248 /*
249 ** Close an jt-file.
250 */
251 static int jtClose(sqlite3_file *pFile){
252   jt_file **pp;
253   jt_file *p = (jt_file *)pFile;
254 
255   closeTransaction(p);
256   enterJtMutex();
257   if( p->zName ){
258     for(pp=&g.pList; *pp!=p; pp=&(*pp)->pNext);
259     *pp = p->pNext;
260   }
261   leaveJtMutex();
262   return sqlite3OsClose(p->pReal);
263 }
264 
265 /*
266 ** Read data from an jt-file.
267 */
268 static int jtRead(
269   sqlite3_file *pFile,
270   void *zBuf,
271   int iAmt,
272   sqlite_int64 iOfst
273 ){
274   jt_file *p = (jt_file *)pFile;
275   return sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
276 }
277 
278 /*
279 ** Parameter zJournal is the name of a journal file that is currently
280 ** open. This function locates and returns the handle opened on the
281 ** corresponding database file by the pager that currently has the
282 ** journal file opened. This file-handle is identified by the
283 ** following properties:
284 **
285 **   a) SQLITE_OPEN_MAIN_DB was specified when the file was opened.
286 **
287 **   b) The file-name specified when the file was opened matches
288 **      all but the final 8 characters of the journal file name.
289 **
290 **   c) There is currently a reserved lock on the file.
291 **/
292 static jt_file *locateDatabaseHandle(const char *zJournal){
293   jt_file *pMain = 0;
294   enterJtMutex();
295   for(pMain=g.pList; pMain; pMain=pMain->pNext){
296     int nName = strlen(zJournal) - strlen("-journal");
297     if( (pMain->flags&SQLITE_OPEN_MAIN_DB)
298      && (strlen(pMain->zName)==nName)
299      && 0==memcmp(pMain->zName, zJournal, nName)
300      && (pMain->eLock>=SQLITE_LOCK_RESERVED)
301     ){
302       break;
303     }
304   }
305   leaveJtMutex();
306   return pMain;
307 }
308 
309 /*
310 ** Parameter z points to a buffer of 4 bytes in size containing a
311 ** unsigned 32-bit integer stored in big-endian format. Decode the
312 ** integer and return its value.
313 */
314 static u32 decodeUint32(const unsigned char *z){
315   return (z[0]<<24) + (z[1]<<16) + (z[2]<<8) + z[3];
316 }
317 
318 /*
319 ** Calculate a checksum from the buffer of length n bytes pointed to
320 ** by parameter z.
321 */
322 static u32 genCksum(const unsigned char *z, int n){
323   int i;
324   u32 cksum = 0;
325   for(i=0; i<n; i++){
326     cksum = cksum + z[i] + (cksum<<3);
327   }
328   return cksum;
329 }
330 
331 /*
332 ** The first argument, zBuf, points to a buffer containing a 28 byte
333 ** serialized journal header. This function deserializes four of the
334 ** integer fields contained in the journal header and writes their
335 ** values to the output variables.
336 **
337 ** SQLITE_OK is returned if the journal-header is successfully
338 ** decoded. Otherwise, SQLITE_ERROR.
339 */
340 static int decodeJournalHdr(
341   const unsigned char *zBuf,         /* Input: 28 byte journal header */
342   u32 *pnRec,                        /* Out: Number of journalled records */
343   u32 *pnPage,                       /* Out: Original database page count */
344   u32 *pnSector,                     /* Out: Sector size in bytes */
345   u32 *pnPagesize                    /* Out: Page size in bytes */
346 ){
347   unsigned char aMagic[] = { 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7 };
348   if( memcmp(aMagic, zBuf, 8) ) return SQLITE_ERROR;
349   if( pnRec ) *pnRec = decodeUint32(&zBuf[8]);
350   if( pnPage ) *pnPage = decodeUint32(&zBuf[16]);
351   if( pnSector ) *pnSector = decodeUint32(&zBuf[20]);
352   if( pnPagesize ) *pnPagesize = decodeUint32(&zBuf[24]);
353   return SQLITE_OK;
354 }
355 
356 /*
357 ** This function is called when a new transaction is opened, just after
358 ** the first journal-header is written to the journal file.
359 */
360 static int openTransaction(jt_file *pMain, jt_file *pJournal){
361   unsigned char *aData;
362   sqlite3_file *p = pMain->pReal;
363   int rc = SQLITE_OK;
364 
365   aData = sqlite3_malloc(pMain->nPagesize);
366   pMain->pWritable = sqlite3BitvecCreate(pMain->nPage);
367   pMain->aCksum = sqlite3_malloc(sizeof(u32) * (pMain->nPage + 1));
368   pJournal->iMaxOff = 0;
369 
370   if( !pMain->pWritable || !pMain->aCksum || !aData ){
371     rc = SQLITE_IOERR_NOMEM;
372   }else if( pMain->nPage>0 ){
373     u32 iTrunk;
374     int iSave;
375     int iSave2;
376 
377     stop_ioerr_simulation(&iSave, &iSave2);
378 
379     /* Read the database free-list. Add the page-number for each free-list
380     ** leaf to the jt_file.pWritable bitvec.
381     */
382     rc = sqlite3OsRead(p, aData, pMain->nPagesize, 0);
383     iTrunk = decodeUint32(&aData[32]);
384     while( rc==SQLITE_OK && iTrunk>0 ){
385       u32 nLeaf;
386       u32 iLeaf;
387       sqlite3_int64 iOff = (iTrunk-1)*pMain->nPagesize;
388       rc = sqlite3OsRead(p, aData, pMain->nPagesize, iOff);
389       nLeaf = decodeUint32(&aData[4]);
390       for(iLeaf=0; rc==SQLITE_OK && iLeaf<nLeaf; iLeaf++){
391         u32 pgno = decodeUint32(&aData[8+4*iLeaf]);
392         sqlite3BitvecSet(pMain->pWritable, pgno);
393       }
394       iTrunk = decodeUint32(aData);
395     }
396 
397     /* Calculate and store a checksum for each page in the database file. */
398     if( rc==SQLITE_OK ){
399       int ii;
400       for(ii=0; rc==SQLITE_OK && ii<pMain->nPage; ii++){
401         i64 iOff = (i64)(pMain->nPagesize) * (i64)ii;
402         if( iOff==PENDING_BYTE ) continue;
403         rc = sqlite3OsRead(pMain->pReal, aData, pMain->nPagesize, iOff);
404         pMain->aCksum[ii] = genCksum(aData, pMain->nPagesize);
405       }
406     }
407 
408     start_ioerr_simulation(iSave, iSave2);
409   }
410 
411   sqlite3_free(aData);
412   return rc;
413 }
414 
415 /*
416 ** The first argument to this function is a handle open on a journal file.
417 ** This function reads the journal file and adds the page number for each
418 ** page in the journal to the Bitvec object passed as the second argument.
419 */
420 static int readJournalFile(jt_file *p, jt_file *pMain){
421   int rc = SQLITE_OK;
422   unsigned char zBuf[28];
423   sqlite3_file *pReal = p->pReal;
424   sqlite3_int64 iOff = 0;
425   sqlite3_int64 iSize = p->iMaxOff;
426   unsigned char *aPage;
427   int iSave;
428   int iSave2;
429 
430   aPage = sqlite3_malloc(pMain->nPagesize);
431   if( !aPage ){
432     return SQLITE_IOERR_NOMEM;
433   }
434 
435   stop_ioerr_simulation(&iSave, &iSave2);
436 
437   while( rc==SQLITE_OK && iOff<iSize ){
438     u32 nRec, nPage, nSector, nPagesize;
439     u32 ii;
440 
441     /* Read and decode the next journal-header from the journal file. */
442     rc = sqlite3OsRead(pReal, zBuf, 28, iOff);
443     if( rc!=SQLITE_OK
444      || decodeJournalHdr(zBuf, &nRec, &nPage, &nSector, &nPagesize)
445     ){
446       goto finish_rjf;
447     }
448     iOff += nSector;
449 
450     if( nRec==0 ){
451       /* A trick. There might be another journal-header immediately
452       ** following this one. In this case, 0 records means 0 records,
453       ** not "read until the end of the file". See also ticket #2565.
454       */
455       if( iSize>=(iOff+nSector) ){
456         rc = sqlite3OsRead(pReal, zBuf, 28, iOff);
457         if( rc!=SQLITE_OK || 0==decodeJournalHdr(zBuf, 0, 0, 0, 0) ){
458           continue;
459         }
460       }
461       nRec = (iSize-iOff) / (pMain->nPagesize+8);
462     }
463 
464     /* Read all the records that follow the journal-header just read. */
465     for(ii=0; rc==SQLITE_OK && ii<nRec && iOff<iSize; ii++){
466       u32 pgno;
467       rc = sqlite3OsRead(pReal, zBuf, 4, iOff);
468       if( rc==SQLITE_OK ){
469         pgno = decodeUint32(zBuf);
470         if( pgno>0 && pgno<=pMain->nPage ){
471           if( 0==sqlite3BitvecTest(pMain->pWritable, pgno) ){
472             rc = sqlite3OsRead(pReal, aPage, pMain->nPagesize, iOff+4);
473             if( rc==SQLITE_OK ){
474               u32 cksum = genCksum(aPage, pMain->nPagesize);
475               assert( cksum==pMain->aCksum[pgno-1] );
476             }
477           }
478           sqlite3BitvecSet(pMain->pWritable, pgno);
479         }
480         iOff += (8 + pMain->nPagesize);
481       }
482     }
483 
484     iOff = ((iOff + (nSector-1)) / nSector) * nSector;
485   }
486 
487 finish_rjf:
488   start_ioerr_simulation(iSave, iSave2);
489   sqlite3_free(aPage);
490   if( rc==SQLITE_IOERR_SHORT_READ ){
491     rc = SQLITE_OK;
492   }
493   return rc;
494 }
495 
496 
497 /*
498 ** Write data to an jt-file.
499 */
500 static int jtWrite(
501   sqlite3_file *pFile,
502   const void *zBuf,
503   int iAmt,
504   sqlite_int64 iOfst
505 ){
506   int rc;
507   jt_file *p = (jt_file *)pFile;
508   if( p->flags&SQLITE_OPEN_MAIN_JOURNAL ){
509     if( iOfst==0 ){
510       jt_file *pMain = locateDatabaseHandle(p->zName);
511       assert( pMain );
512 
513       if( iAmt==28 ){
514         /* Zeroing the first journal-file header. This is the end of a
515         ** transaction. */
516         closeTransaction(pMain);
517       }else if( iAmt!=12 ){
518         /* Writing the first journal header to a journal file. This happens
519         ** when a transaction is first started.  */
520         u8 *z = (u8 *)zBuf;
521         pMain->nPage = decodeUint32(&z[16]);
522         pMain->nPagesize = decodeUint32(&z[24]);
523         if( SQLITE_OK!=(rc=openTransaction(pMain, p)) ){
524           return rc;
525         }
526       }
527     }
528     if( p->iMaxOff<(iOfst + iAmt) ){
529       p->iMaxOff = iOfst + iAmt;
530     }
531   }
532 
533   if( p->flags&SQLITE_OPEN_MAIN_DB && p->pWritable ){
534     if( iAmt<p->nPagesize
535      && p->nPagesize%iAmt==0
536      && iOfst>=(PENDING_BYTE+512)
537      && iOfst+iAmt<=PENDING_BYTE+p->nPagesize
538     ){
539       /* No-op. This special case is hit when the backup code is copying a
540       ** to a database with a larger page-size than the source database and
541       ** it needs to fill in the non-locking-region part of the original
542       ** pending-byte page.
543       */
544     }else{
545       u32 pgno = iOfst/p->nPagesize + 1;
546       assert( (iAmt==1||iAmt==p->nPagesize) && ((iOfst+iAmt)%p->nPagesize)==0 );
547       assert( pgno<=p->nPage || p->nSync>0 );
548       assert( pgno>p->nPage || sqlite3BitvecTest(p->pWritable, pgno) );
549     }
550   }
551 
552   rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
553   if( (p->flags&SQLITE_OPEN_MAIN_JOURNAL) && iAmt==12 ){
554     jt_file *pMain = locateDatabaseHandle(p->zName);
555     int rc2 = readJournalFile(p, pMain);
556     if( rc==SQLITE_OK ) rc = rc2;
557   }
558   return rc;
559 }
560 
561 /*
562 ** Truncate an jt-file.
563 */
564 static int jtTruncate(sqlite3_file *pFile, sqlite_int64 size){
565   jt_file *p = (jt_file *)pFile;
566   if( p->flags&SQLITE_OPEN_MAIN_JOURNAL && size==0 ){
567     /* Truncating a journal file. This is the end of a transaction. */
568     jt_file *pMain = locateDatabaseHandle(p->zName);
569     closeTransaction(pMain);
570   }
571   if( p->flags&SQLITE_OPEN_MAIN_DB && p->pWritable ){
572     u32 pgno;
573     u32 locking_page = (u32)(PENDING_BYTE/p->nPagesize+1);
574     for(pgno=size/p->nPagesize+1; pgno<=p->nPage; pgno++){
575       assert( pgno==locking_page || sqlite3BitvecTest(p->pWritable, pgno) );
576     }
577   }
578   return sqlite3OsTruncate(p->pReal, size);
579 }
580 
581 /*
582 ** Sync an jt-file.
583 */
584 static int jtSync(sqlite3_file *pFile, int flags){
585   jt_file *p = (jt_file *)pFile;
586 
587   if( p->flags&SQLITE_OPEN_MAIN_JOURNAL ){
588     int rc;
589     jt_file *pMain;                   /* The associated database file */
590 
591     /* The journal file is being synced. At this point, we inspect the
592     ** contents of the file up to this point and set each bit in the
593     ** jt_file.pWritable bitvec of the main database file associated with
594     ** this journal file.
595     */
596     pMain = locateDatabaseHandle(p->zName);
597     assert(pMain);
598 
599     /* Set the bitvec values */
600     if( pMain->pWritable ){
601       pMain->nSync++;
602       rc = readJournalFile(p, pMain);
603       if( rc!=SQLITE_OK ){
604         return rc;
605       }
606     }
607   }
608 
609   return sqlite3OsSync(p->pReal, flags);
610 }
611 
612 /*
613 ** Return the current file-size of an jt-file.
614 */
615 static int jtFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
616   jt_file *p = (jt_file *)pFile;
617   return sqlite3OsFileSize(p->pReal, pSize);
618 }
619 
620 /*
621 ** Lock an jt-file.
622 */
623 static int jtLock(sqlite3_file *pFile, int eLock){
624   int rc;
625   jt_file *p = (jt_file *)pFile;
626   rc = sqlite3OsLock(p->pReal, eLock);
627   if( rc==SQLITE_OK && eLock>p->eLock ){
628     p->eLock = eLock;
629   }
630   return rc;
631 }
632 
633 /*
634 ** Unlock an jt-file.
635 */
636 static int jtUnlock(sqlite3_file *pFile, int eLock){
637   int rc;
638   jt_file *p = (jt_file *)pFile;
639   rc = sqlite3OsUnlock(p->pReal, eLock);
640   if( rc==SQLITE_OK && eLock<p->eLock ){
641     p->eLock = eLock;
642   }
643   return rc;
644 }
645 
646 /*
647 ** Check if another file-handle holds a RESERVED lock on an jt-file.
648 */
649 static int jtCheckReservedLock(sqlite3_file *pFile, int *pResOut){
650   jt_file *p = (jt_file *)pFile;
651   return sqlite3OsCheckReservedLock(p->pReal, pResOut);
652 }
653 
654 /*
655 ** File control method. For custom operations on an jt-file.
656 */
657 static int jtFileControl(sqlite3_file *pFile, int op, void *pArg){
658   jt_file *p = (jt_file *)pFile;
659   return sqlite3OsFileControl(p->pReal, op, pArg);
660 }
661 
662 /*
663 ** Return the sector-size in bytes for an jt-file.
664 */
665 static int jtSectorSize(sqlite3_file *pFile){
666   jt_file *p = (jt_file *)pFile;
667   return sqlite3OsSectorSize(p->pReal);
668 }
669 
670 /*
671 ** Return the device characteristic flags supported by an jt-file.
672 */
673 static int jtDeviceCharacteristics(sqlite3_file *pFile){
674   jt_file *p = (jt_file *)pFile;
675   return sqlite3OsDeviceCharacteristics(p->pReal);
676 }
677 
678 /*
679 ** Open an jt file handle.
680 */
681 static int jtOpen(
682   sqlite3_vfs *pVfs,
683   const char *zName,
684   sqlite3_file *pFile,
685   int flags,
686   int *pOutFlags
687 ){
688   int rc;
689   jt_file *p = (jt_file *)pFile;
690   pFile->pMethods = 0;
691   p->pReal = (sqlite3_file *)&p[1];
692   p->pReal->pMethods = 0;
693   rc = sqlite3OsOpen(g.pVfs, zName, p->pReal, flags, pOutFlags);
694   assert( rc==SQLITE_OK || p->pReal->pMethods==0 );
695   if( rc==SQLITE_OK ){
696     pFile->pMethods = &jt_io_methods;
697     p->eLock = 0;
698     p->zName = zName;
699     p->flags = flags;
700     p->pNext = 0;
701     p->pWritable = 0;
702     p->aCksum = 0;
703     enterJtMutex();
704     if( zName ){
705       p->pNext = g.pList;
706       g.pList = p;
707     }
708     leaveJtMutex();
709   }
710   return rc;
711 }
712 
713 /*
714 ** Delete the file located at zPath. If the dirSync argument is true,
715 ** ensure the file-system modifications are synced to disk before
716 ** returning.
717 */
718 static int jtDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
719   int nPath = strlen(zPath);
720   if( nPath>8 && 0==strcmp("-journal", &zPath[nPath-8]) ){
721     /* Deleting a journal file. The end of a transaction. */
722     jt_file *pMain = locateDatabaseHandle(zPath);
723     if( pMain ){
724       closeTransaction(pMain);
725     }
726   }
727 
728   return sqlite3OsDelete(g.pVfs, zPath, dirSync);
729 }
730 
731 /*
732 ** Test for access permissions. Return true if the requested permission
733 ** is available, or false otherwise.
734 */
735 static int jtAccess(
736   sqlite3_vfs *pVfs,
737   const char *zPath,
738   int flags,
739   int *pResOut
740 ){
741   return sqlite3OsAccess(g.pVfs, zPath, flags, pResOut);
742 }
743 
744 /*
745 ** Populate buffer zOut with the full canonical pathname corresponding
746 ** to the pathname in zPath. zOut is guaranteed to point to a buffer
747 ** of at least (JT_MAX_PATHNAME+1) bytes.
748 */
749 static int jtFullPathname(
750   sqlite3_vfs *pVfs,
751   const char *zPath,
752   int nOut,
753   char *zOut
754 ){
755   return sqlite3OsFullPathname(g.pVfs, zPath, nOut, zOut);
756 }
757 
758 /*
759 ** Open the dynamic library located at zPath and return a handle.
760 */
761 static void *jtDlOpen(sqlite3_vfs *pVfs, const char *zPath){
762   return g.pVfs->xDlOpen(g.pVfs, zPath);
763 }
764 
765 /*
766 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
767 ** utf-8 string describing the most recent error encountered associated
768 ** with dynamic libraries.
769 */
770 static void jtDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
771   g.pVfs->xDlError(g.pVfs, nByte, zErrMsg);
772 }
773 
774 /*
775 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
776 */
777 static void (*jtDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
778   return g.pVfs->xDlSym(g.pVfs, p, zSym);
779 }
780 
781 /*
782 ** Close the dynamic library handle pHandle.
783 */
784 static void jtDlClose(sqlite3_vfs *pVfs, void *pHandle){
785   g.pVfs->xDlClose(g.pVfs, pHandle);
786 }
787 
788 /*
789 ** Populate the buffer pointed to by zBufOut with nByte bytes of
790 ** random data.
791 */
792 static int jtRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
793   return sqlite3OsRandomness(g.pVfs, nByte, zBufOut);
794 }
795 
796 /*
797 ** Sleep for nMicro microseconds. Return the number of microseconds
798 ** actually slept.
799 */
800 static int jtSleep(sqlite3_vfs *pVfs, int nMicro){
801   return sqlite3OsSleep(g.pVfs, nMicro);
802 }
803 
804 /*
805 ** Return the current time as a Julian Day number in *pTimeOut.
806 */
807 static int jtCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
808   return g.pVfs->xCurrentTime(g.pVfs, pTimeOut);
809 }
810 /*
811 ** Return the current time as a Julian Day number in *pTimeOut.
812 */
813 static int jtCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
814   return g.pVfs->xCurrentTimeInt64(g.pVfs, pTimeOut);
815 }
816 
817 /**************************************************************************
818 ** Start of public API.
819 */
820 
821 /*
822 ** Configure the jt VFS as a wrapper around the VFS named by parameter
823 ** zWrap. If the isDefault parameter is true, then the jt VFS is installed
824 ** as the new default VFS for SQLite connections. If isDefault is not
825 ** true, then the jt VFS is installed as non-default. In this case it
826 ** is available via its name, "jt".
827 */
828 int jt_register(char *zWrap, int isDefault){
829   g.pVfs = sqlite3_vfs_find(zWrap);
830   if( g.pVfs==0 ){
831     return SQLITE_ERROR;
832   }
833   jt_vfs.szOsFile = sizeof(jt_file) + g.pVfs->szOsFile;
834   if( g.pVfs->iVersion==1 ){
835     jt_vfs.iVersion = 1;
836   }else if( g.pVfs->xCurrentTimeInt64==0 ){
837     jt_vfs.xCurrentTimeInt64 = 0;
838   }
839   sqlite3_vfs_register(&jt_vfs, isDefault);
840   return SQLITE_OK;
841 }
842 
843 /*
844 ** Uninstall the jt VFS, if it is installed.
845 */
846 void jt_unregister(void){
847   sqlite3_vfs_unregister(&jt_vfs);
848 }
849 
850 #endif
851