xref: /sqlite-3.40.0/test/fuzzcheck.c (revision 9e5ecdc1)
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:
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 #ifdef SQLITE_OSS_FUZZ
98 # include <stddef.h>
99 # if !defined(_MSC_VER)
100 #  include <stdint.h>
101 # endif
102 #endif
103 
104 #if defined(_MSC_VER)
105 typedef unsigned char uint8_t;
106 #endif
107 
108 /*
109 ** Files in the virtual file system.
110 */
111 typedef struct VFile VFile;
112 struct VFile {
113   char *zFilename;        /* Filename.  NULL for delete-on-close. From malloc() */
114   int sz;                 /* Size of the file in bytes */
115   int nRef;               /* Number of references to this file */
116   unsigned char *a;       /* Content of the file.  From malloc() */
117 };
118 typedef struct VHandle VHandle;
119 struct VHandle {
120   sqlite3_file base;      /* Base class.  Must be first */
121   VFile *pVFile;          /* The underlying file */
122 };
123 
124 /*
125 ** The value of a database file template, or of an SQL script
126 */
127 typedef struct Blob Blob;
128 struct Blob {
129   Blob *pNext;            /* Next in a list */
130   int id;                 /* Id of this Blob */
131   int seq;                /* Sequence number */
132   int sz;                 /* Size of this Blob in bytes */
133   unsigned char a[1];     /* Blob content.  Extra space allocated as needed. */
134 };
135 
136 /*
137 ** Maximum number of files in the in-memory virtual filesystem.
138 */
139 #define MX_FILE  10
140 
141 /*
142 ** Maximum allowed file size
143 */
144 #define MX_FILE_SZ 10000000
145 
146 /*
147 ** All global variables are gathered into the "g" singleton.
148 */
149 static struct GlobalVars {
150   const char *zArgv0;              /* Name of program */
151   const char *zDbFile;             /* Name of database file */
152   VFile aFile[MX_FILE];            /* The virtual filesystem */
153   int nDb;                         /* Number of template databases */
154   Blob *pFirstDb;                  /* Content of first template database */
155   int nSql;                        /* Number of SQL scripts */
156   Blob *pFirstSql;                 /* First SQL script */
157   unsigned int uRandom;            /* Seed for the SQLite PRNG */
158   char zTestName[100];             /* Name of current test */
159 } g;
160 
161 /*
162 ** Print an error message and quit.
163 */
164 static void fatalError(const char *zFormat, ...){
165   va_list ap;
166   fprintf(stderr, "%s", g.zArgv0);
167   if( g.zDbFile ) fprintf(stderr, " %s", g.zDbFile);
168   if( g.zTestName[0] ) fprintf(stderr, " (%s)", g.zTestName);
169   fprintf(stderr, ": ");
170   va_start(ap, zFormat);
171   vfprintf(stderr, zFormat, ap);
172   va_end(ap);
173   fprintf(stderr, "\n");
174   exit(1);
175 }
176 
177 /*
178 ** signal handler
179 */
180 #ifdef __unix__
181 static void signalHandler(int signum){
182   const char *zSig;
183   if( signum==SIGABRT ){
184     zSig = "abort";
185   }else if( signum==SIGALRM ){
186     zSig = "timeout";
187   }else if( signum==SIGSEGV ){
188     zSig = "segfault";
189   }else{
190     zSig = "signal";
191   }
192   fatalError(zSig);
193 }
194 #endif
195 
196 /*
197 ** Set the an alarm to go off after N seconds.  Disable the alarm
198 ** if N==0
199 */
200 static void setAlarm(int N){
201 #ifdef __unix__
202   alarm(N);
203 #else
204   (void)N;
205 #endif
206 }
207 
208 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
209 /*
210 ** This an SQL progress handler.  After an SQL statement has run for
211 ** many steps, we want to interrupt it.  This guards against infinite
212 ** loops from recursive common table expressions.
213 **
214 ** *pVdbeLimitFlag is true if the --limit-vdbe command-line option is used.
215 ** In that case, hitting the progress handler is a fatal error.
216 */
217 static int progressHandler(void *pVdbeLimitFlag){
218   if( *(int*)pVdbeLimitFlag ) fatalError("too many VDBE cycles");
219   return 1;
220 }
221 #endif
222 
223 /*
224 ** Reallocate memory.  Show and error and quit if unable.
225 */
226 static void *safe_realloc(void *pOld, int szNew){
227   void *pNew = realloc(pOld, szNew<=0 ? 1 : szNew);
228   if( pNew==0 ) fatalError("unable to realloc for %d bytes", szNew);
229   return pNew;
230 }
231 
232 /*
233 ** Initialize the virtual file system.
234 */
235 static void formatVfs(void){
236   int i;
237   for(i=0; i<MX_FILE; i++){
238     g.aFile[i].sz = -1;
239     g.aFile[i].zFilename = 0;
240     g.aFile[i].a = 0;
241     g.aFile[i].nRef = 0;
242   }
243 }
244 
245 
246 /*
247 ** Erase all information in the virtual file system.
248 */
249 static void reformatVfs(void){
250   int i;
251   for(i=0; i<MX_FILE; i++){
252     if( g.aFile[i].sz<0 ) continue;
253     if( g.aFile[i].zFilename ){
254       free(g.aFile[i].zFilename);
255       g.aFile[i].zFilename = 0;
256     }
257     if( g.aFile[i].nRef>0 ){
258       fatalError("file %d still open.  nRef=%d", i, g.aFile[i].nRef);
259     }
260     g.aFile[i].sz = -1;
261     free(g.aFile[i].a);
262     g.aFile[i].a = 0;
263     g.aFile[i].nRef = 0;
264   }
265 }
266 
267 /*
268 ** Find a VFile by name
269 */
270 static VFile *findVFile(const char *zName){
271   int i;
272   if( zName==0 ) return 0;
273   for(i=0; i<MX_FILE; i++){
274     if( g.aFile[i].zFilename==0 ) continue;
275     if( strcmp(g.aFile[i].zFilename, zName)==0 ) return &g.aFile[i];
276   }
277   return 0;
278 }
279 
280 /*
281 ** Find a VFile by name.  Create it if it does not already exist and
282 ** initialize it to the size and content given.
283 **
284 ** Return NULL only if the filesystem is full.
285 */
286 static VFile *createVFile(const char *zName, int sz, unsigned char *pData){
287   VFile *pNew = findVFile(zName);
288   int i;
289   if( pNew ) return pNew;
290   for(i=0; i<MX_FILE && g.aFile[i].sz>=0; i++){}
291   if( i>=MX_FILE ) return 0;
292   pNew = &g.aFile[i];
293   if( zName ){
294     int nName = (int)strlen(zName)+1;
295     pNew->zFilename = safe_realloc(0, nName);
296     memcpy(pNew->zFilename, zName, nName);
297   }else{
298     pNew->zFilename = 0;
299   }
300   pNew->nRef = 0;
301   pNew->sz = sz;
302   pNew->a = safe_realloc(0, sz);
303   if( sz>0 ) memcpy(pNew->a, pData, sz);
304   return pNew;
305 }
306 
307 
308 /*
309 ** Implementation of the "readfile(X)" SQL function.  The entire content
310 ** of the file named X is read and returned as a BLOB.  NULL is returned
311 ** if the file does not exist or is unreadable.
312 */
313 static void readfileFunc(
314   sqlite3_context *context,
315   int argc,
316   sqlite3_value **argv
317 ){
318   const char *zName;
319   FILE *in;
320   long nIn;
321   void *pBuf;
322 
323   zName = (const char*)sqlite3_value_text(argv[0]);
324   if( zName==0 ) return;
325   in = fopen(zName, "rb");
326   if( in==0 ) return;
327   fseek(in, 0, SEEK_END);
328   nIn = ftell(in);
329   rewind(in);
330   pBuf = sqlite3_malloc64( nIn );
331   if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
332     sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
333   }else{
334     sqlite3_free(pBuf);
335   }
336   fclose(in);
337 }
338 
339 /*
340 ** Implementation of the "readtextfile(X)" SQL function.  The text content
341 ** of the file named X through the end of the file or to the first \000
342 ** character, whichever comes first, is read and returned as TEXT.  NULL
343 ** is returned if the file does not exist or is unreadable.
344 */
345 static void readtextfileFunc(
346   sqlite3_context *context,
347   int argc,
348   sqlite3_value **argv
349 ){
350   const char *zName;
351   FILE *in;
352   long nIn;
353   char *pBuf;
354 
355   zName = (const char*)sqlite3_value_text(argv[0]);
356   if( zName==0 ) return;
357   in = fopen(zName, "rb");
358   if( in==0 ) return;
359   fseek(in, 0, SEEK_END);
360   nIn = ftell(in);
361   rewind(in);
362   pBuf = sqlite3_malloc64( nIn+1 );
363   if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
364     pBuf[nIn] = 0;
365     sqlite3_result_text(context, pBuf, -1, sqlite3_free);
366   }else{
367     sqlite3_free(pBuf);
368   }
369   fclose(in);
370 }
371 
372 /*
373 ** Implementation of the "writefile(X,Y)" SQL function.  The argument Y
374 ** is written into file X.  The number of bytes written is returned.  Or
375 ** NULL is returned if something goes wrong, such as being unable to open
376 ** file X for writing.
377 */
378 static void writefileFunc(
379   sqlite3_context *context,
380   int argc,
381   sqlite3_value **argv
382 ){
383   FILE *out;
384   const char *z;
385   sqlite3_int64 rc;
386   const char *zFile;
387 
388   (void)argc;
389   zFile = (const char*)sqlite3_value_text(argv[0]);
390   if( zFile==0 ) return;
391   out = fopen(zFile, "wb");
392   if( out==0 ) return;
393   z = (const char*)sqlite3_value_blob(argv[1]);
394   if( z==0 ){
395     rc = 0;
396   }else{
397     rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
398   }
399   fclose(out);
400   sqlite3_result_int64(context, rc);
401 }
402 
403 
404 /*
405 ** Load a list of Blob objects from the database
406 */
407 static void blobListLoadFromDb(
408   sqlite3 *db,             /* Read from this database */
409   const char *zSql,        /* Query used to extract the blobs */
410   int onlyId,              /* Only load where id is this value */
411   int *pN,                 /* OUT: Write number of blobs loaded here */
412   Blob **ppList            /* OUT: Write the head of the blob list here */
413 ){
414   Blob head;
415   Blob *p;
416   sqlite3_stmt *pStmt;
417   int n = 0;
418   int rc;
419   char *z2;
420 
421   if( onlyId>0 ){
422     z2 = sqlite3_mprintf("%s WHERE rowid=%d", zSql, onlyId);
423   }else{
424     z2 = sqlite3_mprintf("%s", zSql);
425   }
426   rc = sqlite3_prepare_v2(db, z2, -1, &pStmt, 0);
427   sqlite3_free(z2);
428   if( rc ) fatalError("%s", sqlite3_errmsg(db));
429   head.pNext = 0;
430   p = &head;
431   while( SQLITE_ROW==sqlite3_step(pStmt) ){
432     int sz = sqlite3_column_bytes(pStmt, 1);
433     Blob *pNew = safe_realloc(0, sizeof(*pNew)+sz );
434     pNew->id = sqlite3_column_int(pStmt, 0);
435     pNew->sz = sz;
436     pNew->seq = n++;
437     pNew->pNext = 0;
438     memcpy(pNew->a, sqlite3_column_blob(pStmt,1), sz);
439     pNew->a[sz] = 0;
440     p->pNext = pNew;
441     p = pNew;
442   }
443   sqlite3_finalize(pStmt);
444   *pN = n;
445   *ppList = head.pNext;
446 }
447 
448 /*
449 ** Free a list of Blob objects
450 */
451 static void blobListFree(Blob *p){
452   Blob *pNext;
453   while( p ){
454     pNext = p->pNext;
455     free(p);
456     p = pNext;
457   }
458 }
459 
460 /* Return the current wall-clock time */
461 static sqlite3_int64 timeOfDay(void){
462   static sqlite3_vfs *clockVfs = 0;
463   sqlite3_int64 t;
464   if( clockVfs==0 ){
465     clockVfs = sqlite3_vfs_find(0);
466     if( clockVfs==0 ) return 0;
467   }
468   if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
469     clockVfs->xCurrentTimeInt64(clockVfs, &t);
470   }else{
471     double r;
472     clockVfs->xCurrentTime(clockVfs, &r);
473     t = (sqlite3_int64)(r*86400000.0);
474   }
475   return t;
476 }
477 
478 /***************************************************************************
479 ** Code to process combined database+SQL scripts generated by the
480 ** dbsqlfuzz fuzzer.
481 */
482 
483 /* An instance of the following object is passed by pointer as the
484 ** client data to various callbacks.
485 */
486 typedef struct FuzzCtx {
487   sqlite3 *db;               /* The database connection */
488   sqlite3_int64 iCutoffTime; /* Stop processing at this time. */
489   sqlite3_int64 iLastCb;     /* Time recorded for previous progress callback */
490   sqlite3_int64 mxInterval;  /* Longest interval between two progress calls */
491   unsigned nCb;              /* Number of progress callbacks */
492   unsigned mxCb;             /* Maximum number of progress callbacks allowed */
493   unsigned execCnt;          /* Number of calls to the sqlite3_exec callback */
494   int timeoutHit;            /* True when reaching a timeout */
495 } FuzzCtx;
496 
497 /* Verbosity level for the dbsqlfuzz test runner */
498 static int eVerbosity = 0;
499 
500 /* True to activate PRAGMA vdbe_debug=on */
501 static int bVdbeDebug = 0;
502 
503 /* Timeout for each fuzzing attempt, in milliseconds */
504 static int giTimeout = 10000;   /* Defaults to 10 seconds */
505 
506 /* Maximum number of progress handler callbacks */
507 static unsigned int mxProgressCb = 2000;
508 
509 /* Maximum string length in SQLite */
510 static int lengthLimit = 1000000;
511 
512 /* Maximum expression depth */
513 static int depthLimit = 500;
514 
515 /* Limit on the amount of heap memory that can be used */
516 static sqlite3_int64 heapLimit = 100000000;
517 
518 /* Maximum byte-code program length in SQLite */
519 static int vdbeOpLimit = 25000;
520 
521 /* Maximum size of the in-memory database */
522 static sqlite3_int64 maxDbSize = 104857600;
523 
524 /*
525 ** Translate a single byte of Hex into an integer.
526 ** This routine only works if h really is a valid hexadecimal
527 ** character:  0..9a..fA..F
528 */
529 static unsigned char hexToInt(unsigned int h){
530 #ifdef SQLITE_EBCDIC
531   h += 9*(1&~(h>>4));   /* EBCDIC */
532 #else
533   h += 9*(1&(h>>6));    /* ASCII */
534 #endif
535   return h & 0xf;
536 }
537 
538 /*
539 ** The first character of buffer zIn[0..nIn-1] is a '['.  This routine
540 ** checked to see if the buffer holds "[NNNN]" or "[+NNNN]" and if it
541 ** does it makes corresponding changes to the *pK value and *pI value
542 ** and returns true.  If the input buffer does not match the patterns,
543 ** no changes are made to either *pK or *pI and this routine returns false.
544 */
545 static int isOffset(
546   const unsigned char *zIn,  /* Text input */
547   int nIn,                   /* Bytes of input */
548   unsigned int *pK,          /* half-byte cursor to adjust */
549   unsigned int *pI           /* Input index to adjust */
550 ){
551   int i;
552   unsigned int k = 0;
553   unsigned char c;
554   for(i=1; i<nIn && (c = zIn[i])!=']'; i++){
555     if( !isxdigit(c) ) return 0;
556     k = k*16 + hexToInt(c);
557   }
558   if( i==nIn ) return 0;
559   *pK = 2*k;
560   *pI += i;
561   return 1;
562 }
563 
564 /*
565 ** Decode the text starting at zIn into a binary database file.
566 ** The maximum length of zIn is nIn bytes.  Compute the binary database
567 ** file contain in space obtained from sqlite3_malloc().
568 **
569 ** Return the number of bytes of zIn consumed.  Or return -1 if there
570 ** is an error.  One potential error is that the recipe specifies a
571 ** database file larger than MX_FILE_SZ bytes.
572 **
573 ** Abort on an OOM.
574 */
575 static int decodeDatabase(
576   const unsigned char *zIn,      /* Input text to be decoded */
577   int nIn,                       /* Bytes of input text */
578   unsigned char **paDecode,      /* OUT: decoded database file */
579   int *pnDecode                  /* OUT: Size of decoded database */
580 ){
581   unsigned char *a;              /* Database under construction */
582   int mx = 0;                    /* Current size of the database */
583   sqlite3_uint64 nAlloc = 4096;  /* Space allocated in a[] */
584   unsigned int i;                /* Next byte of zIn[] to read */
585   unsigned int j;                /* Temporary integer */
586   unsigned int k;                /* half-byte cursor index for output */
587   unsigned int n;                /* Number of bytes of input */
588   unsigned char b = 0;
589   if( nIn<4 ) return -1;
590   n = (unsigned int)nIn;
591   a = sqlite3_malloc64( nAlloc );
592   if( a==0 ){
593     fprintf(stderr, "Out of memory!\n");
594     exit(1);
595   }
596   memset(a, 0, (size_t)nAlloc);
597   for(i=k=0; i<n; i++){
598     unsigned char c = (unsigned char)zIn[i];
599     if( isxdigit(c) ){
600       k++;
601       if( k & 1 ){
602         b = hexToInt(c)*16;
603       }else{
604         b += hexToInt(c);
605         j = k/2 - 1;
606         if( j>=nAlloc ){
607           sqlite3_uint64 newSize;
608           if( nAlloc==MX_FILE_SZ || j>=MX_FILE_SZ ){
609             if( eVerbosity ){
610               fprintf(stderr, "Input database too big: max %d bytes\n",
611                       MX_FILE_SZ);
612             }
613             sqlite3_free(a);
614             return -1;
615           }
616           newSize = nAlloc*2;
617           if( newSize<=j ){
618             newSize = (j+4096)&~4095;
619           }
620           if( newSize>MX_FILE_SZ ){
621             if( j>=MX_FILE_SZ ){
622               sqlite3_free(a);
623               return -1;
624             }
625             newSize = MX_FILE_SZ;
626           }
627           a = sqlite3_realloc64( a, newSize );
628           if( a==0 ){
629             fprintf(stderr, "Out of memory!\n");
630             exit(1);
631           }
632           assert( newSize > nAlloc );
633           memset(a+nAlloc, 0, (size_t)(newSize - nAlloc));
634           nAlloc = newSize;
635         }
636         if( j>=(unsigned)mx ){
637           mx = (j + 4095)&~4095;
638           if( mx>MX_FILE_SZ ) mx = MX_FILE_SZ;
639         }
640         assert( j<nAlloc );
641         a[j] = b;
642       }
643     }else if( zIn[i]=='[' && i<n-3 && isOffset(zIn+i, nIn-i, &k, &i) ){
644       continue;
645    }else if( zIn[i]=='\n' && i<n-4 && memcmp(zIn+i,"\n--\n",4)==0 ){
646       i += 4;
647       break;
648     }
649   }
650   *pnDecode = mx;
651   *paDecode = a;
652   return i;
653 }
654 
655 /*
656 ** Progress handler callback.
657 **
658 ** The argument is the cutoff-time after which all processing should
659 ** stop.  So return non-zero if the cut-off time is exceeded.
660 */
661 static int progress_handler(void *pClientData) {
662   FuzzCtx *p = (FuzzCtx*)pClientData;
663   sqlite3_int64 iNow = timeOfDay();
664   int rc = iNow>=p->iCutoffTime;
665   sqlite3_int64 iDiff = iNow - p->iLastCb;
666   if( iDiff > p->mxInterval ) p->mxInterval = iDiff;
667   p->nCb++;
668   if( rc==0 && p->mxCb>0 && p->mxCb<=p->nCb ) rc = 1;
669   if( rc && !p->timeoutHit && eVerbosity>=2 ){
670     printf("Timeout on progress callback %d\n", p->nCb);
671     fflush(stdout);
672     p->timeoutHit = 1;
673   }
674   return rc;
675 }
676 
677 /*
678 ** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and
679 ** "PRAGMA parser_trace" since they can dramatically increase the
680 ** amount of output without actually testing anything useful.
681 **
682 ** Also block ATTACH and DETACH
683 */
684 static int block_troublesome_sql(
685   void *Notused,
686   int eCode,
687   const char *zArg1,
688   const char *zArg2,
689   const char *zArg3,
690   const char *zArg4
691 ){
692   (void)Notused;
693   (void)zArg2;
694   (void)zArg3;
695   (void)zArg4;
696   if( eCode==SQLITE_PRAGMA ){
697     if( sqlite3_strnicmp("vdbe_", zArg1, 5)==0
698      || sqlite3_stricmp("parser_trace", zArg1)==0
699      || sqlite3_stricmp("temp_store_directory", zArg1)==0
700     ){
701       return SQLITE_DENY;
702     }
703   }else if( (eCode==SQLITE_ATTACH || eCode==SQLITE_DETACH)
704             && zArg1 && zArg1[0] ){
705     return SQLITE_DENY;
706   }
707   return SQLITE_OK;
708 }
709 
710 /*
711 ** Run the SQL text
712 */
713 static int runDbSql(sqlite3 *db, const char *zSql){
714   int rc;
715   sqlite3_stmt *pStmt;
716   while( isspace(zSql[0]&0x7f) ) zSql++;
717   if( zSql[0]==0 ) return SQLITE_OK;
718   if( eVerbosity>=4 ){
719     printf("RUNNING-SQL: [%s]\n", zSql);
720     fflush(stdout);
721   }
722   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
723   if( rc==SQLITE_OK ){
724     while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
725       if( eVerbosity>=5 ){
726         int j;
727         for(j=0; j<sqlite3_column_count(pStmt); j++){
728           if( j ) printf(",");
729           switch( sqlite3_column_type(pStmt, j) ){
730             case SQLITE_NULL: {
731               printf("NULL");
732               break;
733             }
734             case SQLITE_INTEGER:
735             case SQLITE_FLOAT: {
736               printf("%s", sqlite3_column_text(pStmt, j));
737               break;
738             }
739             case SQLITE_BLOB: {
740               int n = sqlite3_column_bytes(pStmt, j);
741               int i;
742               const unsigned char *a;
743               a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
744               printf("x'");
745               for(i=0; i<n; i++){
746                 printf("%02x", a[i]);
747               }
748               printf("'");
749               break;
750             }
751             case SQLITE_TEXT: {
752               int n = sqlite3_column_bytes(pStmt, j);
753               int i;
754               const unsigned char *a;
755               a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
756               printf("'");
757               for(i=0; i<n; i++){
758                 if( a[i]=='\'' ){
759                   printf("''");
760                 }else{
761                   putchar(a[i]);
762                 }
763               }
764               printf("'");
765               break;
766             }
767           } /* End switch() */
768         } /* End for() */
769         printf("\n");
770         fflush(stdout);
771       } /* End if( eVerbosity>=5 ) */
772     } /* End while( SQLITE_ROW */
773     if( rc!=SQLITE_DONE && eVerbosity>=4 ){
774       printf("SQL-ERROR: (%d) %s\n", rc, sqlite3_errmsg(db));
775       fflush(stdout);
776     }
777   }else if( eVerbosity>=4 ){
778     printf("SQL-ERROR (%d): %s\n", rc, sqlite3_errmsg(db));
779     fflush(stdout);
780   } /* End if( SQLITE_OK ) */
781   return sqlite3_finalize(pStmt);
782 }
783 
784 /* Invoke this routine to run a single test case */
785 int runCombinedDbSqlInput(const uint8_t *aData, size_t nByte){
786   int rc;                    /* SQLite API return value */
787   int iSql;                  /* Index in aData[] of start of SQL */
788   unsigned char *aDb = 0;    /* Decoded database content */
789   int nDb = 0;               /* Size of the decoded database */
790   int i;                     /* Loop counter */
791   int j;                     /* Start of current SQL statement */
792   char *zSql = 0;            /* SQL text to run */
793   int nSql;                  /* Bytes of SQL text */
794   FuzzCtx cx;                /* Fuzzing context */
795 
796   if( nByte<10 ) return 0;
797   if( sqlite3_initialize() ) return 0;
798   if( sqlite3_memory_used()!=0 ){
799     int nAlloc = 0;
800     int nNotUsed = 0;
801     sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
802     fprintf(stderr,"Memory leak in mutator: %lld bytes in %d allocations\n",
803             sqlite3_memory_used(), nAlloc);
804     exit(1);
805   }
806   memset(&cx, 0, sizeof(cx));
807   iSql = decodeDatabase((unsigned char*)aData, (int)nByte, &aDb, &nDb);
808   if( iSql<0 ) return 0;
809   nSql = (int)(nByte - iSql);
810   if( eVerbosity>=3 ){
811     printf(
812       "****** %d-byte input, %d-byte database, %d-byte script "
813       "******\n", (int)nByte, nDb, nSql);
814     fflush(stdout);
815   }
816   rc = sqlite3_open(0, &cx.db);
817   if( rc ) return 1;
818   if( bVdbeDebug ){
819     sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
820   }
821 
822   /* Invoke the progress handler frequently to check to see if we
823   ** are taking too long.  The progress handler will return true
824   ** (which will block further processing) if more than giTimeout seconds have
825   ** elapsed since the start of the test.
826   */
827   cx.iLastCb = timeOfDay();
828   cx.iCutoffTime = cx.iLastCb + giTimeout;  /* Now + giTimeout seconds */
829   cx.mxCb = mxProgressCb;
830 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
831   sqlite3_progress_handler(cx.db, 10, progress_handler, (void*)&cx);
832 #endif
833 
834   /* Set a limit on the maximum size of a prepared statement, and the
835   ** maximum length of a string or blob */
836   if( vdbeOpLimit>0 ){
837     sqlite3_limit(cx.db, SQLITE_LIMIT_VDBE_OP, vdbeOpLimit);
838   }
839   if( lengthLimit>0 ){
840     sqlite3_limit(cx.db, SQLITE_LIMIT_LENGTH, lengthLimit);
841   }
842   if( depthLimit>0 ){
843     sqlite3_limit(cx.db, SQLITE_LIMIT_EXPR_DEPTH, depthLimit);
844   }
845   sqlite3_hard_heap_limit64(heapLimit);
846 
847   if( nDb>=20 && aDb[18]==2 && aDb[19]==2 ){
848     aDb[18] = aDb[19] = 1;
849   }
850   rc = sqlite3_deserialize(cx.db, "main", aDb, nDb, nDb,
851           SQLITE_DESERIALIZE_RESIZEABLE |
852           SQLITE_DESERIALIZE_FREEONCLOSE);
853   if( rc ){
854     fprintf(stderr, "sqlite3_deserialize() failed with %d\n", rc);
855     goto testrun_finished;
856   }
857   if( maxDbSize>0 ){
858     sqlite3_int64 x = maxDbSize;
859     sqlite3_file_control(cx.db, "main", SQLITE_FCNTL_SIZE_LIMIT, &x);
860   }
861 
862   /* For high debugging levels, turn on debug mode */
863   if( eVerbosity>=5 ){
864     sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON;", 0, 0, 0);
865   }
866 
867   /* Block debug pragmas and ATTACH/DETACH.  But wait until after
868   ** deserialize to do this because deserialize depends on ATTACH */
869   sqlite3_set_authorizer(cx.db, block_troublesome_sql, 0);
870 
871   /* Consistent PRNG seed */
872   sqlite3_randomness(0,0);
873 
874   zSql = sqlite3_malloc( nSql + 1 );
875   if( zSql==0 ){
876     fprintf(stderr, "Out of memory!\n");
877   }else{
878     memcpy(zSql, aData+iSql, nSql);
879     zSql[nSql] = 0;
880     for(i=j=0; zSql[i]; i++){
881       if( zSql[i]==';' ){
882         char cSaved = zSql[i+1];
883         zSql[i+1] = 0;
884         if( sqlite3_complete(zSql+j) ){
885           rc = runDbSql(cx.db, zSql+j);
886           j = i+1;
887         }
888         zSql[i+1] = cSaved;
889         if( rc==SQLITE_INTERRUPT || progress_handler(&cx) ){
890           goto testrun_finished;
891         }
892       }
893     }
894     if( j<i ){
895       runDbSql(cx.db, zSql+j);
896     }
897   }
898 testrun_finished:
899   sqlite3_free(zSql);
900   rc = sqlite3_close(cx.db);
901   if( rc!=SQLITE_OK ){
902     fprintf(stdout, "sqlite3_close() returns %d\n", rc);
903   }
904   if( eVerbosity>=2 ){
905     fprintf(stdout, "Peak memory usages: %f MB\n",
906        sqlite3_memory_highwater(1) / 1000000.0);
907   }
908   if( sqlite3_memory_used()!=0 ){
909     int nAlloc = 0;
910     int nNotUsed = 0;
911     sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
912     fprintf(stderr,"Memory leak: %lld bytes in %d allocations\n",
913             sqlite3_memory_used(), nAlloc);
914     exit(1);
915   }
916   return 0;
917 }
918 
919 /*
920 ** END of the dbsqlfuzz code
921 ***************************************************************************/
922 
923 /* Look at a SQL text and try to determine if it begins with a database
924 ** description, such as would be found in a dbsqlfuzz test case.  Return
925 ** true if this does appear to be a dbsqlfuzz test case and false otherwise.
926 */
927 static int isDbSql(unsigned char *a, int n){
928   unsigned char buf[12];
929   int i;
930   if( n>4 && memcmp(a,"\n--\n",4)==0 ) return 1;
931   while( n>0 && isspace(a[0]) ){ a++; n--; }
932   for(i=0; n>0 && i<8; n--, a++){
933     if( isxdigit(a[0]) ) buf[i++] = a[0];
934   }
935   if( i==8 && memcmp(buf,"53514c69",8)==0 ) return 1;
936   return 0;
937 }
938 
939 /* Implementation of the isdbsql(TEXT) SQL function.
940 */
941 static void isDbSqlFunc(
942   sqlite3_context *context,
943   int argc,
944   sqlite3_value **argv
945 ){
946   int n = sqlite3_value_bytes(argv[0]);
947   unsigned char *a = (unsigned char*)sqlite3_value_blob(argv[0]);
948   sqlite3_result_int(context, a!=0 && n>0 && isDbSql(a,n));
949 }
950 
951 /* Methods for the VHandle object
952 */
953 static int inmemClose(sqlite3_file *pFile){
954   VHandle *p = (VHandle*)pFile;
955   VFile *pVFile = p->pVFile;
956   pVFile->nRef--;
957   if( pVFile->nRef==0 && pVFile->zFilename==0 ){
958     pVFile->sz = -1;
959     free(pVFile->a);
960     pVFile->a = 0;
961   }
962   return SQLITE_OK;
963 }
964 static int inmemRead(
965   sqlite3_file *pFile,   /* Read from this open file */
966   void *pData,           /* Store content in this buffer */
967   int iAmt,              /* Bytes of content */
968   sqlite3_int64 iOfst    /* Start reading here */
969 ){
970   VHandle *pHandle = (VHandle*)pFile;
971   VFile *pVFile = pHandle->pVFile;
972   if( iOfst<0 || iOfst>=pVFile->sz ){
973     memset(pData, 0, iAmt);
974     return SQLITE_IOERR_SHORT_READ;
975   }
976   if( iOfst+iAmt>pVFile->sz ){
977     memset(pData, 0, iAmt);
978     iAmt = (int)(pVFile->sz - iOfst);
979     memcpy(pData, pVFile->a + iOfst, iAmt);
980     return SQLITE_IOERR_SHORT_READ;
981   }
982   memcpy(pData, pVFile->a + iOfst, iAmt);
983   return SQLITE_OK;
984 }
985 static int inmemWrite(
986   sqlite3_file *pFile,   /* Write to this file */
987   const void *pData,     /* Content to write */
988   int iAmt,              /* bytes to write */
989   sqlite3_int64 iOfst    /* Start writing here */
990 ){
991   VHandle *pHandle = (VHandle*)pFile;
992   VFile *pVFile = pHandle->pVFile;
993   if( iOfst+iAmt > pVFile->sz ){
994     if( iOfst+iAmt >= MX_FILE_SZ ){
995       return SQLITE_FULL;
996     }
997     pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt));
998     if( iOfst > pVFile->sz ){
999       memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz));
1000     }
1001     pVFile->sz = (int)(iOfst + iAmt);
1002   }
1003   memcpy(pVFile->a + iOfst, pData, iAmt);
1004   return SQLITE_OK;
1005 }
1006 static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){
1007   VHandle *pHandle = (VHandle*)pFile;
1008   VFile *pVFile = pHandle->pVFile;
1009   if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize;
1010   return SQLITE_OK;
1011 }
1012 static int inmemSync(sqlite3_file *pFile, int flags){
1013   return SQLITE_OK;
1014 }
1015 static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){
1016   *pSize = ((VHandle*)pFile)->pVFile->sz;
1017   return SQLITE_OK;
1018 }
1019 static int inmemLock(sqlite3_file *pFile, int type){
1020   return SQLITE_OK;
1021 }
1022 static int inmemUnlock(sqlite3_file *pFile, int type){
1023   return SQLITE_OK;
1024 }
1025 static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){
1026   *pOut = 0;
1027   return SQLITE_OK;
1028 }
1029 static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){
1030   return SQLITE_NOTFOUND;
1031 }
1032 static int inmemSectorSize(sqlite3_file *pFile){
1033   return 512;
1034 }
1035 static int inmemDeviceCharacteristics(sqlite3_file *pFile){
1036   return
1037       SQLITE_IOCAP_SAFE_APPEND |
1038       SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
1039       SQLITE_IOCAP_POWERSAFE_OVERWRITE;
1040 }
1041 
1042 
1043 /* Method table for VHandle
1044 */
1045 static sqlite3_io_methods VHandleMethods = {
1046   /* iVersion  */    1,
1047   /* xClose    */    inmemClose,
1048   /* xRead     */    inmemRead,
1049   /* xWrite    */    inmemWrite,
1050   /* xTruncate */    inmemTruncate,
1051   /* xSync     */    inmemSync,
1052   /* xFileSize */    inmemFileSize,
1053   /* xLock     */    inmemLock,
1054   /* xUnlock   */    inmemUnlock,
1055   /* xCheck... */    inmemCheckReservedLock,
1056   /* xFileCtrl */    inmemFileControl,
1057   /* xSectorSz */    inmemSectorSize,
1058   /* xDevchar  */    inmemDeviceCharacteristics,
1059   /* xShmMap   */    0,
1060   /* xShmLock  */    0,
1061   /* xShmBarrier */  0,
1062   /* xShmUnmap */    0,
1063   /* xFetch    */    0,
1064   /* xUnfetch  */    0
1065 };
1066 
1067 /*
1068 ** Open a new file in the inmem VFS.  All files are anonymous and are
1069 ** delete-on-close.
1070 */
1071 static int inmemOpen(
1072   sqlite3_vfs *pVfs,
1073   const char *zFilename,
1074   sqlite3_file *pFile,
1075   int openFlags,
1076   int *pOutFlags
1077 ){
1078   VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)"");
1079   VHandle *pHandle = (VHandle*)pFile;
1080   if( pVFile==0 ){
1081     return SQLITE_FULL;
1082   }
1083   pHandle->pVFile = pVFile;
1084   pVFile->nRef++;
1085   pFile->pMethods = &VHandleMethods;
1086   if( pOutFlags ) *pOutFlags = openFlags;
1087   return SQLITE_OK;
1088 }
1089 
1090 /*
1091 ** Delete a file by name
1092 */
1093 static int inmemDelete(
1094   sqlite3_vfs *pVfs,
1095   const char *zFilename,
1096   int syncdir
1097 ){
1098   VFile *pVFile = findVFile(zFilename);
1099   if( pVFile==0 ) return SQLITE_OK;
1100   if( pVFile->nRef==0 ){
1101     free(pVFile->zFilename);
1102     pVFile->zFilename = 0;
1103     pVFile->sz = -1;
1104     free(pVFile->a);
1105     pVFile->a = 0;
1106     return SQLITE_OK;
1107   }
1108   return SQLITE_IOERR_DELETE;
1109 }
1110 
1111 /* Check for the existance of a file
1112 */
1113 static int inmemAccess(
1114   sqlite3_vfs *pVfs,
1115   const char *zFilename,
1116   int flags,
1117   int *pResOut
1118 ){
1119   VFile *pVFile = findVFile(zFilename);
1120   *pResOut =  pVFile!=0;
1121   return SQLITE_OK;
1122 }
1123 
1124 /* Get the canonical pathname for a file
1125 */
1126 static int inmemFullPathname(
1127   sqlite3_vfs *pVfs,
1128   const char *zFilename,
1129   int nOut,
1130   char *zOut
1131 ){
1132   sqlite3_snprintf(nOut, zOut, "%s", zFilename);
1133   return SQLITE_OK;
1134 }
1135 
1136 /* Always use the same random see, for repeatability.
1137 */
1138 static int inmemRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
1139   memset(zBuf, 0, nBuf);
1140   memcpy(zBuf, &g.uRandom, nBuf<sizeof(g.uRandom) ? nBuf : sizeof(g.uRandom));
1141   return nBuf;
1142 }
1143 
1144 /*
1145 ** Register the VFS that reads from the g.aFile[] set of files.
1146 */
1147 static void inmemVfsRegister(int makeDefault){
1148   static sqlite3_vfs inmemVfs;
1149   sqlite3_vfs *pDefault = sqlite3_vfs_find(0);
1150   inmemVfs.iVersion = 3;
1151   inmemVfs.szOsFile = sizeof(VHandle);
1152   inmemVfs.mxPathname = 200;
1153   inmemVfs.zName = "inmem";
1154   inmemVfs.xOpen = inmemOpen;
1155   inmemVfs.xDelete = inmemDelete;
1156   inmemVfs.xAccess = inmemAccess;
1157   inmemVfs.xFullPathname = inmemFullPathname;
1158   inmemVfs.xRandomness = inmemRandomness;
1159   inmemVfs.xSleep = pDefault->xSleep;
1160   inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64;
1161   sqlite3_vfs_register(&inmemVfs, makeDefault);
1162 };
1163 
1164 /*
1165 ** Allowed values for the runFlags parameter to runSql()
1166 */
1167 #define SQL_TRACE  0x0001     /* Print each SQL statement as it is prepared */
1168 #define SQL_OUTPUT 0x0002     /* Show the SQL output */
1169 
1170 /*
1171 ** Run multiple commands of SQL.  Similar to sqlite3_exec(), but does not
1172 ** stop if an error is encountered.
1173 */
1174 static void runSql(sqlite3 *db, const char *zSql, unsigned  runFlags){
1175   const char *zMore;
1176   sqlite3_stmt *pStmt;
1177 
1178   while( zSql && zSql[0] ){
1179     zMore = 0;
1180     pStmt = 0;
1181     sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore);
1182     if( zMore==zSql ) break;
1183     if( runFlags & SQL_TRACE ){
1184       const char *z = zSql;
1185       int n;
1186       while( z<zMore && ISSPACE(z[0]) ) z++;
1187       n = (int)(zMore - z);
1188       while( n>0 && ISSPACE(z[n-1]) ) n--;
1189       if( n==0 ) break;
1190       if( pStmt==0 ){
1191         printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db));
1192       }else{
1193         printf("TRACE: %.*s\n", n, z);
1194       }
1195     }
1196     zSql = zMore;
1197     if( pStmt ){
1198       if( (runFlags & SQL_OUTPUT)==0 ){
1199         while( SQLITE_ROW==sqlite3_step(pStmt) ){}
1200       }else{
1201         int nCol = -1;
1202         while( SQLITE_ROW==sqlite3_step(pStmt) ){
1203           int i;
1204           if( nCol<0 ){
1205             nCol = sqlite3_column_count(pStmt);
1206           }else if( nCol>0 ){
1207             printf("--------------------------------------------\n");
1208           }
1209           for(i=0; i<nCol; i++){
1210             int eType = sqlite3_column_type(pStmt,i);
1211             printf("%s = ", sqlite3_column_name(pStmt,i));
1212             switch( eType ){
1213               case SQLITE_NULL: {
1214                 printf("NULL\n");
1215                 break;
1216               }
1217               case SQLITE_INTEGER: {
1218                 printf("INT %s\n", sqlite3_column_text(pStmt,i));
1219                 break;
1220               }
1221               case SQLITE_FLOAT: {
1222                 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i));
1223                 break;
1224               }
1225               case SQLITE_TEXT: {
1226                 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i));
1227                 break;
1228               }
1229               case SQLITE_BLOB: {
1230                 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i));
1231                 break;
1232               }
1233             }
1234           }
1235         }
1236       }
1237       sqlite3_finalize(pStmt);
1238     }
1239   }
1240 }
1241 
1242 /*
1243 ** Rebuild the database file.
1244 **
1245 **    (1)  Remove duplicate entries
1246 **    (2)  Put all entries in order
1247 **    (3)  Vacuum
1248 */
1249 static void rebuild_database(sqlite3 *db, int dbSqlOnly){
1250   int rc;
1251   char *zSql;
1252   zSql = sqlite3_mprintf(
1253      "BEGIN;\n"
1254      "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n"
1255      "DELETE FROM db;\n"
1256      "INSERT INTO db(dbid, dbcontent) "
1257         " SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n"
1258      "DROP TABLE dbx;\n"
1259      "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql %s;\n"
1260      "DELETE FROM xsql;\n"
1261      "INSERT INTO xsql(sqlid,sqltext) "
1262         " SELECT NULL, sqltext FROM sx ORDER BY 2;\n"
1263      "DROP TABLE sx;\n"
1264      "COMMIT;\n"
1265      "PRAGMA page_size=1024;\n"
1266      "VACUUM;\n",
1267      dbSqlOnly ? " WHERE isdbsql(sqltext)" : ""
1268   );
1269   rc = sqlite3_exec(db, zSql, 0, 0, 0);
1270   sqlite3_free(zSql);
1271   if( rc ) fatalError("cannot rebuild: %s", sqlite3_errmsg(db));
1272 }
1273 
1274 /*
1275 ** Return the value of a hexadecimal digit.  Return -1 if the input
1276 ** is not a hex digit.
1277 */
1278 static int hexDigitValue(char c){
1279   if( c>='0' && c<='9' ) return c - '0';
1280   if( c>='a' && c<='f' ) return c - 'a' + 10;
1281   if( c>='A' && c<='F' ) return c - 'A' + 10;
1282   return -1;
1283 }
1284 
1285 /*
1286 ** Interpret zArg as an integer value, possibly with suffixes.
1287 */
1288 static int integerValue(const char *zArg){
1289   sqlite3_int64 v = 0;
1290   static const struct { char *zSuffix; int iMult; } aMult[] = {
1291     { "KiB", 1024 },
1292     { "MiB", 1024*1024 },
1293     { "GiB", 1024*1024*1024 },
1294     { "KB",  1000 },
1295     { "MB",  1000000 },
1296     { "GB",  1000000000 },
1297     { "K",   1000 },
1298     { "M",   1000000 },
1299     { "G",   1000000000 },
1300   };
1301   int i;
1302   int isNeg = 0;
1303   if( zArg[0]=='-' ){
1304     isNeg = 1;
1305     zArg++;
1306   }else if( zArg[0]=='+' ){
1307     zArg++;
1308   }
1309   if( zArg[0]=='0' && zArg[1]=='x' ){
1310     int x;
1311     zArg += 2;
1312     while( (x = hexDigitValue(zArg[0]))>=0 ){
1313       v = (v<<4) + x;
1314       zArg++;
1315     }
1316   }else{
1317     while( ISDIGIT(zArg[0]) ){
1318       v = v*10 + zArg[0] - '0';
1319       zArg++;
1320     }
1321   }
1322   for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
1323     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1324       v *= aMult[i].iMult;
1325       break;
1326     }
1327   }
1328   if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648");
1329   return (int)(isNeg? -v : v);
1330 }
1331 
1332 /*
1333 ** Return the number of "v" characters in a string.  Return 0 if there
1334 ** are any characters in the string other than "v".
1335 */
1336 static int numberOfVChar(const char *z){
1337   int N = 0;
1338   while( z[0] && z[0]=='v' ){
1339     z++;
1340     N++;
1341   }
1342   return z[0]==0 ? N : 0;
1343 }
1344 
1345 /*
1346 ** Print sketchy documentation for this utility program
1347 */
1348 static void showHelp(void){
1349   printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0);
1350   printf(
1351 "Read databases and SQL scripts from SOURCE-DB and execute each script against\n"
1352 "each database, checking for crashes and memory leaks.\n"
1353 "Options:\n"
1354 "  --cell-size-check    Set the PRAGMA cell_size_check=ON\n"
1355 "  --dbid N             Use only the database where dbid=N\n"
1356 "  --export-db DIR      Write databases to files(s) in DIR. Works with --dbid\n"
1357 "  --export-sql DIR     Write SQL to file(s) in DIR. Also works with --sqlid\n"
1358 "  --help               Show this help text\n"
1359 "  --info               Show information about SOURCE-DB w/o running tests\n"
1360 "  --limit-depth N      Limit expression depth to N\n"
1361 "  --limit-mem N        Limit memory used by test SQLite instance to N bytes\n"
1362 "  --limit-vdbe         Panic if any test runs for more than 100,000 cycles\n"
1363 "  --load-sql ARGS...   Load SQL scripts fron files into SOURCE-DB\n"
1364 "  --load-db ARGS...    Load template databases from files into SOURCE_DB\n"
1365 "  --load-dbsql ARGS..  Load dbsqlfuzz outputs into the xsql table\n"
1366 "  -m TEXT              Add a description to the database\n"
1367 "  --native-vfs         Use the native VFS for initially empty database files\n"
1368 "  --native-malloc      Turn off MEMSYS3/5 and Lookaside\n"
1369 "  --oss-fuzz           Enable OSS-FUZZ testing\n"
1370 "  --prng-seed N        Seed value for the PRGN inside of SQLite\n"
1371 "  -q|--quiet           Reduced output\n"
1372 "  --rebuild            Rebuild and vacuum the database file\n"
1373 "  --result-trace       Show the results of each SQL command\n"
1374 "  --sqlid N            Use only SQL where sqlid=N\n"
1375 "  --timeout N          Abort if any single test needs more than N seconds\n"
1376 "  -v|--verbose         Increased output.  Repeat for more output.\n"
1377 "  --vdbe-debug         Activate VDBE debugging.\n"
1378   );
1379 }
1380 
1381 int main(int argc, char **argv){
1382   sqlite3_int64 iBegin;        /* Start time of this program */
1383   int quietFlag = 0;           /* True if --quiet or -q */
1384   int verboseFlag = 0;         /* True if --verbose or -v */
1385   char *zInsSql = 0;           /* SQL statement for --load-db or --load-sql */
1386   int iFirstInsArg = 0;        /* First argv[] for --load-db or --load-sql */
1387   sqlite3 *db = 0;             /* The open database connection */
1388   sqlite3_stmt *pStmt;         /* A prepared statement */
1389   int rc;                      /* Result code from SQLite interface calls */
1390   Blob *pSql;                  /* For looping over SQL scripts */
1391   Blob *pDb;                   /* For looping over template databases */
1392   int i;                       /* Loop index for the argv[] loop */
1393   int dbSqlOnly = 0;           /* Only use scripts that are dbsqlfuzz */
1394   int onlySqlid = -1;          /* --sqlid */
1395   int onlyDbid = -1;           /* --dbid */
1396   int nativeFlag = 0;          /* --native-vfs */
1397   int rebuildFlag = 0;         /* --rebuild */
1398   int vdbeLimitFlag = 0;       /* --limit-vdbe */
1399   int infoFlag = 0;            /* --info */
1400   int timeoutTest = 0;         /* undocumented --timeout-test flag */
1401   int runFlags = 0;            /* Flags sent to runSql() */
1402   char *zMsg = 0;              /* Add this message */
1403   int nSrcDb = 0;              /* Number of source databases */
1404   char **azSrcDb = 0;          /* Array of source database names */
1405   int iSrcDb;                  /* Loop over all source databases */
1406   int nTest = 0;               /* Total number of tests performed */
1407   char *zDbName = "";          /* Appreviated name of a source database */
1408   const char *zFailCode = 0;   /* Value of the TEST_FAILURE env variable */
1409   int cellSzCkFlag = 0;        /* --cell-size-check */
1410   int sqlFuzz = 0;             /* True for SQL fuzz. False for DB fuzz */
1411   int iTimeout = 120;          /* Default 120-second timeout */
1412   int nMem = 0;                /* Memory limit override */
1413   int nMemThisDb = 0;          /* Memory limit set by the CONFIG table */
1414   char *zExpDb = 0;            /* Write Databases to files in this directory */
1415   char *zExpSql = 0;           /* Write SQL to files in this directory */
1416   void *pHeap = 0;             /* Heap for use by SQLite */
1417   int ossFuzz = 0;             /* enable OSS-FUZZ testing */
1418   int ossFuzzThisDb = 0;       /* ossFuzz value for this particular database */
1419   int nativeMalloc = 0;        /* Turn off MEMSYS3/5 and lookaside if true */
1420   sqlite3_vfs *pDfltVfs;       /* The default VFS */
1421   int openFlags4Data;          /* Flags for sqlite3_open_v2() */
1422   int nV;                      /* How much to increase verbosity with -vvvv */
1423 
1424   sqlite3_initialize();
1425   iBegin = timeOfDay();
1426 #ifdef __unix__
1427   signal(SIGALRM, signalHandler);
1428   signal(SIGSEGV, signalHandler);
1429   signal(SIGABRT, signalHandler);
1430 #endif
1431   g.zArgv0 = argv[0];
1432   openFlags4Data = SQLITE_OPEN_READONLY;
1433   zFailCode = getenv("TEST_FAILURE");
1434   pDfltVfs = sqlite3_vfs_find(0);
1435   inmemVfsRegister(1);
1436   for(i=1; i<argc; i++){
1437     const char *z = argv[i];
1438     if( z[0]=='-' ){
1439       z++;
1440       if( z[0]=='-' ) z++;
1441       if( strcmp(z,"cell-size-check")==0 ){
1442         cellSzCkFlag = 1;
1443       }else
1444       if( strcmp(z,"dbid")==0 ){
1445         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1446         onlyDbid = integerValue(argv[++i]);
1447       }else
1448       if( strcmp(z,"export-db")==0 ){
1449         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1450         zExpDb = argv[++i];
1451       }else
1452       if( strcmp(z,"export-sql")==0 || strcmp(z,"export-dbsql")==0 ){
1453         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1454         zExpSql = argv[++i];
1455       }else
1456       if( strcmp(z,"help")==0 ){
1457         showHelp();
1458         return 0;
1459       }else
1460       if( strcmp(z,"info")==0 ){
1461         infoFlag = 1;
1462       }else
1463       if( strcmp(z,"limit-depth")==0 ){
1464         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1465         depthLimit = integerValue(argv[++i]);
1466       }else
1467       if( strcmp(z,"limit-mem")==0 ){
1468         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1469         nMem = integerValue(argv[++i]);
1470       }else
1471       if( strcmp(z,"limit-vdbe")==0 ){
1472         vdbeLimitFlag = 1;
1473       }else
1474       if( strcmp(z,"load-sql")==0 ){
1475         zInsSql = "INSERT INTO xsql(sqltext)"
1476                   "VALUES(CAST(readtextfile(?1) AS text))";
1477         iFirstInsArg = i+1;
1478         openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1479         break;
1480       }else
1481       if( strcmp(z,"load-db")==0 ){
1482         zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
1483         iFirstInsArg = i+1;
1484         openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1485         break;
1486       }else
1487       if( strcmp(z,"load-dbsql")==0 ){
1488         zInsSql = "INSERT INTO xsql(sqltext)"
1489                   "VALUES(CAST(readtextfile(?1) AS text))";
1490         iFirstInsArg = i+1;
1491         openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1492         dbSqlOnly = 1;
1493         break;
1494       }else
1495       if( strcmp(z,"m")==0 ){
1496         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1497         zMsg = argv[++i];
1498         openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1499       }else
1500       if( strcmp(z,"native-malloc")==0 ){
1501         nativeMalloc = 1;
1502       }else
1503       if( strcmp(z,"native-vfs")==0 ){
1504         nativeFlag = 1;
1505       }else
1506       if( strcmp(z,"oss-fuzz")==0 ){
1507         ossFuzz = 1;
1508       }else
1509       if( strcmp(z,"prng-seed")==0 ){
1510         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1511         g.uRandom = atoi(argv[++i]);
1512       }else
1513       if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
1514         quietFlag = 1;
1515         verboseFlag = 0;
1516         eVerbosity = 0;
1517       }else
1518       if( strcmp(z,"rebuild")==0 ){
1519         rebuildFlag = 1;
1520         openFlags4Data = SQLITE_OPEN_READWRITE;
1521       }else
1522       if( strcmp(z,"result-trace")==0 ){
1523         runFlags |= SQL_OUTPUT;
1524       }else
1525       if( strcmp(z,"sqlid")==0 ){
1526         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1527         onlySqlid = integerValue(argv[++i]);
1528       }else
1529       if( strcmp(z,"timeout")==0 ){
1530         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1531         iTimeout = integerValue(argv[++i]);
1532       }else
1533       if( strcmp(z,"timeout-test")==0 ){
1534         timeoutTest = 1;
1535 #ifndef __unix__
1536         fatalError("timeout is not available on non-unix systems");
1537 #endif
1538       }else
1539       if( strcmp(z,"vdbe-debug")==0 ){
1540         bVdbeDebug = 1;
1541       }else
1542       if( strcmp(z,"verbose")==0 ){
1543         quietFlag = 0;
1544         verboseFlag++;
1545         eVerbosity++;
1546         if( verboseFlag>1 ) runFlags |= SQL_TRACE;
1547       }else
1548       if( (nV = numberOfVChar(z))>=1 ){
1549         quietFlag = 0;
1550         verboseFlag += nV;
1551         eVerbosity += nV;
1552         if( verboseFlag>1 ) runFlags |= SQL_TRACE;
1553       }else
1554       if( strcmp(z,"version")==0 ){
1555         int ii;
1556         const char *zz;
1557         printf("SQLite %s %s\n", sqlite3_libversion(), sqlite3_sourceid());
1558         for(ii=0; (zz = sqlite3_compileoption_get(ii))!=0; ii++){
1559           printf("%s\n", zz);
1560         }
1561         return 0;
1562       }else
1563       {
1564         fatalError("unknown option: %s", argv[i]);
1565       }
1566     }else{
1567       nSrcDb++;
1568       azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
1569       azSrcDb[nSrcDb-1] = argv[i];
1570     }
1571   }
1572   if( nSrcDb==0 ) fatalError("no source database specified");
1573   if( nSrcDb>1 ){
1574     if( zMsg ){
1575       fatalError("cannot change the description of more than one database");
1576     }
1577     if( zInsSql ){
1578       fatalError("cannot import into more than one database");
1579     }
1580   }
1581 
1582   /* Process each source database separately */
1583   for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
1584     g.zDbFile = azSrcDb[iSrcDb];
1585     rc = sqlite3_open_v2(azSrcDb[iSrcDb], &db,
1586                          openFlags4Data, pDfltVfs->zName);
1587     if( rc ){
1588       fatalError("cannot open source database %s - %s",
1589       azSrcDb[iSrcDb], sqlite3_errmsg(db));
1590     }
1591 
1592     /* Print the description, if there is one */
1593     if( infoFlag ){
1594       int n;
1595       zDbName = azSrcDb[iSrcDb];
1596       i = (int)strlen(zDbName) - 1;
1597       while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
1598       zDbName += i;
1599       sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
1600       if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
1601         printf("%s: %s", zDbName, sqlite3_column_text(pStmt,0));
1602       }else{
1603         printf("%s: (empty \"readme\")", zDbName);
1604       }
1605       sqlite3_finalize(pStmt);
1606       sqlite3_prepare_v2(db, "SELECT count(*) FROM db", -1, &pStmt, 0);
1607       if( pStmt
1608        && sqlite3_step(pStmt)==SQLITE_ROW
1609        && (n = sqlite3_column_int(pStmt,0))>0
1610       ){
1611         printf(" - %d DBs", n);
1612       }
1613       sqlite3_finalize(pStmt);
1614       sqlite3_prepare_v2(db, "SELECT count(*) FROM xsql", -1, &pStmt, 0);
1615       if( pStmt
1616        && sqlite3_step(pStmt)==SQLITE_ROW
1617        && (n = sqlite3_column_int(pStmt,0))>0
1618       ){
1619         printf(" - %d scripts", n);
1620       }
1621       sqlite3_finalize(pStmt);
1622       printf("\n");
1623       sqlite3_close(db);
1624       continue;
1625     }
1626 
1627     rc = sqlite3_exec(db,
1628        "CREATE TABLE IF NOT EXISTS db(\n"
1629        "  dbid INTEGER PRIMARY KEY, -- database id\n"
1630        "  dbcontent BLOB            -- database disk file image\n"
1631        ");\n"
1632        "CREATE TABLE IF NOT EXISTS xsql(\n"
1633        "  sqlid INTEGER PRIMARY KEY,   -- SQL script id\n"
1634        "  sqltext TEXT                 -- Text of SQL statements to run\n"
1635        ");"
1636        "CREATE TABLE IF NOT EXISTS readme(\n"
1637        "  msg TEXT -- Human-readable description of this file\n"
1638        ");", 0, 0, 0);
1639     if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
1640     if( zMsg ){
1641       char *zSql;
1642       zSql = sqlite3_mprintf(
1643                "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
1644       rc = sqlite3_exec(db, zSql, 0, 0, 0);
1645       sqlite3_free(zSql);
1646       if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
1647     }
1648     ossFuzzThisDb = ossFuzz;
1649 
1650     /* If the CONFIG(name,value) table exists, read db-specific settings
1651     ** from that table */
1652     if( sqlite3_table_column_metadata(db,0,"config",0,0,0,0,0,0)==SQLITE_OK ){
1653       rc = sqlite3_prepare_v2(db, "SELECT name, value FROM config",
1654                                   -1, &pStmt, 0);
1655       if( rc ) fatalError("cannot prepare query of CONFIG table: %s",
1656                           sqlite3_errmsg(db));
1657       while( SQLITE_ROW==sqlite3_step(pStmt) ){
1658         const char *zName = (const char *)sqlite3_column_text(pStmt,0);
1659         if( zName==0 ) continue;
1660         if( strcmp(zName, "oss-fuzz")==0 ){
1661           ossFuzzThisDb = sqlite3_column_int(pStmt,1);
1662           if( verboseFlag ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb);
1663         }
1664         if( strcmp(zName, "limit-mem")==0 ){
1665           nMemThisDb = sqlite3_column_int(pStmt,1);
1666           if( verboseFlag ) printf("Config: limit-mem=%d\n", nMemThisDb);
1667         }
1668       }
1669       sqlite3_finalize(pStmt);
1670     }
1671 
1672     if( zInsSql ){
1673       sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
1674                               readfileFunc, 0, 0);
1675       sqlite3_create_function(db, "readtextfile", 1, SQLITE_UTF8, 0,
1676                               readtextfileFunc, 0, 0);
1677       sqlite3_create_function(db, "isdbsql", 1, SQLITE_UTF8, 0,
1678                               isDbSqlFunc, 0, 0);
1679       rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
1680       if( rc ) fatalError("cannot prepare statement [%s]: %s",
1681                           zInsSql, sqlite3_errmsg(db));
1682       rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
1683       if( rc ) fatalError("cannot start a transaction");
1684       for(i=iFirstInsArg; i<argc; i++){
1685         sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
1686         sqlite3_step(pStmt);
1687         rc = sqlite3_reset(pStmt);
1688         if( rc ) fatalError("insert failed for %s", argv[i]);
1689       }
1690       sqlite3_finalize(pStmt);
1691       rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
1692       if( rc ) fatalError("cannot commit the transaction: %s",
1693                           sqlite3_errmsg(db));
1694       rebuild_database(db, dbSqlOnly);
1695       sqlite3_close(db);
1696       return 0;
1697     }
1698     rc = sqlite3_exec(db, "PRAGMA query_only=1;", 0, 0, 0);
1699     if( rc ) fatalError("cannot set database to query-only");
1700     if( zExpDb!=0 || zExpSql!=0 ){
1701       sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
1702                               writefileFunc, 0, 0);
1703       if( zExpDb!=0 ){
1704         const char *zExDb =
1705           "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent),"
1706           "       dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)"
1707           "  FROM db WHERE ?2<0 OR dbid=?2;";
1708         rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0);
1709         if( rc ) fatalError("cannot prepare statement [%s]: %s",
1710                             zExDb, sqlite3_errmsg(db));
1711         sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb),
1712                             SQLITE_STATIC, SQLITE_UTF8);
1713         sqlite3_bind_int(pStmt, 2, onlyDbid);
1714         while( sqlite3_step(pStmt)==SQLITE_ROW ){
1715           printf("write db-%d (%d bytes) into %s\n",
1716              sqlite3_column_int(pStmt,1),
1717              sqlite3_column_int(pStmt,3),
1718              sqlite3_column_text(pStmt,2));
1719         }
1720         sqlite3_finalize(pStmt);
1721       }
1722       if( zExpSql!=0 ){
1723         const char *zExSql =
1724           "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext),"
1725           "       sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)"
1726           "  FROM xsql WHERE ?2<0 OR sqlid=?2;";
1727         rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0);
1728         if( rc ) fatalError("cannot prepare statement [%s]: %s",
1729                             zExSql, sqlite3_errmsg(db));
1730         sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql),
1731                             SQLITE_STATIC, SQLITE_UTF8);
1732         sqlite3_bind_int(pStmt, 2, onlySqlid);
1733         while( sqlite3_step(pStmt)==SQLITE_ROW ){
1734           printf("write sql-%d (%d bytes) into %s\n",
1735              sqlite3_column_int(pStmt,1),
1736              sqlite3_column_int(pStmt,3),
1737              sqlite3_column_text(pStmt,2));
1738         }
1739         sqlite3_finalize(pStmt);
1740       }
1741       sqlite3_close(db);
1742       return 0;
1743     }
1744 
1745     /* Load all SQL script content and all initial database images from the
1746     ** source db
1747     */
1748     blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
1749                            &g.nSql, &g.pFirstSql);
1750     if( g.nSql==0 ) fatalError("need at least one SQL script");
1751     blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
1752                        &g.nDb, &g.pFirstDb);
1753     if( g.nDb==0 ){
1754       g.pFirstDb = safe_realloc(0, sizeof(Blob));
1755       memset(g.pFirstDb, 0, sizeof(Blob));
1756       g.pFirstDb->id = 1;
1757       g.pFirstDb->seq = 0;
1758       g.nDb = 1;
1759       sqlFuzz = 1;
1760     }
1761 
1762     /* Print the description, if there is one */
1763     if( !quietFlag ){
1764       zDbName = azSrcDb[iSrcDb];
1765       i = (int)strlen(zDbName) - 1;
1766       while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
1767       zDbName += i;
1768       sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
1769       if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
1770         printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
1771       }
1772       sqlite3_finalize(pStmt);
1773     }
1774 
1775     /* Rebuild the database, if requested */
1776     if( rebuildFlag ){
1777       if( !quietFlag ){
1778         printf("%s: rebuilding... ", zDbName);
1779         fflush(stdout);
1780       }
1781       rebuild_database(db, 0);
1782       if( !quietFlag ) printf("done\n");
1783     }
1784 
1785     /* Close the source database.  Verify that no SQLite memory allocations are
1786     ** outstanding.
1787     */
1788     sqlite3_close(db);
1789     if( sqlite3_memory_used()>0 ){
1790       fatalError("SQLite has memory in use before the start of testing");
1791     }
1792 
1793     /* Limit available memory, if requested */
1794     sqlite3_shutdown();
1795     if( nMemThisDb>0 && nMem==0 ){
1796       if( !nativeMalloc ){
1797         pHeap = realloc(pHeap, nMemThisDb);
1798         if( pHeap==0 ){
1799           fatalError("failed to allocate %d bytes of heap memory", nMem);
1800         }
1801         sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMemThisDb, 128);
1802       }else{
1803         sqlite3_hard_heap_limit64((sqlite3_int64)nMemThisDb);
1804       }
1805     }else{
1806       sqlite3_hard_heap_limit64(0);
1807     }
1808 
1809     /* Disable lookaside with the --native-malloc option */
1810     if( nativeMalloc ){
1811       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
1812     }
1813 
1814     /* Reset the in-memory virtual filesystem */
1815     formatVfs();
1816 
1817     /* Run a test using each SQL script against each database.
1818     */
1819     if( !verboseFlag && !quietFlag ) printf("%s:", zDbName);
1820     for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
1821       if( isDbSql(pSql->a, pSql->sz) ){
1822         sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d",pSql->id);
1823         if( verboseFlag ){
1824           printf("%s\n", g.zTestName);
1825           fflush(stdout);
1826         }else if( !quietFlag ){
1827           static int prevAmt = -1;
1828           int idx = pSql->seq;
1829           int amt = idx*10/(g.nSql);
1830           if( amt!=prevAmt ){
1831             printf(" %d%%", amt*10);
1832             fflush(stdout);
1833             prevAmt = amt;
1834           }
1835         }
1836         runCombinedDbSqlInput(pSql->a, pSql->sz);
1837         nTest++;
1838         g.zTestName[0] = 0;
1839         continue;
1840       }
1841       for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
1842         int openFlags;
1843         const char *zVfs = "inmem";
1844         sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
1845                          pSql->id, pDb->id);
1846         if( verboseFlag ){
1847           printf("%s\n", g.zTestName);
1848           fflush(stdout);
1849         }else if( !quietFlag ){
1850           static int prevAmt = -1;
1851           int idx = pSql->seq*g.nDb + pDb->id - 1;
1852           int amt = idx*10/(g.nDb*g.nSql);
1853           if( amt!=prevAmt ){
1854             printf(" %d%%", amt*10);
1855             fflush(stdout);
1856             prevAmt = amt;
1857           }
1858         }
1859         createVFile("main.db", pDb->sz, pDb->a);
1860         sqlite3_randomness(0,0);
1861         if( ossFuzzThisDb ){
1862 #ifndef SQLITE_OSS_FUZZ
1863           fatalError("--oss-fuzz not supported: recompile"
1864                      " with -DSQLITE_OSS_FUZZ");
1865 #else
1866           extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t);
1867           LLVMFuzzerTestOneInput((const uint8_t*)pSql->a, (size_t)pSql->sz);
1868 #endif
1869         }else{
1870           openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
1871           if( nativeFlag && pDb->sz==0 ){
1872             openFlags |= SQLITE_OPEN_MEMORY;
1873             zVfs = 0;
1874           }
1875           rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
1876           if( rc ) fatalError("cannot open inmem database");
1877           sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 100000000);
1878           sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 50);
1879           if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
1880           setAlarm(iTimeout);
1881 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1882           if( sqlFuzz || vdbeLimitFlag ){
1883             sqlite3_progress_handler(db, 100000, progressHandler,
1884                                      &vdbeLimitFlag);
1885           }
1886 #endif
1887 #ifdef SQLITE_TESTCTRL_PRNG_SEED
1888           sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, db);
1889 #endif
1890           if( bVdbeDebug ){
1891             sqlite3_exec(db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
1892           }
1893           do{
1894             runSql(db, (char*)pSql->a, runFlags);
1895           }while( timeoutTest );
1896           setAlarm(0);
1897           sqlite3_exec(db, "PRAGMA temp_store_directory=''", 0, 0, 0);
1898           sqlite3_close(db);
1899         }
1900         if( sqlite3_memory_used()>0 ){
1901            fatalError("memory leak: %lld bytes outstanding",
1902                       sqlite3_memory_used());
1903         }
1904         reformatVfs();
1905         nTest++;
1906         g.zTestName[0] = 0;
1907 
1908         /* Simulate an error if the TEST_FAILURE environment variable is "5".
1909         ** This is used to verify that automated test script really do spot
1910         ** errors that occur in this test program.
1911         */
1912         if( zFailCode ){
1913           if( zFailCode[0]=='5' && zFailCode[1]==0 ){
1914             fatalError("simulated failure");
1915           }else if( zFailCode[0]!=0 ){
1916             /* If TEST_FAILURE is something other than 5, just exit the test
1917             ** early */
1918             printf("\nExit early due to TEST_FAILURE being set\n");
1919             iSrcDb = nSrcDb-1;
1920             goto sourcedb_cleanup;
1921           }
1922         }
1923       }
1924     }
1925     if( !quietFlag && !verboseFlag ){
1926       printf(" 100%% - %d tests\n", g.nDb*g.nSql);
1927     }
1928 
1929     /* Clean up at the end of processing a single source database
1930     */
1931   sourcedb_cleanup:
1932     blobListFree(g.pFirstSql);
1933     blobListFree(g.pFirstDb);
1934     reformatVfs();
1935 
1936   } /* End loop over all source databases */
1937 
1938   if( !quietFlag ){
1939     sqlite3_int64 iElapse = timeOfDay() - iBegin;
1940     printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
1941            "SQLite %s %s\n",
1942            nTest, (int)(iElapse/1000), (int)(iElapse%1000),
1943            sqlite3_libversion(), sqlite3_sourceid());
1944   }
1945   free(azSrcDb);
1946   free(pHeap);
1947   return 0;
1948 }
1949