xref: /sqlite-3.40.0/src/test_vfs.c (revision 789efdb9)
1 /*
2 ** 2010 May 05
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 the implementation of the Tcl [testvfs] command,
14 ** used to create SQLite VFS implementations with various properties and
15 ** instrumentation to support testing SQLite.
16 **
17 **   testvfs VFSNAME ?OPTIONS?
18 **
19 ** Available options are:
20 **
21 **   -noshm      BOOLEAN        (True to omit shm methods. Default false)
22 **   -default    BOOLEAN        (True to make the vfs default. Default false)
23 **   -szosfile   INTEGER        (Value for sqlite3_vfs.szOsFile)
24 **   -mxpathname INTEGER        (Value for sqlite3_vfs.mxPathname)
25 **   -iversion   INTEGER        (Value for sqlite3_vfs.iVersion)
26 */
27 #if SQLITE_TEST          /* This file is used for testing only */
28 
29 #include "sqlite3.h"
30 #include "sqliteInt.h"
31 
32 typedef struct Testvfs Testvfs;
33 typedef struct TestvfsShm TestvfsShm;
34 typedef struct TestvfsBuffer TestvfsBuffer;
35 typedef struct TestvfsFile TestvfsFile;
36 typedef struct TestvfsFd TestvfsFd;
37 
38 /*
39 ** An open file handle.
40 */
41 struct TestvfsFile {
42   sqlite3_file base;              /* Base class.  Must be first */
43   TestvfsFd *pFd;                 /* File data */
44 };
45 #define tvfsGetFd(pFile) (((TestvfsFile *)pFile)->pFd)
46 
47 struct TestvfsFd {
48   sqlite3_vfs *pVfs;              /* The VFS */
49   const char *zFilename;          /* Filename as passed to xOpen() */
50   sqlite3_file *pReal;            /* The real, underlying file descriptor */
51   Tcl_Obj *pShmId;                /* Shared memory id for Tcl callbacks */
52 
53   TestvfsBuffer *pShm;            /* Shared memory buffer */
54   u32 excllock;                   /* Mask of exclusive locks */
55   u32 sharedlock;                 /* Mask of shared locks */
56   TestvfsFd *pNext;               /* Next handle opened on the same file */
57 };
58 
59 
60 #define FAULT_INJECT_NONE       0
61 #define FAULT_INJECT_TRANSIENT  1
62 #define FAULT_INJECT_PERSISTENT 2
63 
64 typedef struct TestFaultInject TestFaultInject;
65 struct TestFaultInject {
66   int iCnt;                       /* Remaining calls before fault injection */
67   int eFault;                     /* A FAULT_INJECT_* value */
68   int nFail;                      /* Number of faults injected */
69 };
70 
71 /*
72 ** An instance of this structure is allocated for each VFS created. The
73 ** sqlite3_vfs.pAppData field of the VFS structure registered with SQLite
74 ** is set to point to it.
75 */
76 struct Testvfs {
77   char *zName;                    /* Name of this VFS */
78   sqlite3_vfs *pParent;           /* The VFS to use for file IO */
79   sqlite3_vfs *pVfs;              /* The testvfs registered with SQLite */
80   Tcl_Interp *interp;             /* Interpreter to run script in */
81   Tcl_Obj *pScript;               /* Script to execute */
82   TestvfsBuffer *pBuffer;         /* List of shared buffers */
83   int isNoshm;
84   int isFullshm;
85 
86   int mask;                       /* Mask controlling [script] and [ioerr] */
87 
88   TestFaultInject ioerr_err;
89   TestFaultInject full_err;
90   TestFaultInject cantopen_err;
91 
92 #if 0
93   int iIoerrCnt;
94   int ioerr;
95   int nIoerrFail;
96   int iFullCnt;
97   int fullerr;
98   int nFullFail;
99 #endif
100 
101   int iDevchar;
102   int iSectorsize;
103 };
104 
105 /*
106 ** The Testvfs.mask variable is set to a combination of the following.
107 ** If a bit is clear in Testvfs.mask, then calls made by SQLite to the
108 ** corresponding VFS method is ignored for purposes of:
109 **
110 **   + Simulating IO errors, and
111 **   + Invoking the Tcl callback script.
112 */
113 #define TESTVFS_SHMOPEN_MASK      0x00000001
114 #define TESTVFS_SHMLOCK_MASK      0x00000010
115 #define TESTVFS_SHMMAP_MASK       0x00000020
116 #define TESTVFS_SHMBARRIER_MASK   0x00000040
117 #define TESTVFS_SHMCLOSE_MASK     0x00000080
118 
119 #define TESTVFS_OPEN_MASK         0x00000100
120 #define TESTVFS_SYNC_MASK         0x00000200
121 #define TESTVFS_DELETE_MASK       0x00000400
122 #define TESTVFS_CLOSE_MASK        0x00000800
123 #define TESTVFS_WRITE_MASK        0x00001000
124 #define TESTVFS_TRUNCATE_MASK     0x00002000
125 #define TESTVFS_ACCESS_MASK       0x00004000
126 #define TESTVFS_FULLPATHNAME_MASK 0x00008000
127 #define TESTVFS_READ_MASK         0x00010000
128 #define TESTVFS_UNLOCK_MASK       0x00020000
129 
130 #define TESTVFS_ALL_MASK          0x0003FFFF
131 
132 
133 #define TESTVFS_MAX_PAGES 1024
134 
135 /*
136 ** A shared-memory buffer. There is one of these objects for each shared
137 ** memory region opened by clients. If two clients open the same file,
138 ** there are two TestvfsFile structures but only one TestvfsBuffer structure.
139 */
140 struct TestvfsBuffer {
141   char *zFile;                    /* Associated file name */
142   int pgsz;                       /* Page size */
143   u8 *aPage[TESTVFS_MAX_PAGES];   /* Array of ckalloc'd pages */
144   TestvfsFd *pFile;               /* List of open handles */
145   TestvfsBuffer *pNext;           /* Next in linked list of all buffers */
146 };
147 
148 
149 #define PARENTVFS(x) (((Testvfs *)((x)->pAppData))->pParent)
150 
151 #define TESTVFS_MAX_ARGS 12
152 
153 
154 /*
155 ** Method declarations for TestvfsFile.
156 */
157 static int tvfsClose(sqlite3_file*);
158 static int tvfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
159 static int tvfsWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
160 static int tvfsTruncate(sqlite3_file*, sqlite3_int64 size);
161 static int tvfsSync(sqlite3_file*, int flags);
162 static int tvfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
163 static int tvfsLock(sqlite3_file*, int);
164 static int tvfsUnlock(sqlite3_file*, int);
165 static int tvfsCheckReservedLock(sqlite3_file*, int *);
166 static int tvfsFileControl(sqlite3_file*, int op, void *pArg);
167 static int tvfsSectorSize(sqlite3_file*);
168 static int tvfsDeviceCharacteristics(sqlite3_file*);
169 
170 /*
171 ** Method declarations for tvfs_vfs.
172 */
173 static int tvfsOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
174 static int tvfsDelete(sqlite3_vfs*, const char *zName, int syncDir);
175 static int tvfsAccess(sqlite3_vfs*, const char *zName, int flags, int *);
176 static int tvfsFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
177 #ifndef SQLITE_OMIT_LOAD_EXTENSION
178 static void *tvfsDlOpen(sqlite3_vfs*, const char *zFilename);
179 static void tvfsDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
180 static void (*tvfsDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void);
181 static void tvfsDlClose(sqlite3_vfs*, void*);
182 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
183 static int tvfsRandomness(sqlite3_vfs*, int nByte, char *zOut);
184 static int tvfsSleep(sqlite3_vfs*, int microseconds);
185 static int tvfsCurrentTime(sqlite3_vfs*, double*);
186 
187 static int tvfsShmOpen(sqlite3_file*);
188 static int tvfsShmLock(sqlite3_file*, int , int, int);
189 static int tvfsShmMap(sqlite3_file*,int,int,int, void volatile **);
190 static void tvfsShmBarrier(sqlite3_file*);
191 static int tvfsShmUnmap(sqlite3_file*, int);
192 
193 static int tvfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
194 static int tvfsUnfetch(sqlite3_file*, sqlite3_int64, void*);
195 
196 static sqlite3_io_methods tvfs_io_methods = {
197   3,                              /* iVersion */
198   tvfsClose,                      /* xClose */
199   tvfsRead,                       /* xRead */
200   tvfsWrite,                      /* xWrite */
201   tvfsTruncate,                   /* xTruncate */
202   tvfsSync,                       /* xSync */
203   tvfsFileSize,                   /* xFileSize */
204   tvfsLock,                       /* xLock */
205   tvfsUnlock,                     /* xUnlock */
206   tvfsCheckReservedLock,          /* xCheckReservedLock */
207   tvfsFileControl,                /* xFileControl */
208   tvfsSectorSize,                 /* xSectorSize */
209   tvfsDeviceCharacteristics,      /* xDeviceCharacteristics */
210   tvfsShmMap,                     /* xShmMap */
211   tvfsShmLock,                    /* xShmLock */
212   tvfsShmBarrier,                 /* xShmBarrier */
213   tvfsShmUnmap,                   /* xShmUnmap */
214   tvfsFetch,
215   tvfsUnfetch
216 };
217 
218 static int tvfsResultCode(Testvfs *p, int *pRc){
219   struct errcode {
220     int eCode;
221     const char *zCode;
222   } aCode[] = {
223     { SQLITE_OK,     "SQLITE_OK"     },
224     { SQLITE_ERROR,  "SQLITE_ERROR"  },
225     { SQLITE_IOERR,  "SQLITE_IOERR"  },
226     { SQLITE_LOCKED, "SQLITE_LOCKED" },
227     { SQLITE_BUSY,   "SQLITE_BUSY"   },
228   };
229 
230   const char *z;
231   int i;
232 
233   z = Tcl_GetStringResult(p->interp);
234   for(i=0; i<ArraySize(aCode); i++){
235     if( 0==strcmp(z, aCode[i].zCode) ){
236       *pRc = aCode[i].eCode;
237       return 1;
238     }
239   }
240 
241   return 0;
242 }
243 
244 static int tvfsInjectFault(TestFaultInject *p){
245   int ret = 0;
246   if( p->eFault ){
247     p->iCnt--;
248     if( p->iCnt==0 || (p->iCnt<0 && p->eFault==FAULT_INJECT_PERSISTENT ) ){
249       ret = 1;
250       p->nFail++;
251     }
252   }
253   return ret;
254 }
255 
256 
257 static int tvfsInjectIoerr(Testvfs *p){
258   return tvfsInjectFault(&p->ioerr_err);
259 }
260 
261 static int tvfsInjectFullerr(Testvfs *p){
262   return tvfsInjectFault(&p->full_err);
263 }
264 static int tvfsInjectCantopenerr(Testvfs *p){
265   return tvfsInjectFault(&p->cantopen_err);
266 }
267 
268 
269 static void tvfsExecTcl(
270   Testvfs *p,
271   const char *zMethod,
272   Tcl_Obj *arg1,
273   Tcl_Obj *arg2,
274   Tcl_Obj *arg3,
275   Tcl_Obj *arg4
276 ){
277   int rc;                         /* Return code from Tcl_EvalObj() */
278   Tcl_Obj *pEval;
279   assert( p->pScript );
280 
281   assert( zMethod );
282   assert( p );
283   assert( arg2==0 || arg1!=0 );
284   assert( arg3==0 || arg2!=0 );
285 
286   pEval = Tcl_DuplicateObj(p->pScript);
287   Tcl_IncrRefCount(p->pScript);
288   Tcl_ListObjAppendElement(p->interp, pEval, Tcl_NewStringObj(zMethod, -1));
289   if( arg1 ) Tcl_ListObjAppendElement(p->interp, pEval, arg1);
290   if( arg2 ) Tcl_ListObjAppendElement(p->interp, pEval, arg2);
291   if( arg3 ) Tcl_ListObjAppendElement(p->interp, pEval, arg3);
292   if( arg4 ) Tcl_ListObjAppendElement(p->interp, pEval, arg4);
293 
294   rc = Tcl_EvalObjEx(p->interp, pEval, TCL_EVAL_GLOBAL);
295   if( rc!=TCL_OK ){
296     Tcl_BackgroundError(p->interp);
297     Tcl_ResetResult(p->interp);
298   }
299 }
300 
301 
302 /*
303 ** Close an tvfs-file.
304 */
305 static int tvfsClose(sqlite3_file *pFile){
306   int rc;
307   TestvfsFile *pTestfile = (TestvfsFile *)pFile;
308   TestvfsFd *pFd = pTestfile->pFd;
309   Testvfs *p = (Testvfs *)pFd->pVfs->pAppData;
310 
311   if( p->pScript && p->mask&TESTVFS_CLOSE_MASK ){
312     tvfsExecTcl(p, "xClose",
313         Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, 0, 0
314     );
315   }
316 
317   if( pFd->pShmId ){
318     Tcl_DecrRefCount(pFd->pShmId);
319     pFd->pShmId = 0;
320   }
321   if( pFile->pMethods ){
322     ckfree((char *)pFile->pMethods);
323   }
324   rc = sqlite3OsClose(pFd->pReal);
325   ckfree((char *)pFd);
326   pTestfile->pFd = 0;
327   return rc;
328 }
329 
330 /*
331 ** Read data from an tvfs-file.
332 */
333 static int tvfsRead(
334   sqlite3_file *pFile,
335   void *zBuf,
336   int iAmt,
337   sqlite_int64 iOfst
338 ){
339   int rc = SQLITE_OK;
340   TestvfsFd *pFd = tvfsGetFd(pFile);
341   Testvfs *p = (Testvfs *)pFd->pVfs->pAppData;
342   if( p->pScript && p->mask&TESTVFS_READ_MASK ){
343     tvfsExecTcl(p, "xRead",
344         Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, 0, 0
345     );
346     tvfsResultCode(p, &rc);
347   }
348   if( rc==SQLITE_OK && p->mask&TESTVFS_READ_MASK && tvfsInjectIoerr(p) ){
349     rc = SQLITE_IOERR;
350   }
351   if( rc==SQLITE_OK ){
352     rc = sqlite3OsRead(pFd->pReal, zBuf, iAmt, iOfst);
353   }
354   return rc;
355 }
356 
357 /*
358 ** Write data to an tvfs-file.
359 */
360 static int tvfsWrite(
361   sqlite3_file *pFile,
362   const void *zBuf,
363   int iAmt,
364   sqlite_int64 iOfst
365 ){
366   int rc = SQLITE_OK;
367   TestvfsFd *pFd = tvfsGetFd(pFile);
368   Testvfs *p = (Testvfs *)pFd->pVfs->pAppData;
369 
370   if( p->pScript && p->mask&TESTVFS_WRITE_MASK ){
371     tvfsExecTcl(p, "xWrite",
372         Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId,
373         Tcl_NewWideIntObj(iOfst), Tcl_NewIntObj(iAmt)
374     );
375     tvfsResultCode(p, &rc);
376   }
377 
378   if( rc==SQLITE_OK && tvfsInjectFullerr(p) ){
379     rc = SQLITE_FULL;
380   }
381   if( rc==SQLITE_OK && p->mask&TESTVFS_WRITE_MASK && tvfsInjectIoerr(p) ){
382     rc = SQLITE_IOERR;
383   }
384 
385   if( rc==SQLITE_OK ){
386     rc = sqlite3OsWrite(pFd->pReal, zBuf, iAmt, iOfst);
387   }
388   return rc;
389 }
390 
391 /*
392 ** Truncate an tvfs-file.
393 */
394 static int tvfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
395   int rc = SQLITE_OK;
396   TestvfsFd *pFd = tvfsGetFd(pFile);
397   Testvfs *p = (Testvfs *)pFd->pVfs->pAppData;
398 
399   if( p->pScript && p->mask&TESTVFS_TRUNCATE_MASK ){
400     tvfsExecTcl(p, "xTruncate",
401         Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId, 0, 0
402     );
403     tvfsResultCode(p, &rc);
404   }
405 
406   if( rc==SQLITE_OK ){
407     rc = sqlite3OsTruncate(pFd->pReal, size);
408   }
409   return rc;
410 }
411 
412 /*
413 ** Sync an tvfs-file.
414 */
415 static int tvfsSync(sqlite3_file *pFile, int flags){
416   int rc = SQLITE_OK;
417   TestvfsFd *pFd = tvfsGetFd(pFile);
418   Testvfs *p = (Testvfs *)pFd->pVfs->pAppData;
419 
420   if( p->pScript && p->mask&TESTVFS_SYNC_MASK ){
421     char *zFlags;
422 
423     switch( flags ){
424       case SQLITE_SYNC_NORMAL:
425         zFlags = "normal";
426         break;
427       case SQLITE_SYNC_FULL:
428         zFlags = "full";
429         break;
430       case SQLITE_SYNC_NORMAL|SQLITE_SYNC_DATAONLY:
431         zFlags = "normal|dataonly";
432         break;
433       case SQLITE_SYNC_FULL|SQLITE_SYNC_DATAONLY:
434         zFlags = "full|dataonly";
435         break;
436       default:
437         assert(0);
438     }
439 
440     tvfsExecTcl(p, "xSync",
441         Tcl_NewStringObj(pFd->zFilename, -1), pFd->pShmId,
442         Tcl_NewStringObj(zFlags, -1), 0
443     );
444     tvfsResultCode(p, &rc);
445   }
446 
447   if( rc==SQLITE_OK && tvfsInjectFullerr(p) ) rc = SQLITE_FULL;
448 
449   if( rc==SQLITE_OK ){
450     rc = sqlite3OsSync(pFd->pReal, flags);
451   }
452 
453   return rc;
454 }
455 
456 /*
457 ** Return the current file-size of an tvfs-file.
458 */
459 static int tvfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
460   TestvfsFd *p = tvfsGetFd(pFile);
461   return sqlite3OsFileSize(p->pReal, pSize);
462 }
463 
464 /*
465 ** Lock an tvfs-file.
466 */
467 static int tvfsLock(sqlite3_file *pFile, int eLock){
468   TestvfsFd *p = tvfsGetFd(pFile);
469   return sqlite3OsLock(p->pReal, eLock);
470 }
471 
472 /*
473 ** Unlock an tvfs-file.
474 */
475 static int tvfsUnlock(sqlite3_file *pFile, int eLock){
476   TestvfsFd *pFd = tvfsGetFd(pFile);
477   Testvfs *p = (Testvfs *)pFd->pVfs->pAppData;
478   if( p->mask&TESTVFS_WRITE_MASK && tvfsInjectIoerr(p) ){
479     return SQLITE_IOERR_UNLOCK;
480   }
481   return sqlite3OsUnlock(pFd->pReal, eLock);
482 }
483 
484 /*
485 ** Check if another file-handle holds a RESERVED lock on an tvfs-file.
486 */
487 static int tvfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
488   TestvfsFd *p = tvfsGetFd(pFile);
489   return sqlite3OsCheckReservedLock(p->pReal, pResOut);
490 }
491 
492 /*
493 ** File control method. For custom operations on an tvfs-file.
494 */
495 static int tvfsFileControl(sqlite3_file *pFile, int op, void *pArg){
496   TestvfsFd *p = tvfsGetFd(pFile);
497   if( op==SQLITE_FCNTL_PRAGMA ){
498     char **argv = (char**)pArg;
499     if( sqlite3_stricmp(argv[1],"error")==0 ){
500       int rc = SQLITE_ERROR;
501       if( argv[2] ){
502         const char *z = argv[2];
503         int x = atoi(z);
504         if( x ){
505           rc = x;
506           while( sqlite3Isdigit(z[0]) ){ z++; }
507           while( sqlite3Isspace(z[0]) ){ z++; }
508         }
509         if( z[0] ) argv[0] = sqlite3_mprintf("%s", z);
510       }
511       return rc;
512     }
513     if( sqlite3_stricmp(argv[1], "filename")==0 ){
514       argv[0] = sqlite3_mprintf("%s", p->zFilename);
515       return SQLITE_OK;
516     }
517   }
518   return sqlite3OsFileControl(p->pReal, op, pArg);
519 }
520 
521 /*
522 ** Return the sector-size in bytes for an tvfs-file.
523 */
524 static int tvfsSectorSize(sqlite3_file *pFile){
525   TestvfsFd *pFd = tvfsGetFd(pFile);
526   Testvfs *p = (Testvfs *)pFd->pVfs->pAppData;
527   if( p->iSectorsize>=0 ){
528     return p->iSectorsize;
529   }
530   return sqlite3OsSectorSize(pFd->pReal);
531 }
532 
533 /*
534 ** Return the device characteristic flags supported by an tvfs-file.
535 */
536 static int tvfsDeviceCharacteristics(sqlite3_file *pFile){
537   TestvfsFd *pFd = tvfsGetFd(pFile);
538   Testvfs *p = (Testvfs *)pFd->pVfs->pAppData;
539   if( p->iDevchar>=0 ){
540     return p->iDevchar;
541   }
542   return sqlite3OsDeviceCharacteristics(pFd->pReal);
543 }
544 
545 /*
546 ** Open an tvfs file handle.
547 */
548 static int tvfsOpen(
549   sqlite3_vfs *pVfs,
550   const char *zName,
551   sqlite3_file *pFile,
552   int flags,
553   int *pOutFlags
554 ){
555   int rc;
556   TestvfsFile *pTestfile = (TestvfsFile *)pFile;
557   TestvfsFd *pFd;
558   Tcl_Obj *pId = 0;
559   Testvfs *p = (Testvfs *)pVfs->pAppData;
560 
561   pFd = (TestvfsFd *)ckalloc(sizeof(TestvfsFd) + PARENTVFS(pVfs)->szOsFile);
562   memset(pFd, 0, sizeof(TestvfsFd) + PARENTVFS(pVfs)->szOsFile);
563   pFd->pShm = 0;
564   pFd->pShmId = 0;
565   pFd->zFilename = zName;
566   pFd->pVfs = pVfs;
567   pFd->pReal = (sqlite3_file *)&pFd[1];
568   memset(pTestfile, 0, sizeof(TestvfsFile));
569   pTestfile->pFd = pFd;
570 
571   /* Evaluate the Tcl script:
572   **
573   **   SCRIPT xOpen FILENAME KEY-VALUE-ARGS
574   **
575   ** If the script returns an SQLite error code other than SQLITE_OK, an
576   ** error is returned to the caller. If it returns SQLITE_OK, the new
577   ** connection is named "anon". Otherwise, the value returned by the
578   ** script is used as the connection name.
579   */
580   Tcl_ResetResult(p->interp);
581   if( p->pScript && p->mask&TESTVFS_OPEN_MASK ){
582     Tcl_Obj *pArg = Tcl_NewObj();
583     Tcl_IncrRefCount(pArg);
584     if( flags&SQLITE_OPEN_MAIN_DB ){
585       const char *z = &zName[strlen(zName)+1];
586       while( *z ){
587         Tcl_ListObjAppendElement(0, pArg, Tcl_NewStringObj(z, -1));
588         z += strlen(z) + 1;
589         Tcl_ListObjAppendElement(0, pArg, Tcl_NewStringObj(z, -1));
590         z += strlen(z) + 1;
591       }
592     }
593     tvfsExecTcl(p, "xOpen", Tcl_NewStringObj(pFd->zFilename, -1), pArg, 0, 0);
594     Tcl_DecrRefCount(pArg);
595     if( tvfsResultCode(p, &rc) ){
596       if( rc!=SQLITE_OK ) return rc;
597     }else{
598       pId = Tcl_GetObjResult(p->interp);
599     }
600   }
601 
602   if( (p->mask&TESTVFS_OPEN_MASK) &&  tvfsInjectIoerr(p) ) return SQLITE_IOERR;
603   if( tvfsInjectCantopenerr(p) ) return SQLITE_CANTOPEN;
604   if( tvfsInjectFullerr(p) ) return SQLITE_FULL;
605 
606   if( !pId ){
607     pId = Tcl_NewStringObj("anon", -1);
608   }
609   Tcl_IncrRefCount(pId);
610   pFd->pShmId = pId;
611   Tcl_ResetResult(p->interp);
612 
613   rc = sqlite3OsOpen(PARENTVFS(pVfs), zName, pFd->pReal, flags, pOutFlags);
614   if( pFd->pReal->pMethods ){
615     sqlite3_io_methods *pMethods;
616     int nByte;
617 
618     if( pVfs->iVersion>1 ){
619       nByte = sizeof(sqlite3_io_methods);
620     }else{
621       nByte = offsetof(sqlite3_io_methods, xShmMap);
622     }
623 
624     pMethods = (sqlite3_io_methods *)ckalloc(nByte);
625     memcpy(pMethods, &tvfs_io_methods, nByte);
626     pMethods->iVersion = pFd->pReal->pMethods->iVersion;
627     if( pMethods->iVersion>pVfs->iVersion ){
628       pMethods->iVersion = pVfs->iVersion;
629     }
630     if( pVfs->iVersion>1 && ((Testvfs *)pVfs->pAppData)->isNoshm ){
631       pMethods->xShmUnmap = 0;
632       pMethods->xShmLock = 0;
633       pMethods->xShmBarrier = 0;
634       pMethods->xShmMap = 0;
635     }
636     pFile->pMethods = pMethods;
637   }
638 
639   return rc;
640 }
641 
642 /*
643 ** Delete the file located at zPath. If the dirSync argument is true,
644 ** ensure the file-system modifications are synced to disk before
645 ** returning.
646 */
647 static int tvfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
648   int rc = SQLITE_OK;
649   Testvfs *p = (Testvfs *)pVfs->pAppData;
650 
651   if( p->pScript && p->mask&TESTVFS_DELETE_MASK ){
652     tvfsExecTcl(p, "xDelete",
653         Tcl_NewStringObj(zPath, -1), Tcl_NewIntObj(dirSync), 0, 0
654     );
655     tvfsResultCode(p, &rc);
656   }
657   if( rc==SQLITE_OK ){
658     rc = sqlite3OsDelete(PARENTVFS(pVfs), zPath, dirSync);
659   }
660   return rc;
661 }
662 
663 /*
664 ** Test for access permissions. Return true if the requested permission
665 ** is available, or false otherwise.
666 */
667 static int tvfsAccess(
668   sqlite3_vfs *pVfs,
669   const char *zPath,
670   int flags,
671   int *pResOut
672 ){
673   Testvfs *p = (Testvfs *)pVfs->pAppData;
674   if( p->pScript && p->mask&TESTVFS_ACCESS_MASK ){
675     int rc;
676     char *zArg = 0;
677     if( flags==SQLITE_ACCESS_EXISTS ) zArg = "SQLITE_ACCESS_EXISTS";
678     if( flags==SQLITE_ACCESS_READWRITE ) zArg = "SQLITE_ACCESS_READWRITE";
679     if( flags==SQLITE_ACCESS_READ ) zArg = "SQLITE_ACCESS_READ";
680     tvfsExecTcl(p, "xAccess",
681         Tcl_NewStringObj(zPath, -1), Tcl_NewStringObj(zArg, -1), 0, 0
682     );
683     if( tvfsResultCode(p, &rc) ){
684       if( rc!=SQLITE_OK ) return rc;
685     }else{
686       Tcl_Interp *interp = p->interp;
687       if( TCL_OK==Tcl_GetBooleanFromObj(0, Tcl_GetObjResult(interp), pResOut) ){
688         return SQLITE_OK;
689       }
690     }
691   }
692   return sqlite3OsAccess(PARENTVFS(pVfs), zPath, flags, pResOut);
693 }
694 
695 /*
696 ** Populate buffer zOut with the full canonical pathname corresponding
697 ** to the pathname in zPath. zOut is guaranteed to point to a buffer
698 ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
699 */
700 static int tvfsFullPathname(
701   sqlite3_vfs *pVfs,
702   const char *zPath,
703   int nOut,
704   char *zOut
705 ){
706   Testvfs *p = (Testvfs *)pVfs->pAppData;
707   if( p->pScript && p->mask&TESTVFS_FULLPATHNAME_MASK ){
708     int rc;
709     tvfsExecTcl(p, "xFullPathname", Tcl_NewStringObj(zPath, -1), 0, 0, 0);
710     if( tvfsResultCode(p, &rc) ){
711       if( rc!=SQLITE_OK ) return rc;
712     }
713   }
714   return sqlite3OsFullPathname(PARENTVFS(pVfs), zPath, nOut, zOut);
715 }
716 
717 #ifndef SQLITE_OMIT_LOAD_EXTENSION
718 /*
719 ** Open the dynamic library located at zPath and return a handle.
720 */
721 static void *tvfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
722   return sqlite3OsDlOpen(PARENTVFS(pVfs), zPath);
723 }
724 
725 /*
726 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
727 ** utf-8 string describing the most recent error encountered associated
728 ** with dynamic libraries.
729 */
730 static void tvfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
731   sqlite3OsDlError(PARENTVFS(pVfs), nByte, zErrMsg);
732 }
733 
734 /*
735 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
736 */
737 static void (*tvfsDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
738   return sqlite3OsDlSym(PARENTVFS(pVfs), p, zSym);
739 }
740 
741 /*
742 ** Close the dynamic library handle pHandle.
743 */
744 static void tvfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
745   sqlite3OsDlClose(PARENTVFS(pVfs), pHandle);
746 }
747 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
748 
749 /*
750 ** Populate the buffer pointed to by zBufOut with nByte bytes of
751 ** random data.
752 */
753 static int tvfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
754   return sqlite3OsRandomness(PARENTVFS(pVfs), nByte, zBufOut);
755 }
756 
757 /*
758 ** Sleep for nMicro microseconds. Return the number of microseconds
759 ** actually slept.
760 */
761 static int tvfsSleep(sqlite3_vfs *pVfs, int nMicro){
762   return sqlite3OsSleep(PARENTVFS(pVfs), nMicro);
763 }
764 
765 /*
766 ** Return the current time as a Julian Day number in *pTimeOut.
767 */
768 static int tvfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
769   return PARENTVFS(pVfs)->xCurrentTime(PARENTVFS(pVfs), pTimeOut);
770 }
771 
772 static int tvfsShmOpen(sqlite3_file *pFile){
773   Testvfs *p;
774   int rc = SQLITE_OK;             /* Return code */
775   TestvfsBuffer *pBuffer;         /* Buffer to open connection to */
776   TestvfsFd *pFd;                 /* The testvfs file structure */
777 
778   pFd = tvfsGetFd(pFile);
779   p = (Testvfs *)pFd->pVfs->pAppData;
780   assert( 0==p->isFullshm );
781   assert( pFd->pShmId && pFd->pShm==0 && pFd->pNext==0 );
782 
783   /* Evaluate the Tcl script:
784   **
785   **   SCRIPT xShmOpen FILENAME
786   */
787   Tcl_ResetResult(p->interp);
788   if( p->pScript && p->mask&TESTVFS_SHMOPEN_MASK ){
789     tvfsExecTcl(p, "xShmOpen", Tcl_NewStringObj(pFd->zFilename, -1), 0, 0, 0);
790     if( tvfsResultCode(p, &rc) ){
791       if( rc!=SQLITE_OK ) return rc;
792     }
793   }
794 
795   assert( rc==SQLITE_OK );
796   if( p->mask&TESTVFS_SHMOPEN_MASK && tvfsInjectIoerr(p) ){
797     return SQLITE_IOERR;
798   }
799 
800   /* Search for a TestvfsBuffer. Create a new one if required. */
801   for(pBuffer=p->pBuffer; pBuffer; pBuffer=pBuffer->pNext){
802     if( 0==strcmp(pFd->zFilename, pBuffer->zFile) ) break;
803   }
804   if( !pBuffer ){
805     int nByte = sizeof(TestvfsBuffer) + (int)strlen(pFd->zFilename) + 1;
806     pBuffer = (TestvfsBuffer *)ckalloc(nByte);
807     memset(pBuffer, 0, nByte);
808     pBuffer->zFile = (char *)&pBuffer[1];
809     strcpy(pBuffer->zFile, pFd->zFilename);
810     pBuffer->pNext = p->pBuffer;
811     p->pBuffer = pBuffer;
812   }
813 
814   /* Connect the TestvfsBuffer to the new TestvfsShm handle and return. */
815   pFd->pNext = pBuffer->pFile;
816   pBuffer->pFile = pFd;
817   pFd->pShm = pBuffer;
818   return SQLITE_OK;
819 }
820 
821 static void tvfsAllocPage(TestvfsBuffer *p, int iPage, int pgsz){
822   assert( iPage<TESTVFS_MAX_PAGES );
823   if( p->aPage[iPage]==0 ){
824     p->aPage[iPage] = (u8 *)ckalloc(pgsz);
825     memset(p->aPage[iPage], 0, pgsz);
826     p->pgsz = pgsz;
827   }
828 }
829 
830 static int tvfsShmMap(
831   sqlite3_file *pFile,            /* Handle open on database file */
832   int iPage,                      /* Page to retrieve */
833   int pgsz,                       /* Size of pages */
834   int isWrite,                    /* True to extend file if necessary */
835   void volatile **pp              /* OUT: Mapped memory */
836 ){
837   int rc = SQLITE_OK;
838   TestvfsFd *pFd = tvfsGetFd(pFile);
839   Testvfs *p = (Testvfs *)(pFd->pVfs->pAppData);
840 
841   if( p->isFullshm ){
842     return sqlite3OsShmMap(pFd->pReal, iPage, pgsz, isWrite, pp);
843   }
844 
845   if( 0==pFd->pShm ){
846     rc = tvfsShmOpen(pFile);
847     if( rc!=SQLITE_OK ){
848       return rc;
849     }
850   }
851 
852   if( p->pScript && p->mask&TESTVFS_SHMMAP_MASK ){
853     Tcl_Obj *pArg = Tcl_NewObj();
854     Tcl_IncrRefCount(pArg);
855     Tcl_ListObjAppendElement(p->interp, pArg, Tcl_NewIntObj(iPage));
856     Tcl_ListObjAppendElement(p->interp, pArg, Tcl_NewIntObj(pgsz));
857     Tcl_ListObjAppendElement(p->interp, pArg, Tcl_NewIntObj(isWrite));
858     tvfsExecTcl(p, "xShmMap",
859         Tcl_NewStringObj(pFd->pShm->zFile, -1), pFd->pShmId, pArg, 0
860     );
861     tvfsResultCode(p, &rc);
862     Tcl_DecrRefCount(pArg);
863   }
864   if( rc==SQLITE_OK && p->mask&TESTVFS_SHMMAP_MASK && tvfsInjectIoerr(p) ){
865     rc = SQLITE_IOERR;
866   }
867 
868   if( rc==SQLITE_OK && isWrite && !pFd->pShm->aPage[iPage] ){
869     tvfsAllocPage(pFd->pShm, iPage, pgsz);
870   }
871   *pp = (void volatile *)pFd->pShm->aPage[iPage];
872 
873   return rc;
874 }
875 
876 
877 static int tvfsShmLock(
878   sqlite3_file *pFile,
879   int ofst,
880   int n,
881   int flags
882 ){
883   int rc = SQLITE_OK;
884   TestvfsFd *pFd = tvfsGetFd(pFile);
885   Testvfs *p = (Testvfs *)(pFd->pVfs->pAppData);
886   int nLock;
887   char zLock[80];
888 
889   if( p->isFullshm ){
890     return sqlite3OsShmLock(pFd->pReal, ofst, n, flags);
891   }
892 
893   if( p->pScript && p->mask&TESTVFS_SHMLOCK_MASK ){
894     sqlite3_snprintf(sizeof(zLock), zLock, "%d %d", ofst, n);
895     nLock = (int)strlen(zLock);
896     if( flags & SQLITE_SHM_LOCK ){
897       strcpy(&zLock[nLock], " lock");
898     }else{
899       strcpy(&zLock[nLock], " unlock");
900     }
901     nLock += (int)strlen(&zLock[nLock]);
902     if( flags & SQLITE_SHM_SHARED ){
903       strcpy(&zLock[nLock], " shared");
904     }else{
905       strcpy(&zLock[nLock], " exclusive");
906     }
907     tvfsExecTcl(p, "xShmLock",
908         Tcl_NewStringObj(pFd->pShm->zFile, -1), pFd->pShmId,
909         Tcl_NewStringObj(zLock, -1), 0
910     );
911     tvfsResultCode(p, &rc);
912   }
913 
914   if( rc==SQLITE_OK && p->mask&TESTVFS_SHMLOCK_MASK && tvfsInjectIoerr(p) ){
915     rc = SQLITE_IOERR;
916   }
917 
918   if( rc==SQLITE_OK ){
919     int isLock = (flags & SQLITE_SHM_LOCK);
920     int isExcl = (flags & SQLITE_SHM_EXCLUSIVE);
921     u32 mask = (((1<<n)-1) << ofst);
922     if( isLock ){
923       TestvfsFd *p2;
924       for(p2=pFd->pShm->pFile; p2; p2=p2->pNext){
925         if( p2==pFd ) continue;
926         if( (p2->excllock&mask) || (isExcl && p2->sharedlock&mask) ){
927           rc = SQLITE_BUSY;
928           break;
929         }
930       }
931       if( rc==SQLITE_OK ){
932         if( isExcl )  pFd->excllock |= mask;
933         if( !isExcl ) pFd->sharedlock |= mask;
934       }
935     }else{
936       if( isExcl )  pFd->excllock &= (~mask);
937       if( !isExcl ) pFd->sharedlock &= (~mask);
938     }
939   }
940 
941   return rc;
942 }
943 
944 static void tvfsShmBarrier(sqlite3_file *pFile){
945   TestvfsFd *pFd = tvfsGetFd(pFile);
946   Testvfs *p = (Testvfs *)(pFd->pVfs->pAppData);
947 
948   if( p->isFullshm ){
949     sqlite3OsShmBarrier(pFd->pReal);
950     return;
951   }
952 
953   if( p->pScript && p->mask&TESTVFS_SHMBARRIER_MASK ){
954     tvfsExecTcl(p, "xShmBarrier",
955         Tcl_NewStringObj(pFd->pShm->zFile, -1), pFd->pShmId, 0, 0
956     );
957   }
958 }
959 
960 static int tvfsShmUnmap(
961   sqlite3_file *pFile,
962   int deleteFlag
963 ){
964   int rc = SQLITE_OK;
965   TestvfsFd *pFd = tvfsGetFd(pFile);
966   Testvfs *p = (Testvfs *)(pFd->pVfs->pAppData);
967   TestvfsBuffer *pBuffer = pFd->pShm;
968   TestvfsFd **ppFd;
969 
970   if( p->isFullshm ){
971     return sqlite3OsShmUnmap(pFd->pReal, deleteFlag);
972   }
973 
974   if( !pBuffer ) return SQLITE_OK;
975   assert( pFd->pShmId && pFd->pShm );
976 
977   if( p->pScript && p->mask&TESTVFS_SHMCLOSE_MASK ){
978     tvfsExecTcl(p, "xShmUnmap",
979         Tcl_NewStringObj(pFd->pShm->zFile, -1), pFd->pShmId, 0, 0
980     );
981     tvfsResultCode(p, &rc);
982   }
983 
984   for(ppFd=&pBuffer->pFile; *ppFd!=pFd; ppFd=&((*ppFd)->pNext));
985   assert( (*ppFd)==pFd );
986   *ppFd = pFd->pNext;
987   pFd->pNext = 0;
988 
989   if( pBuffer->pFile==0 ){
990     int i;
991     TestvfsBuffer **pp;
992     for(pp=&p->pBuffer; *pp!=pBuffer; pp=&((*pp)->pNext));
993     *pp = (*pp)->pNext;
994     for(i=0; pBuffer->aPage[i]; i++){
995       ckfree((char *)pBuffer->aPage[i]);
996     }
997     ckfree((char *)pBuffer);
998   }
999   pFd->pShm = 0;
1000 
1001   return rc;
1002 }
1003 
1004 static int tvfsFetch(
1005     sqlite3_file *pFile,
1006     sqlite3_int64 iOfst,
1007     int iAmt,
1008     void **pp
1009 ){
1010   TestvfsFd *pFd = tvfsGetFd(pFile);
1011   return sqlite3OsFetch(pFd->pReal, iOfst, iAmt, pp);
1012 }
1013 
1014 static int tvfsUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *p){
1015   TestvfsFd *pFd = tvfsGetFd(pFile);
1016   return sqlite3OsUnfetch(pFd->pReal, iOfst, p);
1017 }
1018 
1019 static int testvfs_obj_cmd(
1020   ClientData cd,
1021   Tcl_Interp *interp,
1022   int objc,
1023   Tcl_Obj *CONST objv[]
1024 ){
1025   Testvfs *p = (Testvfs *)cd;
1026 
1027   enum DB_enum {
1028     CMD_SHM, CMD_DELETE, CMD_FILTER, CMD_IOERR, CMD_SCRIPT,
1029     CMD_DEVCHAR, CMD_SECTORSIZE, CMD_FULLERR, CMD_CANTOPENERR
1030   };
1031   struct TestvfsSubcmd {
1032     char *zName;
1033     enum DB_enum eCmd;
1034   } aSubcmd[] = {
1035     { "shm",         CMD_SHM         },
1036     { "delete",      CMD_DELETE      },
1037     { "filter",      CMD_FILTER      },
1038     { "ioerr",       CMD_IOERR       },
1039     { "fullerr",     CMD_FULLERR     },
1040     { "cantopenerr", CMD_CANTOPENERR },
1041     { "script",      CMD_SCRIPT      },
1042     { "devchar",     CMD_DEVCHAR     },
1043     { "sectorsize",  CMD_SECTORSIZE  },
1044     { 0, 0 }
1045   };
1046   int i;
1047 
1048   if( objc<2 ){
1049     Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
1050     return TCL_ERROR;
1051   }
1052   if( Tcl_GetIndexFromObjStruct(
1053         interp, objv[1], aSubcmd, sizeof(aSubcmd[0]), "subcommand", 0, &i)
1054   ){
1055     return TCL_ERROR;
1056   }
1057   Tcl_ResetResult(interp);
1058 
1059   switch( aSubcmd[i].eCmd ){
1060     case CMD_SHM: {
1061       Tcl_Obj *pObj;
1062       int i, rc;
1063       TestvfsBuffer *pBuffer;
1064       char *zName;
1065       if( objc!=3 && objc!=4 ){
1066         Tcl_WrongNumArgs(interp, 2, objv, "FILE ?VALUE?");
1067         return TCL_ERROR;
1068       }
1069       zName = ckalloc(p->pParent->mxPathname);
1070       rc = p->pParent->xFullPathname(
1071           p->pParent, Tcl_GetString(objv[2]),
1072           p->pParent->mxPathname, zName
1073       );
1074       if( rc!=SQLITE_OK ){
1075         Tcl_AppendResult(interp, "failed to get full path: ",
1076                          Tcl_GetString(objv[2]), 0);
1077         ckfree(zName);
1078         return TCL_ERROR;
1079       }
1080       for(pBuffer=p->pBuffer; pBuffer; pBuffer=pBuffer->pNext){
1081         if( 0==strcmp(pBuffer->zFile, zName) ) break;
1082       }
1083       ckfree(zName);
1084       if( !pBuffer ){
1085         Tcl_AppendResult(interp, "no such file: ", Tcl_GetString(objv[2]), 0);
1086         return TCL_ERROR;
1087       }
1088       if( objc==4 ){
1089         int n;
1090         u8 *a = Tcl_GetByteArrayFromObj(objv[3], &n);
1091         int pgsz = pBuffer->pgsz;
1092         if( pgsz==0 ) pgsz = 65536;
1093         for(i=0; i*pgsz<n; i++){
1094           int nByte = pgsz;
1095           tvfsAllocPage(pBuffer, i, pgsz);
1096           if( n-i*pgsz<pgsz ){
1097             nByte = n;
1098           }
1099           memcpy(pBuffer->aPage[i], &a[i*pgsz], nByte);
1100         }
1101       }
1102 
1103       pObj = Tcl_NewObj();
1104       for(i=0; pBuffer->aPage[i]; i++){
1105         int pgsz = pBuffer->pgsz;
1106         if( pgsz==0 ) pgsz = 65536;
1107         Tcl_AppendObjToObj(pObj, Tcl_NewByteArrayObj(pBuffer->aPage[i], pgsz));
1108       }
1109       Tcl_SetObjResult(interp, pObj);
1110       break;
1111     }
1112 
1113     case CMD_FILTER: {
1114       static struct VfsMethod {
1115         char *zName;
1116         int mask;
1117       } vfsmethod [] = {
1118         { "xShmOpen",      TESTVFS_SHMOPEN_MASK },
1119         { "xShmLock",      TESTVFS_SHMLOCK_MASK },
1120         { "xShmBarrier",   TESTVFS_SHMBARRIER_MASK },
1121         { "xShmUnmap",     TESTVFS_SHMCLOSE_MASK },
1122         { "xShmMap",       TESTVFS_SHMMAP_MASK },
1123         { "xSync",         TESTVFS_SYNC_MASK },
1124         { "xDelete",       TESTVFS_DELETE_MASK },
1125         { "xWrite",        TESTVFS_WRITE_MASK },
1126         { "xRead",         TESTVFS_READ_MASK },
1127         { "xTruncate",     TESTVFS_TRUNCATE_MASK },
1128         { "xOpen",         TESTVFS_OPEN_MASK },
1129         { "xClose",        TESTVFS_CLOSE_MASK },
1130         { "xAccess",       TESTVFS_ACCESS_MASK },
1131         { "xFullPathname", TESTVFS_FULLPATHNAME_MASK },
1132         { "xUnlock",       TESTVFS_UNLOCK_MASK },
1133       };
1134       Tcl_Obj **apElem = 0;
1135       int nElem = 0;
1136       int i;
1137       int mask = 0;
1138       if( objc!=3 ){
1139         Tcl_WrongNumArgs(interp, 2, objv, "LIST");
1140         return TCL_ERROR;
1141       }
1142       if( Tcl_ListObjGetElements(interp, objv[2], &nElem, &apElem) ){
1143         return TCL_ERROR;
1144       }
1145       Tcl_ResetResult(interp);
1146       for(i=0; i<nElem; i++){
1147         int iMethod;
1148         char *zElem = Tcl_GetString(apElem[i]);
1149         for(iMethod=0; iMethod<ArraySize(vfsmethod); iMethod++){
1150           if( strcmp(zElem, vfsmethod[iMethod].zName)==0 ){
1151             mask |= vfsmethod[iMethod].mask;
1152             break;
1153           }
1154         }
1155         if( iMethod==ArraySize(vfsmethod) ){
1156           Tcl_AppendResult(interp, "unknown method: ", zElem, 0);
1157           return TCL_ERROR;
1158         }
1159       }
1160       p->mask = mask;
1161       break;
1162     }
1163 
1164     case CMD_SCRIPT: {
1165       if( objc==3 ){
1166         int nByte;
1167         if( p->pScript ){
1168           Tcl_DecrRefCount(p->pScript);
1169           p->pScript = 0;
1170         }
1171         Tcl_GetStringFromObj(objv[2], &nByte);
1172         if( nByte>0 ){
1173           p->pScript = Tcl_DuplicateObj(objv[2]);
1174           Tcl_IncrRefCount(p->pScript);
1175         }
1176       }else if( objc!=2 ){
1177         Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
1178         return TCL_ERROR;
1179       }
1180 
1181       Tcl_ResetResult(interp);
1182       if( p->pScript ) Tcl_SetObjResult(interp, p->pScript);
1183 
1184       break;
1185     }
1186 
1187     /*
1188     ** TESTVFS ioerr ?IFAIL PERSIST?
1189     **
1190     **   Where IFAIL is an integer and PERSIST is boolean.
1191     */
1192     case CMD_CANTOPENERR:
1193     case CMD_IOERR:
1194     case CMD_FULLERR: {
1195       TestFaultInject *pTest;
1196       int iRet;
1197 
1198       switch( aSubcmd[i].eCmd ){
1199         case CMD_IOERR: pTest = &p->ioerr_err; break;
1200         case CMD_FULLERR: pTest = &p->full_err; break;
1201         case CMD_CANTOPENERR: pTest = &p->cantopen_err; break;
1202         default: assert(0);
1203       }
1204       iRet = pTest->nFail;
1205       pTest->nFail = 0;
1206       pTest->eFault = 0;
1207       pTest->iCnt = 0;
1208 
1209       if( objc==4 ){
1210         int iCnt, iPersist;
1211         if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &iCnt)
1212          || TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[3], &iPersist)
1213         ){
1214           return TCL_ERROR;
1215         }
1216         pTest->eFault = iPersist?FAULT_INJECT_PERSISTENT:FAULT_INJECT_TRANSIENT;
1217         pTest->iCnt = iCnt;
1218       }else if( objc!=2 ){
1219         Tcl_WrongNumArgs(interp, 2, objv, "?CNT PERSIST?");
1220         return TCL_ERROR;
1221       }
1222       Tcl_SetObjResult(interp, Tcl_NewIntObj(iRet));
1223       break;
1224     }
1225 
1226     case CMD_DELETE: {
1227       Tcl_DeleteCommand(interp, Tcl_GetString(objv[0]));
1228       break;
1229     }
1230 
1231     case CMD_DEVCHAR: {
1232       struct DeviceFlag {
1233         char *zName;
1234         int iValue;
1235       } aFlag[] = {
1236         { "default",               -1 },
1237         { "atomic",                SQLITE_IOCAP_ATOMIC                },
1238         { "atomic512",             SQLITE_IOCAP_ATOMIC512             },
1239         { "atomic1k",              SQLITE_IOCAP_ATOMIC1K              },
1240         { "atomic2k",              SQLITE_IOCAP_ATOMIC2K              },
1241         { "atomic4k",              SQLITE_IOCAP_ATOMIC4K              },
1242         { "atomic8k",              SQLITE_IOCAP_ATOMIC8K              },
1243         { "atomic16k",             SQLITE_IOCAP_ATOMIC16K             },
1244         { "atomic32k",             SQLITE_IOCAP_ATOMIC32K             },
1245         { "atomic64k",             SQLITE_IOCAP_ATOMIC64K             },
1246         { "sequential",            SQLITE_IOCAP_SEQUENTIAL            },
1247         { "safe_append",           SQLITE_IOCAP_SAFE_APPEND           },
1248         { "undeletable_when_open", SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN },
1249         { "powersafe_overwrite",   SQLITE_IOCAP_POWERSAFE_OVERWRITE   },
1250         { 0, 0 }
1251       };
1252       Tcl_Obj *pRet;
1253       int iFlag;
1254 
1255       if( objc>3 ){
1256         Tcl_WrongNumArgs(interp, 2, objv, "?ATTR-LIST?");
1257         return TCL_ERROR;
1258       }
1259       if( objc==3 ){
1260         int j;
1261         int iNew = 0;
1262         Tcl_Obj **flags = 0;
1263         int nFlags = 0;
1264 
1265         if( Tcl_ListObjGetElements(interp, objv[2], &nFlags, &flags) ){
1266           return TCL_ERROR;
1267         }
1268 
1269         for(j=0; j<nFlags; j++){
1270           int idx = 0;
1271           if( Tcl_GetIndexFromObjStruct(interp, flags[j], aFlag,
1272                 sizeof(aFlag[0]), "flag", 0, &idx)
1273           ){
1274             return TCL_ERROR;
1275           }
1276           if( aFlag[idx].iValue<0 && nFlags>1 ){
1277             Tcl_AppendResult(interp, "bad flags: ", Tcl_GetString(objv[2]), 0);
1278             return TCL_ERROR;
1279           }
1280           iNew |= aFlag[idx].iValue;
1281         }
1282 
1283         p->iDevchar = iNew| 0x10000000;
1284       }
1285 
1286       pRet = Tcl_NewObj();
1287       for(iFlag=0; iFlag<sizeof(aFlag)/sizeof(aFlag[0]); iFlag++){
1288         if( p->iDevchar & aFlag[iFlag].iValue ){
1289           Tcl_ListObjAppendElement(
1290               interp, pRet, Tcl_NewStringObj(aFlag[iFlag].zName, -1)
1291           );
1292         }
1293       }
1294       Tcl_SetObjResult(interp, pRet);
1295 
1296       break;
1297     }
1298 
1299     case CMD_SECTORSIZE: {
1300       if( objc>3 ){
1301         Tcl_WrongNumArgs(interp, 2, objv, "?VALUE?");
1302         return TCL_ERROR;
1303       }
1304       if( objc==3 ){
1305         int iNew = 0;
1306         if( Tcl_GetIntFromObj(interp, objv[2], &iNew) ){
1307           return TCL_ERROR;
1308         }
1309         p->iSectorsize = iNew;
1310       }
1311       Tcl_SetObjResult(interp, Tcl_NewIntObj(p->iSectorsize));
1312       break;
1313     }
1314   }
1315 
1316   return TCL_OK;
1317 }
1318 
1319 static void testvfs_obj_del(ClientData cd){
1320   Testvfs *p = (Testvfs *)cd;
1321   if( p->pScript ) Tcl_DecrRefCount(p->pScript);
1322   sqlite3_vfs_unregister(p->pVfs);
1323   ckfree((char *)p->pVfs);
1324   ckfree((char *)p);
1325 }
1326 
1327 /*
1328 ** Usage:  testvfs VFSNAME ?SWITCHES?
1329 **
1330 ** Switches are:
1331 **
1332 **   -noshm   BOOLEAN             (True to omit shm methods. Default false)
1333 **   -default BOOLEAN             (True to make the vfs default. Default false)
1334 **
1335 ** This command creates two things when it is invoked: an SQLite VFS, and
1336 ** a Tcl command. Both are named VFSNAME. The VFS is installed. It is not
1337 ** installed as the default VFS.
1338 **
1339 ** The VFS passes all file I/O calls through to the underlying VFS.
1340 **
1341 ** Whenever the xShmMap method of the VFS
1342 ** is invoked, the SCRIPT is executed as follows:
1343 **
1344 **   SCRIPT xShmMap    FILENAME ID
1345 **
1346 ** The value returned by the invocation of SCRIPT above is interpreted as
1347 ** an SQLite error code and returned to SQLite. Either a symbolic
1348 ** "SQLITE_OK" or numeric "0" value may be returned.
1349 **
1350 ** The contents of the shared-memory buffer associated with a given file
1351 ** may be read and set using the following command:
1352 **
1353 **   VFSNAME shm FILENAME ?NEWVALUE?
1354 **
1355 ** When the xShmLock method is invoked by SQLite, the following script is
1356 ** run:
1357 **
1358 **   SCRIPT xShmLock    FILENAME ID LOCK
1359 **
1360 ** where LOCK is of the form "OFFSET NBYTE lock/unlock shared/exclusive"
1361 */
1362 static int testvfs_cmd(
1363   ClientData cd,
1364   Tcl_Interp *interp,
1365   int objc,
1366   Tcl_Obj *CONST objv[]
1367 ){
1368   static sqlite3_vfs tvfs_vfs = {
1369     3,                            /* iVersion */
1370     0,                            /* szOsFile */
1371     0,                            /* mxPathname */
1372     0,                            /* pNext */
1373     0,                            /* zName */
1374     0,                            /* pAppData */
1375     tvfsOpen,                     /* xOpen */
1376     tvfsDelete,                   /* xDelete */
1377     tvfsAccess,                   /* xAccess */
1378     tvfsFullPathname,             /* xFullPathname */
1379 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1380     tvfsDlOpen,                   /* xDlOpen */
1381     tvfsDlError,                  /* xDlError */
1382     tvfsDlSym,                    /* xDlSym */
1383     tvfsDlClose,                  /* xDlClose */
1384 #else
1385     0,                            /* xDlOpen */
1386     0,                            /* xDlError */
1387     0,                            /* xDlSym */
1388     0,                            /* xDlClose */
1389 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
1390     tvfsRandomness,               /* xRandomness */
1391     tvfsSleep,                    /* xSleep */
1392     tvfsCurrentTime,              /* xCurrentTime */
1393     0,                            /* xGetLastError */
1394     0,                            /* xCurrentTimeInt64 */
1395     0,                            /* xSetSystemCall */
1396     0,                            /* xGetSystemCall */
1397     0,                            /* xNextSystemCall */
1398   };
1399 
1400   Testvfs *p;                     /* New object */
1401   sqlite3_vfs *pVfs;              /* New VFS */
1402   char *zVfs;
1403   int nByte;                      /* Bytes of space to allocate at p */
1404 
1405   int i;
1406   int isNoshm = 0;                /* True if -noshm is passed */
1407   int isFullshm = 0;              /* True if -fullshm is passed */
1408   int isDefault = 0;              /* True if -default is passed */
1409   int szOsFile = 0;               /* Value passed to -szosfile */
1410   int mxPathname = -1;            /* Value passed to -mxpathname */
1411   int iVersion = 3;               /* Value passed to -iversion */
1412 
1413   if( objc<2 || 0!=(objc%2) ) goto bad_args;
1414   for(i=2; i<objc; i += 2){
1415     int nSwitch;
1416     char *zSwitch;
1417     zSwitch = Tcl_GetStringFromObj(objv[i], &nSwitch);
1418 
1419     if( nSwitch>2 && 0==strncmp("-noshm", zSwitch, nSwitch) ){
1420       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &isNoshm) ){
1421         return TCL_ERROR;
1422       }
1423       if( isNoshm ) isFullshm = 0;
1424     }
1425     else if( nSwitch>2 && 0==strncmp("-default", zSwitch, nSwitch) ){
1426       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &isDefault) ){
1427         return TCL_ERROR;
1428       }
1429     }
1430     else if( nSwitch>2 && 0==strncmp("-szosfile", zSwitch, nSwitch) ){
1431       if( Tcl_GetIntFromObj(interp, objv[i+1], &szOsFile) ){
1432         return TCL_ERROR;
1433       }
1434     }
1435     else if( nSwitch>2 && 0==strncmp("-mxpathname", zSwitch, nSwitch) ){
1436       if( Tcl_GetIntFromObj(interp, objv[i+1], &mxPathname) ){
1437         return TCL_ERROR;
1438       }
1439     }
1440     else if( nSwitch>2 && 0==strncmp("-iversion", zSwitch, nSwitch) ){
1441       if( Tcl_GetIntFromObj(interp, objv[i+1], &iVersion) ){
1442         return TCL_ERROR;
1443       }
1444     }
1445     else if( nSwitch>2 && 0==strncmp("-fullshm", zSwitch, nSwitch) ){
1446       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &isFullshm) ){
1447         return TCL_ERROR;
1448       }
1449       if( isFullshm ) isNoshm = 0;
1450     }
1451     else{
1452       goto bad_args;
1453     }
1454   }
1455 
1456   if( szOsFile<sizeof(TestvfsFile) ){
1457     szOsFile = sizeof(TestvfsFile);
1458   }
1459 
1460   zVfs = Tcl_GetString(objv[1]);
1461   nByte = sizeof(Testvfs) + (int)strlen(zVfs)+1;
1462   p = (Testvfs *)ckalloc(nByte);
1463   memset(p, 0, nByte);
1464   p->iDevchar = -1;
1465   p->iSectorsize = -1;
1466 
1467   /* Create the new object command before querying SQLite for a default VFS
1468   ** to use for 'real' IO operations. This is because creating the new VFS
1469   ** may delete an existing [testvfs] VFS of the same name. If such a VFS
1470   ** is currently the default, the new [testvfs] may end up calling the
1471   ** methods of a deleted object.
1472   */
1473   Tcl_CreateObjCommand(interp, zVfs, testvfs_obj_cmd, p, testvfs_obj_del);
1474   p->pParent = sqlite3_vfs_find(0);
1475   p->interp = interp;
1476 
1477   p->zName = (char *)&p[1];
1478   memcpy(p->zName, zVfs, strlen(zVfs)+1);
1479 
1480   pVfs = (sqlite3_vfs *)ckalloc(sizeof(sqlite3_vfs));
1481   memcpy(pVfs, &tvfs_vfs, sizeof(sqlite3_vfs));
1482   pVfs->pAppData = (void *)p;
1483   pVfs->iVersion = iVersion;
1484   pVfs->zName = p->zName;
1485   pVfs->mxPathname = p->pParent->mxPathname;
1486   if( mxPathname>=0 && mxPathname<pVfs->mxPathname ){
1487     pVfs->mxPathname = mxPathname;
1488   }
1489   pVfs->szOsFile = szOsFile;
1490   p->pVfs = pVfs;
1491   p->isNoshm = isNoshm;
1492   p->isFullshm = isFullshm;
1493   p->mask = TESTVFS_ALL_MASK;
1494 
1495   sqlite3_vfs_register(pVfs, isDefault);
1496 
1497   return TCL_OK;
1498 
1499  bad_args:
1500   Tcl_WrongNumArgs(interp, 1, objv, "VFSNAME ?-noshm BOOL? ?-default BOOL? ?-mxpathname INT? ?-szosfile INT? ?-iversion INT?");
1501   return TCL_ERROR;
1502 }
1503 
1504 int Sqlitetestvfs_Init(Tcl_Interp *interp){
1505   Tcl_CreateObjCommand(interp, "testvfs", testvfs_cmd, 0, 0);
1506   return TCL_OK;
1507 }
1508 
1509 #endif
1510