blob: e1d3a12ecf74b83cf8445ba6e9a45df1c5804142 [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"
drhc56fac72015-10-29 13:48:15 +000088#define ISSPACE(X) isspace((unsigned char)(X))
89#define ISDIGIT(X) isdigit((unsigned char)(X))
90
drh3b74d032015-05-25 18:48:19 +000091
drh94701b02015-06-24 13:25:34 +000092#ifdef __unix__
93# include <signal.h>
94# include <unistd.h>
95#endif
96
drhf0a21722020-03-19 17:27:52 +000097#include <stddef.h>
98#if !defined(_MSC_VER)
99# include <stdint.h>
mistachkinac8ba262018-03-07 14:42:17 +0000100#endif
101
102#if defined(_MSC_VER)
103typedef unsigned char uint8_t;
drhea432ba2016-11-11 16:33:47 +0000104#endif
105
drh3b74d032015-05-25 18:48:19 +0000106/*
107** Files in the virtual file system.
108*/
109typedef struct VFile VFile;
110struct VFile {
drh0fcf6f02021-05-24 12:28:13 +0000111 char *zFilename; /* Filename. NULL for delete-on-close. From malloc() */
112 int sz; /* Size of the file in bytes */
113 int nRef; /* Number of references to this file */
114 unsigned char *a; /* Content of the file. From malloc() */
drh3b74d032015-05-25 18:48:19 +0000115};
116typedef struct VHandle VHandle;
117struct VHandle {
118 sqlite3_file base; /* Base class. Must be first */
119 VFile *pVFile; /* The underlying file */
120};
121
122/*
123** The value of a database file template, or of an SQL script
124*/
125typedef struct Blob Blob;
126struct Blob {
127 Blob *pNext; /* Next in a list */
128 int id; /* Id of this Blob */
drhe5c5f2c2015-05-26 00:28:08 +0000129 int seq; /* Sequence number */
drh3b74d032015-05-25 18:48:19 +0000130 int sz; /* Size of this Blob in bytes */
131 unsigned char a[1]; /* Blob content. Extra space allocated as needed. */
132};
133
134/*
135** Maximum number of files in the in-memory virtual filesystem.
136*/
137#define MX_FILE 10
138
139/*
140** Maximum allowed file size
141*/
142#define MX_FILE_SZ 10000000
143
144/*
145** All global variables are gathered into the "g" singleton.
146*/
147static struct GlobalVars {
148 const char *zArgv0; /* Name of program */
drha7648f02019-12-18 13:02:18 +0000149 const char *zDbFile; /* Name of database file */
drh3b74d032015-05-25 18:48:19 +0000150 VFile aFile[MX_FILE]; /* The virtual filesystem */
151 int nDb; /* Number of template databases */
152 Blob *pFirstDb; /* Content of first template database */
153 int nSql; /* Number of SQL scripts */
154 Blob *pFirstSql; /* First SQL script */
drhbeaf5142016-12-26 00:15:56 +0000155 unsigned int uRandom; /* Seed for the SQLite PRNG */
drh0c278c32022-06-15 10:46:52 +0000156 unsigned char doInvariantChecks; /* True to run query invariant checks */
drh3b74d032015-05-25 18:48:19 +0000157 char zTestName[100]; /* Name of current test */
158} g;
159
160/*
drh0fab1092022-02-04 19:13:18 +0000161** Include the external vt02.c module, if requested by compile-time
162** options.
163*/
164#ifdef VT02_SOURCES
165# include "vt02.c"
166#endif
167
168/*
drh3b74d032015-05-25 18:48:19 +0000169** Print an error message and quit.
170*/
171static void fatalError(const char *zFormat, ...){
172 va_list ap;
drha7648f02019-12-18 13:02:18 +0000173 fprintf(stderr, "%s", g.zArgv0);
174 if( g.zDbFile ) fprintf(stderr, " %s", g.zDbFile);
175 if( g.zTestName[0] ) fprintf(stderr, " (%s)", g.zTestName);
176 fprintf(stderr, ": ");
drh3b74d032015-05-25 18:48:19 +0000177 va_start(ap, zFormat);
178 vfprintf(stderr, zFormat, ap);
179 va_end(ap);
180 fprintf(stderr, "\n");
181 exit(1);
182}
183
184/*
drha7648f02019-12-18 13:02:18 +0000185** signal handler
drh94701b02015-06-24 13:25:34 +0000186*/
187#ifdef __unix__
drha7648f02019-12-18 13:02:18 +0000188static void signalHandler(int signum){
189 const char *zSig;
190 if( signum==SIGABRT ){
191 zSig = "abort";
192 }else if( signum==SIGALRM ){
193 zSig = "timeout";
194 }else if( signum==SIGSEGV ){
195 zSig = "segfault";
196 }else{
197 zSig = "signal";
198 }
199 fatalError(zSig);
drh94701b02015-06-24 13:25:34 +0000200}
201#endif
202
203/*
204** Set the an alarm to go off after N seconds. Disable the alarm
205** if N==0
206*/
207static void setAlarm(int N){
208#ifdef __unix__
209 alarm(N);
210#else
211 (void)N;
212#endif
213}
214
drh78057352015-06-24 23:17:35 +0000215#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh94701b02015-06-24 13:25:34 +0000216/*
drhd83e2832015-06-24 14:45:44 +0000217** This an SQL progress handler. After an SQL statement has run for
218** many steps, we want to interrupt it. This guards against infinite
219** loops from recursive common table expressions.
220**
221** *pVdbeLimitFlag is true if the --limit-vdbe command-line option is used.
222** In that case, hitting the progress handler is a fatal error.
223*/
224static int progressHandler(void *pVdbeLimitFlag){
225 if( *(int*)pVdbeLimitFlag ) fatalError("too many VDBE cycles");
226 return 1;
227}
drh78057352015-06-24 23:17:35 +0000228#endif
drhd83e2832015-06-24 14:45:44 +0000229
230/*
drh0fcf6f02021-05-24 12:28:13 +0000231** Reallocate memory. Show an error and quit if unable.
drh3b74d032015-05-25 18:48:19 +0000232*/
233static void *safe_realloc(void *pOld, int szNew){
drhc5412d52016-03-23 17:54:19 +0000234 void *pNew = realloc(pOld, szNew<=0 ? 1 : szNew);
drh3b74d032015-05-25 18:48:19 +0000235 if( pNew==0 ) fatalError("unable to realloc for %d bytes", szNew);
236 return pNew;
237}
238
239/*
240** Initialize the virtual file system.
241*/
242static void formatVfs(void){
243 int i;
244 for(i=0; i<MX_FILE; i++){
245 g.aFile[i].sz = -1;
246 g.aFile[i].zFilename = 0;
247 g.aFile[i].a = 0;
248 g.aFile[i].nRef = 0;
249 }
250}
251
252
253/*
254** Erase all information in the virtual file system.
255*/
256static void reformatVfs(void){
257 int i;
258 for(i=0; i<MX_FILE; i++){
259 if( g.aFile[i].sz<0 ) continue;
260 if( g.aFile[i].zFilename ){
261 free(g.aFile[i].zFilename);
262 g.aFile[i].zFilename = 0;
263 }
264 if( g.aFile[i].nRef>0 ){
265 fatalError("file %d still open. nRef=%d", i, g.aFile[i].nRef);
266 }
267 g.aFile[i].sz = -1;
268 free(g.aFile[i].a);
269 g.aFile[i].a = 0;
270 g.aFile[i].nRef = 0;
271 }
272}
273
274/*
275** Find a VFile by name
276*/
277static VFile *findVFile(const char *zName){
278 int i;
drha9542b12015-05-25 19:35:42 +0000279 if( zName==0 ) return 0;
drh3b74d032015-05-25 18:48:19 +0000280 for(i=0; i<MX_FILE; i++){
281 if( g.aFile[i].zFilename==0 ) continue;
282 if( strcmp(g.aFile[i].zFilename, zName)==0 ) return &g.aFile[i];
283 }
284 return 0;
285}
286
287/*
288** Find a VFile by name. Create it if it does not already exist and
289** initialize it to the size and content given.
290**
291** Return NULL only if the filesystem is full.
292*/
293static VFile *createVFile(const char *zName, int sz, unsigned char *pData){
294 VFile *pNew = findVFile(zName);
295 int i;
296 if( pNew ) return pNew;
297 for(i=0; i<MX_FILE && g.aFile[i].sz>=0; i++){}
298 if( i>=MX_FILE ) return 0;
299 pNew = &g.aFile[i];
drha9542b12015-05-25 19:35:42 +0000300 if( zName ){
drhe683b892016-02-15 18:47:26 +0000301 int nName = (int)strlen(zName)+1;
302 pNew->zFilename = safe_realloc(0, nName);
303 memcpy(pNew->zFilename, zName, nName);
drha9542b12015-05-25 19:35:42 +0000304 }else{
305 pNew->zFilename = 0;
306 }
drh3b74d032015-05-25 18:48:19 +0000307 pNew->nRef = 0;
308 pNew->sz = sz;
309 pNew->a = safe_realloc(0, sz);
310 if( sz>0 ) memcpy(pNew->a, pData, sz);
311 return pNew;
312}
313
drh075201e2021-10-27 12:05:28 +0000314/* Return true if the line is all zeros */
315static int allZero(unsigned char *aLine){
316 int i;
317 for(i=0; i<16 && aLine[i]==0; i++){}
318 return i==16;
319}
320
321/*
322** Render a database and query as text that can be input into
323** the CLI.
324*/
325static void renderDbSqlForCLI(
326 FILE *out, /* Write to this file */
327 const char *zFile, /* Name of the database file */
328 unsigned char *aDb, /* Database content */
329 int nDb, /* Number of bytes in aDb[] */
330 unsigned char *zSql, /* SQL content */
331 int nSql /* Bytes of SQL */
332){
333 fprintf(out, ".print ******* %s *******\n", zFile);
334 if( nDb>100 ){
335 int i, j; /* Loop counters */
336 int pgsz; /* Size of each page */
337 int lastPage = 0; /* Last page number shown */
338 int iPage; /* Current page number */
339 unsigned char *aLine; /* Single line to display */
340 unsigned char buf[16]; /* Fake line */
341 unsigned char bShow[256]; /* Characters ok to display */
342
343 memset(bShow, '.', sizeof(bShow));
344 for(i=' '; i<='~'; i++){
345 if( i!='{' && i!='}' && i!='"' && i!='\\' ) bShow[i] = i;
346 }
347 pgsz = (aDb[16]<<8) | aDb[17];
348 if( pgsz==0 ) pgsz = 65536;
349 if( pgsz<512 || (pgsz&(pgsz-1))!=0 ) pgsz = 4096;
350 fprintf(out,".open --hexdb\n");
351 fprintf(out,"| size %d pagesize %d filename %s\n",nDb,pgsz,zFile);
352 for(i=0; i<nDb; i += 16){
353 if( i+16>nDb ){
354 memset(buf, 0, sizeof(buf));
355 memcpy(buf, aDb+i, nDb-i);
356 aLine = buf;
357 }else{
358 aLine = aDb + i;
359 }
360 if( allZero(aLine) ) continue;
361 iPage = i/pgsz + 1;
362 if( lastPage!=iPage ){
363 fprintf(out,"| page %d offset %d\n", iPage, (iPage-1)*pgsz);
364 lastPage = iPage;
365 }
366 fprintf(out,"| %5d:", i-(iPage-1)*pgsz);
367 for(j=0; j<16; j++) fprintf(out," %02x", aLine[j]);
368 fprintf(out," ");
369 for(j=0; j<16; j++){
370 unsigned char c = (unsigned char)aLine[j];
371 fputc( bShow[c], stdout);
372 }
373 fputc('\n', stdout);
374 }
375 fprintf(out,"| end %s\n", zFile);
376 }else{
377 fprintf(out,".open :memory:\n");
378 }
379 fprintf(out,".testctrl prng_seed 1 db\n");
380 fprintf(out,".testctrl internal_functions\n");
381 fprintf(out,"%.*s", nSql, zSql);
382 if( nSql>0 && zSql[nSql-1]!='\n' ) fprintf(out, "\n");
383}
384
drh48b4bf22021-10-26 22:36:41 +0000385/*
386** Read the complete content of a file into memory. Add a 0x00 terminator
387** and return a pointer to the result.
388**
389** The file content is held in memory obtained from sqlite_malloc64() which
390** should be freed by the caller.
391*/
392static char *readFile(const char *zFilename, long *sz){
393 FILE *in;
394 long nIn;
395 unsigned char *pBuf;
396
397 *sz = 0;
398 if( zFilename==0 ) return 0;
399 in = fopen(zFilename, "rb");
400 if( in==0 ) return 0;
401 fseek(in, 0, SEEK_END);
402 *sz = nIn = ftell(in);
403 rewind(in);
404 pBuf = sqlite3_malloc64( nIn+1 );
405 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
406 pBuf[nIn] = 0;
407 fclose(in);
drh075201e2021-10-27 12:05:28 +0000408 return (char*)pBuf;
drh48b4bf22021-10-26 22:36:41 +0000409 }
410 sqlite3_free(pBuf);
411 *sz = 0;
412 fclose(in);
413 return 0;
414}
415
drh3b74d032015-05-25 18:48:19 +0000416
417/*
418** Implementation of the "readfile(X)" SQL function. The entire content
419** of the file named X is read and returned as a BLOB. NULL is returned
420** if the file does not exist or is unreadable.
421*/
422static void readfileFunc(
423 sqlite3_context *context,
424 int argc,
425 sqlite3_value **argv
426){
drh3b74d032015-05-25 18:48:19 +0000427 long nIn;
428 void *pBuf;
drh48b4bf22021-10-26 22:36:41 +0000429 const char *zName = (const char*)sqlite3_value_text(argv[0]);
drh3b74d032015-05-25 18:48:19 +0000430
drh3b74d032015-05-25 18:48:19 +0000431 if( zName==0 ) return;
drh48b4bf22021-10-26 22:36:41 +0000432 pBuf = readFile(zName, &nIn);
433 if( pBuf ){
drh3b74d032015-05-25 18:48:19 +0000434 sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
drh3b74d032015-05-25 18:48:19 +0000435 }
drh3b74d032015-05-25 18:48:19 +0000436}
437
438/*
drha8781d92020-02-25 20:05:58 +0000439** Implementation of the "readtextfile(X)" SQL function. The text content
440** of the file named X through the end of the file or to the first \000
441** character, whichever comes first, is read and returned as TEXT. NULL
442** is returned if the file does not exist or is unreadable.
443*/
444static void readtextfileFunc(
445 sqlite3_context *context,
446 int argc,
447 sqlite3_value **argv
448){
449 const char *zName;
450 FILE *in;
451 long nIn;
452 char *pBuf;
453
454 zName = (const char*)sqlite3_value_text(argv[0]);
455 if( zName==0 ) return;
456 in = fopen(zName, "rb");
457 if( in==0 ) return;
458 fseek(in, 0, SEEK_END);
459 nIn = ftell(in);
460 rewind(in);
461 pBuf = sqlite3_malloc64( nIn+1 );
462 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
463 pBuf[nIn] = 0;
464 sqlite3_result_text(context, pBuf, -1, sqlite3_free);
465 }else{
466 sqlite3_free(pBuf);
467 }
468 fclose(in);
469}
470
471/*
drh40e0e0d2015-09-22 18:51:17 +0000472** Implementation of the "writefile(X,Y)" SQL function. The argument Y
473** is written into file X. The number of bytes written is returned. Or
474** NULL is returned if something goes wrong, such as being unable to open
475** file X for writing.
476*/
477static void writefileFunc(
478 sqlite3_context *context,
479 int argc,
480 sqlite3_value **argv
481){
482 FILE *out;
483 const char *z;
484 sqlite3_int64 rc;
485 const char *zFile;
486
487 (void)argc;
488 zFile = (const char*)sqlite3_value_text(argv[0]);
489 if( zFile==0 ) return;
490 out = fopen(zFile, "wb");
491 if( out==0 ) return;
492 z = (const char*)sqlite3_value_blob(argv[1]);
493 if( z==0 ){
494 rc = 0;
495 }else{
496 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
497 }
498 fclose(out);
499 sqlite3_result_int64(context, rc);
500}
501
502
503/*
drh3b74d032015-05-25 18:48:19 +0000504** Load a list of Blob objects from the database
505*/
506static void blobListLoadFromDb(
507 sqlite3 *db, /* Read from this database */
508 const char *zSql, /* Query used to extract the blobs */
drha9542b12015-05-25 19:35:42 +0000509 int onlyId, /* Only load where id is this value */
drh3b74d032015-05-25 18:48:19 +0000510 int *pN, /* OUT: Write number of blobs loaded here */
511 Blob **ppList /* OUT: Write the head of the blob list here */
512){
513 Blob head;
514 Blob *p;
515 sqlite3_stmt *pStmt;
516 int n = 0;
517 int rc;
drha9542b12015-05-25 19:35:42 +0000518 char *z2;
drh3b74d032015-05-25 18:48:19 +0000519
drha9542b12015-05-25 19:35:42 +0000520 if( onlyId>0 ){
521 z2 = sqlite3_mprintf("%s WHERE rowid=%d", zSql, onlyId);
522 }else{
523 z2 = sqlite3_mprintf("%s", zSql);
524 }
525 rc = sqlite3_prepare_v2(db, z2, -1, &pStmt, 0);
526 sqlite3_free(z2);
drh3b74d032015-05-25 18:48:19 +0000527 if( rc ) fatalError("%s", sqlite3_errmsg(db));
528 head.pNext = 0;
529 p = &head;
530 while( SQLITE_ROW==sqlite3_step(pStmt) ){
531 int sz = sqlite3_column_bytes(pStmt, 1);
532 Blob *pNew = safe_realloc(0, sizeof(*pNew)+sz );
533 pNew->id = sqlite3_column_int(pStmt, 0);
534 pNew->sz = sz;
drhe5c5f2c2015-05-26 00:28:08 +0000535 pNew->seq = n++;
drh3b74d032015-05-25 18:48:19 +0000536 pNew->pNext = 0;
537 memcpy(pNew->a, sqlite3_column_blob(pStmt,1), sz);
538 pNew->a[sz] = 0;
539 p->pNext = pNew;
540 p = pNew;
drh3b74d032015-05-25 18:48:19 +0000541 }
542 sqlite3_finalize(pStmt);
543 *pN = n;
544 *ppList = head.pNext;
545}
546
547/*
548** Free a list of Blob objects
549*/
550static void blobListFree(Blob *p){
551 Blob *pNext;
552 while( p ){
553 pNext = p->pNext;
554 free(p);
555 p = pNext;
556 }
557}
558
drh237f41a2020-12-21 12:14:59 +0000559/* Return the current wall-clock time
560**
561** The number of milliseconds since the julian epoch.
562** 1907-01-01 00:00:00 -> 210866716800000
563** 2021-01-01 00:00:00 -> 212476176000000
564*/
drh3b74d032015-05-25 18:48:19 +0000565static sqlite3_int64 timeOfDay(void){
566 static sqlite3_vfs *clockVfs = 0;
567 sqlite3_int64 t;
drh8055a3e2018-11-21 14:27:34 +0000568 if( clockVfs==0 ){
569 clockVfs = sqlite3_vfs_find(0);
570 if( clockVfs==0 ) return 0;
571 }
drh3b74d032015-05-25 18:48:19 +0000572 if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
573 clockVfs->xCurrentTimeInt64(clockVfs, &t);
574 }else{
575 double r;
576 clockVfs->xCurrentTime(clockVfs, &r);
577 t = (sqlite3_int64)(r*86400000.0);
578 }
579 return t;
580}
581
drha47e7092019-01-25 04:00:14 +0000582/***************************************************************************
583** Code to process combined database+SQL scripts generated by the
584** dbsqlfuzz fuzzer.
585*/
586
587/* An instance of the following object is passed by pointer as the
588** client data to various callbacks.
589*/
590typedef struct FuzzCtx {
591 sqlite3 *db; /* The database connection */
592 sqlite3_int64 iCutoffTime; /* Stop processing at this time. */
593 sqlite3_int64 iLastCb; /* Time recorded for previous progress callback */
594 sqlite3_int64 mxInterval; /* Longest interval between two progress calls */
595 unsigned nCb; /* Number of progress callbacks */
596 unsigned mxCb; /* Maximum number of progress callbacks allowed */
597 unsigned execCnt; /* Number of calls to the sqlite3_exec callback */
598 int timeoutHit; /* True when reaching a timeout */
599} FuzzCtx;
600
601/* Verbosity level for the dbsqlfuzz test runner */
602static int eVerbosity = 0;
603
604/* True to activate PRAGMA vdbe_debug=on */
605static int bVdbeDebug = 0;
606
607/* Timeout for each fuzzing attempt, in milliseconds */
drhed457032019-01-25 17:51:06 +0000608static int giTimeout = 10000; /* Defaults to 10 seconds */
drha47e7092019-01-25 04:00:14 +0000609
610/* Maximum number of progress handler callbacks */
611static unsigned int mxProgressCb = 2000;
612
613/* Maximum string length in SQLite */
614static int lengthLimit = 1000000;
615
drhbe03cc92020-01-20 14:42:09 +0000616/* Maximum expression depth */
617static int depthLimit = 500;
618
drh31999c52019-11-14 17:46:32 +0000619/* Limit on the amount of heap memory that can be used */
drha8781d92020-02-25 20:05:58 +0000620static sqlite3_int64 heapLimit = 100000000;
drh31999c52019-11-14 17:46:32 +0000621
drha47e7092019-01-25 04:00:14 +0000622/* Maximum byte-code program length in SQLite */
623static int vdbeOpLimit = 25000;
624
625/* Maximum size of the in-memory database */
626static sqlite3_int64 maxDbSize = 104857600;
drh39b3bcf2020-03-02 16:31:21 +0000627/* OOM simulation parameters */
628static unsigned int oomCounter = 0; /* Simulate OOM when equals 1 */
629static unsigned int oomRepeat = 0; /* Number of OOMs in a row */
630static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
631
632/* This routine is called when a simulated OOM occurs. It is broken
633** out as a separate routine to make it easy to set a breakpoint on
634** the OOM
635*/
636void oomFault(void){
637 if( eVerbosity ){
638 printf("Simulated OOM fault\n");
639 }
640 if( oomRepeat>0 ){
641 oomRepeat--;
642 }else{
643 oomCounter--;
644 }
645}
646
647/* This routine is a replacement malloc() that is used to simulate
648** Out-Of-Memory (OOM) errors for testing purposes.
649*/
650static void *oomMalloc(int nByte){
651 if( oomCounter ){
652 if( oomCounter==1 ){
653 oomFault();
654 return 0;
655 }else{
656 oomCounter--;
657 }
658 }
659 return defaultMalloc(nByte);
660}
661
662/* Register the OOM simulator. This must occur before any memory
663** allocations */
664static void registerOomSimulator(void){
665 sqlite3_mem_methods mem;
666 sqlite3_shutdown();
667 sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
668 defaultMalloc = mem.xMalloc;
669 mem.xMalloc = oomMalloc;
670 sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
671}
672
673/* Turn off any pending OOM simulation */
674static void disableOom(void){
675 oomCounter = 0;
676 oomRepeat = 0;
677}
drha47e7092019-01-25 04:00:14 +0000678
679/*
680** Translate a single byte of Hex into an integer.
681** This routine only works if h really is a valid hexadecimal
682** character: 0..9a..fA..F
683*/
drhed457032019-01-25 17:51:06 +0000684static unsigned char hexToInt(unsigned int h){
drha47e7092019-01-25 04:00:14 +0000685#ifdef SQLITE_EBCDIC
686 h += 9*(1&~(h>>4)); /* EBCDIC */
687#else
688 h += 9*(1&(h>>6)); /* ASCII */
689#endif
690 return h & 0xf;
691}
692
693/*
694** The first character of buffer zIn[0..nIn-1] is a '['. This routine
695** checked to see if the buffer holds "[NNNN]" or "[+NNNN]" and if it
696** does it makes corresponding changes to the *pK value and *pI value
697** and returns true. If the input buffer does not match the patterns,
698** no changes are made to either *pK or *pI and this routine returns false.
699*/
700static int isOffset(
701 const unsigned char *zIn, /* Text input */
702 int nIn, /* Bytes of input */
703 unsigned int *pK, /* half-byte cursor to adjust */
704 unsigned int *pI /* Input index to adjust */
705){
706 int i;
707 unsigned int k = 0;
708 unsigned char c;
709 for(i=1; i<nIn && (c = zIn[i])!=']'; i++){
710 if( !isxdigit(c) ) return 0;
711 k = k*16 + hexToInt(c);
712 }
713 if( i==nIn ) return 0;
714 *pK = 2*k;
715 *pI += i;
716 return 1;
717}
718
719/*
720** Decode the text starting at zIn into a binary database file.
drh0fcf6f02021-05-24 12:28:13 +0000721** The maximum length of zIn is nIn bytes. Store the binary database
722** file in space obtained from sqlite3_malloc().
drha47e7092019-01-25 04:00:14 +0000723**
724** Return the number of bytes of zIn consumed. Or return -1 if there
725** is an error. One potential error is that the recipe specifies a
726** database file larger than MX_FILE_SZ bytes.
727**
728** Abort on an OOM.
729*/
730static int decodeDatabase(
731 const unsigned char *zIn, /* Input text to be decoded */
732 int nIn, /* Bytes of input text */
733 unsigned char **paDecode, /* OUT: decoded database file */
734 int *pnDecode /* OUT: Size of decoded database */
735){
drh672f07c2020-10-20 14:40:53 +0000736 unsigned char *a, *aNew; /* Database under construction */
drha47e7092019-01-25 04:00:14 +0000737 int mx = 0; /* Current size of the database */
738 sqlite3_uint64 nAlloc = 4096; /* Space allocated in a[] */
739 unsigned int i; /* Next byte of zIn[] to read */
740 unsigned int j; /* Temporary integer */
741 unsigned int k; /* half-byte cursor index for output */
742 unsigned int n; /* Number of bytes of input */
743 unsigned char b = 0;
744 if( nIn<4 ) return -1;
745 n = (unsigned int)nIn;
drhed457032019-01-25 17:51:06 +0000746 a = sqlite3_malloc64( nAlloc );
drha47e7092019-01-25 04:00:14 +0000747 if( a==0 ){
748 fprintf(stderr, "Out of memory!\n");
749 exit(1);
750 }
mistachkin065f3bf2019-03-20 05:45:03 +0000751 memset(a, 0, (size_t)nAlloc);
drha47e7092019-01-25 04:00:14 +0000752 for(i=k=0; i<n; i++){
drhaf638922019-02-07 00:17:36 +0000753 unsigned char c = (unsigned char)zIn[i];
drha47e7092019-01-25 04:00:14 +0000754 if( isxdigit(c) ){
755 k++;
756 if( k & 1 ){
757 b = hexToInt(c)*16;
758 }else{
759 b += hexToInt(c);
760 j = k/2 - 1;
761 if( j>=nAlloc ){
762 sqlite3_uint64 newSize;
763 if( nAlloc==MX_FILE_SZ || j>=MX_FILE_SZ ){
764 if( eVerbosity ){
765 fprintf(stderr, "Input database too big: max %d bytes\n",
766 MX_FILE_SZ);
767 }
768 sqlite3_free(a);
769 return -1;
770 }
771 newSize = nAlloc*2;
772 if( newSize<=j ){
773 newSize = (j+4096)&~4095;
774 }
775 if( newSize>MX_FILE_SZ ){
776 if( j>=MX_FILE_SZ ){
777 sqlite3_free(a);
778 return -1;
779 }
780 newSize = MX_FILE_SZ;
781 }
drh672f07c2020-10-20 14:40:53 +0000782 aNew = sqlite3_realloc64( a, newSize );
783 if( aNew==0 ){
784 sqlite3_free(a);
785 return -1;
drha47e7092019-01-25 04:00:14 +0000786 }
drh672f07c2020-10-20 14:40:53 +0000787 a = aNew;
drha47e7092019-01-25 04:00:14 +0000788 assert( newSize > nAlloc );
mistachkin065f3bf2019-03-20 05:45:03 +0000789 memset(a+nAlloc, 0, (size_t)(newSize - nAlloc));
drha47e7092019-01-25 04:00:14 +0000790 nAlloc = newSize;
791 }
792 if( j>=(unsigned)mx ){
793 mx = (j + 4095)&~4095;
794 if( mx>MX_FILE_SZ ) mx = MX_FILE_SZ;
795 }
796 assert( j<nAlloc );
797 a[j] = b;
798 }
799 }else if( zIn[i]=='[' && i<n-3 && isOffset(zIn+i, nIn-i, &k, &i) ){
800 continue;
801 }else if( zIn[i]=='\n' && i<n-4 && memcmp(zIn+i,"\n--\n",4)==0 ){
802 i += 4;
803 break;
804 }
805 }
806 *pnDecode = mx;
807 *paDecode = a;
808 return i;
809}
810
811/*
812** Progress handler callback.
813**
814** The argument is the cutoff-time after which all processing should
815** stop. So return non-zero if the cut-off time is exceeded.
816*/
817static int progress_handler(void *pClientData) {
818 FuzzCtx *p = (FuzzCtx*)pClientData;
819 sqlite3_int64 iNow = timeOfDay();
820 int rc = iNow>=p->iCutoffTime;
821 sqlite3_int64 iDiff = iNow - p->iLastCb;
drh237f41a2020-12-21 12:14:59 +0000822 /* printf("time-remaining: %lld\n", p->iCutoffTime - iNow); */
drha47e7092019-01-25 04:00:14 +0000823 if( iDiff > p->mxInterval ) p->mxInterval = iDiff;
824 p->nCb++;
825 if( rc==0 && p->mxCb>0 && p->mxCb<=p->nCb ) rc = 1;
drhdf216592019-01-25 04:43:26 +0000826 if( rc && !p->timeoutHit && eVerbosity>=2 ){
drha47e7092019-01-25 04:00:14 +0000827 printf("Timeout on progress callback %d\n", p->nCb);
828 fflush(stdout);
829 p->timeoutHit = 1;
830 }
831 return rc;
832}
833
834/*
drha1f79da2022-06-14 19:12:25 +0000835** Flag bits set by block_troublesome_sql()
836*/
837#define BTS_SELECT 0x000001
838#define BTS_NONSELECT 0x000002
839#define BTS_BADFUNC 0x000004
840
841/*
drha47e7092019-01-25 04:00:14 +0000842** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and
843** "PRAGMA parser_trace" since they can dramatically increase the
844** amount of output without actually testing anything useful.
845**
drh8df01492021-03-18 14:36:19 +0000846** Also block ATTACH if attaching a file from the filesystem.
drha47e7092019-01-25 04:00:14 +0000847*/
848static int block_troublesome_sql(
drha1f79da2022-06-14 19:12:25 +0000849 void *pClientData,
drha47e7092019-01-25 04:00:14 +0000850 int eCode,
851 const char *zArg1,
852 const char *zArg2,
853 const char *zArg3,
854 const char *zArg4
855){
drha1f79da2022-06-14 19:12:25 +0000856 unsigned int *pFlags = (unsigned int*)pClientData;
drha47e7092019-01-25 04:00:14 +0000857 (void)zArg3;
858 (void)zArg4;
drha1f79da2022-06-14 19:12:25 +0000859 switch( eCode ){
860 case SQLITE_PRAGMA: {
861 if( sqlite3_stricmp("busy_timeout",zArg1)==0
862 && (zArg2==0 || strtoll(zArg2,0,0)>100 || strtoll(zArg2,0,10)>100)
drh8df01492021-03-18 14:36:19 +0000863 ){
864 return SQLITE_DENY;
drha1f79da2022-06-14 19:12:25 +0000865 }else if( eVerbosity==0 ){
866 if( sqlite3_strnicmp("vdbe_", zArg1, 5)==0
867 || sqlite3_stricmp("parser_trace", zArg1)==0
868 || sqlite3_stricmp("temp_store_directory", zArg1)==0
869 ){
870 return SQLITE_DENY;
871 }
872 }else if( sqlite3_stricmp("oom",zArg1)==0
873 && zArg2!=0 && zArg2[0]!=0 ){
874 oomCounter = atoi(zArg2);
drh8df01492021-03-18 14:36:19 +0000875 }
drha1f79da2022-06-14 19:12:25 +0000876 *pFlags |= BTS_NONSELECT;
877 break;
drh39b3bcf2020-03-02 16:31:21 +0000878 }
drha1f79da2022-06-14 19:12:25 +0000879 case SQLITE_ATTACH: {
880 /* Deny the ATTACH if it is attaching anything other than an in-memory
881 ** database. */
882 *pFlags |= BTS_NONSELECT;
883 if( zArg1==0 ) return SQLITE_DENY;
884 if( strcmp(zArg1,":memory:")==0 ) return SQLITE_OK;
885 if( sqlite3_strglob("file:*[?]vfs=memdb", zArg1)==0
886 && sqlite3_strglob("file:*[^/a-zA-Z0-9_.]*[?]vfs=memdb", zArg1)!=0
887 ){
888 return SQLITE_OK;
889 }
890 return SQLITE_DENY;
drh657a7a62021-03-09 13:12:58 +0000891 }
drha1f79da2022-06-14 19:12:25 +0000892 case SQLITE_SELECT: {
893 *pFlags |= BTS_SELECT;
894 break;
895 }
896 case SQLITE_FUNCTION: {
897 static const char *azBadFuncs[] = {
898 "random",
899 "randomblob",
900 "rtreedepth",
901 };
902 int i;
903 for(i=0; i<sizeof(azBadFuncs)/sizeof(azBadFuncs[0]); i++){
904 if( sqlite3_stricmp(azBadFuncs[i], zArg2)==0 ){
905 *pFlags |= BTS_BADFUNC;
906 break;
907 }
908 }
909 break;
910 }
911 case SQLITE_READ: {
912 /* Benign */
913 break;
914 }
915 default: {
916 *pFlags |= BTS_NONSELECT;
917 }
drha47e7092019-01-25 04:00:14 +0000918 }
919 return SQLITE_OK;
920}
921
drha1f79da2022-06-14 19:12:25 +0000922/* Implementation found in fuzzinvariant.c */
923int fuzz_invariant(
924 sqlite3 *db, /* The database connection */
925 sqlite3_stmt *pStmt, /* Test statement stopped on an SQLITE_ROW */
926 int iCnt, /* Invariant sequence number, starting at 0 */
927 int iRow, /* The row number for pStmt */
928 int *pbCorrupt /* IN/OUT: Flag indicating a corrupt database file */
929);
930
drha47e7092019-01-25 04:00:14 +0000931/*
932** Run the SQL text
933*/
drha1f79da2022-06-14 19:12:25 +0000934static int runDbSql(sqlite3 *db, const char *zSql, unsigned int *pBtsFlags){
drha47e7092019-01-25 04:00:14 +0000935 int rc;
936 sqlite3_stmt *pStmt;
drha1f79da2022-06-14 19:12:25 +0000937 int bCorrupt = 0;
drhaf638922019-02-07 00:17:36 +0000938 while( isspace(zSql[0]&0x7f) ) zSql++;
drha47e7092019-01-25 04:00:14 +0000939 if( zSql[0]==0 ) return SQLITE_OK;
drhdf216592019-01-25 04:43:26 +0000940 if( eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +0000941 printf("RUNNING-SQL: [%s]\n", zSql);
942 fflush(stdout);
943 }
drha1f79da2022-06-14 19:12:25 +0000944 (*pBtsFlags) = 0;
drha47e7092019-01-25 04:00:14 +0000945 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
946 if( rc==SQLITE_OK ){
drha1f79da2022-06-14 19:12:25 +0000947 int nRow = 0;
drha47e7092019-01-25 04:00:14 +0000948 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
drha1f79da2022-06-14 19:12:25 +0000949 nRow++;
drh0c278c32022-06-15 10:46:52 +0000950 if( (*pBtsFlags)==BTS_SELECT && g.doInvariantChecks ){
drha1f79da2022-06-14 19:12:25 +0000951 int iCnt = 0;
952 for(iCnt=0; iCnt<99999; iCnt++){
953 rc = fuzz_invariant(db, pStmt, iCnt, nRow, &bCorrupt);
954 if( rc==SQLITE_DONE ) break;
955 if( eVerbosity>0 ){
956 if( rc==SQLITE_OK ){
957 printf("invariant-check: ok\n");
958 }else if( rc==SQLITE_CORRUPT ){
959 printf("invariant-check: failed due to database corruption\n");
960 }
961 }
962 }
963 }
drhdf216592019-01-25 04:43:26 +0000964 if( eVerbosity>=5 ){
drha47e7092019-01-25 04:00:14 +0000965 int j;
966 for(j=0; j<sqlite3_column_count(pStmt); j++){
967 if( j ) printf(",");
968 switch( sqlite3_column_type(pStmt, j) ){
969 case SQLITE_NULL: {
970 printf("NULL");
971 break;
972 }
973 case SQLITE_INTEGER:
974 case SQLITE_FLOAT: {
975 printf("%s", sqlite3_column_text(pStmt, j));
976 break;
977 }
978 case SQLITE_BLOB: {
979 int n = sqlite3_column_bytes(pStmt, j);
980 int i;
981 const unsigned char *a;
982 a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
983 printf("x'");
984 for(i=0; i<n; i++){
985 printf("%02x", a[i]);
986 }
987 printf("'");
988 break;
989 }
990 case SQLITE_TEXT: {
991 int n = sqlite3_column_bytes(pStmt, j);
992 int i;
993 const unsigned char *a;
994 a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
995 printf("'");
996 for(i=0; i<n; i++){
997 if( a[i]=='\'' ){
998 printf("''");
999 }else{
1000 putchar(a[i]);
1001 }
1002 }
1003 printf("'");
1004 break;
1005 }
1006 } /* End switch() */
1007 } /* End for() */
1008 printf("\n");
1009 fflush(stdout);
drhdf216592019-01-25 04:43:26 +00001010 } /* End if( eVerbosity>=5 ) */
drha47e7092019-01-25 04:00:14 +00001011 } /* End while( SQLITE_ROW */
drhdf216592019-01-25 04:43:26 +00001012 if( rc!=SQLITE_DONE && eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +00001013 printf("SQL-ERROR: (%d) %s\n", rc, sqlite3_errmsg(db));
1014 fflush(stdout);
1015 }
drhdf216592019-01-25 04:43:26 +00001016 }else if( eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +00001017 printf("SQL-ERROR (%d): %s\n", rc, sqlite3_errmsg(db));
1018 fflush(stdout);
1019 } /* End if( SQLITE_OK ) */
1020 return sqlite3_finalize(pStmt);
1021}
1022
1023/* Invoke this routine to run a single test case */
drh075201e2021-10-27 12:05:28 +00001024int runCombinedDbSqlInput(
1025 const uint8_t *aData, /* Combined DB+SQL content */
1026 size_t nByte, /* Size of aData in bytes */
1027 int iTimeout, /* Use this timeout */
1028 int bScript, /* If true, just render CLI output */
1029 int iSqlId /* SQL identifier */
1030){
drha47e7092019-01-25 04:00:14 +00001031 int rc; /* SQLite API return value */
1032 int iSql; /* Index in aData[] of start of SQL */
1033 unsigned char *aDb = 0; /* Decoded database content */
1034 int nDb = 0; /* Size of the decoded database */
1035 int i; /* Loop counter */
1036 int j; /* Start of current SQL statement */
1037 char *zSql = 0; /* SQL text to run */
1038 int nSql; /* Bytes of SQL text */
1039 FuzzCtx cx; /* Fuzzing context */
drha1f79da2022-06-14 19:12:25 +00001040 unsigned int btsFlags = 0; /* Parsing flags */
drha47e7092019-01-25 04:00:14 +00001041
1042 if( nByte<10 ) return 0;
1043 if( sqlite3_initialize() ) return 0;
1044 if( sqlite3_memory_used()!=0 ){
1045 int nAlloc = 0;
1046 int nNotUsed = 0;
1047 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
drh672f07c2020-10-20 14:40:53 +00001048 fprintf(stderr,"memory leak prior to test start:"
1049 " %lld bytes in %d allocations\n",
drha47e7092019-01-25 04:00:14 +00001050 sqlite3_memory_used(), nAlloc);
1051 exit(1);
1052 }
1053 memset(&cx, 0, sizeof(cx));
1054 iSql = decodeDatabase((unsigned char*)aData, (int)nByte, &aDb, &nDb);
1055 if( iSql<0 ) return 0;
drhed457032019-01-25 17:51:06 +00001056 nSql = (int)(nByte - iSql);
drh075201e2021-10-27 12:05:28 +00001057 if( bScript ){
1058 char zName[100];
1059 sqlite3_snprintf(sizeof(zName),zName,"dbsql%06d.db",iSqlId);
1060 renderDbSqlForCLI(stdout, zName, aDb, nDb,
1061 (unsigned char*)(aData+iSql), nSql);
1062 sqlite3_free(aDb);
1063 return 0;
1064 }
drhdf216592019-01-25 04:43:26 +00001065 if( eVerbosity>=3 ){
drha47e7092019-01-25 04:00:14 +00001066 printf(
1067 "****** %d-byte input, %d-byte database, %d-byte script "
1068 "******\n", (int)nByte, nDb, nSql);
1069 fflush(stdout);
1070 }
1071 rc = sqlite3_open(0, &cx.db);
drh672f07c2020-10-20 14:40:53 +00001072 if( rc ){
1073 sqlite3_free(aDb);
1074 return 1;
1075 }
drha47e7092019-01-25 04:00:14 +00001076 if( bVdbeDebug ){
1077 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
1078 }
1079
1080 /* Invoke the progress handler frequently to check to see if we
1081 ** are taking too long. The progress handler will return true
drhed457032019-01-25 17:51:06 +00001082 ** (which will block further processing) if more than giTimeout seconds have
drha47e7092019-01-25 04:00:14 +00001083 ** elapsed since the start of the test.
1084 */
1085 cx.iLastCb = timeOfDay();
drh237f41a2020-12-21 12:14:59 +00001086 cx.iCutoffTime = cx.iLastCb + (iTimeout<giTimeout ? iTimeout : giTimeout);
drha47e7092019-01-25 04:00:14 +00001087 cx.mxCb = mxProgressCb;
1088#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1089 sqlite3_progress_handler(cx.db, 10, progress_handler, (void*)&cx);
1090#endif
1091
1092 /* Set a limit on the maximum size of a prepared statement, and the
1093 ** maximum length of a string or blob */
1094 if( vdbeOpLimit>0 ){
1095 sqlite3_limit(cx.db, SQLITE_LIMIT_VDBE_OP, vdbeOpLimit);
1096 }
1097 if( lengthLimit>0 ){
1098 sqlite3_limit(cx.db, SQLITE_LIMIT_LENGTH, lengthLimit);
1099 }
drhbe03cc92020-01-20 14:42:09 +00001100 if( depthLimit>0 ){
1101 sqlite3_limit(cx.db, SQLITE_LIMIT_EXPR_DEPTH, depthLimit);
1102 }
drh4b3282d2020-04-07 15:07:11 +00001103 sqlite3_limit(cx.db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 100);
drh31999c52019-11-14 17:46:32 +00001104 sqlite3_hard_heap_limit64(heapLimit);
drha47e7092019-01-25 04:00:14 +00001105
1106 if( nDb>=20 && aDb[18]==2 && aDb[19]==2 ){
1107 aDb[18] = aDb[19] = 1;
1108 }
1109 rc = sqlite3_deserialize(cx.db, "main", aDb, nDb, nDb,
1110 SQLITE_DESERIALIZE_RESIZEABLE |
1111 SQLITE_DESERIALIZE_FREEONCLOSE);
1112 if( rc ){
1113 fprintf(stderr, "sqlite3_deserialize() failed with %d\n", rc);
1114 goto testrun_finished;
1115 }
1116 if( maxDbSize>0 ){
1117 sqlite3_int64 x = maxDbSize;
1118 sqlite3_file_control(cx.db, "main", SQLITE_FCNTL_SIZE_LIMIT, &x);
1119 }
1120
drh725a9c72019-01-25 13:03:38 +00001121 /* For high debugging levels, turn on debug mode */
1122 if( eVerbosity>=5 ){
1123 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON;", 0, 0, 0);
1124 }
1125
drha47e7092019-01-25 04:00:14 +00001126 /* Block debug pragmas and ATTACH/DETACH. But wait until after
1127 ** deserialize to do this because deserialize depends on ATTACH */
drha1f79da2022-06-14 19:12:25 +00001128 sqlite3_set_authorizer(cx.db, block_troublesome_sql, &btsFlags);
drha47e7092019-01-25 04:00:14 +00001129
drh0fab1092022-02-04 19:13:18 +00001130#ifdef VT02_SOURCES
1131 sqlite3_vt02_init(cx.db, 0, 0);
1132#endif
1133
drha47e7092019-01-25 04:00:14 +00001134 /* Consistent PRNG seed */
drh319deef2021-04-04 23:56:15 +00001135#ifdef SQLITE_TESTCTRL_PRNG_SEED
1136 sqlite3_table_column_metadata(cx.db, 0, "x", 0, 0, 0, 0, 0, 0);
1137 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, cx.db);
1138#else
drha47e7092019-01-25 04:00:14 +00001139 sqlite3_randomness(0,0);
drh319deef2021-04-04 23:56:15 +00001140#endif
drha47e7092019-01-25 04:00:14 +00001141
1142 zSql = sqlite3_malloc( nSql + 1 );
1143 if( zSql==0 ){
1144 fprintf(stderr, "Out of memory!\n");
1145 }else{
1146 memcpy(zSql, aData+iSql, nSql);
1147 zSql[nSql] = 0;
1148 for(i=j=0; zSql[i]; i++){
1149 if( zSql[i]==';' ){
1150 char cSaved = zSql[i+1];
1151 zSql[i+1] = 0;
1152 if( sqlite3_complete(zSql+j) ){
drha1f79da2022-06-14 19:12:25 +00001153 rc = runDbSql(cx.db, zSql+j, &btsFlags);
drha47e7092019-01-25 04:00:14 +00001154 j = i+1;
1155 }
1156 zSql[i+1] = cSaved;
1157 if( rc==SQLITE_INTERRUPT || progress_handler(&cx) ){
1158 goto testrun_finished;
1159 }
1160 }
1161 }
1162 if( j<i ){
drha1f79da2022-06-14 19:12:25 +00001163 runDbSql(cx.db, zSql+j, &btsFlags);
drha47e7092019-01-25 04:00:14 +00001164 }
1165 }
1166testrun_finished:
1167 sqlite3_free(zSql);
1168 rc = sqlite3_close(cx.db);
1169 if( rc!=SQLITE_OK ){
1170 fprintf(stdout, "sqlite3_close() returns %d\n", rc);
1171 }
drh075201e2021-10-27 12:05:28 +00001172 if( eVerbosity>=2 && !bScript ){
drha47e7092019-01-25 04:00:14 +00001173 fprintf(stdout, "Peak memory usages: %f MB\n",
1174 sqlite3_memory_highwater(1) / 1000000.0);
1175 }
1176 if( sqlite3_memory_used()!=0 ){
1177 int nAlloc = 0;
1178 int nNotUsed = 0;
1179 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
1180 fprintf(stderr,"Memory leak: %lld bytes in %d allocations\n",
1181 sqlite3_memory_used(), nAlloc);
1182 exit(1);
1183 }
drh319deef2021-04-04 23:56:15 +00001184 sqlite3_hard_heap_limit64(0);
1185 sqlite3_soft_heap_limit64(0);
drha47e7092019-01-25 04:00:14 +00001186 return 0;
1187}
1188
1189/*
1190** END of the dbsqlfuzz code
1191***************************************************************************/
1192
1193/* Look at a SQL text and try to determine if it begins with a database
1194** description, such as would be found in a dbsqlfuzz test case. Return
1195** true if this does appear to be a dbsqlfuzz test case and false otherwise.
1196*/
1197static int isDbSql(unsigned char *a, int n){
drhdf216592019-01-25 04:43:26 +00001198 unsigned char buf[12];
1199 int i;
drha47e7092019-01-25 04:00:14 +00001200 if( n>4 && memcmp(a,"\n--\n",4)==0 ) return 1;
1201 while( n>0 && isspace(a[0]) ){ a++; n--; }
drhdf216592019-01-25 04:43:26 +00001202 for(i=0; n>0 && i<8; n--, a++){
1203 if( isxdigit(a[0]) ) buf[i++] = a[0];
1204 }
1205 if( i==8 && memcmp(buf,"53514c69",8)==0 ) return 1;
drha47e7092019-01-25 04:00:14 +00001206 return 0;
1207}
1208
drhe5da9352019-01-27 01:11:40 +00001209/* Implementation of the isdbsql(TEXT) SQL function.
1210*/
1211static void isDbSqlFunc(
1212 sqlite3_context *context,
1213 int argc,
1214 sqlite3_value **argv
1215){
1216 int n = sqlite3_value_bytes(argv[0]);
1217 unsigned char *a = (unsigned char*)sqlite3_value_blob(argv[0]);
1218 sqlite3_result_int(context, a!=0 && n>0 && isDbSql(a,n));
1219}
drha47e7092019-01-25 04:00:14 +00001220
drh3b74d032015-05-25 18:48:19 +00001221/* Methods for the VHandle object
1222*/
1223static int inmemClose(sqlite3_file *pFile){
1224 VHandle *p = (VHandle*)pFile;
1225 VFile *pVFile = p->pVFile;
1226 pVFile->nRef--;
1227 if( pVFile->nRef==0 && pVFile->zFilename==0 ){
1228 pVFile->sz = -1;
1229 free(pVFile->a);
1230 pVFile->a = 0;
1231 }
1232 return SQLITE_OK;
1233}
1234static int inmemRead(
1235 sqlite3_file *pFile, /* Read from this open file */
1236 void *pData, /* Store content in this buffer */
1237 int iAmt, /* Bytes of content */
1238 sqlite3_int64 iOfst /* Start reading here */
1239){
1240 VHandle *pHandle = (VHandle*)pFile;
1241 VFile *pVFile = pHandle->pVFile;
1242 if( iOfst<0 || iOfst>=pVFile->sz ){
1243 memset(pData, 0, iAmt);
1244 return SQLITE_IOERR_SHORT_READ;
1245 }
1246 if( iOfst+iAmt>pVFile->sz ){
1247 memset(pData, 0, iAmt);
drh1573dc32015-05-25 22:29:26 +00001248 iAmt = (int)(pVFile->sz - iOfst);
drhe45985b2018-12-14 02:29:56 +00001249 memcpy(pData, pVFile->a + iOfst, iAmt);
drh3b74d032015-05-25 18:48:19 +00001250 return SQLITE_IOERR_SHORT_READ;
1251 }
drhaca7ea12015-05-25 23:14:37 +00001252 memcpy(pData, pVFile->a + iOfst, iAmt);
drh3b74d032015-05-25 18:48:19 +00001253 return SQLITE_OK;
1254}
1255static int inmemWrite(
1256 sqlite3_file *pFile, /* Write to this file */
1257 const void *pData, /* Content to write */
1258 int iAmt, /* bytes to write */
1259 sqlite3_int64 iOfst /* Start writing here */
1260){
1261 VHandle *pHandle = (VHandle*)pFile;
1262 VFile *pVFile = pHandle->pVFile;
1263 if( iOfst+iAmt > pVFile->sz ){
drha9542b12015-05-25 19:35:42 +00001264 if( iOfst+iAmt >= MX_FILE_SZ ){
1265 return SQLITE_FULL;
1266 }
drh1573dc32015-05-25 22:29:26 +00001267 pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt));
drh908aced2015-05-26 16:12:45 +00001268 if( iOfst > pVFile->sz ){
1269 memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz));
1270 }
drh1573dc32015-05-25 22:29:26 +00001271 pVFile->sz = (int)(iOfst + iAmt);
drh3b74d032015-05-25 18:48:19 +00001272 }
1273 memcpy(pVFile->a + iOfst, pData, iAmt);
1274 return SQLITE_OK;
1275}
1276static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){
1277 VHandle *pHandle = (VHandle*)pFile;
1278 VFile *pVFile = pHandle->pVFile;
drh1573dc32015-05-25 22:29:26 +00001279 if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize;
drh3b74d032015-05-25 18:48:19 +00001280 return SQLITE_OK;
1281}
1282static int inmemSync(sqlite3_file *pFile, int flags){
1283 return SQLITE_OK;
1284}
1285static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){
1286 *pSize = ((VHandle*)pFile)->pVFile->sz;
1287 return SQLITE_OK;
1288}
1289static int inmemLock(sqlite3_file *pFile, int type){
1290 return SQLITE_OK;
1291}
1292static int inmemUnlock(sqlite3_file *pFile, int type){
1293 return SQLITE_OK;
1294}
1295static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){
1296 *pOut = 0;
1297 return SQLITE_OK;
1298}
1299static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){
1300 return SQLITE_NOTFOUND;
1301}
1302static int inmemSectorSize(sqlite3_file *pFile){
1303 return 512;
1304}
1305static int inmemDeviceCharacteristics(sqlite3_file *pFile){
1306 return
1307 SQLITE_IOCAP_SAFE_APPEND |
1308 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
1309 SQLITE_IOCAP_POWERSAFE_OVERWRITE;
1310}
1311
1312
1313/* Method table for VHandle
1314*/
1315static sqlite3_io_methods VHandleMethods = {
1316 /* iVersion */ 1,
1317 /* xClose */ inmemClose,
1318 /* xRead */ inmemRead,
1319 /* xWrite */ inmemWrite,
1320 /* xTruncate */ inmemTruncate,
1321 /* xSync */ inmemSync,
1322 /* xFileSize */ inmemFileSize,
1323 /* xLock */ inmemLock,
1324 /* xUnlock */ inmemUnlock,
1325 /* xCheck... */ inmemCheckReservedLock,
1326 /* xFileCtrl */ inmemFileControl,
1327 /* xSectorSz */ inmemSectorSize,
1328 /* xDevchar */ inmemDeviceCharacteristics,
1329 /* xShmMap */ 0,
1330 /* xShmLock */ 0,
1331 /* xShmBarrier */ 0,
1332 /* xShmUnmap */ 0,
1333 /* xFetch */ 0,
1334 /* xUnfetch */ 0
1335};
1336
1337/*
1338** Open a new file in the inmem VFS. All files are anonymous and are
1339** delete-on-close.
1340*/
1341static int inmemOpen(
1342 sqlite3_vfs *pVfs,
1343 const char *zFilename,
1344 sqlite3_file *pFile,
1345 int openFlags,
1346 int *pOutFlags
1347){
1348 VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)"");
1349 VHandle *pHandle = (VHandle*)pFile;
drha9542b12015-05-25 19:35:42 +00001350 if( pVFile==0 ){
1351 return SQLITE_FULL;
1352 }
drh3b74d032015-05-25 18:48:19 +00001353 pHandle->pVFile = pVFile;
1354 pVFile->nRef++;
1355 pFile->pMethods = &VHandleMethods;
1356 if( pOutFlags ) *pOutFlags = openFlags;
1357 return SQLITE_OK;
1358}
1359
1360/*
1361** Delete a file by name
1362*/
1363static int inmemDelete(
1364 sqlite3_vfs *pVfs,
1365 const char *zFilename,
1366 int syncdir
1367){
1368 VFile *pVFile = findVFile(zFilename);
1369 if( pVFile==0 ) return SQLITE_OK;
1370 if( pVFile->nRef==0 ){
1371 free(pVFile->zFilename);
1372 pVFile->zFilename = 0;
1373 pVFile->sz = -1;
1374 free(pVFile->a);
1375 pVFile->a = 0;
1376 return SQLITE_OK;
1377 }
1378 return SQLITE_IOERR_DELETE;
1379}
1380
1381/* Check for the existance of a file
1382*/
1383static int inmemAccess(
1384 sqlite3_vfs *pVfs,
1385 const char *zFilename,
1386 int flags,
1387 int *pResOut
1388){
1389 VFile *pVFile = findVFile(zFilename);
1390 *pResOut = pVFile!=0;
1391 return SQLITE_OK;
1392}
1393
1394/* Get the canonical pathname for a file
1395*/
1396static int inmemFullPathname(
1397 sqlite3_vfs *pVfs,
1398 const char *zFilename,
1399 int nOut,
1400 char *zOut
1401){
1402 sqlite3_snprintf(nOut, zOut, "%s", zFilename);
1403 return SQLITE_OK;
1404}
1405
drhbeaf5142016-12-26 00:15:56 +00001406/* Always use the same random see, for repeatability.
1407*/
1408static int inmemRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
1409 memset(zBuf, 0, nBuf);
1410 memcpy(zBuf, &g.uRandom, nBuf<sizeof(g.uRandom) ? nBuf : sizeof(g.uRandom));
1411 return nBuf;
1412}
1413
drh3b74d032015-05-25 18:48:19 +00001414/*
1415** Register the VFS that reads from the g.aFile[] set of files.
1416*/
drhbeaf5142016-12-26 00:15:56 +00001417static void inmemVfsRegister(int makeDefault){
drh3b74d032015-05-25 18:48:19 +00001418 static sqlite3_vfs inmemVfs;
1419 sqlite3_vfs *pDefault = sqlite3_vfs_find(0);
drh5337dac2015-11-25 15:15:03 +00001420 inmemVfs.iVersion = 3;
drh3b74d032015-05-25 18:48:19 +00001421 inmemVfs.szOsFile = sizeof(VHandle);
1422 inmemVfs.mxPathname = 200;
1423 inmemVfs.zName = "inmem";
1424 inmemVfs.xOpen = inmemOpen;
1425 inmemVfs.xDelete = inmemDelete;
1426 inmemVfs.xAccess = inmemAccess;
1427 inmemVfs.xFullPathname = inmemFullPathname;
drhbeaf5142016-12-26 00:15:56 +00001428 inmemVfs.xRandomness = inmemRandomness;
drh3b74d032015-05-25 18:48:19 +00001429 inmemVfs.xSleep = pDefault->xSleep;
drh5337dac2015-11-25 15:15:03 +00001430 inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64;
drhbeaf5142016-12-26 00:15:56 +00001431 sqlite3_vfs_register(&inmemVfs, makeDefault);
drh3b74d032015-05-25 18:48:19 +00001432};
1433
drh3b74d032015-05-25 18:48:19 +00001434/*
drhe5c5f2c2015-05-26 00:28:08 +00001435** Allowed values for the runFlags parameter to runSql()
1436*/
1437#define SQL_TRACE 0x0001 /* Print each SQL statement as it is prepared */
1438#define SQL_OUTPUT 0x0002 /* Show the SQL output */
1439
1440/*
drh3b74d032015-05-25 18:48:19 +00001441** Run multiple commands of SQL. Similar to sqlite3_exec(), but does not
1442** stop if an error is encountered.
1443*/
drhe5c5f2c2015-05-26 00:28:08 +00001444static void runSql(sqlite3 *db, const char *zSql, unsigned runFlags){
drh3b74d032015-05-25 18:48:19 +00001445 const char *zMore;
1446 sqlite3_stmt *pStmt;
1447
1448 while( zSql && zSql[0] ){
1449 zMore = 0;
1450 pStmt = 0;
1451 sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore);
drh4ab31472015-05-25 22:17:06 +00001452 if( zMore==zSql ) break;
drhe5c5f2c2015-05-26 00:28:08 +00001453 if( runFlags & SQL_TRACE ){
drh4ab31472015-05-25 22:17:06 +00001454 const char *z = zSql;
1455 int n;
drhc56fac72015-10-29 13:48:15 +00001456 while( z<zMore && ISSPACE(z[0]) ) z++;
drh4ab31472015-05-25 22:17:06 +00001457 n = (int)(zMore - z);
drhc56fac72015-10-29 13:48:15 +00001458 while( n>0 && ISSPACE(z[n-1]) ) n--;
drh4ab31472015-05-25 22:17:06 +00001459 if( n==0 ) break;
1460 if( pStmt==0 ){
1461 printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db));
1462 }else{
1463 printf("TRACE: %.*s\n", n, z);
1464 }
1465 }
drh3b74d032015-05-25 18:48:19 +00001466 zSql = zMore;
1467 if( pStmt ){
drhe5c5f2c2015-05-26 00:28:08 +00001468 if( (runFlags & SQL_OUTPUT)==0 ){
1469 while( SQLITE_ROW==sqlite3_step(pStmt) ){}
1470 }else{
1471 int nCol = -1;
1472 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1473 int i;
1474 if( nCol<0 ){
1475 nCol = sqlite3_column_count(pStmt);
1476 }else if( nCol>0 ){
1477 printf("--------------------------------------------\n");
1478 }
1479 for(i=0; i<nCol; i++){
1480 int eType = sqlite3_column_type(pStmt,i);
1481 printf("%s = ", sqlite3_column_name(pStmt,i));
1482 switch( eType ){
1483 case SQLITE_NULL: {
1484 printf("NULL\n");
1485 break;
1486 }
1487 case SQLITE_INTEGER: {
1488 printf("INT %s\n", sqlite3_column_text(pStmt,i));
1489 break;
1490 }
1491 case SQLITE_FLOAT: {
1492 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i));
1493 break;
1494 }
1495 case SQLITE_TEXT: {
1496 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i));
1497 break;
1498 }
1499 case SQLITE_BLOB: {
1500 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i));
1501 break;
1502 }
1503 }
1504 }
1505 }
1506 }
drh3b74d032015-05-25 18:48:19 +00001507 sqlite3_finalize(pStmt);
drh3b74d032015-05-25 18:48:19 +00001508 }
1509 }
1510}
1511
drha9542b12015-05-25 19:35:42 +00001512/*
drh9a645862015-06-24 12:44:42 +00001513** Rebuild the database file.
1514**
1515** (1) Remove duplicate entries
1516** (2) Put all entries in order
1517** (3) Vacuum
1518*/
drhe5da9352019-01-27 01:11:40 +00001519static void rebuild_database(sqlite3 *db, int dbSqlOnly){
drh9a645862015-06-24 12:44:42 +00001520 int rc;
drhe5da9352019-01-27 01:11:40 +00001521 char *zSql;
1522 zSql = sqlite3_mprintf(
drh9a645862015-06-24 12:44:42 +00001523 "BEGIN;\n"
1524 "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n"
1525 "DELETE FROM db;\n"
drh5ecf9032018-05-08 12:49:53 +00001526 "INSERT INTO db(dbid, dbcontent) "
1527 " SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n"
drh9a645862015-06-24 12:44:42 +00001528 "DROP TABLE dbx;\n"
drhe5da9352019-01-27 01:11:40 +00001529 "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql %s;\n"
drh9a645862015-06-24 12:44:42 +00001530 "DELETE FROM xsql;\n"
drh5ecf9032018-05-08 12:49:53 +00001531 "INSERT INTO xsql(sqlid,sqltext) "
1532 " SELECT NULL, sqltext FROM sx ORDER BY 2;\n"
drh9a645862015-06-24 12:44:42 +00001533 "DROP TABLE sx;\n"
1534 "COMMIT;\n"
1535 "PRAGMA page_size=1024;\n"
drhe5da9352019-01-27 01:11:40 +00001536 "VACUUM;\n",
1537 dbSqlOnly ? " WHERE isdbsql(sqltext)" : ""
1538 );
1539 rc = sqlite3_exec(db, zSql, 0, 0, 0);
1540 sqlite3_free(zSql);
drh9a645862015-06-24 12:44:42 +00001541 if( rc ) fatalError("cannot rebuild: %s", sqlite3_errmsg(db));
1542}
1543
1544/*
drh53e66c32015-07-24 15:49:23 +00001545** Return the value of a hexadecimal digit. Return -1 if the input
1546** is not a hex digit.
1547*/
1548static int hexDigitValue(char c){
1549 if( c>='0' && c<='9' ) return c - '0';
1550 if( c>='a' && c<='f' ) return c - 'a' + 10;
1551 if( c>='A' && c<='F' ) return c - 'A' + 10;
1552 return -1;
1553}
1554
1555/*
1556** Interpret zArg as an integer value, possibly with suffixes.
1557*/
1558static int integerValue(const char *zArg){
1559 sqlite3_int64 v = 0;
1560 static const struct { char *zSuffix; int iMult; } aMult[] = {
1561 { "KiB", 1024 },
1562 { "MiB", 1024*1024 },
1563 { "GiB", 1024*1024*1024 },
1564 { "KB", 1000 },
1565 { "MB", 1000000 },
1566 { "GB", 1000000000 },
1567 { "K", 1000 },
1568 { "M", 1000000 },
1569 { "G", 1000000000 },
1570 };
1571 int i;
1572 int isNeg = 0;
1573 if( zArg[0]=='-' ){
1574 isNeg = 1;
1575 zArg++;
1576 }else if( zArg[0]=='+' ){
1577 zArg++;
1578 }
1579 if( zArg[0]=='0' && zArg[1]=='x' ){
1580 int x;
1581 zArg += 2;
1582 while( (x = hexDigitValue(zArg[0]))>=0 ){
1583 v = (v<<4) + x;
1584 zArg++;
1585 }
1586 }else{
drhc56fac72015-10-29 13:48:15 +00001587 while( ISDIGIT(zArg[0]) ){
drh53e66c32015-07-24 15:49:23 +00001588 v = v*10 + zArg[0] - '0';
1589 zArg++;
1590 }
1591 }
1592 for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
1593 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1594 v *= aMult[i].iMult;
1595 break;
1596 }
1597 }
1598 if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648");
1599 return (int)(isNeg? -v : v);
1600}
1601
1602/*
drh725a9c72019-01-25 13:03:38 +00001603** Return the number of "v" characters in a string. Return 0 if there
1604** are any characters in the string other than "v".
1605*/
1606static int numberOfVChar(const char *z){
1607 int N = 0;
1608 while( z[0] && z[0]=='v' ){
1609 z++;
1610 N++;
1611 }
1612 return z[0]==0 ? N : 0;
1613}
1614
1615/*
drha9542b12015-05-25 19:35:42 +00001616** Print sketchy documentation for this utility program
1617*/
1618static void showHelp(void){
1619 printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0);
1620 printf(
1621"Read databases and SQL scripts from SOURCE-DB and execute each script against\n"
1622"each database, checking for crashes and memory leaks.\n"
1623"Options:\n"
drha36e01a2016-08-03 13:40:54 +00001624" --cell-size-check Set the PRAGMA cell_size_check=ON\n"
1625" --dbid N Use only the database where dbid=N\n"
1626" --export-db DIR Write databases to files(s) in DIR. Works with --dbid\n"
1627" --export-sql DIR Write SQL to file(s) in DIR. Also works with --sqlid\n"
1628" --help Show this help text\n"
drh5180d682018-08-06 01:39:31 +00001629" --info Show information about SOURCE-DB w/o running tests\n"
drh672f07c2020-10-20 14:40:53 +00001630" --limit-depth N Limit expression depth to N. Default: 500\n"
1631" --limit-heap N Limit heap memory to N. Default: 100M\n"
drha36e01a2016-08-03 13:40:54 +00001632" --limit-mem N Limit memory used by test SQLite instance to N bytes\n"
1633" --limit-vdbe Panic if any test runs for more than 100,000 cycles\n"
drhba6619d2021-04-23 12:58:16 +00001634" --load-sql FILE.. Load SQL scripts fron files into SOURCE-DB\n"
1635" --load-db FILE.. Load template databases from files into SOURCE_DB\n"
1636" --load-dbsql FILE.. Load dbsqlfuzz outputs into the xsql table\n"
1637" ^^^^------ Use \"-\" for FILE to read filenames from stdin\n"
drha36e01a2016-08-03 13:40:54 +00001638" -m TEXT Add a description to the database\n"
1639" --native-vfs Use the native VFS for initially empty database files\n"
drh174f8552017-03-20 22:58:27 +00001640" --native-malloc Turn off MEMSYS3/5 and Lookaside\n"
drhea432ba2016-11-11 16:33:47 +00001641" --oss-fuzz Enable OSS-FUZZ testing\n"
drhbeaf5142016-12-26 00:15:56 +00001642" --prng-seed N Seed value for the PRGN inside of SQLite\n"
drh5180d682018-08-06 01:39:31 +00001643" -q|--quiet Reduced output\n"
drh0c278c32022-06-15 10:46:52 +00001644" --query-invariants Run query invariant checks\n"
drha36e01a2016-08-03 13:40:54 +00001645" --rebuild Rebuild and vacuum the database file\n"
1646" --result-trace Show the results of each SQL command\n"
drh075201e2021-10-27 12:05:28 +00001647" --script Output CLI script instead of running tests\n"
drh672f07c2020-10-20 14:40:53 +00001648" --skip N Skip the first N test cases\n"
drhaa0696e2020-04-07 13:08:56 +00001649" --spinner Use a spinner to show progress\n"
drha36e01a2016-08-03 13:40:54 +00001650" --sqlid N Use only SQL where sqlid=N\n"
drh237f41a2020-12-21 12:14:59 +00001651" --timeout N Maximum time for any one test in N millseconds\n"
drha36e01a2016-08-03 13:40:54 +00001652" -v|--verbose Increased output. Repeat for more output.\n"
drh6e1c45e2019-12-18 13:42:04 +00001653" --vdbe-debug Activate VDBE debugging.\n"
drha9542b12015-05-25 19:35:42 +00001654 );
1655}
1656
drh3b74d032015-05-25 18:48:19 +00001657int main(int argc, char **argv){
1658 sqlite3_int64 iBegin; /* Start time of this program */
drh3b74d032015-05-25 18:48:19 +00001659 int quietFlag = 0; /* True if --quiet or -q */
1660 int verboseFlag = 0; /* True if --verbose or -v */
1661 char *zInsSql = 0; /* SQL statement for --load-db or --load-sql */
drh5ecf9032018-05-08 12:49:53 +00001662 int iFirstInsArg = 0; /* First argv[] for --load-db or --load-sql */
drh3b74d032015-05-25 18:48:19 +00001663 sqlite3 *db = 0; /* The open database connection */
drhd9972ef2015-05-26 17:57:56 +00001664 sqlite3_stmt *pStmt; /* A prepared statement */
drh3b74d032015-05-25 18:48:19 +00001665 int rc; /* Result code from SQLite interface calls */
1666 Blob *pSql; /* For looping over SQL scripts */
1667 Blob *pDb; /* For looping over template databases */
1668 int i; /* Loop index for the argv[] loop */
drhe5da9352019-01-27 01:11:40 +00001669 int dbSqlOnly = 0; /* Only use scripts that are dbsqlfuzz */
drha9542b12015-05-25 19:35:42 +00001670 int onlySqlid = -1; /* --sqlid */
1671 int onlyDbid = -1; /* --dbid */
drh15b31282015-05-25 21:59:05 +00001672 int nativeFlag = 0; /* --native-vfs */
drh9a645862015-06-24 12:44:42 +00001673 int rebuildFlag = 0; /* --rebuild */
drhd83e2832015-06-24 14:45:44 +00001674 int vdbeLimitFlag = 0; /* --limit-vdbe */
drh5180d682018-08-06 01:39:31 +00001675 int infoFlag = 0; /* --info */
drh672f07c2020-10-20 14:40:53 +00001676 int nSkip = 0; /* --skip */
drh075201e2021-10-27 12:05:28 +00001677 int bScript = 0; /* --script */
drhaa0696e2020-04-07 13:08:56 +00001678 int bSpinner = 0; /* True for --spinner */
drh94701b02015-06-24 13:25:34 +00001679 int timeoutTest = 0; /* undocumented --timeout-test flag */
drhe5c5f2c2015-05-26 00:28:08 +00001680 int runFlags = 0; /* Flags sent to runSql() */
drhd9972ef2015-05-26 17:57:56 +00001681 char *zMsg = 0; /* Add this message */
1682 int nSrcDb = 0; /* Number of source databases */
1683 char **azSrcDb = 0; /* Array of source database names */
1684 int iSrcDb; /* Loop over all source databases */
1685 int nTest = 0; /* Total number of tests performed */
1686 char *zDbName = ""; /* Appreviated name of a source database */
drh5ecf9032018-05-08 12:49:53 +00001687 const char *zFailCode = 0; /* Value of the TEST_FAILURE env variable */
drh1421d982015-05-27 03:46:18 +00001688 int cellSzCkFlag = 0; /* --cell-size-check */
drh5ecf9032018-05-08 12:49:53 +00001689 int sqlFuzz = 0; /* True for SQL fuzz. False for DB fuzz */
drh237f41a2020-12-21 12:14:59 +00001690 int iTimeout = 120000; /* Default 120-second timeout */
drh31999c52019-11-14 17:46:32 +00001691 int nMem = 0; /* Memory limit override */
drh362b66f2016-11-14 18:27:41 +00001692 int nMemThisDb = 0; /* Memory limit set by the CONFIG table */
drh40e0e0d2015-09-22 18:51:17 +00001693 char *zExpDb = 0; /* Write Databases to files in this directory */
1694 char *zExpSql = 0; /* Write SQL to files in this directory */
drh6653fbe2015-11-13 20:52:49 +00001695 void *pHeap = 0; /* Heap for use by SQLite */
drhea432ba2016-11-11 16:33:47 +00001696 int ossFuzz = 0; /* enable OSS-FUZZ testing */
drh362b66f2016-11-14 18:27:41 +00001697 int ossFuzzThisDb = 0; /* ossFuzz value for this particular database */
drh174f8552017-03-20 22:58:27 +00001698 int nativeMalloc = 0; /* Turn off MEMSYS3/5 and lookaside if true */
drhbeaf5142016-12-26 00:15:56 +00001699 sqlite3_vfs *pDfltVfs; /* The default VFS */
drhf2cf4122018-05-08 13:03:31 +00001700 int openFlags4Data; /* Flags for sqlite3_open_v2() */
drh237f41a2020-12-21 12:14:59 +00001701 int bTimer = 0; /* Show elapse time for each test */
drh725a9c72019-01-25 13:03:38 +00001702 int nV; /* How much to increase verbosity with -vvvv */
drh237f41a2020-12-21 12:14:59 +00001703 sqlite3_int64 tmStart; /* Start of each test */
drh3b74d032015-05-25 18:48:19 +00001704
drhbe536562021-10-23 11:30:35 +00001705 sqlite3_config(SQLITE_CONFIG_URI,1);
drh39b3bcf2020-03-02 16:31:21 +00001706 registerOomSimulator();
drh8055a3e2018-11-21 14:27:34 +00001707 sqlite3_initialize();
drh3b74d032015-05-25 18:48:19 +00001708 iBegin = timeOfDay();
drh94701b02015-06-24 13:25:34 +00001709#ifdef __unix__
drha7648f02019-12-18 13:02:18 +00001710 signal(SIGALRM, signalHandler);
1711 signal(SIGSEGV, signalHandler);
1712 signal(SIGABRT, signalHandler);
drh94701b02015-06-24 13:25:34 +00001713#endif
drh3b74d032015-05-25 18:48:19 +00001714 g.zArgv0 = argv[0];
drhf2cf4122018-05-08 13:03:31 +00001715 openFlags4Data = SQLITE_OPEN_READONLY;
drh4d6fda72015-05-26 18:58:32 +00001716 zFailCode = getenv("TEST_FAILURE");
drhbeaf5142016-12-26 00:15:56 +00001717 pDfltVfs = sqlite3_vfs_find(0);
1718 inmemVfsRegister(1);
drh3b74d032015-05-25 18:48:19 +00001719 for(i=1; i<argc; i++){
1720 const char *z = argv[i];
1721 if( z[0]=='-' ){
1722 z++;
1723 if( z[0]=='-' ) z++;
drh1421d982015-05-27 03:46:18 +00001724 if( strcmp(z,"cell-size-check")==0 ){
1725 cellSzCkFlag = 1;
1726 }else
drha9542b12015-05-25 19:35:42 +00001727 if( strcmp(z,"dbid")==0 ){
1728 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
drh53e66c32015-07-24 15:49:23 +00001729 onlyDbid = integerValue(argv[++i]);
drha9542b12015-05-25 19:35:42 +00001730 }else
drh40e0e0d2015-09-22 18:51:17 +00001731 if( strcmp(z,"export-db")==0 ){
1732 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1733 zExpDb = argv[++i];
1734 }else
drhe5da9352019-01-27 01:11:40 +00001735 if( strcmp(z,"export-sql")==0 || strcmp(z,"export-dbsql")==0 ){
drh40e0e0d2015-09-22 18:51:17 +00001736 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1737 zExpSql = argv[++i];
1738 }else
drh3b74d032015-05-25 18:48:19 +00001739 if( strcmp(z,"help")==0 ){
1740 showHelp();
1741 return 0;
1742 }else
drh5180d682018-08-06 01:39:31 +00001743 if( strcmp(z,"info")==0 ){
1744 infoFlag = 1;
1745 }else
drhbe03cc92020-01-20 14:42:09 +00001746 if( strcmp(z,"limit-depth")==0 ){
1747 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1748 depthLimit = integerValue(argv[++i]);
1749 }else
drh672f07c2020-10-20 14:40:53 +00001750 if( strcmp(z,"limit-heap")==0 ){
1751 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1752 heapLimit = integerValue(argv[++i]);
1753 }else
drh53e66c32015-07-24 15:49:23 +00001754 if( strcmp(z,"limit-mem")==0 ){
1755 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1756 nMem = integerValue(argv[++i]);
1757 }else
drhd83e2832015-06-24 14:45:44 +00001758 if( strcmp(z,"limit-vdbe")==0 ){
1759 vdbeLimitFlag = 1;
1760 }else
drh3b74d032015-05-25 18:48:19 +00001761 if( strcmp(z,"load-sql")==0 ){
drha8781d92020-02-25 20:05:58 +00001762 zInsSql = "INSERT INTO xsql(sqltext)"
1763 "VALUES(CAST(readtextfile(?1) AS text))";
drh3b74d032015-05-25 18:48:19 +00001764 iFirstInsArg = i+1;
drhf2cf4122018-05-08 13:03:31 +00001765 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
drh3b74d032015-05-25 18:48:19 +00001766 break;
1767 }else
1768 if( strcmp(z,"load-db")==0 ){
1769 zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
1770 iFirstInsArg = i+1;
drhf2cf4122018-05-08 13:03:31 +00001771 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
drh3b74d032015-05-25 18:48:19 +00001772 break;
1773 }else
drhe5da9352019-01-27 01:11:40 +00001774 if( strcmp(z,"load-dbsql")==0 ){
drha8781d92020-02-25 20:05:58 +00001775 zInsSql = "INSERT INTO xsql(sqltext)"
drh662bebb2021-10-27 13:16:33 +00001776 "VALUES(readfile(?1))";
drhe5da9352019-01-27 01:11:40 +00001777 iFirstInsArg = i+1;
1778 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1779 dbSqlOnly = 1;
1780 break;
1781 }else
drhd9972ef2015-05-26 17:57:56 +00001782 if( strcmp(z,"m")==0 ){
1783 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1784 zMsg = argv[++i];
drhf2cf4122018-05-08 13:03:31 +00001785 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
drhd9972ef2015-05-26 17:57:56 +00001786 }else
drh174f8552017-03-20 22:58:27 +00001787 if( strcmp(z,"native-malloc")==0 ){
1788 nativeMalloc = 1;
1789 }else
drh15b31282015-05-25 21:59:05 +00001790 if( strcmp(z,"native-vfs")==0 ){
1791 nativeFlag = 1;
1792 }else
drhea432ba2016-11-11 16:33:47 +00001793 if( strcmp(z,"oss-fuzz")==0 ){
1794 ossFuzz = 1;
1795 }else
drhbeaf5142016-12-26 00:15:56 +00001796 if( strcmp(z,"prng-seed")==0 ){
1797 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1798 g.uRandom = atoi(argv[++i]);
1799 }else
drh3b74d032015-05-25 18:48:19 +00001800 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
1801 quietFlag = 1;
1802 verboseFlag = 0;
drha47e7092019-01-25 04:00:14 +00001803 eVerbosity = 0;
drh3b74d032015-05-25 18:48:19 +00001804 }else
drh0c278c32022-06-15 10:46:52 +00001805 if( strcmp(z,"query-invariants")==0 ){
1806 g.doInvariantChecks = 1;
1807 }else
drh9a645862015-06-24 12:44:42 +00001808 if( strcmp(z,"rebuild")==0 ){
1809 rebuildFlag = 1;
drhf2cf4122018-05-08 13:03:31 +00001810 openFlags4Data = SQLITE_OPEN_READWRITE;
drh9a645862015-06-24 12:44:42 +00001811 }else
drhe5c5f2c2015-05-26 00:28:08 +00001812 if( strcmp(z,"result-trace")==0 ){
1813 runFlags |= SQL_OUTPUT;
1814 }else
drh075201e2021-10-27 12:05:28 +00001815 if( strcmp(z,"script")==0 ){
1816 bScript = 1;
1817 }else
drh672f07c2020-10-20 14:40:53 +00001818 if( strcmp(z,"skip")==0 ){
1819 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1820 nSkip = atoi(argv[++i]);
1821 }else
drhaa0696e2020-04-07 13:08:56 +00001822 if( strcmp(z,"spinner")==0 ){
1823 bSpinner = 1;
1824 }else
drh237f41a2020-12-21 12:14:59 +00001825 if( strcmp(z,"timer")==0 ){
1826 bTimer = 1;
1827 }else
drha9542b12015-05-25 19:35:42 +00001828 if( strcmp(z,"sqlid")==0 ){
1829 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
drh53e66c32015-07-24 15:49:23 +00001830 onlySqlid = integerValue(argv[++i]);
drha9542b12015-05-25 19:35:42 +00001831 }else
drh92298632015-06-24 23:44:30 +00001832 if( strcmp(z,"timeout")==0 ){
1833 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
drh53e66c32015-07-24 15:49:23 +00001834 iTimeout = integerValue(argv[++i]);
drh92298632015-06-24 23:44:30 +00001835 }else
drh94701b02015-06-24 13:25:34 +00001836 if( strcmp(z,"timeout-test")==0 ){
1837 timeoutTest = 1;
1838#ifndef __unix__
1839 fatalError("timeout is not available on non-unix systems");
1840#endif
1841 }else
drh6e1c45e2019-12-18 13:42:04 +00001842 if( strcmp(z,"vdbe-debug")==0 ){
1843 bVdbeDebug = 1;
1844 }else
drh725a9c72019-01-25 13:03:38 +00001845 if( strcmp(z,"verbose")==0 ){
drh3b74d032015-05-25 18:48:19 +00001846 quietFlag = 0;
drh4c9d2282016-02-18 14:03:15 +00001847 verboseFlag++;
drha47e7092019-01-25 04:00:14 +00001848 eVerbosity++;
drh4c9d2282016-02-18 14:03:15 +00001849 if( verboseFlag>1 ) runFlags |= SQL_TRACE;
drh3b74d032015-05-25 18:48:19 +00001850 }else
drh725a9c72019-01-25 13:03:38 +00001851 if( (nV = numberOfVChar(z))>=1 ){
1852 quietFlag = 0;
1853 verboseFlag += nV;
1854 eVerbosity += nV;
1855 if( verboseFlag>1 ) runFlags |= SQL_TRACE;
1856 }else
drha47e7092019-01-25 04:00:14 +00001857 if( strcmp(z,"version")==0 ){
1858 int ii;
drhed457032019-01-25 17:51:06 +00001859 const char *zz;
drha47e7092019-01-25 04:00:14 +00001860 printf("SQLite %s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drhed457032019-01-25 17:51:06 +00001861 for(ii=0; (zz = sqlite3_compileoption_get(ii))!=0; ii++){
1862 printf("%s\n", zz);
drha47e7092019-01-25 04:00:14 +00001863 }
1864 return 0;
1865 }else
drh662bebb2021-10-27 13:16:33 +00001866 if( strcmp(z,"is-dbsql")==0 ){
1867 i++;
1868 for(i++; i<argc; i++){
1869 long nData;
1870 char *aData = readFile(argv[i], &nData);
drhbe2d6fd2021-10-27 15:16:30 +00001871 printf("%d %s\n", isDbSql((unsigned char*)aData,nData), argv[i]);
drh662bebb2021-10-27 13:16:33 +00001872 sqlite3_free(aData);
1873 }
1874 exit(0);
1875 }else
drh3b74d032015-05-25 18:48:19 +00001876 {
1877 fatalError("unknown option: %s", argv[i]);
1878 }
1879 }else{
drhd9972ef2015-05-26 17:57:56 +00001880 nSrcDb++;
1881 azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
1882 azSrcDb[nSrcDb-1] = argv[i];
drh3b74d032015-05-25 18:48:19 +00001883 }
1884 }
drhd9972ef2015-05-26 17:57:56 +00001885 if( nSrcDb==0 ) fatalError("no source database specified");
1886 if( nSrcDb>1 ){
1887 if( zMsg ){
1888 fatalError("cannot change the description of more than one database");
drh3b74d032015-05-25 18:48:19 +00001889 }
drhd9972ef2015-05-26 17:57:56 +00001890 if( zInsSql ){
1891 fatalError("cannot import into more than one database");
1892 }
drh3b74d032015-05-25 18:48:19 +00001893 }
1894
drhd9972ef2015-05-26 17:57:56 +00001895 /* Process each source database separately */
1896 for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
drh48b4bf22021-10-26 22:36:41 +00001897 char *zRawData = 0;
1898 long nRawData = 0;
drha7648f02019-12-18 13:02:18 +00001899 g.zDbFile = azSrcDb[iSrcDb];
drhbeaf5142016-12-26 00:15:56 +00001900 rc = sqlite3_open_v2(azSrcDb[iSrcDb], &db,
drhf2cf4122018-05-08 13:03:31 +00001901 openFlags4Data, pDfltVfs->zName);
drh48b4bf22021-10-26 22:36:41 +00001902 if( rc==SQLITE_OK ){
1903 rc = sqlite3_exec(db, "SELECT count(*) FROM sqlite_schema", 0, 0, 0);
1904 }
drhd9972ef2015-05-26 17:57:56 +00001905 if( rc ){
drh48b4bf22021-10-26 22:36:41 +00001906 sqlite3_close(db);
1907 zRawData = readFile(azSrcDb[iSrcDb], &nRawData);
1908 if( zRawData==0 ){
1909 fatalError("input file \"%s\" is not recognized\n", azSrcDb[iSrcDb]);
1910 }
1911 sqlite3_open(":memory:", &db);
drhd9972ef2015-05-26 17:57:56 +00001912 }
drh5180d682018-08-06 01:39:31 +00001913
1914 /* Print the description, if there is one */
1915 if( infoFlag ){
1916 int n;
1917 zDbName = azSrcDb[iSrcDb];
1918 i = (int)strlen(zDbName) - 1;
1919 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
1920 zDbName += i;
1921 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
1922 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
1923 printf("%s: %s", zDbName, sqlite3_column_text(pStmt,0));
1924 }else{
1925 printf("%s: (empty \"readme\")", zDbName);
1926 }
1927 sqlite3_finalize(pStmt);
1928 sqlite3_prepare_v2(db, "SELECT count(*) FROM db", -1, &pStmt, 0);
1929 if( pStmt
1930 && sqlite3_step(pStmt)==SQLITE_ROW
1931 && (n = sqlite3_column_int(pStmt,0))>0
1932 ){
1933 printf(" - %d DBs", n);
1934 }
1935 sqlite3_finalize(pStmt);
1936 sqlite3_prepare_v2(db, "SELECT count(*) FROM xsql", -1, &pStmt, 0);
1937 if( pStmt
1938 && sqlite3_step(pStmt)==SQLITE_ROW
1939 && (n = sqlite3_column_int(pStmt,0))>0
1940 ){
1941 printf(" - %d scripts", n);
1942 }
1943 sqlite3_finalize(pStmt);
1944 printf("\n");
1945 sqlite3_close(db);
drh48b4bf22021-10-26 22:36:41 +00001946 sqlite3_free(zRawData);
drh5180d682018-08-06 01:39:31 +00001947 continue;
1948 }
1949
drh9a645862015-06-24 12:44:42 +00001950 rc = sqlite3_exec(db,
drhd9972ef2015-05-26 17:57:56 +00001951 "CREATE TABLE IF NOT EXISTS db(\n"
1952 " dbid INTEGER PRIMARY KEY, -- database id\n"
1953 " dbcontent BLOB -- database disk file image\n"
1954 ");\n"
1955 "CREATE TABLE IF NOT EXISTS xsql(\n"
1956 " sqlid INTEGER PRIMARY KEY, -- SQL script id\n"
1957 " sqltext TEXT -- Text of SQL statements to run\n"
1958 ");"
1959 "CREATE TABLE IF NOT EXISTS readme(\n"
1960 " msg TEXT -- Human-readable description of this file\n"
1961 ");", 0, 0, 0);
1962 if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
1963 if( zMsg ){
1964 char *zSql;
1965 zSql = sqlite3_mprintf(
1966 "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
1967 rc = sqlite3_exec(db, zSql, 0, 0, 0);
1968 sqlite3_free(zSql);
1969 if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
1970 }
drh48b4bf22021-10-26 22:36:41 +00001971 if( zRawData ){
1972 zInsSql = "INSERT INTO xsql(sqltext) VALUES(?1)";
1973 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
1974 if( rc ) fatalError("cannot prepare statement [%s]: %s",
1975 zInsSql, sqlite3_errmsg(db));
1976 sqlite3_bind_text(pStmt, 1, zRawData, nRawData, SQLITE_STATIC);
1977 sqlite3_step(pStmt);
1978 rc = sqlite3_reset(pStmt);
1979 if( rc ) fatalError("insert failed for %s", argv[i]);
1980 sqlite3_finalize(pStmt);
1981 rebuild_database(db, dbSqlOnly);
1982 zInsSql = 0;
1983 sqlite3_free(zRawData);
1984 zRawData = 0;
1985 }
drh362b66f2016-11-14 18:27:41 +00001986 ossFuzzThisDb = ossFuzz;
1987
1988 /* If the CONFIG(name,value) table exists, read db-specific settings
1989 ** from that table */
1990 if( sqlite3_table_column_metadata(db,0,"config",0,0,0,0,0,0)==SQLITE_OK ){
drh5ecf9032018-05-08 12:49:53 +00001991 rc = sqlite3_prepare_v2(db, "SELECT name, value FROM config",
1992 -1, &pStmt, 0);
drh362b66f2016-11-14 18:27:41 +00001993 if( rc ) fatalError("cannot prepare query of CONFIG table: %s",
1994 sqlite3_errmsg(db));
1995 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1996 const char *zName = (const char *)sqlite3_column_text(pStmt,0);
1997 if( zName==0 ) continue;
1998 if( strcmp(zName, "oss-fuzz")==0 ){
1999 ossFuzzThisDb = sqlite3_column_int(pStmt,1);
2000 if( verboseFlag ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb);
2001 }
drh31999c52019-11-14 17:46:32 +00002002 if( strcmp(zName, "limit-mem")==0 ){
drh362b66f2016-11-14 18:27:41 +00002003 nMemThisDb = sqlite3_column_int(pStmt,1);
2004 if( verboseFlag ) printf("Config: limit-mem=%d\n", nMemThisDb);
drh362b66f2016-11-14 18:27:41 +00002005 }
2006 }
2007 sqlite3_finalize(pStmt);
2008 }
2009
drhd9972ef2015-05-26 17:57:56 +00002010 if( zInsSql ){
2011 sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
2012 readfileFunc, 0, 0);
drha8781d92020-02-25 20:05:58 +00002013 sqlite3_create_function(db, "readtextfile", 1, SQLITE_UTF8, 0,
2014 readtextfileFunc, 0, 0);
drhe5da9352019-01-27 01:11:40 +00002015 sqlite3_create_function(db, "isdbsql", 1, SQLITE_UTF8, 0,
2016 isDbSqlFunc, 0, 0);
drhd9972ef2015-05-26 17:57:56 +00002017 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
2018 if( rc ) fatalError("cannot prepare statement [%s]: %s",
2019 zInsSql, sqlite3_errmsg(db));
2020 rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
2021 if( rc ) fatalError("cannot start a transaction");
2022 for(i=iFirstInsArg; i<argc; i++){
drhba6619d2021-04-23 12:58:16 +00002023 if( strcmp(argv[i],"-")==0 ){
2024 /* A filename of "-" means read multiple filenames from stdin */
drh15212702021-04-23 13:57:53 +00002025 char zLine[2000];
drhba6619d2021-04-23 12:58:16 +00002026 while( rc==0 && fgets(zLine,sizeof(zLine),stdin)!=0 ){
2027 size_t kk = strlen(zLine);
drh59607242021-04-29 18:03:42 +00002028 while( kk>0 && zLine[kk-1]<=' ' ) kk--;
drh9d41caf2021-07-07 19:44:32 +00002029 sqlite3_bind_text(pStmt, 1, zLine, (int)kk, SQLITE_STATIC);
drh59607242021-04-29 18:03:42 +00002030 if( verboseFlag ) printf("loading %.*s\n", (int)kk, zLine);
drhba6619d2021-04-23 12:58:16 +00002031 sqlite3_step(pStmt);
2032 rc = sqlite3_reset(pStmt);
2033 if( rc ) fatalError("insert failed for %s", zLine);
2034 }
2035 }else{
2036 sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
drh59607242021-04-29 18:03:42 +00002037 if( verboseFlag ) printf("loading %s\n", argv[i]);
drhba6619d2021-04-23 12:58:16 +00002038 sqlite3_step(pStmt);
2039 rc = sqlite3_reset(pStmt);
2040 if( rc ) fatalError("insert failed for %s", argv[i]);
2041 }
drh3b74d032015-05-25 18:48:19 +00002042 }
drhd9972ef2015-05-26 17:57:56 +00002043 sqlite3_finalize(pStmt);
2044 rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
drh5ecf9032018-05-08 12:49:53 +00002045 if( rc ) fatalError("cannot commit the transaction: %s",
2046 sqlite3_errmsg(db));
drhe5da9352019-01-27 01:11:40 +00002047 rebuild_database(db, dbSqlOnly);
drh3b74d032015-05-25 18:48:19 +00002048 sqlite3_close(db);
drhd9972ef2015-05-26 17:57:56 +00002049 return 0;
drh3b74d032015-05-25 18:48:19 +00002050 }
drh16f05822017-03-20 20:42:21 +00002051 rc = sqlite3_exec(db, "PRAGMA query_only=1;", 0, 0, 0);
2052 if( rc ) fatalError("cannot set database to query-only");
drh40e0e0d2015-09-22 18:51:17 +00002053 if( zExpDb!=0 || zExpSql!=0 ){
2054 sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
2055 writefileFunc, 0, 0);
2056 if( zExpDb!=0 ){
2057 const char *zExDb =
2058 "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent),"
2059 " dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)"
2060 " FROM db WHERE ?2<0 OR dbid=?2;";
2061 rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0);
2062 if( rc ) fatalError("cannot prepare statement [%s]: %s",
2063 zExDb, sqlite3_errmsg(db));
2064 sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb),
2065 SQLITE_STATIC, SQLITE_UTF8);
2066 sqlite3_bind_int(pStmt, 2, onlyDbid);
2067 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2068 printf("write db-%d (%d bytes) into %s\n",
2069 sqlite3_column_int(pStmt,1),
2070 sqlite3_column_int(pStmt,3),
2071 sqlite3_column_text(pStmt,2));
2072 }
2073 sqlite3_finalize(pStmt);
2074 }
2075 if( zExpSql!=0 ){
2076 const char *zExSql =
2077 "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext),"
2078 " sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)"
2079 " FROM xsql WHERE ?2<0 OR sqlid=?2;";
2080 rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0);
2081 if( rc ) fatalError("cannot prepare statement [%s]: %s",
2082 zExSql, sqlite3_errmsg(db));
2083 sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql),
2084 SQLITE_STATIC, SQLITE_UTF8);
2085 sqlite3_bind_int(pStmt, 2, onlySqlid);
2086 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2087 printf("write sql-%d (%d bytes) into %s\n",
2088 sqlite3_column_int(pStmt,1),
2089 sqlite3_column_int(pStmt,3),
2090 sqlite3_column_text(pStmt,2));
2091 }
2092 sqlite3_finalize(pStmt);
2093 }
2094 sqlite3_close(db);
2095 return 0;
2096 }
drhd9972ef2015-05-26 17:57:56 +00002097
2098 /* Load all SQL script content and all initial database images from the
2099 ** source db
2100 */
2101 blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
2102 &g.nSql, &g.pFirstSql);
2103 if( g.nSql==0 ) fatalError("need at least one SQL script");
2104 blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
2105 &g.nDb, &g.pFirstDb);
2106 if( g.nDb==0 ){
2107 g.pFirstDb = safe_realloc(0, sizeof(Blob));
2108 memset(g.pFirstDb, 0, sizeof(Blob));
2109 g.pFirstDb->id = 1;
2110 g.pFirstDb->seq = 0;
2111 g.nDb = 1;
drhd83e2832015-06-24 14:45:44 +00002112 sqlFuzz = 1;
drhd9972ef2015-05-26 17:57:56 +00002113 }
2114
2115 /* Print the description, if there is one */
drh075201e2021-10-27 12:05:28 +00002116 if( !quietFlag && !bScript ){
drhd9972ef2015-05-26 17:57:56 +00002117 zDbName = azSrcDb[iSrcDb];
drhe683b892016-02-15 18:47:26 +00002118 i = (int)strlen(zDbName) - 1;
drhd9972ef2015-05-26 17:57:56 +00002119 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
2120 zDbName += i;
2121 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
2122 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
2123 printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
2124 }
2125 sqlite3_finalize(pStmt);
2126 }
drh9a645862015-06-24 12:44:42 +00002127
2128 /* Rebuild the database, if requested */
2129 if( rebuildFlag ){
2130 if( !quietFlag ){
2131 printf("%s: rebuilding... ", zDbName);
2132 fflush(stdout);
2133 }
drhe5da9352019-01-27 01:11:40 +00002134 rebuild_database(db, 0);
drh9a645862015-06-24 12:44:42 +00002135 if( !quietFlag ) printf("done\n");
2136 }
drhd9972ef2015-05-26 17:57:56 +00002137
2138 /* Close the source database. Verify that no SQLite memory allocations are
2139 ** outstanding.
2140 */
2141 sqlite3_close(db);
2142 if( sqlite3_memory_used()>0 ){
2143 fatalError("SQLite has memory in use before the start of testing");
2144 }
drh53e66c32015-07-24 15:49:23 +00002145
2146 /* Limit available memory, if requested */
drh174f8552017-03-20 22:58:27 +00002147 sqlite3_shutdown();
drh39b3bcf2020-03-02 16:31:21 +00002148
drh31999c52019-11-14 17:46:32 +00002149 if( nMemThisDb>0 && nMem==0 ){
2150 if( !nativeMalloc ){
2151 pHeap = realloc(pHeap, nMemThisDb);
2152 if( pHeap==0 ){
2153 fatalError("failed to allocate %d bytes of heap memory", nMem);
2154 }
2155 sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMemThisDb, 128);
2156 }else{
2157 sqlite3_hard_heap_limit64((sqlite3_int64)nMemThisDb);
drh53e66c32015-07-24 15:49:23 +00002158 }
drh31999c52019-11-14 17:46:32 +00002159 }else{
2160 sqlite3_hard_heap_limit64(0);
drh53e66c32015-07-24 15:49:23 +00002161 }
drh174f8552017-03-20 22:58:27 +00002162
2163 /* Disable lookaside with the --native-malloc option */
2164 if( nativeMalloc ){
2165 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
2166 }
drhd9972ef2015-05-26 17:57:56 +00002167
drhbeaf5142016-12-26 00:15:56 +00002168 /* Reset the in-memory virtual filesystem */
drhd9972ef2015-05-26 17:57:56 +00002169 formatVfs();
drhd9972ef2015-05-26 17:57:56 +00002170
2171 /* Run a test using each SQL script against each database.
2172 */
drh075201e2021-10-27 12:05:28 +00002173 if( !verboseFlag && !quietFlag && !bSpinner && !bScript ){
2174 printf("%s:", zDbName);
2175 }
drhd9972ef2015-05-26 17:57:56 +00002176 for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
drh237f41a2020-12-21 12:14:59 +00002177 tmStart = timeOfDay();
drha47e7092019-01-25 04:00:14 +00002178 if( isDbSql(pSql->a, pSql->sz) ){
2179 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d",pSql->id);
drh075201e2021-10-27 12:05:28 +00002180 if( bScript ){
2181 /* No progress output */
2182 }else if( bSpinner ){
drhaa0696e2020-04-07 13:08:56 +00002183 int nTotal =g.nSql;
2184 int idx = pSql->seq;
2185 printf("\r%s: %d/%d ", zDbName, idx, nTotal);
2186 fflush(stdout);
2187 }else if( verboseFlag ){
drha47e7092019-01-25 04:00:14 +00002188 printf("%s\n", g.zTestName);
2189 fflush(stdout);
2190 }else if( !quietFlag ){
2191 static int prevAmt = -1;
2192 int idx = pSql->seq;
2193 int amt = idx*10/(g.nSql);
2194 if( amt!=prevAmt ){
2195 printf(" %d%%", amt*10);
2196 fflush(stdout);
2197 prevAmt = amt;
2198 }
2199 }
drh672f07c2020-10-20 14:40:53 +00002200 if( nSkip>0 ){
2201 nSkip--;
2202 }else{
drh075201e2021-10-27 12:05:28 +00002203 runCombinedDbSqlInput(pSql->a, pSql->sz, iTimeout, bScript, pSql->id);
drh672f07c2020-10-20 14:40:53 +00002204 }
drha47e7092019-01-25 04:00:14 +00002205 nTest++;
drh075201e2021-10-27 12:05:28 +00002206 if( bTimer && !bScript ){
drh237f41a2020-12-21 12:14:59 +00002207 sqlite3_int64 tmEnd = timeOfDay();
2208 printf("%lld %s\n", tmEnd - tmStart, g.zTestName);
2209 }
drha47e7092019-01-25 04:00:14 +00002210 g.zTestName[0] = 0;
drh39b3bcf2020-03-02 16:31:21 +00002211 disableOom();
drha47e7092019-01-25 04:00:14 +00002212 continue;
2213 }
drhd9972ef2015-05-26 17:57:56 +00002214 for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
2215 int openFlags;
2216 const char *zVfs = "inmem";
2217 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
2218 pSql->id, pDb->id);
drh075201e2021-10-27 12:05:28 +00002219 if( bScript ){
2220 /* No progress output */
2221 }else if( bSpinner ){
drhaa0696e2020-04-07 13:08:56 +00002222 int nTotal = g.nDb*g.nSql;
2223 int idx = pSql->seq*g.nDb + pDb->id - 1;
2224 printf("\r%s: %d/%d ", zDbName, idx, nTotal);
2225 fflush(stdout);
2226 }else if( verboseFlag ){
drhd9972ef2015-05-26 17:57:56 +00002227 printf("%s\n", g.zTestName);
2228 fflush(stdout);
2229 }else if( !quietFlag ){
2230 static int prevAmt = -1;
2231 int idx = pSql->seq*g.nDb + pDb->id - 1;
2232 int amt = idx*10/(g.nDb*g.nSql);
2233 if( amt!=prevAmt ){
2234 printf(" %d%%", amt*10);
2235 fflush(stdout);
2236 prevAmt = amt;
2237 }
2238 }
drh672f07c2020-10-20 14:40:53 +00002239 if( nSkip>0 ){
2240 nSkip--;
2241 continue;
2242 }
drh075201e2021-10-27 12:05:28 +00002243 if( bScript ){
2244 char zName[100];
2245 sqlite3_snprintf(sizeof(zName), zName, "db%06d.db",
2246 pDb->id>1 ? pDb->id : pSql->id);
2247 renderDbSqlForCLI(stdout, zName,
2248 pDb->a, pDb->sz, pSql->a, pSql->sz);
2249 continue;
2250 }
drhd9972ef2015-05-26 17:57:56 +00002251 createVFile("main.db", pDb->sz, pDb->a);
drhbeaf5142016-12-26 00:15:56 +00002252 sqlite3_randomness(0,0);
drh362b66f2016-11-14 18:27:41 +00002253 if( ossFuzzThisDb ){
drhea432ba2016-11-11 16:33:47 +00002254#ifndef SQLITE_OSS_FUZZ
drh5ecf9032018-05-08 12:49:53 +00002255 fatalError("--oss-fuzz not supported: recompile"
2256 " with -DSQLITE_OSS_FUZZ");
drhea432ba2016-11-11 16:33:47 +00002257#else
2258 extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t);
2259 LLVMFuzzerTestOneInput((const uint8_t*)pSql->a, (size_t)pSql->sz);
drh78057352015-06-24 23:17:35 +00002260#endif
drhea432ba2016-11-11 16:33:47 +00002261 }else{
2262 openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
2263 if( nativeFlag && pDb->sz==0 ){
2264 openFlags |= SQLITE_OPEN_MEMORY;
2265 zVfs = 0;
2266 }
2267 rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
2268 if( rc ) fatalError("cannot open inmem database");
drhdfcfff62016-12-26 12:25:19 +00002269 sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 100000000);
2270 sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 50);
drhea432ba2016-11-11 16:33:47 +00002271 if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
drh237f41a2020-12-21 12:14:59 +00002272 setAlarm((iTimeout+999)/1000);
drh7ae05492021-03-08 16:13:52 +00002273 /* Enable test functions */
2274 sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, db);
drhea432ba2016-11-11 16:33:47 +00002275#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2276 if( sqlFuzz || vdbeLimitFlag ){
drh5ecf9032018-05-08 12:49:53 +00002277 sqlite3_progress_handler(db, 100000, progressHandler,
2278 &vdbeLimitFlag);
drhea432ba2016-11-11 16:33:47 +00002279 }
2280#endif
drhe6e96b12019-08-02 21:03:24 +00002281#ifdef SQLITE_TESTCTRL_PRNG_SEED
drh2e6d83b2019-08-03 01:39:20 +00002282 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, db);
drhe6e96b12019-08-02 21:03:24 +00002283#endif
drh6e1c45e2019-12-18 13:42:04 +00002284 if( bVdbeDebug ){
2285 sqlite3_exec(db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
2286 }
drhea432ba2016-11-11 16:33:47 +00002287 do{
2288 runSql(db, (char*)pSql->a, runFlags);
2289 }while( timeoutTest );
2290 setAlarm(0);
drh174f8552017-03-20 22:58:27 +00002291 sqlite3_exec(db, "PRAGMA temp_store_directory=''", 0, 0, 0);
drhea432ba2016-11-11 16:33:47 +00002292 sqlite3_close(db);
2293 }
drh174f8552017-03-20 22:58:27 +00002294 if( sqlite3_memory_used()>0 ){
2295 fatalError("memory leak: %lld bytes outstanding",
2296 sqlite3_memory_used());
2297 }
drhd9972ef2015-05-26 17:57:56 +00002298 reformatVfs();
2299 nTest++;
drh237f41a2020-12-21 12:14:59 +00002300 if( bTimer ){
2301 sqlite3_int64 tmEnd = timeOfDay();
2302 printf("%lld %s\n", tmEnd - tmStart, g.zTestName);
2303 }
drhd9972ef2015-05-26 17:57:56 +00002304 g.zTestName[0] = 0;
drh4d6fda72015-05-26 18:58:32 +00002305
2306 /* Simulate an error if the TEST_FAILURE environment variable is "5".
2307 ** This is used to verify that automated test script really do spot
2308 ** errors that occur in this test program.
2309 */
2310 if( zFailCode ){
2311 if( zFailCode[0]=='5' && zFailCode[1]==0 ){
2312 fatalError("simulated failure");
2313 }else if( zFailCode[0]!=0 ){
2314 /* If TEST_FAILURE is something other than 5, just exit the test
2315 ** early */
2316 printf("\nExit early due to TEST_FAILURE being set\n");
2317 iSrcDb = nSrcDb-1;
2318 goto sourcedb_cleanup;
2319 }
2320 }
drhd9972ef2015-05-26 17:57:56 +00002321 }
2322 }
drh075201e2021-10-27 12:05:28 +00002323 if( bScript ){
2324 /* No progress output */
2325 }else if( bSpinner ){
drh292ed6d2021-04-23 12:16:16 +00002326 int nTotal = g.nDb*g.nSql;
2327 printf("\r%s: %d/%d \n", zDbName, nTotal, nTotal);
drhaa0696e2020-04-07 13:08:56 +00002328 }else if( !quietFlag && !verboseFlag ){
drhd9972ef2015-05-26 17:57:56 +00002329 printf(" 100%% - %d tests\n", g.nDb*g.nSql);
2330 }
2331
2332 /* Clean up at the end of processing a single source database
2333 */
drh4d6fda72015-05-26 18:58:32 +00002334 sourcedb_cleanup:
drhd9972ef2015-05-26 17:57:56 +00002335 blobListFree(g.pFirstSql);
2336 blobListFree(g.pFirstDb);
2337 reformatVfs();
2338
2339 } /* End loop over all source databases */
drh3b74d032015-05-25 18:48:19 +00002340
drh075201e2021-10-27 12:05:28 +00002341 if( !quietFlag && !bScript ){
drh3b74d032015-05-25 18:48:19 +00002342 sqlite3_int64 iElapse = timeOfDay() - iBegin;
drhd9972ef2015-05-26 17:57:56 +00002343 printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
2344 "SQLite %s %s\n",
2345 nTest, (int)(iElapse/1000), (int)(iElapse%1000),
drh3b74d032015-05-25 18:48:19 +00002346 sqlite3_libversion(), sqlite3_sourceid());
2347 }
drhf74d35b2015-05-27 18:19:50 +00002348 free(azSrcDb);
drh6653fbe2015-11-13 20:52:49 +00002349 free(pHeap);
drh3b74d032015-05-25 18:48:19 +00002350 return 0;
2351}