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