Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/test/fuzzcheck.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / test / fuzzcheck.c` 2772 lines ยท 89163 bytes Raw Blame History 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 82 #include 83 #include 84 #include 85 #include 86 #include 87 #include "sqlite3.h" 88 #include "sqlite3recover.h" 89 #define ISSPACE(X) isspace((unsigned char)(X)) 90 #define ISDIGIT(X) isdigit((unsigned char)(X)) 91 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) 92 # define FLEXARRAY 93 #else 94 # define FLEXARRAY 1 95 #endif 96 97 98 #ifdef __unix__ 99 # include 100 # include 101 #endif 102 103 #include 104 #if !defined(_MSC_VER) 105 # include 106 #endif 107 108 #if defined(_MSC_VER) 109 typedef unsigned char uint8_t; 110 #endif 111 typedef sqlite3_uint64 u64; 112 113 /* 114 ** Files in the virtual file system. 115 */ 116 typedef struct VFile VFile; 117 struct VFile { 118 char *zFilename; /* Filename. NULL for delete-on-close. From malloc() */ 119 int sz; /* Size of the file in bytes */ 120 int nRef; /* Number of references to this file */ 121 unsigned char *a; /* Content of the file. From malloc() */ 122 }; 123 typedef struct VHandle VHandle; 124 struct VHandle { 125 sqlite3_file base; /* Base class. Must be first */ 126 VFile *pVFile; /* The underlying file */ 127 }; 128 129 /* 130 ** The value of a database file template, or of an SQL script 131 */ 132 typedef struct Blob Blob; 133 struct Blob { 134 Blob *pNext; /* Next in a list */ 135 int id; /* Id of this Blob */ 136 int seq; /* Sequence number */ 137 int sz; /* Size of this Blob in bytes */ 138 unsigned char a[FLEXARRAY]; /* Blob content. Allocated as needed. */ 139 }; 140 141 /* Size in bytes of a Blob object sufficient to store N byte of content */ 142 #define SZ_BLOB(N) (offsetof(Blob,a) + (((N)+7)&~7)) 143 144 /* 145 ** Maximum number of files in the in-memory virtual filesystem. 146 */ 147 #define MX_FILE 10 148 149 /* 150 ** Maximum allowed file size 151 */ 152 #define MX_FILE_SZ `10000000` 153 154 /* 155 ** All global variables are gathered into the "g" singleton. 156 */ 157 static struct GlobalVars { 158 const char *zArgv0; /* Name of program */ 159 const char *zDbFile; /* Name of database file */ 160 VFile aFile[MX_FILE]; /* The virtual filesystem */ 161 int nDb; /* Number of template databases */ 162 Blob *pFirstDb; /* Content of first template database */ 163 int nSql; /* Number of SQL scripts */ 164 Blob *pFirstSql; /* First SQL script */ 165 unsigned int uRandom; /* Seed for the SQLite PRNG */ 166 unsigned int nInvariant; /* Number of invariant checks run */ 167 char zTestName[100]; /* Name of current test */ 168 } g; 169 170 /* 171 ** Include various extensions. 172 */ 173 extern int sqlite3_vt02_init(sqlite3*,char**,void*); 174 extern int sqlite3_randomjson_init(sqlite3*,char**,void*); 175 extern int sqlite3_series_init(sqlite3*,char**,void*); 176 extern int sqlite3_base64_init(sqlite3*,char**,void*); 177 extern int sqlite3_base85_init(sqlite3*,char**,void*); 178 extern int sqlite3_completion_init(sqlite3*,char**,void*); 179 extern int sqlite3_decimal_init(sqlite3*,char**,void*); 180 extern int sqlite3_diskused_init(sqlite3*,char**,void*); 181 extern int sqlite3_ieee_init(sqlite3*,char**,void*); 182 extern int sqlite3_regexp_init(sqlite3*,char**,void*); 183 extern int sqlite3_shathree_init(sqlite3*,char**,void*); 184 extern int sqlite3_sha_init(sqlite3*,char**,void*); 185 extern int sqlite3_stmtrand_init(sqlite3*,char**,void*); 186 extern int sqlite3_strdup_init(sqlite3*,char**,void*); 187 188 /* 189 ** Print an error message and quit. 190 */ 191 static void fatalError(const char *zFormat, ...){ 192 va_list ap; 193 fprintf(stderr, "%s", g.zArgv0); 194 if( g.zDbFile ) fprintf(stderr, " %s", g.zDbFile); 195 if( g.zTestName[0] ) fprintf(stderr, " (%s)", g.zTestName); 196 fprintf(stderr, ": "); 197 va_start(ap, zFormat); 198 vfprintf(stderr, zFormat, ap); 199 va_end(ap); 200 fprintf(stderr, "\n"); 201 exit(1); 202 } 203 204 /* 205 ** signal handler 206 */ 207 #ifdef __unix__ 208 static void signalHandler(int signum){ 209 const char *zSig; 210 if( signum==SIGABRT ){ 211 zSig = "abort"; 212 }else if( signum==SIGALRM ){ 213 zSig = "timeout"; 214 }else if( signum==SIGSEGV ){ 215 zSig = "segfault"; 216 }else{ 217 zSig = "signal"; 218 } 219 fatalError(zSig); 220 } 221 #endif 222 223 /* 224 ** Set the an alarm to go off after N seconds. Disable the alarm 225 ** if N==0 226 */ 227 static void setAlarm(int N){ 228 #ifdef __unix__ 229 alarm(N); 230 #else 231 (void)N; 232 #endif 233 } 234 235 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 236 /* 237 ** This an SQL progress handler. After an SQL statement has run for 238 ** many steps, we want to interrupt it. This guards against infinite 239 ** loops from recursive common table expressions. 240 ** 241 ** *pVdbeLimitFlag is true if the --limit-vdbe command-line option is used. 242 ** In that case, hitting the progress handler is a fatal error. 243 */ 244 static int progressHandler(void *pVdbeLimitFlag){ 245 if( *(int*)pVdbeLimitFlag ) fatalError("too many VDBE cycles"); 246 return 1; 247 } 248 #endif 249 250 /* 251 ** Reallocate memory. Show an error and quit if unable. 252 */ 253 static void *safe_realloc(void *pOld, int szNew){ 254 void *pNew = realloc(pOld, szNew<=0 ? 1 : szNew); 255 if( pNew==0 ) fatalError("unable to realloc for %d bytes", szNew); 256 return pNew; 257 } 258 259 /* 260 ** Initialize the virtual file system. 261 */ 262 static void formatVfs(void){ 263 int i; 264 for(i=0; i0 ){ 285 fatalError("file %d still open. nRef=%d", i, g.aFile[i].nRef); 286 } 287 g.aFile[i].sz = -1; 288 free(g.aFile[i].a); 289 g.aFile[i].a = 0; 290 g.aFile[i].nRef = 0; 291 } 292 } 293 294 /* 295 ** Find a VFile by name 296 */ 297 static VFile *findVFile(const char *zName){ 298 int i; 299 if( zName==0 ) return 0; 300 for(i=0; i=0; i++){} 318 if( i>=MX_FILE ) return 0; 319 pNew = &g.aFile[i]; 320 if( zName ){ 321 int nName = (int)strlen(zName)+1; 322 pNew->zFilename = safe_realloc(0, nName); 323 memcpy(pNew->zFilename, zName, nName); 324 }else{ 325 pNew->zFilename = 0; 326 } 327 pNew->nRef = 0; 328 pNew->sz = sz; 329 pNew->a = safe_realloc(0, sz); 330 if( sz>0 ) memcpy(pNew->a, pData, sz); 331 return pNew; 332 } 333 334 /* Return true if the line is all zeros */ 335 static int allZero(unsigned char *aLine){ 336 int i; 337 for(i=0; i<16 && aLine[i]==0; i++){} 338 return i==16; 339 } 340 341 /* 342 ** Render a database and query as text that can be input into 343 ** the CLI. 344 */ 345 static void renderDbSqlForCLI( 346 FILE *out, /* Write to this file */ 347 const char *zFile, /* Name of the database file */ 348 unsigned char *aDb, /* Database content */ 349 int nDb, /* Number of bytes in aDb[] */ 350 unsigned char *zSql, /* SQL content */ 351 int nSql /* Bytes of SQL */ 352 ){ 353 fprintf(out, ".print ******* %s *******\n", zFile); 354 if( nDb>100 ){ 355 int i, j; /* Loop counters */ 356 int pgsz; /* Size of each page */ 357 int lastPage = 0; /* Last page number shown */ 358 int iPage; /* Current page number */ 359 unsigned char *aLine; /* Single line to display */ 360 unsigned char buf[16]; /* Fake line */ 361 unsigned char bShow[256]; /* Characters ok to display */ 362 363 memset(bShow, '.', sizeof(bShow)); 364 for(i=' '; i<='~'; i++){ 365 if( i!='{' && i!='}' && i!='"' && i!='\\' ) bShow[i] = i; 366 } 367 pgsz = (aDb[16]<<8) | aDb[17]; 368 if( pgsz==0 ) pgsz = 65536; 369 if( pgsz<512 || (pgsz&(pgsz-1))!=0 ) pgsz = 4096; 370 fprintf(out,".open --hexdb\n"); 371 fprintf(out,"| size %d pagesize %d filename %s\n",nDb,pgsz,zFile); 372 for(i=0; inDb ){ 374 memset(buf, 0, sizeof(buf)); 375 memcpy(buf, aDb+i, nDb-i); 376 aLine = buf; 377 }else{ 378 aLine = aDb + i; 379 } 380 if( allZero(aLine) ) continue; 381 iPage = i/pgsz + 1; 382 if( lastPage!=iPage ){ 383 fprintf(out,"| page %d offset %d\n", iPage, (iPage-1)*pgsz); 384 lastPage = iPage; 385 } 386 fprintf(out,"| %5d:", i-(iPage-1)*pgsz); 387 for(j=0; j<16; j++) fprintf(out," %02x", aLine[j]); 388 fprintf(out," "); 389 for(j=0; j<16; j++){ 390 unsigned char c = (unsigned char)aLine[j]; 391 fputc( bShow[c], stdout); 392 } 393 fputc('\n', stdout); 394 } 395 fprintf(out,"| end %s\n", zFile); 396 }else{ 397 fprintf(out,".open :memory:\n"); 398 } 399 fprintf(out,".testctrl prng_seed 1 db\n"); 400 fprintf(out,".testctrl internal_functions\n"); 401 fprintf(out,"%.*s", nSql, zSql); 402 if( nSql>0 && zSql[nSql-1]!='\n' ) fprintf(out, "\n"); 403 } 404 405 /* 406 ** Find the tail (the last component) of a pathname. 407 */ 408 static const char *pathTail(const char *zPath){ 409 const char *zTail = zPath; 410 while( zPath[0] ){ 411 if( zPath[0]=='/' && zPath[1]!=0 ) zTail = &zPath[1]; 412 #ifndef __unix__ 413 if( zPath[0]=='\\' && zPath[1]!=0 ) zTail = &zPath[1]; 414 #endif 415 zPath++; 416 } 417 return zTail; 418 } 419 420 /* 421 ** Read the complete content of a file into memory. Add a 0x00 terminator 422 ** and return a pointer to the result. 423 ** 424 ** The file content is held in memory obtained from sqlite_malloc64() which 425 ** should be freed by the caller. 426 */ 427 static char *readFile(const char *zFilename, long *sz){ 428 FILE *in; 429 long nIn; 430 unsigned char *pBuf; 431 432 *sz = 0; 433 if( zFilename==0 ) return 0; 434 in = fopen(zFilename, "rb"); 435 if( in==0 ) return 0; 436 fseek(in, 0, SEEK_END); 437 *sz = nIn = ftell(in); 438 rewind(in); 439 pBuf = sqlite3_malloc64( nIn+1 ); 440 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){ 441 pBuf[nIn] = 0; 442 fclose(in); 443 return (char*)pBuf; 444 } 445 sqlite3_free(pBuf); 446 *sz = 0; 447 fclose(in); 448 return 0; 449 } 450 451 452 /* 453 ** Implementation of the "readfile(X)" SQL function. The entire content 454 ** of the file named X is read and returned as a BLOB. NULL is returned 455 ** if the file does not exist or is unreadable. 456 */ 457 static void readfileFunc( 458 sqlite3_context *context, 459 int argc, 460 sqlite3_value **argv 461 ){ 462 long nIn; 463 void *pBuf; 464 const char *zName = (const char*)sqlite3_value_text(argv[0]); 465 466 if( zName==0 ) return; 467 pBuf = readFile(zName, &nIn); 468 if( pBuf ){ 469 sqlite3_result_blob(context, pBuf, nIn, sqlite3_free); 470 } 471 } 472 473 /* 474 ** Implementation of the "readtextfile(X)" SQL function. The text content 475 ** of the file named X through the end of the file or to the first \000 476 ** character, whichever comes first, is read and returned as TEXT. NULL 477 ** is returned if the file does not exist or is unreadable. 478 */ 479 static void readtextfileFunc( 480 sqlite3_context *context, 481 int argc, 482 sqlite3_value **argv 483 ){ 484 const char *zName; 485 FILE *in; 486 long nIn; 487 char *pBuf; 488 489 zName = (const char*)sqlite3_value_text(argv[0]); 490 if( zName==0 ) return; 491 in = fopen(zName, "rb"); 492 if( in==0 ) return; 493 fseek(in, 0, SEEK_END); 494 nIn = ftell(in); 495 rewind(in); 496 pBuf = sqlite3_malloc64( nIn+1 ); 497 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){ 498 pBuf[nIn] = 0; 499 sqlite3_result_text(context, pBuf, -1, sqlite3_free); 500 }else{ 501 sqlite3_free(pBuf); 502 } 503 fclose(in); 504 } 505 506 /* 507 ** Implementation of the "writefile(X,Y)" SQL function. The argument Y 508 ** is written into file X. The number of bytes written is returned. Or 509 ** NULL is returned if something goes wrong, such as being unable to open 510 ** file X for writing. 511 */ 512 static void writefileFunc( 513 sqlite3_context *context, 514 int argc, 515 sqlite3_value **argv 516 ){ 517 FILE *out; 518 const char *z; 519 sqlite3_int64 rc; 520 const char *zFile; 521 522 (void)argc; 523 zFile = (const char*)sqlite3_value_text(argv[0]); 524 if( zFile==0 ) return; 525 out = fopen(zFile, "wb"); 526 if( out==0 ) return; 527 z = (const char*)sqlite3_value_blob(argv[1]); 528 if( z==0 ){ 529 rc = 0; 530 }else{ 531 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out); 532 } 533 fclose(out); 534 sqlite3_result_int64(context, rc); 535 } 536 537 538 /* 539 ** Load a list of Blob objects from the database 540 */ 541 static void blobListLoadFromDb( 542 sqlite3 *db, /* Read from this database */ 543 const char *zSql, /* Query used to extract the blobs */ 544 int firstId, /* First sqlid to load */ 545 int lastId, /* Last sqlid to load */ 546 int *pN, /* OUT: Write number of blobs loaded here */ 547 Blob **ppList /* OUT: Write the head of the blob list here */ 548 ){ 549 Blob *head; 550 Blob *p; 551 sqlite3_stmt *pStmt; 552 int n = 0; 553 int rc; 554 char *z2; 555 union { 556 Blob sBlob; 557 unsigned char tmp[SZ_BLOB(8)]; 558 } uBlob; 559 560 head = &uBlob.sBlob; 561 if( firstId>0 ){ 562 z2 = sqlite3_mprintf("%s WHERE rowid BETWEEN %d AND %d", zSql, 563 firstId, lastId); 564 }else{ 565 z2 = sqlite3_mprintf("%s", zSql); 566 } 567 rc = sqlite3_prepare_v2(db, z2, -1, &pStmt, 0); 568 sqlite3_free(z2); 569 if( rc ) fatalError("%s", sqlite3_errmsg(db)); 570 head->pNext = 0; 571 p = head; 572 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 573 int sz = sqlite3_column_bytes(pStmt, 1); 574 Blob *pNew = safe_realloc(0, SZ_BLOB(sz+1)); 575 pNew->id = sqlite3_column_int(pStmt, 0); 576 pNew->sz = sz; 577 pNew->seq = n++; 578 pNew->pNext = 0; 579 memcpy(pNew->a, sqlite3_column_blob(pStmt,1), sz); 580 pNew->a[sz] = 0; 581 p->pNext = pNew; 582 p = pNew; 583 } 584 sqlite3_finalize(pStmt); 585 *pN = n; 586 *ppList = head->pNext; 587 } 588 589 /* 590 ** Free a list of Blob objects 591 */ 592 static void blobListFree(Blob *p){ 593 Blob *pNext; 594 while( p ){ 595 pNext = p->pNext; 596 free(p); 597 p = pNext; 598 } 599 } 600 601 /* Return the current wall-clock time 602 ** 603 ** The number of milliseconds since the julian epoch. 604 ** 1907-01-01 00:00:00 -> `210866716800000` 605 ** 2021-01-01 00:00:00 -> `212476176000000` 606 */ 607 static sqlite3_int64 timeOfDay(void){ 608 static sqlite3_vfs *clockVfs = 0; 609 sqlite3_int64 t; 610 if( clockVfs==0 ){ 611 clockVfs = sqlite3_vfs_find(0); 612 if( clockVfs==0 ) return 0; 613 } 614 if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){ 615 clockVfs->xCurrentTimeInt64(clockVfs, &t); 616 }else{ 617 double r; 618 clockVfs->xCurrentTime(clockVfs, &r); 619 t = (sqlite3_int64)(r*`86400000`.0); 620 } 621 return t; 622 } 623 624 /*************************************************************************** 625 ** Code to process combined database+SQL scripts generated by the 626 ** dbsqlfuzz fuzzer. 627 */ 628 629 /* An instance of the following object is passed by pointer as the 630 ** client data to various callbacks. 631 */ 632 typedef struct FuzzCtx { 633 sqlite3 *db; /* The database connection */ 634 sqlite3_int64 iCutoffTime; /* Stop processing at this time. */ 635 sqlite3_int64 iLastCb; /* Time recorded for previous progress callback */ 636 sqlite3_int64 mxInterval; /* Longest interval between two progress calls */ 637 unsigned nCb; /* Number of progress callbacks */ 638 unsigned mxCb; /* Maximum number of progress callbacks allowed */ 639 unsigned execCnt; /* Number of calls to the sqlite3_exec callback */ 640 int timeoutHit; /* True when reaching a timeout */ 641 } FuzzCtx; 642 643 /* Verbosity level for the dbsqlfuzz test runner */ 644 static int eVerbosity = 0; 645 646 /* True to activate PRAGMA vdbe_debug=on */ 647 static int bVdbeDebug = 0; 648 649 /* Timeout for each fuzzing attempt, in milliseconds */ 650 static int giTimeout = 10000; /* Defaults to 10 seconds */ 651 652 /* Maximum number of progress handler callbacks */ 653 static unsigned int mxProgressCb = 2000; 654 655 /* Maximum string length in SQLite */ 656 static int lengthLimit = `1000000`; 657 658 /* Maximum expression depth */ 659 static int depthLimit = 500; 660 661 /* Limit on the amount of heap memory that can be used */ 662 static sqlite3_int64 heapLimit = `100000000`; 663 664 /* Maximum byte-code program length in SQLite */ 665 static int vdbeOpLimit = 25000; 666 667 /* Maximum size of the in-memory database */ 668 static sqlite3_int64 maxDbSize = `104857600`; 669 /* OOM simulation parameters */ 670 static unsigned int oomCounter = 0; /* Simulate OOM when equals 1 */ 671 static unsigned int oomRepeat = 0; /* Number of OOMs in a row */ 672 static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */ 673 674 /* Enable recovery */ 675 static int bNoRecover = 0; 676 677 /* This routine is called when a simulated OOM occurs. It is broken 678 ** out as a separate routine to make it easy to set a breakpoint on 679 ** the OOM 680 */ 681 void oomFault(void){ 682 if( eVerbosity ){ 683 printf("Simulated OOM fault\n"); 684 } 685 if( oomRepeat>0 ){ 686 oomRepeat--; 687 }else{ 688 oomCounter--; 689 } 690 } 691 692 /* This routine is a replacement malloc() that is used to simulate 693 ** Out-Of-Memory (OOM) errors for testing purposes. 694 */ 695 static void *oomMalloc(int nByte){ 696 if( oomCounter ){ 697 if( oomCounter==1 ){ 698 oomFault(); 699 return 0; 700 }else{ 701 oomCounter--; 702 } 703 } 704 return defaultMalloc(nByte); 705 } 706 707 /* Register the OOM simulator. This must occur before any memory 708 ** allocations */ 709 static void registerOomSimulator(void){ 710 sqlite3_mem_methods mem; 711 sqlite3_shutdown(); 712 sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem); 713 defaultMalloc = mem.xMalloc; 714 mem.xMalloc = oomMalloc; 715 sqlite3_config(SQLITE_CONFIG_MALLOC, &mem); 716 } 717 718 /* Turn off any pending OOM simulation */ 719 static void disableOom(void){ 720 oomCounter = 0; 721 oomRepeat = 0; 722 } 723 724 /* 725 ** Translate a single byte of Hex into an integer. 726 ** This routine only works if h really is a valid hexadecimal 727 ** character: 0..9a..fA..F 728 */ 729 static unsigned char hexToInt(unsigned int h){ 730 #ifdef SQLITE_EBCDIC 731 h += 9*(1&~(h>>4)); /* EBCDIC */ 732 #else 733 h += 9*(1&(h>>6)); /* ASCII */ 734 #endif 735 return h & 0xf; 736 } 737 738 /* 739 ** The first character of buffer zIn[0..nIn-1] is a '['. This routine 740 ** checked to see if the buffer holds "[NNNN]" or "[+NNNN]" and if it 741 ** does it makes corresponding changes to the *pK value and *pI value 742 ** and returns true. If the input buffer does not match the patterns, 743 ** no changes are made to either *pK or *pI and this routine returns false. 744 */ 745 static int isOffset( 746 const unsigned char *zIn, /* Text input */ 747 int nIn, /* Bytes of input */ 748 unsigned int *pK, /* half-byte cursor to adjust */ 749 unsigned int *pI /* Input index to adjust */ 750 ){ 751 int i; 752 unsigned int k = 0; 753 unsigned char c; 754 for(i=1; i=nAlloc ){ 807 sqlite3_uint64 newSize; 808 if( nAlloc==MX_FILE_SZ || j>=MX_FILE_SZ ){ 809 if( eVerbosity ){ 810 fprintf(stderr, "Input database too big: max %d bytes\n", 811 MX_FILE_SZ); 812 } 813 sqlite3_free(a); 814 return -1; 815 } 816 newSize = nAlloc*2; 817 if( newSize<=j ){ 818 newSize = (j+4096)&~4095; 819 } 820 if( newSize>MX_FILE_SZ ){ 821 if( j>=MX_FILE_SZ ){ 822 sqlite3_free(a); 823 return -1; 824 } 825 newSize = MX_FILE_SZ; 826 } 827 aNew = sqlite3_realloc64( a, newSize ); 828 if( aNew==0 ){ 829 sqlite3_free(a); 830 return -1; 831 } 832 a = aNew; 833 assert( newSize > nAlloc ); 834 memset(a+nAlloc, 0, (size_t)(newSize - nAlloc)); 835 nAlloc = newSize; 836 } 837 if( j>=(unsigned)mx ){ 838 mx = (j + 4095)&~4095; 839 if( mx>MX_FILE_SZ ) mx = MX_FILE_SZ; 840 } 841 assert( j=p->iCutoffTime; 866 sqlite3_int64 iDiff = iNow - p->iLastCb; 867 /* printf("time-remaining: %lld\n", p->iCutoffTime - iNow); */ 868 if( iDiff > p->mxInterval ) p->mxInterval = iDiff; 869 p->nCb++; 870 if( rc==0 && p->mxCb>0 && p->mxCb<=p->nCb ) rc = 1; 871 if( rc && !p->timeoutHit && eVerbosity>=2 ){ 872 printf("Timeout on progress callback %d\n", p->nCb); 873 fflush(stdout); 874 p->timeoutHit = 1; 875 } 876 return rc; 877 } 878 879 /* 880 ** Flag bits set by block_troublesome_sql() 881 */ 882 #define BTS_SELECT 0x000001 883 #define BTS_NONSELECT 0x000002 884 #define BTS_BADFUNC 0x000004 885 #define BTS_BADPRAGMA 0x000008 /* Sticky for rest of the script */ 886 887 /* 888 ** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and 889 ** "PRAGMA parser_trace" since they can dramatically increase the 890 ** amount of output without actually testing anything useful. 891 ** 892 ** Also block ATTACH if attaching a file from the filesystem. 893 */ 894 static int block_troublesome_sql( 895 void *pClientData, 896 int eCode, 897 const char *zArg1, 898 const char *zArg2, 899 const char *zArg3, 900 const char *zArg4 901 ){ 902 unsigned int *pBtsFlags = (unsigned int*)pClientData; 903 904 (void)zArg3; 905 (void)zArg4; 906 switch( eCode ){ 907 case SQLITE_PRAGMA: { 908 if( sqlite3_stricmp("busy_timeout",zArg1)==0 909 && (zArg2==0 || strtoll(zArg2,0,0)>100 || strtoll(zArg2,0,10)>100) 910 ){ 911 return SQLITE_DENY; 912 }else if( sqlite3_stricmp("hard_heap_limit", zArg1)==0 913 || sqlite3_stricmp("reverse_unordered_selects", zArg1)==0 914 ){ 915 /* BTS_BADPRAGMA is sticky. A hard_heap_limit or 916 ** revert_unordered_selects should inhibit all future attempts 917 ** at verifying query invariants */ 918 *pBtsFlags |= BTS_BADPRAGMA; 919 }else if( eVerbosity==0 ){ 920 if( sqlite3_strnicmp("vdbe_", zArg1, 5)==0 921 || sqlite3_stricmp("parser_trace", zArg1)==0 922 || sqlite3_stricmp("temp_store_directory", zArg1)==0 923 ){ 924 return SQLITE_DENY; 925 } 926 }else if( sqlite3_stricmp("oom",zArg1)==0 927 && zArg2!=0 && zArg2[0]!=0 ){ 928 oomCounter = atoi(zArg2); 929 } 930 *pBtsFlags |= BTS_NONSELECT; 931 break; 932 } 933 case SQLITE_ATTACH: { 934 /* Deny the ATTACH if it is attaching anything other than an in-memory 935 ** database. */ 936 *pBtsFlags |= BTS_NONSELECT; 937 if( zArg1==0 ) return SQLITE_DENY; 938 if( strcmp(zArg1,":memory:")==0 ) return SQLITE_OK; 939 if( sqlite3_strglob("file:*[?]vfs=memdb", zArg1)==0 940 && sqlite3_strglob("file:*[^/a-zA-Z0-9_.]*[?]vfs=memdb", zArg1)!=0 941 ){ 942 return SQLITE_OK; 943 } 944 return SQLITE_DENY; 945 } 946 case SQLITE_SELECT: { 947 *pBtsFlags |= BTS_SELECT; 948 break; 949 } 950 case SQLITE_FUNCTION: { 951 static const char *azBadFuncs[] = { 952 "avg", 953 "count", 954 "cume_dist", 955 "current_date", 956 "current_time", 957 "current_timestamp", 958 "date", 959 "datetime", 960 "decimal_sum", 961 "dense_rank", 962 "first_value", 963 "geopoly_group_bbox", 964 "group_concat", 965 "implies_nonnull_row", 966 "json_group_array", 967 "json_group_object", 968 "julianday", 969 "lag", 970 "last_value", 971 "lead", 972 "max", 973 "min", 974 "nth_value", 975 "ntile", 976 "percent_rank", 977 "random", 978 "randomblob", 979 "rank", 980 "row_number", 981 "sqlite_offset", 982 "strftime", 983 "sum", 984 "time", 985 "total", 986 "unixepoch", 987 }; 988 int first, last; 989 first = 0; 990 last = sizeof(azBadFuncs)/sizeof(azBadFuncs[0]) - 1; 991 do{ 992 int mid = (first+last)/2; 993 int c = sqlite3_stricmp(azBadFuncs[mid], zArg2); 994 if( c<0 ){ 995 first = mid+1; 996 }else if( c>0 ){ 997 last = mid-1; 998 }else{ 999 *pBtsFlags |= BTS_BADFUNC; 1000 break; 1001 } 1002 }while( first<=last ); 1003 break; 1004 } 1005 case SQLITE_READ: { 1006 /* Benign */ 1007 break; 1008 } 1009 default: { 1010 *pBtsFlags |= BTS_NONSELECT; 1011 } 1012 } 1013 return SQLITE_OK; 1014 } 1015 1016 /* Implementation found in fuzzinvariant.c */ 1017 extern int fuzz_invariant( 1018 sqlite3 *db, /* The database connection */ 1019 sqlite3_stmt *pStmt, /* Test statement stopped on an SQLITE_ROW */ 1020 int iCnt, /* Invariant sequence number, starting at 0 */ 1021 int iRow, /* The row number for pStmt */ 1022 int nRow, /* Total number of output rows */ 1023 int *pbCorrupt, /* IN/OUT: Flag indicating a corrupt database file */ 1024 int eVerbosity, /* How much debugging output */ 1025 u64 dbOpt /* Default optimization flags */ 1026 ); 1027 1028 /* Implementation of sqlite_dbdata and sqlite_dbptr */ 1029 extern int sqlite3_dbdata_init(sqlite3*,const char**,void*); 1030 1031 1032 /* 1033 ** This function is used as a callback by the recover extension. Simply 1034 ** print the supplied SQL statement to stdout. 1035 */ 1036 static int recoverSqlCb(void *pCtx, const char *zSql){ 1037 if( eVerbosity>=2 && zSql ){ 1038 printf("%s\n", zSql); 1039 } 1040 return SQLITE_OK; 1041 } 1042 1043 /* 1044 ** This function is called to recover data from the database. 1045 */ 1046 static int recoverDatabase(sqlite3 *db){ 1047 int rc; /* Return code from this routine */ 1048 const char *zRecoveryDb = ""; /* Name of "recovery" database */ 1049 const char *zLAF = "lost_and_found"; /* Name of "lost_and_found" table */ 1050 int bFreelist = 1; /* True to scan the freelist */ 1051 int bRowids = 1; /* True to restore ROWID values */ 1052 sqlite3_recover *p = 0; /* The recovery object */ 1053 1054 p = sqlite3_recover_init_sql(db, "main", recoverSqlCb, 0); 1055 sqlite3_recover_config(p, 789, (void*)zRecoveryDb); 1056 sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF); 1057 sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids); 1058 sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist); 1059 sqlite3_recover_run(p); 1060 if( sqlite3_recover_errcode(p)!=SQLITE_OK ){ 1061 const char *zErr = sqlite3_recover_errmsg(p); 1062 int errCode = sqlite3_recover_errcode(p); 1063 if( eVerbosity>0 ){ 1064 printf("recovery error: %s (%d)\n", zErr, errCode); 1065 } 1066 } 1067 rc = sqlite3_recover_finish(p); 1068 if( eVerbosity>0 && rc ){ 1069 printf("recovery returns error code %d\n", rc); 1070 } 1071 return rc; 1072 } 1073 1074 /* 1075 ** Special parameter binding, for testing and debugging purposes. 1076 ** 1077 ** $int_NNN -> integer value NNN 1078 ** $text_TTTT -> floating point value TTT with destructor 1079 ** $carray_clr -> First argument to carray() for color names 1080 ** $carray_primes -> First argument to carray() for prime numbers 1081 */ 1082 static void bindDebugParameters(sqlite3_stmt *pStmt){ 1083 int nVar = sqlite3_bind_parameter_count(pStmt); 1084 int i; 1085 for(i=1; i<=nVar; i++){ 1086 const char *zVar = sqlite3_bind_parameter_name(pStmt, i); 1087 if( zVar==0 ) continue; 1088 #ifdef SQLITE_ENABLE_CARRAY 1089 if( strcmp(zVar,"$carray_clr")==0 ){ 1090 static char *azColorNames[] = { 1091 "azure", "black", "blue", "brown", "cyan", "fuchsia", "gold", 1092 "gray", "green", "indigo", "khaki", "lime", "magenta", "maroon", 1093 "navy", "olive", "orange", "pink", "purple", "red", "silver", 1094 "tan", "teal", "violet", "white", "yellow" 1095 }; 1096 sqlite3_carray_bind(pStmt,i,azColorNames,26,SQLITE_CARRAY_TEXT,0); 1097 }else 1098 if( strcmp(zVar,"$carray_primes")==0 ){ 1099 static int aPrimes[] = { 1100 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 1101 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 1102 }; 1103 sqlite3_carray_bind(pStmt,i,aPrimes,26,SQLITE_CARRAY_INT32,0); 1104 }else 1105 #endif 1106 if( strncmp(zVar, "$int_", 5)==0 ){ 1107 sqlite3_bind_int(pStmt, i, atoi(&zVar[5])); 1108 }else 1109 if( strncmp(zVar, "$text_", 6)==0 ){ 1110 size_t szVar = strlen(zVar); 1111 char *zBuf = sqlite3_malloc64( szVar-5 ); 1112 if( zBuf ){ 1113 memcpy(zBuf, &zVar[6], szVar-5); 1114 sqlite3_bind_text64(pStmt, i, zBuf, szVar-6, sqlite3_free, SQLITE_UTF8); 1115 } 1116 } 1117 } 1118 } 1119 1120 /* 1121 ** Run the SQL text 1122 */ 1123 static int runDbSql( 1124 sqlite3 *db, /* Run SQL on this database connection */ 1125 const char *zSql, /* The SQL to be run */ 1126 unsigned int *pBtsFlags, 1127 u64 dbOpt /* Default optimization flags */ 1128 ){ 1129 int rc; 1130 sqlite3_stmt *pStmt; 1131 int bCorrupt = 0; 1132 while( isspace(zSql[0]&0x7f) ) zSql++; 1133 if( zSql[0]==0 ) return SQLITE_OK; 1134 if( eVerbosity>=4 ){ 1135 printf("RUNNING-SQL: [%s]\n", zSql); 1136 fflush(stdout); 1137 } 1138 (*pBtsFlags) &= BTS_BADPRAGMA; 1139 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 1140 if( rc==SQLITE_OK ){ 1141 int nRow = 0; 1142 bindDebugParameters(pStmt); 1143 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){ 1144 nRow++; 1145 if( eVerbosity>=4 ){ 1146 int j; 1147 for(j=0; j=5 ) */ 1192 } /* End while( SQLITE_ROW */ 1193 if( rc==SQLITE_DONE ){ 1194 if( (*pBtsFlags)==BTS_SELECT 1195 && !sqlite3_stmt_isexplain(pStmt) 1196 && nRow>0 1197 ){ 1198 int iRow = 0; 1199 sqlite3_reset(pStmt); 1200 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 1201 int iCnt = 0; 1202 iRow++; 1203 for(iCnt=0; iCnt<99999; iCnt++){ 1204 rc = fuzz_invariant(db, pStmt, iCnt, iRow, nRow, 1205 &bCorrupt, eVerbosity, dbOpt); 1206 if( rc==SQLITE_DONE ) break; 1207 if( rc!=SQLITE_ERROR ) g.nInvariant++; 1208 if( eVerbosity>0 ){ 1209 if( rc==SQLITE_OK ){ 1210 printf("invariant-check: ok\n"); 1211 }else if( rc==SQLITE_CORRUPT ){ 1212 printf("invariant-check: failed due to database corruption\n"); 1213 } 1214 } 1215 } 1216 } 1217 } 1218 }else if( eVerbosity>=4 ){ 1219 printf("SQL-ERROR: (%d) %s\n", rc, sqlite3_errmsg(db)); 1220 fflush(stdout); 1221 } 1222 }else if( eVerbosity>=4 ){ 1223 printf("SQL-ERROR (%d): %s\n", rc, sqlite3_errmsg(db)); 1224 fflush(stdout); 1225 } /* End if( SQLITE_OK ) */ 1226 return sqlite3_finalize(pStmt); 1227 } 1228 1229 /* Mappings into dbconfig settings for bits taken from bytes 72..75 of 1230 ** the input database. 1231 ** 1232 ** This should be the same as in dbsqlfuzz.c. Make sure those codes stay 1233 ** in sync. 1234 */ 1235 static const struct { 1236 unsigned int mask; 1237 int iSetting; 1238 char *zName; 1239 } aDbConfigSettings[] = { 1240 { 0x0001, SQLITE_DBCONFIG_ENABLE_FKEY, "enable_fkey" }, 1241 { 0x0002, SQLITE_DBCONFIG_ENABLE_TRIGGER, "enable_trigger" }, 1242 { 0x0004, SQLITE_DBCONFIG_ENABLE_VIEW, "enable_view" }, 1243 { 0x0008, SQLITE_DBCONFIG_ENABLE_QPSG, "enable_qpsg" }, 1244 { 0x0010, SQLITE_DBCONFIG_TRIGGER_EQP, "trigger_eqp" }, 1245 { 0x0020, SQLITE_DBCONFIG_DEFENSIVE, "defensive" }, 1246 { 0x0040, SQLITE_DBCONFIG_WRITABLE_SCHEMA, "writable_schema" }, 1247 { 0x0080, SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, "legacy_alter_table" }, 1248 { 0x0100, SQLITE_DBCONFIG_STMT_SCANSTATUS, "stmt_scanstatus" }, 1249 { 0x0200, SQLITE_DBCONFIG_REVERSE_SCANORDER, "reverse_scanorder" }, 1250 #ifdef SQLITE_DBCONFIG_STRICT_AGGREGATE 1251 { 0x0400, SQLITE_DBCONFIG_STRICT_AGGREGATE, "strict_aggregate" }, 1252 #endif 1253 { 0x0800, SQLITE_DBCONFIG_DQS_DML, "dqs_dml" }, 1254 { 0x1000, SQLITE_DBCONFIG_DQS_DDL, "dqs_ddl" }, 1255 { 0x2000, SQLITE_DBCONFIG_TRUSTED_SCHEMA, "trusted_schema" }, 1256 }; 1257 1258 /* Toggle a dbconfig setting 1259 */ 1260 static void toggleDbConfig(sqlite3 *db, int iSetting){ 1261 int v = 0; 1262 sqlite3_db_config(db, iSetting, -1, &v); 1263 v = !v; 1264 sqlite3_db_config(db, iSetting, v, 0); 1265 } 1266 1267 /* Invoke this routine to run a single test case */ 1268 int runCombinedDbSqlInput( 1269 const uint8_t *aData, /* Combined DB+SQL content */ 1270 size_t nByte, /* Size of aData in bytes */ 1271 int iTimeout, /* Use this timeout */ 1272 int bScript, /* If true, just render CLI output */ 1273 int iSqlId /* SQL identifier */ 1274 ){ 1275 int rc; /* SQLite API return value */ 1276 int iSql; /* Index in aData[] of start of SQL */ 1277 unsigned char *aDb = 0; /* Decoded database content */ 1278 int nDb = 0; /* Size of the decoded database */ 1279 int i; /* Loop counter */ 1280 int j; /* Start of current SQL statement */ 1281 char *zSql = 0; /* SQL text to run */ 1282 int nSql; /* Bytes of SQL text */ 1283 FuzzCtx cx; /* Fuzzing context */ 1284 unsigned int btsFlags = 0; /* Parsing flags */ 1285 unsigned int dbFlags = 0; /* Flag values from db offset 72..75 */ 1286 u64 dbOpt = 0; /* Flag values from db offset 76..83 */ 1287 1288 1289 if( nByte<10 ) return 0; 1290 if( sqlite3_initialize() ) return 0; 1291 if( sqlite3_memory_used()!=0 ){ 1292 int nAlloc = 0; 1293 int nNotUsed = 0; 1294 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0); 1295 fprintf(stderr,"memory leak prior to test start:" 1296 " %lld bytes in %d allocations\n", 1297 sqlite3_memory_used(), nAlloc); 1298 exit(1); 1299 } 1300 memset(&cx, 0, sizeof(cx)); 1301 iSql = decodeDatabase((unsigned char*)aData, (int)nByte, &aDb, &nDb); 1302 if( iSql<0 ) return 0; 1303 if( nDb>=75 ){ 1304 dbFlags = ((unsigned int)aDb[72]<<24) + ((unsigned int)aDb[73]<<16) + 1305 ((unsigned int)aDb[74]<<8) + (unsigned int)aDb[75]; 1306 } 1307 if( nDb>=79 ){ 1308 dbOpt = ((u64)aDb[76]<<24) + ((u64)aDb[77]<<16) + 1309 ((u64)aDb[78]<<8) + (u64)aDb[79]; 1310 } 1311 if( nDb>=83 ){ 1312 dbOpt |= ((u64)aDb[80]<<56) + ((u64)aDb[77]<<48) + 1313 ((u64)aDb[78]<<40) + ((u64)aDb[79]<<32); 1314 } 1315 nSql = (int)(nByte - iSql); 1316 if( bScript ){ 1317 char zName[100]; 1318 sqlite3_snprintf(sizeof(zName),zName,"dbsql%06d.db",iSqlId); 1319 renderDbSqlForCLI(stdout, zName, aDb, nDb, 1320 (unsigned char*)(aData+iSql), nSql); 1321 sqlite3_free(aDb); 1322 return 0; 1323 } 1324 if( eVerbosity>=3 ){ 1325 printf( 1326 "****** %d-byte input, %d-byte database, %d-byte script " 1327 "******\n", (int)nByte, nDb, nSql); 1328 fflush(stdout); 1329 } 1330 rc = sqlite3_open(0, &cx.db); 1331 if( rc ){ 1332 sqlite3_free(aDb); 1333 return 1; 1334 } 1335 sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, cx.db, dbOpt); 1336 for(i=0; i0 ){ 1360 sqlite3_limit(cx.db, SQLITE_LIMIT_VDBE_OP, vdbeOpLimit); 1361 } 1362 if( lengthLimit>0 ){ 1363 sqlite3_limit(cx.db, SQLITE_LIMIT_LENGTH, lengthLimit); 1364 } 1365 if( depthLimit>0 ){ 1366 sqlite3_limit(cx.db, SQLITE_LIMIT_EXPR_DEPTH, depthLimit); 1367 } 1368 sqlite3_limit(cx.db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 100); 1369 sqlite3_hard_heap_limit64(heapLimit); 1370 rc = 1; 1371 sqlite3_test_control(SQLITE_TESTCTRL_JSON_SELFCHECK, &rc); 1372 1373 if( nDb>=20 && aDb[18]==2 && aDb[19]==2 ){ 1374 aDb[18] = aDb[19] = 1; 1375 } 1376 rc = sqlite3_deserialize(cx.db, "main", aDb, nDb, nDb, 1377 SQLITE_DESERIALIZE_RESIZEABLE | 1378 SQLITE_DESERIALIZE_FREEONCLOSE); 1379 if( rc ){ 1380 fprintf(stderr, "sqlite3_deserialize() failed with %d\n", rc); 1381 goto testrun_finished; 1382 } 1383 if( maxDbSize>0 ){ 1384 sqlite3_int64 x = maxDbSize; 1385 sqlite3_file_control(cx.db, "main", SQLITE_FCNTL_SIZE_LIMIT, &x); 1386 } 1387 1388 /* For high debugging levels, turn on debug mode */ 1389 if( eVerbosity>=5 ){ 1390 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON;", 0, 0, 0); 1391 } 1392 1393 /* Block debug pragmas and ATTACH/DETACH. But wait until after 1394 ** deserialize to do this because deserialize depends on ATTACH */ 1395 sqlite3_set_authorizer(cx.db, block_troublesome_sql, &btsFlags); 1396 1397 /* Add the vt02 virtual table */ 1398 sqlite3_vt02_init(cx.db, 0, 0); 1399 1400 /* Activate extensions */ 1401 sqlite3_randomjson_init(cx.db, 0, 0); 1402 sqlite3_series_init(cx.db, 0, 0); 1403 sqlite3_base64_init(cx.db, 0, 0); 1404 sqlite3_base85_init(cx.db, 0, 0); 1405 sqlite3_completion_init(cx.db, 0, 0); 1406 sqlite3_decimal_init(cx.db, 0, 0); 1407 sqlite3_diskused_init(cx.db, 0, 0); 1408 sqlite3_ieee_init(cx.db, 0, 0); 1409 sqlite3_regexp_init(cx.db, 0, 0); 1410 sqlite3_shathree_init(cx.db, 0, 0); 1411 sqlite3_sha_init(cx.db, 0, 0); 1412 sqlite3_stmtrand_init(cx.db, 0, 0); 1413 sqlite3_strdup_init(cx.db, 0, 0); 1414 1415 /* Add support for sqlite_dbdata and sqlite_dbptr virtual tables used 1416 ** by the recovery API */ 1417 sqlite3_dbdata_init(cx.db, 0, 0); 1418 1419 /* Consistent PRNG seed */ 1420 #ifdef SQLITE_TESTCTRL_PRNG_SEED 1421 sqlite3_table_column_metadata(cx.db, 0, "x", 0, 0, 0, 0, 0, 0); 1422 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, cx.db); 1423 #else 1424 sqlite3_randomness(0,0); 1425 #endif 1426 1427 /* Run recovery on the initial database, just to make sure recovery 1428 ** works. */ 1429 if( !bNoRecover ){ 1430 recoverDatabase(cx.db); 1431 } 1432 1433 zSql = sqlite3_malloc( nSql + 1 ); 1434 if( zSql==0 ){ 1435 fprintf(stderr, "Out of memory!\n"); 1436 }else{ 1437 memcpy(zSql, aData+iSql, nSql); 1438 zSql[nSql] = 0; 1439 for(i=j=0; zSql[i]; i++){ 1440 if( zSql[i]==';' ){ 1441 char cSaved = zSql[i+1]; 1442 zSql[i+1] = 0; 1443 if( sqlite3_complete(zSql+j) ){ 1444 rc = runDbSql(cx.db, zSql+j, &btsFlags, dbOpt); 1445 j = i+1; 1446 } 1447 zSql[i+1] = cSaved; 1448 if( rc==SQLITE_INTERRUPT || progress_handler(&cx) ){ 1449 goto testrun_finished; 1450 } 1451 } 1452 } 1453 if( j=2 && !bScript ){ 1464 fprintf(stdout, "Peak memory usages: %f MB\n", 1465 sqlite3_memory_highwater(1) / `1000000`.0); 1466 } 1467 if( sqlite3_memory_used()!=0 ){ 1468 int nAlloc = 0; 1469 int nNotUsed = 0; 1470 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0); 1471 fprintf(stderr,"Memory leak: %lld bytes in %d allocations\n", 1472 sqlite3_memory_used(), nAlloc); 1473 exit(1); 1474 } 1475 sqlite3_hard_heap_limit64(0); 1476 sqlite3_soft_heap_limit64(0); 1477 return 0; 1478 } 1479 1480 /* 1481 ** END of the dbsqlfuzz code 1482 ***************************************************************************/ 1483 1484 /* Look at a SQL text and try to determine if it begins with a database 1485 ** description, such as would be found in a dbsqlfuzz test case. Return 1486 ** true if this does appear to be a dbsqlfuzz test case and false otherwise. 1487 */ 1488 static int isDbSql(unsigned char *a, int n){ 1489 unsigned char buf[12]; 1490 int i; 1491 if( n>4 && memcmp(a,"\n--\n",4)==0 ) return 1; 1492 while( n>0 && isspace(a[0]) ){ a++; n--; } 1493 for(i=0; n>0 && i<8; n--, a++){ 1494 if( isxdigit(a[0]) ) buf[i++] = a[0]; 1495 } 1496 if( i==8 && memcmp(buf,"`53514c69`",8)==0 ) return 1; 1497 return 0; 1498 } 1499 1500 /* Implementation of the isdbsql(TEXT) SQL function. 1501 */ 1502 static void isDbSqlFunc( 1503 sqlite3_context *context, 1504 int argc, 1505 sqlite3_value **argv 1506 ){ 1507 int n = sqlite3_value_bytes(argv[0]); 1508 unsigned char *a = (unsigned char*)sqlite3_value_blob(argv[0]); 1509 sqlite3_result_int(context, a!=0 && n>0 && isDbSql(a,n)); 1510 } 1511 1512 /* Methods for the VHandle object 1513 */ 1514 static int inmemClose(sqlite3_file *pFile){ 1515 VHandle *p = (VHandle*)pFile; 1516 VFile *pVFile = p->pVFile; 1517 pVFile->nRef--; 1518 if( pVFile->nRef==0 && pVFile->zFilename==0 ){ 1519 pVFile->sz = -1; 1520 free(pVFile->a); 1521 pVFile->a = 0; 1522 } 1523 return SQLITE_OK; 1524 } 1525 static int inmemRead( 1526 sqlite3_file *pFile, /* Read from this open file */ 1527 void *pData, /* Store content in this buffer */ 1528 int iAmt, /* Bytes of content */ 1529 sqlite3_int64 iOfst /* Start reading here */ 1530 ){ 1531 VHandle *pHandle = (VHandle*)pFile; 1532 VFile *pVFile = pHandle->pVFile; 1533 if( iOfst<0 || iOfst>=pVFile->sz ){ 1534 memset(pData, 0, iAmt); 1535 return SQLITE_IOERR_SHORT_READ; 1536 } 1537 if( iOfst+iAmt>pVFile->sz ){ 1538 memset(pData, 0, iAmt); 1539 iAmt = (int)(pVFile->sz - iOfst); 1540 memcpy(pData, pVFile->a + iOfst, iAmt); 1541 return SQLITE_IOERR_SHORT_READ; 1542 } 1543 memcpy(pData, pVFile->a + iOfst, iAmt); 1544 return SQLITE_OK; 1545 } 1546 static int inmemWrite( 1547 sqlite3_file *pFile, /* Write to this file */ 1548 const void *pData, /* Content to write */ 1549 int iAmt, /* bytes to write */ 1550 sqlite3_int64 iOfst /* Start writing here */ 1551 ){ 1552 VHandle *pHandle = (VHandle*)pFile; 1553 VFile *pVFile = pHandle->pVFile; 1554 if( iOfst+iAmt > pVFile->sz ){ 1555 if( iOfst+iAmt >= MX_FILE_SZ ){ 1556 return SQLITE_FULL; 1557 } 1558 pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt)); 1559 if( iOfst > pVFile->sz ){ 1560 memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz)); 1561 } 1562 pVFile->sz = (int)(iOfst + iAmt); 1563 } 1564 memcpy(pVFile->a + iOfst, pData, iAmt); 1565 return SQLITE_OK; 1566 } 1567 static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){ 1568 VHandle *pHandle = (VHandle*)pFile; 1569 VFile *pVFile = pHandle->pVFile; 1570 if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize; 1571 return SQLITE_OK; 1572 } 1573 static int inmemSync(sqlite3_file *pFile, int flags){ 1574 return SQLITE_OK; 1575 } 1576 static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){ 1577 *pSize = ((VHandle*)pFile)->pVFile->sz; 1578 return SQLITE_OK; 1579 } 1580 static int inmemLock(sqlite3_file *pFile, int type){ 1581 return SQLITE_OK; 1582 } 1583 static int inmemUnlock(sqlite3_file *pFile, int type){ 1584 return SQLITE_OK; 1585 } 1586 static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){ 1587 *pOut = 0; 1588 return SQLITE_OK; 1589 } 1590 static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){ 1591 return SQLITE_NOTFOUND; 1592 } 1593 static int inmemSectorSize(sqlite3_file *pFile){ 1594 return 512; 1595 } 1596 static int inmemDeviceCharacteristics(sqlite3_file *pFile){ 1597 return 1598 SQLITE_IOCAP_SAFE_APPEND | 1599 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | 1600 SQLITE_IOCAP_POWERSAFE_OVERWRITE; 1601 } 1602 1603 1604 /* Method table for VHandle 1605 */ 1606 static sqlite3_io_methods VHandleMethods = { 1607 /* iVersion */ 1, 1608 /* xClose */ inmemClose, 1609 /* xRead */ inmemRead, 1610 /* xWrite */ inmemWrite, 1611 /* xTruncate */ inmemTruncate, 1612 /* xSync */ inmemSync, 1613 /* xFileSize */ inmemFileSize, 1614 /* xLock */ inmemLock, 1615 /* xUnlock */ inmemUnlock, 1616 /* xCheck... */ inmemCheckReservedLock, 1617 /* xFileCtrl */ inmemFileControl, 1618 /* xSectorSz */ inmemSectorSize, 1619 /* xDevchar */ inmemDeviceCharacteristics, 1620 /* xShmMap */ 0, 1621 /* xShmLock */ 0, 1622 /* xShmBarrier */ 0, 1623 /* xShmUnmap */ 0, 1624 /* xFetch */ 0, 1625 /* xUnfetch */ 0 1626 }; 1627 1628 /* 1629 ** Open a new file in the inmem VFS. All files are anonymous and are 1630 ** delete-on-close. 1631 */ 1632 static int inmemOpen( 1633 sqlite3_vfs *pVfs, 1634 const char *zFilename, 1635 sqlite3_file *pFile, 1636 int openFlags, 1637 int *pOutFlags 1638 ){ 1639 VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)""); 1640 VHandle *pHandle = (VHandle*)pFile; 1641 if( pVFile==0 ){ 1642 return SQLITE_FULL; 1643 } 1644 pHandle->pVFile = pVFile; 1645 pVFile->nRef++; 1646 pFile->pMethods = &VHandleMethods; 1647 if( pOutFlags ) *pOutFlags = openFlags; 1648 return SQLITE_OK; 1649 } 1650 1651 /* 1652 ** Delete a file by name 1653 */ 1654 static int inmemDelete( 1655 sqlite3_vfs *pVfs, 1656 const char *zFilename, 1657 int syncdir 1658 ){ 1659 VFile *pVFile = findVFile(zFilename); 1660 if( pVFile==0 ) return SQLITE_OK; 1661 if( pVFile->nRef==0 ){ 1662 free(pVFile->zFilename); 1663 pVFile->zFilename = 0; 1664 pVFile->sz = -1; 1665 free(pVFile->a); 1666 pVFile->a = 0; 1667 return SQLITE_OK; 1668 } 1669 return SQLITE_IOERR_DELETE; 1670 } 1671 1672 /* Check for the existence of a file 1673 */ 1674 static int inmemAccess( 1675 sqlite3_vfs *pVfs, 1676 const char *zFilename, 1677 int flags, 1678 int *pResOut 1679 ){ 1680 VFile *pVFile = findVFile(zFilename); 1681 *pResOut = pVFile!=0; 1682 return SQLITE_OK; 1683 } 1684 1685 /* Get the canonical pathname for a file 1686 */ 1687 static int inmemFullPathname( 1688 sqlite3_vfs *pVfs, 1689 const char *zFilename, 1690 int nOut, 1691 char *zOut 1692 ){ 1693 sqlite3_snprintf(nOut, zOut, "%s", zFilename); 1694 return SQLITE_OK; 1695 } 1696 1697 /* Always use the same random see, for repeatability. 1698 */ 1699 static int inmemRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ 1700 memset(zBuf, 0, nBuf); 1701 memcpy(zBuf, &g.uRandom, nBufxSleep; 1721 inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64; 1722 sqlite3_vfs_register(&inmemVfs, makeDefault); 1723 }; 1724 1725 /* 1726 ** Allowed values for the runFlags parameter to runSql() 1727 */ 1728 #define SQL_TRACE 0x0001 /* Print each SQL statement as it is prepared */ 1729 #define SQL_OUTPUT 0x0002 /* Show the SQL output */ 1730 1731 /* 1732 ** Run multiple commands of SQL. Similar to sqlite3_exec(), but does not 1733 ** stop if an error is encountered. 1734 */ 1735 static void runSql(sqlite3 *db, const char *zSql, unsigned runFlags){ 1736 const char *zMore; 1737 sqlite3_stmt *pStmt; 1738 1739 while( zSql && zSql[0] ){ 1740 zMore = 0; 1741 pStmt = 0; 1742 sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore); 1743 if( zMore==zSql ) break; 1744 if( runFlags & SQL_TRACE ){ 1745 const char *z = zSql; 1746 int n; 1747 while( z0 && ISSPACE(z[n-1]) ) n--; 1750 if( n==0 ) break; 1751 if( pStmt==0 ){ 1752 printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db)); 1753 }else{ 1754 printf("TRACE: %.*s\n", n, z); 1755 } 1756 } 1757 zSql = zMore; 1758 if( pStmt ){ 1759 if( (runFlags & SQL_OUTPUT)==0 ){ 1760 while( SQLITE_ROW==sqlite3_step(pStmt) ){} 1761 }else{ 1762 int nCol = -1; 1763 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 1764 int i; 1765 if( nCol<0 ){ 1766 nCol = sqlite3_column_count(pStmt); 1767 }else if( nCol>0 ){ 1768 printf("--------------------------------------------\n"); 1769 } 1770 for(i=0; i='0' && c<='9' ) return c - '0'; 1841 if( c>='a' && c<='f' ) return c - 'a' + 10; 1842 if( c>='A' && c<='F' ) return c - 'A' + 10; 1843 return -1; 1844 } 1845 1846 /* 1847 ** Interpret zArg as an integer value, possibly with suffixes. 1848 */ 1849 static int integerValue(const char *zArg){ 1850 sqlite3_int64 v = 0; 1851 static const struct { char *zSuffix; int iMult; } aMult[] = { 1852 { "KiB", 1024 }, 1853 { "MiB", 1024*1024 }, 1854 { "GiB", 1024*1024*1024 }, 1855 { "KB", 1000 }, 1856 { "MB", `1000000` }, 1857 { "GB", `1000000000` }, 1858 { "K", 1000 }, 1859 { "M", `1000000` }, 1860 { "G", `1000000000` }, 1861 }; 1862 int i; 1863 int isNeg = 0; 1864 if( zArg[0]=='-' ){ 1865 isNeg = 1; 1866 zArg++; 1867 }else if( zArg[0]=='+' ){ 1868 zArg++; 1869 } 1870 if( zArg[0]=='0' && zArg[1]=='x' ){ 1871 int x; 1872 zArg += 2; 1873 while( (x = hexDigitValue(zArg[0]))>=0 ){ 1874 v = (v<<4) + x; 1875 zArg++; 1876 } 1877 }else{ 1878 while( ISDIGIT(zArg[0]) ){ 1879 v = v*10 + zArg[0] - '0'; 1880 zArg++; 1881 } 1882 } 1883 for(i=0; i0x7fffffff ) fatalError("parameter too large - max `2147483648`"); 1890 return (int)(isNeg? -v : v); 1891 } 1892 1893 /* 1894 ** Return the number of "v" characters in a string. Return 0 if there 1895 ** are any characters in the string other than "v". 1896 */ 1897 static int numberOfVChar(const char *z){ 1898 int N = 0; 1899 while( z[0] && z[0]=='v' ){ 1900 z++; 1901 N++; 1902 } 1903 return z[0]==0 ? N : 0; 1904 } 1905 1906 /* 1907 ** Print sketchy documentation for this utility program 1908 */ 1909 static void showHelp(void){ 1910 printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0); 1911 printf( 1912 "Read databases and SQL scripts from SOURCE-DB and execute each script against\n" 1913 "each database, checking for crashes and memory leaks.\n" 1914 "Options:\n" 1915 " --brief Output only a summary of results at the end\n" 1916 " --cell-size-check Set the PRAGMA cell_size_check=ON\n" 1917 " --dbid M..N Use only the databases where dbid between M and N\n" 1918 " \"M..\" for M and afterwards. Just \"M\" for M only\n" 1919 " --export-db DIR Write databases to files(s) in DIR. Works with --dbid\n" 1920 " --export-sql DIR Write SQL to file(s) in DIR. Also works with --sqlid\n" 1921 " --help Show this help text\n" 1922 " --info Show information about SOURCE-DB w/o running tests\n" 1923 " --limit-depth N Limit expression depth to N. Default: 500\n" 1924 " --limit-heap N Limit heap memory to N. Default: 100M\n" 1925 " --limit-mem N Limit memory used by test SQLite instance to N bytes\n" 1926 " --limit-vdbe Panic if any test runs for more than 100,000 cycles\n" 1927 " --load-sql FILE.. Load SQL scripts fron files into SOURCE-DB\n" 1928 " --load-db FILE.. Load template databases from files into SOURCE_DB\n" 1929 " --load-dbsql FILE.. Load dbsqlfuzz outputs into the xsql table\n" 1930 " ^^^^------ Use \"-\" for FILE to read filenames from stdin\n" 1931 " -m TEXT Add a description to the database\n" 1932 " --native-vfs Use the native VFS for initially empty database files\n" 1933 " --native-malloc Turn off MEMSYS3/5 and Lookaside\n" 1934 " --no-recover Do not run recovery on dbsqlfuzz databases\n" 1935 " --oss-fuzz Enable OSS-FUZZ testing\n" 1936 " --prng-seed N Seed value for the PRGN inside of SQLite\n" 1937 " -q|--quiet Reduced output\n" 1938 " --rebuild Rebuild and vacuum the database file\n" 1939 " --result-trace Show the results of each SQL command\n" 1940 " --script Output CLI script instead of running tests\n" 1941 " --skip N Skip the first N test cases\n" 1942 " --slice M N Run only the M-th out of each group of N tests\n" 1943 " --spinner Use a spinner to show progress\n" 1944 " --sqlid M..N Use only SQL where sqlid between M..N\n" 1945 " \"M..\" for M and afterwards. Just \"M\" for M only\n" 1946 " --timeout N Maximum time for any one test in N millseconds\n" 1947 " -v|--verbose Increased output. Repeat for more output.\n" 1948 " --vdbe-debug Activate VDBE debugging.\n" 1949 " --wait N Wait N seconds before continuing - useful for\n" 1950 " attaching an MSVC debugging.\n" 1951 ); 1952 } 1953 1954 int main(int argc, char **argv){ 1955 sqlite3_int64 iBegin; /* Start time of this program */ 1956 int quietFlag = 0; /* True if --quiet or -q */ 1957 int briefFlag = 0; /* Output summary report at the end */ 1958 int verboseFlag = 0; /* True if --verbose or -v */ 1959 char *zInsSql = 0; /* SQL statement for --load-db or --load-sql */ 1960 int iFirstInsArg = 0; /* First argv[] for --load-db or --load-sql */ 1961 sqlite3 *db = 0; /* The open database connection */ 1962 sqlite3_stmt *pStmt; /* A prepared statement */ 1963 int rc; /* Result code from SQLite interface calls */ 1964 Blob *pSql; /* For looping over SQL scripts */ 1965 Blob *pDb; /* For looping over template databases */ 1966 int i; /* Loop index for the argv[] loop */ 1967 int dbSqlOnly = 0; /* Only use scripts that are dbsqlfuzz */ 1968 int firstSqlid = -1; /* First --sqlid range */ 1969 int lastSqlid = 0x7fffffff; /* Last --sqlid range */ 1970 int firstDbid = -1; /* --dbid */ 1971 int lastDbid = 0x7fffffff; /* --dbid end */ 1972 int nativeFlag = 0; /* --native-vfs */ 1973 int rebuildFlag = 0; /* --rebuild */ 1974 int vdbeLimitFlag = 0; /* --limit-vdbe */ 1975 int infoFlag = 0; /* --info */ 1976 int nSkip = 0; /* --skip */ 1977 int bScript = 0; /* --script */ 1978 int bSpinner = 0; /* True for --spinner */ 1979 int timeoutTest = 0; /* undocumented --timeout-test flag */ 1980 int runFlags = 0; /* Flags sent to runSql() */ 1981 char *zMsg = 0; /* Add this message */ 1982 int nSrcDb = 0; /* Number of source databases */ 1983 char **azSrcDb = 0; /* Array of source database names */ 1984 int iSrcDb; /* Loop over all source databases */ 1985 int nTest = 0; /* Total number of tests performed */ 1986 int nSliceSkip = 0; /* Skipped due to --slice */ 1987 char *zDbName = ""; /* Appreviated name of a source database */ 1988 const char *zFailCode = 0; /* Value of the TEST_FAILURE env variable */ 1989 int cellSzCkFlag = 0; /* --cell-size-check */ 1990 int sqlFuzz = 0; /* True for SQL fuzz. False for DB fuzz */ 1991 int iTimeout = 120000; /* Default 120-second timeout */ 1992 int nMem = 0; /* Memory limit override */ 1993 int nMemThisDb = 0; /* Memory limit set by the CONFIG table */ 1994 char *zExpDb = 0; /* Write Databases to files in this directory */ 1995 char *zExpSql = 0; /* Write SQL to files in this directory */ 1996 void *pHeap = 0; /* Heap for use by SQLite */ 1997 int ossFuzz = 0; /* enable OSS-FUZZ testing */ 1998 int ossFuzzThisDb = 0; /* ossFuzz value for this particular database */ 1999 int nativeMalloc = 0; /* Turn off MEMSYS3/5 and lookaside if true */ 2000 sqlite3_vfs *pDfltVfs; /* The default VFS */ 2001 int openFlags4Data; /* Flags for sqlite3_open_v2() */ 2002 int bTimer = 0; /* Show elapse time for each test */ 2003 int nV; /* How much to increase verbosity with -vvvv */ 2004 sqlite3_int64 tmStart; /* Start of each test */ 2005 int iEstTime = 0; /* LPF for the time-to-go */ 2006 int iSliceSz = 0; /* Divide the test space into this many pieces */ 2007 int iSliceIdx = 0; /* Only run the piece with this index */ 2008 2009 sqlite3_config(SQLITE_CONFIG_URI,1); 2010 sqlite3_config(SQLITE_CONFIG_MEMSTATUS,1); 2011 registerOomSimulator(); 2012 sqlite3_initialize(); 2013 iBegin = timeOfDay(); 2014 #ifdef __unix__ 2015 signal(SIGALRM, signalHandler); 2016 signal(SIGSEGV, signalHandler); 2017 signal(SIGABRT, signalHandler); 2018 #endif 2019 g.zArgv0 = argv[0]; 2020 openFlags4Data = SQLITE_OPEN_READONLY; 2021 zFailCode = getenv("TEST_FAILURE"); 2022 pDfltVfs = sqlite3_vfs_find(0); 2023 inmemVfsRegister(1); 2024 for(i=1; i=argc-1 ) fatalError("missing arguments on %s", argv[i]); 2041 i++; 2042 zDotDot = strstr(argv[i], ".."); 2043 if( zDotDot ){ 2044 firstDbid = atoi(argv[i]); 2045 if( zDotDot[2] ){ 2046 lastDbid = atoi(&zDotDot[2]); 2047 } 2048 }else{ 2049 lastDbid = firstDbid = integerValue(argv[i]); 2050 } 2051 }else 2052 if( strcmp(z,"export-db")==0 ){ 2053 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 2054 zExpDb = argv[++i]; 2055 }else 2056 if( strcmp(z,"export-sql")==0 || strcmp(z,"export-dbsql")==0 ){ 2057 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 2058 zExpSql = argv[++i]; 2059 }else 2060 if( strcmp(z,"help")==0 ){ 2061 showHelp(); 2062 return 0; 2063 }else 2064 if( strcmp(z,"info")==0 ){ 2065 infoFlag = 1; 2066 }else 2067 if( strcmp(z,"limit-depth")==0 ){ 2068 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 2069 depthLimit = integerValue(argv[++i]); 2070 }else 2071 if( strcmp(z,"limit-heap")==0 ){ 2072 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 2073 heapLimit = integerValue(argv[++i]); 2074 }else 2075 if( strcmp(z,"limit-mem")==0 ){ 2076 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 2077 nMem = integerValue(argv[++i]); 2078 }else 2079 if( strcmp(z,"limit-vdbe")==0 ){ 2080 vdbeLimitFlag = 1; 2081 }else 2082 if( strcmp(z,"load-sql")==0 ){ 2083 zInsSql = "INSERT INTO xsql(sqltext)" 2084 "VALUES(CAST(readtextfile(?1) AS text))"; 2085 iFirstInsArg = i+1; 2086 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 2087 break; 2088 }else 2089 if( strcmp(z,"load-db")==0 ){ 2090 zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))"; 2091 iFirstInsArg = i+1; 2092 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 2093 break; 2094 }else 2095 if( strcmp(z,"load-dbsql")==0 ){ 2096 zInsSql = "INSERT INTO xsql(sqltext)" 2097 "VALUES(readfile(?1))"; 2098 iFirstInsArg = i+1; 2099 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 2100 dbSqlOnly = 1; 2101 break; 2102 }else 2103 if( strcmp(z,"m")==0 ){ 2104 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 2105 zMsg = argv[++i]; 2106 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 2107 }else 2108 if( strcmp(z,"native-malloc")==0 ){ 2109 nativeMalloc = 1; 2110 }else 2111 if( strcmp(z,"native-vfs")==0 ){ 2112 nativeFlag = 1; 2113 }else 2114 if( strcmp(z,"no-recover")==0 ){ 2115 bNoRecover = 1; 2116 }else 2117 if( strcmp(z,"oss-fuzz")==0 ){ 2118 ossFuzz = 1; 2119 }else 2120 if( strcmp(z,"prng-seed")==0 ){ 2121 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 2122 g.uRandom = atoi(argv[++i]); 2123 }else 2124 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ 2125 briefFlag = 0; 2126 quietFlag = 1; 2127 verboseFlag = 0; 2128 eVerbosity = 0; 2129 }else 2130 if( strcmp(z,"rebuild")==0 ){ 2131 rebuildFlag = 1; 2132 openFlags4Data = SQLITE_OPEN_READWRITE; 2133 }else 2134 if( strcmp(z,"result-trace")==0 ){ 2135 runFlags |= SQL_OUTPUT; 2136 }else 2137 if( strcmp(z,"script")==0 ){ 2138 bScript = 1; 2139 }else 2140 if( strcmp(z,"skip")==0 ){ 2141 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 2142 nSkip = atoi(argv[++i]); 2143 }else 2144 if( strcmp(z,"slice")==0 ){ 2145 if( i>=argc-2 ) fatalError("missing arguments on %s", argv[i]); 2146 iSliceIdx = integerValue(argv[++i]); 2147 iSliceSz = integerValue(argv[++i]); 2148 /* --slice implices --brief */ 2149 briefFlag = 1; 2150 quietFlag = 1; 2151 verboseFlag = 1; 2152 eVerbosity = 0; 2153 }else 2154 if( strcmp(z,"spinner")==0 ){ 2155 bSpinner = 1; 2156 }else 2157 if( strcmp(z,"sqlid")==0 ){ 2158 const char *zDotDot; 2159 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 2160 i++; 2161 zDotDot = strstr(argv[i], ".."); 2162 if( zDotDot ){ 2163 firstSqlid = atoi(argv[i]); 2164 if( zDotDot[2] ){ 2165 lastSqlid = atoi(&zDotDot[2]); 2166 } 2167 }else{ 2168 firstSqlid = integerValue(argv[i]); 2169 lastSqlid = firstSqlid; 2170 } 2171 }else 2172 if( strcmp(z,"timeout")==0 ){ 2173 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 2174 iTimeout = integerValue(argv[++i]); 2175 }else 2176 if( strcmp(z,"timeout-test")==0 ){ 2177 timeoutTest = 1; 2178 #ifndef __unix__ 2179 fatalError("timeout is not available on non-unix systems"); 2180 #endif 2181 }else 2182 if( strcmp(z,"timer")==0 ){ 2183 bTimer = 1; 2184 }else 2185 if( strcmp(z,"vdbe-debug")==0 ){ 2186 bVdbeDebug = 1; 2187 }else 2188 if( strcmp(z,"verbose")==0 ){ 2189 briefFlag = 0; 2190 quietFlag = 0; 2191 verboseFlag++; 2192 eVerbosity++; 2193 if( verboseFlag>2 ) runFlags |= SQL_TRACE; 2194 }else 2195 if( (nV = numberOfVChar(z))>=1 ){ 2196 quietFlag = 0; 2197 verboseFlag += nV; 2198 eVerbosity += nV; 2199 if( verboseFlag>2 ) runFlags |= SQL_TRACE; 2200 }else 2201 if( strcmp(z,"version")==0 ){ 2202 int ii; 2203 const char *zz; 2204 printf("SQLite %s %s (%d-bit)\n", 2205 sqlite3_libversion(), sqlite3_sourceid(), 2206 8*(int)sizeof(char*)); 2207 for(ii=0; (zz = sqlite3_compileoption_get(ii))!=0; ii++){ 2208 printf("%s\n", zz); 2209 } 2210 return 0; 2211 }else 2212 if( strcmp(z,"wait")==0 ){ 2213 int iDelay; 2214 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 2215 iDelay = integerValue(argv[++i]); 2216 printf("Waiting %d seconds:", iDelay); 2217 fflush(stdout); 2218 while( 1 /*exit-by-break*/ ){ 2219 sqlite3_sleep(1000); 2220 iDelay--; 2221 if( iDelay<=0 ) break; 2222 printf(" %d", iDelay); 2223 fflush(stdout); 2224 } 2225 printf("\n"); 2226 fflush(stdout); 2227 }else 2228 if( strcmp(z,"is-dbsql")==0 ){ 2229 i++; 2230 for(i++; i1 ){ 2249 if( zMsg ){ 2250 fatalError("cannot change the description of more than one database"); 2251 } 2252 if( zInsSql ){ 2253 fatalError("cannot import into more than one database"); 2254 } 2255 } 2256 if( iSliceSz<=iSliceIdx 2257 || iSliceSz<=0 2258 || iSliceIdx<0 2259 ){ 2260 iSliceSz = iSliceIdx = 0; 2261 } 2262 2263 /* Process each source database separately */ 2264 for(iSrcDb=0; iSrcDbzName); 2270 if( rc==SQLITE_OK ){ 2271 rc = sqlite3_exec(db, "SELECT count(*) FROM sqlite_schema", 0, 0, 0); 2272 } 2273 if( rc ){ 2274 sqlite3_close(db); 2275 zRawData = readFile(azSrcDb[iSrcDb], &nRawData); 2276 if( zRawData==0 ){ 2277 fatalError("input file \"%s\" is not recognized\n", azSrcDb[iSrcDb]); 2278 } 2279 sqlite3_open(":memory:", &db); 2280 } 2281 2282 /* Print the description, if there is one */ 2283 if( infoFlag ){ 2284 int n; 2285 zDbName = azSrcDb[iSrcDb]; 2286 i = (int)strlen(zDbName) - 1; 2287 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; } 2288 zDbName += i; 2289 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0); 2290 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 2291 printf("%s: %s", zDbName, sqlite3_column_text(pStmt,0)); 2292 }else{ 2293 printf("%s: (empty \"readme\")", zDbName); 2294 } 2295 sqlite3_finalize(pStmt); 2296 sqlite3_prepare_v2(db, "SELECT count(*) FROM db", -1, &pStmt, 0); 2297 if( pStmt 2298 && sqlite3_step(pStmt)==SQLITE_ROW 2299 && (n = sqlite3_column_int(pStmt,0))>0 2300 ){ 2301 printf(" - %d DBs", n); 2302 } 2303 sqlite3_finalize(pStmt); 2304 sqlite3_prepare_v2(db, "SELECT count(*) FROM xsql", -1, &pStmt, 0); 2305 if( pStmt 2306 && sqlite3_step(pStmt)==SQLITE_ROW 2307 && (n = sqlite3_column_int(pStmt,0))>0 2308 ){ 2309 printf(" - %d scripts", n); 2310 } 2311 sqlite3_finalize(pStmt); 2312 printf("\n"); 2313 sqlite3_close(db); 2314 sqlite3_free(zRawData); 2315 continue; 2316 } 2317 2318 rc = sqlite3_exec(db, 2319 "CREATE TABLE IF NOT EXISTS db(\n" 2320 " dbid INTEGER PRIMARY KEY, -- database id\n" 2321 " dbcontent BLOB -- database disk file image\n" 2322 ");\n" 2323 "CREATE TABLE IF NOT EXISTS xsql(\n" 2324 " sqlid INTEGER PRIMARY KEY, -- SQL script id\n" 2325 " sqltext TEXT -- Text of SQL statements to run\n" 2326 ");" 2327 "CREATE TABLE IF NOT EXISTS readme(\n" 2328 " msg TEXT -- Human-readable description of this file\n" 2329 ");", 0, 0, 0); 2330 if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db)); 2331 if( zMsg ){ 2332 char *zSql; 2333 zSql = sqlite3_mprintf( 2334 "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg); 2335 rc = sqlite3_exec(db, zSql, 0, 0, 0); 2336 sqlite3_free(zSql); 2337 if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db)); 2338 } 2339 if( zRawData ){ 2340 zInsSql = "INSERT INTO xsql(sqltext) VALUES(?1)"; 2341 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0); 2342 if( rc ) fatalError("cannot prepare statement [%s]: %s", 2343 zInsSql, sqlite3_errmsg(db)); 2344 sqlite3_bind_text(pStmt, 1, zRawData, nRawData, SQLITE_STATIC); 2345 sqlite3_step(pStmt); 2346 rc = sqlite3_reset(pStmt); 2347 if( rc ) fatalError("insert failed for %s", argv[i]); 2348 sqlite3_finalize(pStmt); 2349 rebuild_database(db, dbSqlOnly); 2350 zInsSql = 0; 2351 sqlite3_free(zRawData); 2352 zRawData = 0; 2353 } 2354 ossFuzzThisDb = ossFuzz; 2355 2356 /* If the CONFIG(name,value) table exists, read db-specific settings 2357 ** from that table */ 2358 if( sqlite3_table_column_metadata(db,0,"config",0,0,0,0,0,0)==SQLITE_OK ){ 2359 rc = sqlite3_prepare_v2(db, "SELECT name, value FROM config", 2360 -1, &pStmt, 0); 2361 if( rc ) fatalError("cannot prepare query of CONFIG table: %s", 2362 sqlite3_errmsg(db)); 2363 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 2364 const char *zName = (const char *)sqlite3_column_text(pStmt,0); 2365 if( zName==0 ) continue; 2366 if( strcmp(zName, "oss-fuzz")==0 ){ 2367 ossFuzzThisDb = sqlite3_column_int(pStmt,1); 2368 if( verboseFlag>1 ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb); 2369 } 2370 if( strcmp(zName, "limit-mem")==0 ){ 2371 nMemThisDb = sqlite3_column_int(pStmt,1); 2372 if( verboseFlag>1 ) printf("Config: limit-mem=%d\n", nMemThisDb); 2373 } 2374 } 2375 sqlite3_finalize(pStmt); 2376 } 2377 2378 if( zInsSql ){ 2379 sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0, 2380 readfileFunc, 0, 0); 2381 sqlite3_create_function(db, "readtextfile", 1, SQLITE_UTF8, 0, 2382 readtextfileFunc, 0, 0); 2383 sqlite3_create_function(db, "isdbsql", 1, SQLITE_UTF8, 0, 2384 isDbSqlFunc, 0, 0); 2385 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0); 2386 if( rc ) fatalError("cannot prepare statement [%s]: %s", 2387 zInsSql, sqlite3_errmsg(db)); 2388 rc = sqlite3_exec(db, "BEGIN", 0, 0, 0); 2389 if( rc ) fatalError("cannot start a transaction"); 2390 for(i=iFirstInsArg; i0 && zLine[kk-1]<=' ' ) kk--; 2397 sqlite3_bind_text(pStmt, 1, zLine, (int)kk, SQLITE_STATIC); 2398 if( verboseFlag>1 ) printf("loading %.*s\n", (int)kk, zLine); 2399 sqlite3_step(pStmt); 2400 rc = sqlite3_reset(pStmt); 2401 if( rc ) fatalError("insert failed for %s", zLine); 2402 } 2403 }else{ 2404 sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC); 2405 if( verboseFlag>1 ) printf("loading %s\n", argv[i]); 2406 sqlite3_step(pStmt); 2407 rc = sqlite3_reset(pStmt); 2408 if( rc ) fatalError("insert failed for %s", argv[i]); 2409 } 2410 } 2411 sqlite3_finalize(pStmt); 2412 rc = sqlite3_exec(db, "COMMIT", 0, 0, 0); 2413 if( rc ) fatalError("cannot commit the transaction: %s", 2414 sqlite3_errmsg(db)); 2415 rebuild_database(db, dbSqlOnly); 2416 sqlite3_close(db); 2417 return 0; 2418 } 2419 rc = sqlite3_exec(db, "PRAGMA query_only=1;", 0, 0, 0); 2420 if( rc ) fatalError("cannot set database to query-only"); 2421 if( zExpDb!=0 || zExpSql!=0 ){ 2422 sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0, 2423 writefileFunc, 0, 0); 2424 if( zExpDb!=0 ){ 2425 const char *zExDb = 2426 "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent)," 2427 " dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)" 2428 " FROM db WHERE dbid BETWEEN ?2 AND ?3;"; 2429 rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0); 2430 if( rc ) fatalError("cannot prepare statement [%s]: %s", 2431 zExDb, sqlite3_errmsg(db)); 2432 sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb), 2433 SQLITE_STATIC, SQLITE_UTF8); 2434 sqlite3_bind_int(pStmt, 2, firstDbid); 2435 sqlite3_bind_int(pStmt, 3, lastDbid); 2436 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 2437 printf("write db-%d (%d bytes) into %s\n", 2438 sqlite3_column_int(pStmt,1), 2439 sqlite3_column_int(pStmt,3), 2440 sqlite3_column_text(pStmt,2)); 2441 } 2442 sqlite3_finalize(pStmt); 2443 } 2444 if( zExpSql!=0 ){ 2445 const char *zExSql = 2446 "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext)," 2447 " sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)" 2448 " FROM xsql WHERE sqlid BETWEEN ?2 AND ?3;"; 2449 rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0); 2450 if( rc ) fatalError("cannot prepare statement [%s]: %s", 2451 zExSql, sqlite3_errmsg(db)); 2452 sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql), 2453 SQLITE_STATIC, SQLITE_UTF8); 2454 sqlite3_bind_int(pStmt, 2, firstSqlid); 2455 sqlite3_bind_int(pStmt, 3, lastSqlid); 2456 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 2457 printf("write sql-%d (%d bytes) into %s\n", 2458 sqlite3_column_int(pStmt,1), 2459 sqlite3_column_int(pStmt,3), 2460 sqlite3_column_text(pStmt,2)); 2461 } 2462 sqlite3_finalize(pStmt); 2463 } 2464 sqlite3_close(db); 2465 return 0; 2466 } 2467 2468 /* Load all SQL script content and all initial database images from the 2469 ** source db 2470 */ 2471 blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", firstSqlid, 2472 lastSqlid, &g.nSql, &g.pFirstSql); 2473 if( g.nSql==0 ) fatalError("need at least one SQL script"); 2474 blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", firstDbid, 2475 lastDbid, &g.nDb, &g.pFirstDb); 2476 if( g.nDb==0 ){ 2477 g.pFirstDb = safe_realloc(0, sizeof(Blob)); 2478 memset(g.pFirstDb, 0, sizeof(Blob)); 2479 g.pFirstDb->id = 1; 2480 g.pFirstDb->seq = 0; 2481 g.nDb = 1; 2482 sqlFuzz = 1; 2483 } 2484 2485 /* Print the description, if there is one */ 2486 if( !quietFlag && !bScript ){ 2487 zDbName = azSrcDb[iSrcDb]; 2488 i = (int)strlen(zDbName) - 1; 2489 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; } 2490 zDbName += i; 2491 if( verboseFlag ){ 2492 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0); 2493 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 2494 printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0)); 2495 } 2496 sqlite3_finalize(pStmt); 2497 } 2498 } 2499 2500 /* Rebuild the database, if requested */ 2501 if( rebuildFlag ){ 2502 if( !quietFlag ){ 2503 printf("%s: rebuilding... ", zDbName); 2504 fflush(stdout); 2505 } 2506 rebuild_database(db, 0); 2507 if( !quietFlag ) printf("done\n"); 2508 } 2509 2510 /* Close the source database. Verify that no SQLite memory allocations are 2511 ** outstanding. 2512 */ 2513 sqlite3_close(db); 2514 if( sqlite3_memory_used()>0 ){ 2515 fatalError("SQLite has memory in use before the start of testing"); 2516 } 2517 2518 /* Limit available memory, if requested */ 2519 sqlite3_shutdown(); 2520 2521 if( nMemThisDb>0 && nMem==0 ){ 2522 if( !nativeMalloc ){ 2523 pHeap = realloc(pHeap, nMemThisDb); 2524 if( pHeap==0 ){ 2525 fatalError("failed to allocate %d bytes of heap memory", nMem); 2526 } 2527 sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMemThisDb, 128); 2528 }else{ 2529 sqlite3_hard_heap_limit64((sqlite3_int64)nMemThisDb); 2530 } 2531 }else{ 2532 sqlite3_hard_heap_limit64(0); 2533 } 2534 2535 /* Disable lookaside with the --native-malloc option */ 2536 if( nativeMalloc ){ 2537 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0); 2538 } 2539 2540 /* Reset the in-memory virtual filesystem */ 2541 formatVfs(); 2542 2543 /* Run a test using each SQL script against each database. 2544 */ 2545 if( verboseFlag<2 && !quietFlag && !bSpinner && !bScript ){ 2546 printf("%s:", zDbName); 2547 } 2548 for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){ 2549 tmStart = timeOfDay(); 2550 if( isDbSql(pSql->a, pSql->sz) ){ 2551 if( iSliceSz>0 && (nTest%iSliceSz)!=iSliceIdx ){ 2552 nTest++; 2553 nSliceSkip++; 2554 continue; 2555 } 2556 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d",pSql->id); 2557 if( bScript ){ 2558 /* No progress output */ 2559 }else if( bSpinner ){ 2560 int nTotal = g.nSql; 2561 int idx = pSql->seq; 2562 if( nSrcDb==1 && nTotal>idx && idx>=20 ){ 2563 int iToGo = (timeOfDay() - iBegin)*(nTotal-idx)/(idx*1000); 2564 int hr, min, sec; 2565 if( idx==20 ){ 2566 iEstTime = iToGo; 2567 }else{ 2568 iEstTime = (iToGo + 7*iEstTime)/8; 2569 } 2570 hr = iEstTime/3600; 2571 min = (iEstTime/60)%60; 2572 sec = iEstTime%60; 2573 if( hr>0 ){ 2574 printf("\r%s: %d/%d ETC %d:%02d:%02d ", 2575 zDbName, idx, nTotal, hr, min, sec); 2576 }else{ 2577 printf("\r%s: %d/%d ETC %02d:%02d ", 2578 zDbName, idx, nTotal, min, sec); 2579 } 2580 }else{ 2581 printf("\r%s: %d/%d ", zDbName, idx, nTotal); 2582 } 2583 fflush(stdout); 2584 }else if( verboseFlag>1 ){ 2585 printf("%s\n", g.zTestName); 2586 fflush(stdout); 2587 }else if( !quietFlag ){ 2588 static int prevAmt = -1; 2589 int idx = pSql->seq; 2590 int amt = idx*10/(g.nSql); 2591 if( amt!=prevAmt ){ 2592 printf(" %d%%", amt*10); 2593 fflush(stdout); 2594 prevAmt = amt; 2595 } 2596 } 2597 if( nSkip>0 ){ 2598 nSkip--; 2599 }else{ 2600 runCombinedDbSqlInput(pSql->a, pSql->sz, iTimeout, bScript, pSql->id); 2601 } 2602 nTest++; 2603 if( bTimer && !bScript ){ 2604 sqlite3_int64 tmEnd = timeOfDay(); 2605 printf("%lld %s\n", tmEnd - tmStart, g.zTestName); 2606 } 2607 g.zTestName[0] = 0; 2608 disableOom(); 2609 continue; 2610 } 2611 for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){ 2612 int openFlags; 2613 const char *zVfs = "inmem"; 2614 if( iSliceSz>0 && (nTest%iSliceSz)!=iSliceIdx ){ 2615 nTest++; 2616 nSliceSkip++; 2617 continue; 2618 } 2619 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d", 2620 pSql->id, pDb->id); 2621 if( bScript ){ 2622 /* No progress output */ 2623 }else if( bSpinner ){ 2624 int nTotal = g.nDb*g.nSql; 2625 int idx = pSql->seq*g.nDb + pDb->id - 1; 2626 printf("\r%s: %d/%d ", zDbName, idx, nTotal); 2627 fflush(stdout); 2628 }else if( verboseFlag>1 ){ 2629 printf("%s\n", g.zTestName); 2630 fflush(stdout); 2631 }else if( !quietFlag ){ 2632 static int prevAmt = -1; 2633 int idx = pSql->seq*g.nDb + pDb->id - 1; 2634 int amt = idx*10/(g.nDb*g.nSql); 2635 if( amt!=prevAmt ){ 2636 printf(" %d%%", amt*10); 2637 fflush(stdout); 2638 prevAmt = amt; 2639 } 2640 } 2641 if( nSkip>0 ){ 2642 nSkip--; 2643 continue; 2644 } 2645 if( bScript ){ 2646 char zName[100]; 2647 sqlite3_snprintf(sizeof(zName), zName, "db%06d.db", 2648 pDb->id>1 ? pDb->id : pSql->id); 2649 renderDbSqlForCLI(stdout, zName, 2650 pDb->a, pDb->sz, pSql->a, pSql->sz); 2651 continue; 2652 } 2653 createVFile("main.db", pDb->sz, pDb->a); 2654 sqlite3_randomness(0,0); 2655 if( ossFuzzThisDb ){ 2656 #ifndef SQLITE_OSS_FUZZ 2657 fatalError("--oss-fuzz not supported: recompile" 2658 " with -DSQLITE_OSS_FUZZ"); 2659 #else 2660 extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t); 2661 LLVMFuzzerTestOneInput((const uint8_t*)pSql->a, (size_t)pSql->sz); 2662 #endif 2663 }else{ 2664 openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE; 2665 if( nativeFlag && pDb->sz==0 ){ 2666 openFlags |= SQLITE_OPEN_MEMORY; 2667 zVfs = 0; 2668 } 2669 rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs); 2670 if( rc ) fatalError("cannot open inmem database"); 2671 sqlite3_limit(db, SQLITE_LIMIT_LENGTH, `100000000`); 2672 sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 50); 2673 if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags); 2674 setAlarm((iTimeout+999)/1000); 2675 /* Enable test functions */ 2676 sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, db); 2677 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 2678 if( sqlFuzz || vdbeLimitFlag ){ 2679 sqlite3_progress_handler(db, 100000, progressHandler, 2680 &vdbeLimitFlag); 2681 } 2682 #endif 2683 #ifdef SQLITE_TESTCTRL_PRNG_SEED 2684 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, db); 2685 #endif 2686 if( bVdbeDebug ){ 2687 sqlite3_exec(db, "PRAGMA vdbe_debug=ON", 0, 0, 0); 2688 } 2689 do{ 2690 runSql(db, (char*)pSql->a, runFlags); 2691 }while( timeoutTest ); 2692 setAlarm(0); 2693 sqlite3_exec(db, "PRAGMA temp_store_directory=''", 0, 0, 0); 2694 sqlite3_close(db); 2695 } 2696 if( sqlite3_memory_used()>0 ){ 2697 fatalError("memory leak: %lld bytes outstanding", 2698 sqlite3_memory_used()); 2699 } 2700 reformatVfs(); 2701 nTest++; 2702 if( bTimer ){ 2703 sqlite3_int64 tmEnd = timeOfDay(); 2704 printf("%lld %s\n", tmEnd - tmStart, g.zTestName); 2705 } 2706 g.zTestName[0] = 0; 2707 2708 /* Simulate an error if the TEST_FAILURE environment variable is "5". 2709 ** This is used to verify that automated test script really do spot 2710 ** errors that occur in this test program. 2711 */ 2712 if( zFailCode ){ 2713 if( zFailCode[0]=='5' && zFailCode[1]==0 ){ 2714 fatalError("simulated failure"); 2715 }else if( zFailCode[0]!=0 ){ 2716 /* If TEST_FAILURE is something other than 5, just exit the test 2717 ** early */ 2718 printf("\nExit early due to TEST_FAILURE being set\n"); 2719 iSrcDb = nSrcDb-1; 2720 goto sourcedb_cleanup; 2721 } 2722 } 2723 } 2724 } 2725 if( briefFlag ){ 2726 sqlite3_int64 iElapse = timeOfDay() - iBegin; 2727 if( iSliceSz>0 ){ 2728 printf( 2729 "%s %s: 0 errors out of %d tests, slice %d/%d, %d.%03d seconds\n", 2730 pathTail(argv[0]), pathTail(g.zDbFile), 2731 nTest - nSliceSkip, iSliceIdx, iSliceSz, 2732 (int)(iElapse/1000), (int)(iElapse%1000)); 2733 }else{ 2734 printf("%s %s: 0 errors out of %d tests, %d.%03d seconds\n", 2735 pathTail(argv[0]), pathTail(g.zDbFile), nTest, 2736 (int)(iElapse/1000), (int)(iElapse%1000)); 2737 } 2738 iBegin = timeOfDay(); 2739 }else if( bScript ){ 2740 /* No progress output */ 2741 }else if( bSpinner ){ 2742 int nTotal = g.nDb*g.nSql; 2743 printf("\r%s: %d/%d \n", zDbName, nTotal, nTotal); 2744 }else if( !quietFlag && verboseFlag<2 ){ 2745 printf(" 100%% - %d tests\n", g.nDb*g.nSql); 2746 } 2747 2748 /* Clean up at the end of processing a single source database 2749 */ 2750 sourcedb_cleanup: 2751 blobListFree(g.pFirstSql); 2752 blobListFree(g.pFirstDb); 2753 reformatVfs(); 2754 2755 } /* End loop over all source databases */ 2756 2757 2758 if( !quietFlag && !bScript ){ 2759 sqlite3_int64 iElapse = timeOfDay() - iBegin; 2760 if( g.nInvariant ){ 2761 printf("fuzzcheck: %u query invariants checked\n", g.nInvariant); 2762 } 2763 printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n" 2764 "SQLite %s %s (%d-bit)\n", 2765 nTest, (int)(iElapse/1000), (int)(iElapse%1000), 2766 sqlite3_libversion(), sqlite3_sourceid(), 2767 8*(int)sizeof(char*)); 2768 } 2769 free(azSrcDb); 2770 free(pHeap); 2771 return 0; 2772 }