blob: a0bcc3bf07db428b5db8f4f52a582a7a959f6b2d [file] [log] [blame]
drh3b74d032015-05-25 18:48:19 +00001/*
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**
drh00452192015-06-17 18:24:40 +000013** This is a utility program designed to aid running regressions tests on
drha8781d92020-02-25 20:05:58 +000014** the SQLite library using data from external fuzzers.
drh3b74d032015-05-25 18:48:19 +000015**
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** );
drh00452192015-06-17 18:24:40 +000027** CREATE TABLE IF NOT EXISTS readme(
28** msg TEXT -- Human-readable description of this test collection
29** );
drh3b74d032015-05-25 18:48:19 +000030**
31** For each database file in the DB table, the SQL text in the XSQL table
drh00452192015-06-17 18:24:40 +000032** 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.
drh3b74d032015-05-25 18:48:19 +000042**
43** This program also includes some command-line options to help with
drh00452192015-06-17 18:24:40 +000044** 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.
drha8781d92020-02-25 20:05:58 +000065**
drh0fcf6f02021-05-24 12:28:13 +000066** DBSQLFUZZ: (Added 2020-02-25)
drha8781d92020-02-25 20:05:58 +000067**
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.
drh3b74d032015-05-25 18:48:19 +000080*/
81#include <stdio.h>
82#include <stdlib.h>
83#include <string.h>
84#include <stdarg.h>
85#include <ctype.h>
drha47e7092019-01-25 04:00:14 +000086#include <assert.h>
drh3b74d032015-05-25 18:48:19 +000087#include "sqlite3.h"
drh71b65e82022-10-28 18:35:06 +000088#include "sqlite3recover.h"
drhc56fac72015-10-29 13:48:15 +000089#define ISSPACE(X) isspace((unsigned char)(X))
90#define ISDIGIT(X) isdigit((unsigned char)(X))
91
drh3b74d032015-05-25 18:48:19 +000092
drh94701b02015-06-24 13:25:34 +000093#ifdef __unix__
94# include <signal.h>
95# include <unistd.h>
96#endif
97
drhf0a21722020-03-19 17:27:52 +000098#include <stddef.h>
99#if !defined(_MSC_VER)
100# include <stdint.h>
mistachkinac8ba262018-03-07 14:42:17 +0000101#endif
102
103#if defined(_MSC_VER)
104typedef unsigned char uint8_t;
drhea432ba2016-11-11 16:33:47 +0000105#endif
106
drh3b74d032015-05-25 18:48:19 +0000107/*
108** Files in the virtual file system.
109*/
110typedef struct VFile VFile;
111struct VFile {
drh0fcf6f02021-05-24 12:28:13 +0000112 char *zFilename; /* Filename. NULL for delete-on-close. From malloc() */
113 int sz; /* Size of the file in bytes */
114 int nRef; /* Number of references to this file */
115 unsigned char *a; /* Content of the file. From malloc() */
drh3b74d032015-05-25 18:48:19 +0000116};
117typedef struct VHandle VHandle;
118struct VHandle {
119 sqlite3_file base; /* Base class. Must be first */
120 VFile *pVFile; /* The underlying file */
121};
122
123/*
124** The value of a database file template, or of an SQL script
125*/
126typedef struct Blob Blob;
127struct Blob {
128 Blob *pNext; /* Next in a list */
129 int id; /* Id of this Blob */
drhe5c5f2c2015-05-26 00:28:08 +0000130 int seq; /* Sequence number */
drh3b74d032015-05-25 18:48:19 +0000131 int sz; /* Size of this Blob in bytes */
132 unsigned char a[1]; /* Blob content. Extra space allocated as needed. */
133};
134
135/*
136** Maximum number of files in the in-memory virtual filesystem.
137*/
138#define MX_FILE 10
139
140/*
141** Maximum allowed file size
142*/
143#define MX_FILE_SZ 10000000
144
145/*
146** All global variables are gathered into the "g" singleton.
147*/
148static struct GlobalVars {
149 const char *zArgv0; /* Name of program */
drha7648f02019-12-18 13:02:18 +0000150 const char *zDbFile; /* Name of database file */
drh3b74d032015-05-25 18:48:19 +0000151 VFile aFile[MX_FILE]; /* The virtual filesystem */
152 int nDb; /* Number of template databases */
153 Blob *pFirstDb; /* Content of first template database */
154 int nSql; /* Number of SQL scripts */
155 Blob *pFirstSql; /* First SQL script */
drhbeaf5142016-12-26 00:15:56 +0000156 unsigned int uRandom; /* Seed for the SQLite PRNG */
drhe3bf2c82022-06-15 16:26:37 +0000157 unsigned int nInvariant; /* Number of invariant checks run */
drh3b74d032015-05-25 18:48:19 +0000158 char zTestName[100]; /* Name of current test */
159} g;
160
161/*
drh71b65e82022-10-28 18:35:06 +0000162** Include the external vt02.c module.
drh0fab1092022-02-04 19:13:18 +0000163*/
drh71b65e82022-10-28 18:35:06 +0000164extern int sqlite3_vt02_init(sqlite3*,char***,void*);
165
drh0fab1092022-02-04 19:13:18 +0000166
167/*
drh3b74d032015-05-25 18:48:19 +0000168** Print an error message and quit.
169*/
170static void fatalError(const char *zFormat, ...){
171 va_list ap;
drha7648f02019-12-18 13:02:18 +0000172 fprintf(stderr, "%s", g.zArgv0);
173 if( g.zDbFile ) fprintf(stderr, " %s", g.zDbFile);
174 if( g.zTestName[0] ) fprintf(stderr, " (%s)", g.zTestName);
175 fprintf(stderr, ": ");
drh3b74d032015-05-25 18:48:19 +0000176 va_start(ap, zFormat);
177 vfprintf(stderr, zFormat, ap);
178 va_end(ap);
179 fprintf(stderr, "\n");
180 exit(1);
181}
182
183/*
drha7648f02019-12-18 13:02:18 +0000184** signal handler
drh94701b02015-06-24 13:25:34 +0000185*/
186#ifdef __unix__
drha7648f02019-12-18 13:02:18 +0000187static void signalHandler(int signum){
188 const char *zSig;
189 if( signum==SIGABRT ){
190 zSig = "abort";
191 }else if( signum==SIGALRM ){
192 zSig = "timeout";
193 }else if( signum==SIGSEGV ){
194 zSig = "segfault";
195 }else{
196 zSig = "signal";
197 }
198 fatalError(zSig);
drh94701b02015-06-24 13:25:34 +0000199}
200#endif
201
202/*
203** Set the an alarm to go off after N seconds. Disable the alarm
204** if N==0
205*/
206static void setAlarm(int N){
207#ifdef __unix__
208 alarm(N);
209#else
210 (void)N;
211#endif
212}
213
drh78057352015-06-24 23:17:35 +0000214#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh94701b02015-06-24 13:25:34 +0000215/*
drhd83e2832015-06-24 14:45:44 +0000216** This an SQL progress handler. After an SQL statement has run for
217** many steps, we want to interrupt it. This guards against infinite
218** loops from recursive common table expressions.
219**
220** *pVdbeLimitFlag is true if the --limit-vdbe command-line option is used.
221** In that case, hitting the progress handler is a fatal error.
222*/
223static int progressHandler(void *pVdbeLimitFlag){
224 if( *(int*)pVdbeLimitFlag ) fatalError("too many VDBE cycles");
225 return 1;
226}
drh78057352015-06-24 23:17:35 +0000227#endif
drhd83e2832015-06-24 14:45:44 +0000228
229/*
drh0fcf6f02021-05-24 12:28:13 +0000230** Reallocate memory. Show an error and quit if unable.
drh3b74d032015-05-25 18:48:19 +0000231*/
232static void *safe_realloc(void *pOld, int szNew){
drhc5412d52016-03-23 17:54:19 +0000233 void *pNew = realloc(pOld, szNew<=0 ? 1 : szNew);
drh3b74d032015-05-25 18:48:19 +0000234 if( pNew==0 ) fatalError("unable to realloc for %d bytes", szNew);
235 return pNew;
236}
237
238/*
239** Initialize the virtual file system.
240*/
241static void formatVfs(void){
242 int i;
243 for(i=0; i<MX_FILE; i++){
244 g.aFile[i].sz = -1;
245 g.aFile[i].zFilename = 0;
246 g.aFile[i].a = 0;
247 g.aFile[i].nRef = 0;
248 }
249}
250
251
252/*
253** Erase all information in the virtual file system.
254*/
255static void reformatVfs(void){
256 int i;
257 for(i=0; i<MX_FILE; i++){
258 if( g.aFile[i].sz<0 ) continue;
259 if( g.aFile[i].zFilename ){
260 free(g.aFile[i].zFilename);
261 g.aFile[i].zFilename = 0;
262 }
263 if( g.aFile[i].nRef>0 ){
264 fatalError("file %d still open. nRef=%d", i, g.aFile[i].nRef);
265 }
266 g.aFile[i].sz = -1;
267 free(g.aFile[i].a);
268 g.aFile[i].a = 0;
269 g.aFile[i].nRef = 0;
270 }
271}
272
273/*
274** Find a VFile by name
275*/
276static VFile *findVFile(const char *zName){
277 int i;
drha9542b12015-05-25 19:35:42 +0000278 if( zName==0 ) return 0;
drh3b74d032015-05-25 18:48:19 +0000279 for(i=0; i<MX_FILE; i++){
280 if( g.aFile[i].zFilename==0 ) continue;
281 if( strcmp(g.aFile[i].zFilename, zName)==0 ) return &g.aFile[i];
282 }
283 return 0;
284}
285
286/*
287** Find a VFile by name. Create it if it does not already exist and
288** initialize it to the size and content given.
289**
290** Return NULL only if the filesystem is full.
291*/
292static VFile *createVFile(const char *zName, int sz, unsigned char *pData){
293 VFile *pNew = findVFile(zName);
294 int i;
295 if( pNew ) return pNew;
296 for(i=0; i<MX_FILE && g.aFile[i].sz>=0; i++){}
297 if( i>=MX_FILE ) return 0;
298 pNew = &g.aFile[i];
drha9542b12015-05-25 19:35:42 +0000299 if( zName ){
drhe683b892016-02-15 18:47:26 +0000300 int nName = (int)strlen(zName)+1;
301 pNew->zFilename = safe_realloc(0, nName);
302 memcpy(pNew->zFilename, zName, nName);
drha9542b12015-05-25 19:35:42 +0000303 }else{
304 pNew->zFilename = 0;
305 }
drh3b74d032015-05-25 18:48:19 +0000306 pNew->nRef = 0;
307 pNew->sz = sz;
308 pNew->a = safe_realloc(0, sz);
309 if( sz>0 ) memcpy(pNew->a, pData, sz);
310 return pNew;
311}
312
drh075201e2021-10-27 12:05:28 +0000313/* Return true if the line is all zeros */
314static int allZero(unsigned char *aLine){
315 int i;
316 for(i=0; i<16 && aLine[i]==0; i++){}
317 return i==16;
318}
319
320/*
321** Render a database and query as text that can be input into
322** the CLI.
323*/
324static void renderDbSqlForCLI(
325 FILE *out, /* Write to this file */
326 const char *zFile, /* Name of the database file */
327 unsigned char *aDb, /* Database content */
328 int nDb, /* Number of bytes in aDb[] */
329 unsigned char *zSql, /* SQL content */
330 int nSql /* Bytes of SQL */
331){
332 fprintf(out, ".print ******* %s *******\n", zFile);
333 if( nDb>100 ){
334 int i, j; /* Loop counters */
335 int pgsz; /* Size of each page */
336 int lastPage = 0; /* Last page number shown */
337 int iPage; /* Current page number */
338 unsigned char *aLine; /* Single line to display */
339 unsigned char buf[16]; /* Fake line */
340 unsigned char bShow[256]; /* Characters ok to display */
341
342 memset(bShow, '.', sizeof(bShow));
343 for(i=' '; i<='~'; i++){
344 if( i!='{' && i!='}' && i!='"' && i!='\\' ) bShow[i] = i;
345 }
346 pgsz = (aDb[16]<<8) | aDb[17];
347 if( pgsz==0 ) pgsz = 65536;
348 if( pgsz<512 || (pgsz&(pgsz-1))!=0 ) pgsz = 4096;
349 fprintf(out,".open --hexdb\n");
350 fprintf(out,"| size %d pagesize %d filename %s\n",nDb,pgsz,zFile);
351 for(i=0; i<nDb; i += 16){
352 if( i+16>nDb ){
353 memset(buf, 0, sizeof(buf));
354 memcpy(buf, aDb+i, nDb-i);
355 aLine = buf;
356 }else{
357 aLine = aDb + i;
358 }
359 if( allZero(aLine) ) continue;
360 iPage = i/pgsz + 1;
361 if( lastPage!=iPage ){
362 fprintf(out,"| page %d offset %d\n", iPage, (iPage-1)*pgsz);
363 lastPage = iPage;
364 }
365 fprintf(out,"| %5d:", i-(iPage-1)*pgsz);
366 for(j=0; j<16; j++) fprintf(out," %02x", aLine[j]);
367 fprintf(out," ");
368 for(j=0; j<16; j++){
369 unsigned char c = (unsigned char)aLine[j];
370 fputc( bShow[c], stdout);
371 }
372 fputc('\n', stdout);
373 }
374 fprintf(out,"| end %s\n", zFile);
375 }else{
376 fprintf(out,".open :memory:\n");
377 }
378 fprintf(out,".testctrl prng_seed 1 db\n");
379 fprintf(out,".testctrl internal_functions\n");
380 fprintf(out,"%.*s", nSql, zSql);
381 if( nSql>0 && zSql[nSql-1]!='\n' ) fprintf(out, "\n");
382}
383
drh48b4bf22021-10-26 22:36:41 +0000384/*
385** Read the complete content of a file into memory. Add a 0x00 terminator
386** and return a pointer to the result.
387**
388** The file content is held in memory obtained from sqlite_malloc64() which
389** should be freed by the caller.
390*/
391static char *readFile(const char *zFilename, long *sz){
392 FILE *in;
393 long nIn;
394 unsigned char *pBuf;
395
396 *sz = 0;
397 if( zFilename==0 ) return 0;
398 in = fopen(zFilename, "rb");
399 if( in==0 ) return 0;
400 fseek(in, 0, SEEK_END);
401 *sz = nIn = ftell(in);
402 rewind(in);
403 pBuf = sqlite3_malloc64( nIn+1 );
404 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
405 pBuf[nIn] = 0;
406 fclose(in);
drh075201e2021-10-27 12:05:28 +0000407 return (char*)pBuf;
drh48b4bf22021-10-26 22:36:41 +0000408 }
409 sqlite3_free(pBuf);
410 *sz = 0;
411 fclose(in);
412 return 0;
413}
414
drh3b74d032015-05-25 18:48:19 +0000415
416/*
417** Implementation of the "readfile(X)" SQL function. The entire content
418** of the file named X is read and returned as a BLOB. NULL is returned
419** if the file does not exist or is unreadable.
420*/
421static void readfileFunc(
422 sqlite3_context *context,
423 int argc,
424 sqlite3_value **argv
425){
drh3b74d032015-05-25 18:48:19 +0000426 long nIn;
427 void *pBuf;
drh48b4bf22021-10-26 22:36:41 +0000428 const char *zName = (const char*)sqlite3_value_text(argv[0]);
drh3b74d032015-05-25 18:48:19 +0000429
drh3b74d032015-05-25 18:48:19 +0000430 if( zName==0 ) return;
drh48b4bf22021-10-26 22:36:41 +0000431 pBuf = readFile(zName, &nIn);
432 if( pBuf ){
drh3b74d032015-05-25 18:48:19 +0000433 sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
drh3b74d032015-05-25 18:48:19 +0000434 }
drh3b74d032015-05-25 18:48:19 +0000435}
436
437/*
drha8781d92020-02-25 20:05:58 +0000438** Implementation of the "readtextfile(X)" SQL function. The text content
439** of the file named X through the end of the file or to the first \000
440** character, whichever comes first, is read and returned as TEXT. NULL
441** is returned if the file does not exist or is unreadable.
442*/
443static void readtextfileFunc(
444 sqlite3_context *context,
445 int argc,
446 sqlite3_value **argv
447){
448 const char *zName;
449 FILE *in;
450 long nIn;
451 char *pBuf;
452
453 zName = (const char*)sqlite3_value_text(argv[0]);
454 if( zName==0 ) return;
455 in = fopen(zName, "rb");
456 if( in==0 ) return;
457 fseek(in, 0, SEEK_END);
458 nIn = ftell(in);
459 rewind(in);
460 pBuf = sqlite3_malloc64( nIn+1 );
461 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
462 pBuf[nIn] = 0;
463 sqlite3_result_text(context, pBuf, -1, sqlite3_free);
464 }else{
465 sqlite3_free(pBuf);
466 }
467 fclose(in);
468}
469
470/*
drh40e0e0d2015-09-22 18:51:17 +0000471** Implementation of the "writefile(X,Y)" SQL function. The argument Y
472** is written into file X. The number of bytes written is returned. Or
473** NULL is returned if something goes wrong, such as being unable to open
474** file X for writing.
475*/
476static void writefileFunc(
477 sqlite3_context *context,
478 int argc,
479 sqlite3_value **argv
480){
481 FILE *out;
482 const char *z;
483 sqlite3_int64 rc;
484 const char *zFile;
485
486 (void)argc;
487 zFile = (const char*)sqlite3_value_text(argv[0]);
488 if( zFile==0 ) return;
489 out = fopen(zFile, "wb");
490 if( out==0 ) return;
491 z = (const char*)sqlite3_value_blob(argv[1]);
492 if( z==0 ){
493 rc = 0;
494 }else{
495 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
496 }
497 fclose(out);
498 sqlite3_result_int64(context, rc);
499}
500
501
502/*
drh3b74d032015-05-25 18:48:19 +0000503** Load a list of Blob objects from the database
504*/
505static void blobListLoadFromDb(
506 sqlite3 *db, /* Read from this database */
507 const char *zSql, /* Query used to extract the blobs */
drha9542b12015-05-25 19:35:42 +0000508 int onlyId, /* Only load where id is this value */
drh3b74d032015-05-25 18:48:19 +0000509 int *pN, /* OUT: Write number of blobs loaded here */
510 Blob **ppList /* OUT: Write the head of the blob list here */
511){
512 Blob head;
513 Blob *p;
514 sqlite3_stmt *pStmt;
515 int n = 0;
516 int rc;
drha9542b12015-05-25 19:35:42 +0000517 char *z2;
drh3b74d032015-05-25 18:48:19 +0000518
drha9542b12015-05-25 19:35:42 +0000519 if( onlyId>0 ){
520 z2 = sqlite3_mprintf("%s WHERE rowid=%d", zSql, onlyId);
521 }else{
522 z2 = sqlite3_mprintf("%s", zSql);
523 }
524 rc = sqlite3_prepare_v2(db, z2, -1, &pStmt, 0);
525 sqlite3_free(z2);
drh3b74d032015-05-25 18:48:19 +0000526 if( rc ) fatalError("%s", sqlite3_errmsg(db));
527 head.pNext = 0;
528 p = &head;
529 while( SQLITE_ROW==sqlite3_step(pStmt) ){
530 int sz = sqlite3_column_bytes(pStmt, 1);
531 Blob *pNew = safe_realloc(0, sizeof(*pNew)+sz );
532 pNew->id = sqlite3_column_int(pStmt, 0);
533 pNew->sz = sz;
drhe5c5f2c2015-05-26 00:28:08 +0000534 pNew->seq = n++;
drh3b74d032015-05-25 18:48:19 +0000535 pNew->pNext = 0;
536 memcpy(pNew->a, sqlite3_column_blob(pStmt,1), sz);
537 pNew->a[sz] = 0;
538 p->pNext = pNew;
539 p = pNew;
drh3b74d032015-05-25 18:48:19 +0000540 }
541 sqlite3_finalize(pStmt);
542 *pN = n;
543 *ppList = head.pNext;
544}
545
546/*
547** Free a list of Blob objects
548*/
549static void blobListFree(Blob *p){
550 Blob *pNext;
551 while( p ){
552 pNext = p->pNext;
553 free(p);
554 p = pNext;
555 }
556}
557
drh237f41a2020-12-21 12:14:59 +0000558/* Return the current wall-clock time
559**
560** The number of milliseconds since the julian epoch.
561** 1907-01-01 00:00:00 -> 210866716800000
562** 2021-01-01 00:00:00 -> 212476176000000
563*/
drh3b74d032015-05-25 18:48:19 +0000564static sqlite3_int64 timeOfDay(void){
565 static sqlite3_vfs *clockVfs = 0;
566 sqlite3_int64 t;
drh8055a3e2018-11-21 14:27:34 +0000567 if( clockVfs==0 ){
568 clockVfs = sqlite3_vfs_find(0);
569 if( clockVfs==0 ) return 0;
570 }
drh3b74d032015-05-25 18:48:19 +0000571 if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
572 clockVfs->xCurrentTimeInt64(clockVfs, &t);
573 }else{
574 double r;
575 clockVfs->xCurrentTime(clockVfs, &r);
576 t = (sqlite3_int64)(r*86400000.0);
577 }
578 return t;
579}
580
drha47e7092019-01-25 04:00:14 +0000581/***************************************************************************
582** Code to process combined database+SQL scripts generated by the
583** dbsqlfuzz fuzzer.
584*/
585
586/* An instance of the following object is passed by pointer as the
587** client data to various callbacks.
588*/
589typedef struct FuzzCtx {
590 sqlite3 *db; /* The database connection */
591 sqlite3_int64 iCutoffTime; /* Stop processing at this time. */
592 sqlite3_int64 iLastCb; /* Time recorded for previous progress callback */
593 sqlite3_int64 mxInterval; /* Longest interval between two progress calls */
594 unsigned nCb; /* Number of progress callbacks */
595 unsigned mxCb; /* Maximum number of progress callbacks allowed */
596 unsigned execCnt; /* Number of calls to the sqlite3_exec callback */
597 int timeoutHit; /* True when reaching a timeout */
598} FuzzCtx;
599
600/* Verbosity level for the dbsqlfuzz test runner */
601static int eVerbosity = 0;
602
603/* True to activate PRAGMA vdbe_debug=on */
604static int bVdbeDebug = 0;
605
606/* Timeout for each fuzzing attempt, in milliseconds */
drhed457032019-01-25 17:51:06 +0000607static int giTimeout = 10000; /* Defaults to 10 seconds */
drha47e7092019-01-25 04:00:14 +0000608
609/* Maximum number of progress handler callbacks */
610static unsigned int mxProgressCb = 2000;
611
612/* Maximum string length in SQLite */
613static int lengthLimit = 1000000;
614
drhbe03cc92020-01-20 14:42:09 +0000615/* Maximum expression depth */
616static int depthLimit = 500;
617
drh31999c52019-11-14 17:46:32 +0000618/* Limit on the amount of heap memory that can be used */
drha8781d92020-02-25 20:05:58 +0000619static sqlite3_int64 heapLimit = 100000000;
drh31999c52019-11-14 17:46:32 +0000620
drha47e7092019-01-25 04:00:14 +0000621/* Maximum byte-code program length in SQLite */
622static int vdbeOpLimit = 25000;
623
624/* Maximum size of the in-memory database */
625static sqlite3_int64 maxDbSize = 104857600;
drh39b3bcf2020-03-02 16:31:21 +0000626/* OOM simulation parameters */
627static unsigned int oomCounter = 0; /* Simulate OOM when equals 1 */
628static unsigned int oomRepeat = 0; /* Number of OOMs in a row */
629static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
630
drh71b65e82022-10-28 18:35:06 +0000631/* Enable recovery */
632static int bNoRecover = 0;
633
drh39b3bcf2020-03-02 16:31:21 +0000634/* This routine is called when a simulated OOM occurs. It is broken
635** out as a separate routine to make it easy to set a breakpoint on
636** the OOM
637*/
638void oomFault(void){
639 if( eVerbosity ){
640 printf("Simulated OOM fault\n");
641 }
642 if( oomRepeat>0 ){
643 oomRepeat--;
644 }else{
645 oomCounter--;
646 }
647}
648
649/* This routine is a replacement malloc() that is used to simulate
650** Out-Of-Memory (OOM) errors for testing purposes.
651*/
652static void *oomMalloc(int nByte){
653 if( oomCounter ){
654 if( oomCounter==1 ){
655 oomFault();
656 return 0;
657 }else{
658 oomCounter--;
659 }
660 }
661 return defaultMalloc(nByte);
662}
663
664/* Register the OOM simulator. This must occur before any memory
665** allocations */
666static void registerOomSimulator(void){
667 sqlite3_mem_methods mem;
668 sqlite3_shutdown();
669 sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
670 defaultMalloc = mem.xMalloc;
671 mem.xMalloc = oomMalloc;
672 sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
673}
674
675/* Turn off any pending OOM simulation */
676static void disableOom(void){
677 oomCounter = 0;
678 oomRepeat = 0;
679}
drha47e7092019-01-25 04:00:14 +0000680
681/*
682** Translate a single byte of Hex into an integer.
683** This routine only works if h really is a valid hexadecimal
684** character: 0..9a..fA..F
685*/
drhed457032019-01-25 17:51:06 +0000686static unsigned char hexToInt(unsigned int h){
drha47e7092019-01-25 04:00:14 +0000687#ifdef SQLITE_EBCDIC
688 h += 9*(1&~(h>>4)); /* EBCDIC */
689#else
690 h += 9*(1&(h>>6)); /* ASCII */
691#endif
692 return h & 0xf;
693}
694
695/*
696** The first character of buffer zIn[0..nIn-1] is a '['. This routine
697** checked to see if the buffer holds "[NNNN]" or "[+NNNN]" and if it
698** does it makes corresponding changes to the *pK value and *pI value
699** and returns true. If the input buffer does not match the patterns,
700** no changes are made to either *pK or *pI and this routine returns false.
701*/
702static int isOffset(
703 const unsigned char *zIn, /* Text input */
704 int nIn, /* Bytes of input */
705 unsigned int *pK, /* half-byte cursor to adjust */
706 unsigned int *pI /* Input index to adjust */
707){
708 int i;
709 unsigned int k = 0;
710 unsigned char c;
711 for(i=1; i<nIn && (c = zIn[i])!=']'; i++){
712 if( !isxdigit(c) ) return 0;
713 k = k*16 + hexToInt(c);
714 }
715 if( i==nIn ) return 0;
716 *pK = 2*k;
717 *pI += i;
718 return 1;
719}
720
721/*
722** Decode the text starting at zIn into a binary database file.
drh0fcf6f02021-05-24 12:28:13 +0000723** The maximum length of zIn is nIn bytes. Store the binary database
724** file in space obtained from sqlite3_malloc().
drha47e7092019-01-25 04:00:14 +0000725**
726** Return the number of bytes of zIn consumed. Or return -1 if there
727** is an error. One potential error is that the recipe specifies a
728** database file larger than MX_FILE_SZ bytes.
729**
730** Abort on an OOM.
731*/
732static int decodeDatabase(
733 const unsigned char *zIn, /* Input text to be decoded */
734 int nIn, /* Bytes of input text */
735 unsigned char **paDecode, /* OUT: decoded database file */
736 int *pnDecode /* OUT: Size of decoded database */
737){
drh672f07c2020-10-20 14:40:53 +0000738 unsigned char *a, *aNew; /* Database under construction */
drha47e7092019-01-25 04:00:14 +0000739 int mx = 0; /* Current size of the database */
740 sqlite3_uint64 nAlloc = 4096; /* Space allocated in a[] */
741 unsigned int i; /* Next byte of zIn[] to read */
742 unsigned int j; /* Temporary integer */
743 unsigned int k; /* half-byte cursor index for output */
744 unsigned int n; /* Number of bytes of input */
745 unsigned char b = 0;
746 if( nIn<4 ) return -1;
747 n = (unsigned int)nIn;
drhed457032019-01-25 17:51:06 +0000748 a = sqlite3_malloc64( nAlloc );
drha47e7092019-01-25 04:00:14 +0000749 if( a==0 ){
750 fprintf(stderr, "Out of memory!\n");
751 exit(1);
752 }
mistachkin065f3bf2019-03-20 05:45:03 +0000753 memset(a, 0, (size_t)nAlloc);
drha47e7092019-01-25 04:00:14 +0000754 for(i=k=0; i<n; i++){
drhaf638922019-02-07 00:17:36 +0000755 unsigned char c = (unsigned char)zIn[i];
drha47e7092019-01-25 04:00:14 +0000756 if( isxdigit(c) ){
757 k++;
758 if( k & 1 ){
759 b = hexToInt(c)*16;
760 }else{
761 b += hexToInt(c);
762 j = k/2 - 1;
763 if( j>=nAlloc ){
764 sqlite3_uint64 newSize;
765 if( nAlloc==MX_FILE_SZ || j>=MX_FILE_SZ ){
766 if( eVerbosity ){
767 fprintf(stderr, "Input database too big: max %d bytes\n",
768 MX_FILE_SZ);
769 }
770 sqlite3_free(a);
771 return -1;
772 }
773 newSize = nAlloc*2;
774 if( newSize<=j ){
775 newSize = (j+4096)&~4095;
776 }
777 if( newSize>MX_FILE_SZ ){
778 if( j>=MX_FILE_SZ ){
779 sqlite3_free(a);
780 return -1;
781 }
782 newSize = MX_FILE_SZ;
783 }
drh672f07c2020-10-20 14:40:53 +0000784 aNew = sqlite3_realloc64( a, newSize );
785 if( aNew==0 ){
786 sqlite3_free(a);
787 return -1;
drha47e7092019-01-25 04:00:14 +0000788 }
drh672f07c2020-10-20 14:40:53 +0000789 a = aNew;
drha47e7092019-01-25 04:00:14 +0000790 assert( newSize > nAlloc );
mistachkin065f3bf2019-03-20 05:45:03 +0000791 memset(a+nAlloc, 0, (size_t)(newSize - nAlloc));
drha47e7092019-01-25 04:00:14 +0000792 nAlloc = newSize;
793 }
794 if( j>=(unsigned)mx ){
795 mx = (j + 4095)&~4095;
796 if( mx>MX_FILE_SZ ) mx = MX_FILE_SZ;
797 }
798 assert( j<nAlloc );
799 a[j] = b;
800 }
801 }else if( zIn[i]=='[' && i<n-3 && isOffset(zIn+i, nIn-i, &k, &i) ){
802 continue;
803 }else if( zIn[i]=='\n' && i<n-4 && memcmp(zIn+i,"\n--\n",4)==0 ){
804 i += 4;
805 break;
806 }
807 }
808 *pnDecode = mx;
809 *paDecode = a;
810 return i;
811}
812
813/*
814** Progress handler callback.
815**
816** The argument is the cutoff-time after which all processing should
817** stop. So return non-zero if the cut-off time is exceeded.
818*/
819static int progress_handler(void *pClientData) {
820 FuzzCtx *p = (FuzzCtx*)pClientData;
821 sqlite3_int64 iNow = timeOfDay();
822 int rc = iNow>=p->iCutoffTime;
823 sqlite3_int64 iDiff = iNow - p->iLastCb;
drh237f41a2020-12-21 12:14:59 +0000824 /* printf("time-remaining: %lld\n", p->iCutoffTime - iNow); */
drha47e7092019-01-25 04:00:14 +0000825 if( iDiff > p->mxInterval ) p->mxInterval = iDiff;
826 p->nCb++;
827 if( rc==0 && p->mxCb>0 && p->mxCb<=p->nCb ) rc = 1;
drhdf216592019-01-25 04:43:26 +0000828 if( rc && !p->timeoutHit && eVerbosity>=2 ){
drha47e7092019-01-25 04:00:14 +0000829 printf("Timeout on progress callback %d\n", p->nCb);
830 fflush(stdout);
831 p->timeoutHit = 1;
832 }
833 return rc;
834}
835
836/*
drha1f79da2022-06-14 19:12:25 +0000837** Flag bits set by block_troublesome_sql()
838*/
839#define BTS_SELECT 0x000001
840#define BTS_NONSELECT 0x000002
841#define BTS_BADFUNC 0x000004
drh13736992022-06-18 20:20:30 +0000842#define BTS_BADPRAGMA 0x000008 /* Sticky for rest of the script */
drha1f79da2022-06-14 19:12:25 +0000843
844/*
drha47e7092019-01-25 04:00:14 +0000845** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and
846** "PRAGMA parser_trace" since they can dramatically increase the
847** amount of output without actually testing anything useful.
848**
drh8df01492021-03-18 14:36:19 +0000849** Also block ATTACH if attaching a file from the filesystem.
drha47e7092019-01-25 04:00:14 +0000850*/
851static int block_troublesome_sql(
drha1f79da2022-06-14 19:12:25 +0000852 void *pClientData,
drha47e7092019-01-25 04:00:14 +0000853 int eCode,
854 const char *zArg1,
855 const char *zArg2,
856 const char *zArg3,
857 const char *zArg4
858){
drh13736992022-06-18 20:20:30 +0000859 unsigned int *pBtsFlags = (unsigned int*)pClientData;
860
drha47e7092019-01-25 04:00:14 +0000861 (void)zArg3;
862 (void)zArg4;
drha1f79da2022-06-14 19:12:25 +0000863 switch( eCode ){
864 case SQLITE_PRAGMA: {
865 if( sqlite3_stricmp("busy_timeout",zArg1)==0
866 && (zArg2==0 || strtoll(zArg2,0,0)>100 || strtoll(zArg2,0,10)>100)
drh8df01492021-03-18 14:36:19 +0000867 ){
868 return SQLITE_DENY;
drh13736992022-06-18 20:20:30 +0000869 }else if( sqlite3_stricmp("hard_heap_limit", zArg1)==0
870 || sqlite3_stricmp("reverse_unordered_selects", zArg1)==0
871 ){
872 /* BTS_BADPRAGMA is sticky. A hard_heap_limit or
873 ** revert_unordered_selects should inhibit all future attempts
874 ** at verifying query invariants */
875 *pBtsFlags |= BTS_BADPRAGMA;
drha1f79da2022-06-14 19:12:25 +0000876 }else if( eVerbosity==0 ){
877 if( sqlite3_strnicmp("vdbe_", zArg1, 5)==0
878 || sqlite3_stricmp("parser_trace", zArg1)==0
879 || sqlite3_stricmp("temp_store_directory", zArg1)==0
880 ){
881 return SQLITE_DENY;
drh13736992022-06-18 20:20:30 +0000882 }
drha1f79da2022-06-14 19:12:25 +0000883 }else if( sqlite3_stricmp("oom",zArg1)==0
884 && zArg2!=0 && zArg2[0]!=0 ){
885 oomCounter = atoi(zArg2);
drh8df01492021-03-18 14:36:19 +0000886 }
drh13736992022-06-18 20:20:30 +0000887 *pBtsFlags |= BTS_NONSELECT;
drha1f79da2022-06-14 19:12:25 +0000888 break;
drh39b3bcf2020-03-02 16:31:21 +0000889 }
drha1f79da2022-06-14 19:12:25 +0000890 case SQLITE_ATTACH: {
891 /* Deny the ATTACH if it is attaching anything other than an in-memory
892 ** database. */
drh13736992022-06-18 20:20:30 +0000893 *pBtsFlags |= BTS_NONSELECT;
drha1f79da2022-06-14 19:12:25 +0000894 if( zArg1==0 ) return SQLITE_DENY;
895 if( strcmp(zArg1,":memory:")==0 ) return SQLITE_OK;
896 if( sqlite3_strglob("file:*[?]vfs=memdb", zArg1)==0
897 && sqlite3_strglob("file:*[^/a-zA-Z0-9_.]*[?]vfs=memdb", zArg1)!=0
898 ){
899 return SQLITE_OK;
900 }
901 return SQLITE_DENY;
drh657a7a62021-03-09 13:12:58 +0000902 }
drha1f79da2022-06-14 19:12:25 +0000903 case SQLITE_SELECT: {
drh13736992022-06-18 20:20:30 +0000904 *pBtsFlags |= BTS_SELECT;
drha1f79da2022-06-14 19:12:25 +0000905 break;
906 }
907 case SQLITE_FUNCTION: {
908 static const char *azBadFuncs[] = {
drh13736992022-06-18 20:20:30 +0000909 "avg",
910 "count",
911 "cume_dist",
drh36f904f2022-06-17 15:11:31 +0000912 "current_date",
913 "current_time",
914 "current_timestamp",
915 "date",
916 "datetime",
drh13736992022-06-18 20:20:30 +0000917 "decimal_sum",
918 "dense_rank",
919 "first_value",
920 "geopoly_group_bbox",
921 "group_concat",
drhc2beb0d2022-06-17 17:11:51 +0000922 "implies_nonnull_row",
drh13736992022-06-18 20:20:30 +0000923 "json_group_array",
924 "json_group_object",
drh36f904f2022-06-17 15:11:31 +0000925 "julianday",
drh13736992022-06-18 20:20:30 +0000926 "lag",
927 "last_value",
928 "lead",
929 "max",
930 "min",
931 "nth_value",
932 "ntile",
933 "percent_rank",
drha1f79da2022-06-14 19:12:25 +0000934 "random",
935 "randomblob",
drh13736992022-06-18 20:20:30 +0000936 "rank",
937 "row_number",
drhf26e4512022-06-17 16:52:54 +0000938 "sqlite_offset",
drh36f904f2022-06-17 15:11:31 +0000939 "strftime",
drh13736992022-06-18 20:20:30 +0000940 "sum",
drh36f904f2022-06-17 15:11:31 +0000941 "time",
drh13736992022-06-18 20:20:30 +0000942 "total",
drh36f904f2022-06-17 15:11:31 +0000943 "unixepoch",
drha1f79da2022-06-14 19:12:25 +0000944 };
drhc2beb0d2022-06-17 17:11:51 +0000945 int first, last;
946 first = 0;
947 last = sizeof(azBadFuncs)/sizeof(azBadFuncs[0]) - 1;
948 do{
949 int mid = (first+last)/2;
950 int c = sqlite3_stricmp(azBadFuncs[mid], zArg2);
951 if( c<0 ){
952 first = mid+1;
953 }else if( c>0 ){
954 last = mid-1;
955 }else{
drh13736992022-06-18 20:20:30 +0000956 *pBtsFlags |= BTS_BADFUNC;
drha1f79da2022-06-14 19:12:25 +0000957 break;
958 }
drhc2beb0d2022-06-17 17:11:51 +0000959 }while( first<=last );
drha1f79da2022-06-14 19:12:25 +0000960 break;
961 }
962 case SQLITE_READ: {
963 /* Benign */
964 break;
965 }
966 default: {
drh13736992022-06-18 20:20:30 +0000967 *pBtsFlags |= BTS_NONSELECT;
drha1f79da2022-06-14 19:12:25 +0000968 }
drha47e7092019-01-25 04:00:14 +0000969 }
970 return SQLITE_OK;
971}
972
drha1f79da2022-06-14 19:12:25 +0000973/* Implementation found in fuzzinvariant.c */
drh71b65e82022-10-28 18:35:06 +0000974extern int fuzz_invariant(
drha1f79da2022-06-14 19:12:25 +0000975 sqlite3 *db, /* The database connection */
976 sqlite3_stmt *pStmt, /* Test statement stopped on an SQLITE_ROW */
977 int iCnt, /* Invariant sequence number, starting at 0 */
978 int iRow, /* The row number for pStmt */
drh63880362022-06-17 16:09:47 +0000979 int nRow, /* Total number of output rows */
drhe3bf2c82022-06-15 16:26:37 +0000980 int *pbCorrupt, /* IN/OUT: Flag indicating a corrupt database file */
981 int eVerbosity /* How much debugging output */
drha1f79da2022-06-14 19:12:25 +0000982);
983
drh71b65e82022-10-28 18:35:06 +0000984/* Implementation of sqlite_dbdata and sqlite_dbptr */
985extern int sqlite3_dbdata_init(sqlite3*,const char**,void*);
986
987
988/*
989** This function is used as a callback by the recover extension. Simply
990** print the supplied SQL statement to stdout.
991*/
992static int recoverSqlCb(void *pCtx, const char *zSql){
993 if( eVerbosity>=2 ){
994 printf("%s\n", zSql);
995 }
996 return SQLITE_OK;
997}
998
999/*
1000** This function is called to recover data from the database.
1001*/
1002static int recoverDatabase(sqlite3 *db){
drh2cdcc7f2022-11-02 14:08:26 +00001003 int rc; /* Return code from this routine */
1004 const char *zLAF = "lost_and_found"; /* Name of "lost_and_found" table */
1005 int bFreelist = 1; /* True to scan the freelist */
1006 int bRowids = 1; /* True to restore ROWID values */
1007 sqlite3_recover *p; /* The recovery object */
drh71b65e82022-10-28 18:35:06 +00001008
1009 p = sqlite3_recover_init_sql(db, "main", recoverSqlCb, 0);
drh71b65e82022-10-28 18:35:06 +00001010 sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
1011 sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
1012 sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
1013 sqlite3_recover_run(p);
1014 if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
1015 const char *zErr = sqlite3_recover_errmsg(p);
1016 int errCode = sqlite3_recover_errcode(p);
1017 if( eVerbosity>0 ){
1018 printf("recovery error: %s (%d)\n", zErr, errCode);
1019 }
1020 }
1021 rc = sqlite3_recover_finish(p);
1022 if( eVerbosity>0 && rc ){
1023 printf("recovery returns error code %d\n", rc);
1024 }
1025 return rc;
1026}
1027
drha47e7092019-01-25 04:00:14 +00001028/*
1029** Run the SQL text
1030*/
drha1f79da2022-06-14 19:12:25 +00001031static int runDbSql(sqlite3 *db, const char *zSql, unsigned int *pBtsFlags){
drha47e7092019-01-25 04:00:14 +00001032 int rc;
1033 sqlite3_stmt *pStmt;
drha1f79da2022-06-14 19:12:25 +00001034 int bCorrupt = 0;
drhaf638922019-02-07 00:17:36 +00001035 while( isspace(zSql[0]&0x7f) ) zSql++;
drha47e7092019-01-25 04:00:14 +00001036 if( zSql[0]==0 ) return SQLITE_OK;
drhdf216592019-01-25 04:43:26 +00001037 if( eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +00001038 printf("RUNNING-SQL: [%s]\n", zSql);
1039 fflush(stdout);
1040 }
drh13736992022-06-18 20:20:30 +00001041 (*pBtsFlags) &= ~BTS_BADPRAGMA;
drha47e7092019-01-25 04:00:14 +00001042 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1043 if( rc==SQLITE_OK ){
drha1f79da2022-06-14 19:12:25 +00001044 int nRow = 0;
drha47e7092019-01-25 04:00:14 +00001045 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
drha1f79da2022-06-14 19:12:25 +00001046 nRow++;
drh63880362022-06-17 16:09:47 +00001047 if( eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +00001048 int j;
1049 for(j=0; j<sqlite3_column_count(pStmt); j++){
1050 if( j ) printf(",");
1051 switch( sqlite3_column_type(pStmt, j) ){
1052 case SQLITE_NULL: {
1053 printf("NULL");
1054 break;
1055 }
1056 case SQLITE_INTEGER:
1057 case SQLITE_FLOAT: {
1058 printf("%s", sqlite3_column_text(pStmt, j));
1059 break;
1060 }
1061 case SQLITE_BLOB: {
1062 int n = sqlite3_column_bytes(pStmt, j);
1063 int i;
1064 const unsigned char *a;
1065 a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
1066 printf("x'");
1067 for(i=0; i<n; i++){
1068 printf("%02x", a[i]);
1069 }
1070 printf("'");
1071 break;
1072 }
1073 case SQLITE_TEXT: {
1074 int n = sqlite3_column_bytes(pStmt, j);
1075 int i;
1076 const unsigned char *a;
1077 a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
1078 printf("'");
1079 for(i=0; i<n; i++){
1080 if( a[i]=='\'' ){
1081 printf("''");
1082 }else{
1083 putchar(a[i]);
1084 }
1085 }
1086 printf("'");
1087 break;
1088 }
1089 } /* End switch() */
1090 } /* End for() */
1091 printf("\n");
1092 fflush(stdout);
drhdf216592019-01-25 04:43:26 +00001093 } /* End if( eVerbosity>=5 ) */
drha47e7092019-01-25 04:00:14 +00001094 } /* End while( SQLITE_ROW */
drhc68fb842022-06-17 15:52:43 +00001095 if( rc==SQLITE_DONE ){
1096 if( (*pBtsFlags)==BTS_SELECT
drhc68fb842022-06-17 15:52:43 +00001097 && !sqlite3_stmt_isexplain(pStmt)
1098 && nRow>0
1099 ){
drh63880362022-06-17 16:09:47 +00001100 int iRow = 0;
drhc68fb842022-06-17 15:52:43 +00001101 sqlite3_reset(pStmt);
1102 while( sqlite3_step(pStmt)==SQLITE_ROW ){
1103 int iCnt = 0;
drh63880362022-06-17 16:09:47 +00001104 iRow++;
drhc68fb842022-06-17 15:52:43 +00001105 for(iCnt=0; iCnt<99999; iCnt++){
drh63880362022-06-17 16:09:47 +00001106 rc = fuzz_invariant(db, pStmt, iCnt, iRow, nRow,
1107 &bCorrupt, eVerbosity);
drhc68fb842022-06-17 15:52:43 +00001108 if( rc==SQLITE_DONE ) break;
1109 if( rc!=SQLITE_ERROR ) g.nInvariant++;
1110 if( eVerbosity>0 ){
1111 if( rc==SQLITE_OK ){
1112 printf("invariant-check: ok\n");
1113 }else if( rc==SQLITE_CORRUPT ){
1114 printf("invariant-check: failed due to database corruption\n");
1115 }
1116 }
1117 }
1118 }
1119 }
1120 }else if( eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +00001121 printf("SQL-ERROR: (%d) %s\n", rc, sqlite3_errmsg(db));
1122 fflush(stdout);
1123 }
drhdf216592019-01-25 04:43:26 +00001124 }else if( eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +00001125 printf("SQL-ERROR (%d): %s\n", rc, sqlite3_errmsg(db));
1126 fflush(stdout);
1127 } /* End if( SQLITE_OK ) */
1128 return sqlite3_finalize(pStmt);
1129}
1130
1131/* Invoke this routine to run a single test case */
drh075201e2021-10-27 12:05:28 +00001132int runCombinedDbSqlInput(
1133 const uint8_t *aData, /* Combined DB+SQL content */
1134 size_t nByte, /* Size of aData in bytes */
1135 int iTimeout, /* Use this timeout */
1136 int bScript, /* If true, just render CLI output */
1137 int iSqlId /* SQL identifier */
1138){
drha47e7092019-01-25 04:00:14 +00001139 int rc; /* SQLite API return value */
1140 int iSql; /* Index in aData[] of start of SQL */
1141 unsigned char *aDb = 0; /* Decoded database content */
1142 int nDb = 0; /* Size of the decoded database */
1143 int i; /* Loop counter */
1144 int j; /* Start of current SQL statement */
1145 char *zSql = 0; /* SQL text to run */
1146 int nSql; /* Bytes of SQL text */
1147 FuzzCtx cx; /* Fuzzing context */
drha1f79da2022-06-14 19:12:25 +00001148 unsigned int btsFlags = 0; /* Parsing flags */
drha47e7092019-01-25 04:00:14 +00001149
1150 if( nByte<10 ) return 0;
1151 if( sqlite3_initialize() ) return 0;
1152 if( sqlite3_memory_used()!=0 ){
1153 int nAlloc = 0;
1154 int nNotUsed = 0;
1155 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
drh672f07c2020-10-20 14:40:53 +00001156 fprintf(stderr,"memory leak prior to test start:"
1157 " %lld bytes in %d allocations\n",
drha47e7092019-01-25 04:00:14 +00001158 sqlite3_memory_used(), nAlloc);
1159 exit(1);
1160 }
1161 memset(&cx, 0, sizeof(cx));
1162 iSql = decodeDatabase((unsigned char*)aData, (int)nByte, &aDb, &nDb);
1163 if( iSql<0 ) return 0;
drhed457032019-01-25 17:51:06 +00001164 nSql = (int)(nByte - iSql);
drh075201e2021-10-27 12:05:28 +00001165 if( bScript ){
1166 char zName[100];
1167 sqlite3_snprintf(sizeof(zName),zName,"dbsql%06d.db",iSqlId);
1168 renderDbSqlForCLI(stdout, zName, aDb, nDb,
1169 (unsigned char*)(aData+iSql), nSql);
1170 sqlite3_free(aDb);
1171 return 0;
1172 }
drhdf216592019-01-25 04:43:26 +00001173 if( eVerbosity>=3 ){
drha47e7092019-01-25 04:00:14 +00001174 printf(
1175 "****** %d-byte input, %d-byte database, %d-byte script "
1176 "******\n", (int)nByte, nDb, nSql);
1177 fflush(stdout);
1178 }
1179 rc = sqlite3_open(0, &cx.db);
drh672f07c2020-10-20 14:40:53 +00001180 if( rc ){
1181 sqlite3_free(aDb);
1182 return 1;
1183 }
drha47e7092019-01-25 04:00:14 +00001184 if( bVdbeDebug ){
1185 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
1186 }
1187
1188 /* Invoke the progress handler frequently to check to see if we
1189 ** are taking too long. The progress handler will return true
drhed457032019-01-25 17:51:06 +00001190 ** (which will block further processing) if more than giTimeout seconds have
drha47e7092019-01-25 04:00:14 +00001191 ** elapsed since the start of the test.
1192 */
1193 cx.iLastCb = timeOfDay();
drh237f41a2020-12-21 12:14:59 +00001194 cx.iCutoffTime = cx.iLastCb + (iTimeout<giTimeout ? iTimeout : giTimeout);
drha47e7092019-01-25 04:00:14 +00001195 cx.mxCb = mxProgressCb;
1196#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1197 sqlite3_progress_handler(cx.db, 10, progress_handler, (void*)&cx);
1198#endif
1199
1200 /* Set a limit on the maximum size of a prepared statement, and the
1201 ** maximum length of a string or blob */
1202 if( vdbeOpLimit>0 ){
1203 sqlite3_limit(cx.db, SQLITE_LIMIT_VDBE_OP, vdbeOpLimit);
1204 }
1205 if( lengthLimit>0 ){
1206 sqlite3_limit(cx.db, SQLITE_LIMIT_LENGTH, lengthLimit);
1207 }
drhbe03cc92020-01-20 14:42:09 +00001208 if( depthLimit>0 ){
1209 sqlite3_limit(cx.db, SQLITE_LIMIT_EXPR_DEPTH, depthLimit);
1210 }
drh4b3282d2020-04-07 15:07:11 +00001211 sqlite3_limit(cx.db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 100);
drh31999c52019-11-14 17:46:32 +00001212 sqlite3_hard_heap_limit64(heapLimit);
drha47e7092019-01-25 04:00:14 +00001213
1214 if( nDb>=20 && aDb[18]==2 && aDb[19]==2 ){
1215 aDb[18] = aDb[19] = 1;
1216 }
1217 rc = sqlite3_deserialize(cx.db, "main", aDb, nDb, nDb,
1218 SQLITE_DESERIALIZE_RESIZEABLE |
1219 SQLITE_DESERIALIZE_FREEONCLOSE);
1220 if( rc ){
1221 fprintf(stderr, "sqlite3_deserialize() failed with %d\n", rc);
1222 goto testrun_finished;
1223 }
1224 if( maxDbSize>0 ){
1225 sqlite3_int64 x = maxDbSize;
1226 sqlite3_file_control(cx.db, "main", SQLITE_FCNTL_SIZE_LIMIT, &x);
1227 }
1228
drh725a9c72019-01-25 13:03:38 +00001229 /* For high debugging levels, turn on debug mode */
1230 if( eVerbosity>=5 ){
1231 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON;", 0, 0, 0);
1232 }
1233
drha47e7092019-01-25 04:00:14 +00001234 /* Block debug pragmas and ATTACH/DETACH. But wait until after
1235 ** deserialize to do this because deserialize depends on ATTACH */
drha1f79da2022-06-14 19:12:25 +00001236 sqlite3_set_authorizer(cx.db, block_troublesome_sql, &btsFlags);
drha47e7092019-01-25 04:00:14 +00001237
drh71b65e82022-10-28 18:35:06 +00001238 /* Add the vt02 virtual table */
drh0fab1092022-02-04 19:13:18 +00001239 sqlite3_vt02_init(cx.db, 0, 0);
drh71b65e82022-10-28 18:35:06 +00001240
1241 /* Add support for sqlite_dbdata and sqlite_dbptr virtual tables used
1242 ** by the recovery API */
1243 sqlite3_dbdata_init(cx.db, 0, 0);
drh0fab1092022-02-04 19:13:18 +00001244
drha47e7092019-01-25 04:00:14 +00001245 /* Consistent PRNG seed */
drh319deef2021-04-04 23:56:15 +00001246#ifdef SQLITE_TESTCTRL_PRNG_SEED
1247 sqlite3_table_column_metadata(cx.db, 0, "x", 0, 0, 0, 0, 0, 0);
1248 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, cx.db);
1249#else
drha47e7092019-01-25 04:00:14 +00001250 sqlite3_randomness(0,0);
drh319deef2021-04-04 23:56:15 +00001251#endif
drha47e7092019-01-25 04:00:14 +00001252
drh71b65e82022-10-28 18:35:06 +00001253 /* Run recovery on the initial database, just to make sure recovery
1254 ** works. */
1255 if( !bNoRecover ){
1256 recoverDatabase(cx.db);
1257 }
1258
drha47e7092019-01-25 04:00:14 +00001259 zSql = sqlite3_malloc( nSql + 1 );
1260 if( zSql==0 ){
1261 fprintf(stderr, "Out of memory!\n");
1262 }else{
1263 memcpy(zSql, aData+iSql, nSql);
1264 zSql[nSql] = 0;
1265 for(i=j=0; zSql[i]; i++){
1266 if( zSql[i]==';' ){
1267 char cSaved = zSql[i+1];
1268 zSql[i+1] = 0;
1269 if( sqlite3_complete(zSql+j) ){
drha1f79da2022-06-14 19:12:25 +00001270 rc = runDbSql(cx.db, zSql+j, &btsFlags);
drha47e7092019-01-25 04:00:14 +00001271 j = i+1;
1272 }
1273 zSql[i+1] = cSaved;
1274 if( rc==SQLITE_INTERRUPT || progress_handler(&cx) ){
1275 goto testrun_finished;
1276 }
1277 }
1278 }
1279 if( j<i ){
drha1f79da2022-06-14 19:12:25 +00001280 runDbSql(cx.db, zSql+j, &btsFlags);
drha47e7092019-01-25 04:00:14 +00001281 }
1282 }
1283testrun_finished:
1284 sqlite3_free(zSql);
1285 rc = sqlite3_close(cx.db);
1286 if( rc!=SQLITE_OK ){
1287 fprintf(stdout, "sqlite3_close() returns %d\n", rc);
1288 }
drh075201e2021-10-27 12:05:28 +00001289 if( eVerbosity>=2 && !bScript ){
drha47e7092019-01-25 04:00:14 +00001290 fprintf(stdout, "Peak memory usages: %f MB\n",
1291 sqlite3_memory_highwater(1) / 1000000.0);
1292 }
1293 if( sqlite3_memory_used()!=0 ){
1294 int nAlloc = 0;
1295 int nNotUsed = 0;
1296 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
1297 fprintf(stderr,"Memory leak: %lld bytes in %d allocations\n",
1298 sqlite3_memory_used(), nAlloc);
1299 exit(1);
1300 }
drh319deef2021-04-04 23:56:15 +00001301 sqlite3_hard_heap_limit64(0);
1302 sqlite3_soft_heap_limit64(0);
drha47e7092019-01-25 04:00:14 +00001303 return 0;
1304}
1305
1306/*
1307** END of the dbsqlfuzz code
1308***************************************************************************/
1309
1310/* Look at a SQL text and try to determine if it begins with a database
1311** description, such as would be found in a dbsqlfuzz test case. Return
1312** true if this does appear to be a dbsqlfuzz test case and false otherwise.
1313*/
1314static int isDbSql(unsigned char *a, int n){
drhdf216592019-01-25 04:43:26 +00001315 unsigned char buf[12];
1316 int i;
drha47e7092019-01-25 04:00:14 +00001317 if( n>4 && memcmp(a,"\n--\n",4)==0 ) return 1;
1318 while( n>0 && isspace(a[0]) ){ a++; n--; }
drhdf216592019-01-25 04:43:26 +00001319 for(i=0; n>0 && i<8; n--, a++){
1320 if( isxdigit(a[0]) ) buf[i++] = a[0];
1321 }
1322 if( i==8 && memcmp(buf,"53514c69",8)==0 ) return 1;
drha47e7092019-01-25 04:00:14 +00001323 return 0;
1324}
1325
drhe5da9352019-01-27 01:11:40 +00001326/* Implementation of the isdbsql(TEXT) SQL function.
1327*/
1328static void isDbSqlFunc(
1329 sqlite3_context *context,
1330 int argc,
1331 sqlite3_value **argv
1332){
1333 int n = sqlite3_value_bytes(argv[0]);
1334 unsigned char *a = (unsigned char*)sqlite3_value_blob(argv[0]);
1335 sqlite3_result_int(context, a!=0 && n>0 && isDbSql(a,n));
1336}
drha47e7092019-01-25 04:00:14 +00001337
drh3b74d032015-05-25 18:48:19 +00001338/* Methods for the VHandle object
1339*/
1340static int inmemClose(sqlite3_file *pFile){
1341 VHandle *p = (VHandle*)pFile;
1342 VFile *pVFile = p->pVFile;
1343 pVFile->nRef--;
1344 if( pVFile->nRef==0 && pVFile->zFilename==0 ){
1345 pVFile->sz = -1;
1346 free(pVFile->a);
1347 pVFile->a = 0;
1348 }
1349 return SQLITE_OK;
1350}
1351static int inmemRead(
1352 sqlite3_file *pFile, /* Read from this open file */
1353 void *pData, /* Store content in this buffer */
1354 int iAmt, /* Bytes of content */
1355 sqlite3_int64 iOfst /* Start reading here */
1356){
1357 VHandle *pHandle = (VHandle*)pFile;
1358 VFile *pVFile = pHandle->pVFile;
1359 if( iOfst<0 || iOfst>=pVFile->sz ){
1360 memset(pData, 0, iAmt);
1361 return SQLITE_IOERR_SHORT_READ;
1362 }
1363 if( iOfst+iAmt>pVFile->sz ){
1364 memset(pData, 0, iAmt);
drh1573dc32015-05-25 22:29:26 +00001365 iAmt = (int)(pVFile->sz - iOfst);
drhe45985b2018-12-14 02:29:56 +00001366 memcpy(pData, pVFile->a + iOfst, iAmt);
drh3b74d032015-05-25 18:48:19 +00001367 return SQLITE_IOERR_SHORT_READ;
1368 }
drhaca7ea12015-05-25 23:14:37 +00001369 memcpy(pData, pVFile->a + iOfst, iAmt);
drh3b74d032015-05-25 18:48:19 +00001370 return SQLITE_OK;
1371}
1372static int inmemWrite(
1373 sqlite3_file *pFile, /* Write to this file */
1374 const void *pData, /* Content to write */
1375 int iAmt, /* bytes to write */
1376 sqlite3_int64 iOfst /* Start writing here */
1377){
1378 VHandle *pHandle = (VHandle*)pFile;
1379 VFile *pVFile = pHandle->pVFile;
1380 if( iOfst+iAmt > pVFile->sz ){
drha9542b12015-05-25 19:35:42 +00001381 if( iOfst+iAmt >= MX_FILE_SZ ){
1382 return SQLITE_FULL;
1383 }
drh1573dc32015-05-25 22:29:26 +00001384 pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt));
drh908aced2015-05-26 16:12:45 +00001385 if( iOfst > pVFile->sz ){
1386 memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz));
1387 }
drh1573dc32015-05-25 22:29:26 +00001388 pVFile->sz = (int)(iOfst + iAmt);
drh3b74d032015-05-25 18:48:19 +00001389 }
1390 memcpy(pVFile->a + iOfst, pData, iAmt);
1391 return SQLITE_OK;
1392}
1393static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){
1394 VHandle *pHandle = (VHandle*)pFile;
1395 VFile *pVFile = pHandle->pVFile;
drh1573dc32015-05-25 22:29:26 +00001396 if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize;
drh3b74d032015-05-25 18:48:19 +00001397 return SQLITE_OK;
1398}
1399static int inmemSync(sqlite3_file *pFile, int flags){
1400 return SQLITE_OK;
1401}
1402static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){
1403 *pSize = ((VHandle*)pFile)->pVFile->sz;
1404 return SQLITE_OK;
1405}
1406static int inmemLock(sqlite3_file *pFile, int type){
1407 return SQLITE_OK;
1408}
1409static int inmemUnlock(sqlite3_file *pFile, int type){
1410 return SQLITE_OK;
1411}
1412static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){
1413 *pOut = 0;
1414 return SQLITE_OK;
1415}
1416static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){
1417 return SQLITE_NOTFOUND;
1418}
1419static int inmemSectorSize(sqlite3_file *pFile){
1420 return 512;
1421}
1422static int inmemDeviceCharacteristics(sqlite3_file *pFile){
1423 return
1424 SQLITE_IOCAP_SAFE_APPEND |
1425 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
1426 SQLITE_IOCAP_POWERSAFE_OVERWRITE;
1427}
1428
1429
1430/* Method table for VHandle
1431*/
1432static sqlite3_io_methods VHandleMethods = {
1433 /* iVersion */ 1,
1434 /* xClose */ inmemClose,
1435 /* xRead */ inmemRead,
1436 /* xWrite */ inmemWrite,
1437 /* xTruncate */ inmemTruncate,
1438 /* xSync */ inmemSync,
1439 /* xFileSize */ inmemFileSize,
1440 /* xLock */ inmemLock,
1441 /* xUnlock */ inmemUnlock,
1442 /* xCheck... */ inmemCheckReservedLock,
1443 /* xFileCtrl */ inmemFileControl,
1444 /* xSectorSz */ inmemSectorSize,
1445 /* xDevchar */ inmemDeviceCharacteristics,
1446 /* xShmMap */ 0,
1447 /* xShmLock */ 0,
1448 /* xShmBarrier */ 0,
1449 /* xShmUnmap */ 0,
1450 /* xFetch */ 0,
1451 /* xUnfetch */ 0
1452};
1453
1454/*
1455** Open a new file in the inmem VFS. All files are anonymous and are
1456** delete-on-close.
1457*/
1458static int inmemOpen(
1459 sqlite3_vfs *pVfs,
1460 const char *zFilename,
1461 sqlite3_file *pFile,
1462 int openFlags,
1463 int *pOutFlags
1464){
1465 VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)"");
1466 VHandle *pHandle = (VHandle*)pFile;
drha9542b12015-05-25 19:35:42 +00001467 if( pVFile==0 ){
1468 return SQLITE_FULL;
1469 }
drh3b74d032015-05-25 18:48:19 +00001470 pHandle->pVFile = pVFile;
1471 pVFile->nRef++;
1472 pFile->pMethods = &VHandleMethods;
1473 if( pOutFlags ) *pOutFlags = openFlags;
1474 return SQLITE_OK;
1475}
1476
1477/*
1478** Delete a file by name
1479*/
1480static int inmemDelete(
1481 sqlite3_vfs *pVfs,
1482 const char *zFilename,
1483 int syncdir
1484){
1485 VFile *pVFile = findVFile(zFilename);
1486 if( pVFile==0 ) return SQLITE_OK;
1487 if( pVFile->nRef==0 ){
1488 free(pVFile->zFilename);
1489 pVFile->zFilename = 0;
1490 pVFile->sz = -1;
1491 free(pVFile->a);
1492 pVFile->a = 0;
1493 return SQLITE_OK;
1494 }
1495 return SQLITE_IOERR_DELETE;
1496}
1497
1498/* Check for the existance of a file
1499*/
1500static int inmemAccess(
1501 sqlite3_vfs *pVfs,
1502 const char *zFilename,
1503 int flags,
1504 int *pResOut
1505){
1506 VFile *pVFile = findVFile(zFilename);
1507 *pResOut = pVFile!=0;
1508 return SQLITE_OK;
1509}
1510
1511/* Get the canonical pathname for a file
1512*/
1513static int inmemFullPathname(
1514 sqlite3_vfs *pVfs,
1515 const char *zFilename,
1516 int nOut,
1517 char *zOut
1518){
1519 sqlite3_snprintf(nOut, zOut, "%s", zFilename);
1520 return SQLITE_OK;
1521}
1522
drhbeaf5142016-12-26 00:15:56 +00001523/* Always use the same random see, for repeatability.
1524*/
1525static int inmemRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
1526 memset(zBuf, 0, nBuf);
1527 memcpy(zBuf, &g.uRandom, nBuf<sizeof(g.uRandom) ? nBuf : sizeof(g.uRandom));
1528 return nBuf;
1529}
1530
drh3b74d032015-05-25 18:48:19 +00001531/*
1532** Register the VFS that reads from the g.aFile[] set of files.
1533*/
drhbeaf5142016-12-26 00:15:56 +00001534static void inmemVfsRegister(int makeDefault){
drh3b74d032015-05-25 18:48:19 +00001535 static sqlite3_vfs inmemVfs;
1536 sqlite3_vfs *pDefault = sqlite3_vfs_find(0);
drh5337dac2015-11-25 15:15:03 +00001537 inmemVfs.iVersion = 3;
drh3b74d032015-05-25 18:48:19 +00001538 inmemVfs.szOsFile = sizeof(VHandle);
1539 inmemVfs.mxPathname = 200;
1540 inmemVfs.zName = "inmem";
1541 inmemVfs.xOpen = inmemOpen;
1542 inmemVfs.xDelete = inmemDelete;
1543 inmemVfs.xAccess = inmemAccess;
1544 inmemVfs.xFullPathname = inmemFullPathname;
drhbeaf5142016-12-26 00:15:56 +00001545 inmemVfs.xRandomness = inmemRandomness;
drh3b74d032015-05-25 18:48:19 +00001546 inmemVfs.xSleep = pDefault->xSleep;
drh5337dac2015-11-25 15:15:03 +00001547 inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64;
drhbeaf5142016-12-26 00:15:56 +00001548 sqlite3_vfs_register(&inmemVfs, makeDefault);
drh3b74d032015-05-25 18:48:19 +00001549};
1550
drh3b74d032015-05-25 18:48:19 +00001551/*
drhe5c5f2c2015-05-26 00:28:08 +00001552** Allowed values for the runFlags parameter to runSql()
1553*/
1554#define SQL_TRACE 0x0001 /* Print each SQL statement as it is prepared */
1555#define SQL_OUTPUT 0x0002 /* Show the SQL output */
1556
1557/*
drh3b74d032015-05-25 18:48:19 +00001558** Run multiple commands of SQL. Similar to sqlite3_exec(), but does not
1559** stop if an error is encountered.
1560*/
drhe5c5f2c2015-05-26 00:28:08 +00001561static void runSql(sqlite3 *db, const char *zSql, unsigned runFlags){
drh3b74d032015-05-25 18:48:19 +00001562 const char *zMore;
1563 sqlite3_stmt *pStmt;
1564
1565 while( zSql && zSql[0] ){
1566 zMore = 0;
1567 pStmt = 0;
1568 sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore);
drh4ab31472015-05-25 22:17:06 +00001569 if( zMore==zSql ) break;
drhe5c5f2c2015-05-26 00:28:08 +00001570 if( runFlags & SQL_TRACE ){
drh4ab31472015-05-25 22:17:06 +00001571 const char *z = zSql;
1572 int n;
drhc56fac72015-10-29 13:48:15 +00001573 while( z<zMore && ISSPACE(z[0]) ) z++;
drh4ab31472015-05-25 22:17:06 +00001574 n = (int)(zMore - z);
drhc56fac72015-10-29 13:48:15 +00001575 while( n>0 && ISSPACE(z[n-1]) ) n--;
drh4ab31472015-05-25 22:17:06 +00001576 if( n==0 ) break;
1577 if( pStmt==0 ){
1578 printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db));
1579 }else{
1580 printf("TRACE: %.*s\n", n, z);
1581 }
1582 }
drh3b74d032015-05-25 18:48:19 +00001583 zSql = zMore;
1584 if( pStmt ){
drhe5c5f2c2015-05-26 00:28:08 +00001585 if( (runFlags & SQL_OUTPUT)==0 ){
1586 while( SQLITE_ROW==sqlite3_step(pStmt) ){}
1587 }else{
1588 int nCol = -1;
1589 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1590 int i;
1591 if( nCol<0 ){
1592 nCol = sqlite3_column_count(pStmt);
1593 }else if( nCol>0 ){
1594 printf("--------------------------------------------\n");
1595 }
1596 for(i=0; i<nCol; i++){
1597 int eType = sqlite3_column_type(pStmt,i);
1598 printf("%s = ", sqlite3_column_name(pStmt,i));
1599 switch( eType ){
1600 case SQLITE_NULL: {
1601 printf("NULL\n");
1602 break;
1603 }
1604 case SQLITE_INTEGER: {
1605 printf("INT %s\n", sqlite3_column_text(pStmt,i));
1606 break;
1607 }
1608 case SQLITE_FLOAT: {
1609 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i));
1610 break;
1611 }
1612 case SQLITE_TEXT: {
1613 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i));
1614 break;
1615 }
1616 case SQLITE_BLOB: {
1617 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i));
1618 break;
1619 }
1620 }
1621 }
1622 }
1623 }
drh3b74d032015-05-25 18:48:19 +00001624 sqlite3_finalize(pStmt);
drh3b74d032015-05-25 18:48:19 +00001625 }
1626 }
1627}
1628
drha9542b12015-05-25 19:35:42 +00001629/*
drh9a645862015-06-24 12:44:42 +00001630** Rebuild the database file.
1631**
1632** (1) Remove duplicate entries
1633** (2) Put all entries in order
1634** (3) Vacuum
1635*/
drhe5da9352019-01-27 01:11:40 +00001636static void rebuild_database(sqlite3 *db, int dbSqlOnly){
drh9a645862015-06-24 12:44:42 +00001637 int rc;
drhe5da9352019-01-27 01:11:40 +00001638 char *zSql;
1639 zSql = sqlite3_mprintf(
drh9a645862015-06-24 12:44:42 +00001640 "BEGIN;\n"
1641 "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n"
1642 "DELETE FROM db;\n"
drh5ecf9032018-05-08 12:49:53 +00001643 "INSERT INTO db(dbid, dbcontent) "
1644 " SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n"
drh9a645862015-06-24 12:44:42 +00001645 "DROP TABLE dbx;\n"
drhe5da9352019-01-27 01:11:40 +00001646 "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql %s;\n"
drh9a645862015-06-24 12:44:42 +00001647 "DELETE FROM xsql;\n"
drh5ecf9032018-05-08 12:49:53 +00001648 "INSERT INTO xsql(sqlid,sqltext) "
1649 " SELECT NULL, sqltext FROM sx ORDER BY 2;\n"
drh9a645862015-06-24 12:44:42 +00001650 "DROP TABLE sx;\n"
1651 "COMMIT;\n"
1652 "PRAGMA page_size=1024;\n"
drhe5da9352019-01-27 01:11:40 +00001653 "VACUUM;\n",
1654 dbSqlOnly ? " WHERE isdbsql(sqltext)" : ""
1655 );
1656 rc = sqlite3_exec(db, zSql, 0, 0, 0);
1657 sqlite3_free(zSql);
drh9a645862015-06-24 12:44:42 +00001658 if( rc ) fatalError("cannot rebuild: %s", sqlite3_errmsg(db));
1659}
1660
1661/*
drh53e66c32015-07-24 15:49:23 +00001662** Return the value of a hexadecimal digit. Return -1 if the input
1663** is not a hex digit.
1664*/
1665static int hexDigitValue(char c){
1666 if( c>='0' && c<='9' ) return c - '0';
1667 if( c>='a' && c<='f' ) return c - 'a' + 10;
1668 if( c>='A' && c<='F' ) return c - 'A' + 10;
1669 return -1;
1670}
1671
1672/*
1673** Interpret zArg as an integer value, possibly with suffixes.
1674*/
1675static int integerValue(const char *zArg){
1676 sqlite3_int64 v = 0;
1677 static const struct { char *zSuffix; int iMult; } aMult[] = {
1678 { "KiB", 1024 },
1679 { "MiB", 1024*1024 },
1680 { "GiB", 1024*1024*1024 },
1681 { "KB", 1000 },
1682 { "MB", 1000000 },
1683 { "GB", 1000000000 },
1684 { "K", 1000 },
1685 { "M", 1000000 },
1686 { "G", 1000000000 },
1687 };
1688 int i;
1689 int isNeg = 0;
1690 if( zArg[0]=='-' ){
1691 isNeg = 1;
1692 zArg++;
1693 }else if( zArg[0]=='+' ){
1694 zArg++;
1695 }
1696 if( zArg[0]=='0' && zArg[1]=='x' ){
1697 int x;
1698 zArg += 2;
1699 while( (x = hexDigitValue(zArg[0]))>=0 ){
1700 v = (v<<4) + x;
1701 zArg++;
1702 }
1703 }else{
drhc56fac72015-10-29 13:48:15 +00001704 while( ISDIGIT(zArg[0]) ){
drh53e66c32015-07-24 15:49:23 +00001705 v = v*10 + zArg[0] - '0';
1706 zArg++;
1707 }
1708 }
1709 for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
1710 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1711 v *= aMult[i].iMult;
1712 break;
1713 }
1714 }
1715 if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648");
1716 return (int)(isNeg? -v : v);
1717}
1718
1719/*
drh725a9c72019-01-25 13:03:38 +00001720** Return the number of "v" characters in a string. Return 0 if there
1721** are any characters in the string other than "v".
1722*/
1723static int numberOfVChar(const char *z){
1724 int N = 0;
1725 while( z[0] && z[0]=='v' ){
1726 z++;
1727 N++;
1728 }
1729 return z[0]==0 ? N : 0;
1730}
1731
1732/*
drha9542b12015-05-25 19:35:42 +00001733** Print sketchy documentation for this utility program
1734*/
1735static void showHelp(void){
1736 printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0);
1737 printf(
1738"Read databases and SQL scripts from SOURCE-DB and execute each script against\n"
1739"each database, checking for crashes and memory leaks.\n"
1740"Options:\n"
drha36e01a2016-08-03 13:40:54 +00001741" --cell-size-check Set the PRAGMA cell_size_check=ON\n"
1742" --dbid N Use only the database where dbid=N\n"
1743" --export-db DIR Write databases to files(s) in DIR. Works with --dbid\n"
1744" --export-sql DIR Write SQL to file(s) in DIR. Also works with --sqlid\n"
1745" --help Show this help text\n"
drh5180d682018-08-06 01:39:31 +00001746" --info Show information about SOURCE-DB w/o running tests\n"
drh672f07c2020-10-20 14:40:53 +00001747" --limit-depth N Limit expression depth to N. Default: 500\n"
1748" --limit-heap N Limit heap memory to N. Default: 100M\n"
drha36e01a2016-08-03 13:40:54 +00001749" --limit-mem N Limit memory used by test SQLite instance to N bytes\n"
1750" --limit-vdbe Panic if any test runs for more than 100,000 cycles\n"
drhba6619d2021-04-23 12:58:16 +00001751" --load-sql FILE.. Load SQL scripts fron files into SOURCE-DB\n"
1752" --load-db FILE.. Load template databases from files into SOURCE_DB\n"
1753" --load-dbsql FILE.. Load dbsqlfuzz outputs into the xsql table\n"
1754" ^^^^------ Use \"-\" for FILE to read filenames from stdin\n"
drha36e01a2016-08-03 13:40:54 +00001755" -m TEXT Add a description to the database\n"
1756" --native-vfs Use the native VFS for initially empty database files\n"
drh174f8552017-03-20 22:58:27 +00001757" --native-malloc Turn off MEMSYS3/5 and Lookaside\n"
drh71b65e82022-10-28 18:35:06 +00001758" --no-recover Do not run recovery on dbsqlfuzz databases\n"
drhea432ba2016-11-11 16:33:47 +00001759" --oss-fuzz Enable OSS-FUZZ testing\n"
drhbeaf5142016-12-26 00:15:56 +00001760" --prng-seed N Seed value for the PRGN inside of SQLite\n"
drh5180d682018-08-06 01:39:31 +00001761" -q|--quiet Reduced output\n"
drha36e01a2016-08-03 13:40:54 +00001762" --rebuild Rebuild and vacuum the database file\n"
1763" --result-trace Show the results of each SQL command\n"
drh075201e2021-10-27 12:05:28 +00001764" --script Output CLI script instead of running tests\n"
drh672f07c2020-10-20 14:40:53 +00001765" --skip N Skip the first N test cases\n"
drhaa0696e2020-04-07 13:08:56 +00001766" --spinner Use a spinner to show progress\n"
drha36e01a2016-08-03 13:40:54 +00001767" --sqlid N Use only SQL where sqlid=N\n"
drh237f41a2020-12-21 12:14:59 +00001768" --timeout N Maximum time for any one test in N millseconds\n"
drha36e01a2016-08-03 13:40:54 +00001769" -v|--verbose Increased output. Repeat for more output.\n"
drh6e1c45e2019-12-18 13:42:04 +00001770" --vdbe-debug Activate VDBE debugging.\n"
drha9542b12015-05-25 19:35:42 +00001771 );
1772}
1773
drh3b74d032015-05-25 18:48:19 +00001774int main(int argc, char **argv){
1775 sqlite3_int64 iBegin; /* Start time of this program */
drh3b74d032015-05-25 18:48:19 +00001776 int quietFlag = 0; /* True if --quiet or -q */
1777 int verboseFlag = 0; /* True if --verbose or -v */
1778 char *zInsSql = 0; /* SQL statement for --load-db or --load-sql */
drh5ecf9032018-05-08 12:49:53 +00001779 int iFirstInsArg = 0; /* First argv[] for --load-db or --load-sql */
drh3b74d032015-05-25 18:48:19 +00001780 sqlite3 *db = 0; /* The open database connection */
drhd9972ef2015-05-26 17:57:56 +00001781 sqlite3_stmt *pStmt; /* A prepared statement */
drh3b74d032015-05-25 18:48:19 +00001782 int rc; /* Result code from SQLite interface calls */
1783 Blob *pSql; /* For looping over SQL scripts */
1784 Blob *pDb; /* For looping over template databases */
1785 int i; /* Loop index for the argv[] loop */
drhe5da9352019-01-27 01:11:40 +00001786 int dbSqlOnly = 0; /* Only use scripts that are dbsqlfuzz */
drha9542b12015-05-25 19:35:42 +00001787 int onlySqlid = -1; /* --sqlid */
1788 int onlyDbid = -1; /* --dbid */
drh15b31282015-05-25 21:59:05 +00001789 int nativeFlag = 0; /* --native-vfs */
drh9a645862015-06-24 12:44:42 +00001790 int rebuildFlag = 0; /* --rebuild */
drhd83e2832015-06-24 14:45:44 +00001791 int vdbeLimitFlag = 0; /* --limit-vdbe */
drh5180d682018-08-06 01:39:31 +00001792 int infoFlag = 0; /* --info */
drh672f07c2020-10-20 14:40:53 +00001793 int nSkip = 0; /* --skip */
drh075201e2021-10-27 12:05:28 +00001794 int bScript = 0; /* --script */
drhaa0696e2020-04-07 13:08:56 +00001795 int bSpinner = 0; /* True for --spinner */
drh94701b02015-06-24 13:25:34 +00001796 int timeoutTest = 0; /* undocumented --timeout-test flag */
drhe5c5f2c2015-05-26 00:28:08 +00001797 int runFlags = 0; /* Flags sent to runSql() */
drhd9972ef2015-05-26 17:57:56 +00001798 char *zMsg = 0; /* Add this message */
1799 int nSrcDb = 0; /* Number of source databases */
1800 char **azSrcDb = 0; /* Array of source database names */
1801 int iSrcDb; /* Loop over all source databases */
1802 int nTest = 0; /* Total number of tests performed */
1803 char *zDbName = ""; /* Appreviated name of a source database */
drh5ecf9032018-05-08 12:49:53 +00001804 const char *zFailCode = 0; /* Value of the TEST_FAILURE env variable */
drh1421d982015-05-27 03:46:18 +00001805 int cellSzCkFlag = 0; /* --cell-size-check */
drh5ecf9032018-05-08 12:49:53 +00001806 int sqlFuzz = 0; /* True for SQL fuzz. False for DB fuzz */
drh237f41a2020-12-21 12:14:59 +00001807 int iTimeout = 120000; /* Default 120-second timeout */
drh31999c52019-11-14 17:46:32 +00001808 int nMem = 0; /* Memory limit override */
drh362b66f2016-11-14 18:27:41 +00001809 int nMemThisDb = 0; /* Memory limit set by the CONFIG table */
drh40e0e0d2015-09-22 18:51:17 +00001810 char *zExpDb = 0; /* Write Databases to files in this directory */
1811 char *zExpSql = 0; /* Write SQL to files in this directory */
drh6653fbe2015-11-13 20:52:49 +00001812 void *pHeap = 0; /* Heap for use by SQLite */
drhea432ba2016-11-11 16:33:47 +00001813 int ossFuzz = 0; /* enable OSS-FUZZ testing */
drh362b66f2016-11-14 18:27:41 +00001814 int ossFuzzThisDb = 0; /* ossFuzz value for this particular database */
drh174f8552017-03-20 22:58:27 +00001815 int nativeMalloc = 0; /* Turn off MEMSYS3/5 and lookaside if true */
drhbeaf5142016-12-26 00:15:56 +00001816 sqlite3_vfs *pDfltVfs; /* The default VFS */
drhf2cf4122018-05-08 13:03:31 +00001817 int openFlags4Data; /* Flags for sqlite3_open_v2() */
drh237f41a2020-12-21 12:14:59 +00001818 int bTimer = 0; /* Show elapse time for each test */
drh725a9c72019-01-25 13:03:38 +00001819 int nV; /* How much to increase verbosity with -vvvv */
drh237f41a2020-12-21 12:14:59 +00001820 sqlite3_int64 tmStart; /* Start of each test */
drh3b74d032015-05-25 18:48:19 +00001821
drhbe536562021-10-23 11:30:35 +00001822 sqlite3_config(SQLITE_CONFIG_URI,1);
drh39b3bcf2020-03-02 16:31:21 +00001823 registerOomSimulator();
drh8055a3e2018-11-21 14:27:34 +00001824 sqlite3_initialize();
drh3b74d032015-05-25 18:48:19 +00001825 iBegin = timeOfDay();
drh94701b02015-06-24 13:25:34 +00001826#ifdef __unix__
drha7648f02019-12-18 13:02:18 +00001827 signal(SIGALRM, signalHandler);
1828 signal(SIGSEGV, signalHandler);
1829 signal(SIGABRT, signalHandler);
drh94701b02015-06-24 13:25:34 +00001830#endif
drh3b74d032015-05-25 18:48:19 +00001831 g.zArgv0 = argv[0];
drhf2cf4122018-05-08 13:03:31 +00001832 openFlags4Data = SQLITE_OPEN_READONLY;
drh4d6fda72015-05-26 18:58:32 +00001833 zFailCode = getenv("TEST_FAILURE");
drhbeaf5142016-12-26 00:15:56 +00001834 pDfltVfs = sqlite3_vfs_find(0);
1835 inmemVfsRegister(1);
drh3b74d032015-05-25 18:48:19 +00001836 for(i=1; i<argc; i++){
1837 const char *z = argv[i];
1838 if( z[0]=='-' ){
1839 z++;
1840 if( z[0]=='-' ) z++;
drh1421d982015-05-27 03:46:18 +00001841 if( strcmp(z,"cell-size-check")==0 ){
1842 cellSzCkFlag = 1;
1843 }else
drha9542b12015-05-25 19:35:42 +00001844 if( strcmp(z,"dbid")==0 ){
1845 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
drh53e66c32015-07-24 15:49:23 +00001846 onlyDbid = integerValue(argv[++i]);
drha9542b12015-05-25 19:35:42 +00001847 }else
drh40e0e0d2015-09-22 18:51:17 +00001848 if( strcmp(z,"export-db")==0 ){
1849 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1850 zExpDb = argv[++i];
1851 }else
drhe5da9352019-01-27 01:11:40 +00001852 if( strcmp(z,"export-sql")==0 || strcmp(z,"export-dbsql")==0 ){
drh40e0e0d2015-09-22 18:51:17 +00001853 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1854 zExpSql = argv[++i];
1855 }else
drh3b74d032015-05-25 18:48:19 +00001856 if( strcmp(z,"help")==0 ){
1857 showHelp();
1858 return 0;
1859 }else
drh5180d682018-08-06 01:39:31 +00001860 if( strcmp(z,"info")==0 ){
1861 infoFlag = 1;
1862 }else
drhbe03cc92020-01-20 14:42:09 +00001863 if( strcmp(z,"limit-depth")==0 ){
1864 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1865 depthLimit = integerValue(argv[++i]);
1866 }else
drh672f07c2020-10-20 14:40:53 +00001867 if( strcmp(z,"limit-heap")==0 ){
1868 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1869 heapLimit = integerValue(argv[++i]);
1870 }else
drh53e66c32015-07-24 15:49:23 +00001871 if( strcmp(z,"limit-mem")==0 ){
1872 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1873 nMem = integerValue(argv[++i]);
1874 }else
drhd83e2832015-06-24 14:45:44 +00001875 if( strcmp(z,"limit-vdbe")==0 ){
1876 vdbeLimitFlag = 1;
1877 }else
drh3b74d032015-05-25 18:48:19 +00001878 if( strcmp(z,"load-sql")==0 ){
drha8781d92020-02-25 20:05:58 +00001879 zInsSql = "INSERT INTO xsql(sqltext)"
1880 "VALUES(CAST(readtextfile(?1) AS text))";
drh3b74d032015-05-25 18:48:19 +00001881 iFirstInsArg = i+1;
drhf2cf4122018-05-08 13:03:31 +00001882 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
drh3b74d032015-05-25 18:48:19 +00001883 break;
1884 }else
1885 if( strcmp(z,"load-db")==0 ){
1886 zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
1887 iFirstInsArg = i+1;
drhf2cf4122018-05-08 13:03:31 +00001888 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
drh3b74d032015-05-25 18:48:19 +00001889 break;
1890 }else
drhe5da9352019-01-27 01:11:40 +00001891 if( strcmp(z,"load-dbsql")==0 ){
drha8781d92020-02-25 20:05:58 +00001892 zInsSql = "INSERT INTO xsql(sqltext)"
drh662bebb2021-10-27 13:16:33 +00001893 "VALUES(readfile(?1))";
drhe5da9352019-01-27 01:11:40 +00001894 iFirstInsArg = i+1;
1895 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1896 dbSqlOnly = 1;
1897 break;
1898 }else
drhd9972ef2015-05-26 17:57:56 +00001899 if( strcmp(z,"m")==0 ){
1900 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1901 zMsg = argv[++i];
drhf2cf4122018-05-08 13:03:31 +00001902 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
drhd9972ef2015-05-26 17:57:56 +00001903 }else
drh174f8552017-03-20 22:58:27 +00001904 if( strcmp(z,"native-malloc")==0 ){
1905 nativeMalloc = 1;
1906 }else
drh15b31282015-05-25 21:59:05 +00001907 if( strcmp(z,"native-vfs")==0 ){
1908 nativeFlag = 1;
1909 }else
drh71b65e82022-10-28 18:35:06 +00001910 if( strcmp(z,"no-recover")==0 ){
1911 bNoRecover = 1;
1912 }else
drhea432ba2016-11-11 16:33:47 +00001913 if( strcmp(z,"oss-fuzz")==0 ){
1914 ossFuzz = 1;
1915 }else
drhbeaf5142016-12-26 00:15:56 +00001916 if( strcmp(z,"prng-seed")==0 ){
1917 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1918 g.uRandom = atoi(argv[++i]);
1919 }else
drh3b74d032015-05-25 18:48:19 +00001920 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
1921 quietFlag = 1;
1922 verboseFlag = 0;
drha47e7092019-01-25 04:00:14 +00001923 eVerbosity = 0;
drh3b74d032015-05-25 18:48:19 +00001924 }else
drh9a645862015-06-24 12:44:42 +00001925 if( strcmp(z,"rebuild")==0 ){
1926 rebuildFlag = 1;
drhf2cf4122018-05-08 13:03:31 +00001927 openFlags4Data = SQLITE_OPEN_READWRITE;
drh9a645862015-06-24 12:44:42 +00001928 }else
drhe5c5f2c2015-05-26 00:28:08 +00001929 if( strcmp(z,"result-trace")==0 ){
1930 runFlags |= SQL_OUTPUT;
1931 }else
drh075201e2021-10-27 12:05:28 +00001932 if( strcmp(z,"script")==0 ){
1933 bScript = 1;
1934 }else
drh672f07c2020-10-20 14:40:53 +00001935 if( strcmp(z,"skip")==0 ){
1936 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1937 nSkip = atoi(argv[++i]);
1938 }else
drhaa0696e2020-04-07 13:08:56 +00001939 if( strcmp(z,"spinner")==0 ){
1940 bSpinner = 1;
1941 }else
drh237f41a2020-12-21 12:14:59 +00001942 if( strcmp(z,"timer")==0 ){
1943 bTimer = 1;
1944 }else
drha9542b12015-05-25 19:35:42 +00001945 if( strcmp(z,"sqlid")==0 ){
1946 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
drh53e66c32015-07-24 15:49:23 +00001947 onlySqlid = integerValue(argv[++i]);
drha9542b12015-05-25 19:35:42 +00001948 }else
drh92298632015-06-24 23:44:30 +00001949 if( strcmp(z,"timeout")==0 ){
1950 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
drh53e66c32015-07-24 15:49:23 +00001951 iTimeout = integerValue(argv[++i]);
drh92298632015-06-24 23:44:30 +00001952 }else
drh94701b02015-06-24 13:25:34 +00001953 if( strcmp(z,"timeout-test")==0 ){
1954 timeoutTest = 1;
1955#ifndef __unix__
1956 fatalError("timeout is not available on non-unix systems");
1957#endif
1958 }else
drh6e1c45e2019-12-18 13:42:04 +00001959 if( strcmp(z,"vdbe-debug")==0 ){
1960 bVdbeDebug = 1;
1961 }else
drh725a9c72019-01-25 13:03:38 +00001962 if( strcmp(z,"verbose")==0 ){
drh3b74d032015-05-25 18:48:19 +00001963 quietFlag = 0;
drh4c9d2282016-02-18 14:03:15 +00001964 verboseFlag++;
drha47e7092019-01-25 04:00:14 +00001965 eVerbosity++;
drh4c9d2282016-02-18 14:03:15 +00001966 if( verboseFlag>1 ) runFlags |= SQL_TRACE;
drh3b74d032015-05-25 18:48:19 +00001967 }else
drh725a9c72019-01-25 13:03:38 +00001968 if( (nV = numberOfVChar(z))>=1 ){
1969 quietFlag = 0;
1970 verboseFlag += nV;
1971 eVerbosity += nV;
1972 if( verboseFlag>1 ) runFlags |= SQL_TRACE;
1973 }else
drha47e7092019-01-25 04:00:14 +00001974 if( strcmp(z,"version")==0 ){
1975 int ii;
drhed457032019-01-25 17:51:06 +00001976 const char *zz;
drha47e7092019-01-25 04:00:14 +00001977 printf("SQLite %s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drhed457032019-01-25 17:51:06 +00001978 for(ii=0; (zz = sqlite3_compileoption_get(ii))!=0; ii++){
1979 printf("%s\n", zz);
drha47e7092019-01-25 04:00:14 +00001980 }
1981 return 0;
1982 }else
drh662bebb2021-10-27 13:16:33 +00001983 if( strcmp(z,"is-dbsql")==0 ){
1984 i++;
1985 for(i++; i<argc; i++){
1986 long nData;
1987 char *aData = readFile(argv[i], &nData);
drhbe2d6fd2021-10-27 15:16:30 +00001988 printf("%d %s\n", isDbSql((unsigned char*)aData,nData), argv[i]);
drh662bebb2021-10-27 13:16:33 +00001989 sqlite3_free(aData);
1990 }
1991 exit(0);
1992 }else
drh3b74d032015-05-25 18:48:19 +00001993 {
1994 fatalError("unknown option: %s", argv[i]);
1995 }
1996 }else{
drhd9972ef2015-05-26 17:57:56 +00001997 nSrcDb++;
1998 azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
1999 azSrcDb[nSrcDb-1] = argv[i];
drh3b74d032015-05-25 18:48:19 +00002000 }
2001 }
drhd9972ef2015-05-26 17:57:56 +00002002 if( nSrcDb==0 ) fatalError("no source database specified");
2003 if( nSrcDb>1 ){
2004 if( zMsg ){
2005 fatalError("cannot change the description of more than one database");
drh3b74d032015-05-25 18:48:19 +00002006 }
drhd9972ef2015-05-26 17:57:56 +00002007 if( zInsSql ){
2008 fatalError("cannot import into more than one database");
2009 }
drh3b74d032015-05-25 18:48:19 +00002010 }
2011
drhd9972ef2015-05-26 17:57:56 +00002012 /* Process each source database separately */
2013 for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
drh48b4bf22021-10-26 22:36:41 +00002014 char *zRawData = 0;
2015 long nRawData = 0;
drha7648f02019-12-18 13:02:18 +00002016 g.zDbFile = azSrcDb[iSrcDb];
drhbeaf5142016-12-26 00:15:56 +00002017 rc = sqlite3_open_v2(azSrcDb[iSrcDb], &db,
drhf2cf4122018-05-08 13:03:31 +00002018 openFlags4Data, pDfltVfs->zName);
drh48b4bf22021-10-26 22:36:41 +00002019 if( rc==SQLITE_OK ){
2020 rc = sqlite3_exec(db, "SELECT count(*) FROM sqlite_schema", 0, 0, 0);
2021 }
drhd9972ef2015-05-26 17:57:56 +00002022 if( rc ){
drh48b4bf22021-10-26 22:36:41 +00002023 sqlite3_close(db);
2024 zRawData = readFile(azSrcDb[iSrcDb], &nRawData);
2025 if( zRawData==0 ){
2026 fatalError("input file \"%s\" is not recognized\n", azSrcDb[iSrcDb]);
2027 }
2028 sqlite3_open(":memory:", &db);
drhd9972ef2015-05-26 17:57:56 +00002029 }
drh5180d682018-08-06 01:39:31 +00002030
2031 /* Print the description, if there is one */
2032 if( infoFlag ){
2033 int n;
2034 zDbName = azSrcDb[iSrcDb];
2035 i = (int)strlen(zDbName) - 1;
2036 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
2037 zDbName += i;
2038 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
2039 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
2040 printf("%s: %s", zDbName, sqlite3_column_text(pStmt,0));
2041 }else{
2042 printf("%s: (empty \"readme\")", zDbName);
2043 }
2044 sqlite3_finalize(pStmt);
2045 sqlite3_prepare_v2(db, "SELECT count(*) FROM db", -1, &pStmt, 0);
2046 if( pStmt
2047 && sqlite3_step(pStmt)==SQLITE_ROW
2048 && (n = sqlite3_column_int(pStmt,0))>0
2049 ){
2050 printf(" - %d DBs", n);
2051 }
2052 sqlite3_finalize(pStmt);
2053 sqlite3_prepare_v2(db, "SELECT count(*) FROM xsql", -1, &pStmt, 0);
2054 if( pStmt
2055 && sqlite3_step(pStmt)==SQLITE_ROW
2056 && (n = sqlite3_column_int(pStmt,0))>0
2057 ){
2058 printf(" - %d scripts", n);
2059 }
2060 sqlite3_finalize(pStmt);
2061 printf("\n");
2062 sqlite3_close(db);
drh48b4bf22021-10-26 22:36:41 +00002063 sqlite3_free(zRawData);
drh5180d682018-08-06 01:39:31 +00002064 continue;
2065 }
2066
drh9a645862015-06-24 12:44:42 +00002067 rc = sqlite3_exec(db,
drhd9972ef2015-05-26 17:57:56 +00002068 "CREATE TABLE IF NOT EXISTS db(\n"
2069 " dbid INTEGER PRIMARY KEY, -- database id\n"
2070 " dbcontent BLOB -- database disk file image\n"
2071 ");\n"
2072 "CREATE TABLE IF NOT EXISTS xsql(\n"
2073 " sqlid INTEGER PRIMARY KEY, -- SQL script id\n"
2074 " sqltext TEXT -- Text of SQL statements to run\n"
2075 ");"
2076 "CREATE TABLE IF NOT EXISTS readme(\n"
2077 " msg TEXT -- Human-readable description of this file\n"
2078 ");", 0, 0, 0);
2079 if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
2080 if( zMsg ){
2081 char *zSql;
2082 zSql = sqlite3_mprintf(
2083 "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
2084 rc = sqlite3_exec(db, zSql, 0, 0, 0);
2085 sqlite3_free(zSql);
2086 if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
2087 }
drh48b4bf22021-10-26 22:36:41 +00002088 if( zRawData ){
2089 zInsSql = "INSERT INTO xsql(sqltext) VALUES(?1)";
2090 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
2091 if( rc ) fatalError("cannot prepare statement [%s]: %s",
2092 zInsSql, sqlite3_errmsg(db));
2093 sqlite3_bind_text(pStmt, 1, zRawData, nRawData, SQLITE_STATIC);
2094 sqlite3_step(pStmt);
2095 rc = sqlite3_reset(pStmt);
2096 if( rc ) fatalError("insert failed for %s", argv[i]);
2097 sqlite3_finalize(pStmt);
2098 rebuild_database(db, dbSqlOnly);
2099 zInsSql = 0;
2100 sqlite3_free(zRawData);
2101 zRawData = 0;
2102 }
drh362b66f2016-11-14 18:27:41 +00002103 ossFuzzThisDb = ossFuzz;
2104
2105 /* If the CONFIG(name,value) table exists, read db-specific settings
2106 ** from that table */
2107 if( sqlite3_table_column_metadata(db,0,"config",0,0,0,0,0,0)==SQLITE_OK ){
drh5ecf9032018-05-08 12:49:53 +00002108 rc = sqlite3_prepare_v2(db, "SELECT name, value FROM config",
2109 -1, &pStmt, 0);
drh362b66f2016-11-14 18:27:41 +00002110 if( rc ) fatalError("cannot prepare query of CONFIG table: %s",
2111 sqlite3_errmsg(db));
2112 while( SQLITE_ROW==sqlite3_step(pStmt) ){
2113 const char *zName = (const char *)sqlite3_column_text(pStmt,0);
2114 if( zName==0 ) continue;
2115 if( strcmp(zName, "oss-fuzz")==0 ){
2116 ossFuzzThisDb = sqlite3_column_int(pStmt,1);
2117 if( verboseFlag ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb);
2118 }
drh31999c52019-11-14 17:46:32 +00002119 if( strcmp(zName, "limit-mem")==0 ){
drh362b66f2016-11-14 18:27:41 +00002120 nMemThisDb = sqlite3_column_int(pStmt,1);
2121 if( verboseFlag ) printf("Config: limit-mem=%d\n", nMemThisDb);
drh362b66f2016-11-14 18:27:41 +00002122 }
2123 }
2124 sqlite3_finalize(pStmt);
2125 }
2126
drhd9972ef2015-05-26 17:57:56 +00002127 if( zInsSql ){
2128 sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
2129 readfileFunc, 0, 0);
drha8781d92020-02-25 20:05:58 +00002130 sqlite3_create_function(db, "readtextfile", 1, SQLITE_UTF8, 0,
2131 readtextfileFunc, 0, 0);
drhe5da9352019-01-27 01:11:40 +00002132 sqlite3_create_function(db, "isdbsql", 1, SQLITE_UTF8, 0,
2133 isDbSqlFunc, 0, 0);
drhd9972ef2015-05-26 17:57:56 +00002134 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
2135 if( rc ) fatalError("cannot prepare statement [%s]: %s",
2136 zInsSql, sqlite3_errmsg(db));
2137 rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
2138 if( rc ) fatalError("cannot start a transaction");
2139 for(i=iFirstInsArg; i<argc; i++){
drhba6619d2021-04-23 12:58:16 +00002140 if( strcmp(argv[i],"-")==0 ){
2141 /* A filename of "-" means read multiple filenames from stdin */
drh15212702021-04-23 13:57:53 +00002142 char zLine[2000];
drhba6619d2021-04-23 12:58:16 +00002143 while( rc==0 && fgets(zLine,sizeof(zLine),stdin)!=0 ){
2144 size_t kk = strlen(zLine);
drh59607242021-04-29 18:03:42 +00002145 while( kk>0 && zLine[kk-1]<=' ' ) kk--;
drh9d41caf2021-07-07 19:44:32 +00002146 sqlite3_bind_text(pStmt, 1, zLine, (int)kk, SQLITE_STATIC);
drh59607242021-04-29 18:03:42 +00002147 if( verboseFlag ) printf("loading %.*s\n", (int)kk, zLine);
drhba6619d2021-04-23 12:58:16 +00002148 sqlite3_step(pStmt);
2149 rc = sqlite3_reset(pStmt);
2150 if( rc ) fatalError("insert failed for %s", zLine);
2151 }
2152 }else{
2153 sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
drh59607242021-04-29 18:03:42 +00002154 if( verboseFlag ) printf("loading %s\n", argv[i]);
drhba6619d2021-04-23 12:58:16 +00002155 sqlite3_step(pStmt);
2156 rc = sqlite3_reset(pStmt);
2157 if( rc ) fatalError("insert failed for %s", argv[i]);
2158 }
drh3b74d032015-05-25 18:48:19 +00002159 }
drhd9972ef2015-05-26 17:57:56 +00002160 sqlite3_finalize(pStmt);
2161 rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
drh5ecf9032018-05-08 12:49:53 +00002162 if( rc ) fatalError("cannot commit the transaction: %s",
2163 sqlite3_errmsg(db));
drhe5da9352019-01-27 01:11:40 +00002164 rebuild_database(db, dbSqlOnly);
drh3b74d032015-05-25 18:48:19 +00002165 sqlite3_close(db);
drhd9972ef2015-05-26 17:57:56 +00002166 return 0;
drh3b74d032015-05-25 18:48:19 +00002167 }
drh16f05822017-03-20 20:42:21 +00002168 rc = sqlite3_exec(db, "PRAGMA query_only=1;", 0, 0, 0);
2169 if( rc ) fatalError("cannot set database to query-only");
drh40e0e0d2015-09-22 18:51:17 +00002170 if( zExpDb!=0 || zExpSql!=0 ){
2171 sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
2172 writefileFunc, 0, 0);
2173 if( zExpDb!=0 ){
2174 const char *zExDb =
2175 "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent),"
2176 " dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)"
2177 " FROM db WHERE ?2<0 OR dbid=?2;";
2178 rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0);
2179 if( rc ) fatalError("cannot prepare statement [%s]: %s",
2180 zExDb, sqlite3_errmsg(db));
2181 sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb),
2182 SQLITE_STATIC, SQLITE_UTF8);
2183 sqlite3_bind_int(pStmt, 2, onlyDbid);
2184 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2185 printf("write db-%d (%d bytes) into %s\n",
2186 sqlite3_column_int(pStmt,1),
2187 sqlite3_column_int(pStmt,3),
2188 sqlite3_column_text(pStmt,2));
2189 }
2190 sqlite3_finalize(pStmt);
2191 }
2192 if( zExpSql!=0 ){
2193 const char *zExSql =
2194 "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext),"
2195 " sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)"
2196 " FROM xsql WHERE ?2<0 OR sqlid=?2;";
2197 rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0);
2198 if( rc ) fatalError("cannot prepare statement [%s]: %s",
2199 zExSql, sqlite3_errmsg(db));
2200 sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql),
2201 SQLITE_STATIC, SQLITE_UTF8);
2202 sqlite3_bind_int(pStmt, 2, onlySqlid);
2203 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2204 printf("write sql-%d (%d bytes) into %s\n",
2205 sqlite3_column_int(pStmt,1),
2206 sqlite3_column_int(pStmt,3),
2207 sqlite3_column_text(pStmt,2));
2208 }
2209 sqlite3_finalize(pStmt);
2210 }
2211 sqlite3_close(db);
2212 return 0;
2213 }
drhd9972ef2015-05-26 17:57:56 +00002214
2215 /* Load all SQL script content and all initial database images from the
2216 ** source db
2217 */
2218 blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
2219 &g.nSql, &g.pFirstSql);
2220 if( g.nSql==0 ) fatalError("need at least one SQL script");
2221 blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
2222 &g.nDb, &g.pFirstDb);
2223 if( g.nDb==0 ){
2224 g.pFirstDb = safe_realloc(0, sizeof(Blob));
2225 memset(g.pFirstDb, 0, sizeof(Blob));
2226 g.pFirstDb->id = 1;
2227 g.pFirstDb->seq = 0;
2228 g.nDb = 1;
drhd83e2832015-06-24 14:45:44 +00002229 sqlFuzz = 1;
drhd9972ef2015-05-26 17:57:56 +00002230 }
2231
2232 /* Print the description, if there is one */
drh075201e2021-10-27 12:05:28 +00002233 if( !quietFlag && !bScript ){
drhd9972ef2015-05-26 17:57:56 +00002234 zDbName = azSrcDb[iSrcDb];
drhe683b892016-02-15 18:47:26 +00002235 i = (int)strlen(zDbName) - 1;
drhd9972ef2015-05-26 17:57:56 +00002236 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
2237 zDbName += i;
2238 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
2239 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
2240 printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
2241 }
2242 sqlite3_finalize(pStmt);
2243 }
drh9a645862015-06-24 12:44:42 +00002244
2245 /* Rebuild the database, if requested */
2246 if( rebuildFlag ){
2247 if( !quietFlag ){
2248 printf("%s: rebuilding... ", zDbName);
2249 fflush(stdout);
2250 }
drhe5da9352019-01-27 01:11:40 +00002251 rebuild_database(db, 0);
drh9a645862015-06-24 12:44:42 +00002252 if( !quietFlag ) printf("done\n");
2253 }
drhd9972ef2015-05-26 17:57:56 +00002254
2255 /* Close the source database. Verify that no SQLite memory allocations are
2256 ** outstanding.
2257 */
2258 sqlite3_close(db);
2259 if( sqlite3_memory_used()>0 ){
2260 fatalError("SQLite has memory in use before the start of testing");
2261 }
drh53e66c32015-07-24 15:49:23 +00002262
2263 /* Limit available memory, if requested */
drh174f8552017-03-20 22:58:27 +00002264 sqlite3_shutdown();
drh39b3bcf2020-03-02 16:31:21 +00002265
drh31999c52019-11-14 17:46:32 +00002266 if( nMemThisDb>0 && nMem==0 ){
2267 if( !nativeMalloc ){
2268 pHeap = realloc(pHeap, nMemThisDb);
2269 if( pHeap==0 ){
2270 fatalError("failed to allocate %d bytes of heap memory", nMem);
2271 }
2272 sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMemThisDb, 128);
2273 }else{
2274 sqlite3_hard_heap_limit64((sqlite3_int64)nMemThisDb);
drh53e66c32015-07-24 15:49:23 +00002275 }
drh31999c52019-11-14 17:46:32 +00002276 }else{
2277 sqlite3_hard_heap_limit64(0);
drh53e66c32015-07-24 15:49:23 +00002278 }
drh174f8552017-03-20 22:58:27 +00002279
2280 /* Disable lookaside with the --native-malloc option */
2281 if( nativeMalloc ){
2282 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
2283 }
drhd9972ef2015-05-26 17:57:56 +00002284
drhbeaf5142016-12-26 00:15:56 +00002285 /* Reset the in-memory virtual filesystem */
drhd9972ef2015-05-26 17:57:56 +00002286 formatVfs();
drhd9972ef2015-05-26 17:57:56 +00002287
2288 /* Run a test using each SQL script against each database.
2289 */
drh075201e2021-10-27 12:05:28 +00002290 if( !verboseFlag && !quietFlag && !bSpinner && !bScript ){
2291 printf("%s:", zDbName);
2292 }
drhd9972ef2015-05-26 17:57:56 +00002293 for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
drh237f41a2020-12-21 12:14:59 +00002294 tmStart = timeOfDay();
drha47e7092019-01-25 04:00:14 +00002295 if( isDbSql(pSql->a, pSql->sz) ){
2296 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d",pSql->id);
drh075201e2021-10-27 12:05:28 +00002297 if( bScript ){
2298 /* No progress output */
2299 }else if( bSpinner ){
drhaa0696e2020-04-07 13:08:56 +00002300 int nTotal =g.nSql;
2301 int idx = pSql->seq;
2302 printf("\r%s: %d/%d ", zDbName, idx, nTotal);
2303 fflush(stdout);
2304 }else if( verboseFlag ){
drha47e7092019-01-25 04:00:14 +00002305 printf("%s\n", g.zTestName);
2306 fflush(stdout);
2307 }else if( !quietFlag ){
2308 static int prevAmt = -1;
2309 int idx = pSql->seq;
2310 int amt = idx*10/(g.nSql);
2311 if( amt!=prevAmt ){
2312 printf(" %d%%", amt*10);
2313 fflush(stdout);
2314 prevAmt = amt;
2315 }
2316 }
drh672f07c2020-10-20 14:40:53 +00002317 if( nSkip>0 ){
2318 nSkip--;
2319 }else{
drh075201e2021-10-27 12:05:28 +00002320 runCombinedDbSqlInput(pSql->a, pSql->sz, iTimeout, bScript, pSql->id);
drh672f07c2020-10-20 14:40:53 +00002321 }
drha47e7092019-01-25 04:00:14 +00002322 nTest++;
drh075201e2021-10-27 12:05:28 +00002323 if( bTimer && !bScript ){
drh237f41a2020-12-21 12:14:59 +00002324 sqlite3_int64 tmEnd = timeOfDay();
2325 printf("%lld %s\n", tmEnd - tmStart, g.zTestName);
2326 }
drha47e7092019-01-25 04:00:14 +00002327 g.zTestName[0] = 0;
drh39b3bcf2020-03-02 16:31:21 +00002328 disableOom();
drha47e7092019-01-25 04:00:14 +00002329 continue;
2330 }
drhd9972ef2015-05-26 17:57:56 +00002331 for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
2332 int openFlags;
2333 const char *zVfs = "inmem";
2334 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
2335 pSql->id, pDb->id);
drh075201e2021-10-27 12:05:28 +00002336 if( bScript ){
2337 /* No progress output */
2338 }else if( bSpinner ){
drhaa0696e2020-04-07 13:08:56 +00002339 int nTotal = g.nDb*g.nSql;
2340 int idx = pSql->seq*g.nDb + pDb->id - 1;
2341 printf("\r%s: %d/%d ", zDbName, idx, nTotal);
2342 fflush(stdout);
2343 }else if( verboseFlag ){
drhd9972ef2015-05-26 17:57:56 +00002344 printf("%s\n", g.zTestName);
2345 fflush(stdout);
2346 }else if( !quietFlag ){
2347 static int prevAmt = -1;
2348 int idx = pSql->seq*g.nDb + pDb->id - 1;
2349 int amt = idx*10/(g.nDb*g.nSql);
2350 if( amt!=prevAmt ){
2351 printf(" %d%%", amt*10);
2352 fflush(stdout);
2353 prevAmt = amt;
2354 }
2355 }
drh672f07c2020-10-20 14:40:53 +00002356 if( nSkip>0 ){
2357 nSkip--;
2358 continue;
2359 }
drh075201e2021-10-27 12:05:28 +00002360 if( bScript ){
2361 char zName[100];
2362 sqlite3_snprintf(sizeof(zName), zName, "db%06d.db",
2363 pDb->id>1 ? pDb->id : pSql->id);
2364 renderDbSqlForCLI(stdout, zName,
2365 pDb->a, pDb->sz, pSql->a, pSql->sz);
2366 continue;
2367 }
drhd9972ef2015-05-26 17:57:56 +00002368 createVFile("main.db", pDb->sz, pDb->a);
drhbeaf5142016-12-26 00:15:56 +00002369 sqlite3_randomness(0,0);
drh362b66f2016-11-14 18:27:41 +00002370 if( ossFuzzThisDb ){
drhea432ba2016-11-11 16:33:47 +00002371#ifndef SQLITE_OSS_FUZZ
drh5ecf9032018-05-08 12:49:53 +00002372 fatalError("--oss-fuzz not supported: recompile"
2373 " with -DSQLITE_OSS_FUZZ");
drhea432ba2016-11-11 16:33:47 +00002374#else
2375 extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t);
2376 LLVMFuzzerTestOneInput((const uint8_t*)pSql->a, (size_t)pSql->sz);
drh78057352015-06-24 23:17:35 +00002377#endif
drhea432ba2016-11-11 16:33:47 +00002378 }else{
2379 openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
2380 if( nativeFlag && pDb->sz==0 ){
2381 openFlags |= SQLITE_OPEN_MEMORY;
2382 zVfs = 0;
2383 }
2384 rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
2385 if( rc ) fatalError("cannot open inmem database");
drhdfcfff62016-12-26 12:25:19 +00002386 sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 100000000);
2387 sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 50);
drhea432ba2016-11-11 16:33:47 +00002388 if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
drh237f41a2020-12-21 12:14:59 +00002389 setAlarm((iTimeout+999)/1000);
drh7ae05492021-03-08 16:13:52 +00002390 /* Enable test functions */
2391 sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, db);
drhea432ba2016-11-11 16:33:47 +00002392#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2393 if( sqlFuzz || vdbeLimitFlag ){
drh5ecf9032018-05-08 12:49:53 +00002394 sqlite3_progress_handler(db, 100000, progressHandler,
2395 &vdbeLimitFlag);
drhea432ba2016-11-11 16:33:47 +00002396 }
2397#endif
drhe6e96b12019-08-02 21:03:24 +00002398#ifdef SQLITE_TESTCTRL_PRNG_SEED
drh2e6d83b2019-08-03 01:39:20 +00002399 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, db);
drhe6e96b12019-08-02 21:03:24 +00002400#endif
drh6e1c45e2019-12-18 13:42:04 +00002401 if( bVdbeDebug ){
2402 sqlite3_exec(db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
2403 }
drhea432ba2016-11-11 16:33:47 +00002404 do{
2405 runSql(db, (char*)pSql->a, runFlags);
2406 }while( timeoutTest );
2407 setAlarm(0);
drh174f8552017-03-20 22:58:27 +00002408 sqlite3_exec(db, "PRAGMA temp_store_directory=''", 0, 0, 0);
drhea432ba2016-11-11 16:33:47 +00002409 sqlite3_close(db);
2410 }
drh174f8552017-03-20 22:58:27 +00002411 if( sqlite3_memory_used()>0 ){
2412 fatalError("memory leak: %lld bytes outstanding",
2413 sqlite3_memory_used());
2414 }
drhd9972ef2015-05-26 17:57:56 +00002415 reformatVfs();
2416 nTest++;
drh237f41a2020-12-21 12:14:59 +00002417 if( bTimer ){
2418 sqlite3_int64 tmEnd = timeOfDay();
2419 printf("%lld %s\n", tmEnd - tmStart, g.zTestName);
2420 }
drhd9972ef2015-05-26 17:57:56 +00002421 g.zTestName[0] = 0;
drh4d6fda72015-05-26 18:58:32 +00002422
2423 /* Simulate an error if the TEST_FAILURE environment variable is "5".
2424 ** This is used to verify that automated test script really do spot
2425 ** errors that occur in this test program.
2426 */
2427 if( zFailCode ){
2428 if( zFailCode[0]=='5' && zFailCode[1]==0 ){
2429 fatalError("simulated failure");
2430 }else if( zFailCode[0]!=0 ){
2431 /* If TEST_FAILURE is something other than 5, just exit the test
2432 ** early */
2433 printf("\nExit early due to TEST_FAILURE being set\n");
2434 iSrcDb = nSrcDb-1;
2435 goto sourcedb_cleanup;
2436 }
2437 }
drhd9972ef2015-05-26 17:57:56 +00002438 }
2439 }
drh075201e2021-10-27 12:05:28 +00002440 if( bScript ){
2441 /* No progress output */
2442 }else if( bSpinner ){
drh292ed6d2021-04-23 12:16:16 +00002443 int nTotal = g.nDb*g.nSql;
2444 printf("\r%s: %d/%d \n", zDbName, nTotal, nTotal);
drhaa0696e2020-04-07 13:08:56 +00002445 }else if( !quietFlag && !verboseFlag ){
drhd9972ef2015-05-26 17:57:56 +00002446 printf(" 100%% - %d tests\n", g.nDb*g.nSql);
2447 }
2448
2449 /* Clean up at the end of processing a single source database
2450 */
drh4d6fda72015-05-26 18:58:32 +00002451 sourcedb_cleanup:
drhd9972ef2015-05-26 17:57:56 +00002452 blobListFree(g.pFirstSql);
2453 blobListFree(g.pFirstDb);
2454 reformatVfs();
2455
2456 } /* End loop over all source databases */
drh3b74d032015-05-25 18:48:19 +00002457
drh075201e2021-10-27 12:05:28 +00002458 if( !quietFlag && !bScript ){
drh3b74d032015-05-25 18:48:19 +00002459 sqlite3_int64 iElapse = timeOfDay() - iBegin;
drhe3bf2c82022-06-15 16:26:37 +00002460 if( g.nInvariant ){
2461 printf("fuzzcheck: %u query invariants checked\n", g.nInvariant);
2462 }
drhd9972ef2015-05-26 17:57:56 +00002463 printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
2464 "SQLite %s %s\n",
2465 nTest, (int)(iElapse/1000), (int)(iElapse%1000),
drh3b74d032015-05-25 18:48:19 +00002466 sqlite3_libversion(), sqlite3_sourceid());
2467 }
drhf74d35b2015-05-27 18:19:50 +00002468 free(azSrcDb);
drh6653fbe2015-11-13 20:52:49 +00002469 free(pHeap);
drh3b74d032015-05-25 18:48:19 +00002470 return 0;
2471}