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