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