1 /* 2 ** 2015-05-25 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** 13 ** This is a utility program designed to aid running regressions tests on 14 ** the SQLite library using data from an external fuzzer, such as American 15 ** 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 ** ); 28 ** CREATE TABLE IF NOT EXISTS readme( 29 ** msg TEXT -- Human-readable description of this test collection 30 ** ); 31 ** 32 ** For each database file in the DB table, the SQL text in the XSQL table 33 ** 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. 43 ** 44 ** This program also includes some command-line options to help with 45 ** 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. 66 */ 67 #include <stdio.h> 68 #include <stdlib.h> 69 #include <string.h> 70 #include <stdarg.h> 71 #include <ctype.h> 72 #include <assert.h> 73 #include "sqlite3.h" 74 #define ISSPACE(X) isspace((unsigned char)(X)) 75 #define ISDIGIT(X) isdigit((unsigned char)(X)) 76 77 78 #ifdef __unix__ 79 # include <signal.h> 80 # include <unistd.h> 81 #endif 82 83 #ifdef SQLITE_OSS_FUZZ 84 # include <stddef.h> 85 # if !defined(_MSC_VER) 86 # include <stdint.h> 87 # endif 88 #endif 89 90 #if defined(_MSC_VER) 91 typedef unsigned char uint8_t; 92 #endif 93 94 /* 95 ** Files in the virtual file system. 96 */ 97 typedef struct VFile VFile; 98 struct 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 }; 104 typedef struct VHandle VHandle; 105 struct 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 */ 113 typedef struct Blob Blob; 114 struct Blob { 115 Blob *pNext; /* Next in a list */ 116 int id; /* Id of this Blob */ 117 int seq; /* Sequence number */ 118 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 */ 135 static struct GlobalVars { 136 const char *zArgv0; /* Name of program */ 137 const char *zDbFile; /* Name of database file */ 138 VFile aFile[MX_FILE]; /* The virtual filesystem */ 139 int nDb; /* Number of template databases */ 140 Blob *pFirstDb; /* Content of first template database */ 141 int nSql; /* Number of SQL scripts */ 142 Blob *pFirstSql; /* First SQL script */ 143 unsigned int uRandom; /* Seed for the SQLite PRNG */ 144 char zTestName[100]; /* Name of current test */ 145 } g; 146 147 /* 148 ** Print an error message and quit. 149 */ 150 static void fatalError(const char *zFormat, ...){ 151 va_list ap; 152 fprintf(stderr, "%s", g.zArgv0); 153 if( g.zDbFile ) fprintf(stderr, " %s", g.zDbFile); 154 if( g.zTestName[0] ) fprintf(stderr, " (%s)", g.zTestName); 155 fprintf(stderr, ": "); 156 va_start(ap, zFormat); 157 vfprintf(stderr, zFormat, ap); 158 va_end(ap); 159 fprintf(stderr, "\n"); 160 exit(1); 161 } 162 163 /* 164 ** signal handler 165 */ 166 #ifdef __unix__ 167 static void signalHandler(int signum){ 168 const char *zSig; 169 if( signum==SIGABRT ){ 170 zSig = "abort"; 171 }else if( signum==SIGALRM ){ 172 zSig = "timeout"; 173 }else if( signum==SIGSEGV ){ 174 zSig = "segfault"; 175 }else{ 176 zSig = "signal"; 177 } 178 fatalError(zSig); 179 } 180 #endif 181 182 /* 183 ** Set the an alarm to go off after N seconds. Disable the alarm 184 ** if N==0 185 */ 186 static void setAlarm(int N){ 187 #ifdef __unix__ 188 alarm(N); 189 #else 190 (void)N; 191 #endif 192 } 193 194 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 195 /* 196 ** This an SQL progress handler. After an SQL statement has run for 197 ** many steps, we want to interrupt it. This guards against infinite 198 ** loops from recursive common table expressions. 199 ** 200 ** *pVdbeLimitFlag is true if the --limit-vdbe command-line option is used. 201 ** In that case, hitting the progress handler is a fatal error. 202 */ 203 static int progressHandler(void *pVdbeLimitFlag){ 204 if( *(int*)pVdbeLimitFlag ) fatalError("too many VDBE cycles"); 205 return 1; 206 } 207 #endif 208 209 /* 210 ** Reallocate memory. Show and error and quit if unable. 211 */ 212 static void *safe_realloc(void *pOld, int szNew){ 213 void *pNew = realloc(pOld, szNew<=0 ? 1 : szNew); 214 if( pNew==0 ) fatalError("unable to realloc for %d bytes", szNew); 215 return pNew; 216 } 217 218 /* 219 ** Initialize the virtual file system. 220 */ 221 static void formatVfs(void){ 222 int i; 223 for(i=0; i<MX_FILE; i++){ 224 g.aFile[i].sz = -1; 225 g.aFile[i].zFilename = 0; 226 g.aFile[i].a = 0; 227 g.aFile[i].nRef = 0; 228 } 229 } 230 231 232 /* 233 ** Erase all information in the virtual file system. 234 */ 235 static void reformatVfs(void){ 236 int i; 237 for(i=0; i<MX_FILE; i++){ 238 if( g.aFile[i].sz<0 ) continue; 239 if( g.aFile[i].zFilename ){ 240 free(g.aFile[i].zFilename); 241 g.aFile[i].zFilename = 0; 242 } 243 if( g.aFile[i].nRef>0 ){ 244 fatalError("file %d still open. nRef=%d", i, g.aFile[i].nRef); 245 } 246 g.aFile[i].sz = -1; 247 free(g.aFile[i].a); 248 g.aFile[i].a = 0; 249 g.aFile[i].nRef = 0; 250 } 251 } 252 253 /* 254 ** Find a VFile by name 255 */ 256 static VFile *findVFile(const char *zName){ 257 int i; 258 if( zName==0 ) return 0; 259 for(i=0; i<MX_FILE; i++){ 260 if( g.aFile[i].zFilename==0 ) continue; 261 if( strcmp(g.aFile[i].zFilename, zName)==0 ) return &g.aFile[i]; 262 } 263 return 0; 264 } 265 266 /* 267 ** Find a VFile by name. Create it if it does not already exist and 268 ** initialize it to the size and content given. 269 ** 270 ** Return NULL only if the filesystem is full. 271 */ 272 static VFile *createVFile(const char *zName, int sz, unsigned char *pData){ 273 VFile *pNew = findVFile(zName); 274 int i; 275 if( pNew ) return pNew; 276 for(i=0; i<MX_FILE && g.aFile[i].sz>=0; i++){} 277 if( i>=MX_FILE ) return 0; 278 pNew = &g.aFile[i]; 279 if( zName ){ 280 int nName = (int)strlen(zName)+1; 281 pNew->zFilename = safe_realloc(0, nName); 282 memcpy(pNew->zFilename, zName, nName); 283 }else{ 284 pNew->zFilename = 0; 285 } 286 pNew->nRef = 0; 287 pNew->sz = sz; 288 pNew->a = safe_realloc(0, sz); 289 if( sz>0 ) memcpy(pNew->a, pData, sz); 290 return pNew; 291 } 292 293 294 /* 295 ** Implementation of the "readfile(X)" SQL function. The entire content 296 ** of the file named X is read and returned as a BLOB. NULL is returned 297 ** if the file does not exist or is unreadable. 298 */ 299 static void readfileFunc( 300 sqlite3_context *context, 301 int argc, 302 sqlite3_value **argv 303 ){ 304 const char *zName; 305 FILE *in; 306 long nIn; 307 void *pBuf; 308 309 zName = (const char*)sqlite3_value_text(argv[0]); 310 if( zName==0 ) return; 311 in = fopen(zName, "rb"); 312 if( in==0 ) return; 313 fseek(in, 0, SEEK_END); 314 nIn = ftell(in); 315 rewind(in); 316 pBuf = sqlite3_malloc64( nIn ); 317 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){ 318 sqlite3_result_blob(context, pBuf, nIn, sqlite3_free); 319 }else{ 320 sqlite3_free(pBuf); 321 } 322 fclose(in); 323 } 324 325 /* 326 ** Implementation of the "writefile(X,Y)" SQL function. The argument Y 327 ** is written into file X. The number of bytes written is returned. Or 328 ** NULL is returned if something goes wrong, such as being unable to open 329 ** file X for writing. 330 */ 331 static void writefileFunc( 332 sqlite3_context *context, 333 int argc, 334 sqlite3_value **argv 335 ){ 336 FILE *out; 337 const char *z; 338 sqlite3_int64 rc; 339 const char *zFile; 340 341 (void)argc; 342 zFile = (const char*)sqlite3_value_text(argv[0]); 343 if( zFile==0 ) return; 344 out = fopen(zFile, "wb"); 345 if( out==0 ) return; 346 z = (const char*)sqlite3_value_blob(argv[1]); 347 if( z==0 ){ 348 rc = 0; 349 }else{ 350 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out); 351 } 352 fclose(out); 353 sqlite3_result_int64(context, rc); 354 } 355 356 357 /* 358 ** Load a list of Blob objects from the database 359 */ 360 static void blobListLoadFromDb( 361 sqlite3 *db, /* Read from this database */ 362 const char *zSql, /* Query used to extract the blobs */ 363 int onlyId, /* Only load where id is this value */ 364 int *pN, /* OUT: Write number of blobs loaded here */ 365 Blob **ppList /* OUT: Write the head of the blob list here */ 366 ){ 367 Blob head; 368 Blob *p; 369 sqlite3_stmt *pStmt; 370 int n = 0; 371 int rc; 372 char *z2; 373 374 if( onlyId>0 ){ 375 z2 = sqlite3_mprintf("%s WHERE rowid=%d", zSql, onlyId); 376 }else{ 377 z2 = sqlite3_mprintf("%s", zSql); 378 } 379 rc = sqlite3_prepare_v2(db, z2, -1, &pStmt, 0); 380 sqlite3_free(z2); 381 if( rc ) fatalError("%s", sqlite3_errmsg(db)); 382 head.pNext = 0; 383 p = &head; 384 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 385 int sz = sqlite3_column_bytes(pStmt, 1); 386 Blob *pNew = safe_realloc(0, sizeof(*pNew)+sz ); 387 pNew->id = sqlite3_column_int(pStmt, 0); 388 pNew->sz = sz; 389 pNew->seq = n++; 390 pNew->pNext = 0; 391 memcpy(pNew->a, sqlite3_column_blob(pStmt,1), sz); 392 pNew->a[sz] = 0; 393 p->pNext = pNew; 394 p = pNew; 395 } 396 sqlite3_finalize(pStmt); 397 *pN = n; 398 *ppList = head.pNext; 399 } 400 401 /* 402 ** Free a list of Blob objects 403 */ 404 static void blobListFree(Blob *p){ 405 Blob *pNext; 406 while( p ){ 407 pNext = p->pNext; 408 free(p); 409 p = pNext; 410 } 411 } 412 413 /* Return the current wall-clock time */ 414 static sqlite3_int64 timeOfDay(void){ 415 static sqlite3_vfs *clockVfs = 0; 416 sqlite3_int64 t; 417 if( clockVfs==0 ){ 418 clockVfs = sqlite3_vfs_find(0); 419 if( clockVfs==0 ) return 0; 420 } 421 if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){ 422 clockVfs->xCurrentTimeInt64(clockVfs, &t); 423 }else{ 424 double r; 425 clockVfs->xCurrentTime(clockVfs, &r); 426 t = (sqlite3_int64)(r*86400000.0); 427 } 428 return t; 429 } 430 431 /*************************************************************************** 432 ** Code to process combined database+SQL scripts generated by the 433 ** dbsqlfuzz fuzzer. 434 */ 435 436 /* An instance of the following object is passed by pointer as the 437 ** client data to various callbacks. 438 */ 439 typedef struct FuzzCtx { 440 sqlite3 *db; /* The database connection */ 441 sqlite3_int64 iCutoffTime; /* Stop processing at this time. */ 442 sqlite3_int64 iLastCb; /* Time recorded for previous progress callback */ 443 sqlite3_int64 mxInterval; /* Longest interval between two progress calls */ 444 unsigned nCb; /* Number of progress callbacks */ 445 unsigned mxCb; /* Maximum number of progress callbacks allowed */ 446 unsigned execCnt; /* Number of calls to the sqlite3_exec callback */ 447 int timeoutHit; /* True when reaching a timeout */ 448 } FuzzCtx; 449 450 /* Verbosity level for the dbsqlfuzz test runner */ 451 static int eVerbosity = 0; 452 453 /* True to activate PRAGMA vdbe_debug=on */ 454 static int bVdbeDebug = 0; 455 456 /* Timeout for each fuzzing attempt, in milliseconds */ 457 static int giTimeout = 10000; /* Defaults to 10 seconds */ 458 459 /* Maximum number of progress handler callbacks */ 460 static unsigned int mxProgressCb = 2000; 461 462 /* Maximum string length in SQLite */ 463 static int lengthLimit = 1000000; 464 465 /* Limit on the amount of heap memory that can be used */ 466 static sqlite3_int64 heapLimit = 1000000000; 467 468 /* Maximum byte-code program length in SQLite */ 469 static int vdbeOpLimit = 25000; 470 471 /* Maximum size of the in-memory database */ 472 static sqlite3_int64 maxDbSize = 104857600; 473 474 /* 475 ** Translate a single byte of Hex into an integer. 476 ** This routine only works if h really is a valid hexadecimal 477 ** character: 0..9a..fA..F 478 */ 479 static unsigned char hexToInt(unsigned int h){ 480 #ifdef SQLITE_EBCDIC 481 h += 9*(1&~(h>>4)); /* EBCDIC */ 482 #else 483 h += 9*(1&(h>>6)); /* ASCII */ 484 #endif 485 return h & 0xf; 486 } 487 488 /* 489 ** The first character of buffer zIn[0..nIn-1] is a '['. This routine 490 ** checked to see if the buffer holds "[NNNN]" or "[+NNNN]" and if it 491 ** does it makes corresponding changes to the *pK value and *pI value 492 ** and returns true. If the input buffer does not match the patterns, 493 ** no changes are made to either *pK or *pI and this routine returns false. 494 */ 495 static int isOffset( 496 const unsigned char *zIn, /* Text input */ 497 int nIn, /* Bytes of input */ 498 unsigned int *pK, /* half-byte cursor to adjust */ 499 unsigned int *pI /* Input index to adjust */ 500 ){ 501 int i; 502 unsigned int k = 0; 503 unsigned char c; 504 for(i=1; i<nIn && (c = zIn[i])!=']'; i++){ 505 if( !isxdigit(c) ) return 0; 506 k = k*16 + hexToInt(c); 507 } 508 if( i==nIn ) return 0; 509 *pK = 2*k; 510 *pI += i; 511 return 1; 512 } 513 514 /* 515 ** Decode the text starting at zIn into a binary database file. 516 ** The maximum length of zIn is nIn bytes. Compute the binary database 517 ** file contain in space obtained from sqlite3_malloc(). 518 ** 519 ** Return the number of bytes of zIn consumed. Or return -1 if there 520 ** is an error. One potential error is that the recipe specifies a 521 ** database file larger than MX_FILE_SZ bytes. 522 ** 523 ** Abort on an OOM. 524 */ 525 static int decodeDatabase( 526 const unsigned char *zIn, /* Input text to be decoded */ 527 int nIn, /* Bytes of input text */ 528 unsigned char **paDecode, /* OUT: decoded database file */ 529 int *pnDecode /* OUT: Size of decoded database */ 530 ){ 531 unsigned char *a; /* Database under construction */ 532 int mx = 0; /* Current size of the database */ 533 sqlite3_uint64 nAlloc = 4096; /* Space allocated in a[] */ 534 unsigned int i; /* Next byte of zIn[] to read */ 535 unsigned int j; /* Temporary integer */ 536 unsigned int k; /* half-byte cursor index for output */ 537 unsigned int n; /* Number of bytes of input */ 538 unsigned char b = 0; 539 if( nIn<4 ) return -1; 540 n = (unsigned int)nIn; 541 a = sqlite3_malloc64( nAlloc ); 542 if( a==0 ){ 543 fprintf(stderr, "Out of memory!\n"); 544 exit(1); 545 } 546 memset(a, 0, (size_t)nAlloc); 547 for(i=k=0; i<n; i++){ 548 unsigned char c = (unsigned char)zIn[i]; 549 if( isxdigit(c) ){ 550 k++; 551 if( k & 1 ){ 552 b = hexToInt(c)*16; 553 }else{ 554 b += hexToInt(c); 555 j = k/2 - 1; 556 if( j>=nAlloc ){ 557 sqlite3_uint64 newSize; 558 if( nAlloc==MX_FILE_SZ || j>=MX_FILE_SZ ){ 559 if( eVerbosity ){ 560 fprintf(stderr, "Input database too big: max %d bytes\n", 561 MX_FILE_SZ); 562 } 563 sqlite3_free(a); 564 return -1; 565 } 566 newSize = nAlloc*2; 567 if( newSize<=j ){ 568 newSize = (j+4096)&~4095; 569 } 570 if( newSize>MX_FILE_SZ ){ 571 if( j>=MX_FILE_SZ ){ 572 sqlite3_free(a); 573 return -1; 574 } 575 newSize = MX_FILE_SZ; 576 } 577 a = sqlite3_realloc64( a, newSize ); 578 if( a==0 ){ 579 fprintf(stderr, "Out of memory!\n"); 580 exit(1); 581 } 582 assert( newSize > nAlloc ); 583 memset(a+nAlloc, 0, (size_t)(newSize - nAlloc)); 584 nAlloc = newSize; 585 } 586 if( j>=(unsigned)mx ){ 587 mx = (j + 4095)&~4095; 588 if( mx>MX_FILE_SZ ) mx = MX_FILE_SZ; 589 } 590 assert( j<nAlloc ); 591 a[j] = b; 592 } 593 }else if( zIn[i]=='[' && i<n-3 && isOffset(zIn+i, nIn-i, &k, &i) ){ 594 continue; 595 }else if( zIn[i]=='\n' && i<n-4 && memcmp(zIn+i,"\n--\n",4)==0 ){ 596 i += 4; 597 break; 598 } 599 } 600 *pnDecode = mx; 601 *paDecode = a; 602 return i; 603 } 604 605 /* 606 ** Progress handler callback. 607 ** 608 ** The argument is the cutoff-time after which all processing should 609 ** stop. So return non-zero if the cut-off time is exceeded. 610 */ 611 static int progress_handler(void *pClientData) { 612 FuzzCtx *p = (FuzzCtx*)pClientData; 613 sqlite3_int64 iNow = timeOfDay(); 614 int rc = iNow>=p->iCutoffTime; 615 sqlite3_int64 iDiff = iNow - p->iLastCb; 616 if( iDiff > p->mxInterval ) p->mxInterval = iDiff; 617 p->nCb++; 618 if( rc==0 && p->mxCb>0 && p->mxCb<=p->nCb ) rc = 1; 619 if( rc && !p->timeoutHit && eVerbosity>=2 ){ 620 printf("Timeout on progress callback %d\n", p->nCb); 621 fflush(stdout); 622 p->timeoutHit = 1; 623 } 624 return rc; 625 } 626 627 /* 628 ** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and 629 ** "PRAGMA parser_trace" since they can dramatically increase the 630 ** amount of output without actually testing anything useful. 631 ** 632 ** Also block ATTACH and DETACH 633 */ 634 static int block_troublesome_sql( 635 void *Notused, 636 int eCode, 637 const char *zArg1, 638 const char *zArg2, 639 const char *zArg3, 640 const char *zArg4 641 ){ 642 (void)Notused; 643 (void)zArg2; 644 (void)zArg3; 645 (void)zArg4; 646 if( eCode==SQLITE_PRAGMA ){ 647 if( sqlite3_strnicmp("vdbe_", zArg1, 5)==0 648 || sqlite3_stricmp("parser_trace", zArg1)==0 649 || sqlite3_stricmp("temp_store_directory", zArg1)==0 650 ){ 651 return SQLITE_DENY; 652 } 653 }else if( (eCode==SQLITE_ATTACH || eCode==SQLITE_DETACH) 654 && zArg1 && zArg1[0] ){ 655 return SQLITE_DENY; 656 } 657 return SQLITE_OK; 658 } 659 660 /* 661 ** Run the SQL text 662 */ 663 static int runDbSql(sqlite3 *db, const char *zSql){ 664 int rc; 665 sqlite3_stmt *pStmt; 666 while( isspace(zSql[0]&0x7f) ) zSql++; 667 if( zSql[0]==0 ) return SQLITE_OK; 668 if( eVerbosity>=4 ){ 669 printf("RUNNING-SQL: [%s]\n", zSql); 670 fflush(stdout); 671 } 672 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 673 if( rc==SQLITE_OK ){ 674 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){ 675 if( eVerbosity>=5 ){ 676 int j; 677 for(j=0; j<sqlite3_column_count(pStmt); j++){ 678 if( j ) printf(","); 679 switch( sqlite3_column_type(pStmt, j) ){ 680 case SQLITE_NULL: { 681 printf("NULL"); 682 break; 683 } 684 case SQLITE_INTEGER: 685 case SQLITE_FLOAT: { 686 printf("%s", sqlite3_column_text(pStmt, j)); 687 break; 688 } 689 case SQLITE_BLOB: { 690 int n = sqlite3_column_bytes(pStmt, j); 691 int i; 692 const unsigned char *a; 693 a = (const unsigned char*)sqlite3_column_blob(pStmt, j); 694 printf("x'"); 695 for(i=0; i<n; i++){ 696 printf("%02x", a[i]); 697 } 698 printf("'"); 699 break; 700 } 701 case SQLITE_TEXT: { 702 int n = sqlite3_column_bytes(pStmt, j); 703 int i; 704 const unsigned char *a; 705 a = (const unsigned char*)sqlite3_column_blob(pStmt, j); 706 printf("'"); 707 for(i=0; i<n; i++){ 708 if( a[i]=='\'' ){ 709 printf("''"); 710 }else{ 711 putchar(a[i]); 712 } 713 } 714 printf("'"); 715 break; 716 } 717 } /* End switch() */ 718 } /* End for() */ 719 printf("\n"); 720 fflush(stdout); 721 } /* End if( eVerbosity>=5 ) */ 722 } /* End while( SQLITE_ROW */ 723 if( rc!=SQLITE_DONE && eVerbosity>=4 ){ 724 printf("SQL-ERROR: (%d) %s\n", rc, sqlite3_errmsg(db)); 725 fflush(stdout); 726 } 727 }else if( eVerbosity>=4 ){ 728 printf("SQL-ERROR (%d): %s\n", rc, sqlite3_errmsg(db)); 729 fflush(stdout); 730 } /* End if( SQLITE_OK ) */ 731 return sqlite3_finalize(pStmt); 732 } 733 734 /* Invoke this routine to run a single test case */ 735 int runCombinedDbSqlInput(const uint8_t *aData, size_t nByte){ 736 int rc; /* SQLite API return value */ 737 int iSql; /* Index in aData[] of start of SQL */ 738 unsigned char *aDb = 0; /* Decoded database content */ 739 int nDb = 0; /* Size of the decoded database */ 740 int i; /* Loop counter */ 741 int j; /* Start of current SQL statement */ 742 char *zSql = 0; /* SQL text to run */ 743 int nSql; /* Bytes of SQL text */ 744 FuzzCtx cx; /* Fuzzing context */ 745 746 if( nByte<10 ) return 0; 747 if( sqlite3_initialize() ) return 0; 748 if( sqlite3_memory_used()!=0 ){ 749 int nAlloc = 0; 750 int nNotUsed = 0; 751 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0); 752 fprintf(stderr,"Memory leak in mutator: %lld bytes in %d allocations\n", 753 sqlite3_memory_used(), nAlloc); 754 exit(1); 755 } 756 memset(&cx, 0, sizeof(cx)); 757 iSql = decodeDatabase((unsigned char*)aData, (int)nByte, &aDb, &nDb); 758 if( iSql<0 ) return 0; 759 nSql = (int)(nByte - iSql); 760 if( eVerbosity>=3 ){ 761 printf( 762 "****** %d-byte input, %d-byte database, %d-byte script " 763 "******\n", (int)nByte, nDb, nSql); 764 fflush(stdout); 765 } 766 rc = sqlite3_open(0, &cx.db); 767 if( rc ) return 1; 768 if( bVdbeDebug ){ 769 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON", 0, 0, 0); 770 } 771 772 /* Invoke the progress handler frequently to check to see if we 773 ** are taking too long. The progress handler will return true 774 ** (which will block further processing) if more than giTimeout seconds have 775 ** elapsed since the start of the test. 776 */ 777 cx.iLastCb = timeOfDay(); 778 cx.iCutoffTime = cx.iLastCb + giTimeout; /* Now + giTimeout seconds */ 779 cx.mxCb = mxProgressCb; 780 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 781 sqlite3_progress_handler(cx.db, 10, progress_handler, (void*)&cx); 782 #endif 783 784 /* Set a limit on the maximum size of a prepared statement, and the 785 ** maximum length of a string or blob */ 786 if( vdbeOpLimit>0 ){ 787 sqlite3_limit(cx.db, SQLITE_LIMIT_VDBE_OP, vdbeOpLimit); 788 } 789 if( lengthLimit>0 ){ 790 sqlite3_limit(cx.db, SQLITE_LIMIT_LENGTH, lengthLimit); 791 } 792 sqlite3_hard_heap_limit64(heapLimit); 793 794 if( nDb>=20 && aDb[18]==2 && aDb[19]==2 ){ 795 aDb[18] = aDb[19] = 1; 796 } 797 rc = sqlite3_deserialize(cx.db, "main", aDb, nDb, nDb, 798 SQLITE_DESERIALIZE_RESIZEABLE | 799 SQLITE_DESERIALIZE_FREEONCLOSE); 800 if( rc ){ 801 fprintf(stderr, "sqlite3_deserialize() failed with %d\n", rc); 802 goto testrun_finished; 803 } 804 if( maxDbSize>0 ){ 805 sqlite3_int64 x = maxDbSize; 806 sqlite3_file_control(cx.db, "main", SQLITE_FCNTL_SIZE_LIMIT, &x); 807 } 808 809 /* For high debugging levels, turn on debug mode */ 810 if( eVerbosity>=5 ){ 811 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON;", 0, 0, 0); 812 } 813 814 /* Block debug pragmas and ATTACH/DETACH. But wait until after 815 ** deserialize to do this because deserialize depends on ATTACH */ 816 sqlite3_set_authorizer(cx.db, block_troublesome_sql, 0); 817 818 /* Consistent PRNG seed */ 819 sqlite3_randomness(0,0); 820 821 zSql = sqlite3_malloc( nSql + 1 ); 822 if( zSql==0 ){ 823 fprintf(stderr, "Out of memory!\n"); 824 }else{ 825 memcpy(zSql, aData+iSql, nSql); 826 zSql[nSql] = 0; 827 for(i=j=0; zSql[i]; i++){ 828 if( zSql[i]==';' ){ 829 char cSaved = zSql[i+1]; 830 zSql[i+1] = 0; 831 if( sqlite3_complete(zSql+j) ){ 832 rc = runDbSql(cx.db, zSql+j); 833 j = i+1; 834 } 835 zSql[i+1] = cSaved; 836 if( rc==SQLITE_INTERRUPT || progress_handler(&cx) ){ 837 goto testrun_finished; 838 } 839 } 840 } 841 if( j<i ){ 842 runDbSql(cx.db, zSql+j); 843 } 844 } 845 testrun_finished: 846 sqlite3_free(zSql); 847 rc = sqlite3_close(cx.db); 848 if( rc!=SQLITE_OK ){ 849 fprintf(stdout, "sqlite3_close() returns %d\n", rc); 850 } 851 if( eVerbosity>=2 ){ 852 fprintf(stdout, "Peak memory usages: %f MB\n", 853 sqlite3_memory_highwater(1) / 1000000.0); 854 } 855 if( sqlite3_memory_used()!=0 ){ 856 int nAlloc = 0; 857 int nNotUsed = 0; 858 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0); 859 fprintf(stderr,"Memory leak: %lld bytes in %d allocations\n", 860 sqlite3_memory_used(), nAlloc); 861 exit(1); 862 } 863 return 0; 864 } 865 866 /* 867 ** END of the dbsqlfuzz code 868 ***************************************************************************/ 869 870 /* Look at a SQL text and try to determine if it begins with a database 871 ** description, such as would be found in a dbsqlfuzz test case. Return 872 ** true if this does appear to be a dbsqlfuzz test case and false otherwise. 873 */ 874 static int isDbSql(unsigned char *a, int n){ 875 unsigned char buf[12]; 876 int i; 877 if( n>4 && memcmp(a,"\n--\n",4)==0 ) return 1; 878 while( n>0 && isspace(a[0]) ){ a++; n--; } 879 for(i=0; n>0 && i<8; n--, a++){ 880 if( isxdigit(a[0]) ) buf[i++] = a[0]; 881 } 882 if( i==8 && memcmp(buf,"53514c69",8)==0 ) return 1; 883 return 0; 884 } 885 886 /* Implementation of the isdbsql(TEXT) SQL function. 887 */ 888 static void isDbSqlFunc( 889 sqlite3_context *context, 890 int argc, 891 sqlite3_value **argv 892 ){ 893 int n = sqlite3_value_bytes(argv[0]); 894 unsigned char *a = (unsigned char*)sqlite3_value_blob(argv[0]); 895 sqlite3_result_int(context, a!=0 && n>0 && isDbSql(a,n)); 896 } 897 898 /* Methods for the VHandle object 899 */ 900 static int inmemClose(sqlite3_file *pFile){ 901 VHandle *p = (VHandle*)pFile; 902 VFile *pVFile = p->pVFile; 903 pVFile->nRef--; 904 if( pVFile->nRef==0 && pVFile->zFilename==0 ){ 905 pVFile->sz = -1; 906 free(pVFile->a); 907 pVFile->a = 0; 908 } 909 return SQLITE_OK; 910 } 911 static int inmemRead( 912 sqlite3_file *pFile, /* Read from this open file */ 913 void *pData, /* Store content in this buffer */ 914 int iAmt, /* Bytes of content */ 915 sqlite3_int64 iOfst /* Start reading here */ 916 ){ 917 VHandle *pHandle = (VHandle*)pFile; 918 VFile *pVFile = pHandle->pVFile; 919 if( iOfst<0 || iOfst>=pVFile->sz ){ 920 memset(pData, 0, iAmt); 921 return SQLITE_IOERR_SHORT_READ; 922 } 923 if( iOfst+iAmt>pVFile->sz ){ 924 memset(pData, 0, iAmt); 925 iAmt = (int)(pVFile->sz - iOfst); 926 memcpy(pData, pVFile->a + iOfst, iAmt); 927 return SQLITE_IOERR_SHORT_READ; 928 } 929 memcpy(pData, pVFile->a + iOfst, iAmt); 930 return SQLITE_OK; 931 } 932 static int inmemWrite( 933 sqlite3_file *pFile, /* Write to this file */ 934 const void *pData, /* Content to write */ 935 int iAmt, /* bytes to write */ 936 sqlite3_int64 iOfst /* Start writing here */ 937 ){ 938 VHandle *pHandle = (VHandle*)pFile; 939 VFile *pVFile = pHandle->pVFile; 940 if( iOfst+iAmt > pVFile->sz ){ 941 if( iOfst+iAmt >= MX_FILE_SZ ){ 942 return SQLITE_FULL; 943 } 944 pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt)); 945 if( iOfst > pVFile->sz ){ 946 memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz)); 947 } 948 pVFile->sz = (int)(iOfst + iAmt); 949 } 950 memcpy(pVFile->a + iOfst, pData, iAmt); 951 return SQLITE_OK; 952 } 953 static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){ 954 VHandle *pHandle = (VHandle*)pFile; 955 VFile *pVFile = pHandle->pVFile; 956 if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize; 957 return SQLITE_OK; 958 } 959 static int inmemSync(sqlite3_file *pFile, int flags){ 960 return SQLITE_OK; 961 } 962 static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){ 963 *pSize = ((VHandle*)pFile)->pVFile->sz; 964 return SQLITE_OK; 965 } 966 static int inmemLock(sqlite3_file *pFile, int type){ 967 return SQLITE_OK; 968 } 969 static int inmemUnlock(sqlite3_file *pFile, int type){ 970 return SQLITE_OK; 971 } 972 static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){ 973 *pOut = 0; 974 return SQLITE_OK; 975 } 976 static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){ 977 return SQLITE_NOTFOUND; 978 } 979 static int inmemSectorSize(sqlite3_file *pFile){ 980 return 512; 981 } 982 static int inmemDeviceCharacteristics(sqlite3_file *pFile){ 983 return 984 SQLITE_IOCAP_SAFE_APPEND | 985 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | 986 SQLITE_IOCAP_POWERSAFE_OVERWRITE; 987 } 988 989 990 /* Method table for VHandle 991 */ 992 static sqlite3_io_methods VHandleMethods = { 993 /* iVersion */ 1, 994 /* xClose */ inmemClose, 995 /* xRead */ inmemRead, 996 /* xWrite */ inmemWrite, 997 /* xTruncate */ inmemTruncate, 998 /* xSync */ inmemSync, 999 /* xFileSize */ inmemFileSize, 1000 /* xLock */ inmemLock, 1001 /* xUnlock */ inmemUnlock, 1002 /* xCheck... */ inmemCheckReservedLock, 1003 /* xFileCtrl */ inmemFileControl, 1004 /* xSectorSz */ inmemSectorSize, 1005 /* xDevchar */ inmemDeviceCharacteristics, 1006 /* xShmMap */ 0, 1007 /* xShmLock */ 0, 1008 /* xShmBarrier */ 0, 1009 /* xShmUnmap */ 0, 1010 /* xFetch */ 0, 1011 /* xUnfetch */ 0 1012 }; 1013 1014 /* 1015 ** Open a new file in the inmem VFS. All files are anonymous and are 1016 ** delete-on-close. 1017 */ 1018 static int inmemOpen( 1019 sqlite3_vfs *pVfs, 1020 const char *zFilename, 1021 sqlite3_file *pFile, 1022 int openFlags, 1023 int *pOutFlags 1024 ){ 1025 VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)""); 1026 VHandle *pHandle = (VHandle*)pFile; 1027 if( pVFile==0 ){ 1028 return SQLITE_FULL; 1029 } 1030 pHandle->pVFile = pVFile; 1031 pVFile->nRef++; 1032 pFile->pMethods = &VHandleMethods; 1033 if( pOutFlags ) *pOutFlags = openFlags; 1034 return SQLITE_OK; 1035 } 1036 1037 /* 1038 ** Delete a file by name 1039 */ 1040 static int inmemDelete( 1041 sqlite3_vfs *pVfs, 1042 const char *zFilename, 1043 int syncdir 1044 ){ 1045 VFile *pVFile = findVFile(zFilename); 1046 if( pVFile==0 ) return SQLITE_OK; 1047 if( pVFile->nRef==0 ){ 1048 free(pVFile->zFilename); 1049 pVFile->zFilename = 0; 1050 pVFile->sz = -1; 1051 free(pVFile->a); 1052 pVFile->a = 0; 1053 return SQLITE_OK; 1054 } 1055 return SQLITE_IOERR_DELETE; 1056 } 1057 1058 /* Check for the existance of a file 1059 */ 1060 static int inmemAccess( 1061 sqlite3_vfs *pVfs, 1062 const char *zFilename, 1063 int flags, 1064 int *pResOut 1065 ){ 1066 VFile *pVFile = findVFile(zFilename); 1067 *pResOut = pVFile!=0; 1068 return SQLITE_OK; 1069 } 1070 1071 /* Get the canonical pathname for a file 1072 */ 1073 static int inmemFullPathname( 1074 sqlite3_vfs *pVfs, 1075 const char *zFilename, 1076 int nOut, 1077 char *zOut 1078 ){ 1079 sqlite3_snprintf(nOut, zOut, "%s", zFilename); 1080 return SQLITE_OK; 1081 } 1082 1083 /* Always use the same random see, for repeatability. 1084 */ 1085 static int inmemRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ 1086 memset(zBuf, 0, nBuf); 1087 memcpy(zBuf, &g.uRandom, nBuf<sizeof(g.uRandom) ? nBuf : sizeof(g.uRandom)); 1088 return nBuf; 1089 } 1090 1091 /* 1092 ** Register the VFS that reads from the g.aFile[] set of files. 1093 */ 1094 static void inmemVfsRegister(int makeDefault){ 1095 static sqlite3_vfs inmemVfs; 1096 sqlite3_vfs *pDefault = sqlite3_vfs_find(0); 1097 inmemVfs.iVersion = 3; 1098 inmemVfs.szOsFile = sizeof(VHandle); 1099 inmemVfs.mxPathname = 200; 1100 inmemVfs.zName = "inmem"; 1101 inmemVfs.xOpen = inmemOpen; 1102 inmemVfs.xDelete = inmemDelete; 1103 inmemVfs.xAccess = inmemAccess; 1104 inmemVfs.xFullPathname = inmemFullPathname; 1105 inmemVfs.xRandomness = inmemRandomness; 1106 inmemVfs.xSleep = pDefault->xSleep; 1107 inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64; 1108 sqlite3_vfs_register(&inmemVfs, makeDefault); 1109 }; 1110 1111 /* 1112 ** Allowed values for the runFlags parameter to runSql() 1113 */ 1114 #define SQL_TRACE 0x0001 /* Print each SQL statement as it is prepared */ 1115 #define SQL_OUTPUT 0x0002 /* Show the SQL output */ 1116 1117 /* 1118 ** Run multiple commands of SQL. Similar to sqlite3_exec(), but does not 1119 ** stop if an error is encountered. 1120 */ 1121 static void runSql(sqlite3 *db, const char *zSql, unsigned runFlags){ 1122 const char *zMore; 1123 sqlite3_stmt *pStmt; 1124 1125 while( zSql && zSql[0] ){ 1126 zMore = 0; 1127 pStmt = 0; 1128 sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore); 1129 if( zMore==zSql ) break; 1130 if( runFlags & SQL_TRACE ){ 1131 const char *z = zSql; 1132 int n; 1133 while( z<zMore && ISSPACE(z[0]) ) z++; 1134 n = (int)(zMore - z); 1135 while( n>0 && ISSPACE(z[n-1]) ) n--; 1136 if( n==0 ) break; 1137 if( pStmt==0 ){ 1138 printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db)); 1139 }else{ 1140 printf("TRACE: %.*s\n", n, z); 1141 } 1142 } 1143 zSql = zMore; 1144 if( pStmt ){ 1145 if( (runFlags & SQL_OUTPUT)==0 ){ 1146 while( SQLITE_ROW==sqlite3_step(pStmt) ){} 1147 }else{ 1148 int nCol = -1; 1149 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 1150 int i; 1151 if( nCol<0 ){ 1152 nCol = sqlite3_column_count(pStmt); 1153 }else if( nCol>0 ){ 1154 printf("--------------------------------------------\n"); 1155 } 1156 for(i=0; i<nCol; i++){ 1157 int eType = sqlite3_column_type(pStmt,i); 1158 printf("%s = ", sqlite3_column_name(pStmt,i)); 1159 switch( eType ){ 1160 case SQLITE_NULL: { 1161 printf("NULL\n"); 1162 break; 1163 } 1164 case SQLITE_INTEGER: { 1165 printf("INT %s\n", sqlite3_column_text(pStmt,i)); 1166 break; 1167 } 1168 case SQLITE_FLOAT: { 1169 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i)); 1170 break; 1171 } 1172 case SQLITE_TEXT: { 1173 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i)); 1174 break; 1175 } 1176 case SQLITE_BLOB: { 1177 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i)); 1178 break; 1179 } 1180 } 1181 } 1182 } 1183 } 1184 sqlite3_finalize(pStmt); 1185 } 1186 } 1187 } 1188 1189 /* 1190 ** Rebuild the database file. 1191 ** 1192 ** (1) Remove duplicate entries 1193 ** (2) Put all entries in order 1194 ** (3) Vacuum 1195 */ 1196 static void rebuild_database(sqlite3 *db, int dbSqlOnly){ 1197 int rc; 1198 char *zSql; 1199 zSql = sqlite3_mprintf( 1200 "BEGIN;\n" 1201 "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n" 1202 "DELETE FROM db;\n" 1203 "INSERT INTO db(dbid, dbcontent) " 1204 " SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n" 1205 "DROP TABLE dbx;\n" 1206 "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql %s;\n" 1207 "DELETE FROM xsql;\n" 1208 "INSERT INTO xsql(sqlid,sqltext) " 1209 " SELECT NULL, sqltext FROM sx ORDER BY 2;\n" 1210 "DROP TABLE sx;\n" 1211 "COMMIT;\n" 1212 "PRAGMA page_size=1024;\n" 1213 "VACUUM;\n", 1214 dbSqlOnly ? " WHERE isdbsql(sqltext)" : "" 1215 ); 1216 rc = sqlite3_exec(db, zSql, 0, 0, 0); 1217 sqlite3_free(zSql); 1218 if( rc ) fatalError("cannot rebuild: %s", sqlite3_errmsg(db)); 1219 } 1220 1221 /* 1222 ** Return the value of a hexadecimal digit. Return -1 if the input 1223 ** is not a hex digit. 1224 */ 1225 static int hexDigitValue(char c){ 1226 if( c>='0' && c<='9' ) return c - '0'; 1227 if( c>='a' && c<='f' ) return c - 'a' + 10; 1228 if( c>='A' && c<='F' ) return c - 'A' + 10; 1229 return -1; 1230 } 1231 1232 /* 1233 ** Interpret zArg as an integer value, possibly with suffixes. 1234 */ 1235 static int integerValue(const char *zArg){ 1236 sqlite3_int64 v = 0; 1237 static const struct { char *zSuffix; int iMult; } aMult[] = { 1238 { "KiB", 1024 }, 1239 { "MiB", 1024*1024 }, 1240 { "GiB", 1024*1024*1024 }, 1241 { "KB", 1000 }, 1242 { "MB", 1000000 }, 1243 { "GB", 1000000000 }, 1244 { "K", 1000 }, 1245 { "M", 1000000 }, 1246 { "G", 1000000000 }, 1247 }; 1248 int i; 1249 int isNeg = 0; 1250 if( zArg[0]=='-' ){ 1251 isNeg = 1; 1252 zArg++; 1253 }else if( zArg[0]=='+' ){ 1254 zArg++; 1255 } 1256 if( zArg[0]=='0' && zArg[1]=='x' ){ 1257 int x; 1258 zArg += 2; 1259 while( (x = hexDigitValue(zArg[0]))>=0 ){ 1260 v = (v<<4) + x; 1261 zArg++; 1262 } 1263 }else{ 1264 while( ISDIGIT(zArg[0]) ){ 1265 v = v*10 + zArg[0] - '0'; 1266 zArg++; 1267 } 1268 } 1269 for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){ 1270 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ 1271 v *= aMult[i].iMult; 1272 break; 1273 } 1274 } 1275 if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648"); 1276 return (int)(isNeg? -v : v); 1277 } 1278 1279 /* 1280 ** Return the number of "v" characters in a string. Return 0 if there 1281 ** are any characters in the string other than "v". 1282 */ 1283 static int numberOfVChar(const char *z){ 1284 int N = 0; 1285 while( z[0] && z[0]=='v' ){ 1286 z++; 1287 N++; 1288 } 1289 return z[0]==0 ? N : 0; 1290 } 1291 1292 /* 1293 ** Print sketchy documentation for this utility program 1294 */ 1295 static void showHelp(void){ 1296 printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0); 1297 printf( 1298 "Read databases and SQL scripts from SOURCE-DB and execute each script against\n" 1299 "each database, checking for crashes and memory leaks.\n" 1300 "Options:\n" 1301 " --cell-size-check Set the PRAGMA cell_size_check=ON\n" 1302 " --dbid N Use only the database where dbid=N\n" 1303 " --export-db DIR Write databases to files(s) in DIR. Works with --dbid\n" 1304 " --export-sql DIR Write SQL to file(s) in DIR. Also works with --sqlid\n" 1305 " --help Show this help text\n" 1306 " --info Show information about SOURCE-DB w/o running tests\n" 1307 " --limit-mem N Limit memory used by test SQLite instance to N bytes\n" 1308 " --limit-vdbe Panic if any test runs for more than 100,000 cycles\n" 1309 " --load-sql ARGS... Load SQL scripts fron files into SOURCE-DB\n" 1310 " --load-db ARGS... Load template databases from files into SOURCE_DB\n" 1311 " --load-dbsql ARGS.. Load dbsqlfuzz outputs into the xsql table\n" 1312 " -m TEXT Add a description to the database\n" 1313 " --native-vfs Use the native VFS for initially empty database files\n" 1314 " --native-malloc Turn off MEMSYS3/5 and Lookaside\n" 1315 " --oss-fuzz Enable OSS-FUZZ testing\n" 1316 " --prng-seed N Seed value for the PRGN inside of SQLite\n" 1317 " -q|--quiet Reduced output\n" 1318 " --rebuild Rebuild and vacuum the database file\n" 1319 " --result-trace Show the results of each SQL command\n" 1320 " --sqlid N Use only SQL where sqlid=N\n" 1321 " --timeout N Abort if any single test needs more than N seconds\n" 1322 " -v|--verbose Increased output. Repeat for more output.\n" 1323 " --vdbe-debug Activate VDBE debugging.\n" 1324 ); 1325 } 1326 1327 int main(int argc, char **argv){ 1328 sqlite3_int64 iBegin; /* Start time of this program */ 1329 int quietFlag = 0; /* True if --quiet or -q */ 1330 int verboseFlag = 0; /* True if --verbose or -v */ 1331 char *zInsSql = 0; /* SQL statement for --load-db or --load-sql */ 1332 int iFirstInsArg = 0; /* First argv[] for --load-db or --load-sql */ 1333 sqlite3 *db = 0; /* The open database connection */ 1334 sqlite3_stmt *pStmt; /* A prepared statement */ 1335 int rc; /* Result code from SQLite interface calls */ 1336 Blob *pSql; /* For looping over SQL scripts */ 1337 Blob *pDb; /* For looping over template databases */ 1338 int i; /* Loop index for the argv[] loop */ 1339 int dbSqlOnly = 0; /* Only use scripts that are dbsqlfuzz */ 1340 int onlySqlid = -1; /* --sqlid */ 1341 int onlyDbid = -1; /* --dbid */ 1342 int nativeFlag = 0; /* --native-vfs */ 1343 int rebuildFlag = 0; /* --rebuild */ 1344 int vdbeLimitFlag = 0; /* --limit-vdbe */ 1345 int infoFlag = 0; /* --info */ 1346 int timeoutTest = 0; /* undocumented --timeout-test flag */ 1347 int runFlags = 0; /* Flags sent to runSql() */ 1348 char *zMsg = 0; /* Add this message */ 1349 int nSrcDb = 0; /* Number of source databases */ 1350 char **azSrcDb = 0; /* Array of source database names */ 1351 int iSrcDb; /* Loop over all source databases */ 1352 int nTest = 0; /* Total number of tests performed */ 1353 char *zDbName = ""; /* Appreviated name of a source database */ 1354 const char *zFailCode = 0; /* Value of the TEST_FAILURE env variable */ 1355 int cellSzCkFlag = 0; /* --cell-size-check */ 1356 int sqlFuzz = 0; /* True for SQL fuzz. False for DB fuzz */ 1357 int iTimeout = 120; /* Default 120-second timeout */ 1358 int nMem = 0; /* Memory limit override */ 1359 int nMemThisDb = 0; /* Memory limit set by the CONFIG table */ 1360 char *zExpDb = 0; /* Write Databases to files in this directory */ 1361 char *zExpSql = 0; /* Write SQL to files in this directory */ 1362 void *pHeap = 0; /* Heap for use by SQLite */ 1363 int ossFuzz = 0; /* enable OSS-FUZZ testing */ 1364 int ossFuzzThisDb = 0; /* ossFuzz value for this particular database */ 1365 int nativeMalloc = 0; /* Turn off MEMSYS3/5 and lookaside if true */ 1366 sqlite3_vfs *pDfltVfs; /* The default VFS */ 1367 int openFlags4Data; /* Flags for sqlite3_open_v2() */ 1368 int nV; /* How much to increase verbosity with -vvvv */ 1369 1370 sqlite3_initialize(); 1371 iBegin = timeOfDay(); 1372 #ifdef __unix__ 1373 signal(SIGALRM, signalHandler); 1374 signal(SIGSEGV, signalHandler); 1375 signal(SIGABRT, signalHandler); 1376 #endif 1377 g.zArgv0 = argv[0]; 1378 openFlags4Data = SQLITE_OPEN_READONLY; 1379 zFailCode = getenv("TEST_FAILURE"); 1380 pDfltVfs = sqlite3_vfs_find(0); 1381 inmemVfsRegister(1); 1382 for(i=1; i<argc; i++){ 1383 const char *z = argv[i]; 1384 if( z[0]=='-' ){ 1385 z++; 1386 if( z[0]=='-' ) z++; 1387 if( strcmp(z,"cell-size-check")==0 ){ 1388 cellSzCkFlag = 1; 1389 }else 1390 if( strcmp(z,"dbid")==0 ){ 1391 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1392 onlyDbid = integerValue(argv[++i]); 1393 }else 1394 if( strcmp(z,"export-db")==0 ){ 1395 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1396 zExpDb = argv[++i]; 1397 }else 1398 if( strcmp(z,"export-sql")==0 || strcmp(z,"export-dbsql")==0 ){ 1399 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1400 zExpSql = argv[++i]; 1401 }else 1402 if( strcmp(z,"help")==0 ){ 1403 showHelp(); 1404 return 0; 1405 }else 1406 if( strcmp(z,"info")==0 ){ 1407 infoFlag = 1; 1408 }else 1409 if( strcmp(z,"limit-mem")==0 ){ 1410 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1411 nMem = integerValue(argv[++i]); 1412 }else 1413 if( strcmp(z,"limit-vdbe")==0 ){ 1414 vdbeLimitFlag = 1; 1415 }else 1416 if( strcmp(z,"load-sql")==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 break; 1421 }else 1422 if( strcmp(z,"load-db")==0 ){ 1423 zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))"; 1424 iFirstInsArg = i+1; 1425 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 1426 break; 1427 }else 1428 if( strcmp(z,"load-dbsql")==0 ){ 1429 zInsSql = "INSERT INTO xsql(sqltext)VALUES(CAST(readfile(?1) AS text))"; 1430 iFirstInsArg = i+1; 1431 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 1432 dbSqlOnly = 1; 1433 break; 1434 }else 1435 if( strcmp(z,"m")==0 ){ 1436 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1437 zMsg = argv[++i]; 1438 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 1439 }else 1440 if( strcmp(z,"native-malloc")==0 ){ 1441 nativeMalloc = 1; 1442 }else 1443 if( strcmp(z,"native-vfs")==0 ){ 1444 nativeFlag = 1; 1445 }else 1446 if( strcmp(z,"oss-fuzz")==0 ){ 1447 ossFuzz = 1; 1448 }else 1449 if( strcmp(z,"prng-seed")==0 ){ 1450 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1451 g.uRandom = atoi(argv[++i]); 1452 }else 1453 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ 1454 quietFlag = 1; 1455 verboseFlag = 0; 1456 eVerbosity = 0; 1457 }else 1458 if( strcmp(z,"rebuild")==0 ){ 1459 rebuildFlag = 1; 1460 openFlags4Data = SQLITE_OPEN_READWRITE; 1461 }else 1462 if( strcmp(z,"result-trace")==0 ){ 1463 runFlags |= SQL_OUTPUT; 1464 }else 1465 if( strcmp(z,"sqlid")==0 ){ 1466 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1467 onlySqlid = integerValue(argv[++i]); 1468 }else 1469 if( strcmp(z,"timeout")==0 ){ 1470 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1471 iTimeout = integerValue(argv[++i]); 1472 }else 1473 if( strcmp(z,"timeout-test")==0 ){ 1474 timeoutTest = 1; 1475 #ifndef __unix__ 1476 fatalError("timeout is not available on non-unix systems"); 1477 #endif 1478 }else 1479 if( strcmp(z,"vdbe-debug")==0 ){ 1480 bVdbeDebug = 1; 1481 }else 1482 if( strcmp(z,"verbose")==0 ){ 1483 quietFlag = 0; 1484 verboseFlag++; 1485 eVerbosity++; 1486 if( verboseFlag>1 ) runFlags |= SQL_TRACE; 1487 }else 1488 if( (nV = numberOfVChar(z))>=1 ){ 1489 quietFlag = 0; 1490 verboseFlag += nV; 1491 eVerbosity += nV; 1492 if( verboseFlag>1 ) runFlags |= SQL_TRACE; 1493 }else 1494 if( strcmp(z,"version")==0 ){ 1495 int ii; 1496 const char *zz; 1497 printf("SQLite %s %s\n", sqlite3_libversion(), sqlite3_sourceid()); 1498 for(ii=0; (zz = sqlite3_compileoption_get(ii))!=0; ii++){ 1499 printf("%s\n", zz); 1500 } 1501 return 0; 1502 }else 1503 { 1504 fatalError("unknown option: %s", argv[i]); 1505 } 1506 }else{ 1507 nSrcDb++; 1508 azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0])); 1509 azSrcDb[nSrcDb-1] = argv[i]; 1510 } 1511 } 1512 if( nSrcDb==0 ) fatalError("no source database specified"); 1513 if( nSrcDb>1 ){ 1514 if( zMsg ){ 1515 fatalError("cannot change the description of more than one database"); 1516 } 1517 if( zInsSql ){ 1518 fatalError("cannot import into more than one database"); 1519 } 1520 } 1521 1522 /* Process each source database separately */ 1523 for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){ 1524 g.zDbFile = azSrcDb[iSrcDb]; 1525 rc = sqlite3_open_v2(azSrcDb[iSrcDb], &db, 1526 openFlags4Data, pDfltVfs->zName); 1527 if( rc ){ 1528 fatalError("cannot open source database %s - %s", 1529 azSrcDb[iSrcDb], sqlite3_errmsg(db)); 1530 } 1531 1532 /* Print the description, if there is one */ 1533 if( infoFlag ){ 1534 int n; 1535 zDbName = azSrcDb[iSrcDb]; 1536 i = (int)strlen(zDbName) - 1; 1537 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; } 1538 zDbName += i; 1539 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0); 1540 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 1541 printf("%s: %s", zDbName, sqlite3_column_text(pStmt,0)); 1542 }else{ 1543 printf("%s: (empty \"readme\")", zDbName); 1544 } 1545 sqlite3_finalize(pStmt); 1546 sqlite3_prepare_v2(db, "SELECT count(*) FROM db", -1, &pStmt, 0); 1547 if( pStmt 1548 && sqlite3_step(pStmt)==SQLITE_ROW 1549 && (n = sqlite3_column_int(pStmt,0))>0 1550 ){ 1551 printf(" - %d DBs", n); 1552 } 1553 sqlite3_finalize(pStmt); 1554 sqlite3_prepare_v2(db, "SELECT count(*) FROM xsql", -1, &pStmt, 0); 1555 if( pStmt 1556 && sqlite3_step(pStmt)==SQLITE_ROW 1557 && (n = sqlite3_column_int(pStmt,0))>0 1558 ){ 1559 printf(" - %d scripts", n); 1560 } 1561 sqlite3_finalize(pStmt); 1562 printf("\n"); 1563 sqlite3_close(db); 1564 continue; 1565 } 1566 1567 rc = sqlite3_exec(db, 1568 "CREATE TABLE IF NOT EXISTS db(\n" 1569 " dbid INTEGER PRIMARY KEY, -- database id\n" 1570 " dbcontent BLOB -- database disk file image\n" 1571 ");\n" 1572 "CREATE TABLE IF NOT EXISTS xsql(\n" 1573 " sqlid INTEGER PRIMARY KEY, -- SQL script id\n" 1574 " sqltext TEXT -- Text of SQL statements to run\n" 1575 ");" 1576 "CREATE TABLE IF NOT EXISTS readme(\n" 1577 " msg TEXT -- Human-readable description of this file\n" 1578 ");", 0, 0, 0); 1579 if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db)); 1580 if( zMsg ){ 1581 char *zSql; 1582 zSql = sqlite3_mprintf( 1583 "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg); 1584 rc = sqlite3_exec(db, zSql, 0, 0, 0); 1585 sqlite3_free(zSql); 1586 if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db)); 1587 } 1588 ossFuzzThisDb = ossFuzz; 1589 1590 /* If the CONFIG(name,value) table exists, read db-specific settings 1591 ** from that table */ 1592 if( sqlite3_table_column_metadata(db,0,"config",0,0,0,0,0,0)==SQLITE_OK ){ 1593 rc = sqlite3_prepare_v2(db, "SELECT name, value FROM config", 1594 -1, &pStmt, 0); 1595 if( rc ) fatalError("cannot prepare query of CONFIG table: %s", 1596 sqlite3_errmsg(db)); 1597 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 1598 const char *zName = (const char *)sqlite3_column_text(pStmt,0); 1599 if( zName==0 ) continue; 1600 if( strcmp(zName, "oss-fuzz")==0 ){ 1601 ossFuzzThisDb = sqlite3_column_int(pStmt,1); 1602 if( verboseFlag ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb); 1603 } 1604 if( strcmp(zName, "limit-mem")==0 ){ 1605 nMemThisDb = sqlite3_column_int(pStmt,1); 1606 if( verboseFlag ) printf("Config: limit-mem=%d\n", nMemThisDb); 1607 } 1608 } 1609 sqlite3_finalize(pStmt); 1610 } 1611 1612 if( zInsSql ){ 1613 sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0, 1614 readfileFunc, 0, 0); 1615 sqlite3_create_function(db, "isdbsql", 1, SQLITE_UTF8, 0, 1616 isDbSqlFunc, 0, 0); 1617 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0); 1618 if( rc ) fatalError("cannot prepare statement [%s]: %s", 1619 zInsSql, sqlite3_errmsg(db)); 1620 rc = sqlite3_exec(db, "BEGIN", 0, 0, 0); 1621 if( rc ) fatalError("cannot start a transaction"); 1622 for(i=iFirstInsArg; i<argc; i++){ 1623 sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC); 1624 sqlite3_step(pStmt); 1625 rc = sqlite3_reset(pStmt); 1626 if( rc ) fatalError("insert failed for %s", argv[i]); 1627 } 1628 sqlite3_finalize(pStmt); 1629 rc = sqlite3_exec(db, "COMMIT", 0, 0, 0); 1630 if( rc ) fatalError("cannot commit the transaction: %s", 1631 sqlite3_errmsg(db)); 1632 rebuild_database(db, dbSqlOnly); 1633 sqlite3_close(db); 1634 return 0; 1635 } 1636 rc = sqlite3_exec(db, "PRAGMA query_only=1;", 0, 0, 0); 1637 if( rc ) fatalError("cannot set database to query-only"); 1638 if( zExpDb!=0 || zExpSql!=0 ){ 1639 sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0, 1640 writefileFunc, 0, 0); 1641 if( zExpDb!=0 ){ 1642 const char *zExDb = 1643 "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent)," 1644 " dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)" 1645 " FROM db WHERE ?2<0 OR dbid=?2;"; 1646 rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0); 1647 if( rc ) fatalError("cannot prepare statement [%s]: %s", 1648 zExDb, sqlite3_errmsg(db)); 1649 sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb), 1650 SQLITE_STATIC, SQLITE_UTF8); 1651 sqlite3_bind_int(pStmt, 2, onlyDbid); 1652 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 1653 printf("write db-%d (%d bytes) into %s\n", 1654 sqlite3_column_int(pStmt,1), 1655 sqlite3_column_int(pStmt,3), 1656 sqlite3_column_text(pStmt,2)); 1657 } 1658 sqlite3_finalize(pStmt); 1659 } 1660 if( zExpSql!=0 ){ 1661 const char *zExSql = 1662 "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext)," 1663 " sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)" 1664 " FROM xsql WHERE ?2<0 OR sqlid=?2;"; 1665 rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0); 1666 if( rc ) fatalError("cannot prepare statement [%s]: %s", 1667 zExSql, sqlite3_errmsg(db)); 1668 sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql), 1669 SQLITE_STATIC, SQLITE_UTF8); 1670 sqlite3_bind_int(pStmt, 2, onlySqlid); 1671 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 1672 printf("write sql-%d (%d bytes) into %s\n", 1673 sqlite3_column_int(pStmt,1), 1674 sqlite3_column_int(pStmt,3), 1675 sqlite3_column_text(pStmt,2)); 1676 } 1677 sqlite3_finalize(pStmt); 1678 } 1679 sqlite3_close(db); 1680 return 0; 1681 } 1682 1683 /* Load all SQL script content and all initial database images from the 1684 ** source db 1685 */ 1686 blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid, 1687 &g.nSql, &g.pFirstSql); 1688 if( g.nSql==0 ) fatalError("need at least one SQL script"); 1689 blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid, 1690 &g.nDb, &g.pFirstDb); 1691 if( g.nDb==0 ){ 1692 g.pFirstDb = safe_realloc(0, sizeof(Blob)); 1693 memset(g.pFirstDb, 0, sizeof(Blob)); 1694 g.pFirstDb->id = 1; 1695 g.pFirstDb->seq = 0; 1696 g.nDb = 1; 1697 sqlFuzz = 1; 1698 } 1699 1700 /* Print the description, if there is one */ 1701 if( !quietFlag ){ 1702 zDbName = azSrcDb[iSrcDb]; 1703 i = (int)strlen(zDbName) - 1; 1704 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; } 1705 zDbName += i; 1706 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0); 1707 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 1708 printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0)); 1709 } 1710 sqlite3_finalize(pStmt); 1711 } 1712 1713 /* Rebuild the database, if requested */ 1714 if( rebuildFlag ){ 1715 if( !quietFlag ){ 1716 printf("%s: rebuilding... ", zDbName); 1717 fflush(stdout); 1718 } 1719 rebuild_database(db, 0); 1720 if( !quietFlag ) printf("done\n"); 1721 } 1722 1723 /* Close the source database. Verify that no SQLite memory allocations are 1724 ** outstanding. 1725 */ 1726 sqlite3_close(db); 1727 if( sqlite3_memory_used()>0 ){ 1728 fatalError("SQLite has memory in use before the start of testing"); 1729 } 1730 1731 /* Limit available memory, if requested */ 1732 sqlite3_shutdown(); 1733 if( nMemThisDb>0 && nMem==0 ){ 1734 if( !nativeMalloc ){ 1735 pHeap = realloc(pHeap, nMemThisDb); 1736 if( pHeap==0 ){ 1737 fatalError("failed to allocate %d bytes of heap memory", nMem); 1738 } 1739 sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMemThisDb, 128); 1740 }else{ 1741 sqlite3_hard_heap_limit64((sqlite3_int64)nMemThisDb); 1742 } 1743 }else{ 1744 sqlite3_hard_heap_limit64(0); 1745 } 1746 1747 /* Disable lookaside with the --native-malloc option */ 1748 if( nativeMalloc ){ 1749 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0); 1750 } 1751 1752 /* Reset the in-memory virtual filesystem */ 1753 formatVfs(); 1754 1755 /* Run a test using each SQL script against each database. 1756 */ 1757 if( !verboseFlag && !quietFlag ) printf("%s:", zDbName); 1758 for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){ 1759 if( isDbSql(pSql->a, pSql->sz) ){ 1760 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d",pSql->id); 1761 if( verboseFlag ){ 1762 printf("%s\n", g.zTestName); 1763 fflush(stdout); 1764 }else if( !quietFlag ){ 1765 static int prevAmt = -1; 1766 int idx = pSql->seq; 1767 int amt = idx*10/(g.nSql); 1768 if( amt!=prevAmt ){ 1769 printf(" %d%%", amt*10); 1770 fflush(stdout); 1771 prevAmt = amt; 1772 } 1773 } 1774 runCombinedDbSqlInput(pSql->a, pSql->sz); 1775 nTest++; 1776 g.zTestName[0] = 0; 1777 continue; 1778 } 1779 for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){ 1780 int openFlags; 1781 const char *zVfs = "inmem"; 1782 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d", 1783 pSql->id, pDb->id); 1784 if( verboseFlag ){ 1785 printf("%s\n", g.zTestName); 1786 fflush(stdout); 1787 }else if( !quietFlag ){ 1788 static int prevAmt = -1; 1789 int idx = pSql->seq*g.nDb + pDb->id - 1; 1790 int amt = idx*10/(g.nDb*g.nSql); 1791 if( amt!=prevAmt ){ 1792 printf(" %d%%", amt*10); 1793 fflush(stdout); 1794 prevAmt = amt; 1795 } 1796 } 1797 createVFile("main.db", pDb->sz, pDb->a); 1798 sqlite3_randomness(0,0); 1799 if( ossFuzzThisDb ){ 1800 #ifndef SQLITE_OSS_FUZZ 1801 fatalError("--oss-fuzz not supported: recompile" 1802 " with -DSQLITE_OSS_FUZZ"); 1803 #else 1804 extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t); 1805 LLVMFuzzerTestOneInput((const uint8_t*)pSql->a, (size_t)pSql->sz); 1806 #endif 1807 }else{ 1808 openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE; 1809 if( nativeFlag && pDb->sz==0 ){ 1810 openFlags |= SQLITE_OPEN_MEMORY; 1811 zVfs = 0; 1812 } 1813 rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs); 1814 if( rc ) fatalError("cannot open inmem database"); 1815 sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 100000000); 1816 sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 50); 1817 if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags); 1818 setAlarm(iTimeout); 1819 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 1820 if( sqlFuzz || vdbeLimitFlag ){ 1821 sqlite3_progress_handler(db, 100000, progressHandler, 1822 &vdbeLimitFlag); 1823 } 1824 #endif 1825 #ifdef SQLITE_TESTCTRL_PRNG_SEED 1826 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, db); 1827 #endif 1828 if( bVdbeDebug ){ 1829 sqlite3_exec(db, "PRAGMA vdbe_debug=ON", 0, 0, 0); 1830 } 1831 do{ 1832 runSql(db, (char*)pSql->a, runFlags); 1833 }while( timeoutTest ); 1834 setAlarm(0); 1835 sqlite3_exec(db, "PRAGMA temp_store_directory=''", 0, 0, 0); 1836 sqlite3_close(db); 1837 } 1838 if( sqlite3_memory_used()>0 ){ 1839 fatalError("memory leak: %lld bytes outstanding", 1840 sqlite3_memory_used()); 1841 } 1842 reformatVfs(); 1843 nTest++; 1844 g.zTestName[0] = 0; 1845 1846 /* Simulate an error if the TEST_FAILURE environment variable is "5". 1847 ** This is used to verify that automated test script really do spot 1848 ** errors that occur in this test program. 1849 */ 1850 if( zFailCode ){ 1851 if( zFailCode[0]=='5' && zFailCode[1]==0 ){ 1852 fatalError("simulated failure"); 1853 }else if( zFailCode[0]!=0 ){ 1854 /* If TEST_FAILURE is something other than 5, just exit the test 1855 ** early */ 1856 printf("\nExit early due to TEST_FAILURE being set\n"); 1857 iSrcDb = nSrcDb-1; 1858 goto sourcedb_cleanup; 1859 } 1860 } 1861 } 1862 } 1863 if( !quietFlag && !verboseFlag ){ 1864 printf(" 100%% - %d tests\n", g.nDb*g.nSql); 1865 } 1866 1867 /* Clean up at the end of processing a single source database 1868 */ 1869 sourcedb_cleanup: 1870 blobListFree(g.pFirstSql); 1871 blobListFree(g.pFirstDb); 1872 reformatVfs(); 1873 1874 } /* End loop over all source databases */ 1875 1876 if( !quietFlag ){ 1877 sqlite3_int64 iElapse = timeOfDay() - iBegin; 1878 printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n" 1879 "SQLite %s %s\n", 1880 nTest, (int)(iElapse/1000), (int)(iElapse%1000), 1881 sqlite3_libversion(), sqlite3_sourceid()); 1882 } 1883 free(azSrcDb); 1884 free(pHeap); 1885 return 0; 1886 } 1887