blob: f1d2415de22f65714c88927e310f8eb74e6f8edc [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
14** the SQLite library using data from an external fuzzer, such as American
drh3b74d032015-05-25 18:48:19 +000015** Fuzzy Lop (AFL) (http://lcamtuf.coredump.cx/afl/).
16**
17** This program reads content from an SQLite database file with the following
18** schema:
19**
20** CREATE TABLE db(
21** dbid INTEGER PRIMARY KEY, -- database id
22** dbcontent BLOB -- database disk file image
23** );
24** CREATE TABLE xsql(
25** sqlid INTEGER PRIMARY KEY, -- SQL script id
26** sqltext TEXT -- Text of SQL statements to run
27** );
drh00452192015-06-17 18:24:40 +000028** CREATE TABLE IF NOT EXISTS readme(
29** msg TEXT -- Human-readable description of this test collection
30** );
drh3b74d032015-05-25 18:48:19 +000031**
32** For each database file in the DB table, the SQL text in the XSQL table
drh00452192015-06-17 18:24:40 +000033** is run against that database. All README.MSG values are printed prior
34** to the start of the test (unless the --quiet option is used). If the
35** DB table is empty, then all entries in XSQL are run against an empty
36** in-memory database.
37**
38** This program is looking for crashes, assertion faults, and/or memory leaks.
39** No attempt is made to verify the output. The assumption is that either all
40** of the database files or all of the SQL statements are malformed inputs,
41** generated by a fuzzer, that need to be checked to make sure they do not
42** present a security risk.
drh3b74d032015-05-25 18:48:19 +000043**
44** This program also includes some command-line options to help with
drh00452192015-06-17 18:24:40 +000045** creation and maintenance of the source content database. The command
46**
47** ./fuzzcheck database.db --load-sql FILE...
48**
49** Loads all FILE... arguments into the XSQL table. The --load-db option
50** works the same but loads the files into the DB table. The -m option can
51** be used to initialize the README table. The "database.db" file is created
52** if it does not previously exist. Example:
53**
54** ./fuzzcheck new.db --load-sql *.sql
55** ./fuzzcheck new.db --load-db *.db
56** ./fuzzcheck new.db -m 'New test cases'
57**
58** The three commands above will create the "new.db" file and initialize all
59** tables. Then do "./fuzzcheck new.db" to run the tests.
60**
61** DEBUGGING HINTS:
62**
63** If fuzzcheck does crash, it can be run in the debugger and the content
64** of the global variable g.zTextName[] will identify the specific XSQL and
65** DB values that were running when the crash occurred.
drh3b74d032015-05-25 18:48:19 +000066*/
67#include <stdio.h>
68#include <stdlib.h>
69#include <string.h>
70#include <stdarg.h>
71#include <ctype.h>
drha47e7092019-01-25 04:00:14 +000072#include <assert.h>
drh3b74d032015-05-25 18:48:19 +000073#include "sqlite3.h"
drhc56fac72015-10-29 13:48:15 +000074#define ISSPACE(X) isspace((unsigned char)(X))
75#define ISDIGIT(X) isdigit((unsigned char)(X))
76
drh3b74d032015-05-25 18:48:19 +000077
drh94701b02015-06-24 13:25:34 +000078#ifdef __unix__
79# include <signal.h>
80# include <unistd.h>
81#endif
82
drhea432ba2016-11-11 16:33:47 +000083#ifdef SQLITE_OSS_FUZZ
84# include <stddef.h>
mistachkinac8ba262018-03-07 14:42:17 +000085# if !defined(_MSC_VER)
86# include <stdint.h>
87# endif
88#endif
89
90#if defined(_MSC_VER)
91typedef unsigned char uint8_t;
drhea432ba2016-11-11 16:33:47 +000092#endif
93
drh3b74d032015-05-25 18:48:19 +000094/*
95** Files in the virtual file system.
96*/
97typedef struct VFile VFile;
98struct VFile {
99 char *zFilename; /* Filename. NULL for delete-on-close. From malloc() */
100 int sz; /* Size of the file in bytes */
101 int nRef; /* Number of references to this file */
102 unsigned char *a; /* Content of the file. From malloc() */
103};
104typedef struct VHandle VHandle;
105struct VHandle {
106 sqlite3_file base; /* Base class. Must be first */
107 VFile *pVFile; /* The underlying file */
108};
109
110/*
111** The value of a database file template, or of an SQL script
112*/
113typedef struct Blob Blob;
114struct Blob {
115 Blob *pNext; /* Next in a list */
116 int id; /* Id of this Blob */
drhe5c5f2c2015-05-26 00:28:08 +0000117 int seq; /* Sequence number */
drh3b74d032015-05-25 18:48:19 +0000118 int sz; /* Size of this Blob in bytes */
119 unsigned char a[1]; /* Blob content. Extra space allocated as needed. */
120};
121
122/*
123** Maximum number of files in the in-memory virtual filesystem.
124*/
125#define MX_FILE 10
126
127/*
128** Maximum allowed file size
129*/
130#define MX_FILE_SZ 10000000
131
132/*
133** All global variables are gathered into the "g" singleton.
134*/
135static struct GlobalVars {
136 const char *zArgv0; /* Name of program */
137 VFile aFile[MX_FILE]; /* The virtual filesystem */
138 int nDb; /* Number of template databases */
139 Blob *pFirstDb; /* Content of first template database */
140 int nSql; /* Number of SQL scripts */
141 Blob *pFirstSql; /* First SQL script */
drhbeaf5142016-12-26 00:15:56 +0000142 unsigned int uRandom; /* Seed for the SQLite PRNG */
drh3b74d032015-05-25 18:48:19 +0000143 char zTestName[100]; /* Name of current test */
144} g;
145
146/*
147** Print an error message and quit.
148*/
149static void fatalError(const char *zFormat, ...){
150 va_list ap;
151 if( g.zTestName[0] ){
152 fprintf(stderr, "%s (%s): ", g.zArgv0, g.zTestName);
153 }else{
154 fprintf(stderr, "%s: ", g.zArgv0);
155 }
156 va_start(ap, zFormat);
157 vfprintf(stderr, zFormat, ap);
158 va_end(ap);
159 fprintf(stderr, "\n");
160 exit(1);
161}
162
163/*
drh94701b02015-06-24 13:25:34 +0000164** Timeout handler
165*/
166#ifdef __unix__
167static void timeoutHandler(int NotUsed){
168 (void)NotUsed;
169 fatalError("timeout\n");
170}
171#endif
172
173/*
174** Set the an alarm to go off after N seconds. Disable the alarm
175** if N==0
176*/
177static void setAlarm(int N){
178#ifdef __unix__
179 alarm(N);
180#else
181 (void)N;
182#endif
183}
184
drh78057352015-06-24 23:17:35 +0000185#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh94701b02015-06-24 13:25:34 +0000186/*
drhd83e2832015-06-24 14:45:44 +0000187** This an SQL progress handler. After an SQL statement has run for
188** many steps, we want to interrupt it. This guards against infinite
189** loops from recursive common table expressions.
190**
191** *pVdbeLimitFlag is true if the --limit-vdbe command-line option is used.
192** In that case, hitting the progress handler is a fatal error.
193*/
194static int progressHandler(void *pVdbeLimitFlag){
195 if( *(int*)pVdbeLimitFlag ) fatalError("too many VDBE cycles");
196 return 1;
197}
drh78057352015-06-24 23:17:35 +0000198#endif
drhd83e2832015-06-24 14:45:44 +0000199
200/*
drh3b74d032015-05-25 18:48:19 +0000201** Reallocate memory. Show and error and quit if unable.
202*/
203static void *safe_realloc(void *pOld, int szNew){
drhc5412d52016-03-23 17:54:19 +0000204 void *pNew = realloc(pOld, szNew<=0 ? 1 : szNew);
drh3b74d032015-05-25 18:48:19 +0000205 if( pNew==0 ) fatalError("unable to realloc for %d bytes", szNew);
206 return pNew;
207}
208
209/*
210** Initialize the virtual file system.
211*/
212static void formatVfs(void){
213 int i;
214 for(i=0; i<MX_FILE; i++){
215 g.aFile[i].sz = -1;
216 g.aFile[i].zFilename = 0;
217 g.aFile[i].a = 0;
218 g.aFile[i].nRef = 0;
219 }
220}
221
222
223/*
224** Erase all information in the virtual file system.
225*/
226static void reformatVfs(void){
227 int i;
228 for(i=0; i<MX_FILE; i++){
229 if( g.aFile[i].sz<0 ) continue;
230 if( g.aFile[i].zFilename ){
231 free(g.aFile[i].zFilename);
232 g.aFile[i].zFilename = 0;
233 }
234 if( g.aFile[i].nRef>0 ){
235 fatalError("file %d still open. nRef=%d", i, g.aFile[i].nRef);
236 }
237 g.aFile[i].sz = -1;
238 free(g.aFile[i].a);
239 g.aFile[i].a = 0;
240 g.aFile[i].nRef = 0;
241 }
242}
243
244/*
245** Find a VFile by name
246*/
247static VFile *findVFile(const char *zName){
248 int i;
drha9542b12015-05-25 19:35:42 +0000249 if( zName==0 ) return 0;
drh3b74d032015-05-25 18:48:19 +0000250 for(i=0; i<MX_FILE; i++){
251 if( g.aFile[i].zFilename==0 ) continue;
252 if( strcmp(g.aFile[i].zFilename, zName)==0 ) return &g.aFile[i];
253 }
254 return 0;
255}
256
257/*
258** Find a VFile by name. Create it if it does not already exist and
259** initialize it to the size and content given.
260**
261** Return NULL only if the filesystem is full.
262*/
263static VFile *createVFile(const char *zName, int sz, unsigned char *pData){
264 VFile *pNew = findVFile(zName);
265 int i;
266 if( pNew ) return pNew;
267 for(i=0; i<MX_FILE && g.aFile[i].sz>=0; i++){}
268 if( i>=MX_FILE ) return 0;
269 pNew = &g.aFile[i];
drha9542b12015-05-25 19:35:42 +0000270 if( zName ){
drhe683b892016-02-15 18:47:26 +0000271 int nName = (int)strlen(zName)+1;
272 pNew->zFilename = safe_realloc(0, nName);
273 memcpy(pNew->zFilename, zName, nName);
drha9542b12015-05-25 19:35:42 +0000274 }else{
275 pNew->zFilename = 0;
276 }
drh3b74d032015-05-25 18:48:19 +0000277 pNew->nRef = 0;
278 pNew->sz = sz;
279 pNew->a = safe_realloc(0, sz);
280 if( sz>0 ) memcpy(pNew->a, pData, sz);
281 return pNew;
282}
283
284
285/*
286** Implementation of the "readfile(X)" SQL function. The entire content
287** of the file named X is read and returned as a BLOB. NULL is returned
288** if the file does not exist or is unreadable.
289*/
290static void readfileFunc(
291 sqlite3_context *context,
292 int argc,
293 sqlite3_value **argv
294){
295 const char *zName;
296 FILE *in;
297 long nIn;
298 void *pBuf;
299
300 zName = (const char*)sqlite3_value_text(argv[0]);
301 if( zName==0 ) return;
302 in = fopen(zName, "rb");
303 if( in==0 ) return;
304 fseek(in, 0, SEEK_END);
305 nIn = ftell(in);
306 rewind(in);
307 pBuf = sqlite3_malloc64( nIn );
308 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
309 sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
310 }else{
311 sqlite3_free(pBuf);
312 }
313 fclose(in);
314}
315
316/*
drh40e0e0d2015-09-22 18:51:17 +0000317** Implementation of the "writefile(X,Y)" SQL function. The argument Y
318** is written into file X. The number of bytes written is returned. Or
319** NULL is returned if something goes wrong, such as being unable to open
320** file X for writing.
321*/
322static void writefileFunc(
323 sqlite3_context *context,
324 int argc,
325 sqlite3_value **argv
326){
327 FILE *out;
328 const char *z;
329 sqlite3_int64 rc;
330 const char *zFile;
331
332 (void)argc;
333 zFile = (const char*)sqlite3_value_text(argv[0]);
334 if( zFile==0 ) return;
335 out = fopen(zFile, "wb");
336 if( out==0 ) return;
337 z = (const char*)sqlite3_value_blob(argv[1]);
338 if( z==0 ){
339 rc = 0;
340 }else{
341 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
342 }
343 fclose(out);
344 sqlite3_result_int64(context, rc);
345}
346
347
348/*
drh3b74d032015-05-25 18:48:19 +0000349** Load a list of Blob objects from the database
350*/
351static void blobListLoadFromDb(
352 sqlite3 *db, /* Read from this database */
353 const char *zSql, /* Query used to extract the blobs */
drha9542b12015-05-25 19:35:42 +0000354 int onlyId, /* Only load where id is this value */
drh3b74d032015-05-25 18:48:19 +0000355 int *pN, /* OUT: Write number of blobs loaded here */
356 Blob **ppList /* OUT: Write the head of the blob list here */
357){
358 Blob head;
359 Blob *p;
360 sqlite3_stmt *pStmt;
361 int n = 0;
362 int rc;
drha9542b12015-05-25 19:35:42 +0000363 char *z2;
drh3b74d032015-05-25 18:48:19 +0000364
drha9542b12015-05-25 19:35:42 +0000365 if( onlyId>0 ){
366 z2 = sqlite3_mprintf("%s WHERE rowid=%d", zSql, onlyId);
367 }else{
368 z2 = sqlite3_mprintf("%s", zSql);
369 }
370 rc = sqlite3_prepare_v2(db, z2, -1, &pStmt, 0);
371 sqlite3_free(z2);
drh3b74d032015-05-25 18:48:19 +0000372 if( rc ) fatalError("%s", sqlite3_errmsg(db));
373 head.pNext = 0;
374 p = &head;
375 while( SQLITE_ROW==sqlite3_step(pStmt) ){
376 int sz = sqlite3_column_bytes(pStmt, 1);
377 Blob *pNew = safe_realloc(0, sizeof(*pNew)+sz );
378 pNew->id = sqlite3_column_int(pStmt, 0);
379 pNew->sz = sz;
drhe5c5f2c2015-05-26 00:28:08 +0000380 pNew->seq = n++;
drh3b74d032015-05-25 18:48:19 +0000381 pNew->pNext = 0;
382 memcpy(pNew->a, sqlite3_column_blob(pStmt,1), sz);
383 pNew->a[sz] = 0;
384 p->pNext = pNew;
385 p = pNew;
drh3b74d032015-05-25 18:48:19 +0000386 }
387 sqlite3_finalize(pStmt);
388 *pN = n;
389 *ppList = head.pNext;
390}
391
392/*
393** Free a list of Blob objects
394*/
395static void blobListFree(Blob *p){
396 Blob *pNext;
397 while( p ){
398 pNext = p->pNext;
399 free(p);
400 p = pNext;
401 }
402}
403
drh3b74d032015-05-25 18:48:19 +0000404/* Return the current wall-clock time */
405static sqlite3_int64 timeOfDay(void){
406 static sqlite3_vfs *clockVfs = 0;
407 sqlite3_int64 t;
drh8055a3e2018-11-21 14:27:34 +0000408 if( clockVfs==0 ){
409 clockVfs = sqlite3_vfs_find(0);
410 if( clockVfs==0 ) return 0;
411 }
drh3b74d032015-05-25 18:48:19 +0000412 if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
413 clockVfs->xCurrentTimeInt64(clockVfs, &t);
414 }else{
415 double r;
416 clockVfs->xCurrentTime(clockVfs, &r);
417 t = (sqlite3_int64)(r*86400000.0);
418 }
419 return t;
420}
421
drha47e7092019-01-25 04:00:14 +0000422/***************************************************************************
423** Code to process combined database+SQL scripts generated by the
424** dbsqlfuzz fuzzer.
425*/
426
427/* An instance of the following object is passed by pointer as the
428** client data to various callbacks.
429*/
430typedef struct FuzzCtx {
431 sqlite3 *db; /* The database connection */
432 sqlite3_int64 iCutoffTime; /* Stop processing at this time. */
433 sqlite3_int64 iLastCb; /* Time recorded for previous progress callback */
434 sqlite3_int64 mxInterval; /* Longest interval between two progress calls */
435 unsigned nCb; /* Number of progress callbacks */
436 unsigned mxCb; /* Maximum number of progress callbacks allowed */
437 unsigned execCnt; /* Number of calls to the sqlite3_exec callback */
438 int timeoutHit; /* True when reaching a timeout */
439} FuzzCtx;
440
441/* Verbosity level for the dbsqlfuzz test runner */
442static int eVerbosity = 0;
443
444/* True to activate PRAGMA vdbe_debug=on */
445static int bVdbeDebug = 0;
446
447/* Timeout for each fuzzing attempt, in milliseconds */
drhed457032019-01-25 17:51:06 +0000448static int giTimeout = 10000; /* Defaults to 10 seconds */
drha47e7092019-01-25 04:00:14 +0000449
450/* Maximum number of progress handler callbacks */
451static unsigned int mxProgressCb = 2000;
452
453/* Maximum string length in SQLite */
454static int lengthLimit = 1000000;
455
drh31999c52019-11-14 17:46:32 +0000456/* Limit on the amount of heap memory that can be used */
457static sqlite3_int64 heapLimit = 1000000000;
458
drha47e7092019-01-25 04:00:14 +0000459/* Maximum byte-code program length in SQLite */
460static int vdbeOpLimit = 25000;
461
462/* Maximum size of the in-memory database */
463static sqlite3_int64 maxDbSize = 104857600;
464
465/*
466** Translate a single byte of Hex into an integer.
467** This routine only works if h really is a valid hexadecimal
468** character: 0..9a..fA..F
469*/
drhed457032019-01-25 17:51:06 +0000470static unsigned char hexToInt(unsigned int h){
drha47e7092019-01-25 04:00:14 +0000471#ifdef SQLITE_EBCDIC
472 h += 9*(1&~(h>>4)); /* EBCDIC */
473#else
474 h += 9*(1&(h>>6)); /* ASCII */
475#endif
476 return h & 0xf;
477}
478
479/*
480** The first character of buffer zIn[0..nIn-1] is a '['. This routine
481** checked to see if the buffer holds "[NNNN]" or "[+NNNN]" and if it
482** does it makes corresponding changes to the *pK value and *pI value
483** and returns true. If the input buffer does not match the patterns,
484** no changes are made to either *pK or *pI and this routine returns false.
485*/
486static int isOffset(
487 const unsigned char *zIn, /* Text input */
488 int nIn, /* Bytes of input */
489 unsigned int *pK, /* half-byte cursor to adjust */
490 unsigned int *pI /* Input index to adjust */
491){
492 int i;
493 unsigned int k = 0;
494 unsigned char c;
495 for(i=1; i<nIn && (c = zIn[i])!=']'; i++){
496 if( !isxdigit(c) ) return 0;
497 k = k*16 + hexToInt(c);
498 }
499 if( i==nIn ) return 0;
500 *pK = 2*k;
501 *pI += i;
502 return 1;
503}
504
505/*
506** Decode the text starting at zIn into a binary database file.
507** The maximum length of zIn is nIn bytes. Compute the binary database
508** file contain in space obtained from sqlite3_malloc().
509**
510** Return the number of bytes of zIn consumed. Or return -1 if there
511** is an error. One potential error is that the recipe specifies a
512** database file larger than MX_FILE_SZ bytes.
513**
514** Abort on an OOM.
515*/
516static int decodeDatabase(
517 const unsigned char *zIn, /* Input text to be decoded */
518 int nIn, /* Bytes of input text */
519 unsigned char **paDecode, /* OUT: decoded database file */
520 int *pnDecode /* OUT: Size of decoded database */
521){
522 unsigned char *a; /* Database under construction */
523 int mx = 0; /* Current size of the database */
524 sqlite3_uint64 nAlloc = 4096; /* Space allocated in a[] */
525 unsigned int i; /* Next byte of zIn[] to read */
526 unsigned int j; /* Temporary integer */
527 unsigned int k; /* half-byte cursor index for output */
528 unsigned int n; /* Number of bytes of input */
529 unsigned char b = 0;
530 if( nIn<4 ) return -1;
531 n = (unsigned int)nIn;
drhed457032019-01-25 17:51:06 +0000532 a = sqlite3_malloc64( nAlloc );
drha47e7092019-01-25 04:00:14 +0000533 if( a==0 ){
534 fprintf(stderr, "Out of memory!\n");
535 exit(1);
536 }
mistachkin065f3bf2019-03-20 05:45:03 +0000537 memset(a, 0, (size_t)nAlloc);
drha47e7092019-01-25 04:00:14 +0000538 for(i=k=0; i<n; i++){
drhaf638922019-02-07 00:17:36 +0000539 unsigned char c = (unsigned char)zIn[i];
drha47e7092019-01-25 04:00:14 +0000540 if( isxdigit(c) ){
541 k++;
542 if( k & 1 ){
543 b = hexToInt(c)*16;
544 }else{
545 b += hexToInt(c);
546 j = k/2 - 1;
547 if( j>=nAlloc ){
548 sqlite3_uint64 newSize;
549 if( nAlloc==MX_FILE_SZ || j>=MX_FILE_SZ ){
550 if( eVerbosity ){
551 fprintf(stderr, "Input database too big: max %d bytes\n",
552 MX_FILE_SZ);
553 }
554 sqlite3_free(a);
555 return -1;
556 }
557 newSize = nAlloc*2;
558 if( newSize<=j ){
559 newSize = (j+4096)&~4095;
560 }
561 if( newSize>MX_FILE_SZ ){
562 if( j>=MX_FILE_SZ ){
563 sqlite3_free(a);
564 return -1;
565 }
566 newSize = MX_FILE_SZ;
567 }
drhed457032019-01-25 17:51:06 +0000568 a = sqlite3_realloc64( a, newSize );
drha47e7092019-01-25 04:00:14 +0000569 if( a==0 ){
570 fprintf(stderr, "Out of memory!\n");
571 exit(1);
572 }
573 assert( newSize > nAlloc );
mistachkin065f3bf2019-03-20 05:45:03 +0000574 memset(a+nAlloc, 0, (size_t)(newSize - nAlloc));
drha47e7092019-01-25 04:00:14 +0000575 nAlloc = newSize;
576 }
577 if( j>=(unsigned)mx ){
578 mx = (j + 4095)&~4095;
579 if( mx>MX_FILE_SZ ) mx = MX_FILE_SZ;
580 }
581 assert( j<nAlloc );
582 a[j] = b;
583 }
584 }else if( zIn[i]=='[' && i<n-3 && isOffset(zIn+i, nIn-i, &k, &i) ){
585 continue;
586 }else if( zIn[i]=='\n' && i<n-4 && memcmp(zIn+i,"\n--\n",4)==0 ){
587 i += 4;
588 break;
589 }
590 }
591 *pnDecode = mx;
592 *paDecode = a;
593 return i;
594}
595
596/*
597** Progress handler callback.
598**
599** The argument is the cutoff-time after which all processing should
600** stop. So return non-zero if the cut-off time is exceeded.
601*/
602static int progress_handler(void *pClientData) {
603 FuzzCtx *p = (FuzzCtx*)pClientData;
604 sqlite3_int64 iNow = timeOfDay();
605 int rc = iNow>=p->iCutoffTime;
606 sqlite3_int64 iDiff = iNow - p->iLastCb;
607 if( iDiff > p->mxInterval ) p->mxInterval = iDiff;
608 p->nCb++;
609 if( rc==0 && p->mxCb>0 && p->mxCb<=p->nCb ) rc = 1;
drhdf216592019-01-25 04:43:26 +0000610 if( rc && !p->timeoutHit && eVerbosity>=2 ){
drha47e7092019-01-25 04:00:14 +0000611 printf("Timeout on progress callback %d\n", p->nCb);
612 fflush(stdout);
613 p->timeoutHit = 1;
614 }
615 return rc;
616}
617
618/*
619** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and
620** "PRAGMA parser_trace" since they can dramatically increase the
621** amount of output without actually testing anything useful.
622**
623** Also block ATTACH and DETACH
624*/
625static int block_troublesome_sql(
626 void *Notused,
627 int eCode,
628 const char *zArg1,
629 const char *zArg2,
630 const char *zArg3,
631 const char *zArg4
632){
633 (void)Notused;
634 (void)zArg2;
635 (void)zArg3;
636 (void)zArg4;
637 if( eCode==SQLITE_PRAGMA ){
638 if( sqlite3_strnicmp("vdbe_", zArg1, 5)==0
639 || sqlite3_stricmp("parser_trace", zArg1)==0
640 || sqlite3_stricmp("temp_store_directory", zArg1)==0
641 ){
642 return SQLITE_DENY;
643 }
644 }else if( (eCode==SQLITE_ATTACH || eCode==SQLITE_DETACH)
645 && zArg1 && zArg1[0] ){
646 return SQLITE_DENY;
647 }
648 return SQLITE_OK;
649}
650
651/*
652** Run the SQL text
653*/
654static int runDbSql(sqlite3 *db, const char *zSql){
655 int rc;
656 sqlite3_stmt *pStmt;
drhaf638922019-02-07 00:17:36 +0000657 while( isspace(zSql[0]&0x7f) ) zSql++;
drha47e7092019-01-25 04:00:14 +0000658 if( zSql[0]==0 ) return SQLITE_OK;
drhdf216592019-01-25 04:43:26 +0000659 if( eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +0000660 printf("RUNNING-SQL: [%s]\n", zSql);
661 fflush(stdout);
662 }
663 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
664 if( rc==SQLITE_OK ){
665 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
drhdf216592019-01-25 04:43:26 +0000666 if( eVerbosity>=5 ){
drha47e7092019-01-25 04:00:14 +0000667 int j;
668 for(j=0; j<sqlite3_column_count(pStmt); j++){
669 if( j ) printf(",");
670 switch( sqlite3_column_type(pStmt, j) ){
671 case SQLITE_NULL: {
672 printf("NULL");
673 break;
674 }
675 case SQLITE_INTEGER:
676 case SQLITE_FLOAT: {
677 printf("%s", sqlite3_column_text(pStmt, j));
678 break;
679 }
680 case SQLITE_BLOB: {
681 int n = sqlite3_column_bytes(pStmt, j);
682 int i;
683 const unsigned char *a;
684 a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
685 printf("x'");
686 for(i=0; i<n; i++){
687 printf("%02x", a[i]);
688 }
689 printf("'");
690 break;
691 }
692 case SQLITE_TEXT: {
693 int n = sqlite3_column_bytes(pStmt, j);
694 int i;
695 const unsigned char *a;
696 a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
697 printf("'");
698 for(i=0; i<n; i++){
699 if( a[i]=='\'' ){
700 printf("''");
701 }else{
702 putchar(a[i]);
703 }
704 }
705 printf("'");
706 break;
707 }
708 } /* End switch() */
709 } /* End for() */
710 printf("\n");
711 fflush(stdout);
drhdf216592019-01-25 04:43:26 +0000712 } /* End if( eVerbosity>=5 ) */
drha47e7092019-01-25 04:00:14 +0000713 } /* End while( SQLITE_ROW */
drhdf216592019-01-25 04:43:26 +0000714 if( rc!=SQLITE_DONE && eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +0000715 printf("SQL-ERROR: (%d) %s\n", rc, sqlite3_errmsg(db));
716 fflush(stdout);
717 }
drhdf216592019-01-25 04:43:26 +0000718 }else if( eVerbosity>=4 ){
drha47e7092019-01-25 04:00:14 +0000719 printf("SQL-ERROR (%d): %s\n", rc, sqlite3_errmsg(db));
720 fflush(stdout);
721 } /* End if( SQLITE_OK ) */
722 return sqlite3_finalize(pStmt);
723}
724
725/* Invoke this routine to run a single test case */
726int runCombinedDbSqlInput(const uint8_t *aData, size_t nByte){
727 int rc; /* SQLite API return value */
728 int iSql; /* Index in aData[] of start of SQL */
729 unsigned char *aDb = 0; /* Decoded database content */
730 int nDb = 0; /* Size of the decoded database */
731 int i; /* Loop counter */
732 int j; /* Start of current SQL statement */
733 char *zSql = 0; /* SQL text to run */
734 int nSql; /* Bytes of SQL text */
735 FuzzCtx cx; /* Fuzzing context */
736
737 if( nByte<10 ) return 0;
738 if( sqlite3_initialize() ) return 0;
739 if( sqlite3_memory_used()!=0 ){
740 int nAlloc = 0;
741 int nNotUsed = 0;
742 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
743 fprintf(stderr,"Memory leak in mutator: %lld bytes in %d allocations\n",
744 sqlite3_memory_used(), nAlloc);
745 exit(1);
746 }
747 memset(&cx, 0, sizeof(cx));
748 iSql = decodeDatabase((unsigned char*)aData, (int)nByte, &aDb, &nDb);
749 if( iSql<0 ) return 0;
drhed457032019-01-25 17:51:06 +0000750 nSql = (int)(nByte - iSql);
drhdf216592019-01-25 04:43:26 +0000751 if( eVerbosity>=3 ){
drha47e7092019-01-25 04:00:14 +0000752 printf(
753 "****** %d-byte input, %d-byte database, %d-byte script "
754 "******\n", (int)nByte, nDb, nSql);
755 fflush(stdout);
756 }
757 rc = sqlite3_open(0, &cx.db);
758 if( rc ) return 1;
759 if( bVdbeDebug ){
760 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
761 }
762
763 /* Invoke the progress handler frequently to check to see if we
764 ** are taking too long. The progress handler will return true
drhed457032019-01-25 17:51:06 +0000765 ** (which will block further processing) if more than giTimeout seconds have
drha47e7092019-01-25 04:00:14 +0000766 ** elapsed since the start of the test.
767 */
768 cx.iLastCb = timeOfDay();
drhed457032019-01-25 17:51:06 +0000769 cx.iCutoffTime = cx.iLastCb + giTimeout; /* Now + giTimeout seconds */
drha47e7092019-01-25 04:00:14 +0000770 cx.mxCb = mxProgressCb;
771#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
772 sqlite3_progress_handler(cx.db, 10, progress_handler, (void*)&cx);
773#endif
774
775 /* Set a limit on the maximum size of a prepared statement, and the
776 ** maximum length of a string or blob */
777 if( vdbeOpLimit>0 ){
778 sqlite3_limit(cx.db, SQLITE_LIMIT_VDBE_OP, vdbeOpLimit);
779 }
780 if( lengthLimit>0 ){
781 sqlite3_limit(cx.db, SQLITE_LIMIT_LENGTH, lengthLimit);
782 }
drh31999c52019-11-14 17:46:32 +0000783 sqlite3_hard_heap_limit64(heapLimit);
drha47e7092019-01-25 04:00:14 +0000784
785 if( nDb>=20 && aDb[18]==2 && aDb[19]==2 ){
786 aDb[18] = aDb[19] = 1;
787 }
788 rc = sqlite3_deserialize(cx.db, "main", aDb, nDb, nDb,
789 SQLITE_DESERIALIZE_RESIZEABLE |
790 SQLITE_DESERIALIZE_FREEONCLOSE);
791 if( rc ){
792 fprintf(stderr, "sqlite3_deserialize() failed with %d\n", rc);
793 goto testrun_finished;
794 }
795 if( maxDbSize>0 ){
796 sqlite3_int64 x = maxDbSize;
797 sqlite3_file_control(cx.db, "main", SQLITE_FCNTL_SIZE_LIMIT, &x);
798 }
799
drh725a9c72019-01-25 13:03:38 +0000800 /* For high debugging levels, turn on debug mode */
801 if( eVerbosity>=5 ){
802 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON;", 0, 0, 0);
803 }
804
drha47e7092019-01-25 04:00:14 +0000805 /* Block debug pragmas and ATTACH/DETACH. But wait until after
806 ** deserialize to do this because deserialize depends on ATTACH */
807 sqlite3_set_authorizer(cx.db, block_troublesome_sql, 0);
808
809 /* Consistent PRNG seed */
810 sqlite3_randomness(0,0);
811
812 zSql = sqlite3_malloc( nSql + 1 );
813 if( zSql==0 ){
814 fprintf(stderr, "Out of memory!\n");
815 }else{
816 memcpy(zSql, aData+iSql, nSql);
817 zSql[nSql] = 0;
818 for(i=j=0; zSql[i]; i++){
819 if( zSql[i]==';' ){
820 char cSaved = zSql[i+1];
821 zSql[i+1] = 0;
822 if( sqlite3_complete(zSql+j) ){
823 rc = runDbSql(cx.db, zSql+j);
824 j = i+1;
825 }
826 zSql[i+1] = cSaved;
827 if( rc==SQLITE_INTERRUPT || progress_handler(&cx) ){
828 goto testrun_finished;
829 }
830 }
831 }
832 if( j<i ){
833 runDbSql(cx.db, zSql+j);
834 }
835 }
836testrun_finished:
837 sqlite3_free(zSql);
838 rc = sqlite3_close(cx.db);
839 if( rc!=SQLITE_OK ){
840 fprintf(stdout, "sqlite3_close() returns %d\n", rc);
841 }
drhdf216592019-01-25 04:43:26 +0000842 if( eVerbosity>=2 ){
drha47e7092019-01-25 04:00:14 +0000843 fprintf(stdout, "Peak memory usages: %f MB\n",
844 sqlite3_memory_highwater(1) / 1000000.0);
845 }
846 if( sqlite3_memory_used()!=0 ){
847 int nAlloc = 0;
848 int nNotUsed = 0;
849 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
850 fprintf(stderr,"Memory leak: %lld bytes in %d allocations\n",
851 sqlite3_memory_used(), nAlloc);
852 exit(1);
853 }
854 return 0;
855}
856
857/*
858** END of the dbsqlfuzz code
859***************************************************************************/
860
861/* Look at a SQL text and try to determine if it begins with a database
862** description, such as would be found in a dbsqlfuzz test case. Return
863** true if this does appear to be a dbsqlfuzz test case and false otherwise.
864*/
865static int isDbSql(unsigned char *a, int n){
drhdf216592019-01-25 04:43:26 +0000866 unsigned char buf[12];
867 int i;
drha47e7092019-01-25 04:00:14 +0000868 if( n>4 && memcmp(a,"\n--\n",4)==0 ) return 1;
869 while( n>0 && isspace(a[0]) ){ a++; n--; }
drhdf216592019-01-25 04:43:26 +0000870 for(i=0; n>0 && i<8; n--, a++){
871 if( isxdigit(a[0]) ) buf[i++] = a[0];
872 }
873 if( i==8 && memcmp(buf,"53514c69",8)==0 ) return 1;
drha47e7092019-01-25 04:00:14 +0000874 return 0;
875}
876
drhe5da9352019-01-27 01:11:40 +0000877/* Implementation of the isdbsql(TEXT) SQL function.
878*/
879static void isDbSqlFunc(
880 sqlite3_context *context,
881 int argc,
882 sqlite3_value **argv
883){
884 int n = sqlite3_value_bytes(argv[0]);
885 unsigned char *a = (unsigned char*)sqlite3_value_blob(argv[0]);
886 sqlite3_result_int(context, a!=0 && n>0 && isDbSql(a,n));
887}
drha47e7092019-01-25 04:00:14 +0000888
drh3b74d032015-05-25 18:48:19 +0000889/* Methods for the VHandle object
890*/
891static int inmemClose(sqlite3_file *pFile){
892 VHandle *p = (VHandle*)pFile;
893 VFile *pVFile = p->pVFile;
894 pVFile->nRef--;
895 if( pVFile->nRef==0 && pVFile->zFilename==0 ){
896 pVFile->sz = -1;
897 free(pVFile->a);
898 pVFile->a = 0;
899 }
900 return SQLITE_OK;
901}
902static int inmemRead(
903 sqlite3_file *pFile, /* Read from this open file */
904 void *pData, /* Store content in this buffer */
905 int iAmt, /* Bytes of content */
906 sqlite3_int64 iOfst /* Start reading here */
907){
908 VHandle *pHandle = (VHandle*)pFile;
909 VFile *pVFile = pHandle->pVFile;
910 if( iOfst<0 || iOfst>=pVFile->sz ){
911 memset(pData, 0, iAmt);
912 return SQLITE_IOERR_SHORT_READ;
913 }
914 if( iOfst+iAmt>pVFile->sz ){
915 memset(pData, 0, iAmt);
drh1573dc32015-05-25 22:29:26 +0000916 iAmt = (int)(pVFile->sz - iOfst);
drhe45985b2018-12-14 02:29:56 +0000917 memcpy(pData, pVFile->a + iOfst, iAmt);
drh3b74d032015-05-25 18:48:19 +0000918 return SQLITE_IOERR_SHORT_READ;
919 }
drhaca7ea12015-05-25 23:14:37 +0000920 memcpy(pData, pVFile->a + iOfst, iAmt);
drh3b74d032015-05-25 18:48:19 +0000921 return SQLITE_OK;
922}
923static int inmemWrite(
924 sqlite3_file *pFile, /* Write to this file */
925 const void *pData, /* Content to write */
926 int iAmt, /* bytes to write */
927 sqlite3_int64 iOfst /* Start writing here */
928){
929 VHandle *pHandle = (VHandle*)pFile;
930 VFile *pVFile = pHandle->pVFile;
931 if( iOfst+iAmt > pVFile->sz ){
drha9542b12015-05-25 19:35:42 +0000932 if( iOfst+iAmt >= MX_FILE_SZ ){
933 return SQLITE_FULL;
934 }
drh1573dc32015-05-25 22:29:26 +0000935 pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt));
drh908aced2015-05-26 16:12:45 +0000936 if( iOfst > pVFile->sz ){
937 memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz));
938 }
drh1573dc32015-05-25 22:29:26 +0000939 pVFile->sz = (int)(iOfst + iAmt);
drh3b74d032015-05-25 18:48:19 +0000940 }
941 memcpy(pVFile->a + iOfst, pData, iAmt);
942 return SQLITE_OK;
943}
944static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){
945 VHandle *pHandle = (VHandle*)pFile;
946 VFile *pVFile = pHandle->pVFile;
drh1573dc32015-05-25 22:29:26 +0000947 if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize;
drh3b74d032015-05-25 18:48:19 +0000948 return SQLITE_OK;
949}
950static int inmemSync(sqlite3_file *pFile, int flags){
951 return SQLITE_OK;
952}
953static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){
954 *pSize = ((VHandle*)pFile)->pVFile->sz;
955 return SQLITE_OK;
956}
957static int inmemLock(sqlite3_file *pFile, int type){
958 return SQLITE_OK;
959}
960static int inmemUnlock(sqlite3_file *pFile, int type){
961 return SQLITE_OK;
962}
963static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){
964 *pOut = 0;
965 return SQLITE_OK;
966}
967static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){
968 return SQLITE_NOTFOUND;
969}
970static int inmemSectorSize(sqlite3_file *pFile){
971 return 512;
972}
973static int inmemDeviceCharacteristics(sqlite3_file *pFile){
974 return
975 SQLITE_IOCAP_SAFE_APPEND |
976 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
977 SQLITE_IOCAP_POWERSAFE_OVERWRITE;
978}
979
980
981/* Method table for VHandle
982*/
983static sqlite3_io_methods VHandleMethods = {
984 /* iVersion */ 1,
985 /* xClose */ inmemClose,
986 /* xRead */ inmemRead,
987 /* xWrite */ inmemWrite,
988 /* xTruncate */ inmemTruncate,
989 /* xSync */ inmemSync,
990 /* xFileSize */ inmemFileSize,
991 /* xLock */ inmemLock,
992 /* xUnlock */ inmemUnlock,
993 /* xCheck... */ inmemCheckReservedLock,
994 /* xFileCtrl */ inmemFileControl,
995 /* xSectorSz */ inmemSectorSize,
996 /* xDevchar */ inmemDeviceCharacteristics,
997 /* xShmMap */ 0,
998 /* xShmLock */ 0,
999 /* xShmBarrier */ 0,
1000 /* xShmUnmap */ 0,
1001 /* xFetch */ 0,
1002 /* xUnfetch */ 0
1003};
1004
1005/*
1006** Open a new file in the inmem VFS. All files are anonymous and are
1007** delete-on-close.
1008*/
1009static int inmemOpen(
1010 sqlite3_vfs *pVfs,
1011 const char *zFilename,
1012 sqlite3_file *pFile,
1013 int openFlags,
1014 int *pOutFlags
1015){
1016 VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)"");
1017 VHandle *pHandle = (VHandle*)pFile;
drha9542b12015-05-25 19:35:42 +00001018 if( pVFile==0 ){
1019 return SQLITE_FULL;
1020 }
drh3b74d032015-05-25 18:48:19 +00001021 pHandle->pVFile = pVFile;
1022 pVFile->nRef++;
1023 pFile->pMethods = &VHandleMethods;
1024 if( pOutFlags ) *pOutFlags = openFlags;
1025 return SQLITE_OK;
1026}
1027
1028/*
1029** Delete a file by name
1030*/
1031static int inmemDelete(
1032 sqlite3_vfs *pVfs,
1033 const char *zFilename,
1034 int syncdir
1035){
1036 VFile *pVFile = findVFile(zFilename);
1037 if( pVFile==0 ) return SQLITE_OK;
1038 if( pVFile->nRef==0 ){
1039 free(pVFile->zFilename);
1040 pVFile->zFilename = 0;
1041 pVFile->sz = -1;
1042 free(pVFile->a);
1043 pVFile->a = 0;
1044 return SQLITE_OK;
1045 }
1046 return SQLITE_IOERR_DELETE;
1047}
1048
1049/* Check for the existance of a file
1050*/
1051static int inmemAccess(
1052 sqlite3_vfs *pVfs,
1053 const char *zFilename,
1054 int flags,
1055 int *pResOut
1056){
1057 VFile *pVFile = findVFile(zFilename);
1058 *pResOut = pVFile!=0;
1059 return SQLITE_OK;
1060}
1061
1062/* Get the canonical pathname for a file
1063*/
1064static int inmemFullPathname(
1065 sqlite3_vfs *pVfs,
1066 const char *zFilename,
1067 int nOut,
1068 char *zOut
1069){
1070 sqlite3_snprintf(nOut, zOut, "%s", zFilename);
1071 return SQLITE_OK;
1072}
1073
drhbeaf5142016-12-26 00:15:56 +00001074/* Always use the same random see, for repeatability.
1075*/
1076static int inmemRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
1077 memset(zBuf, 0, nBuf);
1078 memcpy(zBuf, &g.uRandom, nBuf<sizeof(g.uRandom) ? nBuf : sizeof(g.uRandom));
1079 return nBuf;
1080}
1081
drh3b74d032015-05-25 18:48:19 +00001082/*
1083** Register the VFS that reads from the g.aFile[] set of files.
1084*/
drhbeaf5142016-12-26 00:15:56 +00001085static void inmemVfsRegister(int makeDefault){
drh3b74d032015-05-25 18:48:19 +00001086 static sqlite3_vfs inmemVfs;
1087 sqlite3_vfs *pDefault = sqlite3_vfs_find(0);
drh5337dac2015-11-25 15:15:03 +00001088 inmemVfs.iVersion = 3;
drh3b74d032015-05-25 18:48:19 +00001089 inmemVfs.szOsFile = sizeof(VHandle);
1090 inmemVfs.mxPathname = 200;
1091 inmemVfs.zName = "inmem";
1092 inmemVfs.xOpen = inmemOpen;
1093 inmemVfs.xDelete = inmemDelete;
1094 inmemVfs.xAccess = inmemAccess;
1095 inmemVfs.xFullPathname = inmemFullPathname;
drhbeaf5142016-12-26 00:15:56 +00001096 inmemVfs.xRandomness = inmemRandomness;
drh3b74d032015-05-25 18:48:19 +00001097 inmemVfs.xSleep = pDefault->xSleep;
drh5337dac2015-11-25 15:15:03 +00001098 inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64;
drhbeaf5142016-12-26 00:15:56 +00001099 sqlite3_vfs_register(&inmemVfs, makeDefault);
drh3b74d032015-05-25 18:48:19 +00001100};
1101
drh3b74d032015-05-25 18:48:19 +00001102/*
drhe5c5f2c2015-05-26 00:28:08 +00001103** Allowed values for the runFlags parameter to runSql()
1104*/
1105#define SQL_TRACE 0x0001 /* Print each SQL statement as it is prepared */
1106#define SQL_OUTPUT 0x0002 /* Show the SQL output */
1107
1108/*
drh3b74d032015-05-25 18:48:19 +00001109** Run multiple commands of SQL. Similar to sqlite3_exec(), but does not
1110** stop if an error is encountered.
1111*/
drhe5c5f2c2015-05-26 00:28:08 +00001112static void runSql(sqlite3 *db, const char *zSql, unsigned runFlags){
drh3b74d032015-05-25 18:48:19 +00001113 const char *zMore;
1114 sqlite3_stmt *pStmt;
1115
1116 while( zSql && zSql[0] ){
1117 zMore = 0;
1118 pStmt = 0;
1119 sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore);
drh4ab31472015-05-25 22:17:06 +00001120 if( zMore==zSql ) break;
drhe5c5f2c2015-05-26 00:28:08 +00001121 if( runFlags & SQL_TRACE ){
drh4ab31472015-05-25 22:17:06 +00001122 const char *z = zSql;
1123 int n;
drhc56fac72015-10-29 13:48:15 +00001124 while( z<zMore && ISSPACE(z[0]) ) z++;
drh4ab31472015-05-25 22:17:06 +00001125 n = (int)(zMore - z);
drhc56fac72015-10-29 13:48:15 +00001126 while( n>0 && ISSPACE(z[n-1]) ) n--;
drh4ab31472015-05-25 22:17:06 +00001127 if( n==0 ) break;
1128 if( pStmt==0 ){
1129 printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db));
1130 }else{
1131 printf("TRACE: %.*s\n", n, z);
1132 }
1133 }
drh3b74d032015-05-25 18:48:19 +00001134 zSql = zMore;
1135 if( pStmt ){
drhe5c5f2c2015-05-26 00:28:08 +00001136 if( (runFlags & SQL_OUTPUT)==0 ){
1137 while( SQLITE_ROW==sqlite3_step(pStmt) ){}
1138 }else{
1139 int nCol = -1;
1140 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1141 int i;
1142 if( nCol<0 ){
1143 nCol = sqlite3_column_count(pStmt);
1144 }else if( nCol>0 ){
1145 printf("--------------------------------------------\n");
1146 }
1147 for(i=0; i<nCol; i++){
1148 int eType = sqlite3_column_type(pStmt,i);
1149 printf("%s = ", sqlite3_column_name(pStmt,i));
1150 switch( eType ){
1151 case SQLITE_NULL: {
1152 printf("NULL\n");
1153 break;
1154 }
1155 case SQLITE_INTEGER: {
1156 printf("INT %s\n", sqlite3_column_text(pStmt,i));
1157 break;
1158 }
1159 case SQLITE_FLOAT: {
1160 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i));
1161 break;
1162 }
1163 case SQLITE_TEXT: {
1164 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i));
1165 break;
1166 }
1167 case SQLITE_BLOB: {
1168 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i));
1169 break;
1170 }
1171 }
1172 }
1173 }
1174 }
drh3b74d032015-05-25 18:48:19 +00001175 sqlite3_finalize(pStmt);
drh3b74d032015-05-25 18:48:19 +00001176 }
1177 }
1178}
1179
drha9542b12015-05-25 19:35:42 +00001180/*
drh9a645862015-06-24 12:44:42 +00001181** Rebuild the database file.
1182**
1183** (1) Remove duplicate entries
1184** (2) Put all entries in order
1185** (3) Vacuum
1186*/
drhe5da9352019-01-27 01:11:40 +00001187static void rebuild_database(sqlite3 *db, int dbSqlOnly){
drh9a645862015-06-24 12:44:42 +00001188 int rc;
drhe5da9352019-01-27 01:11:40 +00001189 char *zSql;
1190 zSql = sqlite3_mprintf(
drh9a645862015-06-24 12:44:42 +00001191 "BEGIN;\n"
1192 "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n"
1193 "DELETE FROM db;\n"
drh5ecf9032018-05-08 12:49:53 +00001194 "INSERT INTO db(dbid, dbcontent) "
1195 " SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n"
drh9a645862015-06-24 12:44:42 +00001196 "DROP TABLE dbx;\n"
drhe5da9352019-01-27 01:11:40 +00001197 "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql %s;\n"
drh9a645862015-06-24 12:44:42 +00001198 "DELETE FROM xsql;\n"
drh5ecf9032018-05-08 12:49:53 +00001199 "INSERT INTO xsql(sqlid,sqltext) "
1200 " SELECT NULL, sqltext FROM sx ORDER BY 2;\n"
drh9a645862015-06-24 12:44:42 +00001201 "DROP TABLE sx;\n"
1202 "COMMIT;\n"
1203 "PRAGMA page_size=1024;\n"
drhe5da9352019-01-27 01:11:40 +00001204 "VACUUM;\n",
1205 dbSqlOnly ? " WHERE isdbsql(sqltext)" : ""
1206 );
1207 rc = sqlite3_exec(db, zSql, 0, 0, 0);
1208 sqlite3_free(zSql);
drh9a645862015-06-24 12:44:42 +00001209 if( rc ) fatalError("cannot rebuild: %s", sqlite3_errmsg(db));
1210}
1211
1212/*
drh53e66c32015-07-24 15:49:23 +00001213** Return the value of a hexadecimal digit. Return -1 if the input
1214** is not a hex digit.
1215*/
1216static int hexDigitValue(char c){
1217 if( c>='0' && c<='9' ) return c - '0';
1218 if( c>='a' && c<='f' ) return c - 'a' + 10;
1219 if( c>='A' && c<='F' ) return c - 'A' + 10;
1220 return -1;
1221}
1222
1223/*
1224** Interpret zArg as an integer value, possibly with suffixes.
1225*/
1226static int integerValue(const char *zArg){
1227 sqlite3_int64 v = 0;
1228 static const struct { char *zSuffix; int iMult; } aMult[] = {
1229 { "KiB", 1024 },
1230 { "MiB", 1024*1024 },
1231 { "GiB", 1024*1024*1024 },
1232 { "KB", 1000 },
1233 { "MB", 1000000 },
1234 { "GB", 1000000000 },
1235 { "K", 1000 },
1236 { "M", 1000000 },
1237 { "G", 1000000000 },
1238 };
1239 int i;
1240 int isNeg = 0;
1241 if( zArg[0]=='-' ){
1242 isNeg = 1;
1243 zArg++;
1244 }else if( zArg[0]=='+' ){
1245 zArg++;
1246 }
1247 if( zArg[0]=='0' && zArg[1]=='x' ){
1248 int x;
1249 zArg += 2;
1250 while( (x = hexDigitValue(zArg[0]))>=0 ){
1251 v = (v<<4) + x;
1252 zArg++;
1253 }
1254 }else{
drhc56fac72015-10-29 13:48:15 +00001255 while( ISDIGIT(zArg[0]) ){
drh53e66c32015-07-24 15:49:23 +00001256 v = v*10 + zArg[0] - '0';
1257 zArg++;
1258 }
1259 }
1260 for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
1261 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1262 v *= aMult[i].iMult;
1263 break;
1264 }
1265 }
1266 if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648");
1267 return (int)(isNeg? -v : v);
1268}
1269
1270/*
drh725a9c72019-01-25 13:03:38 +00001271** Return the number of "v" characters in a string. Return 0 if there
1272** are any characters in the string other than "v".
1273*/
1274static int numberOfVChar(const char *z){
1275 int N = 0;
1276 while( z[0] && z[0]=='v' ){
1277 z++;
1278 N++;
1279 }
1280 return z[0]==0 ? N : 0;
1281}
1282
1283/*
drha9542b12015-05-25 19:35:42 +00001284** Print sketchy documentation for this utility program
1285*/
1286static void showHelp(void){
1287 printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0);
1288 printf(
1289"Read databases and SQL scripts from SOURCE-DB and execute each script against\n"
1290"each database, checking for crashes and memory leaks.\n"
1291"Options:\n"
drha36e01a2016-08-03 13:40:54 +00001292" --cell-size-check Set the PRAGMA cell_size_check=ON\n"
1293" --dbid N Use only the database where dbid=N\n"
1294" --export-db DIR Write databases to files(s) in DIR. Works with --dbid\n"
1295" --export-sql DIR Write SQL to file(s) in DIR. Also works with --sqlid\n"
1296" --help Show this help text\n"
drh5180d682018-08-06 01:39:31 +00001297" --info Show information about SOURCE-DB w/o running tests\n"
drha36e01a2016-08-03 13:40:54 +00001298" --limit-mem N Limit memory used by test SQLite instance to N bytes\n"
1299" --limit-vdbe Panic if any test runs for more than 100,000 cycles\n"
drh5ecf9032018-05-08 12:49:53 +00001300" --load-sql ARGS... Load SQL scripts fron files into SOURCE-DB\n"
drha36e01a2016-08-03 13:40:54 +00001301" --load-db ARGS... Load template databases from files into SOURCE_DB\n"
drhe5da9352019-01-27 01:11:40 +00001302" --load-dbsql ARGS.. Load dbsqlfuzz outputs into the xsql table\n"
drha36e01a2016-08-03 13:40:54 +00001303" -m TEXT Add a description to the database\n"
1304" --native-vfs Use the native VFS for initially empty database files\n"
drh174f8552017-03-20 22:58:27 +00001305" --native-malloc Turn off MEMSYS3/5 and Lookaside\n"
drhea432ba2016-11-11 16:33:47 +00001306" --oss-fuzz Enable OSS-FUZZ testing\n"
drhbeaf5142016-12-26 00:15:56 +00001307" --prng-seed N Seed value for the PRGN inside of SQLite\n"
drh5180d682018-08-06 01:39:31 +00001308" -q|--quiet Reduced output\n"
drha36e01a2016-08-03 13:40:54 +00001309" --rebuild Rebuild and vacuum the database file\n"
1310" --result-trace Show the results of each SQL command\n"
1311" --sqlid N Use only SQL where sqlid=N\n"
1312" --timeout N Abort if any single test needs more than N seconds\n"
1313" -v|--verbose Increased output. Repeat for more output.\n"
drha9542b12015-05-25 19:35:42 +00001314 );
1315}
1316
drh3b74d032015-05-25 18:48:19 +00001317int main(int argc, char **argv){
1318 sqlite3_int64 iBegin; /* Start time of this program */
drh3b74d032015-05-25 18:48:19 +00001319 int quietFlag = 0; /* True if --quiet or -q */
1320 int verboseFlag = 0; /* True if --verbose or -v */
1321 char *zInsSql = 0; /* SQL statement for --load-db or --load-sql */
drh5ecf9032018-05-08 12:49:53 +00001322 int iFirstInsArg = 0; /* First argv[] for --load-db or --load-sql */
drh3b74d032015-05-25 18:48:19 +00001323 sqlite3 *db = 0; /* The open database connection */
drhd9972ef2015-05-26 17:57:56 +00001324 sqlite3_stmt *pStmt; /* A prepared statement */
drh3b74d032015-05-25 18:48:19 +00001325 int rc; /* Result code from SQLite interface calls */
1326 Blob *pSql; /* For looping over SQL scripts */
1327 Blob *pDb; /* For looping over template databases */
1328 int i; /* Loop index for the argv[] loop */
drhe5da9352019-01-27 01:11:40 +00001329 int dbSqlOnly = 0; /* Only use scripts that are dbsqlfuzz */
drha9542b12015-05-25 19:35:42 +00001330 int onlySqlid = -1; /* --sqlid */
1331 int onlyDbid = -1; /* --dbid */
drh15b31282015-05-25 21:59:05 +00001332 int nativeFlag = 0; /* --native-vfs */
drh9a645862015-06-24 12:44:42 +00001333 int rebuildFlag = 0; /* --rebuild */
drhd83e2832015-06-24 14:45:44 +00001334 int vdbeLimitFlag = 0; /* --limit-vdbe */
drh5180d682018-08-06 01:39:31 +00001335 int infoFlag = 0; /* --info */
drh94701b02015-06-24 13:25:34 +00001336 int timeoutTest = 0; /* undocumented --timeout-test flag */
drhe5c5f2c2015-05-26 00:28:08 +00001337 int runFlags = 0; /* Flags sent to runSql() */
drhd9972ef2015-05-26 17:57:56 +00001338 char *zMsg = 0; /* Add this message */
1339 int nSrcDb = 0; /* Number of source databases */
1340 char **azSrcDb = 0; /* Array of source database names */
1341 int iSrcDb; /* Loop over all source databases */
1342 int nTest = 0; /* Total number of tests performed */
1343 char *zDbName = ""; /* Appreviated name of a source database */
drh5ecf9032018-05-08 12:49:53 +00001344 const char *zFailCode = 0; /* Value of the TEST_FAILURE env variable */
drh1421d982015-05-27 03:46:18 +00001345 int cellSzCkFlag = 0; /* --cell-size-check */
drh5ecf9032018-05-08 12:49:53 +00001346 int sqlFuzz = 0; /* True for SQL fuzz. False for DB fuzz */
drhd4ddcbc2015-06-25 02:25:28 +00001347 int iTimeout = 120; /* Default 120-second timeout */
drh31999c52019-11-14 17:46:32 +00001348 int nMem = 0; /* Memory limit override */
drh362b66f2016-11-14 18:27:41 +00001349 int nMemThisDb = 0; /* Memory limit set by the CONFIG table */
drh40e0e0d2015-09-22 18:51:17 +00001350 char *zExpDb = 0; /* Write Databases to files in this directory */
1351 char *zExpSql = 0; /* Write SQL to files in this directory */
drh6653fbe2015-11-13 20:52:49 +00001352 void *pHeap = 0; /* Heap for use by SQLite */
drhea432ba2016-11-11 16:33:47 +00001353 int ossFuzz = 0; /* enable OSS-FUZZ testing */
drh362b66f2016-11-14 18:27:41 +00001354 int ossFuzzThisDb = 0; /* ossFuzz value for this particular database */
drh174f8552017-03-20 22:58:27 +00001355 int nativeMalloc = 0; /* Turn off MEMSYS3/5 and lookaside if true */
drhbeaf5142016-12-26 00:15:56 +00001356 sqlite3_vfs *pDfltVfs; /* The default VFS */
drhf2cf4122018-05-08 13:03:31 +00001357 int openFlags4Data; /* Flags for sqlite3_open_v2() */
drh725a9c72019-01-25 13:03:38 +00001358 int nV; /* How much to increase verbosity with -vvvv */
drh3b74d032015-05-25 18:48:19 +00001359
drh8055a3e2018-11-21 14:27:34 +00001360 sqlite3_initialize();
drh3b74d032015-05-25 18:48:19 +00001361 iBegin = timeOfDay();
drh94701b02015-06-24 13:25:34 +00001362#ifdef __unix__
1363 signal(SIGALRM, timeoutHandler);
1364#endif
drh3b74d032015-05-25 18:48:19 +00001365 g.zArgv0 = argv[0];
drhf2cf4122018-05-08 13:03:31 +00001366 openFlags4Data = SQLITE_OPEN_READONLY;
drh4d6fda72015-05-26 18:58:32 +00001367 zFailCode = getenv("TEST_FAILURE");
drhbeaf5142016-12-26 00:15:56 +00001368 pDfltVfs = sqlite3_vfs_find(0);
1369 inmemVfsRegister(1);
drh3b74d032015-05-25 18:48:19 +00001370 for(i=1; i<argc; i++){
1371 const char *z = argv[i];
1372 if( z[0]=='-' ){
1373 z++;
1374 if( z[0]=='-' ) z++;
drh1421d982015-05-27 03:46:18 +00001375 if( strcmp(z,"cell-size-check")==0 ){
1376 cellSzCkFlag = 1;
1377 }else
drha9542b12015-05-25 19:35:42 +00001378 if( strcmp(z,"dbid")==0 ){
1379 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
drh53e66c32015-07-24 15:49:23 +00001380 onlyDbid = integerValue(argv[++i]);
drha9542b12015-05-25 19:35:42 +00001381 }else
drh40e0e0d2015-09-22 18:51:17 +00001382 if( strcmp(z,"export-db")==0 ){
1383 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1384 zExpDb = argv[++i];
1385 }else
drhe5da9352019-01-27 01:11:40 +00001386 if( strcmp(z,"export-sql")==0 || strcmp(z,"export-dbsql")==0 ){
drh40e0e0d2015-09-22 18:51:17 +00001387 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1388 zExpSql = argv[++i];
1389 }else
drh3b74d032015-05-25 18:48:19 +00001390 if( strcmp(z,"help")==0 ){
1391 showHelp();
1392 return 0;
1393 }else
drh5180d682018-08-06 01:39:31 +00001394 if( strcmp(z,"info")==0 ){
1395 infoFlag = 1;
1396 }else
drh53e66c32015-07-24 15:49:23 +00001397 if( strcmp(z,"limit-mem")==0 ){
1398 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1399 nMem = integerValue(argv[++i]);
1400 }else
drhd83e2832015-06-24 14:45:44 +00001401 if( strcmp(z,"limit-vdbe")==0 ){
1402 vdbeLimitFlag = 1;
1403 }else
drh3b74d032015-05-25 18:48:19 +00001404 if( strcmp(z,"load-sql")==0 ){
drh5ecf9032018-05-08 12:49:53 +00001405 zInsSql = "INSERT INTO xsql(sqltext)VALUES(CAST(readfile(?1) AS text))";
drh3b74d032015-05-25 18:48:19 +00001406 iFirstInsArg = i+1;
drhf2cf4122018-05-08 13:03:31 +00001407 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
drh3b74d032015-05-25 18:48:19 +00001408 break;
1409 }else
1410 if( strcmp(z,"load-db")==0 ){
1411 zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
1412 iFirstInsArg = i+1;
drhf2cf4122018-05-08 13:03:31 +00001413 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
drh3b74d032015-05-25 18:48:19 +00001414 break;
1415 }else
drhe5da9352019-01-27 01:11:40 +00001416 if( strcmp(z,"load-dbsql")==0 ){
1417 zInsSql = "INSERT INTO xsql(sqltext)VALUES(CAST(readfile(?1) AS text))";
1418 iFirstInsArg = i+1;
1419 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1420 dbSqlOnly = 1;
1421 break;
1422 }else
drhd9972ef2015-05-26 17:57:56 +00001423 if( strcmp(z,"m")==0 ){
1424 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1425 zMsg = argv[++i];
drhf2cf4122018-05-08 13:03:31 +00001426 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
drhd9972ef2015-05-26 17:57:56 +00001427 }else
drh174f8552017-03-20 22:58:27 +00001428 if( strcmp(z,"native-malloc")==0 ){
1429 nativeMalloc = 1;
1430 }else
drh15b31282015-05-25 21:59:05 +00001431 if( strcmp(z,"native-vfs")==0 ){
1432 nativeFlag = 1;
1433 }else
drhea432ba2016-11-11 16:33:47 +00001434 if( strcmp(z,"oss-fuzz")==0 ){
1435 ossFuzz = 1;
1436 }else
drhbeaf5142016-12-26 00:15:56 +00001437 if( strcmp(z,"prng-seed")==0 ){
1438 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1439 g.uRandom = atoi(argv[++i]);
1440 }else
drh3b74d032015-05-25 18:48:19 +00001441 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
1442 quietFlag = 1;
1443 verboseFlag = 0;
drha47e7092019-01-25 04:00:14 +00001444 eVerbosity = 0;
drh3b74d032015-05-25 18:48:19 +00001445 }else
drh9a645862015-06-24 12:44:42 +00001446 if( strcmp(z,"rebuild")==0 ){
1447 rebuildFlag = 1;
drhf2cf4122018-05-08 13:03:31 +00001448 openFlags4Data = SQLITE_OPEN_READWRITE;
drh9a645862015-06-24 12:44:42 +00001449 }else
drhe5c5f2c2015-05-26 00:28:08 +00001450 if( strcmp(z,"result-trace")==0 ){
1451 runFlags |= SQL_OUTPUT;
1452 }else
drha9542b12015-05-25 19:35:42 +00001453 if( strcmp(z,"sqlid")==0 ){
1454 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
drh53e66c32015-07-24 15:49:23 +00001455 onlySqlid = integerValue(argv[++i]);
drha9542b12015-05-25 19:35:42 +00001456 }else
drh92298632015-06-24 23:44:30 +00001457 if( strcmp(z,"timeout")==0 ){
1458 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
drh53e66c32015-07-24 15:49:23 +00001459 iTimeout = integerValue(argv[++i]);
drh92298632015-06-24 23:44:30 +00001460 }else
drh94701b02015-06-24 13:25:34 +00001461 if( strcmp(z,"timeout-test")==0 ){
1462 timeoutTest = 1;
1463#ifndef __unix__
1464 fatalError("timeout is not available on non-unix systems");
1465#endif
1466 }else
drh725a9c72019-01-25 13:03:38 +00001467 if( strcmp(z,"verbose")==0 ){
drh3b74d032015-05-25 18:48:19 +00001468 quietFlag = 0;
drh4c9d2282016-02-18 14:03:15 +00001469 verboseFlag++;
drha47e7092019-01-25 04:00:14 +00001470 eVerbosity++;
drh4c9d2282016-02-18 14:03:15 +00001471 if( verboseFlag>1 ) runFlags |= SQL_TRACE;
drh3b74d032015-05-25 18:48:19 +00001472 }else
drh725a9c72019-01-25 13:03:38 +00001473 if( (nV = numberOfVChar(z))>=1 ){
1474 quietFlag = 0;
1475 verboseFlag += nV;
1476 eVerbosity += nV;
1477 if( verboseFlag>1 ) runFlags |= SQL_TRACE;
1478 }else
drha47e7092019-01-25 04:00:14 +00001479 if( strcmp(z,"version")==0 ){
1480 int ii;
drhed457032019-01-25 17:51:06 +00001481 const char *zz;
drha47e7092019-01-25 04:00:14 +00001482 printf("SQLite %s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drhed457032019-01-25 17:51:06 +00001483 for(ii=0; (zz = sqlite3_compileoption_get(ii))!=0; ii++){
1484 printf("%s\n", zz);
drha47e7092019-01-25 04:00:14 +00001485 }
1486 return 0;
1487 }else
drh3b74d032015-05-25 18:48:19 +00001488 {
1489 fatalError("unknown option: %s", argv[i]);
1490 }
1491 }else{
drhd9972ef2015-05-26 17:57:56 +00001492 nSrcDb++;
1493 azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
1494 azSrcDb[nSrcDb-1] = argv[i];
drh3b74d032015-05-25 18:48:19 +00001495 }
1496 }
drhd9972ef2015-05-26 17:57:56 +00001497 if( nSrcDb==0 ) fatalError("no source database specified");
1498 if( nSrcDb>1 ){
1499 if( zMsg ){
1500 fatalError("cannot change the description of more than one database");
drh3b74d032015-05-25 18:48:19 +00001501 }
drhd9972ef2015-05-26 17:57:56 +00001502 if( zInsSql ){
1503 fatalError("cannot import into more than one database");
1504 }
drh3b74d032015-05-25 18:48:19 +00001505 }
1506
drhd9972ef2015-05-26 17:57:56 +00001507 /* Process each source database separately */
1508 for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
drhbeaf5142016-12-26 00:15:56 +00001509 rc = sqlite3_open_v2(azSrcDb[iSrcDb], &db,
drhf2cf4122018-05-08 13:03:31 +00001510 openFlags4Data, pDfltVfs->zName);
drhd9972ef2015-05-26 17:57:56 +00001511 if( rc ){
1512 fatalError("cannot open source database %s - %s",
1513 azSrcDb[iSrcDb], sqlite3_errmsg(db));
1514 }
drh5180d682018-08-06 01:39:31 +00001515
1516 /* Print the description, if there is one */
1517 if( infoFlag ){
1518 int n;
1519 zDbName = azSrcDb[iSrcDb];
1520 i = (int)strlen(zDbName) - 1;
1521 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
1522 zDbName += i;
1523 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
1524 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
1525 printf("%s: %s", zDbName, sqlite3_column_text(pStmt,0));
1526 }else{
1527 printf("%s: (empty \"readme\")", zDbName);
1528 }
1529 sqlite3_finalize(pStmt);
1530 sqlite3_prepare_v2(db, "SELECT count(*) FROM db", -1, &pStmt, 0);
1531 if( pStmt
1532 && sqlite3_step(pStmt)==SQLITE_ROW
1533 && (n = sqlite3_column_int(pStmt,0))>0
1534 ){
1535 printf(" - %d DBs", n);
1536 }
1537 sqlite3_finalize(pStmt);
1538 sqlite3_prepare_v2(db, "SELECT count(*) FROM xsql", -1, &pStmt, 0);
1539 if( pStmt
1540 && sqlite3_step(pStmt)==SQLITE_ROW
1541 && (n = sqlite3_column_int(pStmt,0))>0
1542 ){
1543 printf(" - %d scripts", n);
1544 }
1545 sqlite3_finalize(pStmt);
1546 printf("\n");
1547 sqlite3_close(db);
1548 continue;
1549 }
1550
drh9a645862015-06-24 12:44:42 +00001551 rc = sqlite3_exec(db,
drhd9972ef2015-05-26 17:57:56 +00001552 "CREATE TABLE IF NOT EXISTS db(\n"
1553 " dbid INTEGER PRIMARY KEY, -- database id\n"
1554 " dbcontent BLOB -- database disk file image\n"
1555 ");\n"
1556 "CREATE TABLE IF NOT EXISTS xsql(\n"
1557 " sqlid INTEGER PRIMARY KEY, -- SQL script id\n"
1558 " sqltext TEXT -- Text of SQL statements to run\n"
1559 ");"
1560 "CREATE TABLE IF NOT EXISTS readme(\n"
1561 " msg TEXT -- Human-readable description of this file\n"
1562 ");", 0, 0, 0);
1563 if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
1564 if( zMsg ){
1565 char *zSql;
1566 zSql = sqlite3_mprintf(
1567 "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
1568 rc = sqlite3_exec(db, zSql, 0, 0, 0);
1569 sqlite3_free(zSql);
1570 if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
1571 }
drh362b66f2016-11-14 18:27:41 +00001572 ossFuzzThisDb = ossFuzz;
1573
1574 /* If the CONFIG(name,value) table exists, read db-specific settings
1575 ** from that table */
1576 if( sqlite3_table_column_metadata(db,0,"config",0,0,0,0,0,0)==SQLITE_OK ){
drh5ecf9032018-05-08 12:49:53 +00001577 rc = sqlite3_prepare_v2(db, "SELECT name, value FROM config",
1578 -1, &pStmt, 0);
drh362b66f2016-11-14 18:27:41 +00001579 if( rc ) fatalError("cannot prepare query of CONFIG table: %s",
1580 sqlite3_errmsg(db));
1581 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1582 const char *zName = (const char *)sqlite3_column_text(pStmt,0);
1583 if( zName==0 ) continue;
1584 if( strcmp(zName, "oss-fuzz")==0 ){
1585 ossFuzzThisDb = sqlite3_column_int(pStmt,1);
1586 if( verboseFlag ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb);
1587 }
drh31999c52019-11-14 17:46:32 +00001588 if( strcmp(zName, "limit-mem")==0 ){
drh362b66f2016-11-14 18:27:41 +00001589 nMemThisDb = sqlite3_column_int(pStmt,1);
1590 if( verboseFlag ) printf("Config: limit-mem=%d\n", nMemThisDb);
drh362b66f2016-11-14 18:27:41 +00001591 }
1592 }
1593 sqlite3_finalize(pStmt);
1594 }
1595
drhd9972ef2015-05-26 17:57:56 +00001596 if( zInsSql ){
1597 sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
1598 readfileFunc, 0, 0);
drhe5da9352019-01-27 01:11:40 +00001599 sqlite3_create_function(db, "isdbsql", 1, SQLITE_UTF8, 0,
1600 isDbSqlFunc, 0, 0);
drhd9972ef2015-05-26 17:57:56 +00001601 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
1602 if( rc ) fatalError("cannot prepare statement [%s]: %s",
1603 zInsSql, sqlite3_errmsg(db));
1604 rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
1605 if( rc ) fatalError("cannot start a transaction");
1606 for(i=iFirstInsArg; i<argc; i++){
1607 sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
1608 sqlite3_step(pStmt);
1609 rc = sqlite3_reset(pStmt);
1610 if( rc ) fatalError("insert failed for %s", argv[i]);
drh3b74d032015-05-25 18:48:19 +00001611 }
drhd9972ef2015-05-26 17:57:56 +00001612 sqlite3_finalize(pStmt);
1613 rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
drh5ecf9032018-05-08 12:49:53 +00001614 if( rc ) fatalError("cannot commit the transaction: %s",
1615 sqlite3_errmsg(db));
drhe5da9352019-01-27 01:11:40 +00001616 rebuild_database(db, dbSqlOnly);
drh3b74d032015-05-25 18:48:19 +00001617 sqlite3_close(db);
drhd9972ef2015-05-26 17:57:56 +00001618 return 0;
drh3b74d032015-05-25 18:48:19 +00001619 }
drh16f05822017-03-20 20:42:21 +00001620 rc = sqlite3_exec(db, "PRAGMA query_only=1;", 0, 0, 0);
1621 if( rc ) fatalError("cannot set database to query-only");
drh40e0e0d2015-09-22 18:51:17 +00001622 if( zExpDb!=0 || zExpSql!=0 ){
1623 sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
1624 writefileFunc, 0, 0);
1625 if( zExpDb!=0 ){
1626 const char *zExDb =
1627 "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent),"
1628 " dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)"
1629 " FROM db WHERE ?2<0 OR dbid=?2;";
1630 rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0);
1631 if( rc ) fatalError("cannot prepare statement [%s]: %s",
1632 zExDb, sqlite3_errmsg(db));
1633 sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb),
1634 SQLITE_STATIC, SQLITE_UTF8);
1635 sqlite3_bind_int(pStmt, 2, onlyDbid);
1636 while( sqlite3_step(pStmt)==SQLITE_ROW ){
1637 printf("write db-%d (%d bytes) into %s\n",
1638 sqlite3_column_int(pStmt,1),
1639 sqlite3_column_int(pStmt,3),
1640 sqlite3_column_text(pStmt,2));
1641 }
1642 sqlite3_finalize(pStmt);
1643 }
1644 if( zExpSql!=0 ){
1645 const char *zExSql =
1646 "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext),"
1647 " sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)"
1648 " FROM xsql WHERE ?2<0 OR sqlid=?2;";
1649 rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0);
1650 if( rc ) fatalError("cannot prepare statement [%s]: %s",
1651 zExSql, sqlite3_errmsg(db));
1652 sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql),
1653 SQLITE_STATIC, SQLITE_UTF8);
1654 sqlite3_bind_int(pStmt, 2, onlySqlid);
1655 while( sqlite3_step(pStmt)==SQLITE_ROW ){
1656 printf("write sql-%d (%d bytes) into %s\n",
1657 sqlite3_column_int(pStmt,1),
1658 sqlite3_column_int(pStmt,3),
1659 sqlite3_column_text(pStmt,2));
1660 }
1661 sqlite3_finalize(pStmt);
1662 }
1663 sqlite3_close(db);
1664 return 0;
1665 }
drhd9972ef2015-05-26 17:57:56 +00001666
1667 /* Load all SQL script content and all initial database images from the
1668 ** source db
1669 */
1670 blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
1671 &g.nSql, &g.pFirstSql);
1672 if( g.nSql==0 ) fatalError("need at least one SQL script");
1673 blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
1674 &g.nDb, &g.pFirstDb);
1675 if( g.nDb==0 ){
1676 g.pFirstDb = safe_realloc(0, sizeof(Blob));
1677 memset(g.pFirstDb, 0, sizeof(Blob));
1678 g.pFirstDb->id = 1;
1679 g.pFirstDb->seq = 0;
1680 g.nDb = 1;
drhd83e2832015-06-24 14:45:44 +00001681 sqlFuzz = 1;
drhd9972ef2015-05-26 17:57:56 +00001682 }
1683
1684 /* Print the description, if there is one */
1685 if( !quietFlag ){
drhd9972ef2015-05-26 17:57:56 +00001686 zDbName = azSrcDb[iSrcDb];
drhe683b892016-02-15 18:47:26 +00001687 i = (int)strlen(zDbName) - 1;
drhd9972ef2015-05-26 17:57:56 +00001688 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
1689 zDbName += i;
1690 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
1691 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
1692 printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
1693 }
1694 sqlite3_finalize(pStmt);
1695 }
drh9a645862015-06-24 12:44:42 +00001696
1697 /* Rebuild the database, if requested */
1698 if( rebuildFlag ){
1699 if( !quietFlag ){
1700 printf("%s: rebuilding... ", zDbName);
1701 fflush(stdout);
1702 }
drhe5da9352019-01-27 01:11:40 +00001703 rebuild_database(db, 0);
drh9a645862015-06-24 12:44:42 +00001704 if( !quietFlag ) printf("done\n");
1705 }
drhd9972ef2015-05-26 17:57:56 +00001706
1707 /* Close the source database. Verify that no SQLite memory allocations are
1708 ** outstanding.
1709 */
1710 sqlite3_close(db);
1711 if( sqlite3_memory_used()>0 ){
1712 fatalError("SQLite has memory in use before the start of testing");
1713 }
drh53e66c32015-07-24 15:49:23 +00001714
1715 /* Limit available memory, if requested */
drh174f8552017-03-20 22:58:27 +00001716 sqlite3_shutdown();
drh31999c52019-11-14 17:46:32 +00001717 if( nMemThisDb>0 && nMem==0 ){
1718 if( !nativeMalloc ){
1719 pHeap = realloc(pHeap, nMemThisDb);
1720 if( pHeap==0 ){
1721 fatalError("failed to allocate %d bytes of heap memory", nMem);
1722 }
1723 sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMemThisDb, 128);
1724 }else{
1725 sqlite3_hard_heap_limit64((sqlite3_int64)nMemThisDb);
drh53e66c32015-07-24 15:49:23 +00001726 }
drh31999c52019-11-14 17:46:32 +00001727 }else{
1728 sqlite3_hard_heap_limit64(0);
drh53e66c32015-07-24 15:49:23 +00001729 }
drh174f8552017-03-20 22:58:27 +00001730
1731 /* Disable lookaside with the --native-malloc option */
1732 if( nativeMalloc ){
1733 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
1734 }
drhd9972ef2015-05-26 17:57:56 +00001735
drhbeaf5142016-12-26 00:15:56 +00001736 /* Reset the in-memory virtual filesystem */
drhd9972ef2015-05-26 17:57:56 +00001737 formatVfs();
drhd9972ef2015-05-26 17:57:56 +00001738
1739 /* Run a test using each SQL script against each database.
1740 */
1741 if( !verboseFlag && !quietFlag ) printf("%s:", zDbName);
1742 for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
drha47e7092019-01-25 04:00:14 +00001743 if( isDbSql(pSql->a, pSql->sz) ){
1744 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d",pSql->id);
1745 if( verboseFlag ){
1746 printf("%s\n", g.zTestName);
1747 fflush(stdout);
1748 }else if( !quietFlag ){
1749 static int prevAmt = -1;
1750 int idx = pSql->seq;
1751 int amt = idx*10/(g.nSql);
1752 if( amt!=prevAmt ){
1753 printf(" %d%%", amt*10);
1754 fflush(stdout);
1755 prevAmt = amt;
1756 }
1757 }
1758 runCombinedDbSqlInput(pSql->a, pSql->sz);
1759 nTest++;
1760 g.zTestName[0] = 0;
1761 continue;
1762 }
drhd9972ef2015-05-26 17:57:56 +00001763 for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
1764 int openFlags;
1765 const char *zVfs = "inmem";
1766 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
1767 pSql->id, pDb->id);
1768 if( verboseFlag ){
1769 printf("%s\n", g.zTestName);
1770 fflush(stdout);
1771 }else if( !quietFlag ){
1772 static int prevAmt = -1;
1773 int idx = pSql->seq*g.nDb + pDb->id - 1;
1774 int amt = idx*10/(g.nDb*g.nSql);
1775 if( amt!=prevAmt ){
1776 printf(" %d%%", amt*10);
1777 fflush(stdout);
1778 prevAmt = amt;
1779 }
1780 }
1781 createVFile("main.db", pDb->sz, pDb->a);
drhbeaf5142016-12-26 00:15:56 +00001782 sqlite3_randomness(0,0);
drh362b66f2016-11-14 18:27:41 +00001783 if( ossFuzzThisDb ){
drhea432ba2016-11-11 16:33:47 +00001784#ifndef SQLITE_OSS_FUZZ
drh5ecf9032018-05-08 12:49:53 +00001785 fatalError("--oss-fuzz not supported: recompile"
1786 " with -DSQLITE_OSS_FUZZ");
drhea432ba2016-11-11 16:33:47 +00001787#else
1788 extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t);
1789 LLVMFuzzerTestOneInput((const uint8_t*)pSql->a, (size_t)pSql->sz);
drh78057352015-06-24 23:17:35 +00001790#endif
drhea432ba2016-11-11 16:33:47 +00001791 }else{
1792 openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
1793 if( nativeFlag && pDb->sz==0 ){
1794 openFlags |= SQLITE_OPEN_MEMORY;
1795 zVfs = 0;
1796 }
1797 rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
1798 if( rc ) fatalError("cannot open inmem database");
drhdfcfff62016-12-26 12:25:19 +00001799 sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 100000000);
1800 sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 50);
drhea432ba2016-11-11 16:33:47 +00001801 if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
1802 setAlarm(iTimeout);
1803#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1804 if( sqlFuzz || vdbeLimitFlag ){
drh5ecf9032018-05-08 12:49:53 +00001805 sqlite3_progress_handler(db, 100000, progressHandler,
1806 &vdbeLimitFlag);
drhea432ba2016-11-11 16:33:47 +00001807 }
1808#endif
drhe6e96b12019-08-02 21:03:24 +00001809#ifdef SQLITE_TESTCTRL_PRNG_SEED
drh2e6d83b2019-08-03 01:39:20 +00001810 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, db);
drhe6e96b12019-08-02 21:03:24 +00001811#endif
drhea432ba2016-11-11 16:33:47 +00001812 do{
1813 runSql(db, (char*)pSql->a, runFlags);
1814 }while( timeoutTest );
1815 setAlarm(0);
drh174f8552017-03-20 22:58:27 +00001816 sqlite3_exec(db, "PRAGMA temp_store_directory=''", 0, 0, 0);
drhea432ba2016-11-11 16:33:47 +00001817 sqlite3_close(db);
1818 }
drh174f8552017-03-20 22:58:27 +00001819 if( sqlite3_memory_used()>0 ){
1820 fatalError("memory leak: %lld bytes outstanding",
1821 sqlite3_memory_used());
1822 }
drhd9972ef2015-05-26 17:57:56 +00001823 reformatVfs();
1824 nTest++;
1825 g.zTestName[0] = 0;
drh4d6fda72015-05-26 18:58:32 +00001826
1827 /* Simulate an error if the TEST_FAILURE environment variable is "5".
1828 ** This is used to verify that automated test script really do spot
1829 ** errors that occur in this test program.
1830 */
1831 if( zFailCode ){
1832 if( zFailCode[0]=='5' && zFailCode[1]==0 ){
1833 fatalError("simulated failure");
1834 }else if( zFailCode[0]!=0 ){
1835 /* If TEST_FAILURE is something other than 5, just exit the test
1836 ** early */
1837 printf("\nExit early due to TEST_FAILURE being set\n");
1838 iSrcDb = nSrcDb-1;
1839 goto sourcedb_cleanup;
1840 }
1841 }
drhd9972ef2015-05-26 17:57:56 +00001842 }
1843 }
1844 if( !quietFlag && !verboseFlag ){
1845 printf(" 100%% - %d tests\n", g.nDb*g.nSql);
1846 }
1847
1848 /* Clean up at the end of processing a single source database
1849 */
drh4d6fda72015-05-26 18:58:32 +00001850 sourcedb_cleanup:
drhd9972ef2015-05-26 17:57:56 +00001851 blobListFree(g.pFirstSql);
1852 blobListFree(g.pFirstDb);
1853 reformatVfs();
1854
1855 } /* End loop over all source databases */
drh3b74d032015-05-25 18:48:19 +00001856
1857 if( !quietFlag ){
1858 sqlite3_int64 iElapse = timeOfDay() - iBegin;
drhd9972ef2015-05-26 17:57:56 +00001859 printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
1860 "SQLite %s %s\n",
1861 nTest, (int)(iElapse/1000), (int)(iElapse%1000),
drh3b74d032015-05-25 18:48:19 +00001862 sqlite3_libversion(), sqlite3_sourceid());
1863 }
drhf74d35b2015-05-27 18:19:50 +00001864 free(azSrcDb);
drh6653fbe2015-11-13 20:52:49 +00001865 free(pHeap);
drh3b74d032015-05-25 18:48:19 +00001866 return 0;
1867}