xref: /sqlite-3.40.0/test/fuzzcheck.c (revision c68fb847)
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         "julianday",
905         "random",
906         "randomblob",
907         "strftime",
908         "time",
909         "unixepoch",
910       };
911       int i;
912       for(i=0; i<sizeof(azBadFuncs)/sizeof(azBadFuncs[0]); i++){
913         if( sqlite3_stricmp(azBadFuncs[i], zArg2)==0 ){
914           *pFlags |= BTS_BADFUNC;
915           break;
916         }
917       }
918       break;
919     }
920     case SQLITE_READ: {
921       /* Benign */
922       break;
923     }
924     default: {
925       *pFlags |= BTS_NONSELECT;
926     }
927   }
928   return SQLITE_OK;
929 }
930 
931 /* Implementation found in fuzzinvariant.c */
932 int fuzz_invariant(
933   sqlite3 *db,            /* The database connection */
934   sqlite3_stmt *pStmt,    /* Test statement stopped on an SQLITE_ROW */
935   int iCnt,               /* Invariant sequence number, starting at 0 */
936   int iRow,               /* The row number for pStmt */
937   int *pbCorrupt,         /* IN/OUT: Flag indicating a corrupt database file */
938   int eVerbosity          /* How much debugging output */
939 );
940 
941 /*
942 ** Run the SQL text
943 */
944 static int runDbSql(sqlite3 *db, const char *zSql, unsigned int *pBtsFlags){
945   int rc;
946   sqlite3_stmt *pStmt;
947   int bCorrupt = 0;
948   while( isspace(zSql[0]&0x7f) ) zSql++;
949   if( zSql[0]==0 ) return SQLITE_OK;
950   if( eVerbosity>=4 ){
951     printf("RUNNING-SQL: [%s]\n", zSql);
952     fflush(stdout);
953   }
954   (*pBtsFlags) = 0;
955   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
956   if( rc==SQLITE_OK ){
957     int nRow = 0;
958     while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
959       nRow++;
960       if( eVerbosity>=5 ){
961         int j;
962         for(j=0; j<sqlite3_column_count(pStmt); j++){
963           if( j ) printf(",");
964           switch( sqlite3_column_type(pStmt, j) ){
965             case SQLITE_NULL: {
966               printf("NULL");
967               break;
968             }
969             case SQLITE_INTEGER:
970             case SQLITE_FLOAT: {
971               printf("%s", sqlite3_column_text(pStmt, j));
972               break;
973             }
974             case SQLITE_BLOB: {
975               int n = sqlite3_column_bytes(pStmt, j);
976               int i;
977               const unsigned char *a;
978               a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
979               printf("x'");
980               for(i=0; i<n; i++){
981                 printf("%02x", a[i]);
982               }
983               printf("'");
984               break;
985             }
986             case SQLITE_TEXT: {
987               int n = sqlite3_column_bytes(pStmt, j);
988               int i;
989               const unsigned char *a;
990               a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
991               printf("'");
992               for(i=0; i<n; i++){
993                 if( a[i]=='\'' ){
994                   printf("''");
995                 }else{
996                   putchar(a[i]);
997                 }
998               }
999               printf("'");
1000               break;
1001             }
1002           } /* End switch() */
1003         } /* End for() */
1004         printf("\n");
1005         fflush(stdout);
1006       } /* End if( eVerbosity>=5 ) */
1007     } /* End while( SQLITE_ROW */
1008     if( rc==SQLITE_DONE ){
1009       if( (*pBtsFlags)==BTS_SELECT
1010        && g.doInvariantChecks
1011        && !sqlite3_stmt_isexplain(pStmt)
1012        && nRow>0
1013       ){
1014         sqlite3_reset(pStmt);
1015         while( sqlite3_step(pStmt)==SQLITE_ROW ){
1016           int iCnt = 0;
1017           for(iCnt=0; iCnt<99999; iCnt++){
1018             rc = fuzz_invariant(db, pStmt, iCnt, nRow, &bCorrupt, eVerbosity);
1019             if( rc==SQLITE_DONE ) break;
1020             if( rc!=SQLITE_ERROR ) g.nInvariant++;
1021             if( eVerbosity>0 ){
1022               if( rc==SQLITE_OK ){
1023                 printf("invariant-check: ok\n");
1024               }else if( rc==SQLITE_CORRUPT ){
1025                 printf("invariant-check: failed due to database corruption\n");
1026               }
1027             }
1028           }
1029         }
1030       }
1031     }else if( eVerbosity>=4 ){
1032       printf("SQL-ERROR: (%d) %s\n", rc, sqlite3_errmsg(db));
1033       fflush(stdout);
1034     }
1035   }else if( eVerbosity>=4 ){
1036     printf("SQL-ERROR (%d): %s\n", rc, sqlite3_errmsg(db));
1037     fflush(stdout);
1038   } /* End if( SQLITE_OK ) */
1039   return sqlite3_finalize(pStmt);
1040 }
1041 
1042 /* Invoke this routine to run a single test case */
1043 int runCombinedDbSqlInput(
1044   const uint8_t *aData,      /* Combined DB+SQL content */
1045   size_t nByte,              /* Size of aData in bytes */
1046   int iTimeout,              /* Use this timeout */
1047   int bScript,               /* If true, just render CLI output */
1048   int iSqlId                 /* SQL identifier */
1049 ){
1050   int rc;                    /* SQLite API return value */
1051   int iSql;                  /* Index in aData[] of start of SQL */
1052   unsigned char *aDb = 0;    /* Decoded database content */
1053   int nDb = 0;               /* Size of the decoded database */
1054   int i;                     /* Loop counter */
1055   int j;                     /* Start of current SQL statement */
1056   char *zSql = 0;            /* SQL text to run */
1057   int nSql;                  /* Bytes of SQL text */
1058   FuzzCtx cx;                /* Fuzzing context */
1059   unsigned int btsFlags = 0; /* Parsing flags */
1060 
1061   if( nByte<10 ) return 0;
1062   if( sqlite3_initialize() ) return 0;
1063   if( sqlite3_memory_used()!=0 ){
1064     int nAlloc = 0;
1065     int nNotUsed = 0;
1066     sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
1067     fprintf(stderr,"memory leak prior to test start:"
1068                    " %lld bytes in %d allocations\n",
1069             sqlite3_memory_used(), nAlloc);
1070     exit(1);
1071   }
1072   memset(&cx, 0, sizeof(cx));
1073   iSql = decodeDatabase((unsigned char*)aData, (int)nByte, &aDb, &nDb);
1074   if( iSql<0 ) return 0;
1075   nSql = (int)(nByte - iSql);
1076   if( bScript ){
1077     char zName[100];
1078     sqlite3_snprintf(sizeof(zName),zName,"dbsql%06d.db",iSqlId);
1079     renderDbSqlForCLI(stdout, zName, aDb, nDb,
1080                       (unsigned char*)(aData+iSql), nSql);
1081     sqlite3_free(aDb);
1082     return 0;
1083   }
1084   if( eVerbosity>=3 ){
1085     printf(
1086       "****** %d-byte input, %d-byte database, %d-byte script "
1087       "******\n", (int)nByte, nDb, nSql);
1088     fflush(stdout);
1089   }
1090   rc = sqlite3_open(0, &cx.db);
1091   if( rc ){
1092     sqlite3_free(aDb);
1093     return 1;
1094   }
1095   if( bVdbeDebug ){
1096     sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
1097   }
1098 
1099   /* Invoke the progress handler frequently to check to see if we
1100   ** are taking too long.  The progress handler will return true
1101   ** (which will block further processing) if more than giTimeout seconds have
1102   ** elapsed since the start of the test.
1103   */
1104   cx.iLastCb = timeOfDay();
1105   cx.iCutoffTime = cx.iLastCb + (iTimeout<giTimeout ? iTimeout : giTimeout);
1106   cx.mxCb = mxProgressCb;
1107 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1108   sqlite3_progress_handler(cx.db, 10, progress_handler, (void*)&cx);
1109 #endif
1110 
1111   /* Set a limit on the maximum size of a prepared statement, and the
1112   ** maximum length of a string or blob */
1113   if( vdbeOpLimit>0 ){
1114     sqlite3_limit(cx.db, SQLITE_LIMIT_VDBE_OP, vdbeOpLimit);
1115   }
1116   if( lengthLimit>0 ){
1117     sqlite3_limit(cx.db, SQLITE_LIMIT_LENGTH, lengthLimit);
1118   }
1119   if( depthLimit>0 ){
1120     sqlite3_limit(cx.db, SQLITE_LIMIT_EXPR_DEPTH, depthLimit);
1121   }
1122   sqlite3_limit(cx.db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 100);
1123   sqlite3_hard_heap_limit64(heapLimit);
1124 
1125   if( nDb>=20 && aDb[18]==2 && aDb[19]==2 ){
1126     aDb[18] = aDb[19] = 1;
1127   }
1128   rc = sqlite3_deserialize(cx.db, "main", aDb, nDb, nDb,
1129           SQLITE_DESERIALIZE_RESIZEABLE |
1130           SQLITE_DESERIALIZE_FREEONCLOSE);
1131   if( rc ){
1132     fprintf(stderr, "sqlite3_deserialize() failed with %d\n", rc);
1133     goto testrun_finished;
1134   }
1135   if( maxDbSize>0 ){
1136     sqlite3_int64 x = maxDbSize;
1137     sqlite3_file_control(cx.db, "main", SQLITE_FCNTL_SIZE_LIMIT, &x);
1138   }
1139 
1140   /* For high debugging levels, turn on debug mode */
1141   if( eVerbosity>=5 ){
1142     sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON;", 0, 0, 0);
1143   }
1144 
1145   /* Block debug pragmas and ATTACH/DETACH.  But wait until after
1146   ** deserialize to do this because deserialize depends on ATTACH */
1147   sqlite3_set_authorizer(cx.db, block_troublesome_sql, &btsFlags);
1148 
1149 #ifdef VT02_SOURCES
1150   sqlite3_vt02_init(cx.db, 0, 0);
1151 #endif
1152 
1153   /* Consistent PRNG seed */
1154 #ifdef SQLITE_TESTCTRL_PRNG_SEED
1155   sqlite3_table_column_metadata(cx.db, 0, "x", 0, 0, 0, 0, 0, 0);
1156   sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, cx.db);
1157 #else
1158   sqlite3_randomness(0,0);
1159 #endif
1160 
1161   zSql = sqlite3_malloc( nSql + 1 );
1162   if( zSql==0 ){
1163     fprintf(stderr, "Out of memory!\n");
1164   }else{
1165     memcpy(zSql, aData+iSql, nSql);
1166     zSql[nSql] = 0;
1167     for(i=j=0; zSql[i]; i++){
1168       if( zSql[i]==';' ){
1169         char cSaved = zSql[i+1];
1170         zSql[i+1] = 0;
1171         if( sqlite3_complete(zSql+j) ){
1172           rc = runDbSql(cx.db, zSql+j, &btsFlags);
1173           j = i+1;
1174         }
1175         zSql[i+1] = cSaved;
1176         if( rc==SQLITE_INTERRUPT || progress_handler(&cx) ){
1177           goto testrun_finished;
1178         }
1179       }
1180     }
1181     if( j<i ){
1182       runDbSql(cx.db, zSql+j, &btsFlags);
1183     }
1184   }
1185 testrun_finished:
1186   sqlite3_free(zSql);
1187   rc = sqlite3_close(cx.db);
1188   if( rc!=SQLITE_OK ){
1189     fprintf(stdout, "sqlite3_close() returns %d\n", rc);
1190   }
1191   if( eVerbosity>=2 && !bScript ){
1192     fprintf(stdout, "Peak memory usages: %f MB\n",
1193        sqlite3_memory_highwater(1) / 1000000.0);
1194   }
1195   if( sqlite3_memory_used()!=0 ){
1196     int nAlloc = 0;
1197     int nNotUsed = 0;
1198     sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
1199     fprintf(stderr,"Memory leak: %lld bytes in %d allocations\n",
1200             sqlite3_memory_used(), nAlloc);
1201     exit(1);
1202   }
1203   sqlite3_hard_heap_limit64(0);
1204   sqlite3_soft_heap_limit64(0);
1205   return 0;
1206 }
1207 
1208 /*
1209 ** END of the dbsqlfuzz code
1210 ***************************************************************************/
1211 
1212 /* Look at a SQL text and try to determine if it begins with a database
1213 ** description, such as would be found in a dbsqlfuzz test case.  Return
1214 ** true if this does appear to be a dbsqlfuzz test case and false otherwise.
1215 */
1216 static int isDbSql(unsigned char *a, int n){
1217   unsigned char buf[12];
1218   int i;
1219   if( n>4 && memcmp(a,"\n--\n",4)==0 ) return 1;
1220   while( n>0 && isspace(a[0]) ){ a++; n--; }
1221   for(i=0; n>0 && i<8; n--, a++){
1222     if( isxdigit(a[0]) ) buf[i++] = a[0];
1223   }
1224   if( i==8 && memcmp(buf,"53514c69",8)==0 ) return 1;
1225   return 0;
1226 }
1227 
1228 /* Implementation of the isdbsql(TEXT) SQL function.
1229 */
1230 static void isDbSqlFunc(
1231   sqlite3_context *context,
1232   int argc,
1233   sqlite3_value **argv
1234 ){
1235   int n = sqlite3_value_bytes(argv[0]);
1236   unsigned char *a = (unsigned char*)sqlite3_value_blob(argv[0]);
1237   sqlite3_result_int(context, a!=0 && n>0 && isDbSql(a,n));
1238 }
1239 
1240 /* Methods for the VHandle object
1241 */
1242 static int inmemClose(sqlite3_file *pFile){
1243   VHandle *p = (VHandle*)pFile;
1244   VFile *pVFile = p->pVFile;
1245   pVFile->nRef--;
1246   if( pVFile->nRef==0 && pVFile->zFilename==0 ){
1247     pVFile->sz = -1;
1248     free(pVFile->a);
1249     pVFile->a = 0;
1250   }
1251   return SQLITE_OK;
1252 }
1253 static int inmemRead(
1254   sqlite3_file *pFile,   /* Read from this open file */
1255   void *pData,           /* Store content in this buffer */
1256   int iAmt,              /* Bytes of content */
1257   sqlite3_int64 iOfst    /* Start reading here */
1258 ){
1259   VHandle *pHandle = (VHandle*)pFile;
1260   VFile *pVFile = pHandle->pVFile;
1261   if( iOfst<0 || iOfst>=pVFile->sz ){
1262     memset(pData, 0, iAmt);
1263     return SQLITE_IOERR_SHORT_READ;
1264   }
1265   if( iOfst+iAmt>pVFile->sz ){
1266     memset(pData, 0, iAmt);
1267     iAmt = (int)(pVFile->sz - iOfst);
1268     memcpy(pData, pVFile->a + iOfst, iAmt);
1269     return SQLITE_IOERR_SHORT_READ;
1270   }
1271   memcpy(pData, pVFile->a + iOfst, iAmt);
1272   return SQLITE_OK;
1273 }
1274 static int inmemWrite(
1275   sqlite3_file *pFile,   /* Write to this file */
1276   const void *pData,     /* Content to write */
1277   int iAmt,              /* bytes to write */
1278   sqlite3_int64 iOfst    /* Start writing here */
1279 ){
1280   VHandle *pHandle = (VHandle*)pFile;
1281   VFile *pVFile = pHandle->pVFile;
1282   if( iOfst+iAmt > pVFile->sz ){
1283     if( iOfst+iAmt >= MX_FILE_SZ ){
1284       return SQLITE_FULL;
1285     }
1286     pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt));
1287     if( iOfst > pVFile->sz ){
1288       memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz));
1289     }
1290     pVFile->sz = (int)(iOfst + iAmt);
1291   }
1292   memcpy(pVFile->a + iOfst, pData, iAmt);
1293   return SQLITE_OK;
1294 }
1295 static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){
1296   VHandle *pHandle = (VHandle*)pFile;
1297   VFile *pVFile = pHandle->pVFile;
1298   if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize;
1299   return SQLITE_OK;
1300 }
1301 static int inmemSync(sqlite3_file *pFile, int flags){
1302   return SQLITE_OK;
1303 }
1304 static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){
1305   *pSize = ((VHandle*)pFile)->pVFile->sz;
1306   return SQLITE_OK;
1307 }
1308 static int inmemLock(sqlite3_file *pFile, int type){
1309   return SQLITE_OK;
1310 }
1311 static int inmemUnlock(sqlite3_file *pFile, int type){
1312   return SQLITE_OK;
1313 }
1314 static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){
1315   *pOut = 0;
1316   return SQLITE_OK;
1317 }
1318 static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){
1319   return SQLITE_NOTFOUND;
1320 }
1321 static int inmemSectorSize(sqlite3_file *pFile){
1322   return 512;
1323 }
1324 static int inmemDeviceCharacteristics(sqlite3_file *pFile){
1325   return
1326       SQLITE_IOCAP_SAFE_APPEND |
1327       SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
1328       SQLITE_IOCAP_POWERSAFE_OVERWRITE;
1329 }
1330 
1331 
1332 /* Method table for VHandle
1333 */
1334 static sqlite3_io_methods VHandleMethods = {
1335   /* iVersion  */    1,
1336   /* xClose    */    inmemClose,
1337   /* xRead     */    inmemRead,
1338   /* xWrite    */    inmemWrite,
1339   /* xTruncate */    inmemTruncate,
1340   /* xSync     */    inmemSync,
1341   /* xFileSize */    inmemFileSize,
1342   /* xLock     */    inmemLock,
1343   /* xUnlock   */    inmemUnlock,
1344   /* xCheck... */    inmemCheckReservedLock,
1345   /* xFileCtrl */    inmemFileControl,
1346   /* xSectorSz */    inmemSectorSize,
1347   /* xDevchar  */    inmemDeviceCharacteristics,
1348   /* xShmMap   */    0,
1349   /* xShmLock  */    0,
1350   /* xShmBarrier */  0,
1351   /* xShmUnmap */    0,
1352   /* xFetch    */    0,
1353   /* xUnfetch  */    0
1354 };
1355 
1356 /*
1357 ** Open a new file in the inmem VFS.  All files are anonymous and are
1358 ** delete-on-close.
1359 */
1360 static int inmemOpen(
1361   sqlite3_vfs *pVfs,
1362   const char *zFilename,
1363   sqlite3_file *pFile,
1364   int openFlags,
1365   int *pOutFlags
1366 ){
1367   VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)"");
1368   VHandle *pHandle = (VHandle*)pFile;
1369   if( pVFile==0 ){
1370     return SQLITE_FULL;
1371   }
1372   pHandle->pVFile = pVFile;
1373   pVFile->nRef++;
1374   pFile->pMethods = &VHandleMethods;
1375   if( pOutFlags ) *pOutFlags = openFlags;
1376   return SQLITE_OK;
1377 }
1378 
1379 /*
1380 ** Delete a file by name
1381 */
1382 static int inmemDelete(
1383   sqlite3_vfs *pVfs,
1384   const char *zFilename,
1385   int syncdir
1386 ){
1387   VFile *pVFile = findVFile(zFilename);
1388   if( pVFile==0 ) return SQLITE_OK;
1389   if( pVFile->nRef==0 ){
1390     free(pVFile->zFilename);
1391     pVFile->zFilename = 0;
1392     pVFile->sz = -1;
1393     free(pVFile->a);
1394     pVFile->a = 0;
1395     return SQLITE_OK;
1396   }
1397   return SQLITE_IOERR_DELETE;
1398 }
1399 
1400 /* Check for the existance of a file
1401 */
1402 static int inmemAccess(
1403   sqlite3_vfs *pVfs,
1404   const char *zFilename,
1405   int flags,
1406   int *pResOut
1407 ){
1408   VFile *pVFile = findVFile(zFilename);
1409   *pResOut =  pVFile!=0;
1410   return SQLITE_OK;
1411 }
1412 
1413 /* Get the canonical pathname for a file
1414 */
1415 static int inmemFullPathname(
1416   sqlite3_vfs *pVfs,
1417   const char *zFilename,
1418   int nOut,
1419   char *zOut
1420 ){
1421   sqlite3_snprintf(nOut, zOut, "%s", zFilename);
1422   return SQLITE_OK;
1423 }
1424 
1425 /* Always use the same random see, for repeatability.
1426 */
1427 static int inmemRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
1428   memset(zBuf, 0, nBuf);
1429   memcpy(zBuf, &g.uRandom, nBuf<sizeof(g.uRandom) ? nBuf : sizeof(g.uRandom));
1430   return nBuf;
1431 }
1432 
1433 /*
1434 ** Register the VFS that reads from the g.aFile[] set of files.
1435 */
1436 static void inmemVfsRegister(int makeDefault){
1437   static sqlite3_vfs inmemVfs;
1438   sqlite3_vfs *pDefault = sqlite3_vfs_find(0);
1439   inmemVfs.iVersion = 3;
1440   inmemVfs.szOsFile = sizeof(VHandle);
1441   inmemVfs.mxPathname = 200;
1442   inmemVfs.zName = "inmem";
1443   inmemVfs.xOpen = inmemOpen;
1444   inmemVfs.xDelete = inmemDelete;
1445   inmemVfs.xAccess = inmemAccess;
1446   inmemVfs.xFullPathname = inmemFullPathname;
1447   inmemVfs.xRandomness = inmemRandomness;
1448   inmemVfs.xSleep = pDefault->xSleep;
1449   inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64;
1450   sqlite3_vfs_register(&inmemVfs, makeDefault);
1451 };
1452 
1453 /*
1454 ** Allowed values for the runFlags parameter to runSql()
1455 */
1456 #define SQL_TRACE  0x0001     /* Print each SQL statement as it is prepared */
1457 #define SQL_OUTPUT 0x0002     /* Show the SQL output */
1458 
1459 /*
1460 ** Run multiple commands of SQL.  Similar to sqlite3_exec(), but does not
1461 ** stop if an error is encountered.
1462 */
1463 static void runSql(sqlite3 *db, const char *zSql, unsigned  runFlags){
1464   const char *zMore;
1465   sqlite3_stmt *pStmt;
1466 
1467   while( zSql && zSql[0] ){
1468     zMore = 0;
1469     pStmt = 0;
1470     sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore);
1471     if( zMore==zSql ) break;
1472     if( runFlags & SQL_TRACE ){
1473       const char *z = zSql;
1474       int n;
1475       while( z<zMore && ISSPACE(z[0]) ) z++;
1476       n = (int)(zMore - z);
1477       while( n>0 && ISSPACE(z[n-1]) ) n--;
1478       if( n==0 ) break;
1479       if( pStmt==0 ){
1480         printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db));
1481       }else{
1482         printf("TRACE: %.*s\n", n, z);
1483       }
1484     }
1485     zSql = zMore;
1486     if( pStmt ){
1487       if( (runFlags & SQL_OUTPUT)==0 ){
1488         while( SQLITE_ROW==sqlite3_step(pStmt) ){}
1489       }else{
1490         int nCol = -1;
1491         while( SQLITE_ROW==sqlite3_step(pStmt) ){
1492           int i;
1493           if( nCol<0 ){
1494             nCol = sqlite3_column_count(pStmt);
1495           }else if( nCol>0 ){
1496             printf("--------------------------------------------\n");
1497           }
1498           for(i=0; i<nCol; i++){
1499             int eType = sqlite3_column_type(pStmt,i);
1500             printf("%s = ", sqlite3_column_name(pStmt,i));
1501             switch( eType ){
1502               case SQLITE_NULL: {
1503                 printf("NULL\n");
1504                 break;
1505               }
1506               case SQLITE_INTEGER: {
1507                 printf("INT %s\n", sqlite3_column_text(pStmt,i));
1508                 break;
1509               }
1510               case SQLITE_FLOAT: {
1511                 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i));
1512                 break;
1513               }
1514               case SQLITE_TEXT: {
1515                 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i));
1516                 break;
1517               }
1518               case SQLITE_BLOB: {
1519                 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i));
1520                 break;
1521               }
1522             }
1523           }
1524         }
1525       }
1526       sqlite3_finalize(pStmt);
1527     }
1528   }
1529 }
1530 
1531 /*
1532 ** Rebuild the database file.
1533 **
1534 **    (1)  Remove duplicate entries
1535 **    (2)  Put all entries in order
1536 **    (3)  Vacuum
1537 */
1538 static void rebuild_database(sqlite3 *db, int dbSqlOnly){
1539   int rc;
1540   char *zSql;
1541   zSql = sqlite3_mprintf(
1542      "BEGIN;\n"
1543      "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n"
1544      "DELETE FROM db;\n"
1545      "INSERT INTO db(dbid, dbcontent) "
1546         " SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n"
1547      "DROP TABLE dbx;\n"
1548      "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql %s;\n"
1549      "DELETE FROM xsql;\n"
1550      "INSERT INTO xsql(sqlid,sqltext) "
1551         " SELECT NULL, sqltext FROM sx ORDER BY 2;\n"
1552      "DROP TABLE sx;\n"
1553      "COMMIT;\n"
1554      "PRAGMA page_size=1024;\n"
1555      "VACUUM;\n",
1556      dbSqlOnly ? " WHERE isdbsql(sqltext)" : ""
1557   );
1558   rc = sqlite3_exec(db, zSql, 0, 0, 0);
1559   sqlite3_free(zSql);
1560   if( rc ) fatalError("cannot rebuild: %s", sqlite3_errmsg(db));
1561 }
1562 
1563 /*
1564 ** Return the value of a hexadecimal digit.  Return -1 if the input
1565 ** is not a hex digit.
1566 */
1567 static int hexDigitValue(char c){
1568   if( c>='0' && c<='9' ) return c - '0';
1569   if( c>='a' && c<='f' ) return c - 'a' + 10;
1570   if( c>='A' && c<='F' ) return c - 'A' + 10;
1571   return -1;
1572 }
1573 
1574 /*
1575 ** Interpret zArg as an integer value, possibly with suffixes.
1576 */
1577 static int integerValue(const char *zArg){
1578   sqlite3_int64 v = 0;
1579   static const struct { char *zSuffix; int iMult; } aMult[] = {
1580     { "KiB", 1024 },
1581     { "MiB", 1024*1024 },
1582     { "GiB", 1024*1024*1024 },
1583     { "KB",  1000 },
1584     { "MB",  1000000 },
1585     { "GB",  1000000000 },
1586     { "K",   1000 },
1587     { "M",   1000000 },
1588     { "G",   1000000000 },
1589   };
1590   int i;
1591   int isNeg = 0;
1592   if( zArg[0]=='-' ){
1593     isNeg = 1;
1594     zArg++;
1595   }else if( zArg[0]=='+' ){
1596     zArg++;
1597   }
1598   if( zArg[0]=='0' && zArg[1]=='x' ){
1599     int x;
1600     zArg += 2;
1601     while( (x = hexDigitValue(zArg[0]))>=0 ){
1602       v = (v<<4) + x;
1603       zArg++;
1604     }
1605   }else{
1606     while( ISDIGIT(zArg[0]) ){
1607       v = v*10 + zArg[0] - '0';
1608       zArg++;
1609     }
1610   }
1611   for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
1612     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1613       v *= aMult[i].iMult;
1614       break;
1615     }
1616   }
1617   if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648");
1618   return (int)(isNeg? -v : v);
1619 }
1620 
1621 /*
1622 ** Return the number of "v" characters in a string.  Return 0 if there
1623 ** are any characters in the string other than "v".
1624 */
1625 static int numberOfVChar(const char *z){
1626   int N = 0;
1627   while( z[0] && z[0]=='v' ){
1628     z++;
1629     N++;
1630   }
1631   return z[0]==0 ? N : 0;
1632 }
1633 
1634 /*
1635 ** Print sketchy documentation for this utility program
1636 */
1637 static void showHelp(void){
1638   printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0);
1639   printf(
1640 "Read databases and SQL scripts from SOURCE-DB and execute each script against\n"
1641 "each database, checking for crashes and memory leaks.\n"
1642 "Options:\n"
1643 "  --cell-size-check    Set the PRAGMA cell_size_check=ON\n"
1644 "  --dbid N             Use only the database where dbid=N\n"
1645 "  --export-db DIR      Write databases to files(s) in DIR. Works with --dbid\n"
1646 "  --export-sql DIR     Write SQL to file(s) in DIR. Also works with --sqlid\n"
1647 "  --help               Show this help text\n"
1648 "  --info               Show information about SOURCE-DB w/o running tests\n"
1649 "  --limit-depth N      Limit expression depth to N.  Default: 500\n"
1650 "  --limit-heap N       Limit heap memory to N.  Default: 100M\n"
1651 "  --limit-mem N        Limit memory used by test SQLite instance to N bytes\n"
1652 "  --limit-vdbe         Panic if any test runs for more than 100,000 cycles\n"
1653 "  --load-sql   FILE..  Load SQL scripts fron files into SOURCE-DB\n"
1654 "  --load-db    FILE..  Load template databases from files into SOURCE_DB\n"
1655 "  --load-dbsql FILE..  Load dbsqlfuzz outputs into the xsql table\n"
1656 "               ^^^^------ Use \"-\" for FILE to read filenames from stdin\n"
1657 "  -m TEXT              Add a description to the database\n"
1658 "  --native-vfs         Use the native VFS for initially empty database files\n"
1659 "  --native-malloc      Turn off MEMSYS3/5 and Lookaside\n"
1660 "  --oss-fuzz           Enable OSS-FUZZ testing\n"
1661 "  --prng-seed N        Seed value for the PRGN inside of SQLite\n"
1662 "  -q|--quiet           Reduced output\n"
1663 "  --query-invariants   Run query invariant checks\n"
1664 "  --rebuild            Rebuild and vacuum the database file\n"
1665 "  --result-trace       Show the results of each SQL command\n"
1666 "  --script             Output CLI script instead of running tests\n"
1667 "  --skip N             Skip the first N test cases\n"
1668 "  --spinner            Use a spinner to show progress\n"
1669 "  --sqlid N            Use only SQL where sqlid=N\n"
1670 "  --timeout N          Maximum time for any one test in N millseconds\n"
1671 "  -v|--verbose         Increased output.  Repeat for more output.\n"
1672 "  --vdbe-debug         Activate VDBE debugging.\n"
1673   );
1674 }
1675 
1676 int main(int argc, char **argv){
1677   sqlite3_int64 iBegin;        /* Start time of this program */
1678   int quietFlag = 0;           /* True if --quiet or -q */
1679   int verboseFlag = 0;         /* True if --verbose or -v */
1680   char *zInsSql = 0;           /* SQL statement for --load-db or --load-sql */
1681   int iFirstInsArg = 0;        /* First argv[] for --load-db or --load-sql */
1682   sqlite3 *db = 0;             /* The open database connection */
1683   sqlite3_stmt *pStmt;         /* A prepared statement */
1684   int rc;                      /* Result code from SQLite interface calls */
1685   Blob *pSql;                  /* For looping over SQL scripts */
1686   Blob *pDb;                   /* For looping over template databases */
1687   int i;                       /* Loop index for the argv[] loop */
1688   int dbSqlOnly = 0;           /* Only use scripts that are dbsqlfuzz */
1689   int onlySqlid = -1;          /* --sqlid */
1690   int onlyDbid = -1;           /* --dbid */
1691   int nativeFlag = 0;          /* --native-vfs */
1692   int rebuildFlag = 0;         /* --rebuild */
1693   int vdbeLimitFlag = 0;       /* --limit-vdbe */
1694   int infoFlag = 0;            /* --info */
1695   int nSkip = 0;               /* --skip */
1696   int bScript = 0;             /* --script */
1697   int bSpinner = 0;            /* True for --spinner */
1698   int timeoutTest = 0;         /* undocumented --timeout-test flag */
1699   int runFlags = 0;            /* Flags sent to runSql() */
1700   char *zMsg = 0;              /* Add this message */
1701   int nSrcDb = 0;              /* Number of source databases */
1702   char **azSrcDb = 0;          /* Array of source database names */
1703   int iSrcDb;                  /* Loop over all source databases */
1704   int nTest = 0;               /* Total number of tests performed */
1705   char *zDbName = "";          /* Appreviated name of a source database */
1706   const char *zFailCode = 0;   /* Value of the TEST_FAILURE env variable */
1707   int cellSzCkFlag = 0;        /* --cell-size-check */
1708   int sqlFuzz = 0;             /* True for SQL fuzz. False for DB fuzz */
1709   int iTimeout = 120000;       /* Default 120-second timeout */
1710   int nMem = 0;                /* Memory limit override */
1711   int nMemThisDb = 0;          /* Memory limit set by the CONFIG table */
1712   char *zExpDb = 0;            /* Write Databases to files in this directory */
1713   char *zExpSql = 0;           /* Write SQL to files in this directory */
1714   void *pHeap = 0;             /* Heap for use by SQLite */
1715   int ossFuzz = 0;             /* enable OSS-FUZZ testing */
1716   int ossFuzzThisDb = 0;       /* ossFuzz value for this particular database */
1717   int nativeMalloc = 0;        /* Turn off MEMSYS3/5 and lookaside if true */
1718   sqlite3_vfs *pDfltVfs;       /* The default VFS */
1719   int openFlags4Data;          /* Flags for sqlite3_open_v2() */
1720   int bTimer = 0;              /* Show elapse time for each test */
1721   int nV;                      /* How much to increase verbosity with -vvvv */
1722   sqlite3_int64 tmStart;       /* Start of each test */
1723 
1724   sqlite3_config(SQLITE_CONFIG_URI,1);
1725   registerOomSimulator();
1726   sqlite3_initialize();
1727   iBegin = timeOfDay();
1728 #ifdef __unix__
1729   signal(SIGALRM, signalHandler);
1730   signal(SIGSEGV, signalHandler);
1731   signal(SIGABRT, signalHandler);
1732 #endif
1733   g.zArgv0 = argv[0];
1734   openFlags4Data = SQLITE_OPEN_READONLY;
1735   zFailCode = getenv("TEST_FAILURE");
1736   pDfltVfs = sqlite3_vfs_find(0);
1737   inmemVfsRegister(1);
1738   for(i=1; i<argc; i++){
1739     const char *z = argv[i];
1740     if( z[0]=='-' ){
1741       z++;
1742       if( z[0]=='-' ) z++;
1743       if( strcmp(z,"cell-size-check")==0 ){
1744         cellSzCkFlag = 1;
1745       }else
1746       if( strcmp(z,"dbid")==0 ){
1747         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1748         onlyDbid = integerValue(argv[++i]);
1749       }else
1750       if( strcmp(z,"export-db")==0 ){
1751         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1752         zExpDb = argv[++i];
1753       }else
1754       if( strcmp(z,"export-sql")==0 || strcmp(z,"export-dbsql")==0 ){
1755         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1756         zExpSql = argv[++i];
1757       }else
1758       if( strcmp(z,"help")==0 ){
1759         showHelp();
1760         return 0;
1761       }else
1762       if( strcmp(z,"info")==0 ){
1763         infoFlag = 1;
1764       }else
1765       if( strcmp(z,"limit-depth")==0 ){
1766         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1767         depthLimit = integerValue(argv[++i]);
1768       }else
1769       if( strcmp(z,"limit-heap")==0 ){
1770         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1771         heapLimit = integerValue(argv[++i]);
1772       }else
1773       if( strcmp(z,"limit-mem")==0 ){
1774         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1775         nMem = integerValue(argv[++i]);
1776       }else
1777       if( strcmp(z,"limit-vdbe")==0 ){
1778         vdbeLimitFlag = 1;
1779       }else
1780       if( strcmp(z,"load-sql")==0 ){
1781         zInsSql = "INSERT INTO xsql(sqltext)"
1782                   "VALUES(CAST(readtextfile(?1) AS text))";
1783         iFirstInsArg = i+1;
1784         openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1785         break;
1786       }else
1787       if( strcmp(z,"load-db")==0 ){
1788         zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
1789         iFirstInsArg = i+1;
1790         openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1791         break;
1792       }else
1793       if( strcmp(z,"load-dbsql")==0 ){
1794         zInsSql = "INSERT INTO xsql(sqltext)"
1795                   "VALUES(readfile(?1))";
1796         iFirstInsArg = i+1;
1797         openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1798         dbSqlOnly = 1;
1799         break;
1800       }else
1801       if( strcmp(z,"m")==0 ){
1802         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1803         zMsg = argv[++i];
1804         openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1805       }else
1806       if( strcmp(z,"native-malloc")==0 ){
1807         nativeMalloc = 1;
1808       }else
1809       if( strcmp(z,"native-vfs")==0 ){
1810         nativeFlag = 1;
1811       }else
1812       if( strcmp(z,"oss-fuzz")==0 ){
1813         ossFuzz = 1;
1814       }else
1815       if( strcmp(z,"prng-seed")==0 ){
1816         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1817         g.uRandom = atoi(argv[++i]);
1818       }else
1819       if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
1820         quietFlag = 1;
1821         verboseFlag = 0;
1822         eVerbosity = 0;
1823       }else
1824       if( strcmp(z,"query-invariants")==0 ){
1825         g.doInvariantChecks = 1;
1826       }else
1827       if( strcmp(z,"rebuild")==0 ){
1828         rebuildFlag = 1;
1829         openFlags4Data = SQLITE_OPEN_READWRITE;
1830       }else
1831       if( strcmp(z,"result-trace")==0 ){
1832         runFlags |= SQL_OUTPUT;
1833       }else
1834       if( strcmp(z,"script")==0 ){
1835         bScript = 1;
1836       }else
1837       if( strcmp(z,"skip")==0 ){
1838         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1839         nSkip = atoi(argv[++i]);
1840       }else
1841       if( strcmp(z,"spinner")==0 ){
1842         bSpinner = 1;
1843       }else
1844       if( strcmp(z,"timer")==0 ){
1845         bTimer = 1;
1846       }else
1847       if( strcmp(z,"sqlid")==0 ){
1848         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1849         onlySqlid = integerValue(argv[++i]);
1850       }else
1851       if( strcmp(z,"timeout")==0 ){
1852         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1853         iTimeout = integerValue(argv[++i]);
1854       }else
1855       if( strcmp(z,"timeout-test")==0 ){
1856         timeoutTest = 1;
1857 #ifndef __unix__
1858         fatalError("timeout is not available on non-unix systems");
1859 #endif
1860       }else
1861       if( strcmp(z,"vdbe-debug")==0 ){
1862         bVdbeDebug = 1;
1863       }else
1864       if( strcmp(z,"verbose")==0 ){
1865         quietFlag = 0;
1866         verboseFlag++;
1867         eVerbosity++;
1868         if( verboseFlag>1 ) runFlags |= SQL_TRACE;
1869       }else
1870       if( (nV = numberOfVChar(z))>=1 ){
1871         quietFlag = 0;
1872         verboseFlag += nV;
1873         eVerbosity += nV;
1874         if( verboseFlag>1 ) runFlags |= SQL_TRACE;
1875       }else
1876       if( strcmp(z,"version")==0 ){
1877         int ii;
1878         const char *zz;
1879         printf("SQLite %s %s\n", sqlite3_libversion(), sqlite3_sourceid());
1880         for(ii=0; (zz = sqlite3_compileoption_get(ii))!=0; ii++){
1881           printf("%s\n", zz);
1882         }
1883         return 0;
1884       }else
1885       if( strcmp(z,"is-dbsql")==0 ){
1886         i++;
1887         for(i++; i<argc; i++){
1888           long nData;
1889           char *aData = readFile(argv[i], &nData);
1890           printf("%d %s\n", isDbSql((unsigned char*)aData,nData), argv[i]);
1891           sqlite3_free(aData);
1892         }
1893         exit(0);
1894       }else
1895       {
1896         fatalError("unknown option: %s", argv[i]);
1897       }
1898     }else{
1899       nSrcDb++;
1900       azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
1901       azSrcDb[nSrcDb-1] = argv[i];
1902     }
1903   }
1904   if( nSrcDb==0 ) fatalError("no source database specified");
1905   if( nSrcDb>1 ){
1906     if( zMsg ){
1907       fatalError("cannot change the description of more than one database");
1908     }
1909     if( zInsSql ){
1910       fatalError("cannot import into more than one database");
1911     }
1912   }
1913 
1914   /* Process each source database separately */
1915   for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
1916     char *zRawData = 0;
1917     long nRawData = 0;
1918     g.zDbFile = azSrcDb[iSrcDb];
1919     rc = sqlite3_open_v2(azSrcDb[iSrcDb], &db,
1920                          openFlags4Data, pDfltVfs->zName);
1921     if( rc==SQLITE_OK ){
1922       rc = sqlite3_exec(db, "SELECT count(*) FROM sqlite_schema", 0, 0, 0);
1923     }
1924     if( rc ){
1925       sqlite3_close(db);
1926       zRawData = readFile(azSrcDb[iSrcDb], &nRawData);
1927       if( zRawData==0 ){
1928         fatalError("input file \"%s\" is not recognized\n", azSrcDb[iSrcDb]);
1929       }
1930       sqlite3_open(":memory:", &db);
1931     }
1932 
1933     /* Print the description, if there is one */
1934     if( infoFlag ){
1935       int n;
1936       zDbName = azSrcDb[iSrcDb];
1937       i = (int)strlen(zDbName) - 1;
1938       while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
1939       zDbName += i;
1940       sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
1941       if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
1942         printf("%s: %s", zDbName, sqlite3_column_text(pStmt,0));
1943       }else{
1944         printf("%s: (empty \"readme\")", zDbName);
1945       }
1946       sqlite3_finalize(pStmt);
1947       sqlite3_prepare_v2(db, "SELECT count(*) FROM db", -1, &pStmt, 0);
1948       if( pStmt
1949        && sqlite3_step(pStmt)==SQLITE_ROW
1950        && (n = sqlite3_column_int(pStmt,0))>0
1951       ){
1952         printf(" - %d DBs", n);
1953       }
1954       sqlite3_finalize(pStmt);
1955       sqlite3_prepare_v2(db, "SELECT count(*) FROM xsql", -1, &pStmt, 0);
1956       if( pStmt
1957        && sqlite3_step(pStmt)==SQLITE_ROW
1958        && (n = sqlite3_column_int(pStmt,0))>0
1959       ){
1960         printf(" - %d scripts", n);
1961       }
1962       sqlite3_finalize(pStmt);
1963       printf("\n");
1964       sqlite3_close(db);
1965       sqlite3_free(zRawData);
1966       continue;
1967     }
1968 
1969     rc = sqlite3_exec(db,
1970        "CREATE TABLE IF NOT EXISTS db(\n"
1971        "  dbid INTEGER PRIMARY KEY, -- database id\n"
1972        "  dbcontent BLOB            -- database disk file image\n"
1973        ");\n"
1974        "CREATE TABLE IF NOT EXISTS xsql(\n"
1975        "  sqlid INTEGER PRIMARY KEY,   -- SQL script id\n"
1976        "  sqltext TEXT                 -- Text of SQL statements to run\n"
1977        ");"
1978        "CREATE TABLE IF NOT EXISTS readme(\n"
1979        "  msg TEXT -- Human-readable description of this file\n"
1980        ");", 0, 0, 0);
1981     if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
1982     if( zMsg ){
1983       char *zSql;
1984       zSql = sqlite3_mprintf(
1985                "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
1986       rc = sqlite3_exec(db, zSql, 0, 0, 0);
1987       sqlite3_free(zSql);
1988       if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
1989     }
1990     if( zRawData ){
1991       zInsSql = "INSERT INTO xsql(sqltext) VALUES(?1)";
1992       rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
1993       if( rc ) fatalError("cannot prepare statement [%s]: %s",
1994                           zInsSql, sqlite3_errmsg(db));
1995       sqlite3_bind_text(pStmt, 1, zRawData, nRawData, SQLITE_STATIC);
1996       sqlite3_step(pStmt);
1997       rc = sqlite3_reset(pStmt);
1998       if( rc ) fatalError("insert failed for %s", argv[i]);
1999       sqlite3_finalize(pStmt);
2000       rebuild_database(db, dbSqlOnly);
2001       zInsSql = 0;
2002       sqlite3_free(zRawData);
2003       zRawData = 0;
2004     }
2005     ossFuzzThisDb = ossFuzz;
2006 
2007     /* If the CONFIG(name,value) table exists, read db-specific settings
2008     ** from that table */
2009     if( sqlite3_table_column_metadata(db,0,"config",0,0,0,0,0,0)==SQLITE_OK ){
2010       rc = sqlite3_prepare_v2(db, "SELECT name, value FROM config",
2011                                   -1, &pStmt, 0);
2012       if( rc ) fatalError("cannot prepare query of CONFIG table: %s",
2013                           sqlite3_errmsg(db));
2014       while( SQLITE_ROW==sqlite3_step(pStmt) ){
2015         const char *zName = (const char *)sqlite3_column_text(pStmt,0);
2016         if( zName==0 ) continue;
2017         if( strcmp(zName, "oss-fuzz")==0 ){
2018           ossFuzzThisDb = sqlite3_column_int(pStmt,1);
2019           if( verboseFlag ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb);
2020         }
2021         if( strcmp(zName, "limit-mem")==0 ){
2022           nMemThisDb = sqlite3_column_int(pStmt,1);
2023           if( verboseFlag ) printf("Config: limit-mem=%d\n", nMemThisDb);
2024         }
2025       }
2026       sqlite3_finalize(pStmt);
2027     }
2028 
2029     if( zInsSql ){
2030       sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
2031                               readfileFunc, 0, 0);
2032       sqlite3_create_function(db, "readtextfile", 1, SQLITE_UTF8, 0,
2033                               readtextfileFunc, 0, 0);
2034       sqlite3_create_function(db, "isdbsql", 1, SQLITE_UTF8, 0,
2035                               isDbSqlFunc, 0, 0);
2036       rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
2037       if( rc ) fatalError("cannot prepare statement [%s]: %s",
2038                           zInsSql, sqlite3_errmsg(db));
2039       rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
2040       if( rc ) fatalError("cannot start a transaction");
2041       for(i=iFirstInsArg; i<argc; i++){
2042         if( strcmp(argv[i],"-")==0 ){
2043           /* A filename of "-" means read multiple filenames from stdin */
2044           char zLine[2000];
2045           while( rc==0 && fgets(zLine,sizeof(zLine),stdin)!=0 ){
2046             size_t kk = strlen(zLine);
2047             while( kk>0 && zLine[kk-1]<=' ' ) kk--;
2048             sqlite3_bind_text(pStmt, 1, zLine, (int)kk, SQLITE_STATIC);
2049             if( verboseFlag ) printf("loading %.*s\n", (int)kk, zLine);
2050             sqlite3_step(pStmt);
2051             rc = sqlite3_reset(pStmt);
2052             if( rc ) fatalError("insert failed for %s", zLine);
2053           }
2054         }else{
2055           sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
2056           if( verboseFlag ) printf("loading %s\n", argv[i]);
2057           sqlite3_step(pStmt);
2058           rc = sqlite3_reset(pStmt);
2059           if( rc ) fatalError("insert failed for %s", argv[i]);
2060         }
2061       }
2062       sqlite3_finalize(pStmt);
2063       rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
2064       if( rc ) fatalError("cannot commit the transaction: %s",
2065                           sqlite3_errmsg(db));
2066       rebuild_database(db, dbSqlOnly);
2067       sqlite3_close(db);
2068       return 0;
2069     }
2070     rc = sqlite3_exec(db, "PRAGMA query_only=1;", 0, 0, 0);
2071     if( rc ) fatalError("cannot set database to query-only");
2072     if( zExpDb!=0 || zExpSql!=0 ){
2073       sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
2074                               writefileFunc, 0, 0);
2075       if( zExpDb!=0 ){
2076         const char *zExDb =
2077           "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent),"
2078           "       dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)"
2079           "  FROM db WHERE ?2<0 OR dbid=?2;";
2080         rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0);
2081         if( rc ) fatalError("cannot prepare statement [%s]: %s",
2082                             zExDb, sqlite3_errmsg(db));
2083         sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb),
2084                             SQLITE_STATIC, SQLITE_UTF8);
2085         sqlite3_bind_int(pStmt, 2, onlyDbid);
2086         while( sqlite3_step(pStmt)==SQLITE_ROW ){
2087           printf("write db-%d (%d bytes) into %s\n",
2088              sqlite3_column_int(pStmt,1),
2089              sqlite3_column_int(pStmt,3),
2090              sqlite3_column_text(pStmt,2));
2091         }
2092         sqlite3_finalize(pStmt);
2093       }
2094       if( zExpSql!=0 ){
2095         const char *zExSql =
2096           "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext),"
2097           "       sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)"
2098           "  FROM xsql WHERE ?2<0 OR sqlid=?2;";
2099         rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0);
2100         if( rc ) fatalError("cannot prepare statement [%s]: %s",
2101                             zExSql, sqlite3_errmsg(db));
2102         sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql),
2103                             SQLITE_STATIC, SQLITE_UTF8);
2104         sqlite3_bind_int(pStmt, 2, onlySqlid);
2105         while( sqlite3_step(pStmt)==SQLITE_ROW ){
2106           printf("write sql-%d (%d bytes) into %s\n",
2107              sqlite3_column_int(pStmt,1),
2108              sqlite3_column_int(pStmt,3),
2109              sqlite3_column_text(pStmt,2));
2110         }
2111         sqlite3_finalize(pStmt);
2112       }
2113       sqlite3_close(db);
2114       return 0;
2115     }
2116 
2117     /* Load all SQL script content and all initial database images from the
2118     ** source db
2119     */
2120     blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
2121                            &g.nSql, &g.pFirstSql);
2122     if( g.nSql==0 ) fatalError("need at least one SQL script");
2123     blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
2124                        &g.nDb, &g.pFirstDb);
2125     if( g.nDb==0 ){
2126       g.pFirstDb = safe_realloc(0, sizeof(Blob));
2127       memset(g.pFirstDb, 0, sizeof(Blob));
2128       g.pFirstDb->id = 1;
2129       g.pFirstDb->seq = 0;
2130       g.nDb = 1;
2131       sqlFuzz = 1;
2132     }
2133 
2134     /* Print the description, if there is one */
2135     if( !quietFlag && !bScript ){
2136       zDbName = azSrcDb[iSrcDb];
2137       i = (int)strlen(zDbName) - 1;
2138       while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
2139       zDbName += i;
2140       sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
2141       if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
2142         printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
2143       }
2144       sqlite3_finalize(pStmt);
2145     }
2146 
2147     /* Rebuild the database, if requested */
2148     if( rebuildFlag ){
2149       if( !quietFlag ){
2150         printf("%s: rebuilding... ", zDbName);
2151         fflush(stdout);
2152       }
2153       rebuild_database(db, 0);
2154       if( !quietFlag ) printf("done\n");
2155     }
2156 
2157     /* Close the source database.  Verify that no SQLite memory allocations are
2158     ** outstanding.
2159     */
2160     sqlite3_close(db);
2161     if( sqlite3_memory_used()>0 ){
2162       fatalError("SQLite has memory in use before the start of testing");
2163     }
2164 
2165     /* Limit available memory, if requested */
2166     sqlite3_shutdown();
2167 
2168     if( nMemThisDb>0 && nMem==0 ){
2169       if( !nativeMalloc ){
2170         pHeap = realloc(pHeap, nMemThisDb);
2171         if( pHeap==0 ){
2172           fatalError("failed to allocate %d bytes of heap memory", nMem);
2173         }
2174         sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMemThisDb, 128);
2175       }else{
2176         sqlite3_hard_heap_limit64((sqlite3_int64)nMemThisDb);
2177       }
2178     }else{
2179       sqlite3_hard_heap_limit64(0);
2180     }
2181 
2182     /* Disable lookaside with the --native-malloc option */
2183     if( nativeMalloc ){
2184       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
2185     }
2186 
2187     /* Reset the in-memory virtual filesystem */
2188     formatVfs();
2189 
2190     /* Run a test using each SQL script against each database.
2191     */
2192     if( !verboseFlag && !quietFlag && !bSpinner && !bScript ){
2193       printf("%s:", zDbName);
2194     }
2195     for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
2196       tmStart = timeOfDay();
2197       if( isDbSql(pSql->a, pSql->sz) ){
2198         sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d",pSql->id);
2199         if( bScript ){
2200           /* No progress output */
2201         }else if( bSpinner ){
2202           int nTotal =g.nSql;
2203           int idx = pSql->seq;
2204           printf("\r%s: %d/%d   ", zDbName, idx, nTotal);
2205           fflush(stdout);
2206         }else if( verboseFlag ){
2207           printf("%s\n", g.zTestName);
2208           fflush(stdout);
2209         }else if( !quietFlag ){
2210           static int prevAmt = -1;
2211           int idx = pSql->seq;
2212           int amt = idx*10/(g.nSql);
2213           if( amt!=prevAmt ){
2214             printf(" %d%%", amt*10);
2215             fflush(stdout);
2216             prevAmt = amt;
2217           }
2218         }
2219         if( nSkip>0 ){
2220           nSkip--;
2221         }else{
2222           runCombinedDbSqlInput(pSql->a, pSql->sz, iTimeout, bScript, pSql->id);
2223         }
2224         nTest++;
2225         if( bTimer && !bScript ){
2226           sqlite3_int64 tmEnd = timeOfDay();
2227           printf("%lld %s\n", tmEnd - tmStart, g.zTestName);
2228         }
2229         g.zTestName[0] = 0;
2230         disableOom();
2231         continue;
2232       }
2233       for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
2234         int openFlags;
2235         const char *zVfs = "inmem";
2236         sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
2237                          pSql->id, pDb->id);
2238         if( bScript ){
2239           /* No progress output */
2240         }else if( bSpinner ){
2241           int nTotal = g.nDb*g.nSql;
2242           int idx = pSql->seq*g.nDb + pDb->id - 1;
2243           printf("\r%s: %d/%d   ", zDbName, idx, nTotal);
2244           fflush(stdout);
2245         }else if( verboseFlag ){
2246           printf("%s\n", g.zTestName);
2247           fflush(stdout);
2248         }else if( !quietFlag ){
2249           static int prevAmt = -1;
2250           int idx = pSql->seq*g.nDb + pDb->id - 1;
2251           int amt = idx*10/(g.nDb*g.nSql);
2252           if( amt!=prevAmt ){
2253             printf(" %d%%", amt*10);
2254             fflush(stdout);
2255             prevAmt = amt;
2256           }
2257         }
2258         if( nSkip>0 ){
2259           nSkip--;
2260           continue;
2261         }
2262         if( bScript ){
2263           char zName[100];
2264           sqlite3_snprintf(sizeof(zName), zName, "db%06d.db",
2265                            pDb->id>1 ? pDb->id : pSql->id);
2266           renderDbSqlForCLI(stdout, zName,
2267              pDb->a, pDb->sz, pSql->a, pSql->sz);
2268           continue;
2269         }
2270         createVFile("main.db", pDb->sz, pDb->a);
2271         sqlite3_randomness(0,0);
2272         if( ossFuzzThisDb ){
2273 #ifndef SQLITE_OSS_FUZZ
2274           fatalError("--oss-fuzz not supported: recompile"
2275                      " with -DSQLITE_OSS_FUZZ");
2276 #else
2277           extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t);
2278           LLVMFuzzerTestOneInput((const uint8_t*)pSql->a, (size_t)pSql->sz);
2279 #endif
2280         }else{
2281           openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
2282           if( nativeFlag && pDb->sz==0 ){
2283             openFlags |= SQLITE_OPEN_MEMORY;
2284             zVfs = 0;
2285           }
2286           rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
2287           if( rc ) fatalError("cannot open inmem database");
2288           sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 100000000);
2289           sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 50);
2290           if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
2291           setAlarm((iTimeout+999)/1000);
2292           /* Enable test functions */
2293           sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, db);
2294 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2295           if( sqlFuzz || vdbeLimitFlag ){
2296             sqlite3_progress_handler(db, 100000, progressHandler,
2297                                      &vdbeLimitFlag);
2298           }
2299 #endif
2300 #ifdef SQLITE_TESTCTRL_PRNG_SEED
2301           sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, db);
2302 #endif
2303           if( bVdbeDebug ){
2304             sqlite3_exec(db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
2305           }
2306           do{
2307             runSql(db, (char*)pSql->a, runFlags);
2308           }while( timeoutTest );
2309           setAlarm(0);
2310           sqlite3_exec(db, "PRAGMA temp_store_directory=''", 0, 0, 0);
2311           sqlite3_close(db);
2312         }
2313         if( sqlite3_memory_used()>0 ){
2314            fatalError("memory leak: %lld bytes outstanding",
2315                       sqlite3_memory_used());
2316         }
2317         reformatVfs();
2318         nTest++;
2319         if( bTimer ){
2320           sqlite3_int64 tmEnd = timeOfDay();
2321           printf("%lld %s\n", tmEnd - tmStart, g.zTestName);
2322         }
2323         g.zTestName[0] = 0;
2324 
2325         /* Simulate an error if the TEST_FAILURE environment variable is "5".
2326         ** This is used to verify that automated test script really do spot
2327         ** errors that occur in this test program.
2328         */
2329         if( zFailCode ){
2330           if( zFailCode[0]=='5' && zFailCode[1]==0 ){
2331             fatalError("simulated failure");
2332           }else if( zFailCode[0]!=0 ){
2333             /* If TEST_FAILURE is something other than 5, just exit the test
2334             ** early */
2335             printf("\nExit early due to TEST_FAILURE being set\n");
2336             iSrcDb = nSrcDb-1;
2337             goto sourcedb_cleanup;
2338           }
2339         }
2340       }
2341     }
2342     if( bScript ){
2343       /* No progress output */
2344     }else if( bSpinner ){
2345       int nTotal = g.nDb*g.nSql;
2346       printf("\r%s: %d/%d   \n", zDbName, nTotal, nTotal);
2347     }else if( !quietFlag && !verboseFlag ){
2348       printf(" 100%% - %d tests\n", g.nDb*g.nSql);
2349     }
2350 
2351     /* Clean up at the end of processing a single source database
2352     */
2353   sourcedb_cleanup:
2354     blobListFree(g.pFirstSql);
2355     blobListFree(g.pFirstDb);
2356     reformatVfs();
2357 
2358   } /* End loop over all source databases */
2359 
2360   if( !quietFlag && !bScript ){
2361     sqlite3_int64 iElapse = timeOfDay() - iBegin;
2362     if( g.nInvariant ){
2363       printf("fuzzcheck: %u query invariants checked\n", g.nInvariant);
2364     }
2365     printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
2366            "SQLite %s %s\n",
2367            nTest, (int)(iElapse/1000), (int)(iElapse%1000),
2368            sqlite3_libversion(), sqlite3_sourceid());
2369   }
2370   free(azSrcDb);
2371   free(pHeap);
2372   return 0;
2373 }
2374