1 /* 2 ** 2015-05-25 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** 13 ** This is a utility program designed to aid running regressions tests on 14 ** the SQLite library using data from external fuzzers. 15 ** 16 ** This program reads content from an SQLite database file with the following 17 ** schema: 18 ** 19 ** CREATE TABLE db( 20 ** dbid INTEGER PRIMARY KEY, -- database id 21 ** dbcontent BLOB -- database disk file image 22 ** ); 23 ** CREATE TABLE xsql( 24 ** sqlid INTEGER PRIMARY KEY, -- SQL script id 25 ** sqltext TEXT -- Text of SQL statements to run 26 ** ); 27 ** CREATE TABLE IF NOT EXISTS readme( 28 ** msg TEXT -- Human-readable description of this test collection 29 ** ); 30 ** 31 ** For each database file in the DB table, the SQL text in the XSQL table 32 ** is run against that database. All README.MSG values are printed prior 33 ** to the start of the test (unless the --quiet option is used). If the 34 ** DB table is empty, then all entries in XSQL are run against an empty 35 ** in-memory database. 36 ** 37 ** This program is looking for crashes, assertion faults, and/or memory leaks. 38 ** No attempt is made to verify the output. The assumption is that either all 39 ** of the database files or all of the SQL statements are malformed inputs, 40 ** generated by a fuzzer, that need to be checked to make sure they do not 41 ** present a security risk. 42 ** 43 ** This program also includes some command-line options to help with 44 ** creation and maintenance of the source content database. The command 45 ** 46 ** ./fuzzcheck database.db --load-sql FILE... 47 ** 48 ** Loads all FILE... arguments into the XSQL table. The --load-db option 49 ** works the same but loads the files into the DB table. The -m option can 50 ** be used to initialize the README table. The "database.db" file is created 51 ** if it does not previously exist. Example: 52 ** 53 ** ./fuzzcheck new.db --load-sql *.sql 54 ** ./fuzzcheck new.db --load-db *.db 55 ** ./fuzzcheck new.db -m 'New test cases' 56 ** 57 ** The three commands above will create the "new.db" file and initialize all 58 ** tables. Then do "./fuzzcheck new.db" to run the tests. 59 ** 60 ** DEBUGGING HINTS: 61 ** 62 ** If fuzzcheck does crash, it can be run in the debugger and the content 63 ** of the global variable g.zTextName[] will identify the specific XSQL and 64 ** DB values that were running when the crash occurred. 65 ** 66 ** DBSQLFUZZ: (Added 2020-02-25) 67 ** 68 ** The dbsqlfuzz fuzzer includes both a database file and SQL to run against 69 ** that database in its input. This utility can now process dbsqlfuzz 70 ** input files. Load such files using the "--load-dbsql FILE ..." command-line 71 ** option. 72 ** 73 ** Dbsqlfuzz inputs are ordinary text. The first part of the file is text 74 ** that describes the content of the database (using a lot of hexadecimal), 75 ** then there is a divider line followed by the SQL to run against the 76 ** database. Because they are ordinary text, dbsqlfuzz inputs are stored 77 ** in the XSQL table, as if they were ordinary SQL inputs. The isDbSql() 78 ** function can look at a text string and determine whether or not it is 79 ** a valid dbsqlfuzz input. 80 */ 81 #include <stdio.h> 82 #include <stdlib.h> 83 #include <string.h> 84 #include <stdarg.h> 85 #include <ctype.h> 86 #include <assert.h> 87 #include "sqlite3.h" 88 #define ISSPACE(X) isspace((unsigned char)(X)) 89 #define ISDIGIT(X) isdigit((unsigned char)(X)) 90 91 92 #ifdef __unix__ 93 # include <signal.h> 94 # include <unistd.h> 95 #endif 96 97 #include <stddef.h> 98 #if !defined(_MSC_VER) 99 # include <stdint.h> 100 #endif 101 102 #if defined(_MSC_VER) 103 typedef unsigned char uint8_t; 104 #endif 105 106 /* 107 ** Files in the virtual file system. 108 */ 109 typedef struct VFile VFile; 110 struct VFile { 111 char *zFilename; /* Filename. NULL for delete-on-close. From malloc() */ 112 int sz; /* Size of the file in bytes */ 113 int nRef; /* Number of references to this file */ 114 unsigned char *a; /* Content of the file. From malloc() */ 115 }; 116 typedef struct VHandle VHandle; 117 struct VHandle { 118 sqlite3_file base; /* Base class. Must be first */ 119 VFile *pVFile; /* The underlying file */ 120 }; 121 122 /* 123 ** The value of a database file template, or of an SQL script 124 */ 125 typedef struct Blob Blob; 126 struct Blob { 127 Blob *pNext; /* Next in a list */ 128 int id; /* Id of this Blob */ 129 int seq; /* Sequence number */ 130 int sz; /* Size of this Blob in bytes */ 131 unsigned char a[1]; /* Blob content. Extra space allocated as needed. */ 132 }; 133 134 /* 135 ** Maximum number of files in the in-memory virtual filesystem. 136 */ 137 #define MX_FILE 10 138 139 /* 140 ** Maximum allowed file size 141 */ 142 #define MX_FILE_SZ 10000000 143 144 /* 145 ** All global variables are gathered into the "g" singleton. 146 */ 147 static struct GlobalVars { 148 const char *zArgv0; /* Name of program */ 149 const char *zDbFile; /* Name of database file */ 150 VFile aFile[MX_FILE]; /* The virtual filesystem */ 151 int nDb; /* Number of template databases */ 152 Blob *pFirstDb; /* Content of first template database */ 153 int nSql; /* Number of SQL scripts */ 154 Blob *pFirstSql; /* First SQL script */ 155 unsigned int uRandom; /* Seed for the SQLite PRNG */ 156 char zTestName[100]; /* Name of current test */ 157 } g; 158 159 /* 160 ** Include the external vt02.c module, if requested by compile-time 161 ** options. 162 */ 163 #ifdef VT02_SOURCES 164 # include "vt02.c" 165 #endif 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 /* This routine is called when a simulated OOM occurs. It is broken 632 ** out as a separate routine to make it easy to set a breakpoint on 633 ** the OOM 634 */ 635 void oomFault(void){ 636 if( eVerbosity ){ 637 printf("Simulated OOM fault\n"); 638 } 639 if( oomRepeat>0 ){ 640 oomRepeat--; 641 }else{ 642 oomCounter--; 643 } 644 } 645 646 /* This routine is a replacement malloc() that is used to simulate 647 ** Out-Of-Memory (OOM) errors for testing purposes. 648 */ 649 static void *oomMalloc(int nByte){ 650 if( oomCounter ){ 651 if( oomCounter==1 ){ 652 oomFault(); 653 return 0; 654 }else{ 655 oomCounter--; 656 } 657 } 658 return defaultMalloc(nByte); 659 } 660 661 /* Register the OOM simulator. This must occur before any memory 662 ** allocations */ 663 static void registerOomSimulator(void){ 664 sqlite3_mem_methods mem; 665 sqlite3_shutdown(); 666 sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem); 667 defaultMalloc = mem.xMalloc; 668 mem.xMalloc = oomMalloc; 669 sqlite3_config(SQLITE_CONFIG_MALLOC, &mem); 670 } 671 672 /* Turn off any pending OOM simulation */ 673 static void disableOom(void){ 674 oomCounter = 0; 675 oomRepeat = 0; 676 } 677 678 /* 679 ** Translate a single byte of Hex into an integer. 680 ** This routine only works if h really is a valid hexadecimal 681 ** character: 0..9a..fA..F 682 */ 683 static unsigned char hexToInt(unsigned int h){ 684 #ifdef SQLITE_EBCDIC 685 h += 9*(1&~(h>>4)); /* EBCDIC */ 686 #else 687 h += 9*(1&(h>>6)); /* ASCII */ 688 #endif 689 return h & 0xf; 690 } 691 692 /* 693 ** The first character of buffer zIn[0..nIn-1] is a '['. This routine 694 ** checked to see if the buffer holds "[NNNN]" or "[+NNNN]" and if it 695 ** does it makes corresponding changes to the *pK value and *pI value 696 ** and returns true. If the input buffer does not match the patterns, 697 ** no changes are made to either *pK or *pI and this routine returns false. 698 */ 699 static int isOffset( 700 const unsigned char *zIn, /* Text input */ 701 int nIn, /* Bytes of input */ 702 unsigned int *pK, /* half-byte cursor to adjust */ 703 unsigned int *pI /* Input index to adjust */ 704 ){ 705 int i; 706 unsigned int k = 0; 707 unsigned char c; 708 for(i=1; i<nIn && (c = zIn[i])!=']'; i++){ 709 if( !isxdigit(c) ) return 0; 710 k = k*16 + hexToInt(c); 711 } 712 if( i==nIn ) return 0; 713 *pK = 2*k; 714 *pI += i; 715 return 1; 716 } 717 718 /* 719 ** Decode the text starting at zIn into a binary database file. 720 ** The maximum length of zIn is nIn bytes. Store the binary database 721 ** file in space obtained from sqlite3_malloc(). 722 ** 723 ** Return the number of bytes of zIn consumed. Or return -1 if there 724 ** is an error. One potential error is that the recipe specifies a 725 ** database file larger than MX_FILE_SZ bytes. 726 ** 727 ** Abort on an OOM. 728 */ 729 static int decodeDatabase( 730 const unsigned char *zIn, /* Input text to be decoded */ 731 int nIn, /* Bytes of input text */ 732 unsigned char **paDecode, /* OUT: decoded database file */ 733 int *pnDecode /* OUT: Size of decoded database */ 734 ){ 735 unsigned char *a, *aNew; /* Database under construction */ 736 int mx = 0; /* Current size of the database */ 737 sqlite3_uint64 nAlloc = 4096; /* Space allocated in a[] */ 738 unsigned int i; /* Next byte of zIn[] to read */ 739 unsigned int j; /* Temporary integer */ 740 unsigned int k; /* half-byte cursor index for output */ 741 unsigned int n; /* Number of bytes of input */ 742 unsigned char b = 0; 743 if( nIn<4 ) return -1; 744 n = (unsigned int)nIn; 745 a = sqlite3_malloc64( nAlloc ); 746 if( a==0 ){ 747 fprintf(stderr, "Out of memory!\n"); 748 exit(1); 749 } 750 memset(a, 0, (size_t)nAlloc); 751 for(i=k=0; i<n; i++){ 752 unsigned char c = (unsigned char)zIn[i]; 753 if( isxdigit(c) ){ 754 k++; 755 if( k & 1 ){ 756 b = hexToInt(c)*16; 757 }else{ 758 b += hexToInt(c); 759 j = k/2 - 1; 760 if( j>=nAlloc ){ 761 sqlite3_uint64 newSize; 762 if( nAlloc==MX_FILE_SZ || j>=MX_FILE_SZ ){ 763 if( eVerbosity ){ 764 fprintf(stderr, "Input database too big: max %d bytes\n", 765 MX_FILE_SZ); 766 } 767 sqlite3_free(a); 768 return -1; 769 } 770 newSize = nAlloc*2; 771 if( newSize<=j ){ 772 newSize = (j+4096)&~4095; 773 } 774 if( newSize>MX_FILE_SZ ){ 775 if( j>=MX_FILE_SZ ){ 776 sqlite3_free(a); 777 return -1; 778 } 779 newSize = MX_FILE_SZ; 780 } 781 aNew = sqlite3_realloc64( a, newSize ); 782 if( aNew==0 ){ 783 sqlite3_free(a); 784 return -1; 785 } 786 a = aNew; 787 assert( newSize > nAlloc ); 788 memset(a+nAlloc, 0, (size_t)(newSize - nAlloc)); 789 nAlloc = newSize; 790 } 791 if( j>=(unsigned)mx ){ 792 mx = (j + 4095)&~4095; 793 if( mx>MX_FILE_SZ ) mx = MX_FILE_SZ; 794 } 795 assert( j<nAlloc ); 796 a[j] = b; 797 } 798 }else if( zIn[i]=='[' && i<n-3 && isOffset(zIn+i, nIn-i, &k, &i) ){ 799 continue; 800 }else if( zIn[i]=='\n' && i<n-4 && memcmp(zIn+i,"\n--\n",4)==0 ){ 801 i += 4; 802 break; 803 } 804 } 805 *pnDecode = mx; 806 *paDecode = a; 807 return i; 808 } 809 810 /* 811 ** Progress handler callback. 812 ** 813 ** The argument is the cutoff-time after which all processing should 814 ** stop. So return non-zero if the cut-off time is exceeded. 815 */ 816 static int progress_handler(void *pClientData) { 817 FuzzCtx *p = (FuzzCtx*)pClientData; 818 sqlite3_int64 iNow = timeOfDay(); 819 int rc = iNow>=p->iCutoffTime; 820 sqlite3_int64 iDiff = iNow - p->iLastCb; 821 /* printf("time-remaining: %lld\n", p->iCutoffTime - iNow); */ 822 if( iDiff > p->mxInterval ) p->mxInterval = iDiff; 823 p->nCb++; 824 if( rc==0 && p->mxCb>0 && p->mxCb<=p->nCb ) rc = 1; 825 if( rc && !p->timeoutHit && eVerbosity>=2 ){ 826 printf("Timeout on progress callback %d\n", p->nCb); 827 fflush(stdout); 828 p->timeoutHit = 1; 829 } 830 return rc; 831 } 832 833 /* 834 ** Flag bits set by block_troublesome_sql() 835 */ 836 #define BTS_SELECT 0x000001 837 #define BTS_NONSELECT 0x000002 838 #define BTS_BADFUNC 0x000004 839 840 /* 841 ** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and 842 ** "PRAGMA parser_trace" since they can dramatically increase the 843 ** amount of output without actually testing anything useful. 844 ** 845 ** Also block ATTACH if attaching a file from the filesystem. 846 */ 847 static int block_troublesome_sql( 848 void *pClientData, 849 int eCode, 850 const char *zArg1, 851 const char *zArg2, 852 const char *zArg3, 853 const char *zArg4 854 ){ 855 unsigned int *pFlags = (unsigned int*)pClientData; 856 (void)zArg3; 857 (void)zArg4; 858 switch( eCode ){ 859 case SQLITE_PRAGMA: { 860 if( sqlite3_stricmp("busy_timeout",zArg1)==0 861 && (zArg2==0 || strtoll(zArg2,0,0)>100 || strtoll(zArg2,0,10)>100) 862 ){ 863 return SQLITE_DENY; 864 }else if( eVerbosity==0 ){ 865 if( sqlite3_strnicmp("vdbe_", zArg1, 5)==0 866 || sqlite3_stricmp("parser_trace", zArg1)==0 867 || sqlite3_stricmp("temp_store_directory", zArg1)==0 868 ){ 869 return SQLITE_DENY; 870 } 871 }else if( sqlite3_stricmp("oom",zArg1)==0 872 && zArg2!=0 && zArg2[0]!=0 ){ 873 oomCounter = atoi(zArg2); 874 } 875 *pFlags |= BTS_NONSELECT; 876 break; 877 } 878 case SQLITE_ATTACH: { 879 /* Deny the ATTACH if it is attaching anything other than an in-memory 880 ** database. */ 881 *pFlags |= BTS_NONSELECT; 882 if( zArg1==0 ) return SQLITE_DENY; 883 if( strcmp(zArg1,":memory:")==0 ) return SQLITE_OK; 884 if( sqlite3_strglob("file:*[?]vfs=memdb", zArg1)==0 885 && sqlite3_strglob("file:*[^/a-zA-Z0-9_.]*[?]vfs=memdb", zArg1)!=0 886 ){ 887 return SQLITE_OK; 888 } 889 return SQLITE_DENY; 890 } 891 case SQLITE_SELECT: { 892 *pFlags |= BTS_SELECT; 893 break; 894 } 895 case SQLITE_FUNCTION: { 896 static const char *azBadFuncs[] = { 897 "random", 898 "randomblob", 899 "rtreedepth", 900 }; 901 int i; 902 for(i=0; i<sizeof(azBadFuncs)/sizeof(azBadFuncs[0]); i++){ 903 if( sqlite3_stricmp(azBadFuncs[i], zArg2)==0 ){ 904 *pFlags |= BTS_BADFUNC; 905 break; 906 } 907 } 908 break; 909 } 910 case SQLITE_READ: { 911 /* Benign */ 912 break; 913 } 914 default: { 915 *pFlags |= BTS_NONSELECT; 916 } 917 } 918 return SQLITE_OK; 919 } 920 921 /* Implementation found in fuzzinvariant.c */ 922 int fuzz_invariant( 923 sqlite3 *db, /* The database connection */ 924 sqlite3_stmt *pStmt, /* Test statement stopped on an SQLITE_ROW */ 925 int iCnt, /* Invariant sequence number, starting at 0 */ 926 int iRow, /* The row number for pStmt */ 927 int *pbCorrupt /* IN/OUT: Flag indicating a corrupt database file */ 928 ); 929 930 /* 931 ** Run the SQL text 932 */ 933 static int runDbSql(sqlite3 *db, const char *zSql, unsigned int *pBtsFlags){ 934 int rc; 935 sqlite3_stmt *pStmt; 936 int bCorrupt = 0; 937 while( isspace(zSql[0]&0x7f) ) zSql++; 938 if( zSql[0]==0 ) return SQLITE_OK; 939 if( eVerbosity>=4 ){ 940 printf("RUNNING-SQL: [%s]\n", zSql); 941 fflush(stdout); 942 } 943 (*pBtsFlags) = 0; 944 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 945 if( rc==SQLITE_OK ){ 946 int nRow = 0; 947 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){ 948 nRow++; 949 if( (*pBtsFlags)==BTS_SELECT ){ 950 int iCnt = 0; 951 for(iCnt=0; iCnt<99999; iCnt++){ 952 rc = fuzz_invariant(db, pStmt, iCnt, nRow, &bCorrupt); 953 if( rc==SQLITE_DONE ) break; 954 if( eVerbosity>0 ){ 955 if( rc==SQLITE_OK ){ 956 printf("invariant-check: ok\n"); 957 }else if( rc==SQLITE_CORRUPT ){ 958 printf("invariant-check: failed due to database corruption\n"); 959 } 960 } 961 } 962 } 963 if( eVerbosity>=5 ){ 964 int j; 965 for(j=0; j<sqlite3_column_count(pStmt); j++){ 966 if( j ) printf(","); 967 switch( sqlite3_column_type(pStmt, j) ){ 968 case SQLITE_NULL: { 969 printf("NULL"); 970 break; 971 } 972 case SQLITE_INTEGER: 973 case SQLITE_FLOAT: { 974 printf("%s", sqlite3_column_text(pStmt, j)); 975 break; 976 } 977 case SQLITE_BLOB: { 978 int n = sqlite3_column_bytes(pStmt, j); 979 int i; 980 const unsigned char *a; 981 a = (const unsigned char*)sqlite3_column_blob(pStmt, j); 982 printf("x'"); 983 for(i=0; i<n; i++){ 984 printf("%02x", a[i]); 985 } 986 printf("'"); 987 break; 988 } 989 case SQLITE_TEXT: { 990 int n = sqlite3_column_bytes(pStmt, j); 991 int i; 992 const unsigned char *a; 993 a = (const unsigned char*)sqlite3_column_blob(pStmt, j); 994 printf("'"); 995 for(i=0; i<n; i++){ 996 if( a[i]=='\'' ){ 997 printf("''"); 998 }else{ 999 putchar(a[i]); 1000 } 1001 } 1002 printf("'"); 1003 break; 1004 } 1005 } /* End switch() */ 1006 } /* End for() */ 1007 printf("\n"); 1008 fflush(stdout); 1009 } /* End if( eVerbosity>=5 ) */ 1010 } /* End while( SQLITE_ROW */ 1011 if( rc!=SQLITE_DONE && eVerbosity>=4 ){ 1012 printf("SQL-ERROR: (%d) %s\n", rc, sqlite3_errmsg(db)); 1013 fflush(stdout); 1014 } 1015 }else if( eVerbosity>=4 ){ 1016 printf("SQL-ERROR (%d): %s\n", rc, sqlite3_errmsg(db)); 1017 fflush(stdout); 1018 } /* End if( SQLITE_OK ) */ 1019 return sqlite3_finalize(pStmt); 1020 } 1021 1022 /* Invoke this routine to run a single test case */ 1023 int runCombinedDbSqlInput( 1024 const uint8_t *aData, /* Combined DB+SQL content */ 1025 size_t nByte, /* Size of aData in bytes */ 1026 int iTimeout, /* Use this timeout */ 1027 int bScript, /* If true, just render CLI output */ 1028 int iSqlId /* SQL identifier */ 1029 ){ 1030 int rc; /* SQLite API return value */ 1031 int iSql; /* Index in aData[] of start of SQL */ 1032 unsigned char *aDb = 0; /* Decoded database content */ 1033 int nDb = 0; /* Size of the decoded database */ 1034 int i; /* Loop counter */ 1035 int j; /* Start of current SQL statement */ 1036 char *zSql = 0; /* SQL text to run */ 1037 int nSql; /* Bytes of SQL text */ 1038 FuzzCtx cx; /* Fuzzing context */ 1039 unsigned int btsFlags = 0; /* Parsing flags */ 1040 1041 if( nByte<10 ) return 0; 1042 if( sqlite3_initialize() ) return 0; 1043 if( sqlite3_memory_used()!=0 ){ 1044 int nAlloc = 0; 1045 int nNotUsed = 0; 1046 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0); 1047 fprintf(stderr,"memory leak prior to test start:" 1048 " %lld bytes in %d allocations\n", 1049 sqlite3_memory_used(), nAlloc); 1050 exit(1); 1051 } 1052 memset(&cx, 0, sizeof(cx)); 1053 iSql = decodeDatabase((unsigned char*)aData, (int)nByte, &aDb, &nDb); 1054 if( iSql<0 ) return 0; 1055 nSql = (int)(nByte - iSql); 1056 if( bScript ){ 1057 char zName[100]; 1058 sqlite3_snprintf(sizeof(zName),zName,"dbsql%06d.db",iSqlId); 1059 renderDbSqlForCLI(stdout, zName, aDb, nDb, 1060 (unsigned char*)(aData+iSql), nSql); 1061 sqlite3_free(aDb); 1062 return 0; 1063 } 1064 if( eVerbosity>=3 ){ 1065 printf( 1066 "****** %d-byte input, %d-byte database, %d-byte script " 1067 "******\n", (int)nByte, nDb, nSql); 1068 fflush(stdout); 1069 } 1070 rc = sqlite3_open(0, &cx.db); 1071 if( rc ){ 1072 sqlite3_free(aDb); 1073 return 1; 1074 } 1075 if( bVdbeDebug ){ 1076 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON", 0, 0, 0); 1077 } 1078 1079 /* Invoke the progress handler frequently to check to see if we 1080 ** are taking too long. The progress handler will return true 1081 ** (which will block further processing) if more than giTimeout seconds have 1082 ** elapsed since the start of the test. 1083 */ 1084 cx.iLastCb = timeOfDay(); 1085 cx.iCutoffTime = cx.iLastCb + (iTimeout<giTimeout ? iTimeout : giTimeout); 1086 cx.mxCb = mxProgressCb; 1087 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 1088 sqlite3_progress_handler(cx.db, 10, progress_handler, (void*)&cx); 1089 #endif 1090 1091 /* Set a limit on the maximum size of a prepared statement, and the 1092 ** maximum length of a string or blob */ 1093 if( vdbeOpLimit>0 ){ 1094 sqlite3_limit(cx.db, SQLITE_LIMIT_VDBE_OP, vdbeOpLimit); 1095 } 1096 if( lengthLimit>0 ){ 1097 sqlite3_limit(cx.db, SQLITE_LIMIT_LENGTH, lengthLimit); 1098 } 1099 if( depthLimit>0 ){ 1100 sqlite3_limit(cx.db, SQLITE_LIMIT_EXPR_DEPTH, depthLimit); 1101 } 1102 sqlite3_limit(cx.db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 100); 1103 sqlite3_hard_heap_limit64(heapLimit); 1104 1105 if( nDb>=20 && aDb[18]==2 && aDb[19]==2 ){ 1106 aDb[18] = aDb[19] = 1; 1107 } 1108 rc = sqlite3_deserialize(cx.db, "main", aDb, nDb, nDb, 1109 SQLITE_DESERIALIZE_RESIZEABLE | 1110 SQLITE_DESERIALIZE_FREEONCLOSE); 1111 if( rc ){ 1112 fprintf(stderr, "sqlite3_deserialize() failed with %d\n", rc); 1113 goto testrun_finished; 1114 } 1115 if( maxDbSize>0 ){ 1116 sqlite3_int64 x = maxDbSize; 1117 sqlite3_file_control(cx.db, "main", SQLITE_FCNTL_SIZE_LIMIT, &x); 1118 } 1119 1120 /* For high debugging levels, turn on debug mode */ 1121 if( eVerbosity>=5 ){ 1122 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON;", 0, 0, 0); 1123 } 1124 1125 /* Block debug pragmas and ATTACH/DETACH. But wait until after 1126 ** deserialize to do this because deserialize depends on ATTACH */ 1127 sqlite3_set_authorizer(cx.db, block_troublesome_sql, &btsFlags); 1128 1129 #ifdef VT02_SOURCES 1130 sqlite3_vt02_init(cx.db, 0, 0); 1131 #endif 1132 1133 /* Consistent PRNG seed */ 1134 #ifdef SQLITE_TESTCTRL_PRNG_SEED 1135 sqlite3_table_column_metadata(cx.db, 0, "x", 0, 0, 0, 0, 0, 0); 1136 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, cx.db); 1137 #else 1138 sqlite3_randomness(0,0); 1139 #endif 1140 1141 zSql = sqlite3_malloc( nSql + 1 ); 1142 if( zSql==0 ){ 1143 fprintf(stderr, "Out of memory!\n"); 1144 }else{ 1145 memcpy(zSql, aData+iSql, nSql); 1146 zSql[nSql] = 0; 1147 for(i=j=0; zSql[i]; i++){ 1148 if( zSql[i]==';' ){ 1149 char cSaved = zSql[i+1]; 1150 zSql[i+1] = 0; 1151 if( sqlite3_complete(zSql+j) ){ 1152 rc = runDbSql(cx.db, zSql+j, &btsFlags); 1153 j = i+1; 1154 } 1155 zSql[i+1] = cSaved; 1156 if( rc==SQLITE_INTERRUPT || progress_handler(&cx) ){ 1157 goto testrun_finished; 1158 } 1159 } 1160 } 1161 if( j<i ){ 1162 runDbSql(cx.db, zSql+j, &btsFlags); 1163 } 1164 } 1165 testrun_finished: 1166 sqlite3_free(zSql); 1167 rc = sqlite3_close(cx.db); 1168 if( rc!=SQLITE_OK ){ 1169 fprintf(stdout, "sqlite3_close() returns %d\n", rc); 1170 } 1171 if( eVerbosity>=2 && !bScript ){ 1172 fprintf(stdout, "Peak memory usages: %f MB\n", 1173 sqlite3_memory_highwater(1) / 1000000.0); 1174 } 1175 if( sqlite3_memory_used()!=0 ){ 1176 int nAlloc = 0; 1177 int nNotUsed = 0; 1178 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0); 1179 fprintf(stderr,"Memory leak: %lld bytes in %d allocations\n", 1180 sqlite3_memory_used(), nAlloc); 1181 exit(1); 1182 } 1183 sqlite3_hard_heap_limit64(0); 1184 sqlite3_soft_heap_limit64(0); 1185 return 0; 1186 } 1187 1188 /* 1189 ** END of the dbsqlfuzz code 1190 ***************************************************************************/ 1191 1192 /* Look at a SQL text and try to determine if it begins with a database 1193 ** description, such as would be found in a dbsqlfuzz test case. Return 1194 ** true if this does appear to be a dbsqlfuzz test case and false otherwise. 1195 */ 1196 static int isDbSql(unsigned char *a, int n){ 1197 unsigned char buf[12]; 1198 int i; 1199 if( n>4 && memcmp(a,"\n--\n",4)==0 ) return 1; 1200 while( n>0 && isspace(a[0]) ){ a++; n--; } 1201 for(i=0; n>0 && i<8; n--, a++){ 1202 if( isxdigit(a[0]) ) buf[i++] = a[0]; 1203 } 1204 if( i==8 && memcmp(buf,"53514c69",8)==0 ) return 1; 1205 return 0; 1206 } 1207 1208 /* Implementation of the isdbsql(TEXT) SQL function. 1209 */ 1210 static void isDbSqlFunc( 1211 sqlite3_context *context, 1212 int argc, 1213 sqlite3_value **argv 1214 ){ 1215 int n = sqlite3_value_bytes(argv[0]); 1216 unsigned char *a = (unsigned char*)sqlite3_value_blob(argv[0]); 1217 sqlite3_result_int(context, a!=0 && n>0 && isDbSql(a,n)); 1218 } 1219 1220 /* Methods for the VHandle object 1221 */ 1222 static int inmemClose(sqlite3_file *pFile){ 1223 VHandle *p = (VHandle*)pFile; 1224 VFile *pVFile = p->pVFile; 1225 pVFile->nRef--; 1226 if( pVFile->nRef==0 && pVFile->zFilename==0 ){ 1227 pVFile->sz = -1; 1228 free(pVFile->a); 1229 pVFile->a = 0; 1230 } 1231 return SQLITE_OK; 1232 } 1233 static int inmemRead( 1234 sqlite3_file *pFile, /* Read from this open file */ 1235 void *pData, /* Store content in this buffer */ 1236 int iAmt, /* Bytes of content */ 1237 sqlite3_int64 iOfst /* Start reading here */ 1238 ){ 1239 VHandle *pHandle = (VHandle*)pFile; 1240 VFile *pVFile = pHandle->pVFile; 1241 if( iOfst<0 || iOfst>=pVFile->sz ){ 1242 memset(pData, 0, iAmt); 1243 return SQLITE_IOERR_SHORT_READ; 1244 } 1245 if( iOfst+iAmt>pVFile->sz ){ 1246 memset(pData, 0, iAmt); 1247 iAmt = (int)(pVFile->sz - iOfst); 1248 memcpy(pData, pVFile->a + iOfst, iAmt); 1249 return SQLITE_IOERR_SHORT_READ; 1250 } 1251 memcpy(pData, pVFile->a + iOfst, iAmt); 1252 return SQLITE_OK; 1253 } 1254 static int inmemWrite( 1255 sqlite3_file *pFile, /* Write to this file */ 1256 const void *pData, /* Content to write */ 1257 int iAmt, /* bytes to write */ 1258 sqlite3_int64 iOfst /* Start writing here */ 1259 ){ 1260 VHandle *pHandle = (VHandle*)pFile; 1261 VFile *pVFile = pHandle->pVFile; 1262 if( iOfst+iAmt > pVFile->sz ){ 1263 if( iOfst+iAmt >= MX_FILE_SZ ){ 1264 return SQLITE_FULL; 1265 } 1266 pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt)); 1267 if( iOfst > pVFile->sz ){ 1268 memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz)); 1269 } 1270 pVFile->sz = (int)(iOfst + iAmt); 1271 } 1272 memcpy(pVFile->a + iOfst, pData, iAmt); 1273 return SQLITE_OK; 1274 } 1275 static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){ 1276 VHandle *pHandle = (VHandle*)pFile; 1277 VFile *pVFile = pHandle->pVFile; 1278 if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize; 1279 return SQLITE_OK; 1280 } 1281 static int inmemSync(sqlite3_file *pFile, int flags){ 1282 return SQLITE_OK; 1283 } 1284 static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){ 1285 *pSize = ((VHandle*)pFile)->pVFile->sz; 1286 return SQLITE_OK; 1287 } 1288 static int inmemLock(sqlite3_file *pFile, int type){ 1289 return SQLITE_OK; 1290 } 1291 static int inmemUnlock(sqlite3_file *pFile, int type){ 1292 return SQLITE_OK; 1293 } 1294 static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){ 1295 *pOut = 0; 1296 return SQLITE_OK; 1297 } 1298 static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){ 1299 return SQLITE_NOTFOUND; 1300 } 1301 static int inmemSectorSize(sqlite3_file *pFile){ 1302 return 512; 1303 } 1304 static int inmemDeviceCharacteristics(sqlite3_file *pFile){ 1305 return 1306 SQLITE_IOCAP_SAFE_APPEND | 1307 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | 1308 SQLITE_IOCAP_POWERSAFE_OVERWRITE; 1309 } 1310 1311 1312 /* Method table for VHandle 1313 */ 1314 static sqlite3_io_methods VHandleMethods = { 1315 /* iVersion */ 1, 1316 /* xClose */ inmemClose, 1317 /* xRead */ inmemRead, 1318 /* xWrite */ inmemWrite, 1319 /* xTruncate */ inmemTruncate, 1320 /* xSync */ inmemSync, 1321 /* xFileSize */ inmemFileSize, 1322 /* xLock */ inmemLock, 1323 /* xUnlock */ inmemUnlock, 1324 /* xCheck... */ inmemCheckReservedLock, 1325 /* xFileCtrl */ inmemFileControl, 1326 /* xSectorSz */ inmemSectorSize, 1327 /* xDevchar */ inmemDeviceCharacteristics, 1328 /* xShmMap */ 0, 1329 /* xShmLock */ 0, 1330 /* xShmBarrier */ 0, 1331 /* xShmUnmap */ 0, 1332 /* xFetch */ 0, 1333 /* xUnfetch */ 0 1334 }; 1335 1336 /* 1337 ** Open a new file in the inmem VFS. All files are anonymous and are 1338 ** delete-on-close. 1339 */ 1340 static int inmemOpen( 1341 sqlite3_vfs *pVfs, 1342 const char *zFilename, 1343 sqlite3_file *pFile, 1344 int openFlags, 1345 int *pOutFlags 1346 ){ 1347 VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)""); 1348 VHandle *pHandle = (VHandle*)pFile; 1349 if( pVFile==0 ){ 1350 return SQLITE_FULL; 1351 } 1352 pHandle->pVFile = pVFile; 1353 pVFile->nRef++; 1354 pFile->pMethods = &VHandleMethods; 1355 if( pOutFlags ) *pOutFlags = openFlags; 1356 return SQLITE_OK; 1357 } 1358 1359 /* 1360 ** Delete a file by name 1361 */ 1362 static int inmemDelete( 1363 sqlite3_vfs *pVfs, 1364 const char *zFilename, 1365 int syncdir 1366 ){ 1367 VFile *pVFile = findVFile(zFilename); 1368 if( pVFile==0 ) return SQLITE_OK; 1369 if( pVFile->nRef==0 ){ 1370 free(pVFile->zFilename); 1371 pVFile->zFilename = 0; 1372 pVFile->sz = -1; 1373 free(pVFile->a); 1374 pVFile->a = 0; 1375 return SQLITE_OK; 1376 } 1377 return SQLITE_IOERR_DELETE; 1378 } 1379 1380 /* Check for the existance of a file 1381 */ 1382 static int inmemAccess( 1383 sqlite3_vfs *pVfs, 1384 const char *zFilename, 1385 int flags, 1386 int *pResOut 1387 ){ 1388 VFile *pVFile = findVFile(zFilename); 1389 *pResOut = pVFile!=0; 1390 return SQLITE_OK; 1391 } 1392 1393 /* Get the canonical pathname for a file 1394 */ 1395 static int inmemFullPathname( 1396 sqlite3_vfs *pVfs, 1397 const char *zFilename, 1398 int nOut, 1399 char *zOut 1400 ){ 1401 sqlite3_snprintf(nOut, zOut, "%s", zFilename); 1402 return SQLITE_OK; 1403 } 1404 1405 /* Always use the same random see, for repeatability. 1406 */ 1407 static int inmemRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ 1408 memset(zBuf, 0, nBuf); 1409 memcpy(zBuf, &g.uRandom, nBuf<sizeof(g.uRandom) ? nBuf : sizeof(g.uRandom)); 1410 return nBuf; 1411 } 1412 1413 /* 1414 ** Register the VFS that reads from the g.aFile[] set of files. 1415 */ 1416 static void inmemVfsRegister(int makeDefault){ 1417 static sqlite3_vfs inmemVfs; 1418 sqlite3_vfs *pDefault = sqlite3_vfs_find(0); 1419 inmemVfs.iVersion = 3; 1420 inmemVfs.szOsFile = sizeof(VHandle); 1421 inmemVfs.mxPathname = 200; 1422 inmemVfs.zName = "inmem"; 1423 inmemVfs.xOpen = inmemOpen; 1424 inmemVfs.xDelete = inmemDelete; 1425 inmemVfs.xAccess = inmemAccess; 1426 inmemVfs.xFullPathname = inmemFullPathname; 1427 inmemVfs.xRandomness = inmemRandomness; 1428 inmemVfs.xSleep = pDefault->xSleep; 1429 inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64; 1430 sqlite3_vfs_register(&inmemVfs, makeDefault); 1431 }; 1432 1433 /* 1434 ** Allowed values for the runFlags parameter to runSql() 1435 */ 1436 #define SQL_TRACE 0x0001 /* Print each SQL statement as it is prepared */ 1437 #define SQL_OUTPUT 0x0002 /* Show the SQL output */ 1438 1439 /* 1440 ** Run multiple commands of SQL. Similar to sqlite3_exec(), but does not 1441 ** stop if an error is encountered. 1442 */ 1443 static void runSql(sqlite3 *db, const char *zSql, unsigned runFlags){ 1444 const char *zMore; 1445 sqlite3_stmt *pStmt; 1446 1447 while( zSql && zSql[0] ){ 1448 zMore = 0; 1449 pStmt = 0; 1450 sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore); 1451 if( zMore==zSql ) break; 1452 if( runFlags & SQL_TRACE ){ 1453 const char *z = zSql; 1454 int n; 1455 while( z<zMore && ISSPACE(z[0]) ) z++; 1456 n = (int)(zMore - z); 1457 while( n>0 && ISSPACE(z[n-1]) ) n--; 1458 if( n==0 ) break; 1459 if( pStmt==0 ){ 1460 printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db)); 1461 }else{ 1462 printf("TRACE: %.*s\n", n, z); 1463 } 1464 } 1465 zSql = zMore; 1466 if( pStmt ){ 1467 if( (runFlags & SQL_OUTPUT)==0 ){ 1468 while( SQLITE_ROW==sqlite3_step(pStmt) ){} 1469 }else{ 1470 int nCol = -1; 1471 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 1472 int i; 1473 if( nCol<0 ){ 1474 nCol = sqlite3_column_count(pStmt); 1475 }else if( nCol>0 ){ 1476 printf("--------------------------------------------\n"); 1477 } 1478 for(i=0; i<nCol; i++){ 1479 int eType = sqlite3_column_type(pStmt,i); 1480 printf("%s = ", sqlite3_column_name(pStmt,i)); 1481 switch( eType ){ 1482 case SQLITE_NULL: { 1483 printf("NULL\n"); 1484 break; 1485 } 1486 case SQLITE_INTEGER: { 1487 printf("INT %s\n", sqlite3_column_text(pStmt,i)); 1488 break; 1489 } 1490 case SQLITE_FLOAT: { 1491 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i)); 1492 break; 1493 } 1494 case SQLITE_TEXT: { 1495 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i)); 1496 break; 1497 } 1498 case SQLITE_BLOB: { 1499 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i)); 1500 break; 1501 } 1502 } 1503 } 1504 } 1505 } 1506 sqlite3_finalize(pStmt); 1507 } 1508 } 1509 } 1510 1511 /* 1512 ** Rebuild the database file. 1513 ** 1514 ** (1) Remove duplicate entries 1515 ** (2) Put all entries in order 1516 ** (3) Vacuum 1517 */ 1518 static void rebuild_database(sqlite3 *db, int dbSqlOnly){ 1519 int rc; 1520 char *zSql; 1521 zSql = sqlite3_mprintf( 1522 "BEGIN;\n" 1523 "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n" 1524 "DELETE FROM db;\n" 1525 "INSERT INTO db(dbid, dbcontent) " 1526 " SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n" 1527 "DROP TABLE dbx;\n" 1528 "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql %s;\n" 1529 "DELETE FROM xsql;\n" 1530 "INSERT INTO xsql(sqlid,sqltext) " 1531 " SELECT NULL, sqltext FROM sx ORDER BY 2;\n" 1532 "DROP TABLE sx;\n" 1533 "COMMIT;\n" 1534 "PRAGMA page_size=1024;\n" 1535 "VACUUM;\n", 1536 dbSqlOnly ? " WHERE isdbsql(sqltext)" : "" 1537 ); 1538 rc = sqlite3_exec(db, zSql, 0, 0, 0); 1539 sqlite3_free(zSql); 1540 if( rc ) fatalError("cannot rebuild: %s", sqlite3_errmsg(db)); 1541 } 1542 1543 /* 1544 ** Return the value of a hexadecimal digit. Return -1 if the input 1545 ** is not a hex digit. 1546 */ 1547 static int hexDigitValue(char c){ 1548 if( c>='0' && c<='9' ) return c - '0'; 1549 if( c>='a' && c<='f' ) return c - 'a' + 10; 1550 if( c>='A' && c<='F' ) return c - 'A' + 10; 1551 return -1; 1552 } 1553 1554 /* 1555 ** Interpret zArg as an integer value, possibly with suffixes. 1556 */ 1557 static int integerValue(const char *zArg){ 1558 sqlite3_int64 v = 0; 1559 static const struct { char *zSuffix; int iMult; } aMult[] = { 1560 { "KiB", 1024 }, 1561 { "MiB", 1024*1024 }, 1562 { "GiB", 1024*1024*1024 }, 1563 { "KB", 1000 }, 1564 { "MB", 1000000 }, 1565 { "GB", 1000000000 }, 1566 { "K", 1000 }, 1567 { "M", 1000000 }, 1568 { "G", 1000000000 }, 1569 }; 1570 int i; 1571 int isNeg = 0; 1572 if( zArg[0]=='-' ){ 1573 isNeg = 1; 1574 zArg++; 1575 }else if( zArg[0]=='+' ){ 1576 zArg++; 1577 } 1578 if( zArg[0]=='0' && zArg[1]=='x' ){ 1579 int x; 1580 zArg += 2; 1581 while( (x = hexDigitValue(zArg[0]))>=0 ){ 1582 v = (v<<4) + x; 1583 zArg++; 1584 } 1585 }else{ 1586 while( ISDIGIT(zArg[0]) ){ 1587 v = v*10 + zArg[0] - '0'; 1588 zArg++; 1589 } 1590 } 1591 for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){ 1592 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ 1593 v *= aMult[i].iMult; 1594 break; 1595 } 1596 } 1597 if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648"); 1598 return (int)(isNeg? -v : v); 1599 } 1600 1601 /* 1602 ** Return the number of "v" characters in a string. Return 0 if there 1603 ** are any characters in the string other than "v". 1604 */ 1605 static int numberOfVChar(const char *z){ 1606 int N = 0; 1607 while( z[0] && z[0]=='v' ){ 1608 z++; 1609 N++; 1610 } 1611 return z[0]==0 ? N : 0; 1612 } 1613 1614 /* 1615 ** Print sketchy documentation for this utility program 1616 */ 1617 static void showHelp(void){ 1618 printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0); 1619 printf( 1620 "Read databases and SQL scripts from SOURCE-DB and execute each script against\n" 1621 "each database, checking for crashes and memory leaks.\n" 1622 "Options:\n" 1623 " --cell-size-check Set the PRAGMA cell_size_check=ON\n" 1624 " --dbid N Use only the database where dbid=N\n" 1625 " --export-db DIR Write databases to files(s) in DIR. Works with --dbid\n" 1626 " --export-sql DIR Write SQL to file(s) in DIR. Also works with --sqlid\n" 1627 " --help Show this help text\n" 1628 " --info Show information about SOURCE-DB w/o running tests\n" 1629 " --limit-depth N Limit expression depth to N. Default: 500\n" 1630 " --limit-heap N Limit heap memory to N. Default: 100M\n" 1631 " --limit-mem N Limit memory used by test SQLite instance to N bytes\n" 1632 " --limit-vdbe Panic if any test runs for more than 100,000 cycles\n" 1633 " --load-sql FILE.. Load SQL scripts fron files into SOURCE-DB\n" 1634 " --load-db FILE.. Load template databases from files into SOURCE_DB\n" 1635 " --load-dbsql FILE.. Load dbsqlfuzz outputs into the xsql table\n" 1636 " ^^^^------ Use \"-\" for FILE to read filenames from stdin\n" 1637 " -m TEXT Add a description to the database\n" 1638 " --native-vfs Use the native VFS for initially empty database files\n" 1639 " --native-malloc Turn off MEMSYS3/5 and Lookaside\n" 1640 " --oss-fuzz Enable OSS-FUZZ testing\n" 1641 " --prng-seed N Seed value for the PRGN inside of SQLite\n" 1642 " -q|--quiet Reduced output\n" 1643 " --rebuild Rebuild and vacuum the database file\n" 1644 " --result-trace Show the results of each SQL command\n" 1645 " --script Output CLI script instead of running tests\n" 1646 " --skip N Skip the first N test cases\n" 1647 " --spinner Use a spinner to show progress\n" 1648 " --sqlid N Use only SQL where sqlid=N\n" 1649 " --timeout N Maximum time for any one test in N millseconds\n" 1650 " -v|--verbose Increased output. Repeat for more output.\n" 1651 " --vdbe-debug Activate VDBE debugging.\n" 1652 ); 1653 } 1654 1655 int main(int argc, char **argv){ 1656 sqlite3_int64 iBegin; /* Start time of this program */ 1657 int quietFlag = 0; /* True if --quiet or -q */ 1658 int verboseFlag = 0; /* True if --verbose or -v */ 1659 char *zInsSql = 0; /* SQL statement for --load-db or --load-sql */ 1660 int iFirstInsArg = 0; /* First argv[] for --load-db or --load-sql */ 1661 sqlite3 *db = 0; /* The open database connection */ 1662 sqlite3_stmt *pStmt; /* A prepared statement */ 1663 int rc; /* Result code from SQLite interface calls */ 1664 Blob *pSql; /* For looping over SQL scripts */ 1665 Blob *pDb; /* For looping over template databases */ 1666 int i; /* Loop index for the argv[] loop */ 1667 int dbSqlOnly = 0; /* Only use scripts that are dbsqlfuzz */ 1668 int onlySqlid = -1; /* --sqlid */ 1669 int onlyDbid = -1; /* --dbid */ 1670 int nativeFlag = 0; /* --native-vfs */ 1671 int rebuildFlag = 0; /* --rebuild */ 1672 int vdbeLimitFlag = 0; /* --limit-vdbe */ 1673 int infoFlag = 0; /* --info */ 1674 int nSkip = 0; /* --skip */ 1675 int bScript = 0; /* --script */ 1676 int bSpinner = 0; /* True for --spinner */ 1677 int timeoutTest = 0; /* undocumented --timeout-test flag */ 1678 int runFlags = 0; /* Flags sent to runSql() */ 1679 char *zMsg = 0; /* Add this message */ 1680 int nSrcDb = 0; /* Number of source databases */ 1681 char **azSrcDb = 0; /* Array of source database names */ 1682 int iSrcDb; /* Loop over all source databases */ 1683 int nTest = 0; /* Total number of tests performed */ 1684 char *zDbName = ""; /* Appreviated name of a source database */ 1685 const char *zFailCode = 0; /* Value of the TEST_FAILURE env variable */ 1686 int cellSzCkFlag = 0; /* --cell-size-check */ 1687 int sqlFuzz = 0; /* True for SQL fuzz. False for DB fuzz */ 1688 int iTimeout = 120000; /* Default 120-second timeout */ 1689 int nMem = 0; /* Memory limit override */ 1690 int nMemThisDb = 0; /* Memory limit set by the CONFIG table */ 1691 char *zExpDb = 0; /* Write Databases to files in this directory */ 1692 char *zExpSql = 0; /* Write SQL to files in this directory */ 1693 void *pHeap = 0; /* Heap for use by SQLite */ 1694 int ossFuzz = 0; /* enable OSS-FUZZ testing */ 1695 int ossFuzzThisDb = 0; /* ossFuzz value for this particular database */ 1696 int nativeMalloc = 0; /* Turn off MEMSYS3/5 and lookaside if true */ 1697 sqlite3_vfs *pDfltVfs; /* The default VFS */ 1698 int openFlags4Data; /* Flags for sqlite3_open_v2() */ 1699 int bTimer = 0; /* Show elapse time for each test */ 1700 int nV; /* How much to increase verbosity with -vvvv */ 1701 sqlite3_int64 tmStart; /* Start of each test */ 1702 1703 sqlite3_config(SQLITE_CONFIG_URI,1); 1704 registerOomSimulator(); 1705 sqlite3_initialize(); 1706 iBegin = timeOfDay(); 1707 #ifdef __unix__ 1708 signal(SIGALRM, signalHandler); 1709 signal(SIGSEGV, signalHandler); 1710 signal(SIGABRT, signalHandler); 1711 #endif 1712 g.zArgv0 = argv[0]; 1713 openFlags4Data = SQLITE_OPEN_READONLY; 1714 zFailCode = getenv("TEST_FAILURE"); 1715 pDfltVfs = sqlite3_vfs_find(0); 1716 inmemVfsRegister(1); 1717 for(i=1; i<argc; i++){ 1718 const char *z = argv[i]; 1719 if( z[0]=='-' ){ 1720 z++; 1721 if( z[0]=='-' ) z++; 1722 if( strcmp(z,"cell-size-check")==0 ){ 1723 cellSzCkFlag = 1; 1724 }else 1725 if( strcmp(z,"dbid")==0 ){ 1726 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1727 onlyDbid = integerValue(argv[++i]); 1728 }else 1729 if( strcmp(z,"export-db")==0 ){ 1730 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1731 zExpDb = argv[++i]; 1732 }else 1733 if( strcmp(z,"export-sql")==0 || strcmp(z,"export-dbsql")==0 ){ 1734 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1735 zExpSql = argv[++i]; 1736 }else 1737 if( strcmp(z,"help")==0 ){ 1738 showHelp(); 1739 return 0; 1740 }else 1741 if( strcmp(z,"info")==0 ){ 1742 infoFlag = 1; 1743 }else 1744 if( strcmp(z,"limit-depth")==0 ){ 1745 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1746 depthLimit = integerValue(argv[++i]); 1747 }else 1748 if( strcmp(z,"limit-heap")==0 ){ 1749 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1750 heapLimit = integerValue(argv[++i]); 1751 }else 1752 if( strcmp(z,"limit-mem")==0 ){ 1753 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1754 nMem = integerValue(argv[++i]); 1755 }else 1756 if( strcmp(z,"limit-vdbe")==0 ){ 1757 vdbeLimitFlag = 1; 1758 }else 1759 if( strcmp(z,"load-sql")==0 ){ 1760 zInsSql = "INSERT INTO xsql(sqltext)" 1761 "VALUES(CAST(readtextfile(?1) AS text))"; 1762 iFirstInsArg = i+1; 1763 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 1764 break; 1765 }else 1766 if( strcmp(z,"load-db")==0 ){ 1767 zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))"; 1768 iFirstInsArg = i+1; 1769 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 1770 break; 1771 }else 1772 if( strcmp(z,"load-dbsql")==0 ){ 1773 zInsSql = "INSERT INTO xsql(sqltext)" 1774 "VALUES(readfile(?1))"; 1775 iFirstInsArg = i+1; 1776 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 1777 dbSqlOnly = 1; 1778 break; 1779 }else 1780 if( strcmp(z,"m")==0 ){ 1781 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1782 zMsg = argv[++i]; 1783 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 1784 }else 1785 if( strcmp(z,"native-malloc")==0 ){ 1786 nativeMalloc = 1; 1787 }else 1788 if( strcmp(z,"native-vfs")==0 ){ 1789 nativeFlag = 1; 1790 }else 1791 if( strcmp(z,"oss-fuzz")==0 ){ 1792 ossFuzz = 1; 1793 }else 1794 if( strcmp(z,"prng-seed")==0 ){ 1795 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1796 g.uRandom = atoi(argv[++i]); 1797 }else 1798 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ 1799 quietFlag = 1; 1800 verboseFlag = 0; 1801 eVerbosity = 0; 1802 }else 1803 if( strcmp(z,"rebuild")==0 ){ 1804 rebuildFlag = 1; 1805 openFlags4Data = SQLITE_OPEN_READWRITE; 1806 }else 1807 if( strcmp(z,"result-trace")==0 ){ 1808 runFlags |= SQL_OUTPUT; 1809 }else 1810 if( strcmp(z,"script")==0 ){ 1811 bScript = 1; 1812 }else 1813 if( strcmp(z,"skip")==0 ){ 1814 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1815 nSkip = atoi(argv[++i]); 1816 }else 1817 if( strcmp(z,"spinner")==0 ){ 1818 bSpinner = 1; 1819 }else 1820 if( strcmp(z,"timer")==0 ){ 1821 bTimer = 1; 1822 }else 1823 if( strcmp(z,"sqlid")==0 ){ 1824 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1825 onlySqlid = integerValue(argv[++i]); 1826 }else 1827 if( strcmp(z,"timeout")==0 ){ 1828 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1829 iTimeout = integerValue(argv[++i]); 1830 }else 1831 if( strcmp(z,"timeout-test")==0 ){ 1832 timeoutTest = 1; 1833 #ifndef __unix__ 1834 fatalError("timeout is not available on non-unix systems"); 1835 #endif 1836 }else 1837 if( strcmp(z,"vdbe-debug")==0 ){ 1838 bVdbeDebug = 1; 1839 }else 1840 if( strcmp(z,"verbose")==0 ){ 1841 quietFlag = 0; 1842 verboseFlag++; 1843 eVerbosity++; 1844 if( verboseFlag>1 ) runFlags |= SQL_TRACE; 1845 }else 1846 if( (nV = numberOfVChar(z))>=1 ){ 1847 quietFlag = 0; 1848 verboseFlag += nV; 1849 eVerbosity += nV; 1850 if( verboseFlag>1 ) runFlags |= SQL_TRACE; 1851 }else 1852 if( strcmp(z,"version")==0 ){ 1853 int ii; 1854 const char *zz; 1855 printf("SQLite %s %s\n", sqlite3_libversion(), sqlite3_sourceid()); 1856 for(ii=0; (zz = sqlite3_compileoption_get(ii))!=0; ii++){ 1857 printf("%s\n", zz); 1858 } 1859 return 0; 1860 }else 1861 if( strcmp(z,"is-dbsql")==0 ){ 1862 i++; 1863 for(i++; i<argc; i++){ 1864 long nData; 1865 char *aData = readFile(argv[i], &nData); 1866 printf("%d %s\n", isDbSql((unsigned char*)aData,nData), argv[i]); 1867 sqlite3_free(aData); 1868 } 1869 exit(0); 1870 }else 1871 { 1872 fatalError("unknown option: %s", argv[i]); 1873 } 1874 }else{ 1875 nSrcDb++; 1876 azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0])); 1877 azSrcDb[nSrcDb-1] = argv[i]; 1878 } 1879 } 1880 if( nSrcDb==0 ) fatalError("no source database specified"); 1881 if( nSrcDb>1 ){ 1882 if( zMsg ){ 1883 fatalError("cannot change the description of more than one database"); 1884 } 1885 if( zInsSql ){ 1886 fatalError("cannot import into more than one database"); 1887 } 1888 } 1889 1890 /* Process each source database separately */ 1891 for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){ 1892 char *zRawData = 0; 1893 long nRawData = 0; 1894 g.zDbFile = azSrcDb[iSrcDb]; 1895 rc = sqlite3_open_v2(azSrcDb[iSrcDb], &db, 1896 openFlags4Data, pDfltVfs->zName); 1897 if( rc==SQLITE_OK ){ 1898 rc = sqlite3_exec(db, "SELECT count(*) FROM sqlite_schema", 0, 0, 0); 1899 } 1900 if( rc ){ 1901 sqlite3_close(db); 1902 zRawData = readFile(azSrcDb[iSrcDb], &nRawData); 1903 if( zRawData==0 ){ 1904 fatalError("input file \"%s\" is not recognized\n", azSrcDb[iSrcDb]); 1905 } 1906 sqlite3_open(":memory:", &db); 1907 } 1908 1909 /* Print the description, if there is one */ 1910 if( infoFlag ){ 1911 int n; 1912 zDbName = azSrcDb[iSrcDb]; 1913 i = (int)strlen(zDbName) - 1; 1914 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; } 1915 zDbName += i; 1916 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0); 1917 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 1918 printf("%s: %s", zDbName, sqlite3_column_text(pStmt,0)); 1919 }else{ 1920 printf("%s: (empty \"readme\")", zDbName); 1921 } 1922 sqlite3_finalize(pStmt); 1923 sqlite3_prepare_v2(db, "SELECT count(*) FROM db", -1, &pStmt, 0); 1924 if( pStmt 1925 && sqlite3_step(pStmt)==SQLITE_ROW 1926 && (n = sqlite3_column_int(pStmt,0))>0 1927 ){ 1928 printf(" - %d DBs", n); 1929 } 1930 sqlite3_finalize(pStmt); 1931 sqlite3_prepare_v2(db, "SELECT count(*) FROM xsql", -1, &pStmt, 0); 1932 if( pStmt 1933 && sqlite3_step(pStmt)==SQLITE_ROW 1934 && (n = sqlite3_column_int(pStmt,0))>0 1935 ){ 1936 printf(" - %d scripts", n); 1937 } 1938 sqlite3_finalize(pStmt); 1939 printf("\n"); 1940 sqlite3_close(db); 1941 sqlite3_free(zRawData); 1942 continue; 1943 } 1944 1945 rc = sqlite3_exec(db, 1946 "CREATE TABLE IF NOT EXISTS db(\n" 1947 " dbid INTEGER PRIMARY KEY, -- database id\n" 1948 " dbcontent BLOB -- database disk file image\n" 1949 ");\n" 1950 "CREATE TABLE IF NOT EXISTS xsql(\n" 1951 " sqlid INTEGER PRIMARY KEY, -- SQL script id\n" 1952 " sqltext TEXT -- Text of SQL statements to run\n" 1953 ");" 1954 "CREATE TABLE IF NOT EXISTS readme(\n" 1955 " msg TEXT -- Human-readable description of this file\n" 1956 ");", 0, 0, 0); 1957 if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db)); 1958 if( zMsg ){ 1959 char *zSql; 1960 zSql = sqlite3_mprintf( 1961 "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg); 1962 rc = sqlite3_exec(db, zSql, 0, 0, 0); 1963 sqlite3_free(zSql); 1964 if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db)); 1965 } 1966 if( zRawData ){ 1967 zInsSql = "INSERT INTO xsql(sqltext) VALUES(?1)"; 1968 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0); 1969 if( rc ) fatalError("cannot prepare statement [%s]: %s", 1970 zInsSql, sqlite3_errmsg(db)); 1971 sqlite3_bind_text(pStmt, 1, zRawData, nRawData, SQLITE_STATIC); 1972 sqlite3_step(pStmt); 1973 rc = sqlite3_reset(pStmt); 1974 if( rc ) fatalError("insert failed for %s", argv[i]); 1975 sqlite3_finalize(pStmt); 1976 rebuild_database(db, dbSqlOnly); 1977 zInsSql = 0; 1978 sqlite3_free(zRawData); 1979 zRawData = 0; 1980 } 1981 ossFuzzThisDb = ossFuzz; 1982 1983 /* If the CONFIG(name,value) table exists, read db-specific settings 1984 ** from that table */ 1985 if( sqlite3_table_column_metadata(db,0,"config",0,0,0,0,0,0)==SQLITE_OK ){ 1986 rc = sqlite3_prepare_v2(db, "SELECT name, value FROM config", 1987 -1, &pStmt, 0); 1988 if( rc ) fatalError("cannot prepare query of CONFIG table: %s", 1989 sqlite3_errmsg(db)); 1990 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 1991 const char *zName = (const char *)sqlite3_column_text(pStmt,0); 1992 if( zName==0 ) continue; 1993 if( strcmp(zName, "oss-fuzz")==0 ){ 1994 ossFuzzThisDb = sqlite3_column_int(pStmt,1); 1995 if( verboseFlag ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb); 1996 } 1997 if( strcmp(zName, "limit-mem")==0 ){ 1998 nMemThisDb = sqlite3_column_int(pStmt,1); 1999 if( verboseFlag ) printf("Config: limit-mem=%d\n", nMemThisDb); 2000 } 2001 } 2002 sqlite3_finalize(pStmt); 2003 } 2004 2005 if( zInsSql ){ 2006 sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0, 2007 readfileFunc, 0, 0); 2008 sqlite3_create_function(db, "readtextfile", 1, SQLITE_UTF8, 0, 2009 readtextfileFunc, 0, 0); 2010 sqlite3_create_function(db, "isdbsql", 1, SQLITE_UTF8, 0, 2011 isDbSqlFunc, 0, 0); 2012 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0); 2013 if( rc ) fatalError("cannot prepare statement [%s]: %s", 2014 zInsSql, sqlite3_errmsg(db)); 2015 rc = sqlite3_exec(db, "BEGIN", 0, 0, 0); 2016 if( rc ) fatalError("cannot start a transaction"); 2017 for(i=iFirstInsArg; i<argc; i++){ 2018 if( strcmp(argv[i],"-")==0 ){ 2019 /* A filename of "-" means read multiple filenames from stdin */ 2020 char zLine[2000]; 2021 while( rc==0 && fgets(zLine,sizeof(zLine),stdin)!=0 ){ 2022 size_t kk = strlen(zLine); 2023 while( kk>0 && zLine[kk-1]<=' ' ) kk--; 2024 sqlite3_bind_text(pStmt, 1, zLine, (int)kk, SQLITE_STATIC); 2025 if( verboseFlag ) printf("loading %.*s\n", (int)kk, zLine); 2026 sqlite3_step(pStmt); 2027 rc = sqlite3_reset(pStmt); 2028 if( rc ) fatalError("insert failed for %s", zLine); 2029 } 2030 }else{ 2031 sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC); 2032 if( verboseFlag ) printf("loading %s\n", argv[i]); 2033 sqlite3_step(pStmt); 2034 rc = sqlite3_reset(pStmt); 2035 if( rc ) fatalError("insert failed for %s", argv[i]); 2036 } 2037 } 2038 sqlite3_finalize(pStmt); 2039 rc = sqlite3_exec(db, "COMMIT", 0, 0, 0); 2040 if( rc ) fatalError("cannot commit the transaction: %s", 2041 sqlite3_errmsg(db)); 2042 rebuild_database(db, dbSqlOnly); 2043 sqlite3_close(db); 2044 return 0; 2045 } 2046 rc = sqlite3_exec(db, "PRAGMA query_only=1;", 0, 0, 0); 2047 if( rc ) fatalError("cannot set database to query-only"); 2048 if( zExpDb!=0 || zExpSql!=0 ){ 2049 sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0, 2050 writefileFunc, 0, 0); 2051 if( zExpDb!=0 ){ 2052 const char *zExDb = 2053 "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent)," 2054 " dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)" 2055 " FROM db WHERE ?2<0 OR dbid=?2;"; 2056 rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0); 2057 if( rc ) fatalError("cannot prepare statement [%s]: %s", 2058 zExDb, sqlite3_errmsg(db)); 2059 sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb), 2060 SQLITE_STATIC, SQLITE_UTF8); 2061 sqlite3_bind_int(pStmt, 2, onlyDbid); 2062 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 2063 printf("write db-%d (%d bytes) into %s\n", 2064 sqlite3_column_int(pStmt,1), 2065 sqlite3_column_int(pStmt,3), 2066 sqlite3_column_text(pStmt,2)); 2067 } 2068 sqlite3_finalize(pStmt); 2069 } 2070 if( zExpSql!=0 ){ 2071 const char *zExSql = 2072 "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext)," 2073 " sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)" 2074 " FROM xsql WHERE ?2<0 OR sqlid=?2;"; 2075 rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0); 2076 if( rc ) fatalError("cannot prepare statement [%s]: %s", 2077 zExSql, sqlite3_errmsg(db)); 2078 sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql), 2079 SQLITE_STATIC, SQLITE_UTF8); 2080 sqlite3_bind_int(pStmt, 2, onlySqlid); 2081 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 2082 printf("write sql-%d (%d bytes) into %s\n", 2083 sqlite3_column_int(pStmt,1), 2084 sqlite3_column_int(pStmt,3), 2085 sqlite3_column_text(pStmt,2)); 2086 } 2087 sqlite3_finalize(pStmt); 2088 } 2089 sqlite3_close(db); 2090 return 0; 2091 } 2092 2093 /* Load all SQL script content and all initial database images from the 2094 ** source db 2095 */ 2096 blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid, 2097 &g.nSql, &g.pFirstSql); 2098 if( g.nSql==0 ) fatalError("need at least one SQL script"); 2099 blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid, 2100 &g.nDb, &g.pFirstDb); 2101 if( g.nDb==0 ){ 2102 g.pFirstDb = safe_realloc(0, sizeof(Blob)); 2103 memset(g.pFirstDb, 0, sizeof(Blob)); 2104 g.pFirstDb->id = 1; 2105 g.pFirstDb->seq = 0; 2106 g.nDb = 1; 2107 sqlFuzz = 1; 2108 } 2109 2110 /* Print the description, if there is one */ 2111 if( !quietFlag && !bScript ){ 2112 zDbName = azSrcDb[iSrcDb]; 2113 i = (int)strlen(zDbName) - 1; 2114 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; } 2115 zDbName += i; 2116 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0); 2117 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 2118 printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0)); 2119 } 2120 sqlite3_finalize(pStmt); 2121 } 2122 2123 /* Rebuild the database, if requested */ 2124 if( rebuildFlag ){ 2125 if( !quietFlag ){ 2126 printf("%s: rebuilding... ", zDbName); 2127 fflush(stdout); 2128 } 2129 rebuild_database(db, 0); 2130 if( !quietFlag ) printf("done\n"); 2131 } 2132 2133 /* Close the source database. Verify that no SQLite memory allocations are 2134 ** outstanding. 2135 */ 2136 sqlite3_close(db); 2137 if( sqlite3_memory_used()>0 ){ 2138 fatalError("SQLite has memory in use before the start of testing"); 2139 } 2140 2141 /* Limit available memory, if requested */ 2142 sqlite3_shutdown(); 2143 2144 if( nMemThisDb>0 && nMem==0 ){ 2145 if( !nativeMalloc ){ 2146 pHeap = realloc(pHeap, nMemThisDb); 2147 if( pHeap==0 ){ 2148 fatalError("failed to allocate %d bytes of heap memory", nMem); 2149 } 2150 sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMemThisDb, 128); 2151 }else{ 2152 sqlite3_hard_heap_limit64((sqlite3_int64)nMemThisDb); 2153 } 2154 }else{ 2155 sqlite3_hard_heap_limit64(0); 2156 } 2157 2158 /* Disable lookaside with the --native-malloc option */ 2159 if( nativeMalloc ){ 2160 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0); 2161 } 2162 2163 /* Reset the in-memory virtual filesystem */ 2164 formatVfs(); 2165 2166 /* Run a test using each SQL script against each database. 2167 */ 2168 if( !verboseFlag && !quietFlag && !bSpinner && !bScript ){ 2169 printf("%s:", zDbName); 2170 } 2171 for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){ 2172 tmStart = timeOfDay(); 2173 if( isDbSql(pSql->a, pSql->sz) ){ 2174 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d",pSql->id); 2175 if( bScript ){ 2176 /* No progress output */ 2177 }else if( bSpinner ){ 2178 int nTotal =g.nSql; 2179 int idx = pSql->seq; 2180 printf("\r%s: %d/%d ", zDbName, idx, nTotal); 2181 fflush(stdout); 2182 }else if( verboseFlag ){ 2183 printf("%s\n", g.zTestName); 2184 fflush(stdout); 2185 }else if( !quietFlag ){ 2186 static int prevAmt = -1; 2187 int idx = pSql->seq; 2188 int amt = idx*10/(g.nSql); 2189 if( amt!=prevAmt ){ 2190 printf(" %d%%", amt*10); 2191 fflush(stdout); 2192 prevAmt = amt; 2193 } 2194 } 2195 if( nSkip>0 ){ 2196 nSkip--; 2197 }else{ 2198 runCombinedDbSqlInput(pSql->a, pSql->sz, iTimeout, bScript, pSql->id); 2199 } 2200 nTest++; 2201 if( bTimer && !bScript ){ 2202 sqlite3_int64 tmEnd = timeOfDay(); 2203 printf("%lld %s\n", tmEnd - tmStart, g.zTestName); 2204 } 2205 g.zTestName[0] = 0; 2206 disableOom(); 2207 continue; 2208 } 2209 for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){ 2210 int openFlags; 2211 const char *zVfs = "inmem"; 2212 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d", 2213 pSql->id, pDb->id); 2214 if( bScript ){ 2215 /* No progress output */ 2216 }else if( bSpinner ){ 2217 int nTotal = g.nDb*g.nSql; 2218 int idx = pSql->seq*g.nDb + pDb->id - 1; 2219 printf("\r%s: %d/%d ", zDbName, idx, nTotal); 2220 fflush(stdout); 2221 }else if( verboseFlag ){ 2222 printf("%s\n", g.zTestName); 2223 fflush(stdout); 2224 }else if( !quietFlag ){ 2225 static int prevAmt = -1; 2226 int idx = pSql->seq*g.nDb + pDb->id - 1; 2227 int amt = idx*10/(g.nDb*g.nSql); 2228 if( amt!=prevAmt ){ 2229 printf(" %d%%", amt*10); 2230 fflush(stdout); 2231 prevAmt = amt; 2232 } 2233 } 2234 if( nSkip>0 ){ 2235 nSkip--; 2236 continue; 2237 } 2238 if( bScript ){ 2239 char zName[100]; 2240 sqlite3_snprintf(sizeof(zName), zName, "db%06d.db", 2241 pDb->id>1 ? pDb->id : pSql->id); 2242 renderDbSqlForCLI(stdout, zName, 2243 pDb->a, pDb->sz, pSql->a, pSql->sz); 2244 continue; 2245 } 2246 createVFile("main.db", pDb->sz, pDb->a); 2247 sqlite3_randomness(0,0); 2248 if( ossFuzzThisDb ){ 2249 #ifndef SQLITE_OSS_FUZZ 2250 fatalError("--oss-fuzz not supported: recompile" 2251 " with -DSQLITE_OSS_FUZZ"); 2252 #else 2253 extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t); 2254 LLVMFuzzerTestOneInput((const uint8_t*)pSql->a, (size_t)pSql->sz); 2255 #endif 2256 }else{ 2257 openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE; 2258 if( nativeFlag && pDb->sz==0 ){ 2259 openFlags |= SQLITE_OPEN_MEMORY; 2260 zVfs = 0; 2261 } 2262 rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs); 2263 if( rc ) fatalError("cannot open inmem database"); 2264 sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 100000000); 2265 sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 50); 2266 if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags); 2267 setAlarm((iTimeout+999)/1000); 2268 /* Enable test functions */ 2269 sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, db); 2270 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 2271 if( sqlFuzz || vdbeLimitFlag ){ 2272 sqlite3_progress_handler(db, 100000, progressHandler, 2273 &vdbeLimitFlag); 2274 } 2275 #endif 2276 #ifdef SQLITE_TESTCTRL_PRNG_SEED 2277 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, db); 2278 #endif 2279 if( bVdbeDebug ){ 2280 sqlite3_exec(db, "PRAGMA vdbe_debug=ON", 0, 0, 0); 2281 } 2282 do{ 2283 runSql(db, (char*)pSql->a, runFlags); 2284 }while( timeoutTest ); 2285 setAlarm(0); 2286 sqlite3_exec(db, "PRAGMA temp_store_directory=''", 0, 0, 0); 2287 sqlite3_close(db); 2288 } 2289 if( sqlite3_memory_used()>0 ){ 2290 fatalError("memory leak: %lld bytes outstanding", 2291 sqlite3_memory_used()); 2292 } 2293 reformatVfs(); 2294 nTest++; 2295 if( bTimer ){ 2296 sqlite3_int64 tmEnd = timeOfDay(); 2297 printf("%lld %s\n", tmEnd - tmStart, g.zTestName); 2298 } 2299 g.zTestName[0] = 0; 2300 2301 /* Simulate an error if the TEST_FAILURE environment variable is "5". 2302 ** This is used to verify that automated test script really do spot 2303 ** errors that occur in this test program. 2304 */ 2305 if( zFailCode ){ 2306 if( zFailCode[0]=='5' && zFailCode[1]==0 ){ 2307 fatalError("simulated failure"); 2308 }else if( zFailCode[0]!=0 ){ 2309 /* If TEST_FAILURE is something other than 5, just exit the test 2310 ** early */ 2311 printf("\nExit early due to TEST_FAILURE being set\n"); 2312 iSrcDb = nSrcDb-1; 2313 goto sourcedb_cleanup; 2314 } 2315 } 2316 } 2317 } 2318 if( bScript ){ 2319 /* No progress output */ 2320 }else if( bSpinner ){ 2321 int nTotal = g.nDb*g.nSql; 2322 printf("\r%s: %d/%d \n", zDbName, nTotal, nTotal); 2323 }else if( !quietFlag && !verboseFlag ){ 2324 printf(" 100%% - %d tests\n", g.nDb*g.nSql); 2325 } 2326 2327 /* Clean up at the end of processing a single source database 2328 */ 2329 sourcedb_cleanup: 2330 blobListFree(g.pFirstSql); 2331 blobListFree(g.pFirstDb); 2332 reformatVfs(); 2333 2334 } /* End loop over all source databases */ 2335 2336 if( !quietFlag && !bScript ){ 2337 sqlite3_int64 iElapse = timeOfDay() - iBegin; 2338 printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n" 2339 "SQLite %s %s\n", 2340 nTest, (int)(iElapse/1000), (int)(iElapse%1000), 2341 sqlite3_libversion(), sqlite3_sourceid()); 2342 } 2343 free(azSrcDb); 2344 free(pHeap); 2345 return 0; 2346 } 2347