xref: /sqlite-3.40.0/test/fuzzcheck.c (revision c2beb0d8)
1 /*
2 ** 2015-05-25
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 is a utility program designed to aid running regressions tests on
14 ** the SQLite library using data from external fuzzers.
15 **
16 ** This program reads content from an SQLite database file with the following
17 ** schema:
18 **
19 **     CREATE TABLE db(
20 **       dbid INTEGER PRIMARY KEY, -- database id
21 **       dbcontent BLOB            -- database disk file image
22 **     );
23 **     CREATE TABLE xsql(
24 **       sqlid INTEGER PRIMARY KEY,   -- SQL script id
25 **       sqltext TEXT                 -- Text of SQL statements to run
26 **     );
27 **     CREATE TABLE IF NOT EXISTS readme(
28 **       msg TEXT -- Human-readable description of this test collection
29 **     );
30 **
31 ** For each database file in the DB table, the SQL text in the XSQL table
32 ** is run against that database.  All README.MSG values are printed prior
33 ** to the start of the test (unless the --quiet option is used).  If the
34 ** DB table is empty, then all entries in XSQL are run against an empty
35 ** in-memory database.
36 **
37 ** This program is looking for crashes, assertion faults, and/or memory leaks.
38 ** No attempt is made to verify the output.  The assumption is that either all
39 ** of the database files or all of the SQL statements are malformed inputs,
40 ** generated by a fuzzer, that need to be checked to make sure they do not
41 ** present a security risk.
42 **
43 ** This program also includes some command-line options to help with
44 ** creation and maintenance of the source content database.  The command
45 **
46 **     ./fuzzcheck database.db --load-sql FILE...
47 **
48 ** Loads all FILE... arguments into the XSQL table.  The --load-db option
49 ** works the same but loads the files into the DB table.  The -m option can
50 ** be used to initialize the README table.  The "database.db" file is created
51 ** if it does not previously exist.  Example:
52 **
53 **     ./fuzzcheck new.db --load-sql *.sql
54 **     ./fuzzcheck new.db --load-db *.db
55 **     ./fuzzcheck new.db -m 'New test cases'
56 **
57 ** The three commands above will create the "new.db" file and initialize all
58 ** tables.  Then do "./fuzzcheck new.db" to run the tests.
59 **
60 ** DEBUGGING HINTS:
61 **
62 ** If fuzzcheck does crash, it can be run in the debugger and the content
63 ** of the global variable g.zTextName[] will identify the specific XSQL and
64 ** DB values that were running when the crash occurred.
65 **
66 ** DBSQLFUZZ: (Added 2020-02-25)
67 **
68 ** The dbsqlfuzz fuzzer includes both a database file and SQL to run against
69 ** that database in its input.  This utility can now process dbsqlfuzz
70 ** input files.  Load such files using the "--load-dbsql FILE ..." command-line
71 ** option.
72 **
73 ** Dbsqlfuzz inputs are ordinary text.  The first part of the file is text
74 ** that describes the content of the database (using a lot of hexadecimal),
75 ** then there is a divider line followed by the SQL to run against the
76 ** database.  Because they are ordinary text, dbsqlfuzz inputs are stored
77 ** in the XSQL table, as if they were ordinary SQL inputs.  The isDbSql()
78 ** function can look at a text string and determine whether or not it is
79 ** a valid dbsqlfuzz input.
80 */
81 #include <stdio.h>
82 #include <stdlib.h>
83 #include <string.h>
84 #include <stdarg.h>
85 #include <ctype.h>
86 #include <assert.h>
87 #include "sqlite3.h"
88 #define ISSPACE(X) isspace((unsigned char)(X))
89 #define ISDIGIT(X) isdigit((unsigned char)(X))
90 
91 
92 #ifdef __unix__
93 # include <signal.h>
94 # include <unistd.h>
95 #endif
96 
97 #include <stddef.h>
98 #if !defined(_MSC_VER)
99 # include <stdint.h>
100 #endif
101 
102 #if defined(_MSC_VER)
103 typedef unsigned char uint8_t;
104 #endif
105 
106 /*
107 ** Files in the virtual file system.
108 */
109 typedef struct VFile VFile;
110 struct VFile {
111   char *zFilename;      /* Filename.  NULL for delete-on-close. From malloc() */
112   int sz;               /* Size of the file in bytes */
113   int nRef;             /* Number of references to this file */
114   unsigned char *a;     /* Content of the file.  From malloc() */
115 };
116 typedef struct VHandle VHandle;
117 struct VHandle {
118   sqlite3_file base;      /* Base class.  Must be first */
119   VFile *pVFile;          /* The underlying file */
120 };
121 
122 /*
123 ** The value of a database file template, or of an SQL script
124 */
125 typedef struct Blob Blob;
126 struct Blob {
127   Blob *pNext;            /* Next in a list */
128   int id;                 /* Id of this Blob */
129   int seq;                /* Sequence number */
130   int sz;                 /* Size of this Blob in bytes */
131   unsigned char a[1];     /* Blob content.  Extra space allocated as needed. */
132 };
133 
134 /*
135 ** Maximum number of files in the in-memory virtual filesystem.
136 */
137 #define MX_FILE  10
138 
139 /*
140 ** Maximum allowed file size
141 */
142 #define MX_FILE_SZ 10000000
143 
144 /*
145 ** All global variables are gathered into the "g" singleton.
146 */
147 static struct GlobalVars {
148   const char *zArgv0;              /* Name of program */
149   const char *zDbFile;             /* Name of database file */
150   VFile aFile[MX_FILE];            /* The virtual filesystem */
151   int nDb;                         /* Number of template databases */
152   Blob *pFirstDb;                  /* Content of first template database */
153   int nSql;                        /* Number of SQL scripts */
154   Blob *pFirstSql;                 /* First SQL script */
155   unsigned int uRandom;            /* Seed for the SQLite PRNG */
156   unsigned char doInvariantChecks; /* True to run query invariant checks */
157   unsigned int nInvariant;         /* Number of invariant checks run */
158   char zTestName[100];             /* Name of current test */
159 } g;
160 
161 /*
162 ** Include the external vt02.c module, if requested by compile-time
163 ** options.
164 */
165 #ifdef VT02_SOURCES
166 # include "vt02.c"
167 #endif
168 
169 /*
170 ** Print an error message and quit.
171 */
172 static void fatalError(const char *zFormat, ...){
173   va_list ap;
174   fprintf(stderr, "%s", g.zArgv0);
175   if( g.zDbFile ) fprintf(stderr, " %s", g.zDbFile);
176   if( g.zTestName[0] ) fprintf(stderr, " (%s)", g.zTestName);
177   fprintf(stderr, ": ");
178   va_start(ap, zFormat);
179   vfprintf(stderr, zFormat, ap);
180   va_end(ap);
181   fprintf(stderr, "\n");
182   exit(1);
183 }
184 
185 /*
186 ** signal handler
187 */
188 #ifdef __unix__
189 static void signalHandler(int signum){
190   const char *zSig;
191   if( signum==SIGABRT ){
192     zSig = "abort";
193   }else if( signum==SIGALRM ){
194     zSig = "timeout";
195   }else if( signum==SIGSEGV ){
196     zSig = "segfault";
197   }else{
198     zSig = "signal";
199   }
200   fatalError(zSig);
201 }
202 #endif
203 
204 /*
205 ** Set the an alarm to go off after N seconds.  Disable the alarm
206 ** if N==0
207 */
208 static void setAlarm(int N){
209 #ifdef __unix__
210   alarm(N);
211 #else
212   (void)N;
213 #endif
214 }
215 
216 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
217 /*
218 ** This an SQL progress handler.  After an SQL statement has run for
219 ** many steps, we want to interrupt it.  This guards against infinite
220 ** loops from recursive common table expressions.
221 **
222 ** *pVdbeLimitFlag is true if the --limit-vdbe command-line option is used.
223 ** In that case, hitting the progress handler is a fatal error.
224 */
225 static int progressHandler(void *pVdbeLimitFlag){
226   if( *(int*)pVdbeLimitFlag ) fatalError("too many VDBE cycles");
227   return 1;
228 }
229 #endif
230 
231 /*
232 ** Reallocate memory.  Show an error and quit if unable.
233 */
234 static void *safe_realloc(void *pOld, int szNew){
235   void *pNew = realloc(pOld, szNew<=0 ? 1 : szNew);
236   if( pNew==0 ) fatalError("unable to realloc for %d bytes", szNew);
237   return pNew;
238 }
239 
240 /*
241 ** Initialize the virtual file system.
242 */
243 static void formatVfs(void){
244   int i;
245   for(i=0; i<MX_FILE; i++){
246     g.aFile[i].sz = -1;
247     g.aFile[i].zFilename = 0;
248     g.aFile[i].a = 0;
249     g.aFile[i].nRef = 0;
250   }
251 }
252 
253 
254 /*
255 ** Erase all information in the virtual file system.
256 */
257 static void reformatVfs(void){
258   int i;
259   for(i=0; i<MX_FILE; i++){
260     if( g.aFile[i].sz<0 ) continue;
261     if( g.aFile[i].zFilename ){
262       free(g.aFile[i].zFilename);
263       g.aFile[i].zFilename = 0;
264     }
265     if( g.aFile[i].nRef>0 ){
266       fatalError("file %d still open.  nRef=%d", i, g.aFile[i].nRef);
267     }
268     g.aFile[i].sz = -1;
269     free(g.aFile[i].a);
270     g.aFile[i].a = 0;
271     g.aFile[i].nRef = 0;
272   }
273 }
274 
275 /*
276 ** Find a VFile by name
277 */
278 static VFile *findVFile(const char *zName){
279   int i;
280   if( zName==0 ) return 0;
281   for(i=0; i<MX_FILE; i++){
282     if( g.aFile[i].zFilename==0 ) continue;
283     if( strcmp(g.aFile[i].zFilename, zName)==0 ) return &g.aFile[i];
284   }
285   return 0;
286 }
287 
288 /*
289 ** Find a VFile by name.  Create it if it does not already exist and
290 ** initialize it to the size and content given.
291 **
292 ** Return NULL only if the filesystem is full.
293 */
294 static VFile *createVFile(const char *zName, int sz, unsigned char *pData){
295   VFile *pNew = findVFile(zName);
296   int i;
297   if( pNew ) return pNew;
298   for(i=0; i<MX_FILE && g.aFile[i].sz>=0; i++){}
299   if( i>=MX_FILE ) return 0;
300   pNew = &g.aFile[i];
301   if( zName ){
302     int nName = (int)strlen(zName)+1;
303     pNew->zFilename = safe_realloc(0, nName);
304     memcpy(pNew->zFilename, zName, nName);
305   }else{
306     pNew->zFilename = 0;
307   }
308   pNew->nRef = 0;
309   pNew->sz = sz;
310   pNew->a = safe_realloc(0, sz);
311   if( sz>0 ) memcpy(pNew->a, pData, sz);
312   return pNew;
313 }
314 
315 /* Return true if the line is all zeros */
316 static int allZero(unsigned char *aLine){
317   int i;
318   for(i=0; i<16 && aLine[i]==0; i++){}
319   return i==16;
320 }
321 
322 /*
323 ** Render a database and query as text that can be input into
324 ** the CLI.
325 */
326 static void renderDbSqlForCLI(
327   FILE *out,             /* Write to this file */
328   const char *zFile,     /* Name of the database file */
329   unsigned char *aDb,    /* Database content */
330   int nDb,               /* Number of bytes in aDb[] */
331   unsigned char *zSql,   /* SQL content */
332   int nSql               /* Bytes of SQL */
333 ){
334   fprintf(out, ".print ******* %s *******\n", zFile);
335   if( nDb>100 ){
336     int i, j;                   /* Loop counters */
337     int pgsz;                   /* Size of each page */
338     int lastPage = 0;           /* Last page number shown */
339     int iPage;                  /* Current page number */
340     unsigned char *aLine;       /* Single line to display */
341     unsigned char buf[16];      /* Fake line */
342     unsigned char bShow[256];   /* Characters ok to display */
343 
344     memset(bShow, '.', sizeof(bShow));
345     for(i=' '; i<='~'; i++){
346       if( i!='{' && i!='}' && i!='"' && i!='\\' ) bShow[i] = i;
347     }
348     pgsz = (aDb[16]<<8) | aDb[17];
349     if( pgsz==0 ) pgsz = 65536;
350     if( pgsz<512 || (pgsz&(pgsz-1))!=0 ) pgsz = 4096;
351     fprintf(out,".open --hexdb\n");
352     fprintf(out,"| size %d pagesize %d filename %s\n",nDb,pgsz,zFile);
353     for(i=0; i<nDb; i += 16){
354       if( i+16>nDb ){
355         memset(buf, 0, sizeof(buf));
356         memcpy(buf, aDb+i, nDb-i);
357         aLine = buf;
358       }else{
359         aLine = aDb + i;
360       }
361       if( allZero(aLine) ) continue;
362       iPage = i/pgsz + 1;
363       if( lastPage!=iPage ){
364         fprintf(out,"| page %d offset %d\n", iPage, (iPage-1)*pgsz);
365         lastPage = iPage;
366       }
367       fprintf(out,"|  %5d:", i-(iPage-1)*pgsz);
368       for(j=0; j<16; j++) fprintf(out," %02x", aLine[j]);
369       fprintf(out,"   ");
370       for(j=0; j<16; j++){
371         unsigned char c = (unsigned char)aLine[j];
372         fputc( bShow[c], stdout);
373       }
374       fputc('\n', stdout);
375     }
376     fprintf(out,"| end %s\n", zFile);
377   }else{
378     fprintf(out,".open :memory:\n");
379   }
380   fprintf(out,".testctrl prng_seed 1 db\n");
381   fprintf(out,".testctrl internal_functions\n");
382   fprintf(out,"%.*s", nSql, zSql);
383   if( nSql>0 && zSql[nSql-1]!='\n' ) fprintf(out, "\n");
384 }
385 
386 /*
387 ** Read the complete content of a file into memory.  Add a 0x00 terminator
388 ** and return a pointer to the result.
389 **
390 ** The file content is held in memory obtained from sqlite_malloc64() which
391 ** should be freed by the caller.
392 */
393 static char *readFile(const char *zFilename, long *sz){
394   FILE *in;
395   long nIn;
396   unsigned char *pBuf;
397 
398   *sz = 0;
399   if( zFilename==0 ) return 0;
400   in = fopen(zFilename, "rb");
401   if( in==0 ) return 0;
402   fseek(in, 0, SEEK_END);
403   *sz = nIn = ftell(in);
404   rewind(in);
405   pBuf = sqlite3_malloc64( nIn+1 );
406   if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
407     pBuf[nIn] = 0;
408     fclose(in);
409     return (char*)pBuf;
410   }
411   sqlite3_free(pBuf);
412   *sz = 0;
413   fclose(in);
414   return 0;
415 }
416 
417 
418 /*
419 ** Implementation of the "readfile(X)" SQL function.  The entire content
420 ** of the file named X is read and returned as a BLOB.  NULL is returned
421 ** if the file does not exist or is unreadable.
422 */
423 static void readfileFunc(
424   sqlite3_context *context,
425   int argc,
426   sqlite3_value **argv
427 ){
428   long nIn;
429   void *pBuf;
430   const char *zName = (const char*)sqlite3_value_text(argv[0]);
431 
432   if( zName==0 ) return;
433   pBuf = readFile(zName, &nIn);
434   if( pBuf ){
435     sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
436   }
437 }
438 
439 /*
440 ** Implementation of the "readtextfile(X)" SQL function.  The text content
441 ** of the file named X through the end of the file or to the first \000
442 ** character, whichever comes first, is read and returned as TEXT.  NULL
443 ** is returned if the file does not exist or is unreadable.
444 */
445 static void readtextfileFunc(
446   sqlite3_context *context,
447   int argc,
448   sqlite3_value **argv
449 ){
450   const char *zName;
451   FILE *in;
452   long nIn;
453   char *pBuf;
454 
455   zName = (const char*)sqlite3_value_text(argv[0]);
456   if( zName==0 ) return;
457   in = fopen(zName, "rb");
458   if( in==0 ) return;
459   fseek(in, 0, SEEK_END);
460   nIn = ftell(in);
461   rewind(in);
462   pBuf = sqlite3_malloc64( nIn+1 );
463   if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
464     pBuf[nIn] = 0;
465     sqlite3_result_text(context, pBuf, -1, sqlite3_free);
466   }else{
467     sqlite3_free(pBuf);
468   }
469   fclose(in);
470 }
471 
472 /*
473 ** Implementation of the "writefile(X,Y)" SQL function.  The argument Y
474 ** is written into file X.  The number of bytes written is returned.  Or
475 ** NULL is returned if something goes wrong, such as being unable to open
476 ** file X for writing.
477 */
478 static void writefileFunc(
479   sqlite3_context *context,
480   int argc,
481   sqlite3_value **argv
482 ){
483   FILE *out;
484   const char *z;
485   sqlite3_int64 rc;
486   const char *zFile;
487 
488   (void)argc;
489   zFile = (const char*)sqlite3_value_text(argv[0]);
490   if( zFile==0 ) return;
491   out = fopen(zFile, "wb");
492   if( out==0 ) return;
493   z = (const char*)sqlite3_value_blob(argv[1]);
494   if( z==0 ){
495     rc = 0;
496   }else{
497     rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
498   }
499   fclose(out);
500   sqlite3_result_int64(context, rc);
501 }
502 
503 
504 /*
505 ** Load a list of Blob objects from the database
506 */
507 static void blobListLoadFromDb(
508   sqlite3 *db,             /* Read from this database */
509   const char *zSql,        /* Query used to extract the blobs */
510   int onlyId,              /* Only load where id is this value */
511   int *pN,                 /* OUT: Write number of blobs loaded here */
512   Blob **ppList            /* OUT: Write the head of the blob list here */
513 ){
514   Blob head;
515   Blob *p;
516   sqlite3_stmt *pStmt;
517   int n = 0;
518   int rc;
519   char *z2;
520 
521   if( onlyId>0 ){
522     z2 = sqlite3_mprintf("%s WHERE rowid=%d", zSql, onlyId);
523   }else{
524     z2 = sqlite3_mprintf("%s", zSql);
525   }
526   rc = sqlite3_prepare_v2(db, z2, -1, &pStmt, 0);
527   sqlite3_free(z2);
528   if( rc ) fatalError("%s", sqlite3_errmsg(db));
529   head.pNext = 0;
530   p = &head;
531   while( SQLITE_ROW==sqlite3_step(pStmt) ){
532     int sz = sqlite3_column_bytes(pStmt, 1);
533     Blob *pNew = safe_realloc(0, sizeof(*pNew)+sz );
534     pNew->id = sqlite3_column_int(pStmt, 0);
535     pNew->sz = sz;
536     pNew->seq = n++;
537     pNew->pNext = 0;
538     memcpy(pNew->a, sqlite3_column_blob(pStmt,1), sz);
539     pNew->a[sz] = 0;
540     p->pNext = pNew;
541     p = pNew;
542   }
543   sqlite3_finalize(pStmt);
544   *pN = n;
545   *ppList = head.pNext;
546 }
547 
548 /*
549 ** Free a list of Blob objects
550 */
551 static void blobListFree(Blob *p){
552   Blob *pNext;
553   while( p ){
554     pNext = p->pNext;
555     free(p);
556     p = pNext;
557   }
558 }
559 
560 /* Return the current wall-clock time
561 **
562 ** The number of milliseconds since the julian epoch.
563 ** 1907-01-01 00:00:00  ->  210866716800000
564 ** 2021-01-01 00:00:00  ->  212476176000000
565 */
566 static sqlite3_int64 timeOfDay(void){
567   static sqlite3_vfs *clockVfs = 0;
568   sqlite3_int64 t;
569   if( clockVfs==0 ){
570     clockVfs = sqlite3_vfs_find(0);
571     if( clockVfs==0 ) return 0;
572   }
573   if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
574     clockVfs->xCurrentTimeInt64(clockVfs, &t);
575   }else{
576     double r;
577     clockVfs->xCurrentTime(clockVfs, &r);
578     t = (sqlite3_int64)(r*86400000.0);
579   }
580   return t;
581 }
582 
583 /***************************************************************************
584 ** Code to process combined database+SQL scripts generated by the
585 ** dbsqlfuzz fuzzer.
586 */
587 
588 /* An instance of the following object is passed by pointer as the
589 ** client data to various callbacks.
590 */
591 typedef struct FuzzCtx {
592   sqlite3 *db;               /* The database connection */
593   sqlite3_int64 iCutoffTime; /* Stop processing at this time. */
594   sqlite3_int64 iLastCb;     /* Time recorded for previous progress callback */
595   sqlite3_int64 mxInterval;  /* Longest interval between two progress calls */
596   unsigned nCb;              /* Number of progress callbacks */
597   unsigned mxCb;             /* Maximum number of progress callbacks allowed */
598   unsigned execCnt;          /* Number of calls to the sqlite3_exec callback */
599   int timeoutHit;            /* True when reaching a timeout */
600 } FuzzCtx;
601 
602 /* Verbosity level for the dbsqlfuzz test runner */
603 static int eVerbosity = 0;
604 
605 /* True to activate PRAGMA vdbe_debug=on */
606 static int bVdbeDebug = 0;
607 
608 /* Timeout for each fuzzing attempt, in milliseconds */
609 static int giTimeout = 10000;   /* Defaults to 10 seconds */
610 
611 /* Maximum number of progress handler callbacks */
612 static unsigned int mxProgressCb = 2000;
613 
614 /* Maximum string length in SQLite */
615 static int lengthLimit = 1000000;
616 
617 /* Maximum expression depth */
618 static int depthLimit = 500;
619 
620 /* Limit on the amount of heap memory that can be used */
621 static sqlite3_int64 heapLimit = 100000000;
622 
623 /* Maximum byte-code program length in SQLite */
624 static int vdbeOpLimit = 25000;
625 
626 /* Maximum size of the in-memory database */
627 static sqlite3_int64 maxDbSize = 104857600;
628 /* OOM simulation parameters */
629 static unsigned int oomCounter = 0;    /* Simulate OOM when equals 1 */
630 static unsigned int oomRepeat = 0;     /* Number of OOMs in a row */
631 static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
632 
633 /* This routine is called when a simulated OOM occurs.  It is broken
634 ** out as a separate routine to make it easy to set a breakpoint on
635 ** the OOM
636 */
637 void oomFault(void){
638   if( eVerbosity ){
639     printf("Simulated OOM fault\n");
640   }
641   if( oomRepeat>0 ){
642     oomRepeat--;
643   }else{
644     oomCounter--;
645   }
646 }
647 
648 /* This routine is a replacement malloc() that is used to simulate
649 ** Out-Of-Memory (OOM) errors for testing purposes.
650 */
651 static void *oomMalloc(int nByte){
652   if( oomCounter ){
653     if( oomCounter==1 ){
654       oomFault();
655       return 0;
656     }else{
657       oomCounter--;
658     }
659   }
660   return defaultMalloc(nByte);
661 }
662 
663 /* Register the OOM simulator.  This must occur before any memory
664 ** allocations */
665 static void registerOomSimulator(void){
666   sqlite3_mem_methods mem;
667   sqlite3_shutdown();
668   sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
669   defaultMalloc = mem.xMalloc;
670   mem.xMalloc = oomMalloc;
671   sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
672 }
673 
674 /* Turn off any pending OOM simulation */
675 static void disableOom(void){
676   oomCounter = 0;
677   oomRepeat = 0;
678 }
679 
680 /*
681 ** Translate a single byte of Hex into an integer.
682 ** This routine only works if h really is a valid hexadecimal
683 ** character:  0..9a..fA..F
684 */
685 static unsigned char hexToInt(unsigned int h){
686 #ifdef SQLITE_EBCDIC
687   h += 9*(1&~(h>>4));   /* EBCDIC */
688 #else
689   h += 9*(1&(h>>6));    /* ASCII */
690 #endif
691   return h & 0xf;
692 }
693 
694 /*
695 ** The first character of buffer zIn[0..nIn-1] is a '['.  This routine
696 ** checked to see if the buffer holds "[NNNN]" or "[+NNNN]" and if it
697 ** does it makes corresponding changes to the *pK value and *pI value
698 ** and returns true.  If the input buffer does not match the patterns,
699 ** no changes are made to either *pK or *pI and this routine returns false.
700 */
701 static int isOffset(
702   const unsigned char *zIn,  /* Text input */
703   int nIn,                   /* Bytes of input */
704   unsigned int *pK,          /* half-byte cursor to adjust */
705   unsigned int *pI           /* Input index to adjust */
706 ){
707   int i;
708   unsigned int k = 0;
709   unsigned char c;
710   for(i=1; i<nIn && (c = zIn[i])!=']'; i++){
711     if( !isxdigit(c) ) return 0;
712     k = k*16 + hexToInt(c);
713   }
714   if( i==nIn ) return 0;
715   *pK = 2*k;
716   *pI += i;
717   return 1;
718 }
719 
720 /*
721 ** Decode the text starting at zIn into a binary database file.
722 ** The maximum length of zIn is nIn bytes.  Store the binary database
723 ** file in space obtained from sqlite3_malloc().
724 **
725 ** Return the number of bytes of zIn consumed.  Or return -1 if there
726 ** is an error.  One potential error is that the recipe specifies a
727 ** database file larger than MX_FILE_SZ bytes.
728 **
729 ** Abort on an OOM.
730 */
731 static int decodeDatabase(
732   const unsigned char *zIn,      /* Input text to be decoded */
733   int nIn,                       /* Bytes of input text */
734   unsigned char **paDecode,      /* OUT: decoded database file */
735   int *pnDecode                  /* OUT: Size of decoded database */
736 ){
737   unsigned char *a, *aNew;       /* Database under construction */
738   int mx = 0;                    /* Current size of the database */
739   sqlite3_uint64 nAlloc = 4096;  /* Space allocated in a[] */
740   unsigned int i;                /* Next byte of zIn[] to read */
741   unsigned int j;                /* Temporary integer */
742   unsigned int k;                /* half-byte cursor index for output */
743   unsigned int n;                /* Number of bytes of input */
744   unsigned char b = 0;
745   if( nIn<4 ) return -1;
746   n = (unsigned int)nIn;
747   a = sqlite3_malloc64( nAlloc );
748   if( a==0 ){
749     fprintf(stderr, "Out of memory!\n");
750     exit(1);
751   }
752   memset(a, 0, (size_t)nAlloc);
753   for(i=k=0; i<n; i++){
754     unsigned char c = (unsigned char)zIn[i];
755     if( isxdigit(c) ){
756       k++;
757       if( k & 1 ){
758         b = hexToInt(c)*16;
759       }else{
760         b += hexToInt(c);
761         j = k/2 - 1;
762         if( j>=nAlloc ){
763           sqlite3_uint64 newSize;
764           if( nAlloc==MX_FILE_SZ || j>=MX_FILE_SZ ){
765             if( eVerbosity ){
766               fprintf(stderr, "Input database too big: max %d bytes\n",
767                       MX_FILE_SZ);
768             }
769             sqlite3_free(a);
770             return -1;
771           }
772           newSize = nAlloc*2;
773           if( newSize<=j ){
774             newSize = (j+4096)&~4095;
775           }
776           if( newSize>MX_FILE_SZ ){
777             if( j>=MX_FILE_SZ ){
778               sqlite3_free(a);
779               return -1;
780             }
781             newSize = MX_FILE_SZ;
782           }
783           aNew = sqlite3_realloc64( a, newSize );
784           if( aNew==0 ){
785             sqlite3_free(a);
786             return -1;
787           }
788           a = aNew;
789           assert( newSize > nAlloc );
790           memset(a+nAlloc, 0, (size_t)(newSize - nAlloc));
791           nAlloc = newSize;
792         }
793         if( j>=(unsigned)mx ){
794           mx = (j + 4095)&~4095;
795           if( mx>MX_FILE_SZ ) mx = MX_FILE_SZ;
796         }
797         assert( j<nAlloc );
798         a[j] = b;
799       }
800     }else if( zIn[i]=='[' && i<n-3 && isOffset(zIn+i, nIn-i, &k, &i) ){
801       continue;
802    }else if( zIn[i]=='\n' && i<n-4 && memcmp(zIn+i,"\n--\n",4)==0 ){
803       i += 4;
804       break;
805     }
806   }
807   *pnDecode = mx;
808   *paDecode = a;
809   return i;
810 }
811 
812 /*
813 ** Progress handler callback.
814 **
815 ** The argument is the cutoff-time after which all processing should
816 ** stop.  So return non-zero if the cut-off time is exceeded.
817 */
818 static int progress_handler(void *pClientData) {
819   FuzzCtx *p = (FuzzCtx*)pClientData;
820   sqlite3_int64 iNow = timeOfDay();
821   int rc = iNow>=p->iCutoffTime;
822   sqlite3_int64 iDiff = iNow - p->iLastCb;
823   /* printf("time-remaining: %lld\n", p->iCutoffTime - iNow); */
824   if( iDiff > p->mxInterval ) p->mxInterval = iDiff;
825   p->nCb++;
826   if( rc==0 && p->mxCb>0 && p->mxCb<=p->nCb ) rc = 1;
827   if( rc && !p->timeoutHit && eVerbosity>=2 ){
828     printf("Timeout on progress callback %d\n", p->nCb);
829     fflush(stdout);
830     p->timeoutHit = 1;
831   }
832   return rc;
833 }
834 
835 /*
836 ** Flag bits set by block_troublesome_sql()
837 */
838 #define BTS_SELECT      0x000001
839 #define BTS_NONSELECT   0x000002
840 #define BTS_BADFUNC     0x000004
841 
842 /*
843 ** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and
844 ** "PRAGMA parser_trace" since they can dramatically increase the
845 ** amount of output without actually testing anything useful.
846 **
847 ** Also block ATTACH if attaching a file from the filesystem.
848 */
849 static int block_troublesome_sql(
850   void *pClientData,
851   int eCode,
852   const char *zArg1,
853   const char *zArg2,
854   const char *zArg3,
855   const char *zArg4
856 ){
857   unsigned int *pFlags = (unsigned int*)pClientData;
858   (void)zArg3;
859   (void)zArg4;
860   switch( eCode ){
861     case SQLITE_PRAGMA: {
862       if( sqlite3_stricmp("busy_timeout",zArg1)==0
863        && (zArg2==0 || strtoll(zArg2,0,0)>100 || strtoll(zArg2,0,10)>100)
864       ){
865         return SQLITE_DENY;
866       }else if( eVerbosity==0 ){
867         if( sqlite3_strnicmp("vdbe_", zArg1, 5)==0
868          || sqlite3_stricmp("parser_trace", zArg1)==0
869          || sqlite3_stricmp("temp_store_directory", zArg1)==0
870         ){
871          return SQLITE_DENY;
872        }
873       }else if( sqlite3_stricmp("oom",zArg1)==0
874               && zArg2!=0 && zArg2[0]!=0 ){
875         oomCounter = atoi(zArg2);
876       }
877       *pFlags |= BTS_NONSELECT;
878       break;
879     }
880     case SQLITE_ATTACH: {
881       /* Deny the ATTACH if it is attaching anything other than an in-memory
882       ** database. */
883       *pFlags |= BTS_NONSELECT;
884       if( zArg1==0 ) return SQLITE_DENY;
885       if( strcmp(zArg1,":memory:")==0 ) return SQLITE_OK;
886       if( sqlite3_strglob("file:*[?]vfs=memdb", zArg1)==0
887        && sqlite3_strglob("file:*[^/a-zA-Z0-9_.]*[?]vfs=memdb", zArg1)!=0
888       ){
889         return SQLITE_OK;
890       }
891       return SQLITE_DENY;
892     }
893     case SQLITE_SELECT: {
894       *pFlags |= BTS_SELECT;
895       break;
896     }
897     case SQLITE_FUNCTION: {
898       static const char *azBadFuncs[] = {
899         "current_date",
900         "current_time",
901         "current_timestamp",
902         "date",
903         "datetime",
904         "implies_nonnull_row",
905         "julianday",
906         "random",
907         "randomblob",
908         "sqlite_offset",
909         "strftime",
910         "time",
911         "unixepoch",
912       };
913       int first, last;
914       first = 0;
915       last = sizeof(azBadFuncs)/sizeof(azBadFuncs[0]) - 1;
916       do{
917         int mid = (first+last)/2;
918         int c = sqlite3_stricmp(azBadFuncs[mid], zArg2);
919         if( c<0 ){
920           first = mid+1;
921         }else if( c>0 ){
922           last = mid-1;
923         }else{
924           *pFlags |= BTS_BADFUNC;
925           break;
926         }
927       }while( first<=last );
928       break;
929     }
930     case SQLITE_READ: {
931       /* Benign */
932       break;
933     }
934     default: {
935       *pFlags |= BTS_NONSELECT;
936     }
937   }
938   return SQLITE_OK;
939 }
940 
941 /* Implementation found in fuzzinvariant.c */
942 int fuzz_invariant(
943   sqlite3 *db,            /* The database connection */
944   sqlite3_stmt *pStmt,    /* Test statement stopped on an SQLITE_ROW */
945   int iCnt,               /* Invariant sequence number, starting at 0 */
946   int iRow,               /* The row number for pStmt */
947   int nRow,               /* Total number of output rows */
948   int *pbCorrupt,         /* IN/OUT: Flag indicating a corrupt database file */
949   int eVerbosity          /* How much debugging output */
950 );
951 
952 /*
953 ** Run the SQL text
954 */
955 static int runDbSql(sqlite3 *db, const char *zSql, unsigned int *pBtsFlags){
956   int rc;
957   sqlite3_stmt *pStmt;
958   int bCorrupt = 0;
959   while( isspace(zSql[0]&0x7f) ) zSql++;
960   if( zSql[0]==0 ) return SQLITE_OK;
961   if( eVerbosity>=4 ){
962     printf("RUNNING-SQL: [%s]\n", zSql);
963     fflush(stdout);
964   }
965   (*pBtsFlags) = 0;
966   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
967   if( rc==SQLITE_OK ){
968     int nRow = 0;
969     while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
970       nRow++;
971       if( eVerbosity>=4 ){
972         int j;
973         for(j=0; j<sqlite3_column_count(pStmt); j++){
974           if( j ) printf(",");
975           switch( sqlite3_column_type(pStmt, j) ){
976             case SQLITE_NULL: {
977               printf("NULL");
978               break;
979             }
980             case SQLITE_INTEGER:
981             case SQLITE_FLOAT: {
982               printf("%s", sqlite3_column_text(pStmt, j));
983               break;
984             }
985             case SQLITE_BLOB: {
986               int n = sqlite3_column_bytes(pStmt, j);
987               int i;
988               const unsigned char *a;
989               a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
990               printf("x'");
991               for(i=0; i<n; i++){
992                 printf("%02x", a[i]);
993               }
994               printf("'");
995               break;
996             }
997             case SQLITE_TEXT: {
998               int n = sqlite3_column_bytes(pStmt, j);
999               int i;
1000               const unsigned char *a;
1001               a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
1002               printf("'");
1003               for(i=0; i<n; i++){
1004                 if( a[i]=='\'' ){
1005                   printf("''");
1006                 }else{
1007                   putchar(a[i]);
1008                 }
1009               }
1010               printf("'");
1011               break;
1012             }
1013           } /* End switch() */
1014         } /* End for() */
1015         printf("\n");
1016         fflush(stdout);
1017       } /* End if( eVerbosity>=5 ) */
1018     } /* End while( SQLITE_ROW */
1019     if( rc==SQLITE_DONE ){
1020       if( (*pBtsFlags)==BTS_SELECT
1021        && g.doInvariantChecks
1022        && !sqlite3_stmt_isexplain(pStmt)
1023        && nRow>0
1024       ){
1025         int iRow = 0;
1026         sqlite3_reset(pStmt);
1027         while( sqlite3_step(pStmt)==SQLITE_ROW ){
1028           int iCnt = 0;
1029           iRow++;
1030           for(iCnt=0; iCnt<99999; iCnt++){
1031             rc = fuzz_invariant(db, pStmt, iCnt, iRow, nRow,
1032                                 &bCorrupt, eVerbosity);
1033             if( rc==SQLITE_DONE ) break;
1034             if( rc!=SQLITE_ERROR ) g.nInvariant++;
1035             if( eVerbosity>0 ){
1036               if( rc==SQLITE_OK ){
1037                 printf("invariant-check: ok\n");
1038               }else if( rc==SQLITE_CORRUPT ){
1039                 printf("invariant-check: failed due to database corruption\n");
1040               }
1041             }
1042           }
1043         }
1044       }
1045     }else if( eVerbosity>=4 ){
1046       printf("SQL-ERROR: (%d) %s\n", rc, sqlite3_errmsg(db));
1047       fflush(stdout);
1048     }
1049   }else if( eVerbosity>=4 ){
1050     printf("SQL-ERROR (%d): %s\n", rc, sqlite3_errmsg(db));
1051     fflush(stdout);
1052   } /* End if( SQLITE_OK ) */
1053   return sqlite3_finalize(pStmt);
1054 }
1055 
1056 /* Invoke this routine to run a single test case */
1057 int runCombinedDbSqlInput(
1058   const uint8_t *aData,      /* Combined DB+SQL content */
1059   size_t nByte,              /* Size of aData in bytes */
1060   int iTimeout,              /* Use this timeout */
1061   int bScript,               /* If true, just render CLI output */
1062   int iSqlId                 /* SQL identifier */
1063 ){
1064   int rc;                    /* SQLite API return value */
1065   int iSql;                  /* Index in aData[] of start of SQL */
1066   unsigned char *aDb = 0;    /* Decoded database content */
1067   int nDb = 0;               /* Size of the decoded database */
1068   int i;                     /* Loop counter */
1069   int j;                     /* Start of current SQL statement */
1070   char *zSql = 0;            /* SQL text to run */
1071   int nSql;                  /* Bytes of SQL text */
1072   FuzzCtx cx;                /* Fuzzing context */
1073   unsigned int btsFlags = 0; /* Parsing flags */
1074 
1075   if( nByte<10 ) return 0;
1076   if( sqlite3_initialize() ) return 0;
1077   if( sqlite3_memory_used()!=0 ){
1078     int nAlloc = 0;
1079     int nNotUsed = 0;
1080     sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
1081     fprintf(stderr,"memory leak prior to test start:"
1082                    " %lld bytes in %d allocations\n",
1083             sqlite3_memory_used(), nAlloc);
1084     exit(1);
1085   }
1086   memset(&cx, 0, sizeof(cx));
1087   iSql = decodeDatabase((unsigned char*)aData, (int)nByte, &aDb, &nDb);
1088   if( iSql<0 ) return 0;
1089   nSql = (int)(nByte - iSql);
1090   if( bScript ){
1091     char zName[100];
1092     sqlite3_snprintf(sizeof(zName),zName,"dbsql%06d.db",iSqlId);
1093     renderDbSqlForCLI(stdout, zName, aDb, nDb,
1094                       (unsigned char*)(aData+iSql), nSql);
1095     sqlite3_free(aDb);
1096     return 0;
1097   }
1098   if( eVerbosity>=3 ){
1099     printf(
1100       "****** %d-byte input, %d-byte database, %d-byte script "
1101       "******\n", (int)nByte, nDb, nSql);
1102     fflush(stdout);
1103   }
1104   rc = sqlite3_open(0, &cx.db);
1105   if( rc ){
1106     sqlite3_free(aDb);
1107     return 1;
1108   }
1109   if( bVdbeDebug ){
1110     sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
1111   }
1112 
1113   /* Invoke the progress handler frequently to check to see if we
1114   ** are taking too long.  The progress handler will return true
1115   ** (which will block further processing) if more than giTimeout seconds have
1116   ** elapsed since the start of the test.
1117   */
1118   cx.iLastCb = timeOfDay();
1119   cx.iCutoffTime = cx.iLastCb + (iTimeout<giTimeout ? iTimeout : giTimeout);
1120   cx.mxCb = mxProgressCb;
1121 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1122   sqlite3_progress_handler(cx.db, 10, progress_handler, (void*)&cx);
1123 #endif
1124 
1125   /* Set a limit on the maximum size of a prepared statement, and the
1126   ** maximum length of a string or blob */
1127   if( vdbeOpLimit>0 ){
1128     sqlite3_limit(cx.db, SQLITE_LIMIT_VDBE_OP, vdbeOpLimit);
1129   }
1130   if( lengthLimit>0 ){
1131     sqlite3_limit(cx.db, SQLITE_LIMIT_LENGTH, lengthLimit);
1132   }
1133   if( depthLimit>0 ){
1134     sqlite3_limit(cx.db, SQLITE_LIMIT_EXPR_DEPTH, depthLimit);
1135   }
1136   sqlite3_limit(cx.db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 100);
1137   sqlite3_hard_heap_limit64(heapLimit);
1138 
1139   if( nDb>=20 && aDb[18]==2 && aDb[19]==2 ){
1140     aDb[18] = aDb[19] = 1;
1141   }
1142   rc = sqlite3_deserialize(cx.db, "main", aDb, nDb, nDb,
1143           SQLITE_DESERIALIZE_RESIZEABLE |
1144           SQLITE_DESERIALIZE_FREEONCLOSE);
1145   if( rc ){
1146     fprintf(stderr, "sqlite3_deserialize() failed with %d\n", rc);
1147     goto testrun_finished;
1148   }
1149   if( maxDbSize>0 ){
1150     sqlite3_int64 x = maxDbSize;
1151     sqlite3_file_control(cx.db, "main", SQLITE_FCNTL_SIZE_LIMIT, &x);
1152   }
1153 
1154   /* For high debugging levels, turn on debug mode */
1155   if( eVerbosity>=5 ){
1156     sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON;", 0, 0, 0);
1157   }
1158 
1159   /* Block debug pragmas and ATTACH/DETACH.  But wait until after
1160   ** deserialize to do this because deserialize depends on ATTACH */
1161   sqlite3_set_authorizer(cx.db, block_troublesome_sql, &btsFlags);
1162 
1163 #ifdef VT02_SOURCES
1164   sqlite3_vt02_init(cx.db, 0, 0);
1165 #endif
1166 
1167   /* Consistent PRNG seed */
1168 #ifdef SQLITE_TESTCTRL_PRNG_SEED
1169   sqlite3_table_column_metadata(cx.db, 0, "x", 0, 0, 0, 0, 0, 0);
1170   sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, cx.db);
1171 #else
1172   sqlite3_randomness(0,0);
1173 #endif
1174 
1175   zSql = sqlite3_malloc( nSql + 1 );
1176   if( zSql==0 ){
1177     fprintf(stderr, "Out of memory!\n");
1178   }else{
1179     memcpy(zSql, aData+iSql, nSql);
1180     zSql[nSql] = 0;
1181     for(i=j=0; zSql[i]; i++){
1182       if( zSql[i]==';' ){
1183         char cSaved = zSql[i+1];
1184         zSql[i+1] = 0;
1185         if( sqlite3_complete(zSql+j) ){
1186           rc = runDbSql(cx.db, zSql+j, &btsFlags);
1187           j = i+1;
1188         }
1189         zSql[i+1] = cSaved;
1190         if( rc==SQLITE_INTERRUPT || progress_handler(&cx) ){
1191           goto testrun_finished;
1192         }
1193       }
1194     }
1195     if( j<i ){
1196       runDbSql(cx.db, zSql+j, &btsFlags);
1197     }
1198   }
1199 testrun_finished:
1200   sqlite3_free(zSql);
1201   rc = sqlite3_close(cx.db);
1202   if( rc!=SQLITE_OK ){
1203     fprintf(stdout, "sqlite3_close() returns %d\n", rc);
1204   }
1205   if( eVerbosity>=2 && !bScript ){
1206     fprintf(stdout, "Peak memory usages: %f MB\n",
1207        sqlite3_memory_highwater(1) / 1000000.0);
1208   }
1209   if( sqlite3_memory_used()!=0 ){
1210     int nAlloc = 0;
1211     int nNotUsed = 0;
1212     sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
1213     fprintf(stderr,"Memory leak: %lld bytes in %d allocations\n",
1214             sqlite3_memory_used(), nAlloc);
1215     exit(1);
1216   }
1217   sqlite3_hard_heap_limit64(0);
1218   sqlite3_soft_heap_limit64(0);
1219   return 0;
1220 }
1221 
1222 /*
1223 ** END of the dbsqlfuzz code
1224 ***************************************************************************/
1225 
1226 /* Look at a SQL text and try to determine if it begins with a database
1227 ** description, such as would be found in a dbsqlfuzz test case.  Return
1228 ** true if this does appear to be a dbsqlfuzz test case and false otherwise.
1229 */
1230 static int isDbSql(unsigned char *a, int n){
1231   unsigned char buf[12];
1232   int i;
1233   if( n>4 && memcmp(a,"\n--\n",4)==0 ) return 1;
1234   while( n>0 && isspace(a[0]) ){ a++; n--; }
1235   for(i=0; n>0 && i<8; n--, a++){
1236     if( isxdigit(a[0]) ) buf[i++] = a[0];
1237   }
1238   if( i==8 && memcmp(buf,"53514c69",8)==0 ) return 1;
1239   return 0;
1240 }
1241 
1242 /* Implementation of the isdbsql(TEXT) SQL function.
1243 */
1244 static void isDbSqlFunc(
1245   sqlite3_context *context,
1246   int argc,
1247   sqlite3_value **argv
1248 ){
1249   int n = sqlite3_value_bytes(argv[0]);
1250   unsigned char *a = (unsigned char*)sqlite3_value_blob(argv[0]);
1251   sqlite3_result_int(context, a!=0 && n>0 && isDbSql(a,n));
1252 }
1253 
1254 /* Methods for the VHandle object
1255 */
1256 static int inmemClose(sqlite3_file *pFile){
1257   VHandle *p = (VHandle*)pFile;
1258   VFile *pVFile = p->pVFile;
1259   pVFile->nRef--;
1260   if( pVFile->nRef==0 && pVFile->zFilename==0 ){
1261     pVFile->sz = -1;
1262     free(pVFile->a);
1263     pVFile->a = 0;
1264   }
1265   return SQLITE_OK;
1266 }
1267 static int inmemRead(
1268   sqlite3_file *pFile,   /* Read from this open file */
1269   void *pData,           /* Store content in this buffer */
1270   int iAmt,              /* Bytes of content */
1271   sqlite3_int64 iOfst    /* Start reading here */
1272 ){
1273   VHandle *pHandle = (VHandle*)pFile;
1274   VFile *pVFile = pHandle->pVFile;
1275   if( iOfst<0 || iOfst>=pVFile->sz ){
1276     memset(pData, 0, iAmt);
1277     return SQLITE_IOERR_SHORT_READ;
1278   }
1279   if( iOfst+iAmt>pVFile->sz ){
1280     memset(pData, 0, iAmt);
1281     iAmt = (int)(pVFile->sz - iOfst);
1282     memcpy(pData, pVFile->a + iOfst, iAmt);
1283     return SQLITE_IOERR_SHORT_READ;
1284   }
1285   memcpy(pData, pVFile->a + iOfst, iAmt);
1286   return SQLITE_OK;
1287 }
1288 static int inmemWrite(
1289   sqlite3_file *pFile,   /* Write to this file */
1290   const void *pData,     /* Content to write */
1291   int iAmt,              /* bytes to write */
1292   sqlite3_int64 iOfst    /* Start writing here */
1293 ){
1294   VHandle *pHandle = (VHandle*)pFile;
1295   VFile *pVFile = pHandle->pVFile;
1296   if( iOfst+iAmt > pVFile->sz ){
1297     if( iOfst+iAmt >= MX_FILE_SZ ){
1298       return SQLITE_FULL;
1299     }
1300     pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt));
1301     if( iOfst > pVFile->sz ){
1302       memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz));
1303     }
1304     pVFile->sz = (int)(iOfst + iAmt);
1305   }
1306   memcpy(pVFile->a + iOfst, pData, iAmt);
1307   return SQLITE_OK;
1308 }
1309 static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){
1310   VHandle *pHandle = (VHandle*)pFile;
1311   VFile *pVFile = pHandle->pVFile;
1312   if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize;
1313   return SQLITE_OK;
1314 }
1315 static int inmemSync(sqlite3_file *pFile, int flags){
1316   return SQLITE_OK;
1317 }
1318 static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){
1319   *pSize = ((VHandle*)pFile)->pVFile->sz;
1320   return SQLITE_OK;
1321 }
1322 static int inmemLock(sqlite3_file *pFile, int type){
1323   return SQLITE_OK;
1324 }
1325 static int inmemUnlock(sqlite3_file *pFile, int type){
1326   return SQLITE_OK;
1327 }
1328 static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){
1329   *pOut = 0;
1330   return SQLITE_OK;
1331 }
1332 static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){
1333   return SQLITE_NOTFOUND;
1334 }
1335 static int inmemSectorSize(sqlite3_file *pFile){
1336   return 512;
1337 }
1338 static int inmemDeviceCharacteristics(sqlite3_file *pFile){
1339   return
1340       SQLITE_IOCAP_SAFE_APPEND |
1341       SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
1342       SQLITE_IOCAP_POWERSAFE_OVERWRITE;
1343 }
1344 
1345 
1346 /* Method table for VHandle
1347 */
1348 static sqlite3_io_methods VHandleMethods = {
1349   /* iVersion  */    1,
1350   /* xClose    */    inmemClose,
1351   /* xRead     */    inmemRead,
1352   /* xWrite    */    inmemWrite,
1353   /* xTruncate */    inmemTruncate,
1354   /* xSync     */    inmemSync,
1355   /* xFileSize */    inmemFileSize,
1356   /* xLock     */    inmemLock,
1357   /* xUnlock   */    inmemUnlock,
1358   /* xCheck... */    inmemCheckReservedLock,
1359   /* xFileCtrl */    inmemFileControl,
1360   /* xSectorSz */    inmemSectorSize,
1361   /* xDevchar  */    inmemDeviceCharacteristics,
1362   /* xShmMap   */    0,
1363   /* xShmLock  */    0,
1364   /* xShmBarrier */  0,
1365   /* xShmUnmap */    0,
1366   /* xFetch    */    0,
1367   /* xUnfetch  */    0
1368 };
1369 
1370 /*
1371 ** Open a new file in the inmem VFS.  All files are anonymous and are
1372 ** delete-on-close.
1373 */
1374 static int inmemOpen(
1375   sqlite3_vfs *pVfs,
1376   const char *zFilename,
1377   sqlite3_file *pFile,
1378   int openFlags,
1379   int *pOutFlags
1380 ){
1381   VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)"");
1382   VHandle *pHandle = (VHandle*)pFile;
1383   if( pVFile==0 ){
1384     return SQLITE_FULL;
1385   }
1386   pHandle->pVFile = pVFile;
1387   pVFile->nRef++;
1388   pFile->pMethods = &VHandleMethods;
1389   if( pOutFlags ) *pOutFlags = openFlags;
1390   return SQLITE_OK;
1391 }
1392 
1393 /*
1394 ** Delete a file by name
1395 */
1396 static int inmemDelete(
1397   sqlite3_vfs *pVfs,
1398   const char *zFilename,
1399   int syncdir
1400 ){
1401   VFile *pVFile = findVFile(zFilename);
1402   if( pVFile==0 ) return SQLITE_OK;
1403   if( pVFile->nRef==0 ){
1404     free(pVFile->zFilename);
1405     pVFile->zFilename = 0;
1406     pVFile->sz = -1;
1407     free(pVFile->a);
1408     pVFile->a = 0;
1409     return SQLITE_OK;
1410   }
1411   return SQLITE_IOERR_DELETE;
1412 }
1413 
1414 /* Check for the existance of a file
1415 */
1416 static int inmemAccess(
1417   sqlite3_vfs *pVfs,
1418   const char *zFilename,
1419   int flags,
1420   int *pResOut
1421 ){
1422   VFile *pVFile = findVFile(zFilename);
1423   *pResOut =  pVFile!=0;
1424   return SQLITE_OK;
1425 }
1426 
1427 /* Get the canonical pathname for a file
1428 */
1429 static int inmemFullPathname(
1430   sqlite3_vfs *pVfs,
1431   const char *zFilename,
1432   int nOut,
1433   char *zOut
1434 ){
1435   sqlite3_snprintf(nOut, zOut, "%s", zFilename);
1436   return SQLITE_OK;
1437 }
1438 
1439 /* Always use the same random see, for repeatability.
1440 */
1441 static int inmemRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
1442   memset(zBuf, 0, nBuf);
1443   memcpy(zBuf, &g.uRandom, nBuf<sizeof(g.uRandom) ? nBuf : sizeof(g.uRandom));
1444   return nBuf;
1445 }
1446 
1447 /*
1448 ** Register the VFS that reads from the g.aFile[] set of files.
1449 */
1450 static void inmemVfsRegister(int makeDefault){
1451   static sqlite3_vfs inmemVfs;
1452   sqlite3_vfs *pDefault = sqlite3_vfs_find(0);
1453   inmemVfs.iVersion = 3;
1454   inmemVfs.szOsFile = sizeof(VHandle);
1455   inmemVfs.mxPathname = 200;
1456   inmemVfs.zName = "inmem";
1457   inmemVfs.xOpen = inmemOpen;
1458   inmemVfs.xDelete = inmemDelete;
1459   inmemVfs.xAccess = inmemAccess;
1460   inmemVfs.xFullPathname = inmemFullPathname;
1461   inmemVfs.xRandomness = inmemRandomness;
1462   inmemVfs.xSleep = pDefault->xSleep;
1463   inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64;
1464   sqlite3_vfs_register(&inmemVfs, makeDefault);
1465 };
1466 
1467 /*
1468 ** Allowed values for the runFlags parameter to runSql()
1469 */
1470 #define SQL_TRACE  0x0001     /* Print each SQL statement as it is prepared */
1471 #define SQL_OUTPUT 0x0002     /* Show the SQL output */
1472 
1473 /*
1474 ** Run multiple commands of SQL.  Similar to sqlite3_exec(), but does not
1475 ** stop if an error is encountered.
1476 */
1477 static void runSql(sqlite3 *db, const char *zSql, unsigned  runFlags){
1478   const char *zMore;
1479   sqlite3_stmt *pStmt;
1480 
1481   while( zSql && zSql[0] ){
1482     zMore = 0;
1483     pStmt = 0;
1484     sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore);
1485     if( zMore==zSql ) break;
1486     if( runFlags & SQL_TRACE ){
1487       const char *z = zSql;
1488       int n;
1489       while( z<zMore && ISSPACE(z[0]) ) z++;
1490       n = (int)(zMore - z);
1491       while( n>0 && ISSPACE(z[n-1]) ) n--;
1492       if( n==0 ) break;
1493       if( pStmt==0 ){
1494         printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db));
1495       }else{
1496         printf("TRACE: %.*s\n", n, z);
1497       }
1498     }
1499     zSql = zMore;
1500     if( pStmt ){
1501       if( (runFlags & SQL_OUTPUT)==0 ){
1502         while( SQLITE_ROW==sqlite3_step(pStmt) ){}
1503       }else{
1504         int nCol = -1;
1505         while( SQLITE_ROW==sqlite3_step(pStmt) ){
1506           int i;
1507           if( nCol<0 ){
1508             nCol = sqlite3_column_count(pStmt);
1509           }else if( nCol>0 ){
1510             printf("--------------------------------------------\n");
1511           }
1512           for(i=0; i<nCol; i++){
1513             int eType = sqlite3_column_type(pStmt,i);
1514             printf("%s = ", sqlite3_column_name(pStmt,i));
1515             switch( eType ){
1516               case SQLITE_NULL: {
1517                 printf("NULL\n");
1518                 break;
1519               }
1520               case SQLITE_INTEGER: {
1521                 printf("INT %s\n", sqlite3_column_text(pStmt,i));
1522                 break;
1523               }
1524               case SQLITE_FLOAT: {
1525                 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i));
1526                 break;
1527               }
1528               case SQLITE_TEXT: {
1529                 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i));
1530                 break;
1531               }
1532               case SQLITE_BLOB: {
1533                 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i));
1534                 break;
1535               }
1536             }
1537           }
1538         }
1539       }
1540       sqlite3_finalize(pStmt);
1541     }
1542   }
1543 }
1544 
1545 /*
1546 ** Rebuild the database file.
1547 **
1548 **    (1)  Remove duplicate entries
1549 **    (2)  Put all entries in order
1550 **    (3)  Vacuum
1551 */
1552 static void rebuild_database(sqlite3 *db, int dbSqlOnly){
1553   int rc;
1554   char *zSql;
1555   zSql = sqlite3_mprintf(
1556      "BEGIN;\n"
1557      "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n"
1558      "DELETE FROM db;\n"
1559      "INSERT INTO db(dbid, dbcontent) "
1560         " SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n"
1561      "DROP TABLE dbx;\n"
1562      "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql %s;\n"
1563      "DELETE FROM xsql;\n"
1564      "INSERT INTO xsql(sqlid,sqltext) "
1565         " SELECT NULL, sqltext FROM sx ORDER BY 2;\n"
1566      "DROP TABLE sx;\n"
1567      "COMMIT;\n"
1568      "PRAGMA page_size=1024;\n"
1569      "VACUUM;\n",
1570      dbSqlOnly ? " WHERE isdbsql(sqltext)" : ""
1571   );
1572   rc = sqlite3_exec(db, zSql, 0, 0, 0);
1573   sqlite3_free(zSql);
1574   if( rc ) fatalError("cannot rebuild: %s", sqlite3_errmsg(db));
1575 }
1576 
1577 /*
1578 ** Return the value of a hexadecimal digit.  Return -1 if the input
1579 ** is not a hex digit.
1580 */
1581 static int hexDigitValue(char c){
1582   if( c>='0' && c<='9' ) return c - '0';
1583   if( c>='a' && c<='f' ) return c - 'a' + 10;
1584   if( c>='A' && c<='F' ) return c - 'A' + 10;
1585   return -1;
1586 }
1587 
1588 /*
1589 ** Interpret zArg as an integer value, possibly with suffixes.
1590 */
1591 static int integerValue(const char *zArg){
1592   sqlite3_int64 v = 0;
1593   static const struct { char *zSuffix; int iMult; } aMult[] = {
1594     { "KiB", 1024 },
1595     { "MiB", 1024*1024 },
1596     { "GiB", 1024*1024*1024 },
1597     { "KB",  1000 },
1598     { "MB",  1000000 },
1599     { "GB",  1000000000 },
1600     { "K",   1000 },
1601     { "M",   1000000 },
1602     { "G",   1000000000 },
1603   };
1604   int i;
1605   int isNeg = 0;
1606   if( zArg[0]=='-' ){
1607     isNeg = 1;
1608     zArg++;
1609   }else if( zArg[0]=='+' ){
1610     zArg++;
1611   }
1612   if( zArg[0]=='0' && zArg[1]=='x' ){
1613     int x;
1614     zArg += 2;
1615     while( (x = hexDigitValue(zArg[0]))>=0 ){
1616       v = (v<<4) + x;
1617       zArg++;
1618     }
1619   }else{
1620     while( ISDIGIT(zArg[0]) ){
1621       v = v*10 + zArg[0] - '0';
1622       zArg++;
1623     }
1624   }
1625   for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
1626     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1627       v *= aMult[i].iMult;
1628       break;
1629     }
1630   }
1631   if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648");
1632   return (int)(isNeg? -v : v);
1633 }
1634 
1635 /*
1636 ** Return the number of "v" characters in a string.  Return 0 if there
1637 ** are any characters in the string other than "v".
1638 */
1639 static int numberOfVChar(const char *z){
1640   int N = 0;
1641   while( z[0] && z[0]=='v' ){
1642     z++;
1643     N++;
1644   }
1645   return z[0]==0 ? N : 0;
1646 }
1647 
1648 /*
1649 ** Print sketchy documentation for this utility program
1650 */
1651 static void showHelp(void){
1652   printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0);
1653   printf(
1654 "Read databases and SQL scripts from SOURCE-DB and execute each script against\n"
1655 "each database, checking for crashes and memory leaks.\n"
1656 "Options:\n"
1657 "  --cell-size-check    Set the PRAGMA cell_size_check=ON\n"
1658 "  --dbid N             Use only the database where dbid=N\n"
1659 "  --export-db DIR      Write databases to files(s) in DIR. Works with --dbid\n"
1660 "  --export-sql DIR     Write SQL to file(s) in DIR. Also works with --sqlid\n"
1661 "  --help               Show this help text\n"
1662 "  --info               Show information about SOURCE-DB w/o running tests\n"
1663 "  --limit-depth N      Limit expression depth to N.  Default: 500\n"
1664 "  --limit-heap N       Limit heap memory to N.  Default: 100M\n"
1665 "  --limit-mem N        Limit memory used by test SQLite instance to N bytes\n"
1666 "  --limit-vdbe         Panic if any test runs for more than 100,000 cycles\n"
1667 "  --load-sql   FILE..  Load SQL scripts fron files into SOURCE-DB\n"
1668 "  --load-db    FILE..  Load template databases from files into SOURCE_DB\n"
1669 "  --load-dbsql FILE..  Load dbsqlfuzz outputs into the xsql table\n"
1670 "               ^^^^------ Use \"-\" for FILE to read filenames from stdin\n"
1671 "  -m TEXT              Add a description to the database\n"
1672 "  --native-vfs         Use the native VFS for initially empty database files\n"
1673 "  --native-malloc      Turn off MEMSYS3/5 and Lookaside\n"
1674 "  --oss-fuzz           Enable OSS-FUZZ testing\n"
1675 "  --prng-seed N        Seed value for the PRGN inside of SQLite\n"
1676 "  -q|--quiet           Reduced output\n"
1677 "  --query-invariants   Run query invariant checks\n"
1678 "  --rebuild            Rebuild and vacuum the database file\n"
1679 "  --result-trace       Show the results of each SQL command\n"
1680 "  --script             Output CLI script instead of running tests\n"
1681 "  --skip N             Skip the first N test cases\n"
1682 "  --spinner            Use a spinner to show progress\n"
1683 "  --sqlid N            Use only SQL where sqlid=N\n"
1684 "  --timeout N          Maximum time for any one test in N millseconds\n"
1685 "  -v|--verbose         Increased output.  Repeat for more output.\n"
1686 "  --vdbe-debug         Activate VDBE debugging.\n"
1687   );
1688 }
1689 
1690 int main(int argc, char **argv){
1691   sqlite3_int64 iBegin;        /* Start time of this program */
1692   int quietFlag = 0;           /* True if --quiet or -q */
1693   int verboseFlag = 0;         /* True if --verbose or -v */
1694   char *zInsSql = 0;           /* SQL statement for --load-db or --load-sql */
1695   int iFirstInsArg = 0;        /* First argv[] for --load-db or --load-sql */
1696   sqlite3 *db = 0;             /* The open database connection */
1697   sqlite3_stmt *pStmt;         /* A prepared statement */
1698   int rc;                      /* Result code from SQLite interface calls */
1699   Blob *pSql;                  /* For looping over SQL scripts */
1700   Blob *pDb;                   /* For looping over template databases */
1701   int i;                       /* Loop index for the argv[] loop */
1702   int dbSqlOnly = 0;           /* Only use scripts that are dbsqlfuzz */
1703   int onlySqlid = -1;          /* --sqlid */
1704   int onlyDbid = -1;           /* --dbid */
1705   int nativeFlag = 0;          /* --native-vfs */
1706   int rebuildFlag = 0;         /* --rebuild */
1707   int vdbeLimitFlag = 0;       /* --limit-vdbe */
1708   int infoFlag = 0;            /* --info */
1709   int nSkip = 0;               /* --skip */
1710   int bScript = 0;             /* --script */
1711   int bSpinner = 0;            /* True for --spinner */
1712   int timeoutTest = 0;         /* undocumented --timeout-test flag */
1713   int runFlags = 0;            /* Flags sent to runSql() */
1714   char *zMsg = 0;              /* Add this message */
1715   int nSrcDb = 0;              /* Number of source databases */
1716   char **azSrcDb = 0;          /* Array of source database names */
1717   int iSrcDb;                  /* Loop over all source databases */
1718   int nTest = 0;               /* Total number of tests performed */
1719   char *zDbName = "";          /* Appreviated name of a source database */
1720   const char *zFailCode = 0;   /* Value of the TEST_FAILURE env variable */
1721   int cellSzCkFlag = 0;        /* --cell-size-check */
1722   int sqlFuzz = 0;             /* True for SQL fuzz. False for DB fuzz */
1723   int iTimeout = 120000;       /* Default 120-second timeout */
1724   int nMem = 0;                /* Memory limit override */
1725   int nMemThisDb = 0;          /* Memory limit set by the CONFIG table */
1726   char *zExpDb = 0;            /* Write Databases to files in this directory */
1727   char *zExpSql = 0;           /* Write SQL to files in this directory */
1728   void *pHeap = 0;             /* Heap for use by SQLite */
1729   int ossFuzz = 0;             /* enable OSS-FUZZ testing */
1730   int ossFuzzThisDb = 0;       /* ossFuzz value for this particular database */
1731   int nativeMalloc = 0;        /* Turn off MEMSYS3/5 and lookaside if true */
1732   sqlite3_vfs *pDfltVfs;       /* The default VFS */
1733   int openFlags4Data;          /* Flags for sqlite3_open_v2() */
1734   int bTimer = 0;              /* Show elapse time for each test */
1735   int nV;                      /* How much to increase verbosity with -vvvv */
1736   sqlite3_int64 tmStart;       /* Start of each test */
1737 
1738   sqlite3_config(SQLITE_CONFIG_URI,1);
1739   registerOomSimulator();
1740   sqlite3_initialize();
1741   iBegin = timeOfDay();
1742 #ifdef __unix__
1743   signal(SIGALRM, signalHandler);
1744   signal(SIGSEGV, signalHandler);
1745   signal(SIGABRT, signalHandler);
1746 #endif
1747   g.zArgv0 = argv[0];
1748   openFlags4Data = SQLITE_OPEN_READONLY;
1749   zFailCode = getenv("TEST_FAILURE");
1750   pDfltVfs = sqlite3_vfs_find(0);
1751   inmemVfsRegister(1);
1752   for(i=1; i<argc; i++){
1753     const char *z = argv[i];
1754     if( z[0]=='-' ){
1755       z++;
1756       if( z[0]=='-' ) z++;
1757       if( strcmp(z,"cell-size-check")==0 ){
1758         cellSzCkFlag = 1;
1759       }else
1760       if( strcmp(z,"dbid")==0 ){
1761         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1762         onlyDbid = integerValue(argv[++i]);
1763       }else
1764       if( strcmp(z,"export-db")==0 ){
1765         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1766         zExpDb = argv[++i];
1767       }else
1768       if( strcmp(z,"export-sql")==0 || strcmp(z,"export-dbsql")==0 ){
1769         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1770         zExpSql = argv[++i];
1771       }else
1772       if( strcmp(z,"help")==0 ){
1773         showHelp();
1774         return 0;
1775       }else
1776       if( strcmp(z,"info")==0 ){
1777         infoFlag = 1;
1778       }else
1779       if( strcmp(z,"limit-depth")==0 ){
1780         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1781         depthLimit = integerValue(argv[++i]);
1782       }else
1783       if( strcmp(z,"limit-heap")==0 ){
1784         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1785         heapLimit = integerValue(argv[++i]);
1786       }else
1787       if( strcmp(z,"limit-mem")==0 ){
1788         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1789         nMem = integerValue(argv[++i]);
1790       }else
1791       if( strcmp(z,"limit-vdbe")==0 ){
1792         vdbeLimitFlag = 1;
1793       }else
1794       if( strcmp(z,"load-sql")==0 ){
1795         zInsSql = "INSERT INTO xsql(sqltext)"
1796                   "VALUES(CAST(readtextfile(?1) AS text))";
1797         iFirstInsArg = i+1;
1798         openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1799         break;
1800       }else
1801       if( strcmp(z,"load-db")==0 ){
1802         zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
1803         iFirstInsArg = i+1;
1804         openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1805         break;
1806       }else
1807       if( strcmp(z,"load-dbsql")==0 ){
1808         zInsSql = "INSERT INTO xsql(sqltext)"
1809                   "VALUES(readfile(?1))";
1810         iFirstInsArg = i+1;
1811         openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1812         dbSqlOnly = 1;
1813         break;
1814       }else
1815       if( strcmp(z,"m")==0 ){
1816         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1817         zMsg = argv[++i];
1818         openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1819       }else
1820       if( strcmp(z,"native-malloc")==0 ){
1821         nativeMalloc = 1;
1822       }else
1823       if( strcmp(z,"native-vfs")==0 ){
1824         nativeFlag = 1;
1825       }else
1826       if( strcmp(z,"oss-fuzz")==0 ){
1827         ossFuzz = 1;
1828       }else
1829       if( strcmp(z,"prng-seed")==0 ){
1830         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1831         g.uRandom = atoi(argv[++i]);
1832       }else
1833       if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
1834         quietFlag = 1;
1835         verboseFlag = 0;
1836         eVerbosity = 0;
1837       }else
1838       if( strcmp(z,"query-invariants")==0 ){
1839         g.doInvariantChecks = 1;
1840       }else
1841       if( strcmp(z,"rebuild")==0 ){
1842         rebuildFlag = 1;
1843         openFlags4Data = SQLITE_OPEN_READWRITE;
1844       }else
1845       if( strcmp(z,"result-trace")==0 ){
1846         runFlags |= SQL_OUTPUT;
1847       }else
1848       if( strcmp(z,"script")==0 ){
1849         bScript = 1;
1850       }else
1851       if( strcmp(z,"skip")==0 ){
1852         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1853         nSkip = atoi(argv[++i]);
1854       }else
1855       if( strcmp(z,"spinner")==0 ){
1856         bSpinner = 1;
1857       }else
1858       if( strcmp(z,"timer")==0 ){
1859         bTimer = 1;
1860       }else
1861       if( strcmp(z,"sqlid")==0 ){
1862         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1863         onlySqlid = integerValue(argv[++i]);
1864       }else
1865       if( strcmp(z,"timeout")==0 ){
1866         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1867         iTimeout = integerValue(argv[++i]);
1868       }else
1869       if( strcmp(z,"timeout-test")==0 ){
1870         timeoutTest = 1;
1871 #ifndef __unix__
1872         fatalError("timeout is not available on non-unix systems");
1873 #endif
1874       }else
1875       if( strcmp(z,"vdbe-debug")==0 ){
1876         bVdbeDebug = 1;
1877       }else
1878       if( strcmp(z,"verbose")==0 ){
1879         quietFlag = 0;
1880         verboseFlag++;
1881         eVerbosity++;
1882         if( verboseFlag>1 ) runFlags |= SQL_TRACE;
1883       }else
1884       if( (nV = numberOfVChar(z))>=1 ){
1885         quietFlag = 0;
1886         verboseFlag += nV;
1887         eVerbosity += nV;
1888         if( verboseFlag>1 ) runFlags |= SQL_TRACE;
1889       }else
1890       if( strcmp(z,"version")==0 ){
1891         int ii;
1892         const char *zz;
1893         printf("SQLite %s %s\n", sqlite3_libversion(), sqlite3_sourceid());
1894         for(ii=0; (zz = sqlite3_compileoption_get(ii))!=0; ii++){
1895           printf("%s\n", zz);
1896         }
1897         return 0;
1898       }else
1899       if( strcmp(z,"is-dbsql")==0 ){
1900         i++;
1901         for(i++; i<argc; i++){
1902           long nData;
1903           char *aData = readFile(argv[i], &nData);
1904           printf("%d %s\n", isDbSql((unsigned char*)aData,nData), argv[i]);
1905           sqlite3_free(aData);
1906         }
1907         exit(0);
1908       }else
1909       {
1910         fatalError("unknown option: %s", argv[i]);
1911       }
1912     }else{
1913       nSrcDb++;
1914       azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
1915       azSrcDb[nSrcDb-1] = argv[i];
1916     }
1917   }
1918   if( nSrcDb==0 ) fatalError("no source database specified");
1919   if( nSrcDb>1 ){
1920     if( zMsg ){
1921       fatalError("cannot change the description of more than one database");
1922     }
1923     if( zInsSql ){
1924       fatalError("cannot import into more than one database");
1925     }
1926   }
1927 
1928   /* Process each source database separately */
1929   for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
1930     char *zRawData = 0;
1931     long nRawData = 0;
1932     g.zDbFile = azSrcDb[iSrcDb];
1933     rc = sqlite3_open_v2(azSrcDb[iSrcDb], &db,
1934                          openFlags4Data, pDfltVfs->zName);
1935     if( rc==SQLITE_OK ){
1936       rc = sqlite3_exec(db, "SELECT count(*) FROM sqlite_schema", 0, 0, 0);
1937     }
1938     if( rc ){
1939       sqlite3_close(db);
1940       zRawData = readFile(azSrcDb[iSrcDb], &nRawData);
1941       if( zRawData==0 ){
1942         fatalError("input file \"%s\" is not recognized\n", azSrcDb[iSrcDb]);
1943       }
1944       sqlite3_open(":memory:", &db);
1945     }
1946 
1947     /* Print the description, if there is one */
1948     if( infoFlag ){
1949       int n;
1950       zDbName = azSrcDb[iSrcDb];
1951       i = (int)strlen(zDbName) - 1;
1952       while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
1953       zDbName += i;
1954       sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
1955       if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
1956         printf("%s: %s", zDbName, sqlite3_column_text(pStmt,0));
1957       }else{
1958         printf("%s: (empty \"readme\")", zDbName);
1959       }
1960       sqlite3_finalize(pStmt);
1961       sqlite3_prepare_v2(db, "SELECT count(*) FROM db", -1, &pStmt, 0);
1962       if( pStmt
1963        && sqlite3_step(pStmt)==SQLITE_ROW
1964        && (n = sqlite3_column_int(pStmt,0))>0
1965       ){
1966         printf(" - %d DBs", n);
1967       }
1968       sqlite3_finalize(pStmt);
1969       sqlite3_prepare_v2(db, "SELECT count(*) FROM xsql", -1, &pStmt, 0);
1970       if( pStmt
1971        && sqlite3_step(pStmt)==SQLITE_ROW
1972        && (n = sqlite3_column_int(pStmt,0))>0
1973       ){
1974         printf(" - %d scripts", n);
1975       }
1976       sqlite3_finalize(pStmt);
1977       printf("\n");
1978       sqlite3_close(db);
1979       sqlite3_free(zRawData);
1980       continue;
1981     }
1982 
1983     rc = sqlite3_exec(db,
1984        "CREATE TABLE IF NOT EXISTS db(\n"
1985        "  dbid INTEGER PRIMARY KEY, -- database id\n"
1986        "  dbcontent BLOB            -- database disk file image\n"
1987        ");\n"
1988        "CREATE TABLE IF NOT EXISTS xsql(\n"
1989        "  sqlid INTEGER PRIMARY KEY,   -- SQL script id\n"
1990        "  sqltext TEXT                 -- Text of SQL statements to run\n"
1991        ");"
1992        "CREATE TABLE IF NOT EXISTS readme(\n"
1993        "  msg TEXT -- Human-readable description of this file\n"
1994        ");", 0, 0, 0);
1995     if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
1996     if( zMsg ){
1997       char *zSql;
1998       zSql = sqlite3_mprintf(
1999                "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
2000       rc = sqlite3_exec(db, zSql, 0, 0, 0);
2001       sqlite3_free(zSql);
2002       if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
2003     }
2004     if( zRawData ){
2005       zInsSql = "INSERT INTO xsql(sqltext) VALUES(?1)";
2006       rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
2007       if( rc ) fatalError("cannot prepare statement [%s]: %s",
2008                           zInsSql, sqlite3_errmsg(db));
2009       sqlite3_bind_text(pStmt, 1, zRawData, nRawData, SQLITE_STATIC);
2010       sqlite3_step(pStmt);
2011       rc = sqlite3_reset(pStmt);
2012       if( rc ) fatalError("insert failed for %s", argv[i]);
2013       sqlite3_finalize(pStmt);
2014       rebuild_database(db, dbSqlOnly);
2015       zInsSql = 0;
2016       sqlite3_free(zRawData);
2017       zRawData = 0;
2018     }
2019     ossFuzzThisDb = ossFuzz;
2020 
2021     /* If the CONFIG(name,value) table exists, read db-specific settings
2022     ** from that table */
2023     if( sqlite3_table_column_metadata(db,0,"config",0,0,0,0,0,0)==SQLITE_OK ){
2024       rc = sqlite3_prepare_v2(db, "SELECT name, value FROM config",
2025                                   -1, &pStmt, 0);
2026       if( rc ) fatalError("cannot prepare query of CONFIG table: %s",
2027                           sqlite3_errmsg(db));
2028       while( SQLITE_ROW==sqlite3_step(pStmt) ){
2029         const char *zName = (const char *)sqlite3_column_text(pStmt,0);
2030         if( zName==0 ) continue;
2031         if( strcmp(zName, "oss-fuzz")==0 ){
2032           ossFuzzThisDb = sqlite3_column_int(pStmt,1);
2033           if( verboseFlag ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb);
2034         }
2035         if( strcmp(zName, "limit-mem")==0 ){
2036           nMemThisDb = sqlite3_column_int(pStmt,1);
2037           if( verboseFlag ) printf("Config: limit-mem=%d\n", nMemThisDb);
2038         }
2039       }
2040       sqlite3_finalize(pStmt);
2041     }
2042 
2043     if( zInsSql ){
2044       sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
2045                               readfileFunc, 0, 0);
2046       sqlite3_create_function(db, "readtextfile", 1, SQLITE_UTF8, 0,
2047                               readtextfileFunc, 0, 0);
2048       sqlite3_create_function(db, "isdbsql", 1, SQLITE_UTF8, 0,
2049                               isDbSqlFunc, 0, 0);
2050       rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
2051       if( rc ) fatalError("cannot prepare statement [%s]: %s",
2052                           zInsSql, sqlite3_errmsg(db));
2053       rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
2054       if( rc ) fatalError("cannot start a transaction");
2055       for(i=iFirstInsArg; i<argc; i++){
2056         if( strcmp(argv[i],"-")==0 ){
2057           /* A filename of "-" means read multiple filenames from stdin */
2058           char zLine[2000];
2059           while( rc==0 && fgets(zLine,sizeof(zLine),stdin)!=0 ){
2060             size_t kk = strlen(zLine);
2061             while( kk>0 && zLine[kk-1]<=' ' ) kk--;
2062             sqlite3_bind_text(pStmt, 1, zLine, (int)kk, SQLITE_STATIC);
2063             if( verboseFlag ) printf("loading %.*s\n", (int)kk, zLine);
2064             sqlite3_step(pStmt);
2065             rc = sqlite3_reset(pStmt);
2066             if( rc ) fatalError("insert failed for %s", zLine);
2067           }
2068         }else{
2069           sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
2070           if( verboseFlag ) printf("loading %s\n", argv[i]);
2071           sqlite3_step(pStmt);
2072           rc = sqlite3_reset(pStmt);
2073           if( rc ) fatalError("insert failed for %s", argv[i]);
2074         }
2075       }
2076       sqlite3_finalize(pStmt);
2077       rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
2078       if( rc ) fatalError("cannot commit the transaction: %s",
2079                           sqlite3_errmsg(db));
2080       rebuild_database(db, dbSqlOnly);
2081       sqlite3_close(db);
2082       return 0;
2083     }
2084     rc = sqlite3_exec(db, "PRAGMA query_only=1;", 0, 0, 0);
2085     if( rc ) fatalError("cannot set database to query-only");
2086     if( zExpDb!=0 || zExpSql!=0 ){
2087       sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
2088                               writefileFunc, 0, 0);
2089       if( zExpDb!=0 ){
2090         const char *zExDb =
2091           "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent),"
2092           "       dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)"
2093           "  FROM db WHERE ?2<0 OR dbid=?2;";
2094         rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0);
2095         if( rc ) fatalError("cannot prepare statement [%s]: %s",
2096                             zExDb, sqlite3_errmsg(db));
2097         sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb),
2098                             SQLITE_STATIC, SQLITE_UTF8);
2099         sqlite3_bind_int(pStmt, 2, onlyDbid);
2100         while( sqlite3_step(pStmt)==SQLITE_ROW ){
2101           printf("write db-%d (%d bytes) into %s\n",
2102              sqlite3_column_int(pStmt,1),
2103              sqlite3_column_int(pStmt,3),
2104              sqlite3_column_text(pStmt,2));
2105         }
2106         sqlite3_finalize(pStmt);
2107       }
2108       if( zExpSql!=0 ){
2109         const char *zExSql =
2110           "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext),"
2111           "       sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)"
2112           "  FROM xsql WHERE ?2<0 OR sqlid=?2;";
2113         rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0);
2114         if( rc ) fatalError("cannot prepare statement [%s]: %s",
2115                             zExSql, sqlite3_errmsg(db));
2116         sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql),
2117                             SQLITE_STATIC, SQLITE_UTF8);
2118         sqlite3_bind_int(pStmt, 2, onlySqlid);
2119         while( sqlite3_step(pStmt)==SQLITE_ROW ){
2120           printf("write sql-%d (%d bytes) into %s\n",
2121              sqlite3_column_int(pStmt,1),
2122              sqlite3_column_int(pStmt,3),
2123              sqlite3_column_text(pStmt,2));
2124         }
2125         sqlite3_finalize(pStmt);
2126       }
2127       sqlite3_close(db);
2128       return 0;
2129     }
2130 
2131     /* Load all SQL script content and all initial database images from the
2132     ** source db
2133     */
2134     blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
2135                            &g.nSql, &g.pFirstSql);
2136     if( g.nSql==0 ) fatalError("need at least one SQL script");
2137     blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
2138                        &g.nDb, &g.pFirstDb);
2139     if( g.nDb==0 ){
2140       g.pFirstDb = safe_realloc(0, sizeof(Blob));
2141       memset(g.pFirstDb, 0, sizeof(Blob));
2142       g.pFirstDb->id = 1;
2143       g.pFirstDb->seq = 0;
2144       g.nDb = 1;
2145       sqlFuzz = 1;
2146     }
2147 
2148     /* Print the description, if there is one */
2149     if( !quietFlag && !bScript ){
2150       zDbName = azSrcDb[iSrcDb];
2151       i = (int)strlen(zDbName) - 1;
2152       while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
2153       zDbName += i;
2154       sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
2155       if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
2156         printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
2157       }
2158       sqlite3_finalize(pStmt);
2159     }
2160 
2161     /* Rebuild the database, if requested */
2162     if( rebuildFlag ){
2163       if( !quietFlag ){
2164         printf("%s: rebuilding... ", zDbName);
2165         fflush(stdout);
2166       }
2167       rebuild_database(db, 0);
2168       if( !quietFlag ) printf("done\n");
2169     }
2170 
2171     /* Close the source database.  Verify that no SQLite memory allocations are
2172     ** outstanding.
2173     */
2174     sqlite3_close(db);
2175     if( sqlite3_memory_used()>0 ){
2176       fatalError("SQLite has memory in use before the start of testing");
2177     }
2178 
2179     /* Limit available memory, if requested */
2180     sqlite3_shutdown();
2181 
2182     if( nMemThisDb>0 && nMem==0 ){
2183       if( !nativeMalloc ){
2184         pHeap = realloc(pHeap, nMemThisDb);
2185         if( pHeap==0 ){
2186           fatalError("failed to allocate %d bytes of heap memory", nMem);
2187         }
2188         sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMemThisDb, 128);
2189       }else{
2190         sqlite3_hard_heap_limit64((sqlite3_int64)nMemThisDb);
2191       }
2192     }else{
2193       sqlite3_hard_heap_limit64(0);
2194     }
2195 
2196     /* Disable lookaside with the --native-malloc option */
2197     if( nativeMalloc ){
2198       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
2199     }
2200 
2201     /* Reset the in-memory virtual filesystem */
2202     formatVfs();
2203 
2204     /* Run a test using each SQL script against each database.
2205     */
2206     if( !verboseFlag && !quietFlag && !bSpinner && !bScript ){
2207       printf("%s:", zDbName);
2208     }
2209     for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
2210       tmStart = timeOfDay();
2211       if( isDbSql(pSql->a, pSql->sz) ){
2212         sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d",pSql->id);
2213         if( bScript ){
2214           /* No progress output */
2215         }else if( bSpinner ){
2216           int nTotal =g.nSql;
2217           int idx = pSql->seq;
2218           printf("\r%s: %d/%d   ", zDbName, idx, nTotal);
2219           fflush(stdout);
2220         }else if( verboseFlag ){
2221           printf("%s\n", g.zTestName);
2222           fflush(stdout);
2223         }else if( !quietFlag ){
2224           static int prevAmt = -1;
2225           int idx = pSql->seq;
2226           int amt = idx*10/(g.nSql);
2227           if( amt!=prevAmt ){
2228             printf(" %d%%", amt*10);
2229             fflush(stdout);
2230             prevAmt = amt;
2231           }
2232         }
2233         if( nSkip>0 ){
2234           nSkip--;
2235         }else{
2236           runCombinedDbSqlInput(pSql->a, pSql->sz, iTimeout, bScript, pSql->id);
2237         }
2238         nTest++;
2239         if( bTimer && !bScript ){
2240           sqlite3_int64 tmEnd = timeOfDay();
2241           printf("%lld %s\n", tmEnd - tmStart, g.zTestName);
2242         }
2243         g.zTestName[0] = 0;
2244         disableOom();
2245         continue;
2246       }
2247       for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
2248         int openFlags;
2249         const char *zVfs = "inmem";
2250         sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
2251                          pSql->id, pDb->id);
2252         if( bScript ){
2253           /* No progress output */
2254         }else if( bSpinner ){
2255           int nTotal = g.nDb*g.nSql;
2256           int idx = pSql->seq*g.nDb + pDb->id - 1;
2257           printf("\r%s: %d/%d   ", zDbName, idx, nTotal);
2258           fflush(stdout);
2259         }else if( verboseFlag ){
2260           printf("%s\n", g.zTestName);
2261           fflush(stdout);
2262         }else if( !quietFlag ){
2263           static int prevAmt = -1;
2264           int idx = pSql->seq*g.nDb + pDb->id - 1;
2265           int amt = idx*10/(g.nDb*g.nSql);
2266           if( amt!=prevAmt ){
2267             printf(" %d%%", amt*10);
2268             fflush(stdout);
2269             prevAmt = amt;
2270           }
2271         }
2272         if( nSkip>0 ){
2273           nSkip--;
2274           continue;
2275         }
2276         if( bScript ){
2277           char zName[100];
2278           sqlite3_snprintf(sizeof(zName), zName, "db%06d.db",
2279                            pDb->id>1 ? pDb->id : pSql->id);
2280           renderDbSqlForCLI(stdout, zName,
2281              pDb->a, pDb->sz, pSql->a, pSql->sz);
2282           continue;
2283         }
2284         createVFile("main.db", pDb->sz, pDb->a);
2285         sqlite3_randomness(0,0);
2286         if( ossFuzzThisDb ){
2287 #ifndef SQLITE_OSS_FUZZ
2288           fatalError("--oss-fuzz not supported: recompile"
2289                      " with -DSQLITE_OSS_FUZZ");
2290 #else
2291           extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t);
2292           LLVMFuzzerTestOneInput((const uint8_t*)pSql->a, (size_t)pSql->sz);
2293 #endif
2294         }else{
2295           openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
2296           if( nativeFlag && pDb->sz==0 ){
2297             openFlags |= SQLITE_OPEN_MEMORY;
2298             zVfs = 0;
2299           }
2300           rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
2301           if( rc ) fatalError("cannot open inmem database");
2302           sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 100000000);
2303           sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 50);
2304           if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
2305           setAlarm((iTimeout+999)/1000);
2306           /* Enable test functions */
2307           sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, db);
2308 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2309           if( sqlFuzz || vdbeLimitFlag ){
2310             sqlite3_progress_handler(db, 100000, progressHandler,
2311                                      &vdbeLimitFlag);
2312           }
2313 #endif
2314 #ifdef SQLITE_TESTCTRL_PRNG_SEED
2315           sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, db);
2316 #endif
2317           if( bVdbeDebug ){
2318             sqlite3_exec(db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
2319           }
2320           do{
2321             runSql(db, (char*)pSql->a, runFlags);
2322           }while( timeoutTest );
2323           setAlarm(0);
2324           sqlite3_exec(db, "PRAGMA temp_store_directory=''", 0, 0, 0);
2325           sqlite3_close(db);
2326         }
2327         if( sqlite3_memory_used()>0 ){
2328            fatalError("memory leak: %lld bytes outstanding",
2329                       sqlite3_memory_used());
2330         }
2331         reformatVfs();
2332         nTest++;
2333         if( bTimer ){
2334           sqlite3_int64 tmEnd = timeOfDay();
2335           printf("%lld %s\n", tmEnd - tmStart, g.zTestName);
2336         }
2337         g.zTestName[0] = 0;
2338 
2339         /* Simulate an error if the TEST_FAILURE environment variable is "5".
2340         ** This is used to verify that automated test script really do spot
2341         ** errors that occur in this test program.
2342         */
2343         if( zFailCode ){
2344           if( zFailCode[0]=='5' && zFailCode[1]==0 ){
2345             fatalError("simulated failure");
2346           }else if( zFailCode[0]!=0 ){
2347             /* If TEST_FAILURE is something other than 5, just exit the test
2348             ** early */
2349             printf("\nExit early due to TEST_FAILURE being set\n");
2350             iSrcDb = nSrcDb-1;
2351             goto sourcedb_cleanup;
2352           }
2353         }
2354       }
2355     }
2356     if( bScript ){
2357       /* No progress output */
2358     }else if( bSpinner ){
2359       int nTotal = g.nDb*g.nSql;
2360       printf("\r%s: %d/%d   \n", zDbName, nTotal, nTotal);
2361     }else if( !quietFlag && !verboseFlag ){
2362       printf(" 100%% - %d tests\n", g.nDb*g.nSql);
2363     }
2364 
2365     /* Clean up at the end of processing a single source database
2366     */
2367   sourcedb_cleanup:
2368     blobListFree(g.pFirstSql);
2369     blobListFree(g.pFirstDb);
2370     reformatVfs();
2371 
2372   } /* End loop over all source databases */
2373 
2374   if( !quietFlag && !bScript ){
2375     sqlite3_int64 iElapse = timeOfDay() - iBegin;
2376     if( g.nInvariant ){
2377       printf("fuzzcheck: %u query invariants checked\n", g.nInvariant);
2378     }
2379     printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
2380            "SQLite %s %s\n",
2381            nTest, (int)(iElapse/1000), (int)(iElapse%1000),
2382            sqlite3_libversion(), sqlite3_sourceid());
2383   }
2384   free(azSrcDb);
2385   free(pHeap);
2386   return 0;
2387 }
2388