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