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