blob: f5a7b092e3380a498239ec366801922b0f0aa1be [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 */
drh3b74d032015-05-25 18:48:19 +0000156 char zTestName[100]; /* Name of current test */
157} g;
158
159/*
160** Print an error message and quit.
161*/
162static void fatalError(const char *zFormat, ...){
163 va_list ap;
drha7648f02019-12-18 13:02:18 +0000164 fprintf(stderr, "%s", g.zArgv0);
165 if( g.zDbFile ) fprintf(stderr, " %s", g.zDbFile);
166 if( g.zTestName[0] ) fprintf(stderr, " (%s)", g.zTestName);
167 fprintf(stderr, ": ");
drh3b74d032015-05-25 18:48:19 +0000168 va_start(ap, zFormat);
169 vfprintf(stderr, zFormat, ap);
170 va_end(ap);
171 fprintf(stderr, "\n");
172 exit(1);
173}
174
175/*
drha7648f02019-12-18 13:02:18 +0000176** signal handler
drh94701b02015-06-24 13:25:34 +0000177*/
178#ifdef __unix__
drha7648f02019-12-18 13:02:18 +0000179static void signalHandler(int signum){
180 const char *zSig;
181 if( signum==SIGABRT ){
182 zSig = "abort";
183 }else if( signum==SIGALRM ){
184 zSig = "timeout";
185 }else if( signum==SIGSEGV ){
186 zSig = "segfault";
187 }else{
188 zSig = "signal";
189 }
190 fatalError(zSig);
drh94701b02015-06-24 13:25:34 +0000191}
192#endif
193
194/*
195** Set the an alarm to go off after N seconds. Disable the alarm
196** if N==0
197*/
198static void setAlarm(int N){
199#ifdef __unix__
200 alarm(N);
201#else
202 (void)N;
203#endif
204}
205
drh78057352015-06-24 23:17:35 +0000206#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh94701b02015-06-24 13:25:34 +0000207/*
drhd83e2832015-06-24 14:45:44 +0000208** This an SQL progress handler. After an SQL statement has run for
209** many steps, we want to interrupt it. This guards against infinite
210** loops from recursive common table expressions.
211**
212** *pVdbeLimitFlag is true if the --limit-vdbe command-line option is used.
213** In that case, hitting the progress handler is a fatal error.
214*/
215static int progressHandler(void *pVdbeLimitFlag){
216 if( *(int*)pVdbeLimitFlag ) fatalError("too many VDBE cycles");
217 return 1;
218}
drh78057352015-06-24 23:17:35 +0000219#endif
drhd83e2832015-06-24 14:45:44 +0000220
221/*
drh0fcf6f02021-05-24 12:28:13 +0000222** Reallocate memory. Show an error and quit if unable.
drh3b74d032015-05-25 18:48:19 +0000223*/
224static void *safe_realloc(void *pOld, int szNew){
drhc5412d52016-03-23 17:54:19 +0000225 void *pNew = realloc(pOld, szNew<=0 ? 1 : szNew);
drh3b74d032015-05-25 18:48:19 +0000226 if( pNew==0 ) fatalError("unable to realloc for %d bytes", szNew);
227 return pNew;
228}
229
230/*
231** Initialize the virtual file system.
232*/
233static void formatVfs(void){
234 int i;
235 for(i=0; i<MX_FILE; i++){
236 g.aFile[i].sz = -1;
237 g.aFile[i].zFilename = 0;
238 g.aFile[i].a = 0;
239 g.aFile[i].nRef = 0;
240 }
241}
242
243
244/*
245** Erase all information in the virtual file system.
246*/
247static void reformatVfs(void){
248 int i;
249 for(i=0; i<MX_FILE; i++){
250 if( g.aFile[i].sz<0 ) continue;
251 if( g.aFile[i].zFilename ){
252 free(g.aFile[i].zFilename);
253 g.aFile[i].zFilename = 0;
254 }
255 if( g.aFile[i].nRef>0 ){
256 fatalError("file %d still open. nRef=%d", i, g.aFile[i].nRef);
257 }
258 g.aFile[i].sz = -1;
259 free(g.aFile[i].a);
260 g.aFile[i].a = 0;
261 g.aFile[i].nRef = 0;
262 }
263}
264
265/*
266** Find a VFile by name
267*/
268static VFile *findVFile(const char *zName){
269 int i;
drha9542b12015-05-25 19:35:42 +0000270 if( zName==0 ) return 0;
drh3b74d032015-05-25 18:48:19 +0000271 for(i=0; i<MX_FILE; i++){
272 if( g.aFile[i].zFilename==0 ) continue;
273 if( strcmp(g.aFile[i].zFilename, zName)==0 ) return &g.aFile[i];
274 }
275 return 0;
276}
277
278/*
279** Find a VFile by name. Create it if it does not already exist and
280** initialize it to the size and content given.
281**
282** Return NULL only if the filesystem is full.
283*/
284static VFile *createVFile(const char *zName, int sz, unsigned char *pData){
285 VFile *pNew = findVFile(zName);
286 int i;
287 if( pNew ) return pNew;
288 for(i=0; i<MX_FILE && g.aFile[i].sz>=0; i++){}
289 if( i>=MX_FILE ) return 0;
290 pNew = &g.aFile[i];
drha9542b12015-05-25 19:35:42 +0000291 if( zName ){
drhe683b892016-02-15 18:47:26 +0000292 int nName = (int)strlen(zName)+1;
293 pNew->zFilename = safe_realloc(0, nName);
294 memcpy(pNew->zFilename, zName, nName);
drha9542b12015-05-25 19:35:42 +0000295 }else{
296 pNew->zFilename = 0;
297 }
drh3b74d032015-05-25 18:48:19 +0000298 pNew->nRef = 0;
299 pNew->sz = sz;
300 pNew->a = safe_realloc(0, sz);
301 if( sz>0 ) memcpy(pNew->a, pData, sz);
302 return pNew;
303}
304
drh075201e2021-10-27 12:05:28 +0000305/* Return true if the line is all zeros */
306static int allZero(unsigned char *aLine){
307 int i;
308 for(i=0; i<16 && aLine[i]==0; i++){}
309 return i==16;
310}
311
312/*
313** Render a database and query as text that can be input into
314** the CLI.
315*/
316static void renderDbSqlForCLI(
317 FILE *out, /* Write to this file */
318 const char *zFile, /* Name of the database file */
319 unsigned char *aDb, /* Database content */
320 int nDb, /* Number of bytes in aDb[] */
321 unsigned char *zSql, /* SQL content */
322 int nSql /* Bytes of SQL */
323){
324 fprintf(out, ".print ******* %s *******\n", zFile);
325 if( nDb>100 ){
326 int i, j; /* Loop counters */
327 int pgsz; /* Size of each page */
328 int lastPage = 0; /* Last page number shown */
329 int iPage; /* Current page number */
330 unsigned char *aLine; /* Single line to display */
331 unsigned char buf[16]; /* Fake line */
332 unsigned char bShow[256]; /* Characters ok to display */
333
334 memset(bShow, '.', sizeof(bShow));
335 for(i=' '; i<='~'; i++){
336 if( i!='{' && i!='}' && i!='"' && i!='\\' ) bShow[i] = i;
337 }
338 pgsz = (aDb[16]<<8) | aDb[17];
339 if( pgsz==0 ) pgsz = 65536;
340 if( pgsz<512 || (pgsz&(pgsz-1))!=0 ) pgsz = 4096;
341 fprintf(out,".open --hexdb\n");
342 fprintf(out,"| size %d pagesize %d filename %s\n",nDb,pgsz,zFile);
343 for(i=0; i<nDb; i += 16){
344 if( i+16>nDb ){
345 memset(buf, 0, sizeof(buf));
346 memcpy(buf, aDb+i, nDb-i);
347 aLine = buf;
348 }else{
349 aLine = aDb + i;
350 }
351 if( allZero(aLine) ) continue;
352 iPage = i/pgsz + 1;
353 if( lastPage!=iPage ){
354 fprintf(out,"| page %d offset %d\n", iPage, (iPage-1)*pgsz);
355 lastPage = iPage;
356 }
357 fprintf(out,"| %5d:", i-(iPage-1)*pgsz);
358 for(j=0; j<16; j++) fprintf(out," %02x", aLine[j]);
359 fprintf(out," ");
360 for(j=0; j<16; j++){
361 unsigned char c = (unsigned char)aLine[j];
362 fputc( bShow[c], stdout);
363 }
364 fputc('\n', stdout);
365 }
366 fprintf(out,"| end %s\n", zFile);
367 }else{
368 fprintf(out,".open :memory:\n");
369 }
370 fprintf(out,".testctrl prng_seed 1 db\n");
371 fprintf(out,".testctrl internal_functions\n");
372 fprintf(out,"%.*s", nSql, zSql);
373 if( nSql>0 && zSql[nSql-1]!='\n' ) fprintf(out, "\n");
374}
375
drh48b4bf22021-10-26 22:36:41 +0000376/*
377** Read the complete content of a file into memory. Add a 0x00 terminator
378** and return a pointer to the result.
379**
380** The file content is held in memory obtained from sqlite_malloc64() which
381** should be freed by the caller.
382*/
383static char *readFile(const char *zFilename, long *sz){
384 FILE *in;
385 long nIn;
386 unsigned char *pBuf;
387
388 *sz = 0;
389 if( zFilename==0 ) return 0;
390 in = fopen(zFilename, "rb");
391 if( in==0 ) return 0;
392 fseek(in, 0, SEEK_END);
393 *sz = nIn = ftell(in);
394 rewind(in);
395 pBuf = sqlite3_malloc64( nIn+1 );
396 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
397 pBuf[nIn] = 0;
398 fclose(in);
drh075201e2021-10-27 12:05:28 +0000399 return (char*)pBuf;
drh48b4bf22021-10-26 22:36:41 +0000400 }
401 sqlite3_free(pBuf);
402 *sz = 0;
403 fclose(in);
404 return 0;
405}
406
drh3b74d032015-05-25 18:48:19 +0000407
408/*
409** Implementation of the "readfile(X)" SQL function. The entire content
410** of the file named X is read and returned as a BLOB. NULL is returned
411** if the file does not exist or is unreadable.
412*/
413static void readfileFunc(
414 sqlite3_context *context,
415 int argc,
416 sqlite3_value **argv
417){
drh3b74d032015-05-25 18:48:19 +0000418 long nIn;
419 void *pBuf;
drh48b4bf22021-10-26 22:36:41 +0000420 const char *zName = (const char*)sqlite3_value_text(argv[0]);
drh3b74d032015-05-25 18:48:19 +0000421
drh3b74d032015-05-25 18:48:19 +0000422 if( zName==0 ) return;
drh48b4bf22021-10-26 22:36:41 +0000423 pBuf = readFile(zName, &nIn);
424 if( pBuf ){
drh3b74d032015-05-25 18:48:19 +0000425 sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
drh3b74d032015-05-25 18:48:19 +0000426 }
drh3b74d032015-05-25 18:48:19 +0000427}
428
429/*
drha8781d92020-02-25 20:05:58 +0000430** Implementation of the "readtextfile(X)" SQL function. The text content
431** of the file named X through the end of the file or to the first \000
432** character, whichever comes first, is read and returned as TEXT. NULL
433** is returned if the file does not exist or is unreadable.
434*/
435static void readtextfileFunc(
436 sqlite3_context *context,
437 int argc,
438 sqlite3_value **argv
439){
440 const char *zName;
441 FILE *in;
442 long nIn;
443 char *pBuf;
444
445 zName = (const char*)sqlite3_value_text(argv[0]);
446 if( zName==0 ) return;
447 in = fopen(zName, "rb");
448 if( in==0 ) return;
449 fseek(in, 0, SEEK_END);
450 nIn = ftell(in);
451 rewind(in);
452 pBuf = sqlite3_malloc64( nIn+1 );
453 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
454 pBuf[nIn] = 0;
455 sqlite3_result_text(context, pBuf, -1, sqlite3_free);
456 }else{
457 sqlite3_free(pBuf);
458 }
459 fclose(in);
460}
461
462/*
drh40e0e0d2015-09-22 18:51:17 +0000463** Implementation of the "writefile(X,Y)" SQL function. The argument Y
464** is written into file X. The number of bytes written is returned. Or
465** NULL is returned if something goes wrong, such as being unable to open
466** file X for writing.
467*/
468static void writefileFunc(
469 sqlite3_context *context,
470 int argc,
471 sqlite3_value **argv
472){
473 FILE *out;
474 const char *z;
475 sqlite3_int64 rc;
476 const char *zFile;
477
478 (void)argc;
479 zFile = (const char*)sqlite3_value_text(argv[0]);
480 if( zFile==0 ) return;
481 out = fopen(zFile, "wb");
482 if( out==0 ) return;
483 z = (const char*)sqlite3_value_blob(argv[1]);
484 if( z==0 ){
485 rc = 0;
486 }else{
487 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
488 }
489 fclose(out);
490 sqlite3_result_int64(context, rc);
491}
492
493
494/*
drh3b74d032015-05-25 18:48:19 +0000495** Load a list of Blob objects from the database
496*/
497static void blobListLoadFromDb(
498 sqlite3 *db, /* Read from this database */
499 const char *zSql, /* Query used to extract the blobs */
drha9542b12015-05-25 19:35:42 +0000500 int onlyId, /* Only load where id is this value */
drh3b74d032015-05-25 18:48:19 +0000501 int *pN, /* OUT: Write number of blobs loaded here */
502 Blob **ppList /* OUT: Write the head of the blob list here */
503){
504 Blob head;
505 Blob *p;
506 sqlite3_stmt *pStmt;
507 int n = 0;
508 int rc;
drha9542b12015-05-25 19:35:42 +0000509 char *z2;
drh3b74d032015-05-25 18:48:19 +0000510
drha9542b12015-05-25 19:35:42 +0000511 if( onlyId>0 ){
512 z2 = sqlite3_mprintf("%s WHERE rowid=%d", zSql, onlyId);
513 }else{
514 z2 = sqlite3_mprintf("%s", zSql);
515 }
516 rc = sqlite3_prepare_v2(db, z2, -1, &pStmt, 0);
517 sqlite3_free(z2);
drh3b74d032015-05-25 18:48:19 +0000518 if( rc ) fatalError("%s", sqlite3_errmsg(db));
519 head.pNext = 0;
520 p = &head;
521 while( SQLITE_ROW==sqlite3_step(pStmt) ){
522 int sz = sqlite3_column_bytes(pStmt, 1);
523 Blob *pNew = safe_realloc(0, sizeof(*pNew)+sz );
524 pNew->id = sqlite3_column_int(pStmt, 0);
525 pNew->sz = sz;
drhe5c5f2c2015-05-26 00:28:08 +0000526 pNew->seq = n++;
drh3b74d032015-05-25 18:48:19 +0000527 pNew->pNext = 0;
528 memcpy(pNew->a, sqlite3_column_blob(pStmt,1), sz);
529 pNew->a[sz] = 0;
530 p->pNext = pNew;
531 p = pNew;
drh3b74d032015-05-25 18:48:19 +0000532 }
533 sqlite3_finalize(pStmt);
534 *pN = n;
535 *ppList = head.pNext;
536}
537
538/*
539** Free a list of Blob objects
540*/
541static void blobListFree(Blob *p){
542 Blob *pNext;
543 while( p ){
544 pNext = p->pNext;
545 free(p);
546 p = pNext;
547 }
548}
549
drh237f41a2020-12-21 12:14:59 +0000550/* Return the current wall-clock time
551**
552** The number of milliseconds since the julian epoch.
553** 1907-01-01 00:00:00 -> 210866716800000
554** 2021-01-01 00:00:00 -> 212476176000000
555*/
drh3b74d032015-05-25 18:48:19 +0000556static sqlite3_int64 timeOfDay(void){
557 static sqlite3_vfs *clockVfs = 0;
558 sqlite3_int64 t;
drh8055a3e2018-11-21 14:27:34 +0000559 if( clockVfs==0 ){
560 clockVfs = sqlite3_vfs_find(0);
561 if( clockVfs==0 ) return 0;
562 }
drh3b74d032015-05-25 18:48:19 +0000563 if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
564 clockVfs->xCurrentTimeInt64(clockVfs, &t);
565 }else{
566 double r;
567 clockVfs->xCurrentTime(clockVfs, &r);
568 t = (sqlite3_int64)(r*86400000.0);
569 }
570 return t;
571}
572
drha47e7092019-01-25 04:00:14 +0000573/***************************************************************************
574** Code to process combined database+SQL scripts generated by the
575** dbsqlfuzz fuzzer.
576*/
577
578/* An instance of the following object is passed by pointer as the
579** client data to various callbacks.
580*/
581typedef struct FuzzCtx {
582 sqlite3 *db; /* The database connection */
583 sqlite3_int64 iCutoffTime; /* Stop processing at this time. */
584 sqlite3_int64 iLastCb; /* Time recorded for previous progress callback */
585 sqlite3_int64 mxInterval; /* Longest interval between two progress calls */
586 unsigned nCb; /* Number of progress callbacks */
587 unsigned mxCb; /* Maximum number of progress callbacks allowed */
588 unsigned execCnt; /* Number of calls to the sqlite3_exec callback */
589 int timeoutHit; /* True when reaching a timeout */
590} FuzzCtx;
591
592/* Verbosity level for the dbsqlfuzz test runner */
593static int eVerbosity = 0;
594
595/* True to activate PRAGMA vdbe_debug=on */
596static int bVdbeDebug = 0;
597
598/* Timeout for each fuzzing attempt, in milliseconds */
drhed457032019-01-25 17:51:06 +0000599static int giTimeout = 10000; /* Defaults to 10 seconds */
drha47e7092019-01-25 04:00:14 +0000600
601/* Maximum number of progress handler callbacks */
602static unsigned int mxProgressCb = 2000;
603
604/* Maximum string length in SQLite */
605static int lengthLimit = 1000000;
606
drhbe03cc92020-01-20 14:42:09 +0000607/* Maximum expression depth */
608static int depthLimit = 500;
609
drh31999c52019-11-14 17:46:32 +0000610/* Limit on the amount of heap memory that can be used */
drha8781d92020-02-25 20:05:58 +0000611static sqlite3_int64 heapLimit = 100000000;
drh31999c52019-11-14 17:46:32 +0000612
drha47e7092019-01-25 04:00:14 +0000613/* Maximum byte-code program length in SQLite */
614static int vdbeOpLimit = 25000;
615
616/* Maximum size of the in-memory database */
617static sqlite3_int64 maxDbSize = 104857600;
drh39b3bcf2020-03-02 16:31:21 +0000618/* OOM simulation parameters */
619static unsigned int oomCounter = 0; /* Simulate OOM when equals 1 */
620static unsigned int oomRepeat = 0; /* Number of OOMs in a row */
621static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
622
623/* This routine is called when a simulated OOM occurs. It is broken
624** out as a separate routine to make it easy to set a breakpoint on
625** the OOM
626*/
627void oomFault(void){
628 if( eVerbosity ){
629 printf("Simulated OOM fault\n");
630 }
631 if( oomRepeat>0 ){
632 oomRepeat--;
633 }else{
634 oomCounter--;
635 }
636}
637
638/* This routine is a replacement malloc() that is used to simulate
639** Out-Of-Memory (OOM) errors for testing purposes.
640*/
641static void *oomMalloc(int nByte){
642 if( oomCounter ){
643 if( oomCounter==1 ){
644 oomFault();
645 return 0;
646 }else{
647 oomCounter--;
648 }
649 }
650 return defaultMalloc(nByte);
651}
652
653/* Register the OOM simulator. This must occur before any memory
654** allocations */
655static void registerOomSimulator(void){
656 sqlite3_mem_methods mem;
657 sqlite3_shutdown();
658 sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
659 defaultMalloc = mem.xMalloc;
660 mem.xMalloc = oomMalloc;
661 sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
662}
663
664/* Turn off any pending OOM simulation */
665static void disableOom(void){
666 oomCounter = 0;
667 oomRepeat = 0;
668}
drha47e7092019-01-25 04:00:14 +0000669
670/*
671** Translate a single byte of Hex into an integer.
672** This routine only works if h really is a valid hexadecimal
673** character: 0..9a..fA..F
674*/
drhed457032019-01-25 17:51:06 +0000675static unsigned char hexToInt(unsigned int h){
drha47e7092019-01-25 04:00:14 +0000676#ifdef SQLITE_EBCDIC
677 h += 9*(1&~(h>>4)); /* EBCDIC */
678#else
679 h += 9*(1&(h>>6)); /* ASCII */
680#endif
681 return h & 0xf;
682}
683
684/*
685** The first character of buffer zIn[0..nIn-1] is a '['. This routine
686** checked to see if the buffer holds "[NNNN]" or "[+NNNN]" and if it
687** does it makes corresponding changes to the *pK value and *pI value
688** and returns true. If the input buffer does not match the patterns,
689** no changes are made to either *pK or *pI and this routine returns false.
690*/
691static int isOffset(
692 const unsigned char *zIn, /* Text input */
693 int nIn, /* Bytes of input */
694 unsigned int *pK, /* half-byte cursor to adjust */
695 unsigned int *pI /* Input index to adjust */
696){
697 int i;
698 unsigned int k = 0;
699 unsigned char c;
700 for(i=1; i<nIn && (c = zIn[i])!=']'; i++){
701 if( !isxdigit(c) ) return 0;
702 k = k*16 + hexToInt(c);
703 }
704 if( i==nIn ) return 0;
705 *pK = 2*k;
706 *pI += i;
707 return 1;
708}
709
710/*
711** Decode the text starting at zIn into a binary database file.
drh0fcf6f02021-05-24 12:28:13 +0000712** The maximum length of zIn is nIn bytes. Store the binary database
713** file in space obtained from sqlite3_malloc().
drha47e7092019-01-25 04:00:14 +0000714**
715** Return the number of bytes of zIn consumed. Or return -1 if there
716** is an error. One potential error is that the recipe specifies a
717** database file larger than MX_FILE_SZ bytes.
718**
719** Abort on an OOM.
720*/
721static int decodeDatabase(
722 const unsigned char *zIn, /* Input text to be decoded */
723 int nIn, /* Bytes of input text */
724 unsigned char **paDecode, /* OUT: decoded database file */
725 int *pnDecode /* OUT: Size of decoded database */
726){
drh672f07c2020-10-20 14:40:53 +0000727 unsigned char *a, *aNew; /* Database under construction */
drha47e7092019-01-25 04:00:14 +0000728 int mx = 0; /* Current size of the database */
729 sqlite3_uint64 nAlloc = 4096; /* Space allocated in a[] */
730 unsigned int i; /* Next byte of zIn[] to read */
731 unsigned int j; /* Temporary integer */
732 unsigned int k; /* half-byte cursor index for output */
733 unsigned int n; /* Number of bytes of input */
734 unsigned char b = 0;
735 if( nIn<4 ) return -1;
736 n = (unsigned int)nIn;
drhed457032019-01-25 17:51:06 +0000737 a = sqlite3_malloc64( nAlloc );
drha47e7092019-01-25 04:00:14 +0000738 if( a==0 ){
739 fprintf(stderr, "Out of memory!\n");
740 exit(1);
741 }
mistachkin065f3bf2019-03-20 05:45:03 +0000742 memset(a, 0, (size_t)nAlloc);
drha47e7092019-01-25 04:00:14 +0000743 for(i=k=0; i<n; i++){
drhaf638922019-02-07 00:17:36 +0000744 unsigned char c = (unsigned char)zIn[i];
drha47e7092019-01-25 04:00:14 +0000745 if( isxdigit(c) ){
746 k++;
747 if( k & 1 ){
748 b = hexToInt(c)*16;
749 }else{
750 b += hexToInt(c);
751 j = k/2 - 1;
752 if( j>=nAlloc ){
753 sqlite3_uint64 newSize;
754 if( nAlloc==MX_FILE_SZ || j>=MX_FILE_SZ ){
755 if( eVerbosity ){
756 fprintf(stderr, "Input database too big: max %d bytes\n",
757 MX_FILE_SZ);
758 }
759 sqlite3_free(a);
760 return -1;
761 }
762 newSize = nAlloc*2;
763 if( newSize<=j ){
764 newSize = (j+4096)&~4095;
765 }
766 if( newSize>MX_FILE_SZ ){
767 if( j>=MX_FILE_SZ ){
768 sqlite3_free(a);
769 return -1;
770 }
771 newSize = MX_FILE_SZ;
772 }
drh672f07c2020-10-20 14:40:53 +0000773 aNew = sqlite3_realloc64( a, newSize );
774 if( aNew==0 ){
775 sqlite3_free(a);
776 return -1;
drha47e7092019-01-25 04:00:14 +0000777 }
drh672f07c2020-10-20 14:40:53 +0000778 a = aNew;
drha47e7092019-01-25 04:00:14 +0000779 assert( newSize > nAlloc );
mistachkin065f3bf2019-03-20 05:45:03 +0000780 memset(a+nAlloc, 0, (size_t)(newSize - nAlloc));
drha47e7092019-01-25 04:00:14 +0000781 nAlloc = newSize;
782 }
783 if( j>=(unsigned)mx ){
784 mx = (j + 4095)&~4095;
785 if( mx>MX_FILE_SZ ) mx = MX_FILE_SZ;
786 }
787 assert( j<nAlloc );
788 a[j] = b;
789 }
790 }else if( zIn[i]=='[' && i<n-3 && isOffset(zIn+i, nIn-i, &k, &i) ){
791 continue;
792 }else if( zIn[i]=='\n' && i<n-4 && memcmp(zIn+i,"\n--\n",4)==0 ){
793 i += 4;
794 break;
795 }
796 }
797 *pnDecode = mx;
798 *paDecode = a;
799 return i;
800}
801
802/*
803** Progress handler callback.
804**
805** The argument is the cutoff-time after which all processing should
806** stop. So return non-zero if the cut-off time is exceeded.
807*/
808static int progress_handler(void *pClientData) {
809 FuzzCtx *p = (FuzzCtx*)pClientData;
810 sqlite3_int64 iNow = timeOfDay();
811 int rc = iNow>=p->iCutoffTime;
812 sqlite3_int64 iDiff = iNow - p->iLastCb;
drh237f41a2020-12-21 12:14:59 +0000813 /* printf("time-remaining: %lld\n", p->iCutoffTime - iNow); */
drha47e7092019-01-25 04:00:14 +0000814 if( iDiff > p->mxInterval ) p->mxInterval = iDiff;
815 p->nCb++;
816 if( rc==0 && p->mxCb>0 && p->mxCb<=p->nCb ) rc = 1;
drhdf216592019-01-25 04:43:26 +0000817 if( rc && !p->timeoutHit && eVerbosity>=2 ){
drha47e7092019-01-25 04:00:14 +0000818 printf("Timeout on progress callback %d\n", p->nCb);
819 fflush(stdout);
820 p->timeoutHit = 1;
821 }
822 return rc;
823}
824
825/*
826** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and
827** "PRAGMA parser_trace" since they can dramatically increase the
828** amount of output without actually testing anything useful.
829**
drh8df01492021-03-18 14:36:19 +0000830** Also block ATTACH if attaching a file from the filesystem.
drha47e7092019-01-25 04:00:14 +0000831*/
832static int block_troublesome_sql(
833 void *Notused,
834 int eCode,
835 const char *zArg1,
836 const char *zArg2,
837 const char *zArg3,
838 const char *zArg4
839){
840 (void)Notused;
841 (void)zArg2;
842 (void)zArg3;
843 (void)zArg4;
844 if( eCode==SQLITE_PRAGMA ){
drh63e8f032021-10-25 12:54:23 +0000845 if( sqlite3_stricmp("busy_timeout",zArg1)==0
drh81258cc2021-11-22 13:59:06 +0000846 && (zArg2==0 || strtoll(zArg2,0,0)>100 || strtoll(zArg2,0,10)>100)
drh63e8f032021-10-25 12:54:23 +0000847 ){
848 return SQLITE_DENY;
849 }else if( eVerbosity==0 ){
drh8df01492021-03-18 14:36:19 +0000850 if( sqlite3_strnicmp("vdbe_", zArg1, 5)==0
851 || sqlite3_stricmp("parser_trace", zArg1)==0
852 || sqlite3_stricmp("temp_store_directory", zArg1)==0
853 ){
854 return SQLITE_DENY;
855 }
856 }else if( sqlite3_stricmp("oom",zArg1)==0
857 && zArg2!=0 && zArg2[0]!=0 ){
drh39b3bcf2020-03-02 16:31:21 +0000858 oomCounter = atoi(zArg2);
859 }
drh657a7a62021-03-09 13:12:58 +0000860 }else if( eCode==SQLITE_ATTACH ){
drhc8f72112021-10-23 22:14:11 +0000861 /* Deny the ATTACH if it is attaching anything other than an in-memory
862 ** database. */
drhbe536562021-10-23 11:30:35 +0000863 if( zArg1==0 ) return SQLITE_DENY;
drhc8f72112021-10-23 22:14:11 +0000864 if( strcmp(zArg1,":memory:")==0 ) return SQLITE_OK;
865 if( sqlite3_strglob("file:*[?]vfs=memdb", zArg1)==0
866 && sqlite3_strglob("file:*[^/a-zA-Z0-9_.]*[?]vfs=memdb", zArg1)!=0
drhbe536562021-10-23 11:30:35 +0000867 ){
drhc8f72112021-10-23 22:14:11 +0000868 return SQLITE_OK;
drh657a7a62021-03-09 13:12:58 +0000869 }
drhc8f72112021-10-23 22:14:11 +0000870 return SQLITE_DENY;
drha47e7092019-01-25 04:00:14 +0000871 }
872 return SQLITE_OK;
873}
874
875/*
876** Run the SQL text
877*/
878static int runDbSql(sqlite3 *db, const char *zSql){
879 int rc;
880 sqlite3_stmt *pStmt;
drhaf638922019-02-07 00:17:36 +0000881 while( isspace(zSql[0]&0x7f) ) zSql++;
drha47e7092019-01-25 04:00:14 +0000882 if( zSql[0]==0 ) return SQLITE_OK;
drhdf216592019-01-25 04:43:26 +0000883 if( eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +0000884 printf("RUNNING-SQL: [%s]\n", zSql);
885 fflush(stdout);
886 }
887 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
888 if( rc==SQLITE_OK ){
889 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
drhdf216592019-01-25 04:43:26 +0000890 if( eVerbosity>=5 ){
drha47e7092019-01-25 04:00:14 +0000891 int j;
892 for(j=0; j<sqlite3_column_count(pStmt); j++){
893 if( j ) printf(",");
894 switch( sqlite3_column_type(pStmt, j) ){
895 case SQLITE_NULL: {
896 printf("NULL");
897 break;
898 }
899 case SQLITE_INTEGER:
900 case SQLITE_FLOAT: {
901 printf("%s", sqlite3_column_text(pStmt, j));
902 break;
903 }
904 case SQLITE_BLOB: {
905 int n = sqlite3_column_bytes(pStmt, j);
906 int i;
907 const unsigned char *a;
908 a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
909 printf("x'");
910 for(i=0; i<n; i++){
911 printf("%02x", a[i]);
912 }
913 printf("'");
914 break;
915 }
916 case SQLITE_TEXT: {
917 int n = sqlite3_column_bytes(pStmt, j);
918 int i;
919 const unsigned char *a;
920 a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
921 printf("'");
922 for(i=0; i<n; i++){
923 if( a[i]=='\'' ){
924 printf("''");
925 }else{
926 putchar(a[i]);
927 }
928 }
929 printf("'");
930 break;
931 }
932 } /* End switch() */
933 } /* End for() */
934 printf("\n");
935 fflush(stdout);
drhdf216592019-01-25 04:43:26 +0000936 } /* End if( eVerbosity>=5 ) */
drha47e7092019-01-25 04:00:14 +0000937 } /* End while( SQLITE_ROW */
drhdf216592019-01-25 04:43:26 +0000938 if( rc!=SQLITE_DONE && eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +0000939 printf("SQL-ERROR: (%d) %s\n", rc, sqlite3_errmsg(db));
940 fflush(stdout);
941 }
drhdf216592019-01-25 04:43:26 +0000942 }else if( eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +0000943 printf("SQL-ERROR (%d): %s\n", rc, sqlite3_errmsg(db));
944 fflush(stdout);
945 } /* End if( SQLITE_OK ) */
946 return sqlite3_finalize(pStmt);
947}
948
949/* Invoke this routine to run a single test case */
drh075201e2021-10-27 12:05:28 +0000950int runCombinedDbSqlInput(
951 const uint8_t *aData, /* Combined DB+SQL content */
952 size_t nByte, /* Size of aData in bytes */
953 int iTimeout, /* Use this timeout */
954 int bScript, /* If true, just render CLI output */
955 int iSqlId /* SQL identifier */
956){
drha47e7092019-01-25 04:00:14 +0000957 int rc; /* SQLite API return value */
958 int iSql; /* Index in aData[] of start of SQL */
959 unsigned char *aDb = 0; /* Decoded database content */
960 int nDb = 0; /* Size of the decoded database */
961 int i; /* Loop counter */
962 int j; /* Start of current SQL statement */
963 char *zSql = 0; /* SQL text to run */
964 int nSql; /* Bytes of SQL text */
965 FuzzCtx cx; /* Fuzzing context */
966
967 if( nByte<10 ) return 0;
968 if( sqlite3_initialize() ) return 0;
969 if( sqlite3_memory_used()!=0 ){
970 int nAlloc = 0;
971 int nNotUsed = 0;
972 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
drh672f07c2020-10-20 14:40:53 +0000973 fprintf(stderr,"memory leak prior to test start:"
974 " %lld bytes in %d allocations\n",
drha47e7092019-01-25 04:00:14 +0000975 sqlite3_memory_used(), nAlloc);
976 exit(1);
977 }
978 memset(&cx, 0, sizeof(cx));
979 iSql = decodeDatabase((unsigned char*)aData, (int)nByte, &aDb, &nDb);
980 if( iSql<0 ) return 0;
drhed457032019-01-25 17:51:06 +0000981 nSql = (int)(nByte - iSql);
drh075201e2021-10-27 12:05:28 +0000982 if( bScript ){
983 char zName[100];
984 sqlite3_snprintf(sizeof(zName),zName,"dbsql%06d.db",iSqlId);
985 renderDbSqlForCLI(stdout, zName, aDb, nDb,
986 (unsigned char*)(aData+iSql), nSql);
987 sqlite3_free(aDb);
988 return 0;
989 }
drhdf216592019-01-25 04:43:26 +0000990 if( eVerbosity>=3 ){
drha47e7092019-01-25 04:00:14 +0000991 printf(
992 "****** %d-byte input, %d-byte database, %d-byte script "
993 "******\n", (int)nByte, nDb, nSql);
994 fflush(stdout);
995 }
996 rc = sqlite3_open(0, &cx.db);
drh672f07c2020-10-20 14:40:53 +0000997 if( rc ){
998 sqlite3_free(aDb);
999 return 1;
1000 }
drha47e7092019-01-25 04:00:14 +00001001 if( bVdbeDebug ){
1002 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
1003 }
1004
1005 /* Invoke the progress handler frequently to check to see if we
1006 ** are taking too long. The progress handler will return true
drhed457032019-01-25 17:51:06 +00001007 ** (which will block further processing) if more than giTimeout seconds have
drha47e7092019-01-25 04:00:14 +00001008 ** elapsed since the start of the test.
1009 */
1010 cx.iLastCb = timeOfDay();
drh237f41a2020-12-21 12:14:59 +00001011 cx.iCutoffTime = cx.iLastCb + (iTimeout<giTimeout ? iTimeout : giTimeout);
drha47e7092019-01-25 04:00:14 +00001012 cx.mxCb = mxProgressCb;
1013#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1014 sqlite3_progress_handler(cx.db, 10, progress_handler, (void*)&cx);
1015#endif
1016
1017 /* Set a limit on the maximum size of a prepared statement, and the
1018 ** maximum length of a string or blob */
1019 if( vdbeOpLimit>0 ){
1020 sqlite3_limit(cx.db, SQLITE_LIMIT_VDBE_OP, vdbeOpLimit);
1021 }
1022 if( lengthLimit>0 ){
1023 sqlite3_limit(cx.db, SQLITE_LIMIT_LENGTH, lengthLimit);
1024 }
drhbe03cc92020-01-20 14:42:09 +00001025 if( depthLimit>0 ){
1026 sqlite3_limit(cx.db, SQLITE_LIMIT_EXPR_DEPTH, depthLimit);
1027 }
drh4b3282d2020-04-07 15:07:11 +00001028 sqlite3_limit(cx.db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 100);
drh31999c52019-11-14 17:46:32 +00001029 sqlite3_hard_heap_limit64(heapLimit);
drha47e7092019-01-25 04:00:14 +00001030
1031 if( nDb>=20 && aDb[18]==2 && aDb[19]==2 ){
1032 aDb[18] = aDb[19] = 1;
1033 }
1034 rc = sqlite3_deserialize(cx.db, "main", aDb, nDb, nDb,
1035 SQLITE_DESERIALIZE_RESIZEABLE |
1036 SQLITE_DESERIALIZE_FREEONCLOSE);
1037 if( rc ){
1038 fprintf(stderr, "sqlite3_deserialize() failed with %d\n", rc);
1039 goto testrun_finished;
1040 }
1041 if( maxDbSize>0 ){
1042 sqlite3_int64 x = maxDbSize;
1043 sqlite3_file_control(cx.db, "main", SQLITE_FCNTL_SIZE_LIMIT, &x);
1044 }
1045
drh725a9c72019-01-25 13:03:38 +00001046 /* For high debugging levels, turn on debug mode */
1047 if( eVerbosity>=5 ){
1048 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON;", 0, 0, 0);
1049 }
1050
drha47e7092019-01-25 04:00:14 +00001051 /* Block debug pragmas and ATTACH/DETACH. But wait until after
1052 ** deserialize to do this because deserialize depends on ATTACH */
1053 sqlite3_set_authorizer(cx.db, block_troublesome_sql, 0);
1054
1055 /* Consistent PRNG seed */
drh319deef2021-04-04 23:56:15 +00001056#ifdef SQLITE_TESTCTRL_PRNG_SEED
1057 sqlite3_table_column_metadata(cx.db, 0, "x", 0, 0, 0, 0, 0, 0);
1058 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, cx.db);
1059#else
drha47e7092019-01-25 04:00:14 +00001060 sqlite3_randomness(0,0);
drh319deef2021-04-04 23:56:15 +00001061#endif
drha47e7092019-01-25 04:00:14 +00001062
1063 zSql = sqlite3_malloc( nSql + 1 );
1064 if( zSql==0 ){
1065 fprintf(stderr, "Out of memory!\n");
1066 }else{
1067 memcpy(zSql, aData+iSql, nSql);
1068 zSql[nSql] = 0;
1069 for(i=j=0; zSql[i]; i++){
1070 if( zSql[i]==';' ){
1071 char cSaved = zSql[i+1];
1072 zSql[i+1] = 0;
1073 if( sqlite3_complete(zSql+j) ){
1074 rc = runDbSql(cx.db, zSql+j);
1075 j = i+1;
1076 }
1077 zSql[i+1] = cSaved;
1078 if( rc==SQLITE_INTERRUPT || progress_handler(&cx) ){
1079 goto testrun_finished;
1080 }
1081 }
1082 }
1083 if( j<i ){
1084 runDbSql(cx.db, zSql+j);
1085 }
1086 }
1087testrun_finished:
1088 sqlite3_free(zSql);
1089 rc = sqlite3_close(cx.db);
1090 if( rc!=SQLITE_OK ){
1091 fprintf(stdout, "sqlite3_close() returns %d\n", rc);
1092 }
drh075201e2021-10-27 12:05:28 +00001093 if( eVerbosity>=2 && !bScript ){
drha47e7092019-01-25 04:00:14 +00001094 fprintf(stdout, "Peak memory usages: %f MB\n",
1095 sqlite3_memory_highwater(1) / 1000000.0);
1096 }
1097 if( sqlite3_memory_used()!=0 ){
1098 int nAlloc = 0;
1099 int nNotUsed = 0;
1100 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
1101 fprintf(stderr,"Memory leak: %lld bytes in %d allocations\n",
1102 sqlite3_memory_used(), nAlloc);
1103 exit(1);
1104 }
drh319deef2021-04-04 23:56:15 +00001105 sqlite3_hard_heap_limit64(0);
1106 sqlite3_soft_heap_limit64(0);
drha47e7092019-01-25 04:00:14 +00001107 return 0;
1108}
1109
1110/*
1111** END of the dbsqlfuzz code
1112***************************************************************************/
1113
1114/* Look at a SQL text and try to determine if it begins with a database
1115** description, such as would be found in a dbsqlfuzz test case. Return
1116** true if this does appear to be a dbsqlfuzz test case and false otherwise.
1117*/
1118static int isDbSql(unsigned char *a, int n){
drhdf216592019-01-25 04:43:26 +00001119 unsigned char buf[12];
1120 int i;
drha47e7092019-01-25 04:00:14 +00001121 if( n>4 && memcmp(a,"\n--\n",4)==0 ) return 1;
1122 while( n>0 && isspace(a[0]) ){ a++; n--; }
drhdf216592019-01-25 04:43:26 +00001123 for(i=0; n>0 && i<8; n--, a++){
1124 if( isxdigit(a[0]) ) buf[i++] = a[0];
1125 }
1126 if( i==8 && memcmp(buf,"53514c69",8)==0 ) return 1;
drha47e7092019-01-25 04:00:14 +00001127 return 0;
1128}
1129
drhe5da9352019-01-27 01:11:40 +00001130/* Implementation of the isdbsql(TEXT) SQL function.
1131*/
1132static void isDbSqlFunc(
1133 sqlite3_context *context,
1134 int argc,
1135 sqlite3_value **argv
1136){
1137 int n = sqlite3_value_bytes(argv[0]);
1138 unsigned char *a = (unsigned char*)sqlite3_value_blob(argv[0]);
1139 sqlite3_result_int(context, a!=0 && n>0 && isDbSql(a,n));
1140}
drha47e7092019-01-25 04:00:14 +00001141
drh3b74d032015-05-25 18:48:19 +00001142/* Methods for the VHandle object
1143*/
1144static int inmemClose(sqlite3_file *pFile){
1145 VHandle *p = (VHandle*)pFile;
1146 VFile *pVFile = p->pVFile;
1147 pVFile->nRef--;
1148 if( pVFile->nRef==0 && pVFile->zFilename==0 ){
1149 pVFile->sz = -1;
1150 free(pVFile->a);
1151 pVFile->a = 0;
1152 }
1153 return SQLITE_OK;
1154}
1155static int inmemRead(
1156 sqlite3_file *pFile, /* Read from this open file */
1157 void *pData, /* Store content in this buffer */
1158 int iAmt, /* Bytes of content */
1159 sqlite3_int64 iOfst /* Start reading here */
1160){
1161 VHandle *pHandle = (VHandle*)pFile;
1162 VFile *pVFile = pHandle->pVFile;
1163 if( iOfst<0 || iOfst>=pVFile->sz ){
1164 memset(pData, 0, iAmt);
1165 return SQLITE_IOERR_SHORT_READ;
1166 }
1167 if( iOfst+iAmt>pVFile->sz ){
1168 memset(pData, 0, iAmt);
drh1573dc32015-05-25 22:29:26 +00001169 iAmt = (int)(pVFile->sz - iOfst);
drhe45985b2018-12-14 02:29:56 +00001170 memcpy(pData, pVFile->a + iOfst, iAmt);
drh3b74d032015-05-25 18:48:19 +00001171 return SQLITE_IOERR_SHORT_READ;
1172 }
drhaca7ea12015-05-25 23:14:37 +00001173 memcpy(pData, pVFile->a + iOfst, iAmt);
drh3b74d032015-05-25 18:48:19 +00001174 return SQLITE_OK;
1175}
1176static int inmemWrite(
1177 sqlite3_file *pFile, /* Write to this file */
1178 const void *pData, /* Content to write */
1179 int iAmt, /* bytes to write */
1180 sqlite3_int64 iOfst /* Start writing here */
1181){
1182 VHandle *pHandle = (VHandle*)pFile;
1183 VFile *pVFile = pHandle->pVFile;
1184 if( iOfst+iAmt > pVFile->sz ){
drha9542b12015-05-25 19:35:42 +00001185 if( iOfst+iAmt >= MX_FILE_SZ ){
1186 return SQLITE_FULL;
1187 }
drh1573dc32015-05-25 22:29:26 +00001188 pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt));
drh908aced2015-05-26 16:12:45 +00001189 if( iOfst > pVFile->sz ){
1190 memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz));
1191 }
drh1573dc32015-05-25 22:29:26 +00001192 pVFile->sz = (int)(iOfst + iAmt);
drh3b74d032015-05-25 18:48:19 +00001193 }
1194 memcpy(pVFile->a + iOfst, pData, iAmt);
1195 return SQLITE_OK;
1196}
1197static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){
1198 VHandle *pHandle = (VHandle*)pFile;
1199 VFile *pVFile = pHandle->pVFile;
drh1573dc32015-05-25 22:29:26 +00001200 if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize;
drh3b74d032015-05-25 18:48:19 +00001201 return SQLITE_OK;
1202}
1203static int inmemSync(sqlite3_file *pFile, int flags){
1204 return SQLITE_OK;
1205}
1206static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){
1207 *pSize = ((VHandle*)pFile)->pVFile->sz;
1208 return SQLITE_OK;
1209}
1210static int inmemLock(sqlite3_file *pFile, int type){
1211 return SQLITE_OK;
1212}
1213static int inmemUnlock(sqlite3_file *pFile, int type){
1214 return SQLITE_OK;
1215}
1216static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){
1217 *pOut = 0;
1218 return SQLITE_OK;
1219}
1220static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){
1221 return SQLITE_NOTFOUND;
1222}
1223static int inmemSectorSize(sqlite3_file *pFile){
1224 return 512;
1225}
1226static int inmemDeviceCharacteristics(sqlite3_file *pFile){
1227 return
1228 SQLITE_IOCAP_SAFE_APPEND |
1229 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
1230 SQLITE_IOCAP_POWERSAFE_OVERWRITE;
1231}
1232
1233
1234/* Method table for VHandle
1235*/
1236static sqlite3_io_methods VHandleMethods = {
1237 /* iVersion */ 1,
1238 /* xClose */ inmemClose,
1239 /* xRead */ inmemRead,
1240 /* xWrite */ inmemWrite,
1241 /* xTruncate */ inmemTruncate,
1242 /* xSync */ inmemSync,
1243 /* xFileSize */ inmemFileSize,
1244 /* xLock */ inmemLock,
1245 /* xUnlock */ inmemUnlock,
1246 /* xCheck... */ inmemCheckReservedLock,
1247 /* xFileCtrl */ inmemFileControl,
1248 /* xSectorSz */ inmemSectorSize,
1249 /* xDevchar */ inmemDeviceCharacteristics,
1250 /* xShmMap */ 0,
1251 /* xShmLock */ 0,
1252 /* xShmBarrier */ 0,
1253 /* xShmUnmap */ 0,
1254 /* xFetch */ 0,
1255 /* xUnfetch */ 0
1256};
1257
1258/*
1259** Open a new file in the inmem VFS. All files are anonymous and are
1260** delete-on-close.
1261*/
1262static int inmemOpen(
1263 sqlite3_vfs *pVfs,
1264 const char *zFilename,
1265 sqlite3_file *pFile,
1266 int openFlags,
1267 int *pOutFlags
1268){
1269 VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)"");
1270 VHandle *pHandle = (VHandle*)pFile;
drha9542b12015-05-25 19:35:42 +00001271 if( pVFile==0 ){
1272 return SQLITE_FULL;
1273 }
drh3b74d032015-05-25 18:48:19 +00001274 pHandle->pVFile = pVFile;
1275 pVFile->nRef++;
1276 pFile->pMethods = &VHandleMethods;
1277 if( pOutFlags ) *pOutFlags = openFlags;
1278 return SQLITE_OK;
1279}
1280
1281/*
1282** Delete a file by name
1283*/
1284static int inmemDelete(
1285 sqlite3_vfs *pVfs,
1286 const char *zFilename,
1287 int syncdir
1288){
1289 VFile *pVFile = findVFile(zFilename);
1290 if( pVFile==0 ) return SQLITE_OK;
1291 if( pVFile->nRef==0 ){
1292 free(pVFile->zFilename);
1293 pVFile->zFilename = 0;
1294 pVFile->sz = -1;
1295 free(pVFile->a);
1296 pVFile->a = 0;
1297 return SQLITE_OK;
1298 }
1299 return SQLITE_IOERR_DELETE;
1300}
1301
1302/* Check for the existance of a file
1303*/
1304static int inmemAccess(
1305 sqlite3_vfs *pVfs,
1306 const char *zFilename,
1307 int flags,
1308 int *pResOut
1309){
1310 VFile *pVFile = findVFile(zFilename);
1311 *pResOut = pVFile!=0;
1312 return SQLITE_OK;
1313}
1314
1315/* Get the canonical pathname for a file
1316*/
1317static int inmemFullPathname(
1318 sqlite3_vfs *pVfs,
1319 const char *zFilename,
1320 int nOut,
1321 char *zOut
1322){
1323 sqlite3_snprintf(nOut, zOut, "%s", zFilename);
1324 return SQLITE_OK;
1325}
1326
drhbeaf5142016-12-26 00:15:56 +00001327/* Always use the same random see, for repeatability.
1328*/
1329static int inmemRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
1330 memset(zBuf, 0, nBuf);
1331 memcpy(zBuf, &g.uRandom, nBuf<sizeof(g.uRandom) ? nBuf : sizeof(g.uRandom));
1332 return nBuf;
1333}
1334
drh3b74d032015-05-25 18:48:19 +00001335/*
1336** Register the VFS that reads from the g.aFile[] set of files.
1337*/
drhbeaf5142016-12-26 00:15:56 +00001338static void inmemVfsRegister(int makeDefault){
drh3b74d032015-05-25 18:48:19 +00001339 static sqlite3_vfs inmemVfs;
1340 sqlite3_vfs *pDefault = sqlite3_vfs_find(0);
drh5337dac2015-11-25 15:15:03 +00001341 inmemVfs.iVersion = 3;
drh3b74d032015-05-25 18:48:19 +00001342 inmemVfs.szOsFile = sizeof(VHandle);
1343 inmemVfs.mxPathname = 200;
1344 inmemVfs.zName = "inmem";
1345 inmemVfs.xOpen = inmemOpen;
1346 inmemVfs.xDelete = inmemDelete;
1347 inmemVfs.xAccess = inmemAccess;
1348 inmemVfs.xFullPathname = inmemFullPathname;
drhbeaf5142016-12-26 00:15:56 +00001349 inmemVfs.xRandomness = inmemRandomness;
drh3b74d032015-05-25 18:48:19 +00001350 inmemVfs.xSleep = pDefault->xSleep;
drh5337dac2015-11-25 15:15:03 +00001351 inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64;
drhbeaf5142016-12-26 00:15:56 +00001352 sqlite3_vfs_register(&inmemVfs, makeDefault);
drh3b74d032015-05-25 18:48:19 +00001353};
1354
drh3b74d032015-05-25 18:48:19 +00001355/*
drhe5c5f2c2015-05-26 00:28:08 +00001356** Allowed values for the runFlags parameter to runSql()
1357*/
1358#define SQL_TRACE 0x0001 /* Print each SQL statement as it is prepared */
1359#define SQL_OUTPUT 0x0002 /* Show the SQL output */
1360
1361/*
drh3b74d032015-05-25 18:48:19 +00001362** Run multiple commands of SQL. Similar to sqlite3_exec(), but does not
1363** stop if an error is encountered.
1364*/
drhe5c5f2c2015-05-26 00:28:08 +00001365static void runSql(sqlite3 *db, const char *zSql, unsigned runFlags){
drh3b74d032015-05-25 18:48:19 +00001366 const char *zMore;
1367 sqlite3_stmt *pStmt;
1368
1369 while( zSql && zSql[0] ){
1370 zMore = 0;
1371 pStmt = 0;
1372 sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore);
drh4ab31472015-05-25 22:17:06 +00001373 if( zMore==zSql ) break;
drhe5c5f2c2015-05-26 00:28:08 +00001374 if( runFlags & SQL_TRACE ){
drh4ab31472015-05-25 22:17:06 +00001375 const char *z = zSql;
1376 int n;
drhc56fac72015-10-29 13:48:15 +00001377 while( z<zMore && ISSPACE(z[0]) ) z++;
drh4ab31472015-05-25 22:17:06 +00001378 n = (int)(zMore - z);
drhc56fac72015-10-29 13:48:15 +00001379 while( n>0 && ISSPACE(z[n-1]) ) n--;
drh4ab31472015-05-25 22:17:06 +00001380 if( n==0 ) break;
1381 if( pStmt==0 ){
1382 printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db));
1383 }else{
1384 printf("TRACE: %.*s\n", n, z);
1385 }
1386 }
drh3b74d032015-05-25 18:48:19 +00001387 zSql = zMore;
1388 if( pStmt ){
drhe5c5f2c2015-05-26 00:28:08 +00001389 if( (runFlags & SQL_OUTPUT)==0 ){
1390 while( SQLITE_ROW==sqlite3_step(pStmt) ){}
1391 }else{
1392 int nCol = -1;
1393 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1394 int i;
1395 if( nCol<0 ){
1396 nCol = sqlite3_column_count(pStmt);
1397 }else if( nCol>0 ){
1398 printf("--------------------------------------------\n");
1399 }
1400 for(i=0; i<nCol; i++){
1401 int eType = sqlite3_column_type(pStmt,i);
1402 printf("%s = ", sqlite3_column_name(pStmt,i));
1403 switch( eType ){
1404 case SQLITE_NULL: {
1405 printf("NULL\n");
1406 break;
1407 }
1408 case SQLITE_INTEGER: {
1409 printf("INT %s\n", sqlite3_column_text(pStmt,i));
1410 break;
1411 }
1412 case SQLITE_FLOAT: {
1413 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i));
1414 break;
1415 }
1416 case SQLITE_TEXT: {
1417 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i));
1418 break;
1419 }
1420 case SQLITE_BLOB: {
1421 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i));
1422 break;
1423 }
1424 }
1425 }
1426 }
1427 }
drh3b74d032015-05-25 18:48:19 +00001428 sqlite3_finalize(pStmt);
drh3b74d032015-05-25 18:48:19 +00001429 }
1430 }
1431}
1432
drha9542b12015-05-25 19:35:42 +00001433/*
drh9a645862015-06-24 12:44:42 +00001434** Rebuild the database file.
1435**
1436** (1) Remove duplicate entries
1437** (2) Put all entries in order
1438** (3) Vacuum
1439*/
drhe5da9352019-01-27 01:11:40 +00001440static void rebuild_database(sqlite3 *db, int dbSqlOnly){
drh9a645862015-06-24 12:44:42 +00001441 int rc;
drhe5da9352019-01-27 01:11:40 +00001442 char *zSql;
1443 zSql = sqlite3_mprintf(
drh9a645862015-06-24 12:44:42 +00001444 "BEGIN;\n"
1445 "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n"
1446 "DELETE FROM db;\n"
drh5ecf9032018-05-08 12:49:53 +00001447 "INSERT INTO db(dbid, dbcontent) "
1448 " SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n"
drh9a645862015-06-24 12:44:42 +00001449 "DROP TABLE dbx;\n"
drhe5da9352019-01-27 01:11:40 +00001450 "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql %s;\n"
drh9a645862015-06-24 12:44:42 +00001451 "DELETE FROM xsql;\n"
drh5ecf9032018-05-08 12:49:53 +00001452 "INSERT INTO xsql(sqlid,sqltext) "
1453 " SELECT NULL, sqltext FROM sx ORDER BY 2;\n"
drh9a645862015-06-24 12:44:42 +00001454 "DROP TABLE sx;\n"
1455 "COMMIT;\n"
1456 "PRAGMA page_size=1024;\n"
drhe5da9352019-01-27 01:11:40 +00001457 "VACUUM;\n",
1458 dbSqlOnly ? " WHERE isdbsql(sqltext)" : ""
1459 );
1460 rc = sqlite3_exec(db, zSql, 0, 0, 0);
1461 sqlite3_free(zSql);
drh9a645862015-06-24 12:44:42 +00001462 if( rc ) fatalError("cannot rebuild: %s", sqlite3_errmsg(db));
1463}
1464
1465/*
drh53e66c32015-07-24 15:49:23 +00001466** Return the value of a hexadecimal digit. Return -1 if the input
1467** is not a hex digit.
1468*/
1469static int hexDigitValue(char c){
1470 if( c>='0' && c<='9' ) return c - '0';
1471 if( c>='a' && c<='f' ) return c - 'a' + 10;
1472 if( c>='A' && c<='F' ) return c - 'A' + 10;
1473 return -1;
1474}
1475
1476/*
1477** Interpret zArg as an integer value, possibly with suffixes.
1478*/
1479static int integerValue(const char *zArg){
1480 sqlite3_int64 v = 0;
1481 static const struct { char *zSuffix; int iMult; } aMult[] = {
1482 { "KiB", 1024 },
1483 { "MiB", 1024*1024 },
1484 { "GiB", 1024*1024*1024 },
1485 { "KB", 1000 },
1486 { "MB", 1000000 },
1487 { "GB", 1000000000 },
1488 { "K", 1000 },
1489 { "M", 1000000 },
1490 { "G", 1000000000 },
1491 };
1492 int i;
1493 int isNeg = 0;
1494 if( zArg[0]=='-' ){
1495 isNeg = 1;
1496 zArg++;
1497 }else if( zArg[0]=='+' ){
1498 zArg++;
1499 }
1500 if( zArg[0]=='0' && zArg[1]=='x' ){
1501 int x;
1502 zArg += 2;
1503 while( (x = hexDigitValue(zArg[0]))>=0 ){
1504 v = (v<<4) + x;
1505 zArg++;
1506 }
1507 }else{
drhc56fac72015-10-29 13:48:15 +00001508 while( ISDIGIT(zArg[0]) ){
drh53e66c32015-07-24 15:49:23 +00001509 v = v*10 + zArg[0] - '0';
1510 zArg++;
1511 }
1512 }
1513 for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
1514 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1515 v *= aMult[i].iMult;
1516 break;
1517 }
1518 }
1519 if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648");
1520 return (int)(isNeg? -v : v);
1521}
1522
1523/*
drh725a9c72019-01-25 13:03:38 +00001524** Return the number of "v" characters in a string. Return 0 if there
1525** are any characters in the string other than "v".
1526*/
1527static int numberOfVChar(const char *z){
1528 int N = 0;
1529 while( z[0] && z[0]=='v' ){
1530 z++;
1531 N++;
1532 }
1533 return z[0]==0 ? N : 0;
1534}
1535
1536/*
drha9542b12015-05-25 19:35:42 +00001537** Print sketchy documentation for this utility program
1538*/
1539static void showHelp(void){
1540 printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0);
1541 printf(
1542"Read databases and SQL scripts from SOURCE-DB and execute each script against\n"
1543"each database, checking for crashes and memory leaks.\n"
1544"Options:\n"
drha36e01a2016-08-03 13:40:54 +00001545" --cell-size-check Set the PRAGMA cell_size_check=ON\n"
1546" --dbid N Use only the database where dbid=N\n"
1547" --export-db DIR Write databases to files(s) in DIR. Works with --dbid\n"
1548" --export-sql DIR Write SQL to file(s) in DIR. Also works with --sqlid\n"
1549" --help Show this help text\n"
drh5180d682018-08-06 01:39:31 +00001550" --info Show information about SOURCE-DB w/o running tests\n"
drh672f07c2020-10-20 14:40:53 +00001551" --limit-depth N Limit expression depth to N. Default: 500\n"
1552" --limit-heap N Limit heap memory to N. Default: 100M\n"
drha36e01a2016-08-03 13:40:54 +00001553" --limit-mem N Limit memory used by test SQLite instance to N bytes\n"
1554" --limit-vdbe Panic if any test runs for more than 100,000 cycles\n"
drhba6619d2021-04-23 12:58:16 +00001555" --load-sql FILE.. Load SQL scripts fron files into SOURCE-DB\n"
1556" --load-db FILE.. Load template databases from files into SOURCE_DB\n"
1557" --load-dbsql FILE.. Load dbsqlfuzz outputs into the xsql table\n"
1558" ^^^^------ Use \"-\" for FILE to read filenames from stdin\n"
drha36e01a2016-08-03 13:40:54 +00001559" -m TEXT Add a description to the database\n"
1560" --native-vfs Use the native VFS for initially empty database files\n"
drh174f8552017-03-20 22:58:27 +00001561" --native-malloc Turn off MEMSYS3/5 and Lookaside\n"
drhea432ba2016-11-11 16:33:47 +00001562" --oss-fuzz Enable OSS-FUZZ testing\n"
drhbeaf5142016-12-26 00:15:56 +00001563" --prng-seed N Seed value for the PRGN inside of SQLite\n"
drh5180d682018-08-06 01:39:31 +00001564" -q|--quiet Reduced output\n"
drha36e01a2016-08-03 13:40:54 +00001565" --rebuild Rebuild and vacuum the database file\n"
1566" --result-trace Show the results of each SQL command\n"
drh075201e2021-10-27 12:05:28 +00001567" --script Output CLI script instead of running tests\n"
drh672f07c2020-10-20 14:40:53 +00001568" --skip N Skip the first N test cases\n"
drhaa0696e2020-04-07 13:08:56 +00001569" --spinner Use a spinner to show progress\n"
drha36e01a2016-08-03 13:40:54 +00001570" --sqlid N Use only SQL where sqlid=N\n"
drh237f41a2020-12-21 12:14:59 +00001571" --timeout N Maximum time for any one test in N millseconds\n"
drha36e01a2016-08-03 13:40:54 +00001572" -v|--verbose Increased output. Repeat for more output.\n"
drh6e1c45e2019-12-18 13:42:04 +00001573" --vdbe-debug Activate VDBE debugging.\n"
drha9542b12015-05-25 19:35:42 +00001574 );
1575}
1576
drh3b74d032015-05-25 18:48:19 +00001577int main(int argc, char **argv){
1578 sqlite3_int64 iBegin; /* Start time of this program */
drh3b74d032015-05-25 18:48:19 +00001579 int quietFlag = 0; /* True if --quiet or -q */
1580 int verboseFlag = 0; /* True if --verbose or -v */
1581 char *zInsSql = 0; /* SQL statement for --load-db or --load-sql */
drh5ecf9032018-05-08 12:49:53 +00001582 int iFirstInsArg = 0; /* First argv[] for --load-db or --load-sql */
drh3b74d032015-05-25 18:48:19 +00001583 sqlite3 *db = 0; /* The open database connection */
drhd9972ef2015-05-26 17:57:56 +00001584 sqlite3_stmt *pStmt; /* A prepared statement */
drh3b74d032015-05-25 18:48:19 +00001585 int rc; /* Result code from SQLite interface calls */
1586 Blob *pSql; /* For looping over SQL scripts */
1587 Blob *pDb; /* For looping over template databases */
1588 int i; /* Loop index for the argv[] loop */
drhe5da9352019-01-27 01:11:40 +00001589 int dbSqlOnly = 0; /* Only use scripts that are dbsqlfuzz */
drha9542b12015-05-25 19:35:42 +00001590 int onlySqlid = -1; /* --sqlid */
1591 int onlyDbid = -1; /* --dbid */
drh15b31282015-05-25 21:59:05 +00001592 int nativeFlag = 0; /* --native-vfs */
drh9a645862015-06-24 12:44:42 +00001593 int rebuildFlag = 0; /* --rebuild */
drhd83e2832015-06-24 14:45:44 +00001594 int vdbeLimitFlag = 0; /* --limit-vdbe */
drh5180d682018-08-06 01:39:31 +00001595 int infoFlag = 0; /* --info */
drh672f07c2020-10-20 14:40:53 +00001596 int nSkip = 0; /* --skip */
drh075201e2021-10-27 12:05:28 +00001597 int bScript = 0; /* --script */
drhaa0696e2020-04-07 13:08:56 +00001598 int bSpinner = 0; /* True for --spinner */
drh94701b02015-06-24 13:25:34 +00001599 int timeoutTest = 0; /* undocumented --timeout-test flag */
drhe5c5f2c2015-05-26 00:28:08 +00001600 int runFlags = 0; /* Flags sent to runSql() */
drhd9972ef2015-05-26 17:57:56 +00001601 char *zMsg = 0; /* Add this message */
1602 int nSrcDb = 0; /* Number of source databases */
1603 char **azSrcDb = 0; /* Array of source database names */
1604 int iSrcDb; /* Loop over all source databases */
1605 int nTest = 0; /* Total number of tests performed */
1606 char *zDbName = ""; /* Appreviated name of a source database */
drh5ecf9032018-05-08 12:49:53 +00001607 const char *zFailCode = 0; /* Value of the TEST_FAILURE env variable */
drh1421d982015-05-27 03:46:18 +00001608 int cellSzCkFlag = 0; /* --cell-size-check */
drh5ecf9032018-05-08 12:49:53 +00001609 int sqlFuzz = 0; /* True for SQL fuzz. False for DB fuzz */
drh237f41a2020-12-21 12:14:59 +00001610 int iTimeout = 120000; /* Default 120-second timeout */
drh31999c52019-11-14 17:46:32 +00001611 int nMem = 0; /* Memory limit override */
drh362b66f2016-11-14 18:27:41 +00001612 int nMemThisDb = 0; /* Memory limit set by the CONFIG table */
drh40e0e0d2015-09-22 18:51:17 +00001613 char *zExpDb = 0; /* Write Databases to files in this directory */
1614 char *zExpSql = 0; /* Write SQL to files in this directory */
drh6653fbe2015-11-13 20:52:49 +00001615 void *pHeap = 0; /* Heap for use by SQLite */
drhea432ba2016-11-11 16:33:47 +00001616 int ossFuzz = 0; /* enable OSS-FUZZ testing */
drh362b66f2016-11-14 18:27:41 +00001617 int ossFuzzThisDb = 0; /* ossFuzz value for this particular database */
drh174f8552017-03-20 22:58:27 +00001618 int nativeMalloc = 0; /* Turn off MEMSYS3/5 and lookaside if true */
drhbeaf5142016-12-26 00:15:56 +00001619 sqlite3_vfs *pDfltVfs; /* The default VFS */
drhf2cf4122018-05-08 13:03:31 +00001620 int openFlags4Data; /* Flags for sqlite3_open_v2() */
drh237f41a2020-12-21 12:14:59 +00001621 int bTimer = 0; /* Show elapse time for each test */
drh725a9c72019-01-25 13:03:38 +00001622 int nV; /* How much to increase verbosity with -vvvv */
drh237f41a2020-12-21 12:14:59 +00001623 sqlite3_int64 tmStart; /* Start of each test */
drh3b74d032015-05-25 18:48:19 +00001624
drhbe536562021-10-23 11:30:35 +00001625 sqlite3_config(SQLITE_CONFIG_URI,1);
drh39b3bcf2020-03-02 16:31:21 +00001626 registerOomSimulator();
drh8055a3e2018-11-21 14:27:34 +00001627 sqlite3_initialize();
drh3b74d032015-05-25 18:48:19 +00001628 iBegin = timeOfDay();
drh94701b02015-06-24 13:25:34 +00001629#ifdef __unix__
drha7648f02019-12-18 13:02:18 +00001630 signal(SIGALRM, signalHandler);
1631 signal(SIGSEGV, signalHandler);
1632 signal(SIGABRT, signalHandler);
drh94701b02015-06-24 13:25:34 +00001633#endif
drh3b74d032015-05-25 18:48:19 +00001634 g.zArgv0 = argv[0];
drhf2cf4122018-05-08 13:03:31 +00001635 openFlags4Data = SQLITE_OPEN_READONLY;
drh4d6fda72015-05-26 18:58:32 +00001636 zFailCode = getenv("TEST_FAILURE");
drhbeaf5142016-12-26 00:15:56 +00001637 pDfltVfs = sqlite3_vfs_find(0);
1638 inmemVfsRegister(1);
drh3b74d032015-05-25 18:48:19 +00001639 for(i=1; i<argc; i++){
1640 const char *z = argv[i];
1641 if( z[0]=='-' ){
1642 z++;
1643 if( z[0]=='-' ) z++;
drh1421d982015-05-27 03:46:18 +00001644 if( strcmp(z,"cell-size-check")==0 ){
1645 cellSzCkFlag = 1;
1646 }else
drha9542b12015-05-25 19:35:42 +00001647 if( strcmp(z,"dbid")==0 ){
1648 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
drh53e66c32015-07-24 15:49:23 +00001649 onlyDbid = integerValue(argv[++i]);
drha9542b12015-05-25 19:35:42 +00001650 }else
drh40e0e0d2015-09-22 18:51:17 +00001651 if( strcmp(z,"export-db")==0 ){
1652 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1653 zExpDb = argv[++i];
1654 }else
drhe5da9352019-01-27 01:11:40 +00001655 if( strcmp(z,"export-sql")==0 || strcmp(z,"export-dbsql")==0 ){
drh40e0e0d2015-09-22 18:51:17 +00001656 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1657 zExpSql = argv[++i];
1658 }else
drh3b74d032015-05-25 18:48:19 +00001659 if( strcmp(z,"help")==0 ){
1660 showHelp();
1661 return 0;
1662 }else
drh5180d682018-08-06 01:39:31 +00001663 if( strcmp(z,"info")==0 ){
1664 infoFlag = 1;
1665 }else
drhbe03cc92020-01-20 14:42:09 +00001666 if( strcmp(z,"limit-depth")==0 ){
1667 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1668 depthLimit = integerValue(argv[++i]);
1669 }else
drh672f07c2020-10-20 14:40:53 +00001670 if( strcmp(z,"limit-heap")==0 ){
1671 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1672 heapLimit = integerValue(argv[++i]);
1673 }else
drh53e66c32015-07-24 15:49:23 +00001674 if( strcmp(z,"limit-mem")==0 ){
1675 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1676 nMem = integerValue(argv[++i]);
1677 }else
drhd83e2832015-06-24 14:45:44 +00001678 if( strcmp(z,"limit-vdbe")==0 ){
1679 vdbeLimitFlag = 1;
1680 }else
drh3b74d032015-05-25 18:48:19 +00001681 if( strcmp(z,"load-sql")==0 ){
drha8781d92020-02-25 20:05:58 +00001682 zInsSql = "INSERT INTO xsql(sqltext)"
1683 "VALUES(CAST(readtextfile(?1) AS text))";
drh3b74d032015-05-25 18:48:19 +00001684 iFirstInsArg = i+1;
drhf2cf4122018-05-08 13:03:31 +00001685 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
drh3b74d032015-05-25 18:48:19 +00001686 break;
1687 }else
1688 if( strcmp(z,"load-db")==0 ){
1689 zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
1690 iFirstInsArg = i+1;
drhf2cf4122018-05-08 13:03:31 +00001691 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
drh3b74d032015-05-25 18:48:19 +00001692 break;
1693 }else
drhe5da9352019-01-27 01:11:40 +00001694 if( strcmp(z,"load-dbsql")==0 ){
drha8781d92020-02-25 20:05:58 +00001695 zInsSql = "INSERT INTO xsql(sqltext)"
drh662bebb2021-10-27 13:16:33 +00001696 "VALUES(readfile(?1))";
drhe5da9352019-01-27 01:11:40 +00001697 iFirstInsArg = i+1;
1698 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1699 dbSqlOnly = 1;
1700 break;
1701 }else
drhd9972ef2015-05-26 17:57:56 +00001702 if( strcmp(z,"m")==0 ){
1703 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1704 zMsg = argv[++i];
drhf2cf4122018-05-08 13:03:31 +00001705 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
drhd9972ef2015-05-26 17:57:56 +00001706 }else
drh174f8552017-03-20 22:58:27 +00001707 if( strcmp(z,"native-malloc")==0 ){
1708 nativeMalloc = 1;
1709 }else
drh15b31282015-05-25 21:59:05 +00001710 if( strcmp(z,"native-vfs")==0 ){
1711 nativeFlag = 1;
1712 }else
drhea432ba2016-11-11 16:33:47 +00001713 if( strcmp(z,"oss-fuzz")==0 ){
1714 ossFuzz = 1;
1715 }else
drhbeaf5142016-12-26 00:15:56 +00001716 if( strcmp(z,"prng-seed")==0 ){
1717 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1718 g.uRandom = atoi(argv[++i]);
1719 }else
drh3b74d032015-05-25 18:48:19 +00001720 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
1721 quietFlag = 1;
1722 verboseFlag = 0;
drha47e7092019-01-25 04:00:14 +00001723 eVerbosity = 0;
drh3b74d032015-05-25 18:48:19 +00001724 }else
drh9a645862015-06-24 12:44:42 +00001725 if( strcmp(z,"rebuild")==0 ){
1726 rebuildFlag = 1;
drhf2cf4122018-05-08 13:03:31 +00001727 openFlags4Data = SQLITE_OPEN_READWRITE;
drh9a645862015-06-24 12:44:42 +00001728 }else
drhe5c5f2c2015-05-26 00:28:08 +00001729 if( strcmp(z,"result-trace")==0 ){
1730 runFlags |= SQL_OUTPUT;
1731 }else
drh075201e2021-10-27 12:05:28 +00001732 if( strcmp(z,"script")==0 ){
1733 bScript = 1;
1734 }else
drh672f07c2020-10-20 14:40:53 +00001735 if( strcmp(z,"skip")==0 ){
1736 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1737 nSkip = atoi(argv[++i]);
1738 }else
drhaa0696e2020-04-07 13:08:56 +00001739 if( strcmp(z,"spinner")==0 ){
1740 bSpinner = 1;
1741 }else
drh237f41a2020-12-21 12:14:59 +00001742 if( strcmp(z,"timer")==0 ){
1743 bTimer = 1;
1744 }else
drha9542b12015-05-25 19:35:42 +00001745 if( strcmp(z,"sqlid")==0 ){
1746 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
drh53e66c32015-07-24 15:49:23 +00001747 onlySqlid = integerValue(argv[++i]);
drha9542b12015-05-25 19:35:42 +00001748 }else
drh92298632015-06-24 23:44:30 +00001749 if( strcmp(z,"timeout")==0 ){
1750 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
drh53e66c32015-07-24 15:49:23 +00001751 iTimeout = integerValue(argv[++i]);
drh92298632015-06-24 23:44:30 +00001752 }else
drh94701b02015-06-24 13:25:34 +00001753 if( strcmp(z,"timeout-test")==0 ){
1754 timeoutTest = 1;
1755#ifndef __unix__
1756 fatalError("timeout is not available on non-unix systems");
1757#endif
1758 }else
drh6e1c45e2019-12-18 13:42:04 +00001759 if( strcmp(z,"vdbe-debug")==0 ){
1760 bVdbeDebug = 1;
1761 }else
drh725a9c72019-01-25 13:03:38 +00001762 if( strcmp(z,"verbose")==0 ){
drh3b74d032015-05-25 18:48:19 +00001763 quietFlag = 0;
drh4c9d2282016-02-18 14:03:15 +00001764 verboseFlag++;
drha47e7092019-01-25 04:00:14 +00001765 eVerbosity++;
drh4c9d2282016-02-18 14:03:15 +00001766 if( verboseFlag>1 ) runFlags |= SQL_TRACE;
drh3b74d032015-05-25 18:48:19 +00001767 }else
drh725a9c72019-01-25 13:03:38 +00001768 if( (nV = numberOfVChar(z))>=1 ){
1769 quietFlag = 0;
1770 verboseFlag += nV;
1771 eVerbosity += nV;
1772 if( verboseFlag>1 ) runFlags |= SQL_TRACE;
1773 }else
drha47e7092019-01-25 04:00:14 +00001774 if( strcmp(z,"version")==0 ){
1775 int ii;
drhed457032019-01-25 17:51:06 +00001776 const char *zz;
drha47e7092019-01-25 04:00:14 +00001777 printf("SQLite %s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drhed457032019-01-25 17:51:06 +00001778 for(ii=0; (zz = sqlite3_compileoption_get(ii))!=0; ii++){
1779 printf("%s\n", zz);
drha47e7092019-01-25 04:00:14 +00001780 }
1781 return 0;
1782 }else
drh662bebb2021-10-27 13:16:33 +00001783 if( strcmp(z,"is-dbsql")==0 ){
1784 i++;
1785 for(i++; i<argc; i++){
1786 long nData;
1787 char *aData = readFile(argv[i], &nData);
drhbe2d6fd2021-10-27 15:16:30 +00001788 printf("%d %s\n", isDbSql((unsigned char*)aData,nData), argv[i]);
drh662bebb2021-10-27 13:16:33 +00001789 sqlite3_free(aData);
1790 }
1791 exit(0);
1792 }else
drh3b74d032015-05-25 18:48:19 +00001793 {
1794 fatalError("unknown option: %s", argv[i]);
1795 }
1796 }else{
drhd9972ef2015-05-26 17:57:56 +00001797 nSrcDb++;
1798 azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
1799 azSrcDb[nSrcDb-1] = argv[i];
drh3b74d032015-05-25 18:48:19 +00001800 }
1801 }
drhd9972ef2015-05-26 17:57:56 +00001802 if( nSrcDb==0 ) fatalError("no source database specified");
1803 if( nSrcDb>1 ){
1804 if( zMsg ){
1805 fatalError("cannot change the description of more than one database");
drh3b74d032015-05-25 18:48:19 +00001806 }
drhd9972ef2015-05-26 17:57:56 +00001807 if( zInsSql ){
1808 fatalError("cannot import into more than one database");
1809 }
drh3b74d032015-05-25 18:48:19 +00001810 }
1811
drhd9972ef2015-05-26 17:57:56 +00001812 /* Process each source database separately */
1813 for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
drh48b4bf22021-10-26 22:36:41 +00001814 char *zRawData = 0;
1815 long nRawData = 0;
drha7648f02019-12-18 13:02:18 +00001816 g.zDbFile = azSrcDb[iSrcDb];
drhbeaf5142016-12-26 00:15:56 +00001817 rc = sqlite3_open_v2(azSrcDb[iSrcDb], &db,
drhf2cf4122018-05-08 13:03:31 +00001818 openFlags4Data, pDfltVfs->zName);
drh48b4bf22021-10-26 22:36:41 +00001819 if( rc==SQLITE_OK ){
1820 rc = sqlite3_exec(db, "SELECT count(*) FROM sqlite_schema", 0, 0, 0);
1821 }
drhd9972ef2015-05-26 17:57:56 +00001822 if( rc ){
drh48b4bf22021-10-26 22:36:41 +00001823 sqlite3_close(db);
1824 zRawData = readFile(azSrcDb[iSrcDb], &nRawData);
1825 if( zRawData==0 ){
1826 fatalError("input file \"%s\" is not recognized\n", azSrcDb[iSrcDb]);
1827 }
1828 sqlite3_open(":memory:", &db);
drhd9972ef2015-05-26 17:57:56 +00001829 }
drh5180d682018-08-06 01:39:31 +00001830
1831 /* Print the description, if there is one */
1832 if( infoFlag ){
1833 int n;
1834 zDbName = azSrcDb[iSrcDb];
1835 i = (int)strlen(zDbName) - 1;
1836 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
1837 zDbName += i;
1838 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
1839 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
1840 printf("%s: %s", zDbName, sqlite3_column_text(pStmt,0));
1841 }else{
1842 printf("%s: (empty \"readme\")", zDbName);
1843 }
1844 sqlite3_finalize(pStmt);
1845 sqlite3_prepare_v2(db, "SELECT count(*) FROM db", -1, &pStmt, 0);
1846 if( pStmt
1847 && sqlite3_step(pStmt)==SQLITE_ROW
1848 && (n = sqlite3_column_int(pStmt,0))>0
1849 ){
1850 printf(" - %d DBs", n);
1851 }
1852 sqlite3_finalize(pStmt);
1853 sqlite3_prepare_v2(db, "SELECT count(*) FROM xsql", -1, &pStmt, 0);
1854 if( pStmt
1855 && sqlite3_step(pStmt)==SQLITE_ROW
1856 && (n = sqlite3_column_int(pStmt,0))>0
1857 ){
1858 printf(" - %d scripts", n);
1859 }
1860 sqlite3_finalize(pStmt);
1861 printf("\n");
1862 sqlite3_close(db);
drh48b4bf22021-10-26 22:36:41 +00001863 sqlite3_free(zRawData);
drh5180d682018-08-06 01:39:31 +00001864 continue;
1865 }
1866
drh9a645862015-06-24 12:44:42 +00001867 rc = sqlite3_exec(db,
drhd9972ef2015-05-26 17:57:56 +00001868 "CREATE TABLE IF NOT EXISTS db(\n"
1869 " dbid INTEGER PRIMARY KEY, -- database id\n"
1870 " dbcontent BLOB -- database disk file image\n"
1871 ");\n"
1872 "CREATE TABLE IF NOT EXISTS xsql(\n"
1873 " sqlid INTEGER PRIMARY KEY, -- SQL script id\n"
1874 " sqltext TEXT -- Text of SQL statements to run\n"
1875 ");"
1876 "CREATE TABLE IF NOT EXISTS readme(\n"
1877 " msg TEXT -- Human-readable description of this file\n"
1878 ");", 0, 0, 0);
1879 if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
1880 if( zMsg ){
1881 char *zSql;
1882 zSql = sqlite3_mprintf(
1883 "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
1884 rc = sqlite3_exec(db, zSql, 0, 0, 0);
1885 sqlite3_free(zSql);
1886 if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
1887 }
drh48b4bf22021-10-26 22:36:41 +00001888 if( zRawData ){
1889 zInsSql = "INSERT INTO xsql(sqltext) VALUES(?1)";
1890 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
1891 if( rc ) fatalError("cannot prepare statement [%s]: %s",
1892 zInsSql, sqlite3_errmsg(db));
1893 sqlite3_bind_text(pStmt, 1, zRawData, nRawData, SQLITE_STATIC);
1894 sqlite3_step(pStmt);
1895 rc = sqlite3_reset(pStmt);
1896 if( rc ) fatalError("insert failed for %s", argv[i]);
1897 sqlite3_finalize(pStmt);
1898 rebuild_database(db, dbSqlOnly);
1899 zInsSql = 0;
1900 sqlite3_free(zRawData);
1901 zRawData = 0;
1902 }
drh362b66f2016-11-14 18:27:41 +00001903 ossFuzzThisDb = ossFuzz;
1904
1905 /* If the CONFIG(name,value) table exists, read db-specific settings
1906 ** from that table */
1907 if( sqlite3_table_column_metadata(db,0,"config",0,0,0,0,0,0)==SQLITE_OK ){
drh5ecf9032018-05-08 12:49:53 +00001908 rc = sqlite3_prepare_v2(db, "SELECT name, value FROM config",
1909 -1, &pStmt, 0);
drh362b66f2016-11-14 18:27:41 +00001910 if( rc ) fatalError("cannot prepare query of CONFIG table: %s",
1911 sqlite3_errmsg(db));
1912 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1913 const char *zName = (const char *)sqlite3_column_text(pStmt,0);
1914 if( zName==0 ) continue;
1915 if( strcmp(zName, "oss-fuzz")==0 ){
1916 ossFuzzThisDb = sqlite3_column_int(pStmt,1);
1917 if( verboseFlag ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb);
1918 }
drh31999c52019-11-14 17:46:32 +00001919 if( strcmp(zName, "limit-mem")==0 ){
drh362b66f2016-11-14 18:27:41 +00001920 nMemThisDb = sqlite3_column_int(pStmt,1);
1921 if( verboseFlag ) printf("Config: limit-mem=%d\n", nMemThisDb);
drh362b66f2016-11-14 18:27:41 +00001922 }
1923 }
1924 sqlite3_finalize(pStmt);
1925 }
1926
drhd9972ef2015-05-26 17:57:56 +00001927 if( zInsSql ){
1928 sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
1929 readfileFunc, 0, 0);
drha8781d92020-02-25 20:05:58 +00001930 sqlite3_create_function(db, "readtextfile", 1, SQLITE_UTF8, 0,
1931 readtextfileFunc, 0, 0);
drhe5da9352019-01-27 01:11:40 +00001932 sqlite3_create_function(db, "isdbsql", 1, SQLITE_UTF8, 0,
1933 isDbSqlFunc, 0, 0);
drhd9972ef2015-05-26 17:57:56 +00001934 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
1935 if( rc ) fatalError("cannot prepare statement [%s]: %s",
1936 zInsSql, sqlite3_errmsg(db));
1937 rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
1938 if( rc ) fatalError("cannot start a transaction");
1939 for(i=iFirstInsArg; i<argc; i++){
drhba6619d2021-04-23 12:58:16 +00001940 if( strcmp(argv[i],"-")==0 ){
1941 /* A filename of "-" means read multiple filenames from stdin */
drh15212702021-04-23 13:57:53 +00001942 char zLine[2000];
drhba6619d2021-04-23 12:58:16 +00001943 while( rc==0 && fgets(zLine,sizeof(zLine),stdin)!=0 ){
1944 size_t kk = strlen(zLine);
drh59607242021-04-29 18:03:42 +00001945 while( kk>0 && zLine[kk-1]<=' ' ) kk--;
drh9d41caf2021-07-07 19:44:32 +00001946 sqlite3_bind_text(pStmt, 1, zLine, (int)kk, SQLITE_STATIC);
drh59607242021-04-29 18:03:42 +00001947 if( verboseFlag ) printf("loading %.*s\n", (int)kk, zLine);
drhba6619d2021-04-23 12:58:16 +00001948 sqlite3_step(pStmt);
1949 rc = sqlite3_reset(pStmt);
1950 if( rc ) fatalError("insert failed for %s", zLine);
1951 }
1952 }else{
1953 sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
drh59607242021-04-29 18:03:42 +00001954 if( verboseFlag ) printf("loading %s\n", argv[i]);
drhba6619d2021-04-23 12:58:16 +00001955 sqlite3_step(pStmt);
1956 rc = sqlite3_reset(pStmt);
1957 if( rc ) fatalError("insert failed for %s", argv[i]);
1958 }
drh3b74d032015-05-25 18:48:19 +00001959 }
drhd9972ef2015-05-26 17:57:56 +00001960 sqlite3_finalize(pStmt);
1961 rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
drh5ecf9032018-05-08 12:49:53 +00001962 if( rc ) fatalError("cannot commit the transaction: %s",
1963 sqlite3_errmsg(db));
drhe5da9352019-01-27 01:11:40 +00001964 rebuild_database(db, dbSqlOnly);
drh3b74d032015-05-25 18:48:19 +00001965 sqlite3_close(db);
drhd9972ef2015-05-26 17:57:56 +00001966 return 0;
drh3b74d032015-05-25 18:48:19 +00001967 }
drh16f05822017-03-20 20:42:21 +00001968 rc = sqlite3_exec(db, "PRAGMA query_only=1;", 0, 0, 0);
1969 if( rc ) fatalError("cannot set database to query-only");
drh40e0e0d2015-09-22 18:51:17 +00001970 if( zExpDb!=0 || zExpSql!=0 ){
1971 sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
1972 writefileFunc, 0, 0);
1973 if( zExpDb!=0 ){
1974 const char *zExDb =
1975 "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent),"
1976 " dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)"
1977 " FROM db WHERE ?2<0 OR dbid=?2;";
1978 rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0);
1979 if( rc ) fatalError("cannot prepare statement [%s]: %s",
1980 zExDb, sqlite3_errmsg(db));
1981 sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb),
1982 SQLITE_STATIC, SQLITE_UTF8);
1983 sqlite3_bind_int(pStmt, 2, onlyDbid);
1984 while( sqlite3_step(pStmt)==SQLITE_ROW ){
1985 printf("write db-%d (%d bytes) into %s\n",
1986 sqlite3_column_int(pStmt,1),
1987 sqlite3_column_int(pStmt,3),
1988 sqlite3_column_text(pStmt,2));
1989 }
1990 sqlite3_finalize(pStmt);
1991 }
1992 if( zExpSql!=0 ){
1993 const char *zExSql =
1994 "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext),"
1995 " sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)"
1996 " FROM xsql WHERE ?2<0 OR sqlid=?2;";
1997 rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0);
1998 if( rc ) fatalError("cannot prepare statement [%s]: %s",
1999 zExSql, sqlite3_errmsg(db));
2000 sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql),
2001 SQLITE_STATIC, SQLITE_UTF8);
2002 sqlite3_bind_int(pStmt, 2, onlySqlid);
2003 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2004 printf("write sql-%d (%d bytes) into %s\n",
2005 sqlite3_column_int(pStmt,1),
2006 sqlite3_column_int(pStmt,3),
2007 sqlite3_column_text(pStmt,2));
2008 }
2009 sqlite3_finalize(pStmt);
2010 }
2011 sqlite3_close(db);
2012 return 0;
2013 }
drhd9972ef2015-05-26 17:57:56 +00002014
2015 /* Load all SQL script content and all initial database images from the
2016 ** source db
2017 */
2018 blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
2019 &g.nSql, &g.pFirstSql);
2020 if( g.nSql==0 ) fatalError("need at least one SQL script");
2021 blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
2022 &g.nDb, &g.pFirstDb);
2023 if( g.nDb==0 ){
2024 g.pFirstDb = safe_realloc(0, sizeof(Blob));
2025 memset(g.pFirstDb, 0, sizeof(Blob));
2026 g.pFirstDb->id = 1;
2027 g.pFirstDb->seq = 0;
2028 g.nDb = 1;
drhd83e2832015-06-24 14:45:44 +00002029 sqlFuzz = 1;
drhd9972ef2015-05-26 17:57:56 +00002030 }
2031
2032 /* Print the description, if there is one */
drh075201e2021-10-27 12:05:28 +00002033 if( !quietFlag && !bScript ){
drhd9972ef2015-05-26 17:57:56 +00002034 zDbName = azSrcDb[iSrcDb];
drhe683b892016-02-15 18:47:26 +00002035 i = (int)strlen(zDbName) - 1;
drhd9972ef2015-05-26 17:57:56 +00002036 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\n", zDbName, sqlite3_column_text(pStmt,0));
2041 }
2042 sqlite3_finalize(pStmt);
2043 }
drh9a645862015-06-24 12:44:42 +00002044
2045 /* Rebuild the database, if requested */
2046 if( rebuildFlag ){
2047 if( !quietFlag ){
2048 printf("%s: rebuilding... ", zDbName);
2049 fflush(stdout);
2050 }
drhe5da9352019-01-27 01:11:40 +00002051 rebuild_database(db, 0);
drh9a645862015-06-24 12:44:42 +00002052 if( !quietFlag ) printf("done\n");
2053 }
drhd9972ef2015-05-26 17:57:56 +00002054
2055 /* Close the source database. Verify that no SQLite memory allocations are
2056 ** outstanding.
2057 */
2058 sqlite3_close(db);
2059 if( sqlite3_memory_used()>0 ){
2060 fatalError("SQLite has memory in use before the start of testing");
2061 }
drh53e66c32015-07-24 15:49:23 +00002062
2063 /* Limit available memory, if requested */
drh174f8552017-03-20 22:58:27 +00002064 sqlite3_shutdown();
drh39b3bcf2020-03-02 16:31:21 +00002065
drh31999c52019-11-14 17:46:32 +00002066 if( nMemThisDb>0 && nMem==0 ){
2067 if( !nativeMalloc ){
2068 pHeap = realloc(pHeap, nMemThisDb);
2069 if( pHeap==0 ){
2070 fatalError("failed to allocate %d bytes of heap memory", nMem);
2071 }
2072 sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMemThisDb, 128);
2073 }else{
2074 sqlite3_hard_heap_limit64((sqlite3_int64)nMemThisDb);
drh53e66c32015-07-24 15:49:23 +00002075 }
drh31999c52019-11-14 17:46:32 +00002076 }else{
2077 sqlite3_hard_heap_limit64(0);
drh53e66c32015-07-24 15:49:23 +00002078 }
drh174f8552017-03-20 22:58:27 +00002079
2080 /* Disable lookaside with the --native-malloc option */
2081 if( nativeMalloc ){
2082 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
2083 }
drhd9972ef2015-05-26 17:57:56 +00002084
drhbeaf5142016-12-26 00:15:56 +00002085 /* Reset the in-memory virtual filesystem */
drhd9972ef2015-05-26 17:57:56 +00002086 formatVfs();
drhd9972ef2015-05-26 17:57:56 +00002087
2088 /* Run a test using each SQL script against each database.
2089 */
drh075201e2021-10-27 12:05:28 +00002090 if( !verboseFlag && !quietFlag && !bSpinner && !bScript ){
2091 printf("%s:", zDbName);
2092 }
drhd9972ef2015-05-26 17:57:56 +00002093 for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
drh237f41a2020-12-21 12:14:59 +00002094 tmStart = timeOfDay();
drha47e7092019-01-25 04:00:14 +00002095 if( isDbSql(pSql->a, pSql->sz) ){
2096 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d",pSql->id);
drh075201e2021-10-27 12:05:28 +00002097 if( bScript ){
2098 /* No progress output */
2099 }else if( bSpinner ){
drhaa0696e2020-04-07 13:08:56 +00002100 int nTotal =g.nSql;
2101 int idx = pSql->seq;
2102 printf("\r%s: %d/%d ", zDbName, idx, nTotal);
2103 fflush(stdout);
2104 }else if( verboseFlag ){
drha47e7092019-01-25 04:00:14 +00002105 printf("%s\n", g.zTestName);
2106 fflush(stdout);
2107 }else if( !quietFlag ){
2108 static int prevAmt = -1;
2109 int idx = pSql->seq;
2110 int amt = idx*10/(g.nSql);
2111 if( amt!=prevAmt ){
2112 printf(" %d%%", amt*10);
2113 fflush(stdout);
2114 prevAmt = amt;
2115 }
2116 }
drh672f07c2020-10-20 14:40:53 +00002117 if( nSkip>0 ){
2118 nSkip--;
2119 }else{
drh075201e2021-10-27 12:05:28 +00002120 runCombinedDbSqlInput(pSql->a, pSql->sz, iTimeout, bScript, pSql->id);
drh672f07c2020-10-20 14:40:53 +00002121 }
drha47e7092019-01-25 04:00:14 +00002122 nTest++;
drh075201e2021-10-27 12:05:28 +00002123 if( bTimer && !bScript ){
drh237f41a2020-12-21 12:14:59 +00002124 sqlite3_int64 tmEnd = timeOfDay();
2125 printf("%lld %s\n", tmEnd - tmStart, g.zTestName);
2126 }
drha47e7092019-01-25 04:00:14 +00002127 g.zTestName[0] = 0;
drh39b3bcf2020-03-02 16:31:21 +00002128 disableOom();
drha47e7092019-01-25 04:00:14 +00002129 continue;
2130 }
drhd9972ef2015-05-26 17:57:56 +00002131 for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
2132 int openFlags;
2133 const char *zVfs = "inmem";
2134 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
2135 pSql->id, pDb->id);
drh075201e2021-10-27 12:05:28 +00002136 if( bScript ){
2137 /* No progress output */
2138 }else if( bSpinner ){
drhaa0696e2020-04-07 13:08:56 +00002139 int nTotal = g.nDb*g.nSql;
2140 int idx = pSql->seq*g.nDb + pDb->id - 1;
2141 printf("\r%s: %d/%d ", zDbName, idx, nTotal);
2142 fflush(stdout);
2143 }else if( verboseFlag ){
drhd9972ef2015-05-26 17:57:56 +00002144 printf("%s\n", g.zTestName);
2145 fflush(stdout);
2146 }else if( !quietFlag ){
2147 static int prevAmt = -1;
2148 int idx = pSql->seq*g.nDb + pDb->id - 1;
2149 int amt = idx*10/(g.nDb*g.nSql);
2150 if( amt!=prevAmt ){
2151 printf(" %d%%", amt*10);
2152 fflush(stdout);
2153 prevAmt = amt;
2154 }
2155 }
drh672f07c2020-10-20 14:40:53 +00002156 if( nSkip>0 ){
2157 nSkip--;
2158 continue;
2159 }
drh075201e2021-10-27 12:05:28 +00002160 if( bScript ){
2161 char zName[100];
2162 sqlite3_snprintf(sizeof(zName), zName, "db%06d.db",
2163 pDb->id>1 ? pDb->id : pSql->id);
2164 renderDbSqlForCLI(stdout, zName,
2165 pDb->a, pDb->sz, pSql->a, pSql->sz);
2166 continue;
2167 }
drhd9972ef2015-05-26 17:57:56 +00002168 createVFile("main.db", pDb->sz, pDb->a);
drhbeaf5142016-12-26 00:15:56 +00002169 sqlite3_randomness(0,0);
drh362b66f2016-11-14 18:27:41 +00002170 if( ossFuzzThisDb ){
drhea432ba2016-11-11 16:33:47 +00002171#ifndef SQLITE_OSS_FUZZ
drh5ecf9032018-05-08 12:49:53 +00002172 fatalError("--oss-fuzz not supported: recompile"
2173 " with -DSQLITE_OSS_FUZZ");
drhea432ba2016-11-11 16:33:47 +00002174#else
2175 extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t);
2176 LLVMFuzzerTestOneInput((const uint8_t*)pSql->a, (size_t)pSql->sz);
drh78057352015-06-24 23:17:35 +00002177#endif
drhea432ba2016-11-11 16:33:47 +00002178 }else{
2179 openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
2180 if( nativeFlag && pDb->sz==0 ){
2181 openFlags |= SQLITE_OPEN_MEMORY;
2182 zVfs = 0;
2183 }
2184 rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
2185 if( rc ) fatalError("cannot open inmem database");
drhdfcfff62016-12-26 12:25:19 +00002186 sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 100000000);
2187 sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 50);
drhea432ba2016-11-11 16:33:47 +00002188 if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
drh237f41a2020-12-21 12:14:59 +00002189 setAlarm((iTimeout+999)/1000);
drh7ae05492021-03-08 16:13:52 +00002190 /* Enable test functions */
2191 sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, db);
drhea432ba2016-11-11 16:33:47 +00002192#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2193 if( sqlFuzz || vdbeLimitFlag ){
drh5ecf9032018-05-08 12:49:53 +00002194 sqlite3_progress_handler(db, 100000, progressHandler,
2195 &vdbeLimitFlag);
drhea432ba2016-11-11 16:33:47 +00002196 }
2197#endif
drhe6e96b12019-08-02 21:03:24 +00002198#ifdef SQLITE_TESTCTRL_PRNG_SEED
drh2e6d83b2019-08-03 01:39:20 +00002199 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, db);
drhe6e96b12019-08-02 21:03:24 +00002200#endif
drh6e1c45e2019-12-18 13:42:04 +00002201 if( bVdbeDebug ){
2202 sqlite3_exec(db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
2203 }
drhea432ba2016-11-11 16:33:47 +00002204 do{
2205 runSql(db, (char*)pSql->a, runFlags);
2206 }while( timeoutTest );
2207 setAlarm(0);
drh174f8552017-03-20 22:58:27 +00002208 sqlite3_exec(db, "PRAGMA temp_store_directory=''", 0, 0, 0);
drhea432ba2016-11-11 16:33:47 +00002209 sqlite3_close(db);
2210 }
drh174f8552017-03-20 22:58:27 +00002211 if( sqlite3_memory_used()>0 ){
2212 fatalError("memory leak: %lld bytes outstanding",
2213 sqlite3_memory_used());
2214 }
drhd9972ef2015-05-26 17:57:56 +00002215 reformatVfs();
2216 nTest++;
drh237f41a2020-12-21 12:14:59 +00002217 if( bTimer ){
2218 sqlite3_int64 tmEnd = timeOfDay();
2219 printf("%lld %s\n", tmEnd - tmStart, g.zTestName);
2220 }
drhd9972ef2015-05-26 17:57:56 +00002221 g.zTestName[0] = 0;
drh4d6fda72015-05-26 18:58:32 +00002222
2223 /* Simulate an error if the TEST_FAILURE environment variable is "5".
2224 ** This is used to verify that automated test script really do spot
2225 ** errors that occur in this test program.
2226 */
2227 if( zFailCode ){
2228 if( zFailCode[0]=='5' && zFailCode[1]==0 ){
2229 fatalError("simulated failure");
2230 }else if( zFailCode[0]!=0 ){
2231 /* If TEST_FAILURE is something other than 5, just exit the test
2232 ** early */
2233 printf("\nExit early due to TEST_FAILURE being set\n");
2234 iSrcDb = nSrcDb-1;
2235 goto sourcedb_cleanup;
2236 }
2237 }
drhd9972ef2015-05-26 17:57:56 +00002238 }
2239 }
drh075201e2021-10-27 12:05:28 +00002240 if( bScript ){
2241 /* No progress output */
2242 }else if( bSpinner ){
drh292ed6d2021-04-23 12:16:16 +00002243 int nTotal = g.nDb*g.nSql;
2244 printf("\r%s: %d/%d \n", zDbName, nTotal, nTotal);
drhaa0696e2020-04-07 13:08:56 +00002245 }else if( !quietFlag && !verboseFlag ){
drhd9972ef2015-05-26 17:57:56 +00002246 printf(" 100%% - %d tests\n", g.nDb*g.nSql);
2247 }
2248
2249 /* Clean up at the end of processing a single source database
2250 */
drh4d6fda72015-05-26 18:58:32 +00002251 sourcedb_cleanup:
drhd9972ef2015-05-26 17:57:56 +00002252 blobListFree(g.pFirstSql);
2253 blobListFree(g.pFirstDb);
2254 reformatVfs();
2255
2256 } /* End loop over all source databases */
drh3b74d032015-05-25 18:48:19 +00002257
drh075201e2021-10-27 12:05:28 +00002258 if( !quietFlag && !bScript ){
drh3b74d032015-05-25 18:48:19 +00002259 sqlite3_int64 iElapse = timeOfDay() - iBegin;
drhd9972ef2015-05-26 17:57:56 +00002260 printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
2261 "SQLite %s %s\n",
2262 nTest, (int)(iElapse/1000), (int)(iElapse%1000),
drh3b74d032015-05-25 18:48:19 +00002263 sqlite3_libversion(), sqlite3_sourceid());
2264 }
drhf74d35b2015-05-27 18:19:50 +00002265 free(azSrcDb);
drh6653fbe2015-11-13 20:52:49 +00002266 free(pHeap);
drh3b74d032015-05-25 18:48:19 +00002267 return 0;
2268}