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 ** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and 835 ** "PRAGMA parser_trace" since they can dramatically increase the 836 ** amount of output without actually testing anything useful. 837 ** 838 ** Also block ATTACH if attaching a file from the filesystem. 839 */ 840 static int block_troublesome_sql( 841 void *Notused, 842 int eCode, 843 const char *zArg1, 844 const char *zArg2, 845 const char *zArg3, 846 const char *zArg4 847 ){ 848 (void)Notused; 849 (void)zArg2; 850 (void)zArg3; 851 (void)zArg4; 852 if( eCode==SQLITE_PRAGMA ){ 853 if( sqlite3_stricmp("busy_timeout",zArg1)==0 854 && (zArg2==0 || strtoll(zArg2,0,0)>100 || strtoll(zArg2,0,10)>100) 855 ){ 856 return SQLITE_DENY; 857 }else if( eVerbosity==0 ){ 858 if( sqlite3_strnicmp("vdbe_", zArg1, 5)==0 859 || sqlite3_stricmp("parser_trace", zArg1)==0 860 || sqlite3_stricmp("temp_store_directory", zArg1)==0 861 ){ 862 return SQLITE_DENY; 863 } 864 }else if( sqlite3_stricmp("oom",zArg1)==0 865 && zArg2!=0 && zArg2[0]!=0 ){ 866 oomCounter = atoi(zArg2); 867 } 868 }else if( eCode==SQLITE_ATTACH ){ 869 /* Deny the ATTACH if it is attaching anything other than an in-memory 870 ** database. */ 871 if( zArg1==0 ) return SQLITE_DENY; 872 if( strcmp(zArg1,":memory:")==0 ) return SQLITE_OK; 873 if( sqlite3_strglob("file:*[?]vfs=memdb", zArg1)==0 874 && sqlite3_strglob("file:*[^/a-zA-Z0-9_.]*[?]vfs=memdb", zArg1)!=0 875 ){ 876 return SQLITE_OK; 877 } 878 return SQLITE_DENY; 879 } 880 return SQLITE_OK; 881 } 882 883 /* 884 ** Run the SQL text 885 */ 886 static int runDbSql(sqlite3 *db, const char *zSql){ 887 int rc; 888 sqlite3_stmt *pStmt; 889 while( isspace(zSql[0]&0x7f) ) zSql++; 890 if( zSql[0]==0 ) return SQLITE_OK; 891 if( eVerbosity>=4 ){ 892 printf("RUNNING-SQL: [%s]\n", zSql); 893 fflush(stdout); 894 } 895 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 896 if( rc==SQLITE_OK ){ 897 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){ 898 if( eVerbosity>=5 ){ 899 int j; 900 for(j=0; j<sqlite3_column_count(pStmt); j++){ 901 if( j ) printf(","); 902 switch( sqlite3_column_type(pStmt, j) ){ 903 case SQLITE_NULL: { 904 printf("NULL"); 905 break; 906 } 907 case SQLITE_INTEGER: 908 case SQLITE_FLOAT: { 909 printf("%s", sqlite3_column_text(pStmt, j)); 910 break; 911 } 912 case SQLITE_BLOB: { 913 int n = sqlite3_column_bytes(pStmt, j); 914 int i; 915 const unsigned char *a; 916 a = (const unsigned char*)sqlite3_column_blob(pStmt, j); 917 printf("x'"); 918 for(i=0; i<n; i++){ 919 printf("%02x", a[i]); 920 } 921 printf("'"); 922 break; 923 } 924 case SQLITE_TEXT: { 925 int n = sqlite3_column_bytes(pStmt, j); 926 int i; 927 const unsigned char *a; 928 a = (const unsigned char*)sqlite3_column_blob(pStmt, j); 929 printf("'"); 930 for(i=0; i<n; i++){ 931 if( a[i]=='\'' ){ 932 printf("''"); 933 }else{ 934 putchar(a[i]); 935 } 936 } 937 printf("'"); 938 break; 939 } 940 } /* End switch() */ 941 } /* End for() */ 942 printf("\n"); 943 fflush(stdout); 944 } /* End if( eVerbosity>=5 ) */ 945 } /* End while( SQLITE_ROW */ 946 if( rc!=SQLITE_DONE && eVerbosity>=4 ){ 947 printf("SQL-ERROR: (%d) %s\n", rc, sqlite3_errmsg(db)); 948 fflush(stdout); 949 } 950 }else if( eVerbosity>=4 ){ 951 printf("SQL-ERROR (%d): %s\n", rc, sqlite3_errmsg(db)); 952 fflush(stdout); 953 } /* End if( SQLITE_OK ) */ 954 return sqlite3_finalize(pStmt); 955 } 956 957 /* Invoke this routine to run a single test case */ 958 int runCombinedDbSqlInput( 959 const uint8_t *aData, /* Combined DB+SQL content */ 960 size_t nByte, /* Size of aData in bytes */ 961 int iTimeout, /* Use this timeout */ 962 int bScript, /* If true, just render CLI output */ 963 int iSqlId /* SQL identifier */ 964 ){ 965 int rc; /* SQLite API return value */ 966 int iSql; /* Index in aData[] of start of SQL */ 967 unsigned char *aDb = 0; /* Decoded database content */ 968 int nDb = 0; /* Size of the decoded database */ 969 int i; /* Loop counter */ 970 int j; /* Start of current SQL statement */ 971 char *zSql = 0; /* SQL text to run */ 972 int nSql; /* Bytes of SQL text */ 973 FuzzCtx cx; /* Fuzzing context */ 974 975 if( nByte<10 ) return 0; 976 if( sqlite3_initialize() ) return 0; 977 if( sqlite3_memory_used()!=0 ){ 978 int nAlloc = 0; 979 int nNotUsed = 0; 980 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0); 981 fprintf(stderr,"memory leak prior to test start:" 982 " %lld bytes in %d allocations\n", 983 sqlite3_memory_used(), nAlloc); 984 exit(1); 985 } 986 memset(&cx, 0, sizeof(cx)); 987 iSql = decodeDatabase((unsigned char*)aData, (int)nByte, &aDb, &nDb); 988 if( iSql<0 ) return 0; 989 nSql = (int)(nByte - iSql); 990 if( bScript ){ 991 char zName[100]; 992 sqlite3_snprintf(sizeof(zName),zName,"dbsql%06d.db",iSqlId); 993 renderDbSqlForCLI(stdout, zName, aDb, nDb, 994 (unsigned char*)(aData+iSql), nSql); 995 sqlite3_free(aDb); 996 return 0; 997 } 998 if( eVerbosity>=3 ){ 999 printf( 1000 "****** %d-byte input, %d-byte database, %d-byte script " 1001 "******\n", (int)nByte, nDb, nSql); 1002 fflush(stdout); 1003 } 1004 rc = sqlite3_open(0, &cx.db); 1005 if( rc ){ 1006 sqlite3_free(aDb); 1007 return 1; 1008 } 1009 if( bVdbeDebug ){ 1010 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON", 0, 0, 0); 1011 } 1012 1013 /* Invoke the progress handler frequently to check to see if we 1014 ** are taking too long. The progress handler will return true 1015 ** (which will block further processing) if more than giTimeout seconds have 1016 ** elapsed since the start of the test. 1017 */ 1018 cx.iLastCb = timeOfDay(); 1019 cx.iCutoffTime = cx.iLastCb + (iTimeout<giTimeout ? iTimeout : giTimeout); 1020 cx.mxCb = mxProgressCb; 1021 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 1022 sqlite3_progress_handler(cx.db, 10, progress_handler, (void*)&cx); 1023 #endif 1024 1025 /* Set a limit on the maximum size of a prepared statement, and the 1026 ** maximum length of a string or blob */ 1027 if( vdbeOpLimit>0 ){ 1028 sqlite3_limit(cx.db, SQLITE_LIMIT_VDBE_OP, vdbeOpLimit); 1029 } 1030 if( lengthLimit>0 ){ 1031 sqlite3_limit(cx.db, SQLITE_LIMIT_LENGTH, lengthLimit); 1032 } 1033 if( depthLimit>0 ){ 1034 sqlite3_limit(cx.db, SQLITE_LIMIT_EXPR_DEPTH, depthLimit); 1035 } 1036 sqlite3_limit(cx.db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 100); 1037 sqlite3_hard_heap_limit64(heapLimit); 1038 1039 if( nDb>=20 && aDb[18]==2 && aDb[19]==2 ){ 1040 aDb[18] = aDb[19] = 1; 1041 } 1042 rc = sqlite3_deserialize(cx.db, "main", aDb, nDb, nDb, 1043 SQLITE_DESERIALIZE_RESIZEABLE | 1044 SQLITE_DESERIALIZE_FREEONCLOSE); 1045 if( rc ){ 1046 fprintf(stderr, "sqlite3_deserialize() failed with %d\n", rc); 1047 goto testrun_finished; 1048 } 1049 if( maxDbSize>0 ){ 1050 sqlite3_int64 x = maxDbSize; 1051 sqlite3_file_control(cx.db, "main", SQLITE_FCNTL_SIZE_LIMIT, &x); 1052 } 1053 1054 /* For high debugging levels, turn on debug mode */ 1055 if( eVerbosity>=5 ){ 1056 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON;", 0, 0, 0); 1057 } 1058 1059 /* Block debug pragmas and ATTACH/DETACH. But wait until after 1060 ** deserialize to do this because deserialize depends on ATTACH */ 1061 sqlite3_set_authorizer(cx.db, block_troublesome_sql, 0); 1062 1063 #ifdef VT02_SOURCES 1064 sqlite3_vt02_init(cx.db, 0, 0); 1065 #endif 1066 1067 /* Consistent PRNG seed */ 1068 #ifdef SQLITE_TESTCTRL_PRNG_SEED 1069 sqlite3_table_column_metadata(cx.db, 0, "x", 0, 0, 0, 0, 0, 0); 1070 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, cx.db); 1071 #else 1072 sqlite3_randomness(0,0); 1073 #endif 1074 1075 zSql = sqlite3_malloc( nSql + 1 ); 1076 if( zSql==0 ){ 1077 fprintf(stderr, "Out of memory!\n"); 1078 }else{ 1079 memcpy(zSql, aData+iSql, nSql); 1080 zSql[nSql] = 0; 1081 for(i=j=0; zSql[i]; i++){ 1082 if( zSql[i]==';' ){ 1083 char cSaved = zSql[i+1]; 1084 zSql[i+1] = 0; 1085 if( sqlite3_complete(zSql+j) ){ 1086 rc = runDbSql(cx.db, zSql+j); 1087 j = i+1; 1088 } 1089 zSql[i+1] = cSaved; 1090 if( rc==SQLITE_INTERRUPT || progress_handler(&cx) ){ 1091 goto testrun_finished; 1092 } 1093 } 1094 } 1095 if( j<i ){ 1096 runDbSql(cx.db, zSql+j); 1097 } 1098 } 1099 testrun_finished: 1100 sqlite3_free(zSql); 1101 rc = sqlite3_close(cx.db); 1102 if( rc!=SQLITE_OK ){ 1103 fprintf(stdout, "sqlite3_close() returns %d\n", rc); 1104 } 1105 if( eVerbosity>=2 && !bScript ){ 1106 fprintf(stdout, "Peak memory usages: %f MB\n", 1107 sqlite3_memory_highwater(1) / 1000000.0); 1108 } 1109 if( sqlite3_memory_used()!=0 ){ 1110 int nAlloc = 0; 1111 int nNotUsed = 0; 1112 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0); 1113 fprintf(stderr,"Memory leak: %lld bytes in %d allocations\n", 1114 sqlite3_memory_used(), nAlloc); 1115 exit(1); 1116 } 1117 sqlite3_hard_heap_limit64(0); 1118 sqlite3_soft_heap_limit64(0); 1119 return 0; 1120 } 1121 1122 /* 1123 ** END of the dbsqlfuzz code 1124 ***************************************************************************/ 1125 1126 /* Look at a SQL text and try to determine if it begins with a database 1127 ** description, such as would be found in a dbsqlfuzz test case. Return 1128 ** true if this does appear to be a dbsqlfuzz test case and false otherwise. 1129 */ 1130 static int isDbSql(unsigned char *a, int n){ 1131 unsigned char buf[12]; 1132 int i; 1133 if( n>4 && memcmp(a,"\n--\n",4)==0 ) return 1; 1134 while( n>0 && isspace(a[0]) ){ a++; n--; } 1135 for(i=0; n>0 && i<8; n--, a++){ 1136 if( isxdigit(a[0]) ) buf[i++] = a[0]; 1137 } 1138 if( i==8 && memcmp(buf,"53514c69",8)==0 ) return 1; 1139 return 0; 1140 } 1141 1142 /* Implementation of the isdbsql(TEXT) SQL function. 1143 */ 1144 static void isDbSqlFunc( 1145 sqlite3_context *context, 1146 int argc, 1147 sqlite3_value **argv 1148 ){ 1149 int n = sqlite3_value_bytes(argv[0]); 1150 unsigned char *a = (unsigned char*)sqlite3_value_blob(argv[0]); 1151 sqlite3_result_int(context, a!=0 && n>0 && isDbSql(a,n)); 1152 } 1153 1154 /* Methods for the VHandle object 1155 */ 1156 static int inmemClose(sqlite3_file *pFile){ 1157 VHandle *p = (VHandle*)pFile; 1158 VFile *pVFile = p->pVFile; 1159 pVFile->nRef--; 1160 if( pVFile->nRef==0 && pVFile->zFilename==0 ){ 1161 pVFile->sz = -1; 1162 free(pVFile->a); 1163 pVFile->a = 0; 1164 } 1165 return SQLITE_OK; 1166 } 1167 static int inmemRead( 1168 sqlite3_file *pFile, /* Read from this open file */ 1169 void *pData, /* Store content in this buffer */ 1170 int iAmt, /* Bytes of content */ 1171 sqlite3_int64 iOfst /* Start reading here */ 1172 ){ 1173 VHandle *pHandle = (VHandle*)pFile; 1174 VFile *pVFile = pHandle->pVFile; 1175 if( iOfst<0 || iOfst>=pVFile->sz ){ 1176 memset(pData, 0, iAmt); 1177 return SQLITE_IOERR_SHORT_READ; 1178 } 1179 if( iOfst+iAmt>pVFile->sz ){ 1180 memset(pData, 0, iAmt); 1181 iAmt = (int)(pVFile->sz - iOfst); 1182 memcpy(pData, pVFile->a + iOfst, iAmt); 1183 return SQLITE_IOERR_SHORT_READ; 1184 } 1185 memcpy(pData, pVFile->a + iOfst, iAmt); 1186 return SQLITE_OK; 1187 } 1188 static int inmemWrite( 1189 sqlite3_file *pFile, /* Write to this file */ 1190 const void *pData, /* Content to write */ 1191 int iAmt, /* bytes to write */ 1192 sqlite3_int64 iOfst /* Start writing here */ 1193 ){ 1194 VHandle *pHandle = (VHandle*)pFile; 1195 VFile *pVFile = pHandle->pVFile; 1196 if( iOfst+iAmt > pVFile->sz ){ 1197 if( iOfst+iAmt >= MX_FILE_SZ ){ 1198 return SQLITE_FULL; 1199 } 1200 pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt)); 1201 if( iOfst > pVFile->sz ){ 1202 memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz)); 1203 } 1204 pVFile->sz = (int)(iOfst + iAmt); 1205 } 1206 memcpy(pVFile->a + iOfst, pData, iAmt); 1207 return SQLITE_OK; 1208 } 1209 static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){ 1210 VHandle *pHandle = (VHandle*)pFile; 1211 VFile *pVFile = pHandle->pVFile; 1212 if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize; 1213 return SQLITE_OK; 1214 } 1215 static int inmemSync(sqlite3_file *pFile, int flags){ 1216 return SQLITE_OK; 1217 } 1218 static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){ 1219 *pSize = ((VHandle*)pFile)->pVFile->sz; 1220 return SQLITE_OK; 1221 } 1222 static int inmemLock(sqlite3_file *pFile, int type){ 1223 return SQLITE_OK; 1224 } 1225 static int inmemUnlock(sqlite3_file *pFile, int type){ 1226 return SQLITE_OK; 1227 } 1228 static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){ 1229 *pOut = 0; 1230 return SQLITE_OK; 1231 } 1232 static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){ 1233 return SQLITE_NOTFOUND; 1234 } 1235 static int inmemSectorSize(sqlite3_file *pFile){ 1236 return 512; 1237 } 1238 static int inmemDeviceCharacteristics(sqlite3_file *pFile){ 1239 return 1240 SQLITE_IOCAP_SAFE_APPEND | 1241 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | 1242 SQLITE_IOCAP_POWERSAFE_OVERWRITE; 1243 } 1244 1245 1246 /* Method table for VHandle 1247 */ 1248 static sqlite3_io_methods VHandleMethods = { 1249 /* iVersion */ 1, 1250 /* xClose */ inmemClose, 1251 /* xRead */ inmemRead, 1252 /* xWrite */ inmemWrite, 1253 /* xTruncate */ inmemTruncate, 1254 /* xSync */ inmemSync, 1255 /* xFileSize */ inmemFileSize, 1256 /* xLock */ inmemLock, 1257 /* xUnlock */ inmemUnlock, 1258 /* xCheck... */ inmemCheckReservedLock, 1259 /* xFileCtrl */ inmemFileControl, 1260 /* xSectorSz */ inmemSectorSize, 1261 /* xDevchar */ inmemDeviceCharacteristics, 1262 /* xShmMap */ 0, 1263 /* xShmLock */ 0, 1264 /* xShmBarrier */ 0, 1265 /* xShmUnmap */ 0, 1266 /* xFetch */ 0, 1267 /* xUnfetch */ 0 1268 }; 1269 1270 /* 1271 ** Open a new file in the inmem VFS. All files are anonymous and are 1272 ** delete-on-close. 1273 */ 1274 static int inmemOpen( 1275 sqlite3_vfs *pVfs, 1276 const char *zFilename, 1277 sqlite3_file *pFile, 1278 int openFlags, 1279 int *pOutFlags 1280 ){ 1281 VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)""); 1282 VHandle *pHandle = (VHandle*)pFile; 1283 if( pVFile==0 ){ 1284 return SQLITE_FULL; 1285 } 1286 pHandle->pVFile = pVFile; 1287 pVFile->nRef++; 1288 pFile->pMethods = &VHandleMethods; 1289 if( pOutFlags ) *pOutFlags = openFlags; 1290 return SQLITE_OK; 1291 } 1292 1293 /* 1294 ** Delete a file by name 1295 */ 1296 static int inmemDelete( 1297 sqlite3_vfs *pVfs, 1298 const char *zFilename, 1299 int syncdir 1300 ){ 1301 VFile *pVFile = findVFile(zFilename); 1302 if( pVFile==0 ) return SQLITE_OK; 1303 if( pVFile->nRef==0 ){ 1304 free(pVFile->zFilename); 1305 pVFile->zFilename = 0; 1306 pVFile->sz = -1; 1307 free(pVFile->a); 1308 pVFile->a = 0; 1309 return SQLITE_OK; 1310 } 1311 return SQLITE_IOERR_DELETE; 1312 } 1313 1314 /* Check for the existance of a file 1315 */ 1316 static int inmemAccess( 1317 sqlite3_vfs *pVfs, 1318 const char *zFilename, 1319 int flags, 1320 int *pResOut 1321 ){ 1322 VFile *pVFile = findVFile(zFilename); 1323 *pResOut = pVFile!=0; 1324 return SQLITE_OK; 1325 } 1326 1327 /* Get the canonical pathname for a file 1328 */ 1329 static int inmemFullPathname( 1330 sqlite3_vfs *pVfs, 1331 const char *zFilename, 1332 int nOut, 1333 char *zOut 1334 ){ 1335 sqlite3_snprintf(nOut, zOut, "%s", zFilename); 1336 return SQLITE_OK; 1337 } 1338 1339 /* Always use the same random see, for repeatability. 1340 */ 1341 static int inmemRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ 1342 memset(zBuf, 0, nBuf); 1343 memcpy(zBuf, &g.uRandom, nBuf<sizeof(g.uRandom) ? nBuf : sizeof(g.uRandom)); 1344 return nBuf; 1345 } 1346 1347 /* 1348 ** Register the VFS that reads from the g.aFile[] set of files. 1349 */ 1350 static void inmemVfsRegister(int makeDefault){ 1351 static sqlite3_vfs inmemVfs; 1352 sqlite3_vfs *pDefault = sqlite3_vfs_find(0); 1353 inmemVfs.iVersion = 3; 1354 inmemVfs.szOsFile = sizeof(VHandle); 1355 inmemVfs.mxPathname = 200; 1356 inmemVfs.zName = "inmem"; 1357 inmemVfs.xOpen = inmemOpen; 1358 inmemVfs.xDelete = inmemDelete; 1359 inmemVfs.xAccess = inmemAccess; 1360 inmemVfs.xFullPathname = inmemFullPathname; 1361 inmemVfs.xRandomness = inmemRandomness; 1362 inmemVfs.xSleep = pDefault->xSleep; 1363 inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64; 1364 sqlite3_vfs_register(&inmemVfs, makeDefault); 1365 }; 1366 1367 /* 1368 ** Allowed values for the runFlags parameter to runSql() 1369 */ 1370 #define SQL_TRACE 0x0001 /* Print each SQL statement as it is prepared */ 1371 #define SQL_OUTPUT 0x0002 /* Show the SQL output */ 1372 1373 /* 1374 ** Run multiple commands of SQL. Similar to sqlite3_exec(), but does not 1375 ** stop if an error is encountered. 1376 */ 1377 static void runSql(sqlite3 *db, const char *zSql, unsigned runFlags){ 1378 const char *zMore; 1379 sqlite3_stmt *pStmt; 1380 1381 while( zSql && zSql[0] ){ 1382 zMore = 0; 1383 pStmt = 0; 1384 sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore); 1385 if( zMore==zSql ) break; 1386 if( runFlags & SQL_TRACE ){ 1387 const char *z = zSql; 1388 int n; 1389 while( z<zMore && ISSPACE(z[0]) ) z++; 1390 n = (int)(zMore - z); 1391 while( n>0 && ISSPACE(z[n-1]) ) n--; 1392 if( n==0 ) break; 1393 if( pStmt==0 ){ 1394 printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db)); 1395 }else{ 1396 printf("TRACE: %.*s\n", n, z); 1397 } 1398 } 1399 zSql = zMore; 1400 if( pStmt ){ 1401 if( (runFlags & SQL_OUTPUT)==0 ){ 1402 while( SQLITE_ROW==sqlite3_step(pStmt) ){} 1403 }else{ 1404 int nCol = -1; 1405 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 1406 int i; 1407 if( nCol<0 ){ 1408 nCol = sqlite3_column_count(pStmt); 1409 }else if( nCol>0 ){ 1410 printf("--------------------------------------------\n"); 1411 } 1412 for(i=0; i<nCol; i++){ 1413 int eType = sqlite3_column_type(pStmt,i); 1414 printf("%s = ", sqlite3_column_name(pStmt,i)); 1415 switch( eType ){ 1416 case SQLITE_NULL: { 1417 printf("NULL\n"); 1418 break; 1419 } 1420 case SQLITE_INTEGER: { 1421 printf("INT %s\n", sqlite3_column_text(pStmt,i)); 1422 break; 1423 } 1424 case SQLITE_FLOAT: { 1425 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i)); 1426 break; 1427 } 1428 case SQLITE_TEXT: { 1429 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i)); 1430 break; 1431 } 1432 case SQLITE_BLOB: { 1433 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i)); 1434 break; 1435 } 1436 } 1437 } 1438 } 1439 } 1440 sqlite3_finalize(pStmt); 1441 } 1442 } 1443 } 1444 1445 /* 1446 ** Rebuild the database file. 1447 ** 1448 ** (1) Remove duplicate entries 1449 ** (2) Put all entries in order 1450 ** (3) Vacuum 1451 */ 1452 static void rebuild_database(sqlite3 *db, int dbSqlOnly){ 1453 int rc; 1454 char *zSql; 1455 zSql = sqlite3_mprintf( 1456 "BEGIN;\n" 1457 "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n" 1458 "DELETE FROM db;\n" 1459 "INSERT INTO db(dbid, dbcontent) " 1460 " SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n" 1461 "DROP TABLE dbx;\n" 1462 "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql %s;\n" 1463 "DELETE FROM xsql;\n" 1464 "INSERT INTO xsql(sqlid,sqltext) " 1465 " SELECT NULL, sqltext FROM sx ORDER BY 2;\n" 1466 "DROP TABLE sx;\n" 1467 "COMMIT;\n" 1468 "PRAGMA page_size=1024;\n" 1469 "VACUUM;\n", 1470 dbSqlOnly ? " WHERE isdbsql(sqltext)" : "" 1471 ); 1472 rc = sqlite3_exec(db, zSql, 0, 0, 0); 1473 sqlite3_free(zSql); 1474 if( rc ) fatalError("cannot rebuild: %s", sqlite3_errmsg(db)); 1475 } 1476 1477 /* 1478 ** Return the value of a hexadecimal digit. Return -1 if the input 1479 ** is not a hex digit. 1480 */ 1481 static int hexDigitValue(char c){ 1482 if( c>='0' && c<='9' ) return c - '0'; 1483 if( c>='a' && c<='f' ) return c - 'a' + 10; 1484 if( c>='A' && c<='F' ) return c - 'A' + 10; 1485 return -1; 1486 } 1487 1488 /* 1489 ** Interpret zArg as an integer value, possibly with suffixes. 1490 */ 1491 static int integerValue(const char *zArg){ 1492 sqlite3_int64 v = 0; 1493 static const struct { char *zSuffix; int iMult; } aMult[] = { 1494 { "KiB", 1024 }, 1495 { "MiB", 1024*1024 }, 1496 { "GiB", 1024*1024*1024 }, 1497 { "KB", 1000 }, 1498 { "MB", 1000000 }, 1499 { "GB", 1000000000 }, 1500 { "K", 1000 }, 1501 { "M", 1000000 }, 1502 { "G", 1000000000 }, 1503 }; 1504 int i; 1505 int isNeg = 0; 1506 if( zArg[0]=='-' ){ 1507 isNeg = 1; 1508 zArg++; 1509 }else if( zArg[0]=='+' ){ 1510 zArg++; 1511 } 1512 if( zArg[0]=='0' && zArg[1]=='x' ){ 1513 int x; 1514 zArg += 2; 1515 while( (x = hexDigitValue(zArg[0]))>=0 ){ 1516 v = (v<<4) + x; 1517 zArg++; 1518 } 1519 }else{ 1520 while( ISDIGIT(zArg[0]) ){ 1521 v = v*10 + zArg[0] - '0'; 1522 zArg++; 1523 } 1524 } 1525 for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){ 1526 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ 1527 v *= aMult[i].iMult; 1528 break; 1529 } 1530 } 1531 if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648"); 1532 return (int)(isNeg? -v : v); 1533 } 1534 1535 /* 1536 ** Return the number of "v" characters in a string. Return 0 if there 1537 ** are any characters in the string other than "v". 1538 */ 1539 static int numberOfVChar(const char *z){ 1540 int N = 0; 1541 while( z[0] && z[0]=='v' ){ 1542 z++; 1543 N++; 1544 } 1545 return z[0]==0 ? N : 0; 1546 } 1547 1548 /* 1549 ** Print sketchy documentation for this utility program 1550 */ 1551 static void showHelp(void){ 1552 printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0); 1553 printf( 1554 "Read databases and SQL scripts from SOURCE-DB and execute each script against\n" 1555 "each database, checking for crashes and memory leaks.\n" 1556 "Options:\n" 1557 " --cell-size-check Set the PRAGMA cell_size_check=ON\n" 1558 " --dbid N Use only the database where dbid=N\n" 1559 " --export-db DIR Write databases to files(s) in DIR. Works with --dbid\n" 1560 " --export-sql DIR Write SQL to file(s) in DIR. Also works with --sqlid\n" 1561 " --help Show this help text\n" 1562 " --info Show information about SOURCE-DB w/o running tests\n" 1563 " --limit-depth N Limit expression depth to N. Default: 500\n" 1564 " --limit-heap N Limit heap memory to N. Default: 100M\n" 1565 " --limit-mem N Limit memory used by test SQLite instance to N bytes\n" 1566 " --limit-vdbe Panic if any test runs for more than 100,000 cycles\n" 1567 " --load-sql FILE.. Load SQL scripts fron files into SOURCE-DB\n" 1568 " --load-db FILE.. Load template databases from files into SOURCE_DB\n" 1569 " --load-dbsql FILE.. Load dbsqlfuzz outputs into the xsql table\n" 1570 " ^^^^------ Use \"-\" for FILE to read filenames from stdin\n" 1571 " -m TEXT Add a description to the database\n" 1572 " --native-vfs Use the native VFS for initially empty database files\n" 1573 " --native-malloc Turn off MEMSYS3/5 and Lookaside\n" 1574 " --oss-fuzz Enable OSS-FUZZ testing\n" 1575 " --prng-seed N Seed value for the PRGN inside of SQLite\n" 1576 " -q|--quiet Reduced output\n" 1577 " --rebuild Rebuild and vacuum the database file\n" 1578 " --result-trace Show the results of each SQL command\n" 1579 " --script Output CLI script instead of running tests\n" 1580 " --skip N Skip the first N test cases\n" 1581 " --spinner Use a spinner to show progress\n" 1582 " --sqlid N Use only SQL where sqlid=N\n" 1583 " --timeout N Maximum time for any one test in N millseconds\n" 1584 " -v|--verbose Increased output. Repeat for more output.\n" 1585 " --vdbe-debug Activate VDBE debugging.\n" 1586 ); 1587 } 1588 1589 int main(int argc, char **argv){ 1590 sqlite3_int64 iBegin; /* Start time of this program */ 1591 int quietFlag = 0; /* True if --quiet or -q */ 1592 int verboseFlag = 0; /* True if --verbose or -v */ 1593 char *zInsSql = 0; /* SQL statement for --load-db or --load-sql */ 1594 int iFirstInsArg = 0; /* First argv[] for --load-db or --load-sql */ 1595 sqlite3 *db = 0; /* The open database connection */ 1596 sqlite3_stmt *pStmt; /* A prepared statement */ 1597 int rc; /* Result code from SQLite interface calls */ 1598 Blob *pSql; /* For looping over SQL scripts */ 1599 Blob *pDb; /* For looping over template databases */ 1600 int i; /* Loop index for the argv[] loop */ 1601 int dbSqlOnly = 0; /* Only use scripts that are dbsqlfuzz */ 1602 int onlySqlid = -1; /* --sqlid */ 1603 int onlyDbid = -1; /* --dbid */ 1604 int nativeFlag = 0; /* --native-vfs */ 1605 int rebuildFlag = 0; /* --rebuild */ 1606 int vdbeLimitFlag = 0; /* --limit-vdbe */ 1607 int infoFlag = 0; /* --info */ 1608 int nSkip = 0; /* --skip */ 1609 int bScript = 0; /* --script */ 1610 int bSpinner = 0; /* True for --spinner */ 1611 int timeoutTest = 0; /* undocumented --timeout-test flag */ 1612 int runFlags = 0; /* Flags sent to runSql() */ 1613 char *zMsg = 0; /* Add this message */ 1614 int nSrcDb = 0; /* Number of source databases */ 1615 char **azSrcDb = 0; /* Array of source database names */ 1616 int iSrcDb; /* Loop over all source databases */ 1617 int nTest = 0; /* Total number of tests performed */ 1618 char *zDbName = ""; /* Appreviated name of a source database */ 1619 const char *zFailCode = 0; /* Value of the TEST_FAILURE env variable */ 1620 int cellSzCkFlag = 0; /* --cell-size-check */ 1621 int sqlFuzz = 0; /* True for SQL fuzz. False for DB fuzz */ 1622 int iTimeout = 120000; /* Default 120-second timeout */ 1623 int nMem = 0; /* Memory limit override */ 1624 int nMemThisDb = 0; /* Memory limit set by the CONFIG table */ 1625 char *zExpDb = 0; /* Write Databases to files in this directory */ 1626 char *zExpSql = 0; /* Write SQL to files in this directory */ 1627 void *pHeap = 0; /* Heap for use by SQLite */ 1628 int ossFuzz = 0; /* enable OSS-FUZZ testing */ 1629 int ossFuzzThisDb = 0; /* ossFuzz value for this particular database */ 1630 int nativeMalloc = 0; /* Turn off MEMSYS3/5 and lookaside if true */ 1631 sqlite3_vfs *pDfltVfs; /* The default VFS */ 1632 int openFlags4Data; /* Flags for sqlite3_open_v2() */ 1633 int bTimer = 0; /* Show elapse time for each test */ 1634 int nV; /* How much to increase verbosity with -vvvv */ 1635 sqlite3_int64 tmStart; /* Start of each test */ 1636 1637 sqlite3_config(SQLITE_CONFIG_URI,1); 1638 registerOomSimulator(); 1639 sqlite3_initialize(); 1640 iBegin = timeOfDay(); 1641 #ifdef __unix__ 1642 signal(SIGALRM, signalHandler); 1643 signal(SIGSEGV, signalHandler); 1644 signal(SIGABRT, signalHandler); 1645 #endif 1646 g.zArgv0 = argv[0]; 1647 openFlags4Data = SQLITE_OPEN_READONLY; 1648 zFailCode = getenv("TEST_FAILURE"); 1649 pDfltVfs = sqlite3_vfs_find(0); 1650 inmemVfsRegister(1); 1651 for(i=1; i<argc; i++){ 1652 const char *z = argv[i]; 1653 if( z[0]=='-' ){ 1654 z++; 1655 if( z[0]=='-' ) z++; 1656 if( strcmp(z,"cell-size-check")==0 ){ 1657 cellSzCkFlag = 1; 1658 }else 1659 if( strcmp(z,"dbid")==0 ){ 1660 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1661 onlyDbid = integerValue(argv[++i]); 1662 }else 1663 if( strcmp(z,"export-db")==0 ){ 1664 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1665 zExpDb = argv[++i]; 1666 }else 1667 if( strcmp(z,"export-sql")==0 || strcmp(z,"export-dbsql")==0 ){ 1668 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1669 zExpSql = argv[++i]; 1670 }else 1671 if( strcmp(z,"help")==0 ){ 1672 showHelp(); 1673 return 0; 1674 }else 1675 if( strcmp(z,"info")==0 ){ 1676 infoFlag = 1; 1677 }else 1678 if( strcmp(z,"limit-depth")==0 ){ 1679 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1680 depthLimit = integerValue(argv[++i]); 1681 }else 1682 if( strcmp(z,"limit-heap")==0 ){ 1683 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1684 heapLimit = integerValue(argv[++i]); 1685 }else 1686 if( strcmp(z,"limit-mem")==0 ){ 1687 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1688 nMem = integerValue(argv[++i]); 1689 }else 1690 if( strcmp(z,"limit-vdbe")==0 ){ 1691 vdbeLimitFlag = 1; 1692 }else 1693 if( strcmp(z,"load-sql")==0 ){ 1694 zInsSql = "INSERT INTO xsql(sqltext)" 1695 "VALUES(CAST(readtextfile(?1) AS text))"; 1696 iFirstInsArg = i+1; 1697 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 1698 break; 1699 }else 1700 if( strcmp(z,"load-db")==0 ){ 1701 zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))"; 1702 iFirstInsArg = i+1; 1703 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 1704 break; 1705 }else 1706 if( strcmp(z,"load-dbsql")==0 ){ 1707 zInsSql = "INSERT INTO xsql(sqltext)" 1708 "VALUES(readfile(?1))"; 1709 iFirstInsArg = i+1; 1710 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 1711 dbSqlOnly = 1; 1712 break; 1713 }else 1714 if( strcmp(z,"m")==0 ){ 1715 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1716 zMsg = argv[++i]; 1717 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 1718 }else 1719 if( strcmp(z,"native-malloc")==0 ){ 1720 nativeMalloc = 1; 1721 }else 1722 if( strcmp(z,"native-vfs")==0 ){ 1723 nativeFlag = 1; 1724 }else 1725 if( strcmp(z,"oss-fuzz")==0 ){ 1726 ossFuzz = 1; 1727 }else 1728 if( strcmp(z,"prng-seed")==0 ){ 1729 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1730 g.uRandom = atoi(argv[++i]); 1731 }else 1732 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ 1733 quietFlag = 1; 1734 verboseFlag = 0; 1735 eVerbosity = 0; 1736 }else 1737 if( strcmp(z,"rebuild")==0 ){ 1738 rebuildFlag = 1; 1739 openFlags4Data = SQLITE_OPEN_READWRITE; 1740 }else 1741 if( strcmp(z,"result-trace")==0 ){ 1742 runFlags |= SQL_OUTPUT; 1743 }else 1744 if( strcmp(z,"script")==0 ){ 1745 bScript = 1; 1746 }else 1747 if( strcmp(z,"skip")==0 ){ 1748 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1749 nSkip = atoi(argv[++i]); 1750 }else 1751 if( strcmp(z,"spinner")==0 ){ 1752 bSpinner = 1; 1753 }else 1754 if( strcmp(z,"timer")==0 ){ 1755 bTimer = 1; 1756 }else 1757 if( strcmp(z,"sqlid")==0 ){ 1758 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1759 onlySqlid = integerValue(argv[++i]); 1760 }else 1761 if( strcmp(z,"timeout")==0 ){ 1762 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); 1763 iTimeout = integerValue(argv[++i]); 1764 }else 1765 if( strcmp(z,"timeout-test")==0 ){ 1766 timeoutTest = 1; 1767 #ifndef __unix__ 1768 fatalError("timeout is not available on non-unix systems"); 1769 #endif 1770 }else 1771 if( strcmp(z,"vdbe-debug")==0 ){ 1772 bVdbeDebug = 1; 1773 }else 1774 if( strcmp(z,"verbose")==0 ){ 1775 quietFlag = 0; 1776 verboseFlag++; 1777 eVerbosity++; 1778 if( verboseFlag>1 ) runFlags |= SQL_TRACE; 1779 }else 1780 if( (nV = numberOfVChar(z))>=1 ){ 1781 quietFlag = 0; 1782 verboseFlag += nV; 1783 eVerbosity += nV; 1784 if( verboseFlag>1 ) runFlags |= SQL_TRACE; 1785 }else 1786 if( strcmp(z,"version")==0 ){ 1787 int ii; 1788 const char *zz; 1789 printf("SQLite %s %s\n", sqlite3_libversion(), sqlite3_sourceid()); 1790 for(ii=0; (zz = sqlite3_compileoption_get(ii))!=0; ii++){ 1791 printf("%s\n", zz); 1792 } 1793 return 0; 1794 }else 1795 if( strcmp(z,"is-dbsql")==0 ){ 1796 i++; 1797 for(i++; i<argc; i++){ 1798 long nData; 1799 char *aData = readFile(argv[i], &nData); 1800 printf("%d %s\n", isDbSql((unsigned char*)aData,nData), argv[i]); 1801 sqlite3_free(aData); 1802 } 1803 exit(0); 1804 }else 1805 { 1806 fatalError("unknown option: %s", argv[i]); 1807 } 1808 }else{ 1809 nSrcDb++; 1810 azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0])); 1811 azSrcDb[nSrcDb-1] = argv[i]; 1812 } 1813 } 1814 if( nSrcDb==0 ) fatalError("no source database specified"); 1815 if( nSrcDb>1 ){ 1816 if( zMsg ){ 1817 fatalError("cannot change the description of more than one database"); 1818 } 1819 if( zInsSql ){ 1820 fatalError("cannot import into more than one database"); 1821 } 1822 } 1823 1824 /* Process each source database separately */ 1825 for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){ 1826 char *zRawData = 0; 1827 long nRawData = 0; 1828 g.zDbFile = azSrcDb[iSrcDb]; 1829 rc = sqlite3_open_v2(azSrcDb[iSrcDb], &db, 1830 openFlags4Data, pDfltVfs->zName); 1831 if( rc==SQLITE_OK ){ 1832 rc = sqlite3_exec(db, "SELECT count(*) FROM sqlite_schema", 0, 0, 0); 1833 } 1834 if( rc ){ 1835 sqlite3_close(db); 1836 zRawData = readFile(azSrcDb[iSrcDb], &nRawData); 1837 if( zRawData==0 ){ 1838 fatalError("input file \"%s\" is not recognized\n", azSrcDb[iSrcDb]); 1839 } 1840 sqlite3_open(":memory:", &db); 1841 } 1842 1843 /* Print the description, if there is one */ 1844 if( infoFlag ){ 1845 int n; 1846 zDbName = azSrcDb[iSrcDb]; 1847 i = (int)strlen(zDbName) - 1; 1848 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; } 1849 zDbName += i; 1850 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0); 1851 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 1852 printf("%s: %s", zDbName, sqlite3_column_text(pStmt,0)); 1853 }else{ 1854 printf("%s: (empty \"readme\")", zDbName); 1855 } 1856 sqlite3_finalize(pStmt); 1857 sqlite3_prepare_v2(db, "SELECT count(*) FROM db", -1, &pStmt, 0); 1858 if( pStmt 1859 && sqlite3_step(pStmt)==SQLITE_ROW 1860 && (n = sqlite3_column_int(pStmt,0))>0 1861 ){ 1862 printf(" - %d DBs", n); 1863 } 1864 sqlite3_finalize(pStmt); 1865 sqlite3_prepare_v2(db, "SELECT count(*) FROM xsql", -1, &pStmt, 0); 1866 if( pStmt 1867 && sqlite3_step(pStmt)==SQLITE_ROW 1868 && (n = sqlite3_column_int(pStmt,0))>0 1869 ){ 1870 printf(" - %d scripts", n); 1871 } 1872 sqlite3_finalize(pStmt); 1873 printf("\n"); 1874 sqlite3_close(db); 1875 sqlite3_free(zRawData); 1876 continue; 1877 } 1878 1879 rc = sqlite3_exec(db, 1880 "CREATE TABLE IF NOT EXISTS db(\n" 1881 " dbid INTEGER PRIMARY KEY, -- database id\n" 1882 " dbcontent BLOB -- database disk file image\n" 1883 ");\n" 1884 "CREATE TABLE IF NOT EXISTS xsql(\n" 1885 " sqlid INTEGER PRIMARY KEY, -- SQL script id\n" 1886 " sqltext TEXT -- Text of SQL statements to run\n" 1887 ");" 1888 "CREATE TABLE IF NOT EXISTS readme(\n" 1889 " msg TEXT -- Human-readable description of this file\n" 1890 ");", 0, 0, 0); 1891 if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db)); 1892 if( zMsg ){ 1893 char *zSql; 1894 zSql = sqlite3_mprintf( 1895 "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg); 1896 rc = sqlite3_exec(db, zSql, 0, 0, 0); 1897 sqlite3_free(zSql); 1898 if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db)); 1899 } 1900 if( zRawData ){ 1901 zInsSql = "INSERT INTO xsql(sqltext) VALUES(?1)"; 1902 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0); 1903 if( rc ) fatalError("cannot prepare statement [%s]: %s", 1904 zInsSql, sqlite3_errmsg(db)); 1905 sqlite3_bind_text(pStmt, 1, zRawData, nRawData, SQLITE_STATIC); 1906 sqlite3_step(pStmt); 1907 rc = sqlite3_reset(pStmt); 1908 if( rc ) fatalError("insert failed for %s", argv[i]); 1909 sqlite3_finalize(pStmt); 1910 rebuild_database(db, dbSqlOnly); 1911 zInsSql = 0; 1912 sqlite3_free(zRawData); 1913 zRawData = 0; 1914 } 1915 ossFuzzThisDb = ossFuzz; 1916 1917 /* If the CONFIG(name,value) table exists, read db-specific settings 1918 ** from that table */ 1919 if( sqlite3_table_column_metadata(db,0,"config",0,0,0,0,0,0)==SQLITE_OK ){ 1920 rc = sqlite3_prepare_v2(db, "SELECT name, value FROM config", 1921 -1, &pStmt, 0); 1922 if( rc ) fatalError("cannot prepare query of CONFIG table: %s", 1923 sqlite3_errmsg(db)); 1924 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 1925 const char *zName = (const char *)sqlite3_column_text(pStmt,0); 1926 if( zName==0 ) continue; 1927 if( strcmp(zName, "oss-fuzz")==0 ){ 1928 ossFuzzThisDb = sqlite3_column_int(pStmt,1); 1929 if( verboseFlag ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb); 1930 } 1931 if( strcmp(zName, "limit-mem")==0 ){ 1932 nMemThisDb = sqlite3_column_int(pStmt,1); 1933 if( verboseFlag ) printf("Config: limit-mem=%d\n", nMemThisDb); 1934 } 1935 } 1936 sqlite3_finalize(pStmt); 1937 } 1938 1939 if( zInsSql ){ 1940 sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0, 1941 readfileFunc, 0, 0); 1942 sqlite3_create_function(db, "readtextfile", 1, SQLITE_UTF8, 0, 1943 readtextfileFunc, 0, 0); 1944 sqlite3_create_function(db, "isdbsql", 1, SQLITE_UTF8, 0, 1945 isDbSqlFunc, 0, 0); 1946 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0); 1947 if( rc ) fatalError("cannot prepare statement [%s]: %s", 1948 zInsSql, sqlite3_errmsg(db)); 1949 rc = sqlite3_exec(db, "BEGIN", 0, 0, 0); 1950 if( rc ) fatalError("cannot start a transaction"); 1951 for(i=iFirstInsArg; i<argc; i++){ 1952 if( strcmp(argv[i],"-")==0 ){ 1953 /* A filename of "-" means read multiple filenames from stdin */ 1954 char zLine[2000]; 1955 while( rc==0 && fgets(zLine,sizeof(zLine),stdin)!=0 ){ 1956 size_t kk = strlen(zLine); 1957 while( kk>0 && zLine[kk-1]<=' ' ) kk--; 1958 sqlite3_bind_text(pStmt, 1, zLine, (int)kk, SQLITE_STATIC); 1959 if( verboseFlag ) printf("loading %.*s\n", (int)kk, zLine); 1960 sqlite3_step(pStmt); 1961 rc = sqlite3_reset(pStmt); 1962 if( rc ) fatalError("insert failed for %s", zLine); 1963 } 1964 }else{ 1965 sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC); 1966 if( verboseFlag ) printf("loading %s\n", argv[i]); 1967 sqlite3_step(pStmt); 1968 rc = sqlite3_reset(pStmt); 1969 if( rc ) fatalError("insert failed for %s", argv[i]); 1970 } 1971 } 1972 sqlite3_finalize(pStmt); 1973 rc = sqlite3_exec(db, "COMMIT", 0, 0, 0); 1974 if( rc ) fatalError("cannot commit the transaction: %s", 1975 sqlite3_errmsg(db)); 1976 rebuild_database(db, dbSqlOnly); 1977 sqlite3_close(db); 1978 return 0; 1979 } 1980 rc = sqlite3_exec(db, "PRAGMA query_only=1;", 0, 0, 0); 1981 if( rc ) fatalError("cannot set database to query-only"); 1982 if( zExpDb!=0 || zExpSql!=0 ){ 1983 sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0, 1984 writefileFunc, 0, 0); 1985 if( zExpDb!=0 ){ 1986 const char *zExDb = 1987 "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent)," 1988 " dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)" 1989 " FROM db WHERE ?2<0 OR dbid=?2;"; 1990 rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0); 1991 if( rc ) fatalError("cannot prepare statement [%s]: %s", 1992 zExDb, sqlite3_errmsg(db)); 1993 sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb), 1994 SQLITE_STATIC, SQLITE_UTF8); 1995 sqlite3_bind_int(pStmt, 2, onlyDbid); 1996 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 1997 printf("write db-%d (%d bytes) into %s\n", 1998 sqlite3_column_int(pStmt,1), 1999 sqlite3_column_int(pStmt,3), 2000 sqlite3_column_text(pStmt,2)); 2001 } 2002 sqlite3_finalize(pStmt); 2003 } 2004 if( zExpSql!=0 ){ 2005 const char *zExSql = 2006 "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext)," 2007 " sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)" 2008 " FROM xsql WHERE ?2<0 OR sqlid=?2;"; 2009 rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0); 2010 if( rc ) fatalError("cannot prepare statement [%s]: %s", 2011 zExSql, sqlite3_errmsg(db)); 2012 sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql), 2013 SQLITE_STATIC, SQLITE_UTF8); 2014 sqlite3_bind_int(pStmt, 2, onlySqlid); 2015 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 2016 printf("write sql-%d (%d bytes) into %s\n", 2017 sqlite3_column_int(pStmt,1), 2018 sqlite3_column_int(pStmt,3), 2019 sqlite3_column_text(pStmt,2)); 2020 } 2021 sqlite3_finalize(pStmt); 2022 } 2023 sqlite3_close(db); 2024 return 0; 2025 } 2026 2027 /* Load all SQL script content and all initial database images from the 2028 ** source db 2029 */ 2030 blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid, 2031 &g.nSql, &g.pFirstSql); 2032 if( g.nSql==0 ) fatalError("need at least one SQL script"); 2033 blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid, 2034 &g.nDb, &g.pFirstDb); 2035 if( g.nDb==0 ){ 2036 g.pFirstDb = safe_realloc(0, sizeof(Blob)); 2037 memset(g.pFirstDb, 0, sizeof(Blob)); 2038 g.pFirstDb->id = 1; 2039 g.pFirstDb->seq = 0; 2040 g.nDb = 1; 2041 sqlFuzz = 1; 2042 } 2043 2044 /* Print the description, if there is one */ 2045 if( !quietFlag && !bScript ){ 2046 zDbName = azSrcDb[iSrcDb]; 2047 i = (int)strlen(zDbName) - 1; 2048 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; } 2049 zDbName += i; 2050 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0); 2051 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 2052 printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0)); 2053 } 2054 sqlite3_finalize(pStmt); 2055 } 2056 2057 /* Rebuild the database, if requested */ 2058 if( rebuildFlag ){ 2059 if( !quietFlag ){ 2060 printf("%s: rebuilding... ", zDbName); 2061 fflush(stdout); 2062 } 2063 rebuild_database(db, 0); 2064 if( !quietFlag ) printf("done\n"); 2065 } 2066 2067 /* Close the source database. Verify that no SQLite memory allocations are 2068 ** outstanding. 2069 */ 2070 sqlite3_close(db); 2071 if( sqlite3_memory_used()>0 ){ 2072 fatalError("SQLite has memory in use before the start of testing"); 2073 } 2074 2075 /* Limit available memory, if requested */ 2076 sqlite3_shutdown(); 2077 2078 if( nMemThisDb>0 && nMem==0 ){ 2079 if( !nativeMalloc ){ 2080 pHeap = realloc(pHeap, nMemThisDb); 2081 if( pHeap==0 ){ 2082 fatalError("failed to allocate %d bytes of heap memory", nMem); 2083 } 2084 sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMemThisDb, 128); 2085 }else{ 2086 sqlite3_hard_heap_limit64((sqlite3_int64)nMemThisDb); 2087 } 2088 }else{ 2089 sqlite3_hard_heap_limit64(0); 2090 } 2091 2092 /* Disable lookaside with the --native-malloc option */ 2093 if( nativeMalloc ){ 2094 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0); 2095 } 2096 2097 /* Reset the in-memory virtual filesystem */ 2098 formatVfs(); 2099 2100 /* Run a test using each SQL script against each database. 2101 */ 2102 if( !verboseFlag && !quietFlag && !bSpinner && !bScript ){ 2103 printf("%s:", zDbName); 2104 } 2105 for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){ 2106 tmStart = timeOfDay(); 2107 if( isDbSql(pSql->a, pSql->sz) ){ 2108 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d",pSql->id); 2109 if( bScript ){ 2110 /* No progress output */ 2111 }else if( bSpinner ){ 2112 int nTotal =g.nSql; 2113 int idx = pSql->seq; 2114 printf("\r%s: %d/%d ", zDbName, idx, nTotal); 2115 fflush(stdout); 2116 }else if( verboseFlag ){ 2117 printf("%s\n", g.zTestName); 2118 fflush(stdout); 2119 }else if( !quietFlag ){ 2120 static int prevAmt = -1; 2121 int idx = pSql->seq; 2122 int amt = idx*10/(g.nSql); 2123 if( amt!=prevAmt ){ 2124 printf(" %d%%", amt*10); 2125 fflush(stdout); 2126 prevAmt = amt; 2127 } 2128 } 2129 if( nSkip>0 ){ 2130 nSkip--; 2131 }else{ 2132 runCombinedDbSqlInput(pSql->a, pSql->sz, iTimeout, bScript, pSql->id); 2133 } 2134 nTest++; 2135 if( bTimer && !bScript ){ 2136 sqlite3_int64 tmEnd = timeOfDay(); 2137 printf("%lld %s\n", tmEnd - tmStart, g.zTestName); 2138 } 2139 g.zTestName[0] = 0; 2140 disableOom(); 2141 continue; 2142 } 2143 for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){ 2144 int openFlags; 2145 const char *zVfs = "inmem"; 2146 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d", 2147 pSql->id, pDb->id); 2148 if( bScript ){ 2149 /* No progress output */ 2150 }else if( bSpinner ){ 2151 int nTotal = g.nDb*g.nSql; 2152 int idx = pSql->seq*g.nDb + pDb->id - 1; 2153 printf("\r%s: %d/%d ", zDbName, idx, nTotal); 2154 fflush(stdout); 2155 }else if( verboseFlag ){ 2156 printf("%s\n", g.zTestName); 2157 fflush(stdout); 2158 }else if( !quietFlag ){ 2159 static int prevAmt = -1; 2160 int idx = pSql->seq*g.nDb + pDb->id - 1; 2161 int amt = idx*10/(g.nDb*g.nSql); 2162 if( amt!=prevAmt ){ 2163 printf(" %d%%", amt*10); 2164 fflush(stdout); 2165 prevAmt = amt; 2166 } 2167 } 2168 if( nSkip>0 ){ 2169 nSkip--; 2170 continue; 2171 } 2172 if( bScript ){ 2173 char zName[100]; 2174 sqlite3_snprintf(sizeof(zName), zName, "db%06d.db", 2175 pDb->id>1 ? pDb->id : pSql->id); 2176 renderDbSqlForCLI(stdout, zName, 2177 pDb->a, pDb->sz, pSql->a, pSql->sz); 2178 continue; 2179 } 2180 createVFile("main.db", pDb->sz, pDb->a); 2181 sqlite3_randomness(0,0); 2182 if( ossFuzzThisDb ){ 2183 #ifndef SQLITE_OSS_FUZZ 2184 fatalError("--oss-fuzz not supported: recompile" 2185 " with -DSQLITE_OSS_FUZZ"); 2186 #else 2187 extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t); 2188 LLVMFuzzerTestOneInput((const uint8_t*)pSql->a, (size_t)pSql->sz); 2189 #endif 2190 }else{ 2191 openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE; 2192 if( nativeFlag && pDb->sz==0 ){ 2193 openFlags |= SQLITE_OPEN_MEMORY; 2194 zVfs = 0; 2195 } 2196 rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs); 2197 if( rc ) fatalError("cannot open inmem database"); 2198 sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 100000000); 2199 sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 50); 2200 if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags); 2201 setAlarm((iTimeout+999)/1000); 2202 /* Enable test functions */ 2203 sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, db); 2204 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 2205 if( sqlFuzz || vdbeLimitFlag ){ 2206 sqlite3_progress_handler(db, 100000, progressHandler, 2207 &vdbeLimitFlag); 2208 } 2209 #endif 2210 #ifdef SQLITE_TESTCTRL_PRNG_SEED 2211 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, db); 2212 #endif 2213 if( bVdbeDebug ){ 2214 sqlite3_exec(db, "PRAGMA vdbe_debug=ON", 0, 0, 0); 2215 } 2216 do{ 2217 runSql(db, (char*)pSql->a, runFlags); 2218 }while( timeoutTest ); 2219 setAlarm(0); 2220 sqlite3_exec(db, "PRAGMA temp_store_directory=''", 0, 0, 0); 2221 sqlite3_close(db); 2222 } 2223 if( sqlite3_memory_used()>0 ){ 2224 fatalError("memory leak: %lld bytes outstanding", 2225 sqlite3_memory_used()); 2226 } 2227 reformatVfs(); 2228 nTest++; 2229 if( bTimer ){ 2230 sqlite3_int64 tmEnd = timeOfDay(); 2231 printf("%lld %s\n", tmEnd - tmStart, g.zTestName); 2232 } 2233 g.zTestName[0] = 0; 2234 2235 /* Simulate an error if the TEST_FAILURE environment variable is "5". 2236 ** This is used to verify that automated test script really do spot 2237 ** errors that occur in this test program. 2238 */ 2239 if( zFailCode ){ 2240 if( zFailCode[0]=='5' && zFailCode[1]==0 ){ 2241 fatalError("simulated failure"); 2242 }else if( zFailCode[0]!=0 ){ 2243 /* If TEST_FAILURE is something other than 5, just exit the test 2244 ** early */ 2245 printf("\nExit early due to TEST_FAILURE being set\n"); 2246 iSrcDb = nSrcDb-1; 2247 goto sourcedb_cleanup; 2248 } 2249 } 2250 } 2251 } 2252 if( bScript ){ 2253 /* No progress output */ 2254 }else if( bSpinner ){ 2255 int nTotal = g.nDb*g.nSql; 2256 printf("\r%s: %d/%d \n", zDbName, nTotal, nTotal); 2257 }else if( !quietFlag && !verboseFlag ){ 2258 printf(" 100%% - %d tests\n", g.nDb*g.nSql); 2259 } 2260 2261 /* Clean up at the end of processing a single source database 2262 */ 2263 sourcedb_cleanup: 2264 blobListFree(g.pFirstSql); 2265 blobListFree(g.pFirstDb); 2266 reformatVfs(); 2267 2268 } /* End loop over all source databases */ 2269 2270 if( !quietFlag && !bScript ){ 2271 sqlite3_int64 iElapse = timeOfDay() - iBegin; 2272 printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n" 2273 "SQLite %s %s\n", 2274 nTest, (int)(iElapse/1000), (int)(iElapse%1000), 2275 sqlite3_libversion(), sqlite3_sourceid()); 2276 } 2277 free(azSrcDb); 2278 free(pHeap); 2279 return 0; 2280 } 2281